linkedin-relay-mcp 3.26.0 → 3.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/mcp-shim.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/contracts.ts","../src/engine/company.ts","../src/progress.ts","../src/engine/budget.ts","../src/engine/auth.ts","../src/engine/classify.ts","../src/engine/client.ts","../src/engine/parse.ts","../src/engine/index.ts","../src/engine/session.ts","../src/commands/paged.ts","../src/engine/sdui-form.ts","../src/engine/posts.ts","../src/engine/jobs.ts","../src/engine/people.ts","../src/commands/people.ts","../src/commands/posts-search.ts","../src/commands/company.ts","../src/engine/events.ts","../src/commands/events.ts","../src/engine/job-premium.ts","../src/commands/jobs.ts","../src/engine/sdui-scheduled.ts","../src/commands/live.ts","../src/commands/local.ts","../src/commands/messaging.ts","../src/engine/messaging.ts","../src/engine/my-items.ts","../src/commands/my-items.ts","../src/engine/search.ts","../src/engine/network.ts","../src/commands/network.ts","../src/engine/notifications.ts","../src/commands/notifications.ts","../src/engine/contact-info.ts","../src/engine/full-profile.ts","../src/engine/recommendations.ts","../src/engine/sdui-profile.ts","../src/engine/sdui-skill.ts","../src/commands/profile.ts","../src/commands/registry.ts","../src/engine/sdui-position.ts","../src/commands/gate.ts","../src/commands/approval.ts","../src/commands/confirm.ts","../src/commands/write.ts","../src/engine/sdui-comment.ts","../src/engine/voyager-reply.ts","../src/engine/voyager-write.ts","../src/commands/profile-image.ts","../src/engine/sdui-profile-image.ts","../src/commands/token.ts","../src/engine/oauth.ts","../src/commands/transport.ts","../src/commands/role.ts","../src/commands/search-kinds.ts","../src/commands/skill.ts","../src/engine/profile-views.ts","../src/commands/viewers.ts","../src/entry.ts"],"sourcesContent":["#!/usr/bin/env bun\n// ─── MCP surface ──────────────────────────────────────────────────────────────\n//\n// Thin by contract: this file validates arguments, calls the same runners the\n// CLI calls, and returns the same envelope. No parsing, no transport, no\n// pacing, no cache logic lives here.\n//\n// Writes are not registered. Not disabled, not permission-gated — absent. The\n// registry marks each command's audience and risk, `mcpCommands()` filters on\n// both, and a test asserts no write survives that filter. An agent talking to\n// this server cannot post, comment, react, connect or message, whatever\n// arguments it composes.\n//\n// Tool descriptions do real work here. The agent reads them BEFORE it ever sees\n// a response, so each one states the specific misreading that would cause harm\n// — chiefly that an empty result and a failed fetch look identical unless you\n// check the counts.\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { z } from 'zod';\nimport { runCacheStatus, runLocal, runSourceRead } from './commands/cache.ts';\nimport { runCompany } from './commands/company.ts';\nimport { runEvent, runEvents } from './commands/events.ts';\nimport { type JobsRequest, runJob, runJobFilters, runJobs } from './commands/jobs.ts';\nimport { runFeed, runPost, runReactions, runScheduled, runWhoami } from './commands/live.ts';\nimport { runBudget, runDoctor, runRisk } from './commands/local.ts';\nimport {\n runDraft,\n runDraftRemove,\n runDrafts,\n runInbox,\n runMessages,\n} from './commands/messaging.ts';\nimport { runMyItems } from './commands/my-items.ts';\nimport { runNetwork } from './commands/network.ts';\nimport { runNotifications } from './commands/notifications.ts';\nimport { type PeopleRequest, runPeople, runPeopleFilters } from './commands/people.ts';\nimport { runPostsSearch } from './commands/posts-search.ts';\nimport { runProfile } from './commands/profile.ts';\nimport { mcpCommands } from './commands/registry.ts';\nimport { runExperience } from './commands/role.ts';\nimport { runFind, runFindFilters } from './commands/search-kinds.ts';\nimport { runSkills } from './commands/skill.ts';\nimport { runViewers } from './commands/viewers.ts';\nimport { shouldRunAsEntry } from './entry.ts';\nimport type { Envelope } from './types.ts';\n\nconst READING_CONTRACT =\n 'ALWAYS read `meta` before reporting. `state:\"complete\"` with an empty `items` genuinely means ' +\n 'none. `state:\"partial\"` means references failed to resolve — the record is INCOMPLETE, not ' +\n 'small. `claimedCount > 0` with `returnedCount === 0` is a FAILED FETCH, never \"no results\". ' +\n 'A non-empty `unknownTypes` means LinkedIn changed shape and the parser is behind — say so. ' +\n 'If `meta.budget.remaining` is low, tell the user and stop.';\n\nconst NO_RETRY =\n 'Never retry on failure. RATE_LIMITED, REQUEST_DENIED, CHALLENGE_DETECTED and COOLDOWN_ACTIVE ' +\n 'all mean a cross-process cooldown has opened; every further call will refuse until it lifts. ' +\n 'Report it and stop.';\n\n/** Render an envelope as MCP content. Errors stay envelopes, not exceptions. */\nfunction reply(envelope: Envelope) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(envelope) }],\n isError: !envelope.ok,\n };\n}\n\nexport function buildServer(): McpServer {\n const server = new McpServer({ name: 'linkedin-relay', version: '0.1.0' });\n\n // Guard rather than trust: if a write ever reached this list, fail loudly at\n // startup instead of quietly exposing it.\n const exposed = mcpCommands();\n const write = exposed.find((c) => c.risk === 'write');\n if (write !== undefined) {\n throw new Error(`refusing to start: write command '${write.name}' reached the MCP surface`);\n }\n\n server.tool(\n 'risk',\n 'Circuit-breaker state and the ToS notice. Free, no network. CALL THIS FIRST in a research ' +\n 'session — it reports whether LinkedIn has thrown a throttle, block or challenge, so you ' +\n 'find out before spending calls rather than one wasted call at a time.',\n {},\n async () => reply(runRisk(Date.now())),\n );\n\n server.tool(\n 'budget',\n \"Remaining request budget per class, with each cap's provenance. Free, no network. The caps \" +\n 'are deliberately low because LinkedIn restricts accounts for READ velocity alone — they are ' +\n \"guesses, not measured safe limits, and they cannot see the user's own browser activity.\",\n {},\n async () => reply(runBudget(Date.now(), false, false)),\n );\n\n server.tool(\n 'doctor',\n 'Diagnose setup end to end: session, cooldown, budget, engine readiness. Free with offline. ' +\n 'Run this first when anything behaves oddly. Never reveals credential values.',\n { offline: z.boolean().optional().describe('skip live checks (default true)') },\n async ({ offline }) => reply(runDoctor(Date.now(), offline ?? true)),\n );\n\n server.tool(\n 'whoami',\n 'The authenticated LinkedIn member: name, headline, public id, urn. Cheap (1 call). Good ' +\n `first call to confirm the session works and which account it is. ${NO_RETRY}`,\n {},\n async () => reply(await runWhoami()),\n );\n\n server.tool(\n 'search',\n 'Search LinkedIn posts, companies, groups, events, courses, products, services or schools ' +\n '(people and jobs have their own tools, `people` and `jobs`). 1 search call per 50 results ' +\n '(posts: per 20; a posts call is heavy, ask for the depth you need). Rows: id, name, ' +\n 'subtitle, detail, summary, url — what subtitle and detail hold depends on the kind ' +\n '(companies: industry • HQ, followers; groups: members; events: when, where • organiser; ' +\n 'courses: length, instructor • released; schools: place, alumni; services: the provider). ' +\n 'Posts rows: id (the post urn, which `post` takes), url, author, authorHeadline, authorUrl, ' +\n \"posted (as LinkedIn shows it, in the user's language), text, reactions, comments, reposts. \" +\n 'Several keyword sets as a list are searched and merged by id, with `matched`. Filter ' +\n 'options and their ids for each kind come from `search_filters`. LinkedIn pages at most ' +\n `1000 results per query; \\`meta.servedLimit\\` means it claimed more. ${READING_CONTRACT} ${NO_RETRY}`,\n {\n kind: z.enum([\n 'posts',\n 'companies',\n 'groups',\n 'events',\n 'courses',\n 'products',\n 'services',\n 'schools',\n ]),\n keywords: z.union([z.string(), z.array(z.string()).min(1)]).optional(),\n location: z.string().optional().describe('companies (HQ) and services: a place by name'),\n industry: z.array(z.string()).optional().describe('companies: industry ids'),\n network: z\n .array(z.enum(['1st', '2nd', '3rd+']))\n .optional()\n .describe('companies, services'),\n filter: z\n .array(z.string())\n .optional()\n .describe('raw key=v1,v2 by the names search_filters lists'),\n sort: z.enum(['recent', 'relevant']).optional().describe('posts'),\n posted: z.enum(['24h', 'week', 'month']).optional().describe('posts'),\n type: z\n .array(z.enum(['videos', 'images', 'jobs', 'live', 'articles', 'documents']))\n .optional()\n .describe('posts'),\n postedBy: z\n .array(z.enum(['1st', 'me']))\n .optional()\n .describe('posts'),\n from: z.array(z.string()).optional().describe('posts by these people (profile ids)'),\n mentions: z\n .array(z.string())\n .optional()\n .describe('posts mentioning these people (profile ids)'),\n fromCompany: z\n .array(z.string())\n .optional()\n .describe('posts by these companies (names or ids)'),\n mentionsCompany: z.array(z.string()).optional().describe('posts mentioning these companies'),\n authorCompany: z.array(z.string()).optional().describe('posts by people at these companies'),\n authorIndustry: z\n .array(z.string())\n .optional()\n .describe('posts by people in these industries'),\n authorTitle: z.string().optional().describe('posts by people with this job title'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .optional()\n .describe('per keyword set; default 25 (posts 20)'),\n start: z.number().int().min(0).optional(),\n compact: z.boolean().optional().describe('one line per result'),\n },\n async ({\n kind,\n keywords,\n location,\n industry,\n network,\n filter,\n limit,\n start,\n compact,\n ...posts\n }) => {\n const opts = compact === true ? { compact: true } : {};\n const common = {\n ...(keywords !== undefined ? { keywords } : {}),\n ...(start !== undefined ? { start } : {}),\n ...(filter !== undefined ? { raw: filter } : {}),\n };\n if (kind === 'posts')\n return reply(await runPostsSearch({ ...common, ...posts, limit: limit ?? 20 }, opts));\n return reply(\n await runFind(\n kind,\n {\n ...common,\n limit: limit ?? 25,\n ...(location !== undefined ? { location } : {}),\n ...(industry !== undefined ? { industry } : {}),\n ...(network !== undefined ? { network } : {}),\n },\n opts,\n ),\n );\n },\n );\n\n server.tool(\n 'search_filters',\n \"Every filter a search kind has for a query, with each option's id and live count: the \" +\n 'values `search` takes as raw `filter` (key=value by the listed key), or `industry`, … ' +\n `1 search call. ${NO_RETRY}`,\n {\n kind: z.enum(['companies', 'groups', 'events', 'courses', 'products', 'services', 'schools']),\n keywords: z.string().optional(),\n location: z.string().optional(),\n },\n async ({ kind, keywords, location }) =>\n reply(\n await runFindFilters(kind, {\n ...(keywords !== undefined ? { keywords } : {}),\n ...(location !== undefined ? { location } : {}),\n }),\n ),\n );\n\n const peopleQuery = {\n keywords: z\n .union([z.string(), z.array(z.string()).min(1)])\n .optional()\n .describe('search terms; a list runs one search per entry and merges them by person'),\n company: z.array(z.string()).optional().describe('current company: names or ids'),\n pastCompany: z.array(z.string()).optional().describe('past company: names or ids'),\n school: z.array(z.string()).optional().describe('school: names or ids'),\n location: z.string().optional().describe('a place by name, looked up to its geo id'),\n geo: z.array(z.string()).optional().describe('geo ids, from people_filters'),\n network: z.array(z.enum(['1st', '2nd', '3rd+'])).optional(),\n industry: z.array(z.string()).optional().describe('industry ids, from people_filters'),\n language: z.array(z.string()).optional().describe('profile language codes: en, de, …'),\n service: z.array(z.string()).optional().describe('service category ids'),\n connectionOf: z.string().optional().describe(\"a profile id: that person's connections\"),\n followerOf: z.string().optional().describe(\"a profile id: that person's followers\"),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n title: z.string().optional().describe('free text matched against current title'),\n companyText: z.string().optional().describe('free text matched against company names'),\n schoolText: z.string().optional().describe('free text matched against school names'),\n openToVolunteer: z.boolean().optional(),\n filter: z\n .array(z.string())\n .optional()\n .describe('raw key=v1,v2 by the parameter names people_filters lists'),\n };\n type PeopleArgs = { [K in keyof typeof peopleQuery]?: z.infer<(typeof peopleQuery)[K]> };\n const peopleRequest = (a: PeopleArgs, limit: number): PeopleRequest => {\n const { keywords, location, filter, ...rest } = a;\n return {\n limit,\n ...(keywords !== undefined ? { keywords } : {}),\n ...(location !== undefined ? { location } : {}),\n filter: { ...rest, ...(filter !== undefined ? { raw: filter } : {}) },\n };\n };\n\n server.tool(\n 'people',\n 'Search LinkedIn people with every filter the people search has. 1 search call per 50 ' +\n 'people, plus 1 per company, school or place given by name. Filter by current or past ' +\n 'company, school, place, connection degree, industry, title, profile language, or the ' +\n \"connections / followers of a person (their profile id, a row's `id`). Names are looked \" +\n 'up to ids and `data.resolved` says what each became: CHECK IT, a name can match a ' +\n 'different organisation. Rows: id, name, headline, location, degree, verified, insight ' +\n '(mutual connections, services), url. Several keyword sets as a list are searched and ' +\n 'merged by person, with `matched`. Out-of-network people come back as \"LinkedIn Member\" ' +\n 'with no url: LinkedIn will not name them to this account. LinkedIn pages at most 1000 ' +\n 'people per query; `meta.servedLimit` means it claimed more, so narrow with filters. ' +\n `\\`meta.next\\` is the start for the next page. ${READING_CONTRACT} ${NO_RETRY}`,\n {\n ...peopleQuery,\n limit: z.number().int().min(1).max(1000).optional().describe('per keyword set; default 25'),\n start: z.number().int().min(0).optional(),\n compact: z.boolean().optional().describe('one line per person'),\n },\n async ({ limit, start, compact, ...q }) =>\n reply(\n await runPeople(\n { ...peopleRequest(q, limit ?? 25), ...(start !== undefined ? { start } : {}) },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'people_filters',\n \"Every people-search filter for a query, with each option's id and live count, and which \" +\n 'filters take free text. The ids go into `people` (geo, industry, service, company, …) ' +\n `or raw \\`filter\\` (key=value by the listed key). 1 search call. ${NO_RETRY}`,\n peopleQuery,\n async (q) => reply(await runPeopleFilters(peopleRequest(q, 25))),\n );\n\n const jobQuery = {\n keywords: z\n .union([z.string(), z.array(z.string()).min(1)])\n .optional()\n .describe('search terms; a list runs one search per entry and merges them by job id'),\n location: z\n .string()\n .optional()\n .describe('a place, resolved by LinkedIn; check data.location for what it chose'),\n geoId: z.string().optional().describe('an exact geo id, in place of location'),\n distance: z.number().int().optional().describe('miles around the location'),\n posted: z.string().optional().describe('24h | week | month | <N>h | <N>d'),\n experience: z\n .array(z.enum(['internship', 'entry', 'associate', 'mid-senior', 'director', 'executive']))\n .optional(),\n type: z\n .array(\n z.enum([\n 'full-time',\n 'part-time',\n 'contract',\n 'temporary',\n 'volunteer',\n 'internship',\n 'other',\n ]),\n )\n .optional(),\n workplace: z.array(z.enum(['on-site', 'remote', 'hybrid'])).optional(),\n easyApply: z.boolean().optional(),\n under10: z.boolean().optional().describe('fewer than 10 applicants'),\n verified: z.boolean().optional(),\n inNetwork: z.boolean().optional(),\n fairChance: z.boolean().optional(),\n company: z.array(z.string()).optional().describe('company ids, from job_filters'),\n industry: z.array(z.string()).optional().describe('industry ids, from job_filters'),\n function: z.array(z.string()).optional().describe('function codes, from job_filters'),\n title: z.array(z.string()).optional().describe('title ids, from job_filters'),\n place: z.array(z.string()).optional().describe('city geo ids, from job_filters'),\n filter: z\n .array(z.string())\n .optional()\n .describe('raw key=v1,v2 by the parameter names job_filters lists'),\n sort: z.enum(['recent', 'relevant']).optional(),\n };\n type JobArgs = { [K in keyof typeof jobQuery]?: z.infer<(typeof jobQuery)[K]> };\n const jobRequest = (a: JobArgs, limit: number): JobsRequest => {\n const { keywords, location, geoId, filter, ...rest } = a;\n return {\n limit,\n ...(keywords !== undefined ? { keywords } : {}),\n ...(location !== undefined ? { location } : {}),\n ...(geoId !== undefined ? { geoId } : {}),\n filter: { ...rest, ...(filter !== undefined ? { raw: filter } : {}) },\n };\n };\n\n server.tool(\n 'jobs',\n 'Search LinkedIn jobs with every filter the jobs page has. 1 job-search call per 100 results (150 a day). ' +\n 'Rows carry id, title, company, location, workplace, listed (date), easyApply, promoted, ' +\n 'salary when shown, url. RANK ON THOSE, then call `job` on finalists for the description ' +\n 'and apply link; `details:true` reads every row in full, 100 per job read (60 a day). ' +\n 'Pass several keyword sets as a list to search them all with the same filters in one ' +\n 'call: jobs found by several come back once, with `matched` naming the sets that found ' +\n 'them, most-matched first; `meta.searches` reports each set and `meta.duplicates` how ' +\n 'many repeats were merged. ' +\n 'Ids for company/industry/title/place/filter come from `job_filters`. `data.location` is ' +\n \"the place a typed location resolved to: check it. `meta.claimedCount` is LinkedIn's total; \" +\n '`meta.next` is the start for the next page; LinkedIn serves at most 1000 per search. ' +\n 'topApplicant: true (Premium) lists instead the jobs where LinkedIn says the user would be ' +\n 'a top applicant, 100 per call; it takes no keywords, location or filters. ' +\n `${READING_CONTRACT} ${NO_RETRY}`,\n {\n ...jobQuery,\n topApplicant: z\n .boolean()\n .optional()\n .describe(\"Premium: LinkedIn's list of jobs where the user would be a top applicant\"),\n limit: z.number().int().min(1).max(1000).optional().describe('per keyword set; default 25'),\n start: z.number().int().min(0).optional(),\n details: z.boolean().optional().describe('read each job: apply link, applicants'),\n description: z.boolean().optional().describe('with details, keep full descriptions'),\n compact: z.boolean().optional().describe('one line per job'),\n },\n async ({ limit, start, details, description, compact, topApplicant, ...q }) =>\n reply(\n await runJobs(\n {\n ...jobRequest(q, limit ?? 25),\n ...(topApplicant === true ? { collection: 'top-applicant' as const } : {}),\n ...(start !== undefined ? { start } : {}),\n ...(details !== undefined ? { details } : {}),\n ...(description !== undefined ? { description } : {}),\n },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'job',\n 'LinkedIn jobs by id or URL, in full: description, apply {type: external | easy-apply, url}, ' +\n 'company, location, workplace, employmentType, applicants, listed/expires, state (LISTED or ' +\n 'CLOSED), and whether the user already applied or saved it. One id returns the job; ' +\n 'several return {items, meta}, read 100 per job read (60 a day), so pass all finalists in ' +\n `one call. meta.unread lists ids LinkedIn did not return. team: true adds hiringTeam ` +\n '[{name, id, url, headline, degree, role (\"Job poster\"), verified}] per job — who posted ' +\n 'it and who is hiring — one page call (60 a day) per job; [] means LinkedIn shows no one, ' +\n 'and hiringTeamError says why one could not be read. insights: true (Premium) adds ' +\n 'premium {applicants {total, lastDay, seniority [{level, share, count}], education ' +\n '[{degree, share}]}, company {name, headcount {asOf, now, sixMonthsAgo, yearAgo, ' +\n \"twoYearsAgo, growth1y (%)}, function {name, now, …} (the job's function), medianTenure, \" +\n \"competitors [{name, industry, url}], hiring, priorities, landscape (LinkedIn's generated \" +\n 'text)}}, one more job read per job; premiumError says why they could not be read. ' +\n NO_RETRY,\n {\n job: z\n .union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .describe('job id, /jobs/view/ URL or ?currentJobId= URL, or a list of them'),\n team: z.boolean().optional().describe(\"also read each job's hiring team\"),\n insights: z\n .boolean()\n .optional()\n .describe(\"Premium: who applied, and the company's headcount and insights\"),\n },\n async ({ job, team, insights }) =>\n reply(await runJob(job, {}, undefined, { team: team === true, insights: insights === true })),\n );\n\n server.tool(\n 'job_filters',\n \"Every job-search filter for a query, with each option's id and live result count: the \" +\n 'values `jobs` takes for company, industry, function, title, place, and raw `filter` ' +\n `(key=value by the listed key). 1 job-search call. ${NO_RETRY}`,\n jobQuery,\n async (q) => reply(await runJobFilters(jobRequest(q, 25))),\n );\n\n server.tool(\n 'profile',\n 'Read one LinkedIn profile in full: name, headline, about, location, industry, the top card ' +\n '(title, company, school), and every section — experience [{title, company, companyId, ' +\n 'employmentType, location, start, end | current, description}] whole (read on past the ' +\n 'first 10 companies), education, skills (top 20; counts.skills has the total; skills: ' +\n 'true reads them all), ' +\n 'certifications, languages, honors, publications, projects, volunteering, courses, ' +\n 'organizations, patents, testScores. Empty sections are left out. 1 profile read (30 a day), ' +\n '+1 per 50 more companies. contact: true adds contact {email, websites [{url, type}], ' +\n 'phones, birthday, connectedSince, …} as the profile shows it to you, for 1 more profile ' +\n 'read; it failing leaves contactError. posts: N adds posts, their N newest (the posts search, ' +\n 'from them; postsError if it fails). recommendations: true adds recommendations {received, ' +\n 'given}: [{name, url, headline, degree, context (when and how they worked together, in the ' +\n \"user's language), text}]. MEDIUM cost — use only on finalists surfaced by `people` or \" +\n '`search`. compact: true makes each role, school and entry one line and drops ' +\n `descriptions; fields keeps only those named. ${NO_RETRY}`,\n {\n id: z.string().min(1).describe('public id, urn, or profile URL'),\n compact: z.boolean().optional().describe('one line per role, school and entry'),\n fields: z.string().optional().describe('comma-separated top-level fields to keep'),\n contact: z.boolean().optional().describe('also read the contact info (1 more profile read)'),\n posts: z\n .number()\n .int()\n .min(1)\n .max(50)\n .optional()\n .describe('also read their N newest posts (1 search call per 20)'),\n skills: z\n .boolean()\n .optional()\n .describe('read every skill, not just the top 20 (1 page call per 10)'),\n recommendations: z\n .boolean()\n .optional()\n .describe('also read the recommendations they received and gave (2+ page calls)'),\n },\n async ({ id, compact, fields, contact, posts, skills, recommendations }) =>\n reply(\n await runProfile(\n id,\n {\n ...(compact === true ? { compact: true } : {}),\n ...(fields !== undefined ? { fields } : {}),\n },\n undefined,\n {\n contact: contact === true,\n skills: skills === true,\n recommendations: recommendations === true,\n ...(posts !== undefined ? { posts } : {}),\n },\n ),\n ),\n );\n\n server.tool(\n 'feed',\n \"The user's own chronological LinkedIn feed: author, when, text, url. MEDIUM cost. Promoted \" +\n 'posts are dropped and counted in `meta.excludedCount`, so fewer items than `limit` usually ' +\n `means ads were filtered, not that the fetch failed. ${READING_CONTRACT} ${NO_RETRY}`,\n { limit: z.number().int().min(1).max(20).optional().describe('default 10') },\n async ({ limit }) => reply(await runFeed(limit ?? 10)),\n );\n\n server.tool(\n 'post',\n \"A LinkedIn post's comment thread. EXPENSIVE — read only finalists. Accepts a bare \" +\n 'urn:li:activity:…, a urn:li:ugcPost:…, or a linkedin.com/feed/update/… URL; no prior lookup ' +\n 'is needed. Feed and search rows already report how many comments a post has, so use that to ' +\n 'decide whether the thread is worth a call. `meta.state` is always \"unknown\" — this is the ' +\n 'first page and pagination is not followed, so NEVER report a comment count as complete. ' +\n `Nested replies are not supported and a comment with replies does not carry them. ${READING_CONTRACT} ${NO_RETRY}`,\n {\n urn: z.string().min(1).describe('activity/ugcPost urn, or a feed-update URL'),\n limit: z.number().int().min(1).max(100).optional().describe('default 20'),\n },\n async ({ urn, limit }) => reply(await runPost(urn, limit ?? 20)),\n );\n\n server.tool(\n 'reactions',\n 'Who reacted to a LinkedIn post, and with which reaction. MEDIUM cost. Often more informative ' +\n 'than the comments for mapping who is paying attention to a topic. Same input forms as ' +\n '`post`. `meta.state` is always \"unknown\" — first page only, so do not report a total. ' +\n `${READING_CONTRACT} ${NO_RETRY}`,\n {\n urn: z.string().min(1).describe('activity/ugcPost urn, or a feed-update URL'),\n limit: z.number().int().min(1).max(100).optional().describe('default 20'),\n },\n async ({ urn, limit }) => reply(await runReactions(urn, limit ?? 20)),\n );\n\n server.tool(\n 'local',\n 'Search the LOCAL cache. Free — no network call, no budget spent. PREFER THIS before any live ' +\n 'command: if the answer is already cached, there is no reason to spend a request on it. The ' +\n 'cache only fills when the user runs a live read with --retain, so an empty result here means ' +\n 'nothing has been retained yet — NOT that LinkedIn has nothing. Check `meta.cachedTotal`.',\n {\n query: z.string().optional().describe('substring match; omit to list everything'),\n source: z.string().optional().describe('comma-separated: connections,my-posts,third-party'),\n since: z.string().optional().describe('YYYY-MM-DD'),\n limit: z.number().int().min(1).max(1000).optional().describe('per keyword set; default 25'),\n },\n async ({ query, source, since, limit }) => reply(runLocal(query, source, since, limit ?? 25)),\n );\n\n server.tool(\n 'experience',\n \"The roles on the user's own LinkedIn profile: positionId and title. LIVE — 2 calls. The \" +\n 'positionId is what `lnrelay role edit|remove` takes (CLI-only; changing a role is a write ' +\n `the user approves). ${NO_RETRY}`,\n {},\n async () => reply(await runExperience()),\n );\n\n server.tool(\n 'skills',\n \"The skills on the user's own LinkedIn profile: skillId and name. LIVE — about 3 calls. \" +\n '`name` is null when it could not be matched to its row for certain. Adding or removing a ' +\n `skill is the CLI-only \\`lnrelay skill\\`, a write the user approves. ${NO_RETRY}`,\n {},\n async () => reply(await runSkills()),\n );\n\n server.tool(\n 'my_items',\n \"The user's My items. posts: posts they saved — id (the post urn, which `post` takes), url, \" +\n 'author, authorHeadline, posted, text. learning: their LinkedIn Learning courses — name, ' +\n 'length, detail (instructor, released), progress, url. jobs: the job tracker — id (which ' +\n '`job` takes), title, company, location, workplace, stage, note (\"No longer accepting ' +\n 'applications\"), url; with no stage, all five stages (5 page calls) and `meta.byStage`. ' +\n `1 page call per 10 items. ${NO_RETRY}`,\n {\n list: z.enum(['posts', 'learning', 'jobs']),\n stage: z.enum(['saved', 'in-progress', 'applied', 'interview', 'archived']).optional(),\n limit: z.number().int().min(1).max(500).optional().describe('default 50'),\n compact: z.boolean().optional(),\n },\n async ({ list, stage, limit, compact }) =>\n reply(\n await runMyItems(\n list,\n { limit: limit ?? 50, ...(stage !== undefined ? { stage } : {}) },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'notifications',\n \"The user's LinkedIn notifications, newest first: unseen (the bell's count), and items \" +\n \"{kind (LinkedIn's name, e.g. FOLLOW_PAGE_HERO), text, detail, at (ISO), read, url, from \" +\n '(who or what it is about)}. Reading here does not mark them seen. 1 page call per 25. ' +\n NO_RETRY,\n {\n unread: z.boolean().optional().describe('only the unread ones'),\n limit: z.number().int().min(1).max(200).optional().describe('default 25'),\n compact: z.boolean().optional().describe('one line each'),\n },\n async ({ unread, limit, compact }) =>\n reply(\n await runNotifications(\n { limit: limit ?? 25, ...(unread === true ? { unread: true } : {}) },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'viewers',\n \"Who viewed the user's profile, as their profile-views page shows it: total, \" +\n 'privateViewers (a count only), and items — named viewers {name, id, url, degree, ' +\n 'headline, viewed} and anonymous ones {anonymous, description, viewed, searchUrl}. ' +\n \"Premium names every viewer, takes days (7, 14, 28, 90 or 365; default the page's 90) \" +\n 'and adds highlights [{label, value}] (top location, industry, company) and companies ' +\n '[{name, share}]. A free account is shown up to 3. meta.state is complete only when the ' +\n \"named and private add up to total. Degree, labels and times are in the user's language. \" +\n `2 page calls. ${NO_RETRY}`,\n {\n days: z\n .union([z.literal(7), z.literal(14), z.literal(28), z.literal(90), z.literal(365)])\n .optional()\n .describe('the range in days (Premium)'),\n compact: z.boolean().optional().describe('one line a viewer'),\n },\n async ({ days, compact }) =>\n reply(\n await runViewers({\n ...(compact === true ? { compact: true } : {}),\n ...(days !== undefined ? { days } : {}),\n }),\n ),\n );\n\n server.tool(\n 'events',\n \"The events page's own lists: events LinkedIn recommends to the user, and its Premium \" +\n \"LinkedIn Live events. Rows: id, name, when (as shown, in the user's language), organizer, \" +\n 'attendees, premium, url. 1 page call. To find events by topic use `search` with kind ' +\n `events; to read one in full use \\`event\\`. ${NO_RETRY}`,\n {\n premium: z.boolean().optional().describe('only the Premium LinkedIn Live events'),\n limit: z.number().int().min(1).max(100).optional().describe('default 25'),\n compact: z.boolean().optional(),\n },\n async ({ premium, limit, compact }) =>\n reply(\n await runEvents(\n { limit: limit ?? 25, ...(premium === true ? { premium: true } : {}) },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'event',\n 'Events in full, by id or URL: name, when (as shown), start/end (ISO), timeZone, state ' +\n '(FUTURE, ONGOING, PAST), cancelled, online, place (city, region, country), site (its own ' +\n 'registration page), attendees, organizer {name, kind, url}, private, premium, you (the ' +\n \"user's own response, when they gave one), description. 1 page call per event. \" +\n NO_RETRY,\n {\n event: z\n .union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .describe('event id or URL, or a list'),\n },\n async ({ event }) => reply(await runEvent(Array.isArray(event) ? event : [event])),\n );\n\n server.tool(\n 'company',\n 'A LinkedIn company page in full, by universal name, /company/ or /showcase/ URL, or id: ' +\n 'id (what people/jobs company filters and search posts fromCompany take), name, about, ' +\n 'website, industry, type, size (the band it chose), employeesOnLinkedIn, followers, ' +\n 'headquarters, specialties, locations, affiliated and showcasePages [{id, name, url, ' +\n 'followers}], jobsUrl. 1 page call per company; several return {items, meta}, with ' +\n 'meta.unread for any not found. posts: N adds its N newest posts (a posts search, on the ' +\n `search budget); postsError says why they could not be read. ${NO_RETRY}`,\n {\n company: z\n .union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .describe('universal name (microsoft), company URL or id, or a list'),\n posts: z.number().int().min(1).max(50).optional().describe('also its newest N posts'),\n compact: z.boolean().optional().describe('one line per company (several) and per post'),\n },\n async ({ company, posts, compact }) =>\n reply(\n await runCompany(\n Array.isArray(company) ? company : [company],\n posts !== undefined ? { posts } : {},\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'network',\n \"The user's own My Network. With no `list`: the count of connections, people they follow, \" +\n 'followers, pages, events, groups and invitations they sent (7 page calls). With a `list`: ' +\n 'its rows — people as id, name, headline, location, degree, url; pages, events and groups ' +\n 'as id, name, subtitle, detail, url; invitations as to, id, headline, sent, note, url. ' +\n '1 page call per 50 rows. Read only: no badge is cleared and nothing is marked seen. ' +\n `Received invitations and \"people you may know\" are not available. ${NO_RETRY}`,\n {\n list: z\n .enum(['connections', 'following', 'followers', 'pages', 'events', 'groups', 'invitations'])\n .optional(),\n limit: z.number().int().min(1).max(1000).optional().describe('default 50'),\n start: z.number().int().min(0).optional(),\n compact: z.boolean().optional(),\n },\n async ({ list, limit, start, compact }) =>\n reply(\n await runNetwork(\n list,\n { limit: limit ?? 50, ...(start !== undefined ? { start } : {}) },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'inbox',\n \"The user's LinkedIn conversations in a folder, newest first: id, url, with (each person or \" +\n 'organisation: name, kind, headline, degree, url), unread, lastActivity, last message ' +\n '(from, fromMe, at, text, sponsored), folders, inmail. 1 page call per 20. READS ONLY: ' +\n 'nothing is marked read or seen, and nothing is stored. These are private messages: quote ' +\n 'them to the user, never elsewhere. `meta.unread` counts conversations with unread messages. ' +\n `Folders: inbox (default), primary, other, archive, requests, spam. ${NO_RETRY}`,\n {\n folder: z.enum(['inbox', 'primary', 'other', 'archive', 'requests', 'spam']).optional(),\n unread: z.boolean().optional().describe('only conversations with unread messages'),\n limit: z.number().int().min(1).max(500).optional().describe('default 20'),\n compact: z.boolean().optional(),\n },\n async ({ folder, unread, limit, compact }) =>\n reply(\n await runInbox(\n {\n folder: folder ?? 'inbox',\n limit: limit ?? 20,\n ...(unread === true ? { unread: true } : {}),\n },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'messages',\n \"One conversation's latest messages, oldest first: from, fromMe, at, text, subject. 1 page \" +\n 'call. Reading does not mark it read. `meta.state` \"partial\" means a full page came back ' +\n `and older messages may exist; only the latest page is read. ${NO_RETRY}`,\n { conversation: z.string().min(1).describe('a conversation id from inbox, or its thread URL') },\n async ({ conversation }) => reply(await runMessages(conversation)),\n );\n\n server.tool(\n 'draft',\n 'Save a reply draft for a conversation ON THIS MACHINE, with its link, for the user to review ' +\n 'and send themselves. NOTHING IS SENT — this tool cannot send messages, on any surface. Show ' +\n 'the user the draft and the link. 1 page call, to check the conversation and who it is ' +\n 'with. Pass `remove` with a draft id to delete a draft instead.',\n {\n conversation: z.string().optional().describe('a conversation id or thread URL'),\n text: z.string().optional().describe('the reply'),\n remove: z.string().optional().describe('a draft id to delete'),\n },\n async ({ conversation, text, remove }) =>\n reply(remove !== undefined ? runDraftRemove(remove) : await runDraft(conversation, text)),\n );\n\n server.tool(\n 'drafts',\n 'The reply drafts saved on this machine: id, to, text, the conversation link. Free, local.',\n {},\n async () => reply(runDrafts()),\n );\n\n server.tool(\n 'scheduled',\n \"The user's own posts waiting to publish, soonest first: urn, scheduledAt (ISO), text. LIVE \" +\n '— about 1 call per 10 posts. These are NOT in `my_posts` until they go out. Links in `text` ' +\n 'show as lnkd.in short links, as LinkedIn lists them. `text` is null when it could not be ' +\n \"matched to its post for certain. `meta.claimedCount` is LinkedIn's own count; if \" +\n `\\`meta.state\\` is not \"complete\", say the list may be short. ${NO_RETRY}`,\n {},\n async () => reply(await runScheduled()),\n );\n\n for (const source of ['connections', 'my-posts'] as const) {\n server.tool(\n source.replace('-', '_'),\n `The user's own ${source === 'connections' ? 'connections' : 'authored posts'}, read from the ` +\n 'LOCAL cache. Free — no network call, no budget spent. An empty result means the cache has ' +\n `not been filled, NOT that the user has none: tell them to run \\`lnrelay sync ${source}\\` ` +\n 'themselves (it is CLI-only). Check `meta.cachedTotal` to tell the two apart.',\n {\n query: z.string().optional().describe('substring match; omit to list everything'),\n limit: z.number().int().min(1).max(1000).optional().describe('per keyword set; default 25'),\n },\n async ({ query, limit }) => reply(runSourceRead(source, query, limit ?? 25)),\n );\n }\n\n server.tool(\n 'cache_status',\n 'What is cached per source, with sync checkpoints and the retention policy. Free, no network. ' +\n 'Third-party records expire 30 days after capture — the body goes, an identity stub stays, so ' +\n 'a re-fetch is a visible choice rather than a silent budget charge.',\n {},\n async () => reply(runCacheStatus()),\n );\n\n return server;\n}\n\nconst entry = shouldRunAsEntry(process.argv[1], import.meta.url, import.meta.main, [\n 'linkedin-relay-mcp',\n 'lnrelay',\n]);\n\nif (entry.run) {\n const server = buildServer();\n await server.connect(new StdioServerTransport());\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 const meta = node.metadata as { shareUrn?: unknown } | undefined;\n\n return defined({\n type: typeOf(node),\n urn,\n // The urn the post was CREATED as (share or ugcPost) — what `share` prints,\n // and a different number from the activity urn above.\n shareUrn: typeof meta?.shareUrn === 'string' ? meta.shareUrn : undefined,\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\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","// ─── 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. Since 2026-10-16\n // `lnrelay profile` reads `fullProfile` below instead, which has the name\n // and every section; this one stays recorded for the projection trap.\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 // A WRITE contract: creates a poll object that a post then references. The\n // queryId is from mguttmann/linkedin-internal-api (docs/24) and returned a\n // pollSummary urn on this machine on the date below.\n createPoll: {\n name: 'createPoll',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerFeedDashPollsPollSummary.f8ad99cf791d833d37dddb373d06fb3a',\n provenance: 'verified',\n capturedAt: '2026-10-13',\n },\n\n // The composer's link lookup: a URL in, the article LinkedIn made of it out\n // (`urn:li:article:<id>`), which a post then carries as ARTICLE media. queryId\n // from mguttmann/linkedin-internal-api; same article urn the web composer\n // attached when captured on the date below.\n urlPreview: {\n name: 'urlPreview',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerContentcreationDashUpdateUrlPreview.b092c1aea4b6c087ec0d09614b3b3320',\n provenance: 'verified',\n capturedAt: '2026-10-13',\n },\n\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 // A profile in full, probed 2026-10-16: name, About and every section, each\n // a collection in `included`. It holds the first 10 position groups and 20\n // skills; the rest of the experience pages through `profilePositions`\n // (32 of 32 in two calls). Skills did not page (profileSkills answered 400).\n // See engine/full-profile.ts.\n fullProfile: {\n name: 'fullProfile',\n transport: 'voyager-restli',\n path: `${VOYAGER}/identity/dash/profiles`,\n decorationId: 'com.linkedin.voyager.dash.deco.identity.profile.FullProfileWithEntities-93',\n provenance: 'verified',\n capturedAt: '2026-10-16',\n },\n profilePositions: {\n name: 'profilePositions',\n transport: 'voyager-restli',\n path: `${VOYAGER}/identity/dash/profilePositionGroups`,\n decorationId: 'com.linkedin.voyager.dash.deco.identity.profile.FullProfilePositionGroup-50',\n provenance: 'verified',\n capturedAt: '2026-10-16',\n },\n\n // The owner's notifications, probed 2026-10-29: the cards the bell opens,\n // newest first. The page itself also marks them seen; reading them here\n // does not. See engine/notifications.ts.\n notifications: {\n name: 'notifications',\n transport: 'voyager-restli',\n path: `${VOYAGER}/voyagerIdentityDashNotificationCards`,\n decorationId:\n 'com.linkedin.voyager.dash.deco.identity.notifications.CardsCollectionWithInjectionsNoPills-25',\n provenance: 'verified',\n capturedAt: '2026-10-29',\n },\n\n // A company page, captured 2026-10-14. The GraphQL company query by\n // universalName answers only the company's urn, so this is the REST\n // resource: by id (`/<id>`) or by name (`q=universalName`). It carries the\n // About tab's fields, the affiliated and showcase pages, and followers. See\n // engine/company.ts.\n company: {\n name: 'company',\n transport: 'voyager-restli',\n path: `${VOYAGER}/organization/companies`,\n decorationId: 'com.linkedin.voyager.deco.organization.web.WebFullCompanyMain-12',\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n\n // Job search, captured 2026-10-14. The jobs page itself now opens an SDUI\n // \"AI job search\" that drops filters it does not support; these are the\n // classic Voyager resources still behind /jobs/search/, which take them all.\n // See engine/jobs.ts.\n // The owner's messages, captured 2026-10-14; see engine/messaging.ts. Reads\n // only: the page's own \"seen\", read and delivery calls are not made.\n messengerConversations: {\n name: 'messengerConversations',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/voyagerMessagingGraphQL/graphql`,\n queryId: 'messengerConversations.9501074288a12f3ae9e3c7ea243bccbf',\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n messengerMessages: {\n name: 'messengerMessages',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/voyagerMessagingGraphQL/graphql`,\n queryId: 'messengerMessages.5846eeb71c981f11e0134cb6626cc314',\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n\n // Connection invitations the owner has sent, captured 2026-10-14; see\n // engine/network.ts.\n sentInvitations: {\n name: 'sentInvitations',\n transport: 'voyager-restli',\n path: `${VOYAGER}/relationships/sentInvitationViewsV2`,\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n\n // One event in full, captured 2026-10-14; see engine/events.ts.\n professionalEvent: {\n name: 'professionalEvent',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerEventsDashProfessionalEvents.210672c5faddd345ead9663d93cd2241',\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n\n jobCards: {\n name: 'jobCards',\n transport: 'voyager-restli',\n path: `${VOYAGER}/voyagerJobsDashJobCards`,\n decorationId: 'com.linkedin.voyager.dash.deco.jobs.search.JobSearchCardsCollection-220',\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n jobFilters: {\n name: 'jobFilters',\n transport: 'voyager-restli',\n path: `${VOYAGER}/voyagerJobsDashSearchFilterClustersResource`,\n decorationId: 'com.linkedin.voyager.dash.deco.search.SearchFilterCluster-44',\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n // Premium job reads, captured 2026-11-22 from /jobs/collections/top-applicant/\n // and a job's detail pane. See engine/job-premium.ts.\n jobCollection: {\n name: 'jobCollection',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerJobsDashJobCards.fc1f897bcf2dc9afd5184ef3e9ed589b',\n provenance: 'verified',\n capturedAt: '2026-11-22',\n },\n jobDetailSections: {\n name: 'jobDetailSections',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerJobsDashJobPostingDetailSections.bc2eee77d01abc6616b8c8855344dfd5',\n provenance: 'verified',\n capturedAt: '2026-11-22',\n },\n jobPosting: {\n name: 'jobPosting',\n transport: 'voyager-restli',\n path: `${VOYAGER}/jobs/jobPostings`,\n decorationId: 'com.linkedin.voyager.deco.jobs.web.shared.WebFullJobPosting-65',\n provenance: 'verified',\n capturedAt: '2026-10-14',\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","// ─── A company page ───────────────────────────────────────────────────────────\n//\n// Captured 2026-10-14. The company page itself is server-rendered SDUI; the\n// GraphQL company query by universalName answers only the company's urn. The\n// REST resource behind the `company` contract answers in JSON with what the\n// About tab shows:\n//\n// organization/companies/<id> the company\n// organization/companies?q=universalName&… a collection of one\n//\n// Both carry the affiliated and showcase pages in `included`, each with its\n// follower count. LinkedIn left `tagline` and `foundedOn` null for Microsoft,\n// whose page shows neither; they are read when present.\n\nimport { CONTRACTS } from './contracts.ts';\nimport type { Failure } from './sdui-form.ts';\n\nexport type CompanyRef = { id: string } | { name: string };\n\n/** A company from its universal name, page URL, numeric id or urn. */\nexport function companyRefOf(input: string): CompanyRef | undefined {\n const s = input.trim();\n if (/^\\d+$/.test(s)) return { id: s };\n const urn = s.match(/^urn:li:(?:fsd_company|fs_normalized_company|company|organization):(\\d+)$/);\n if (urn?.[1] !== undefined) return { id: urn[1] };\n const page = s.match(/linkedin\\.com\\/(?:company|showcase)\\/([^/?#\\s]+)/);\n const slug = page?.[1] ?? (/^[A-Za-z0-9][A-Za-z0-9_%.-]*$/.test(s) ? s : undefined);\n if (slug === undefined) return undefined;\n const name = decodeURIComponent(slug);\n return /^\\d+$/.test(name) ? { id: name } : { name };\n}\n\nexport function companyUrl(ref: CompanyRef): string {\n const c = CONTRACTS.company;\n if (c?.decorationId === undefined) throw new Error(\"the 'company' contract is missing\");\n const deco = `decorationId=${c.decorationId}`;\n return 'id' in ref\n ? `${c.path}/${ref.id}?${deco}`\n : `${c.path}?${deco}&q=universalName&universalName=${encodeURIComponent(ref.name)}`;\n}\n\n// ─── Reading it ───────────────────────────────────────────────────────────────\n\nexport interface RelatedPage {\n id: string;\n name: string;\n url?: string;\n followers?: number;\n}\n\nexport interface Company {\n /** What `people --company`, `jobs --company` and `search posts --from-company` take. */\n id: string;\n name: string;\n universalName?: string;\n url: string;\n tagline?: string;\n /** The About tab's overview. */\n about?: string;\n website?: string;\n industry?: string;\n /** \"Public Company\", \"Privately Held\", … */\n type?: string;\n /** The size band the company chose, \"10,001+\" or \"51-200\". */\n size?: string;\n /** Members who list the company: the page's \"employees\" link. */\n employeesOnLinkedIn?: number;\n followers?: number;\n headquarters?: string;\n founded?: number;\n phone?: string;\n specialties?: string[];\n locations?: string[];\n affiliated?: RelatedPage[];\n showcasePages?: RelatedPage[];\n /** The company's own job search, every affiliate included. */\n jobsUrl?: string;\n}\n\ntype Node = Record<string, unknown>;\n\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst idOf = (urn: unknown) => String(urn ?? '').match(/:(\\d+)$/)?.[1];\nconst str = (v: unknown) => (typeof v === 'string' && v.trim() !== '' ? v.trim() : undefined);\nconst slash = (u: unknown) => {\n const s = str(u);\n return s === undefined ? undefined : s.endsWith('/') ? s : `${s}/`;\n};\n\nfunction defined<T extends object>(obj: T): T {\n for (const k of Object.keys(obj) as (keyof T)[]) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\n/** \"1 Microsoft Way, Redmond, Washington 98052, US\" */\nfunction address(a: unknown): string | undefined {\n const n = a as Node | null | undefined;\n if (n === null || n === undefined) return undefined;\n const region = [str(n.geographicArea), str(n.postalCode)].filter(Boolean).join(' ');\n const parts = [str(n.line1), str(n.line2), str(n.city), str(region), str(n.country)];\n const line = parts.filter(Boolean).join(', ');\n return line === '' ? undefined : line;\n}\n\nfunction sizeOf(range: unknown): string | undefined {\n const r = range as { start?: unknown; end?: unknown } | null | undefined;\n if (typeof r?.start !== 'number') return undefined;\n const n = (x: number) => x.toLocaleString('en-US');\n return typeof r.end === 'number' ? `${n(r.start)}-${n(r.end)}` : `${n(r.start)}+`;\n}\n\nconst urns = (v: unknown) => (Array.isArray(v) ? v.filter((u) => typeof u === 'string') : []);\n\nexport function parseCompany(json: unknown): { ok: true; company: Company } | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const data = root?.data;\n if (data === undefined || data === null) return drift('the company answer carried no data');\n const included = root?.included ?? [];\n const byUrn = new Map(included.map((n) => [n.entityUrn, n]));\n\n // By id the data is the company; by name, a collection of (at most) one.\n let c: Node | undefined = data;\n if (!String(data.$type ?? '').endsWith('organization.Company')) {\n const listed = urns(data['*elements']);\n if (listed.length === 0)\n return { ok: false, code: 'NOT_FOUND', message: 'no company has that name on LinkedIn' };\n c = byUrn.get(listed[0]);\n if (c === undefined) return drift('the company was listed but not sent');\n }\n const id = idOf(c.entityUrn);\n const name = str(c.name);\n if (id === undefined || name === undefined) return drift('the company carried no id or name');\n\n const followersOf = (n: Node) => {\n const f = byUrn.get(n['*followingInfo']) as Node | undefined;\n return typeof f?.followerCount === 'number' ? f.followerCount : undefined;\n };\n const related = (list: unknown): RelatedPage[] | undefined => {\n const pages = urns(list).flatMap((u) => {\n const p = byUrn.get(u);\n const pid = idOf(u);\n const pname = str(p?.name);\n if (p === undefined || pid === undefined || pname === undefined) return [];\n return [defined({ id: pid, name: pname, url: slash(p.url), followers: followersOf(p) })];\n });\n return pages.length > 0 ? pages : undefined;\n };\n const industry = urns(c['*companyIndustries'])\n .map((u) => str(byUrn.get(u)?.localizedName))\n .find((x) => x !== undefined);\n const locations = (Array.isArray(c.confirmedLocations) ? c.confirmedLocations : [])\n .map(address)\n .filter((x): x is string => x !== undefined);\n const specialties = Array.isArray(c.specialities)\n ? c.specialities.filter((x): x is string => typeof x === 'string')\n : [];\n const founded = (c.foundedOn as { year?: unknown } | null | undefined)?.year;\n\n return {\n ok: true,\n company: defined({\n id,\n name,\n universalName: str(c.universalName),\n url: slash(c.url) ?? `https://www.linkedin.com/company/${id}/`,\n tagline: str(c.tagline),\n about: str(c.description),\n website: str(c.companyPageUrl),\n industry,\n type: str((c.companyType as Node | null | undefined)?.localizedName),\n size: sizeOf(c.staffCountRange),\n employeesOnLinkedIn: typeof c.staffCount === 'number' ? c.staffCount : undefined,\n followers: followersOf(c),\n headquarters: address(c.headquarter),\n founded: typeof founded === 'number' ? founded : undefined,\n phone: str((c.phone as Node | null | undefined)?.number),\n specialties: specialties.length > 0 ? specialties : undefined,\n locations: locations.length > 0 ? locations : undefined,\n affiliated: related(c.affiliatedCompanies),\n showcasePages: related(c.showcasePages),\n jobsUrl: str(c.jobSearchPageUrl),\n }),\n };\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 =\n | 'profile'\n | 'search'\n | 'page'\n | 'jobSearch'\n | 'jobRead'\n | 'write'\n | '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 // Set on 2026-10-14 by the owner's decision, for job hunting: about ten\n // keyword searches read in full (25 jobs a page, often 100-300 a search),\n // then the finalists read for their apply links. Kept apart from `search`\n // so a hunt neither uses up nor is stopped by people and company research.\n // Guesses like every other cap; the client's 3-15s gap still paces each call.\n jobSearch: {\n perDay: 150,\n provenance: 'guessed',\n note: 'job search pages and filter lists; set for ~10 keyword searches a day',\n },\n jobRead: {\n perDay: 60,\n provenance: 'guessed',\n note: 'one job read in full, for its apply link',\n },\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 // Raised from 250 with the job classes, so a full hunt (~120 searches and\n // 60 reads) still leaves room for everything else.\n global: { perDay: 350, 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","// ─── 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","// ─── 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 // A challenge is an HTML page. JSON and RSC answers are data, and data says\n // \"challenges\" (a job description opened an indefinite cooldown, 2026-11-22).\n if (!/^\\s*</.test(body)) return 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 /** Sent verbatim — a media upload PUTs the file itself. Exclusive with `body`. */\n bytes?: Uint8Array;\n /** Extra headers, layered over the session's. An upload names its own content type. */\n headers?: Record<string, string>;\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\n/** Bytes go verbatim, a JSON body is serialised, and a read carries nothing. */\nfunction encodeBody(spec: RequestSpec): Uint8Array | string | undefined {\n if (spec.bytes !== undefined) return spec.bytes;\n return spec.body === undefined ? undefined : JSON.stringify(spec.body);\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 Object.assign(requestHeaders, spec.headers);\n const body = encodeBody(spec);\n\n try {\n const res = await deps.fetch(spec.url, {\n method: spec.method ?? 'GET',\n headers: requestHeaders,\n ...(body === undefined ? {} : { 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","// ─── 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 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 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 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","// 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","// ─── Paged searches over several keyword sets, merged by id ───────────────────\n//\n// Shared by `jobs` and `people`. Each keyword set is searched on its own,\n// paged to the limit, and the results are merged by id: a row found by several\n// sets comes back once, naming them in `matched`, most-matched first. A set\n// that fails is reported and the others are kept; only all failing is an error.\n\nimport type { Failure } from '../engine/sdui-form.ts';\n\n/** One page of a search, as a source parsed it. */\nexport interface Paged<T extends { id: string }> {\n ok: true;\n items: T[];\n /** How far LinkedIn will page this query. */\n total?: number;\n /** LinkedIn's own count of matches, when it is more than it will page. */\n claimed?: number;\n /** What the source resolved part of the query to (a place, say). */\n resolved?: unknown;\n unknownTypes: Record<string, number>;\n}\n\nexport type PageFetch<T extends { id: string }> = (\n keywords: string | undefined,\n start: number,\n) => Promise<Paged<T> | Failure>;\n\nexport interface Paging {\n pageSize: number;\n /** LinkedIn serves no further than this into any one query. */\n max: number;\n}\n\nexport type Matched<T> = T & {\n /** With several keyword sets: the ones that found this row, in the order given. */\n matched?: string[];\n};\n\n/** The keyword sets, trimmed, each once (case-insensitively), in the order given. */\nexport function keywordSets(keywords: string | string[] | undefined): string[] {\n const given = keywords === undefined ? [] : Array.isArray(keywords) ? keywords : [keywords];\n const out: string[] = [];\n for (const k of given.map((g) => g.trim())) {\n if (k !== '' && !out.some((o) => o.toLowerCase() === k.toLowerCase())) out.push(k);\n }\n return out;\n}\n\ninterface Collected<T> {\n items: T[];\n total?: number;\n claimed?: number;\n resolved?: unknown;\n stoppedBy?: string;\n exhausted: boolean;\n unknownTypes: Record<string, number>;\n}\n\nfunction addCounts(into: Record<string, number>, from: Record<string, number>) {\n for (const [k, n] of Object.entries(from)) into[k] = (into[k] ?? 0) + n;\n}\n\n/** Pages from `first` until `want` rows, the end of the results, or a failure. */\nasync function collect<T extends { id: string }>(\n fetchPage: PageFetch<T>,\n keywords: string | undefined,\n first: number,\n want: number,\n paging: Paging,\n): Promise<Collected<T> | Failure> {\n const out: Collected<T> = { items: [], exhausted: false, unknownTypes: {} };\n for (let start = first; out.items.length < want && start < paging.max; start += paging.pageSize) {\n const page = await fetchPage(keywords, start);\n if (!page.ok) {\n // The first page failing is a failure; a later one leaves a partial list.\n if (out.items.length === 0) return page;\n out.stoppedBy = page.code;\n break;\n }\n out.total = page.total ?? out.total;\n out.claimed = page.claimed ?? out.claimed;\n out.resolved = page.resolved ?? out.resolved;\n addCounts(out.unknownTypes, page.unknownTypes);\n const fresh = page.items.filter((j) => !out.items.some((x) => x.id === j.id));\n const room = want - out.items.length;\n out.items.push(...fresh.slice(0, room));\n // The limit cut this page short: there is more, even on the last page.\n if (fresh.length > room) break;\n if (\n page.items.length === 0 ||\n (out.total !== undefined && start + paging.pageSize >= out.total)\n ) {\n out.exhausted = true;\n break;\n }\n }\n return out;\n}\n\n/** One keyword set's search, as `meta.searches` reports it. */\nexport interface SearchReport {\n keywords?: string;\n claimedCount?: number;\n returnedCount: number;\n state: 'complete' | 'partial' | 'failed';\n next?: number;\n /** LinkedIn claims more than it will serve; narrow the query to see the rest. */\n servedLimit?: number;\n stoppedBy?: string;\n}\n\nfunction reportOf<T>(\n keywords: string | undefined,\n found: Collected<T>,\n first: number,\n): SearchReport {\n const capped =\n found.exhausted &&\n found.claimed !== undefined &&\n found.total !== undefined &&\n found.claimed > found.total;\n const report: SearchReport = {\n ...(keywords !== undefined ? { keywords } : {}),\n claimedCount: found.claimed ?? found.total,\n returnedCount: found.items.length,\n state: found.stoppedBy === undefined && found.exhausted && !capped ? 'complete' : 'partial',\n };\n if (!found.exhausted) report.next = first + found.items.length;\n if (capped) report.servedLimit = found.total;\n if (found.stoppedBy !== undefined) report.stoppedBy = found.stoppedBy;\n return report;\n}\n\nexport interface Merged<T> {\n rows: Matched<T>[];\n searches: SearchReport[];\n /** Rows dropped because an earlier keyword set had already found them. */\n duplicates: number;\n resolved?: unknown;\n unknownTypes: Record<string, number>;\n failure?: Failure;\n}\n\n/** Adds one search's rows; a row already found gains this keyword set instead. */\nfunction mergeInto<T extends { id: string }>(\n out: Merged<T>,\n byId: Map<string, Matched<T>>,\n items: T[],\n keywords?: string,\n) {\n for (const item of items) {\n const seen = byId.get(item.id);\n if (seen !== undefined) {\n out.duplicates++;\n if (keywords !== undefined) seen.matched?.push(keywords);\n continue;\n }\n const row: Matched<T> = keywords !== undefined ? { ...item, matched: [keywords] } : item;\n byId.set(item.id, row);\n out.rows.push(row);\n }\n}\n\n/**\n * Runs each keyword set's search and merges the results by id. With several\n * sets, each row says which found it and the most-found come first; ties keep\n * the order LinkedIn ranked them in.\n */\nexport async function searchAll<T extends { id: string }>(\n fetchPage: PageFetch<T>,\n sets: (string | undefined)[],\n first: number,\n want: number,\n paging: Paging,\n): Promise<Merged<T>> {\n const out: Merged<T> = { rows: [], searches: [], duplicates: 0, unknownTypes: {} };\n const byId = new Map<string, Matched<T>>();\n for (const keywords of sets) {\n const found = await collect(fetchPage, keywords, first, want, paging);\n if ('ok' in found) {\n out.failure = out.failure ?? found;\n out.searches.push({\n ...(keywords !== undefined ? { keywords } : {}),\n returnedCount: 0,\n state: 'failed',\n stoppedBy: found.code,\n });\n continue;\n }\n out.searches.push(reportOf(keywords, found, first));\n out.resolved = out.resolved ?? found.resolved;\n addCounts(out.unknownTypes, found.unknownTypes);\n mergeInto(out, byId, found.items, sets.length > 1 ? keywords : undefined);\n }\n if (sets.length > 1) out.rows.sort((x, y) => (y.matched?.length ?? 0) - (x.matched?.length ?? 0));\n return out;\n}\n\n/**\n * The envelope's `meta`. One keyword set keeps the plain shape with its own\n * paging; several add `searches` (each set's report) and `duplicates`.\n */\nexport function metaOf<T>(\n operation: string,\n merged: Merged<T>,\n single: boolean,\n first: number,\n extra: { unread?: number; readStop?: string } = {},\n): Record<string, unknown> {\n const { unread = 0, readStop } = extra;\n const searched = merged.searches;\n const allComplete = searched.every((r) => r.state === 'complete');\n const meta: Record<string, unknown> = {\n state: allComplete && unread === 0 && readStop === undefined ? 'complete' : 'partial',\n operation,\n };\n if (single) {\n const { keywords: _k, state: _s, ...report } = searched[0] as SearchReport;\n Object.assign(meta, report, { start: first });\n if (readStop !== undefined) meta.stoppedBy = meta.stoppedBy ?? readStop;\n } else {\n Object.assign(meta, {\n returnedCount: merged.rows.length,\n duplicates: merged.duplicates,\n start: first,\n searches: searched,\n ...(readStop !== undefined ? { stoppedBy: readStop } : {}),\n });\n }\n if (unread > 0) meta.unread = unread;\n if (Object.keys(merged.unknownTypes).length > 0) meta.unknownTypes = merged.unknownTypes;\n return meta;\n}\n\n/** One flat line from the given parts; a bar inside a value would read as a column break. */\nexport function line(parts: (string | undefined)[]): string {\n return parts\n .filter((p): p is string => p !== undefined && p !== '')\n .map((p) => p.replaceAll(' | ', ' / '))\n .join(' | ');\n}\n","// ─── SDUI forms, read and sent back ───────────────────────────────────────────\n//\n// LinkedIn's profile forms are SDUI. Opening one returns every field's current\n// value (`modelStates`) and the server actions its buttons fire, each with the\n// state keys it reads and its payload. A save is that action, those values,\n// some replaced. Nothing here knows any particular form; sdui-profile.ts and\n// sdui-position.ts do.\n//\n// The browser sends some values it COMPUTES from others (a company is\n// required unless the role is freelance). Those are evaluated here from the\n// expression the form ships, and an expression we do not recognise is refused:\n// a guessed value is a save that quietly says something else.\n\nexport interface ModelValue {\n protoCase: string;\n value: unknown;\n}\n\nexport type Model = Map<string, ModelValue>;\n\nexport interface RequestArgs {\n requestedStateKeys: { key: { value: { id: string } } }[];\n payload: Record<string, unknown>;\n}\n\nexport type Failure = { ok: false; code: string; message: string; hint?: string };\n\n/** The balanced JSON array or object starting at `start`. */\nexport function balanced(s: string, start: number): string | null {\n const open = s[start];\n const close = open === '[' ? ']' : '}';\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let i = start; i < s.length; i++) {\n const ch = s[i];\n if (escaped) escaped = false;\n else if (ch === '\\\\') escaped = true;\n else if (ch === '\"') inString = !inString;\n else if (!inString && ch === open) depth++;\n else if (!inString && ch === close) {\n depth--;\n if (depth === 0) return s.slice(start, i + 1);\n }\n }\n return null;\n}\n\nexport function parseAt<T>(s: string, start: number): T | null {\n const text = start < 0 ? null : balanced(s, start);\n if (text === null) return null;\n try {\n return JSON.parse(text) as T;\n } catch {\n return null;\n }\n}\n\n/** A model state's value in the shape the browser sends it back. */\nfunction plain(v: Record<string, unknown>): ModelValue {\n const protoCase = String(v.$case);\n const raw = v[protoCase];\n if (protoCase === 'stringListValue') {\n return { protoCase, value: (raw as { stringValues?: string[] })?.stringValues ?? [] };\n }\n // React Server Components encode a bigint as \"$n<digits>\".\n if (protoCase === 'signedLongValue' && typeof raw === 'string' && raw.startsWith('$n')) {\n return { protoCase, value: { type: 'bigint', value: raw.slice(2) } };\n }\n return { protoCase, value: raw };\n}\n\n/**\n * The form's initial values. The same keys reappear inside actions (a\n * checkbox's SetState, a reset); only `modelStates` holds what the profile\n * has now. Null when there is none — a form we no longer understand.\n */\nexport function readModel(stream: string): Model | null {\n const at = stream.indexOf('\"modelStates\":[');\n const entries = parseAt<\n { key?: { key?: { value?: { id?: string } } }; value?: Record<string, unknown> }[]\n >(stream, at === -1 ? -1 : stream.indexOf('[', at));\n if (entries === null) return null;\n const model: Model = new Map();\n for (const entry of entries) {\n const id = entry.key?.key?.value?.id;\n if (id !== undefined && entry.value !== undefined && !model.has(id)) {\n model.set(id, plain(entry.value));\n }\n }\n return model;\n}\n\n/** A server action's arguments, verbatim, or null when the stream has none. */\nexport function findRequest(stream: string, requestId: string): RequestArgs | null {\n const at = stream.indexOf(`\"requestId\":\"${requestId}\",\"requestedArguments\":`);\n if (at === -1) return null;\n const args = parseAt<RequestArgs>(\n stream,\n stream.indexOf('{', stream.indexOf('\"requestedArguments\":', at)),\n );\n return args !== null && Array.isArray(args.requestedStateKeys) && args.payload !== undefined\n ? args\n : null;\n}\n\ntype Evaluated = { ok: true; value: unknown } | Failure;\ntype Node = { expression?: { $case?: string } & Record<string, unknown> };\n\nconst unknownExpression = (what: string): Failure => ({\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `the form computes a value with an expression this tool does not evaluate (${what})`,\n hint: 'Nothing was sent. Re-capture the form to see what it has become.',\n});\n\nfunction boundId(body: unknown): string | undefined {\n return (body as { key?: { key?: { value?: { id?: string } } } })?.key?.key?.value?.id;\n}\n\nfunction str(node: Node, model: Model): string | null {\n const e = node.expression;\n if (e?.$case === 'stringValue') return String(e.stringValue);\n if (e?.$case === 'bindableString') {\n const v = model.get(boundId(e.bindableString) ?? '')?.value;\n return typeof v === 'string' ? v : '';\n }\n return null;\n}\n\nfunction bool(node: Node, model: Model): boolean | null {\n const e = node.expression;\n const body = e?.[e?.$case ?? ''] as Record<string, Node> | undefined;\n switch (e?.$case) {\n case 'booleanExpression':\n return bool(body as Node, model);\n case 'booleanValue':\n return e.booleanValue === true;\n case 'bindableBoolean':\n return model.get(boundId(e.bindableBoolean) ?? '')?.value === true;\n case 'notExpression': {\n const a = bool(body?.a ?? {}, model);\n return a === null ? null : !a;\n }\n case 'orExpression':\n case 'andExpression': {\n const a = bool(body?.a ?? {}, model);\n const b = bool(body?.b ?? {}, model);\n if (a === null || b === null) return null;\n return e.$case === 'orExpression' ? a || b : a && b;\n }\n case 'stringEqualsExpression': {\n const a = str(body?.a ?? {}, model);\n const b = str(body?.b ?? {}, model);\n if (a === null || b === null) return null;\n return (body as { ignoreCase?: boolean }).ignoreCase === true\n ? a.toLowerCase() === b.toLowerCase()\n : a === b;\n }\n default:\n return null;\n }\n}\n\n/** Evaluate a computed value the way the browser would. */\nexport function evaluate(expression: unknown, model: Model): Evaluated {\n const value = bool(expression as Node, model);\n return value === null\n ? unknownExpression(JSON.stringify(expression).slice(0, 80))\n : { ok: true, value };\n}\n\n/** A computed value the caller resolves itself; undefined to evaluate it here. */\nexport type Resolver = (key: string, value: ModelValue) => Evaluated | undefined;\n\nexport interface WireState {\n key: string;\n namespace: 'MemoryNamespace';\n value: unknown;\n originalProtoCase: string;\n protoKey: { $type: 'proto.sdui.Key'; value: { $case: 'id'; id: string } };\n}\n\n/**\n * The states a request sends: one per requested key the form has a value for\n * (the browser omits the rest), computed ones evaluated.\n */\nexport function wireStates(keys: string[], model: Model, resolve: Resolver): WireState[] | Failure {\n const out: WireState[] = [];\n for (const id of keys) {\n const state = model.get(id);\n if (state === undefined) continue;\n let value = state.value;\n if (state.protoCase === 'expression') {\n const r = resolve(id, state) ?? evaluate(state.value, model);\n if (!r.ok) return r;\n value = r.value;\n }\n out.push({\n key: id,\n namespace: 'MemoryNamespace',\n value,\n originalProtoCase: state.protoCase,\n protoKey: { $type: 'proto.sdui.Key', value: { $case: 'id', id } },\n });\n }\n return out;\n}\n\nexport const keysOf = (args: RequestArgs): string[] =>\n args.requestedStateKeys.map((k) => k.key.value.id);\n\n/** A server-request body as the browser sends it. */\nexport function requestBody(\n requestId: string,\n args: RequestArgs,\n states: unknown[],\n screen: string,\n) {\n const requestedArguments = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: args.requestedStateKeys,\n payload: args.payload,\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n return {\n requestId,\n serverRequest: {\n requestId,\n requestedArguments,\n isApfcEnabled: false,\n isStreaming: false,\n rumPageKey: '',\n },\n states,\n requestedArguments: { ...requestedArguments, states, screenId: screen, knownTemplateIds: [] },\n };\n}\n\n/** Open a profile form as the browser does. A read, though it is issued as a POST. */\nexport function navBody(screen: string, payload: Record<string, unknown>) {\n return {\n clientArguments: {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload,\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n states: [],\n screenId: screen,\n knownTemplateIds: [],\n },\n isModal: true,\n };\n}\n\n/** Errors a 200 can still carry: a non-empty `errors` list in the response. */\nexport function responseErrors(raw: string): string | null {\n return raw.match(/\"errors\":\\[([^\\]]+)\\]/)?.[1]?.slice(0, 300) ?? null;\n}\n","// ─── Searching posts ──────────────────────────────────────────────────────────\n//\n// Captured 2026-10-14. Posts are the one search kind the Voyager search no\n// longer serves: asked for `resultType:CONTENT` it claims hundreds of matches\n// and returns none, at any page size. The results page loads them from an SDUI\n// pager, `contentSearchResults`, whose payload takes the keywords, the start,\n// the count and every filter as a list under the filter panel's own names.\n//\n// The answer is an RSC stream, and a heavy one (about half a megabyte a post).\n// A post is not one record in it. Each post's top row (`feed-full-update`)\n// holds the card's skeleton; its author, text and counts sit in other rows,\n// reached through `$L<id>` references, and the numbers live in the stream's\n// model state, keyed by the post's content urn:\n//\n// ReactionType_<TYPE>_<urn> commentCount-<urn> repostCount-<urn>\n//\n// So a post is read by following its top row's references and reading each\n// part from the rows it reaches. The content urn (a ugcPost, share or group\n// post) is the post's id: /feed/update/<urn>/ opens it and `post` reads its\n// comments. Labels such as the time (\"5 hours ago\") come in the viewer's\n// LinkedIn language and are kept as shown.\n\nimport type { Failure } from './sdui-form.ts';\nimport { balanced, readModel } from './sdui-form.ts';\n\nexport const POSTS_PAGER = 'com.linkedin.sdui.search.contentSearchResults';\nconst SCREEN = 'com.linkedin.sdui.flagshipnav.search.SearchResultsContent';\nexport const POSTS_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/pagination?sduiid=${POSTS_PAGER}`;\n\n/** Posts per call. The page asks for 3; 20 came back whole (2026-10-14). */\nexport const POSTS_PAGE = 20;\n\n/** The filters the pager takes, each a list, as the filter panel names them. */\nexport const POST_FILTERS = [\n 'sortBy',\n 'postedBy',\n 'datePosted',\n 'contentType',\n 'fromMember',\n 'mentionsOrganization',\n 'mentionsMember',\n 'fromOrganization',\n 'authorCompany',\n 'authorIndustry',\n 'authorJobTitle',\n] as const;\n\nexport type PostFilter = (typeof POST_FILTERS)[number];\n\nexport interface PostsQuery {\n keywords?: string;\n filters: Partial<Record<PostFilter, string[]>>;\n start: number;\n count?: number;\n}\n\n/** The pager request, shaped as the results page sends it. */\nexport function postsPagerBody(q: PostsQuery) {\n const payload: Record<string, unknown> = {\n startIndex: q.start,\n keywords: q.keywords ?? '',\n count: q.count ?? POSTS_PAGE,\n };\n for (const f of POST_FILTERS) payload[f] = q.filters[f] ?? [];\n payload.spellCheckEnabled = true;\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 pagerId: POSTS_PAGER,\n clientArguments: { ...args, states: [], screenId: SCREEN, knownTemplateIds: [] },\n paginationRequest: {\n $type: 'proto.sdui.actions.requests.PaginationRequest',\n pagerId: POSTS_PAGER,\n retryCount: 0,\n requestedArguments: args,\n },\n };\n}\n\n// ─── The stream's rows ────────────────────────────────────────────────────────\n\n/** How many UTF-16 units `bytes` UTF-8 bytes take, starting at `from`. */\nfunction unitsFor(stream: string, from: number, bytes: number): number {\n let i = from;\n let left = bytes;\n while (left > 0 && i < stream.length) {\n const c = stream.codePointAt(i) as number;\n left -= c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n i += c > 0xffff ? 2 : 1;\n }\n return i - from;\n}\n\n/**\n * An RSC stream split into its `<hex id>:<payload>` rows. A row ends at a\n * newline, except a text row, `<id>:T<hex byte length>,<text>`, which is\n * exactly that many bytes (newlines and all) with the next row straight after.\n */\nexport class Rows {\n readonly byId = new Map<string, string>();\n private readonly starts: { id: string; at: number }[] = [];\n private readonly texts = new Set<string>();\n\n constructor(readonly stream: string) {\n const head = /([0-9a-f]+):(?:T([0-9a-f]+),)?/y;\n let pos = 0;\n while (pos < stream.length) {\n if (stream[pos] === '\\n') {\n pos++;\n continue;\n }\n head.lastIndex = pos;\n const m = head.exec(stream);\n if (m === null) {\n // Not a row start: skip to the next line.\n const nl = stream.indexOf('\\n', pos);\n pos = nl === -1 ? stream.length : nl + 1;\n continue;\n }\n const id = m[1] as string;\n const body = pos + m[0].length;\n this.starts.push({ id, at: pos });\n let end: number;\n if (m[2] !== undefined) {\n end = body + unitsFor(stream, body, Number.parseInt(m[2], 16));\n this.texts.add(id);\n } else {\n const nl = stream.indexOf('\\n', body);\n end = nl === -1 ? stream.length : nl;\n }\n this.byId.set(id, stream.slice(body, end));\n pos = end;\n }\n }\n\n /** Whether a row is raw text (a `T` row) rather than JSON. */\n isText(id: string): boolean {\n return this.texts.has(id);\n }\n\n /** The row a stream position falls in. */\n at(pos: number): string | undefined {\n let lo = 0;\n let hi = this.starts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if ((this.starts[mid] as { at: number }).at <= pos) lo = mid;\n else hi = mid - 1;\n }\n return this.starts[lo]?.id;\n }\n\n /** Every row reachable from `id` through references, nearest first. */\n reach(id: string, limit = 400): string[] {\n const seen = new Set<string>([id]);\n const queue = [id];\n while (queue.length > 0 && seen.size < limit) {\n const row = this.byId.get(queue.shift() as string) ?? '';\n for (const m of row.matchAll(/\"\\$L?([0-9a-f]+)(?::[^\"]*)?\"/g)) {\n const ref = m[1] as string;\n if (!seen.has(ref) && this.byId.has(ref)) {\n seen.add(ref);\n queue.push(ref);\n }\n }\n }\n return [...seen];\n }\n}\n\n// ─── Reading a post ───────────────────────────────────────────────────────────\n\nexport interface PostHit {\n /** The content urn: ugcPost, share or groupPost. */\n id: string;\n url: string;\n author?: string;\n authorHeadline?: string;\n authorUrl?: string;\n /** When, as LinkedIn shows it, in the viewer's language (\"5h\", \"5 órája\"). */\n posted?: string;\n text?: string;\n reactions?: number;\n comments?: number;\n reposts?: number;\n}\n\n/**\n * The visible strings under a node, in order. An element is `[\"$\", type,\n * key, props]`: only its props' children are text; references are skipped.\n */\nfunction strings(v: unknown, out: string[] = []): string[] {\n if (typeof v === 'string') {\n if (!v.startsWith('$')) out.push(v);\n } else if (Array.isArray(v)) {\n if (v[0] === '$' && v[1] === 'br') out.push('\\n');\n else if (v[0] === '$') strings(v[3], out);\n else for (const x of v) strings(x, out);\n } else if (v !== null && typeof v === 'object' && 'children' in v) {\n strings((v as { children: unknown }).children, out);\n }\n return out;\n}\n\n/** Every text block in a row from `from` on, as the reader would see it. */\nfunction texts(row: string, from = 0): string[] {\n const part = row.slice(Math.max(0, from));\n const out: string[] = [];\n for (const m of part.matchAll(/\"textProps\":/g)) {\n const obj = balanced(part, part.indexOf('{', m.index ?? 0));\n if (obj === null) continue;\n const t = strings(JSON.parse(obj)).join('').trim();\n if (t !== '') out.push(t);\n }\n return out;\n}\n\nconst jsonString = (s: string) => JSON.parse(`\"${s}\"`) as string;\n\nconst REACTIONS = [\n 'LIKE',\n 'PRAISE',\n 'EMPATHY',\n 'INTEREST',\n 'APPRECIATION',\n 'ENTERTAINMENT',\n 'SUPER_LIKE',\n];\n\ninterface Read {\n post: PostHit | undefined;\n /** The rows the post was read from, and the path to them. */\n used: string[];\n}\n\n/** The first row under `from` holding `view`, and that row's own subtree. */\nfunction part(\n rows: Rows,\n from: string[],\n view: string,\n depth = 60,\n): { row: string; under: string[] } | undefined {\n const id = from.find((r) => rows.byId.get(r)?.includes(`\"viewName\":\"${view}\"`));\n return id === undefined ? undefined : { row: id, under: rows.reach(id, depth) };\n}\n\n/** The first row in `ids` that `find` reads something from, and what it read. */\nfunction firstIn<T>(rows: Rows, ids: string[], find: (row: string) => T | undefined) {\n for (const id of ids) {\n const v = find(rows.byId.get(id) ?? '');\n if (v !== undefined) return { id, v };\n }\n return undefined;\n}\n\nfunction authorOf(rows: Rows, actor: { under: string[] } | undefined) {\n if (actor === undefined) return { fields: {}, used: [] as string[] };\n const state = (key: string) => (row: string) => {\n const m = row.match(new RegExp(`\"${key}\"[^]*?\"stringValue\":\"((?:[^\"\\\\\\\\]|\\\\\\\\.)*)\"`));\n return m?.[1] === undefined ? undefined : jsonString(m[1]);\n };\n // Person links come relative (\"/in/<vanity>/\"), page links absolute.\n const link = firstIn(\n rows,\n actor.under,\n (row) =>\n row.match(\n /\"(?:https:\\/\\/www\\.linkedin\\.com)?(\\/(?:in|company|school|showcase)\\/[^\"?/]+)/,\n )?.[1],\n );\n const person = firstIn(rows, actor.under, state('profile_name_loading_state'));\n const headline = firstIn(rows, actor.under, state('profile_headline_loading_state'));\n // A company or page has no profile state: its name is the visible text\n // the author link's own label starts with.\n const page =\n person !== undefined\n ? undefined\n : firstIn(rows, actor.under, (row) => {\n const labels = [...row.matchAll(/\"aria-label\":\"((?:[^\"\\\\]|\\\\.)+)\"/g)].map((m) =>\n jsonString(m[1] as string).trim(),\n );\n // The label may carry a badge after the name (\"Microsoft Premium\").\n return texts(row).find((t) => labels.some((l) => l === t || l.startsWith(`${t} `)));\n });\n const named = person ?? page;\n return {\n fields: {\n ...(named !== undefined ? { author: named.v.trim() } : {}),\n ...(headline !== undefined ? { authorHeadline: headline.v } : {}),\n ...(link !== undefined ? { authorUrl: `https://www.linkedin.com${link.v}/` } : {}),\n },\n used: [link?.id, named?.id, headline?.id].filter((x): x is string => x !== undefined),\n };\n}\n\nfunction readPost(rows: Rows, top: string, model: ReturnType<typeof readModel>): Read {\n const reach = rows.reach(top);\n const counted = reach.find((r) => /commentCount-urn:li:\\w+:\\d+/.test(rows.byId.get(r) ?? ''));\n const id =\n counted === undefined\n ? undefined\n : rows.byId.get(counted)?.match(/commentCount-(urn:li:\\w+:\\d+)/)?.[1];\n if (id === undefined) return { post: undefined, used: [top] };\n\n const actor = part(rows, reach, 'feed-actor');\n const author = authorOf(rows, actor);\n const sub = part(rows, reach, 'feed-actor-sub-description', 4);\n const commentary = part(rows, reach, 'feed-commentary');\n const n = (k: string) => {\n const v = (model?.get(k) as { value?: unknown } | undefined)?.value;\n return typeof v === 'number' ? v : undefined;\n };\n const byType = REACTIONS.map((r) => n(`ReactionType_${r}_${id}`));\n const reactions = byType.some((v) => v !== undefined)\n ? byType.reduce<number>((a, v) => a + (v ?? 0), 0)\n : undefined;\n const subRow = sub === undefined ? '' : (rows.byId.get(sub.row) ?? '');\n const posted =\n sub === undefined\n ? undefined\n : texts(subRow, subRow.indexOf('\"viewName\":\"feed-actor-sub-description\"'))[0];\n const said =\n commentary === undefined ? undefined : firstIn(rows, commentary.under, (row) => texts(row)[0]);\n const text = said?.v;\n\n const post: PostHit = {\n id,\n url: `https://www.linkedin.com/feed/update/${id}/`,\n ...author.fields,\n ...(posted !== undefined ? { posted } : {}),\n ...(text !== undefined ? { text } : {}),\n ...(reactions !== undefined ? { reactions } : {}),\n };\n const comments = n(`commentCount-${id}`);\n const reposts = n(`repostCount-${id}`);\n if (comments !== undefined) post.comments = comments;\n if (reposts !== undefined) post.reposts = reposts;\n const parts = [actor?.row, sub?.row, commentary?.row, said?.id].filter(\n (x): x is string => x !== undefined,\n );\n const used = [top, counted as string, ...author.used, ...parts];\n return { post, used };\n}\n\nexport interface PostsPage {\n ok: true;\n posts: PostHit[];\n /** Cards that looked like posts but carried no content urn. */\n unread: number;\n /** The rows the posts were read from: what a fixture needs to keep. */\n used: Set<string>;\n}\n\nexport function parsePosts(stream: string): PostsPage | Failure {\n if (\n !stream.includes(POSTS_PAGER) &&\n !stream.includes('\"isPartialPage\"') &&\n !stream.includes('feed-full-update')\n ) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the posts search page could not be read',\n hint: 'the posts search response changed shape; re-capture it',\n };\n }\n const rows = new Rows(stream);\n const model = readModel(stream);\n const posts: PostHit[] = [];\n const used = new Set<string>();\n const tops = new Set<string>();\n let unread = 0;\n for (const m of stream.matchAll(/\"viewName\":\"feed-full-update\"/g)) {\n const top = rows.at(m.index ?? 0);\n if (top === undefined || tops.has(top)) continue;\n tops.add(top);\n const r = readPost(rows, top, model);\n for (const u of r.used) used.add(u);\n if (r.post === undefined) unread++;\n else if (!posts.some((p) => p.id === r.post?.id)) posts.push(r.post);\n }\n if (unread > 0 && posts.length === 0) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `${unread} posts were listed but none could be read`,\n hint: 'the posts search response changed shape; re-capture it',\n };\n }\n return { ok: true, posts, unread, used };\n}\n","// ─── Job search ───────────────────────────────────────────────────────────────\n//\n// Captured 2026-10-14. The jobs page now opens LinkedIn's \"AI job search\", an\n// SDUI screen that answers in an RSC stream and silently drops filters it does\n// not support (it lost the location and experience level of the URL we gave\n// it). The classic search behind /jobs/search/ is still served as plain\n// Voyager JSON, takes every filter, and is what this module speaks:\n//\n// jobCards voyagerJobsDashJobCards?q=jobSearch 25 cards a page\n// filters voyagerJobsDashSearchFilterClustersResource every filter, its\n// option ids, counts\n// detail jobs/jobPostings/<id> description, apply\n// link, applicants\n// hiring team SDUI component peopleWhoCanHelp who posted it, who\n// is hiring for it\n//\n// A typed location goes as `seoLocation`; LinkedIn resolves it and echoes the\n// geo it chose, which we report, because \"Vienna, Austria\" resolved to one\n// district of Vienna. A `geoId` is exact.\n\nimport { CONTRACTS } from './contracts.ts';\nimport { Rows } from './posts.ts';\nimport { encodeVariables, type RestliValue } from './restli.ts';\nimport type { Failure } from './sdui-form.ts';\n\n/** The three job contracts, verified; a missing one is a build error, not drift. */\nfunction contract(name: 'jobCards' | 'jobFilters' | 'jobPosting') {\n const c = CONTRACTS[name];\n if (c?.decorationId === undefined) throw new Error(`job contract '${name}' is missing`);\n return { path: c.path, decorationId: c.decorationId };\n}\n\n/**\n * Jobs per search call. The browser asks for 25; the server serves up to 100\n * and answers 101 with a 400 (probed 2026-10-14). Four times fewer calls.\n */\nexport const PAGE_SIZE = 100;\n\n/** Jobs per batch read. 100 returned all 100 in one call (2026-10-14). */\nexport const BATCH_SIZE = 100;\n\nexport interface JobQuery {\n keywords?: string;\n /** Free text, resolved by LinkedIn. Ignored when `geoId` is given. */\n location?: string;\n geoId?: string;\n /** selectedFilters, by LinkedIn's own parameter names. */\n filters: Record<string, string[]>;\n start: number;\n count: number;\n}\n\nfunction queryTuple(q: JobQuery): string {\n const locationUnion: RestliValue =\n q.geoId !== undefined\n ? { geoId: q.geoId }\n : q.location !== undefined\n ? { seoLocation: { location: q.location } }\n : undefined;\n const selected = Object.entries(q.filters).filter(([, v]) => v.length > 0);\n return encodeVariables({\n origin: 'JOB_SEARCH_PAGE_JOB_FILTER',\n keywords: q.keywords,\n locationUnion,\n selectedFilters: selected.length > 0 ? Object.fromEntries(selected) : undefined,\n spellCorrectionEnabled: true,\n });\n}\n\nexport function jobSearchUrl(q: JobQuery): string {\n const c = contract('jobCards');\n return (\n `${c.path}?decorationId=${c.decorationId}` +\n `&count=${q.count}&q=jobSearch&query=${queryTuple(q)}&start=${q.start}`\n );\n}\n\nexport function jobFiltersUrl(q: JobQuery): string {\n const c = contract('jobFilters');\n return `${c.path}?decorationId=${c.decorationId}&q=filters&query=${queryTuple(q)}`;\n}\n\nexport function jobDetailUrl(id: string): string {\n const c = contract('jobPosting');\n return `${c.path}/${id}?decorationId=${c.decorationId}`;\n}\n\n/** Many jobs in one call, the same projection as one: a Rest.li batch get. */\nexport function jobBatchUrl(ids: string[]): string {\n const c = contract('jobPosting');\n return `${c.path}?ids=List(${ids.join(',')})&decorationId=${c.decorationId}`;\n}\n\n/** A bare id, a /jobs/view/ URL, a ?currentJobId= URL or a job urn. */\nexport function jobIdOf(input: string): string | undefined {\n const s = input.trim();\n if (/^\\d+$/.test(s)) return s;\n const found =\n s.match(/\\/jobs\\/view\\/(?:[^/?#]*-)?(\\d+)/) ??\n s.match(/[?&]currentJobId=(\\d+)/) ??\n s.match(/urn:li:(?:fsd_|fs_normalized_)?jobPosting:(\\d+)/);\n return found?.[1];\n}\n\nconst viewUrl = (id: string) => `https://www.linkedin.com/jobs/view/${id}/`;\nconst day = (ms: unknown) =>\n typeof ms === 'number' ? new Date(ms).toISOString().slice(0, 10) : undefined;\n\ntype Node = Record<string, unknown>;\nconst text = (v: unknown): string | undefined => {\n const t = (v as { text?: unknown } | null | undefined)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim() : undefined;\n};\n\nfunction defined<T extends Record<string, unknown>>(obj: T): T {\n for (const k of Object.keys(obj)) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\n// ─── Cards ────────────────────────────────────────────────────────────────────\n\nexport type Workplace = 'on-site' | 'remote' | 'hybrid';\n\nexport interface JobCard {\n id: string;\n title: string;\n company?: string;\n location?: string;\n workplace?: Workplace;\n /** The day it was listed, YYYY-MM-DD. */\n listed?: string;\n easyApply: boolean;\n promoted: boolean;\n /** The pay line some cards carry, as LinkedIn wrote it. */\n salary?: string;\n /** Other card lines, e.g. \"Be an early applicant\", \"5 applicants\". */\n insights?: string[];\n url: string;\n}\n\nconst WORKPLACE_SUFFIX: Record<string, Workplace> = {\n remote: 'remote',\n hybrid: 'hybrid',\n 'on-site': 'on-site',\n};\n\n/** \"Warsaw, Poland (Remote)\" -> the place and the workplace, apart. */\nfunction splitLocation(line: string | undefined): { location?: string; workplace?: Workplace } {\n if (line === undefined) return {};\n const m = line.match(/^(.*?)\\s*\\(([^()]+)\\)$/);\n const kind = m?.[2] === undefined ? undefined : WORKPLACE_SUFFIX[m[2].toLowerCase()];\n return kind === undefined || m?.[1] === undefined\n ? { location: line }\n : { location: m[1], workplace: kind };\n}\n\nfunction cardToJob(card: Node): JobCard | undefined {\n const urn = card.jobPostingUrn ?? card['*jobPosting'];\n const id = typeof urn === 'string' ? jobIdOf(urn) : undefined;\n const title = typeof card.jobPostingTitle === 'string' ? card.jobPostingTitle : text(card.title);\n if (id === undefined || title === undefined) return undefined;\n\n const footer = Array.isArray(card.footerItems) ? (card.footerItems as Node[]) : [];\n const listed = footer.find((f) => f.type === 'LISTED_DATE');\n const insights = footer\n .filter((f) => !['LISTED_DATE', 'PROMOTED', 'EASY_APPLY_TEXT'].includes(String(f.type)))\n .map((f) => text(f.text))\n .filter((t): t is string => t !== undefined);\n const insight = text((card.relevanceInsight as Node | null)?.text);\n if (insight !== undefined) insights.push(insight);\n\n return defined({\n id,\n title,\n company: text(card.primaryDescription),\n ...splitLocation(text(card.secondaryDescription)),\n listed: day(listed?.timeAt),\n easyApply: footer.some((f) => f.type === 'EASY_APPLY_TEXT'),\n promoted: footer.some((f) => f.type === 'PROMOTED'),\n salary: text(card.tertiaryDescription),\n insights: insights.length > 0 ? insights : undefined,\n url: viewUrl(id),\n });\n}\n\nexport interface JobPage {\n ok: true;\n jobs: JobCard[];\n /** LinkedIn's claimed total for the query. */\n total: number | undefined;\n start: number;\n /** The place a typed location resolved to. */\n location?: { geoId: string; name: string };\n /** Card kinds we do not read, by name: counted, never silently dropped. */\n unknownTypes: Record<string, number>;\n}\n\nconst drift = (message: string): Failure => ({\n ok: false,\n code: 'SCHEMA_DRIFT',\n message,\n hint: 'the job search response changed shape; re-capture it',\n});\n\n/** The cards the page lists, in order; other card kinds counted by name. */\nfunction readCards(elements: Node[], included: Node[]) {\n const byUrn = new Map<string, Node>();\n for (const node of included) {\n if (typeof node.entityUrn === 'string') byUrn.set(node.entityUrn, node);\n }\n const jobs: JobCard[] = [];\n const unknownTypes: Record<string, number> = {};\n let unresolved = 0;\n for (const el of elements) {\n // Search calls it `jobCardUnion`; a collection, `jobCard`, with every other kind null.\n const union = (el.jobCardUnion ?? el.jobCard ?? {}) as Record<string, unknown>;\n const ref = union['*jobPostingCard'];\n if (typeof ref !== 'string') {\n for (const [kind, v] of Object.entries(union))\n if (v !== null && !kind.startsWith('$')) unknownTypes[kind] = (unknownTypes[kind] ?? 0) + 1;\n continue;\n }\n const card = byUrn.get(ref);\n const job = card === undefined ? undefined : cardToJob(card);\n if (job === undefined) unresolved++;\n else if (!jobs.some((j) => j.id === job.id)) jobs.push(job);\n }\n return { jobs, unknownTypes, unresolved };\n}\n\n/** The geo a typed location resolved to, as the response echoes it. */\nfunction resolvedGeo(included: Node[]): { location: { geoId: string; name: string } } | object {\n const geo = included.find((n) => typeof n.$type === 'string' && n.$type.endsWith('.common.Geo'));\n const geoId = typeof geo?.entityUrn === 'string' ? geo.entityUrn.split(':').pop() : undefined;\n const name = typeof geo?.fullLocalizedName === 'string' ? geo.fullLocalizedName : undefined;\n return geoId !== undefined && name !== undefined ? { location: { geoId, name } } : {};\n}\n\nexport function parseJobCards(json: unknown): JobPage | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const data = root?.data;\n const elements = data?.elements;\n if (data === undefined || !Array.isArray(elements))\n return drift('the job search returned no result list');\n const paging = (data.paging ?? {}) as { total?: unknown; start?: unknown };\n const total = typeof paging.total === 'number' ? paging.total : undefined;\n const start = typeof paging.start === 'number' ? paging.start : 0;\n const included = root?.included ?? [];\n\n const { jobs, unknownTypes, unresolved } = readCards(elements as Node[], included);\n if (unresolved > 0 && jobs.length === 0)\n return drift(`${unresolved} job cards were listed but none could be read`);\n if (elements.length === 0 && total !== undefined && total > start) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `LinkedIn claims ${total} jobs but returned none from ${start}`,\n hint: 'a failed fetch, not an empty search; do not report \"no jobs\"',\n };\n }\n return { ok: true, jobs, total, start, ...resolvedGeo(included), unknownTypes };\n}\n\n// ─── Detail ───────────────────────────────────────────────────────────────────\n\nexport interface JobDetail {\n id: string;\n title: string;\n company?: string;\n companyUrl?: string;\n location?: string;\n workplace?: Workplace;\n employmentType?: string;\n experienceLevel?: string;\n industries?: string[];\n functions?: string[];\n listed?: string;\n expires?: string;\n /** LISTED, CLOSED, … as LinkedIn reports it. */\n state?: string;\n applicants?: number;\n apply?: { type: 'easy-apply' | 'external'; url?: string };\n /** The employer's applicant tracking system, when LinkedIn names it. */\n ats?: string;\n applied?: boolean;\n saved?: boolean;\n description?: string;\n url: string;\n}\n\nconst WORKPLACE_URN: Record<string, Workplace> = { '1': 'on-site', '2': 'remote', '3': 'hybrid' };\n\nfunction applyOf(method: unknown, id: string): JobDetail['apply'] {\n const m = method as Node | null | undefined;\n if (m === null || m === undefined) return undefined;\n const type = String(m.$type ?? '');\n if (type.endsWith('OffsiteApply')) {\n const url = typeof m.companyApplyUrl === 'string' ? m.companyApplyUrl : undefined;\n return defined({ type: 'external' as const, url });\n }\n if (type.endsWith('OnsiteApply')) {\n // Some Easy Apply jobs carry no apply URL; the button is on the job page.\n const url = typeof m.easyApplyUrl === 'string' ? m.easyApplyUrl : viewUrl(id);\n return { type: 'easy-apply' as const, url };\n }\n return undefined;\n}\n\n/** One posting, its company and the user's own state looked up in `included`. */\nfunction postingToJob(d: Node, included: Node[]): JobDetail | undefined {\n const rawId = d.jobPostingId ?? d.entityUrn;\n const id = rawId === undefined ? undefined : jobIdOf(String(rawId));\n if (id === undefined || typeof d.title !== 'string') return undefined;\n const find = (urn: unknown) =>\n typeof urn === 'string' ? included.find((n) => n.entityUrn === urn) : undefined;\n\n const details = (d.companyDetails ?? {}) as Node;\n const company = find(details.company ?? details['*companyResolutionResult']);\n const companyName =\n typeof company?.name === 'string'\n ? company.name\n : typeof details.companyName === 'string'\n ? details.companyName\n : undefined;\n const workplaces = Array.isArray(d.workplaceTypes) ? (d.workplaceTypes as string[]) : [];\n const workplace = WORKPLACE_URN[String(workplaces[0]?.split(':').pop())];\n const applying = find(d['*applyingInfo']);\n const saving = find(d['*savingInfo']);\n const list = (v: unknown) =>\n Array.isArray(v) && v.length > 0 ? v.filter((x) => typeof x === 'string') : undefined;\n const nonEmpty = (v: unknown) => (typeof v === 'string' && v !== '' ? v : undefined);\n\n return defined({\n id,\n title: d.title,\n company: companyName,\n companyUrl: typeof company?.url === 'string' ? company.url : undefined,\n location: nonEmpty(d.formattedLocation),\n workplace: workplace ?? (d.workRemoteAllowed === true ? 'remote' : undefined),\n employmentType: nonEmpty(d.formattedEmploymentStatus),\n experienceLevel: nonEmpty(d.formattedExperienceLevel),\n industries: list(d.formattedIndustries),\n functions: list(d.formattedJobFunctions),\n listed: day(d.listedAt),\n expires: day(d.expireAt),\n state: nonEmpty(d.jobState),\n applicants: typeof d.applies === 'number' && d.applies > 0 ? d.applies : undefined,\n apply: applyOf(d.applyMethod, id),\n ats: nonEmpty(d.applicantTrackingSystem),\n applied: typeof applying?.applied === 'boolean' ? applying.applied : undefined,\n saved: typeof saving?.saved === 'boolean' ? saving.saved : undefined,\n description: text(d.description),\n url: viewUrl(id),\n });\n}\n\nexport function parseJobDetail(json: unknown): { ok: true; job: JobDetail } | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const job = root?.data === undefined ? undefined : postingToJob(root.data, root.included ?? []);\n return job === undefined ? drift('the job response carried no posting') : { ok: true, job };\n}\n\nexport interface JobBatch {\n ok: true;\n jobs: JobDetail[];\n /** Ids the batch answered with an error. */\n missing: string[];\n}\n\nexport function parseJobBatch(json: unknown): JobBatch | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const results = root?.data?.results;\n if (results === null || typeof results !== 'object')\n return drift('the batch job response carried no results');\n const included = root?.included ?? [];\n const byUrn = new Map(included.map((n) => [n.entityUrn, n]));\n const jobs: JobDetail[] = [];\n for (const ref of Object.values(results as Record<string, unknown>)) {\n const node = typeof ref === 'string' ? byUrn.get(ref) : (ref as Node);\n const job = node === undefined ? undefined : postingToJob(node, included);\n if (job !== undefined) jobs.push(job);\n }\n const claimed = Object.keys(results as object).length;\n if (claimed > 0 && jobs.length === 0)\n return drift(`the batch listed ${claimed} jobs but none could be read`);\n const errors = (root?.data?.errors ?? {}) as Record<string, unknown>;\n return { ok: true, jobs, missing: Object.keys(errors).map((k) => k.replace(/^\\*/, '')) };\n}\n\n// ─── The hiring team ──────────────────────────────────────────────────────────\n//\n// Captured 2026-10-14. The detail's own JobHiringTeam is always empty (160 jobs\n// read, 0 members); the job page draws \"Meet the hiring team\" from an SDUI\n// component instead, one POST per job. It answers `0:null` when the job shows\n// no one, and in the session's language: the degree is LinkedIn's own words.\n\nexport const HIRING_TEAM = 'com.linkedin.sdui.generated.jobseeker.dsl.impl.peopleWhoCanHelp';\nexport const HIRING_TEAM_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/component?componentId=${HIRING_TEAM}&sduiid=${HIRING_TEAM}`;\n\nexport function hiringTeamBody(jobId: string) {\n return {\n componentId: HIRING_TEAM,\n clientArguments: {\n payload: { jobId, isTwoPane: false },\n states: [],\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n screenId: 'com.linkedin.sdui.flagshipnav.jobs.JobDetails',\n knownTemplateIds: [],\n },\n };\n}\n\nexport interface HiringMember {\n name: string;\n /** Their profile id: what `profile` and messages take. */\n id?: string;\n url: string;\n headline?: string;\n /** Connection degree, as LinkedIn words it in the session's language. */\n degree?: string;\n /** \"Job poster\", when LinkedIn says so. */\n role?: string;\n verified?: boolean;\n}\n\nconst unquote = (s: string) => JSON.parse(`\"${s}\"`) as string;\n\n/** One person's card row: name, then degree (\"• 3rd\"), headline and role. */\nfunction memberOf(card: string, id: string | undefined): HiringMember | undefined {\n const url = card.match(/\"url\":\"(https:\\/\\/www\\.linkedin\\.com\\/in\\/[^\"/]+\\/)\"/)?.[1];\n const name = card.match(/\\[null,\"((?:[^\"\\\\]|\\\\.)+)\"/)?.[1];\n if (url === undefined || name === undefined) return undefined;\n const lines = [...card.matchAll(/\"children\":\\[\"((?:[^\"\\\\$]|\\\\.)(?:[^\"\\\\]|\\\\.)*)\"\\]/g)].map((m) =>\n unquote(m[1] as string).trim(),\n );\n const degree = lines.find((l) => l.startsWith('•'));\n const [headline, role] = lines.filter((l) => l !== degree && l !== '');\n return defined({\n name: unquote(name).trim(),\n id,\n url,\n headline,\n degree: degree?.replace(/^•\\s*/, ''),\n role,\n verified: /\"role\":\"img\",\"aria-label\"/.test(card) ? true : undefined,\n });\n}\n\nexport function parseHiringTeam(stream: string): { ok: true; members: HiringMember[] } | Failure {\n if (/^0:null\\s*$/.test(stream.trim())) return { ok: true, members: [] };\n if (!stream.includes('peopleWhoCanHelp'))\n return drift('the hiring team answer was not the hiring team component');\n const rows = new Rows(stream);\n const cards = [...rows.byId].filter(([, row]) => /linkedin\\.com\\\\?\\/in\\\\?\\//.test(row));\n // Each card sits beside its Message button, which names their profile id.\n const at = (card: string) => stream.indexOf(`\"$L${card}\"`);\n const placed = cards.map(([key]) => at(key)).sort((a, b) => a - b);\n const members: HiringMember[] = [];\n for (const [key, row] of cards) {\n const from = at(key);\n const to = placed.find((p) => p > from) ?? stream.length;\n const id = stream.slice(from, to).match(/recipient=([A-Za-z0-9_-]+)/)?.[1];\n const m = memberOf(row, from === -1 ? undefined : id);\n if (m !== undefined) members.push(m);\n }\n const shown = (stream.match(/screenContext=JOB_DETAILS_HIRING_TEAM/g) ?? []).length;\n if (members.length === 0 && Math.max(shown, cards.length) > 0)\n return drift(\n `${Math.max(shown, cards.length)} hiring team members were shown but none could be read`,\n );\n return { ok: true, members };\n}\n\n// ─── Filters ──────────────────────────────────────────────────────────────────\n\nexport interface JobFilter {\n /** The parameter name `--filter key=…` and selectedFilters take. */\n key: string;\n label: string;\n options: { value: string; label: string; count?: number }[];\n}\n\nexport function parseJobFilters(json: unknown): { ok: true; filters: JobFilter[] } | Failure {\n const elements = (json as { data?: { elements?: unknown } } | null)?.data?.elements;\n if (!Array.isArray(elements)) return drift('the job filter list was missing');\n const filters: JobFilter[] = [];\n for (const el of elements as Node[]) {\n const groups = [\n ...((el.secondaryFilterGroups as Node[] | undefined) ?? []),\n ...((el.primaryFilterGroups as Node[] | undefined) ?? []),\n ];\n for (const group of groups) {\n for (const f of (group.filters as Node[] | undefined) ?? []) {\n const key = f.parameterName;\n if (typeof key !== 'string' || filters.some((x) => x.key === key)) continue;\n const values = [\n ...((f.secondaryFilterValues as Node[] | undefined) ?? []),\n ...((f.primaryFilterValues as Node[] | undefined) ?? []),\n ];\n const options = values\n .filter((v) => typeof v.value === 'string')\n .map((v) =>\n defined({\n value: v.value as string,\n label:\n text(v.displayName) ??\n (typeof v.displayName === 'string' ? v.displayName : String(v.value)),\n count: typeof v.count === 'number' ? v.count : undefined,\n }),\n );\n // An option-less filter is an upsell placeholder, not a knob.\n if (options.length === 0) continue;\n filters.push({ key, label: text(f.displayName) ?? key, options });\n }\n }\n }\n if (filters.length === 0) return drift('the job filter list was empty');\n return { ok: true, filters };\n}\n\n// ─── Friendly filter names ────────────────────────────────────────────────────\n\nexport interface JobFilterOptions {\n posted?: string;\n experience?: string[];\n type?: string[];\n workplace?: string[];\n easyApply?: boolean;\n under10?: boolean;\n verified?: boolean;\n inNetwork?: boolean;\n fairChance?: boolean;\n company?: string[];\n industry?: string[];\n function?: string[];\n title?: string[];\n place?: string[];\n sort?: string;\n distance?: number;\n /** `key=v1,v2`, by LinkedIn's own parameter names, from `job-filters`. */\n raw?: string[];\n}\n\nconst NAMED: Record<string, { param: string; values: Record<string, string> }> = {\n experience: {\n param: 'experience',\n values: {\n internship: '1',\n entry: '2',\n associate: '3',\n 'mid-senior': '4',\n senior: '4',\n director: '5',\n executive: '6',\n },\n },\n type: {\n param: 'jobType',\n values: {\n 'full-time': 'F',\n 'part-time': 'P',\n contract: 'C',\n temporary: 'T',\n volunteer: 'V',\n internship: 'I',\n other: 'O',\n },\n },\n workplace: {\n param: 'workplaceType',\n values: { 'on-site': '1', onsite: '1', remote: '2', hybrid: '3' },\n },\n};\n\nconst POSTED: Record<string, number> = {\n day: 86_400,\n '24h': 86_400,\n week: 604_800,\n month: 2_592_000,\n};\n\n/** A filter value we cannot map; caught once, in `jobFilterSelection`. */\nclass Refused extends Error {}\n\nfunction postedRange(given: string): string {\n const p = given.toLowerCase();\n const n = p.match(/^(\\d+)([hd])$/);\n const seconds = POSTED[p] ?? (n ? Number(n[1]) * (n[2] === 'h' ? 3600 : 86_400) : undefined);\n if (seconds === undefined)\n throw new Refused(`--posted '${given}' is not one of: 24h, week, month, or <N>h / <N>d`);\n return `r${seconds}`;\n}\n\n/** Friendly names, or LinkedIn's own codes, onto the codes; duplicates once. */\nfunction named(name: keyof typeof NAMED, given: string[]): string[] {\n const { values } = NAMED[name] as (typeof NAMED)[string];\n const out: string[] = [];\n for (const v of given) {\n const mapped = values[v.toLowerCase()] ?? (Object.values(values).includes(v) ? v : undefined);\n if (mapped === undefined)\n throw new Refused(`--${name} '${v}' is not one of: ${Object.keys(values).join(', ')}`);\n if (!out.includes(mapped)) out.push(mapped);\n }\n return out;\n}\n\nfunction rawFilter(r: string): [string, string[]] {\n const m = r.match(/^([A-Za-z_]+)=(.+)$/);\n if (m?.[1] === undefined || m[2] === undefined)\n throw new Refused(`--filter '${r}' is not key=value[,value]`);\n const values = m[2]\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v !== '');\n return [m[1], values];\n}\n\nfunction selection(o: JobFilterOptions): Record<string, string[]> {\n const filters: Record<string, string[]> = {};\n if (o.posted !== undefined) filters.timePostedRange = [postedRange(o.posted)];\n for (const name of ['experience', 'type', 'workplace'] as const) {\n const given = o[name];\n if (given !== undefined && given.length > 0)\n filters[(NAMED[name] as (typeof NAMED)[string]).param] = named(name, given);\n }\n const flags: [boolean | undefined, string][] = [\n [o.easyApply, 'applyWithLinkedin'],\n [o.under10, 'earlyApplicant'],\n [o.verified, 'verifiedJob'],\n [o.inNetwork, 'jobInYourNetwork'],\n [o.fairChance, 'fairChanceEmployer'],\n ];\n for (const [on, param] of flags) if (on === true) filters[param] = ['true'];\n const ids: [string[] | undefined, string][] = [\n [o.company, 'company'],\n [o.industry, 'industry'],\n [o.function, 'function'],\n [o.title, 'title'],\n [o.place, 'populatedPlace'],\n ];\n for (const [given, param] of ids)\n if (given !== undefined && given.length > 0) filters[param] = given;\n if (o.sort !== undefined) {\n const sort = { recent: 'DD', relevant: 'R' }[o.sort.toLowerCase()];\n if (sort === undefined) throw new Refused(`--sort '${o.sort}' is not one of: recent, relevant`);\n filters.sortBy = [sort];\n }\n if (o.distance !== undefined) filters.distance = [String(o.distance)];\n for (const r of o.raw ?? []) {\n const [key, values] = rawFilter(r);\n filters[key] = values;\n }\n return filters;\n}\n\nexport function jobFilterSelection(\n o: JobFilterOptions,\n): { ok: true; filters: Record<string, string[]> } | Failure {\n try {\n return { ok: true, filters: selection(o) };\n } catch (e) {\n if (e instanceof Refused) return { ok: false, code: 'INVALID_INPUT', message: e.message };\n throw e;\n }\n}\n","// ─── People search ────────────────────────────────────────────────────────────\n//\n// Probed 2026-10-14. The people results page itself now renders over SDUI,\n// but the Voyager search it grew out of (`voyagerSearchDashClusters`, the\n// `search` contract) still answers with every filter the page offers, passed\n// as `queryParameters` under LinkedIn's own names:\n//\n// network F, S, O 1st, 2nd, 3rd+\n// geoUrn geo ids places\n// currentCompany company ids\n// pastCompany company ids\n// schoolFilter school ids (a school is an organisation id)\n// industry industry ids\n// profileLanguage en, de, …\n// serviceCategory service ids\n// connectionOf one profile id their connections\n// followerOf one profile id their followers\n// openToVolunteer true\n// activelyHiringForJobTitles -100 for any\n// firstName lastName title company schoolFreetext free text\n//\n// `includeFiltersInResponse:true` returns every filter with its options' ids\n// and live counts. Pages hold up to 50: asking for 100 is answered with an\n// EMPTY SUCCESS (total 0, no error), the most dangerous shape a search can\n// fail in, so 50 is a constant, not an option. LinkedIn pages at most 1000\n// people of any query, whatever it claims to have matched.\n\nimport { CONTRACTS } from './contracts.ts';\nimport { encodeVariables } from './restli.ts';\nimport type { Failure } from './sdui-form.ts';\n\n/** People per call. 100 returns an empty success; see above. */\nexport const PEOPLE_PAGE = 50;\n\ntype Node = Record<string, unknown>;\nconst text = (v: unknown): string | undefined => {\n const t = (v as { text?: unknown } | null | undefined)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim() : undefined;\n};\n\nfunction defined<T extends Record<string, unknown>>(obj: T): T {\n for (const k of Object.keys(obj)) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\nconst drift = (message: string): Failure => ({\n ok: false,\n code: 'SCHEMA_DRIFT',\n message,\n hint: 'the people search response changed shape; re-capture it',\n});\n\n// ─── The request ──────────────────────────────────────────────────────────────\n\nexport interface PeopleQuery {\n keywords?: string;\n /** queryParameters by LinkedIn's own names; resultType is added. */\n params: Record<string, string[]>;\n start: number;\n /** Ask for the filter list with this page. */\n withFilters?: boolean;\n /** Another result type: COMPANIES, SCHOOLS, GROUPS, … (see engine/search.ts). */\n kind?: string;\n /** The My Network hub's lists use their own origin and intent (engine/network.ts). */\n origin?: string;\n intent?: string;\n}\n\nexport function peopleSearchUrl(q: PeopleQuery): string {\n const c = CONTRACTS.search;\n if (c?.queryId === undefined) throw new Error(\"the 'search' contract is missing\");\n const queryParameters = [\n ...Object.entries(q.params)\n .filter(([, v]) => v.length > 0)\n .map(([key, value]) => ({ key, value })),\n { key: 'resultType', value: [q.kind ?? 'PEOPLE'] },\n ];\n const variables = encodeVariables({\n start: q.start,\n count: PEOPLE_PAGE,\n origin: q.origin ?? 'FACETED_SEARCH',\n query: {\n // An empty `keywords` is answered with a 400: none is sent then.\n keywords: q.keywords === '' ? undefined : q.keywords,\n flagshipSearchIntent: q.intent ?? 'SEARCH_SRP',\n queryParameters,\n includeFiltersInResponse: q.withFilters === true,\n },\n });\n return `${c.path}?variables=${variables}&queryId=${c.queryId}`;\n}\n\n// ─── Results ──────────────────────────────────────────────────────────────────\n\nexport type Degree = '1st' | '2nd' | '3rd+' | 'out of network';\n\nexport interface Person {\n /** The profile id: what `connectionOf`, `followerOf` and `profile` take. */\n id: string;\n name: string;\n headline?: string;\n location?: string;\n degree?: Degree;\n verified?: boolean;\n /** The line under a result: mutual connections, services offered, … */\n insight?: string;\n /** Absent for members LinkedIn will not name to this account. */\n url?: string;\n}\n\nconst DEGREE: Record<string, Degree> = {\n DISTANCE_1: '1st',\n DISTANCE_2: '2nd',\n DISTANCE_3: '3rd+',\n OUT_OF_NETWORK: 'out of network',\n};\n\nconst PROFILE_ID = /urn:li:fsd_profile:([A-Za-z0-9_-]+)/;\n\nfunction insightOf(row: Node): string | undefined {\n const all = Array.isArray(row.insightsResolutionResults)\n ? (row.insightsResolutionResults as Node[])\n : [];\n const lines = all\n .map((i) => text((i.simpleInsight as Node | null)?.title))\n .filter((t): t is string => t !== undefined);\n return text(row.summary) ?? (lines.length > 0 ? lines.join('; ') : undefined);\n}\n\n/** `/in/<vanity>/` without the tracking query; a headless search URL is no profile. */\nfunction profileUrl(nav: unknown): string | undefined {\n if (typeof nav !== 'string') return undefined;\n const m = nav.match(/^(https:\\/\\/www\\.linkedin\\.com\\/in\\/[^/?#]+)/);\n return m?.[1] === undefined ? undefined : `${m[1]}/`;\n}\n\nfunction rowToPerson(row: Node): Person | undefined {\n const id = String(row.entityUrn ?? '').match(PROFILE_ID)?.[1];\n const name = text(row.title);\n if (id === undefined || name === undefined) return undefined;\n const tracking = (row.entityCustomTrackingInfo ?? {}) as Node;\n const badge = JSON.stringify(row.badgeIcon ?? null);\n return defined({\n id,\n name,\n headline: text(row.primarySubtitle),\n location: text(row.secondarySubtitle),\n degree: DEGREE[String(tracking.memberDistance)],\n verified: badge.includes('VERIFIED') ? true : undefined,\n insight: insightOf(row),\n url: profileUrl(row.navigationUrl),\n });\n}\n\nexport interface Clusters {\n elements?: { items?: { item?: Node }[] }[];\n paging?: { total?: unknown; start?: unknown };\n metadata?: Node;\n}\n\nexport function clustersOf(json: unknown): Clusters | undefined {\n const d = (json as { data?: { data?: Node } } | null)?.data?.data;\n const c = d?.searchDashClustersByAll;\n return c !== null && typeof c === 'object' ? (c as Clusters) : undefined;\n}\n\nexport interface PeoplePage {\n ok: true;\n people: Person[];\n /** How far LinkedIn will page this query: at most 1000. */\n total?: number;\n /** LinkedIn's own count of matches, often far more than it pages. */\n claimed?: number;\n start: number;\n /** Page furniture dropped on purpose: feedback cards, empty slots. */\n excluded: number;\n unknownTypes: Record<string, number>;\n}\n\n/** Items that are page furniture, not results. */\nconst FURNITURE = new Set([\n '*feedbackCard',\n '*bannerCard',\n '*searchSuggestionCard',\n '*promoCard',\n 'simpleText',\n 'simpleTextV2',\n '*simpleText',\n]);\n\n/** What one cluster item is: a result's urn, furniture, or kinds we do not read. */\nfunction classify(item: Node | undefined): { ref: string } | 'furniture' | string[] {\n const ref = item?.['*entityResult'];\n if (typeof ref === 'string') return { ref };\n const kinds = Object.entries(item ?? {})\n .filter(([k, v]) => v !== null && !k.startsWith('$'))\n .map(([k]) => k);\n return kinds.every((k) => FURNITURE.has(k)) ? 'furniture' : kinds;\n}\n\n/**\n * The results in a page, in LinkedIn's order, each mapped by `toRow`; page\n * furniture counted apart; item kinds we do not read counted by name.\n */\nexport function readItems<T extends { id: string }>(\n c: Clusters,\n included: Node[],\n toRow: (row: Node) => T | undefined,\n) {\n const byUrn = new Map(included.map((n) => [n.entityUrn, n]));\n const people: T[] = [];\n const unknownTypes: Record<string, number> = {};\n let excluded = 0;\n let unresolved = 0;\n const items = (c.elements ?? []).flatMap((el) => el.items ?? []);\n for (const { item } of items) {\n const kind = classify(item);\n if (kind === 'furniture') {\n excluded++;\n } else if (Array.isArray(kind)) {\n for (const k of kind) unknownTypes[k] = (unknownTypes[k] ?? 0) + 1;\n } else {\n const row = byUrn.get(kind.ref);\n const person = row === undefined ? undefined : toRow(row);\n if (person === undefined) unresolved++;\n else if (!people.some((p) => p.id === person.id)) people.push(person);\n }\n }\n return { people, unknownTypes, excluded, unresolved };\n}\n\nexport function parsePeople(json: unknown): PeoplePage | Failure {\n const c = clustersOf(json);\n if (c === undefined || !Array.isArray(c.elements))\n return drift('the people search returned no result list');\n const included = (json as { included?: Node[] }).included ?? [];\n const { people, unknownTypes, excluded, unresolved } = readItems(c, included, rowToPerson);\n const total = typeof c.paging?.total === 'number' ? c.paging.total : undefined;\n const start = typeof c.paging?.start === 'number' ? c.paging.start : 0;\n const claimedRaw = c.metadata?.totalResultCount;\n const claimed = typeof claimedRaw === 'number' ? claimedRaw : total;\n\n if (unresolved > 0 && people.length === 0)\n return drift(`${unresolved} people were listed but none could be read`);\n if (people.length === 0 && total !== undefined && total > start) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `LinkedIn claims ${total} people but returned none from ${start}`,\n hint: 'a failed fetch, not an empty search; do not report \"nobody\"',\n };\n }\n return {\n ok: true,\n people,\n ...(total !== undefined ? { total } : {}),\n ...(claimed !== undefined ? { claimed } : {}),\n start,\n excluded,\n unknownTypes,\n };\n}\n\n// ─── Filters ──────────────────────────────────────────────────────────────────\n\nexport interface PeopleFilter {\n /** The parameter name `--filter key=…` takes. */\n key: string;\n label: string;\n /** select: pick option ids; text: free text. */\n input: 'select' | 'text';\n /** What a name is looked up as, when the filter takes ids LinkedIn can search for. */\n lookup?: string;\n options: { value: string; label: string; count?: number }[];\n}\n\nexport function parsePeopleFilters(json: unknown): { ok: true; filters: PeopleFilter[] } | Failure {\n const cluster = clustersOf(json)?.metadata?.primaryFilterCluster as Node | null | undefined;\n if (cluster === null || cluster === undefined)\n return drift('the people search returned no filter list');\n const groups = [\n ...((cluster.secondaryFilterGroups as Node[] | undefined) ?? []),\n ...((cluster.primaryFilterGroups as Node[] | undefined) ?? []),\n ];\n const filters: PeopleFilter[] = [];\n for (const g of groups) {\n for (const f of (g.filters as Node[] | undefined) ?? []) {\n const key = f.parameterName;\n // A navigation filter switches to another kind of search; not a knob.\n if (typeof key !== 'string' || f.renderType === 'NAVIGATION') continue;\n if (filters.some((x) => x.key === key)) continue;\n const values = [\n ...((f.secondaryFilterValues as Node[] | undefined) ?? []),\n ...((f.primaryFilterValues as Node[] | undefined) ?? []),\n ];\n filters.push(\n defined({\n key,\n label: text(f.displayName) ?? key,\n input: f.renderType === 'FREE_TEXT' ? ('text' as const) : ('select' as const),\n lookup: typeof f.typeaheadType === 'string' ? f.typeaheadType : undefined,\n options: values\n .filter((v) => typeof v.value === 'string')\n .map((v) =>\n defined({\n value: v.value as string,\n label: typeof v.displayName === 'string' ? v.displayName : String(v.value),\n count: typeof v.count === 'number' && v.count > 0 ? v.count : undefined,\n }),\n ),\n }),\n );\n }\n }\n if (filters.length === 0) return drift('the people filter list was empty');\n return { ok: true, filters };\n}\n\n// ─── Companies and schools by name ────────────────────────────────────────────\n\n/** A company or school search: each hit with the organisation id filters take. */\nexport function parseOrgHits(\n json: unknown,\n): { ok: true; hits: { id: string; name: string }[] } | Failure {\n const c = clustersOf(json);\n if (c === undefined) return drift('the organisation search returned no result list');\n const included = (json as { included?: Node[] }).included ?? [];\n const byUrn = new Map(included.map((n) => [n.entityUrn, n]));\n const hits: { id: string; name: string }[] = [];\n for (const el of c.elements ?? []) {\n for (const { item } of el.items ?? []) {\n const row = byUrn.get(item?.['*entityResult']);\n const id = String(row?.entityUrn ?? '').match(/urn:li:fsd_company:(\\d+)/)?.[1];\n const name = text(row?.title);\n if (id !== undefined && name !== undefined && !hits.some((h) => h.id === id))\n hits.push({ id, name });\n }\n }\n return { ok: true, hits };\n}\n\n// ─── Friendly filter names ────────────────────────────────────────────────────\n\nexport interface PeopleFilterOptions {\n /** 1st, 2nd, 3rd+. */\n network?: string[];\n /** Current company ids. */\n company?: string[];\n pastCompany?: string[];\n school?: string[];\n /** Geo ids. */\n geo?: string[];\n industry?: string[];\n /** Profile language codes: en, de, … */\n language?: string[];\n /** Service category ids. */\n service?: string[];\n /** A profile id or urn: their connections. */\n connectionOf?: string;\n /** A profile id or urn: their followers. */\n followerOf?: string;\n firstName?: string;\n lastName?: string;\n /** Free text matched against the current title. */\n title?: string;\n /** Free text matched against company names, current or past. */\n companyText?: string;\n schoolText?: string;\n openToVolunteer?: boolean;\n /** `key=v1,v2`, by LinkedIn's own parameter names, from `people-filters`. */\n raw?: string[];\n}\n\nconst NETWORK: Record<string, string> = {\n '1st': 'F',\n '1': 'F',\n '2nd': 'S',\n '2': 'S',\n '3rd+': 'O',\n '3rd': 'O',\n '3': 'O',\n};\n\nconst profileId = (v: string) => v.match(/^(?:urn:li:fsd_profile:)?(AC[A-Za-z0-9_-]{10,})$/)?.[1];\n\nclass Refused extends Error {}\n\nfunction selection(o: PeopleFilterOptions): Record<string, string[]> {\n const params: Record<string, string[]> = {};\n if (o.network !== undefined && o.network.length > 0) {\n params.network = o.network.map((n) => {\n const code = NETWORK[n.toLowerCase()] ?? (['F', 'S', 'O'].includes(n) ? n : undefined);\n if (code === undefined) throw new Refused(`--network '${n}' is not one of: 1st, 2nd, 3rd+`);\n return code;\n });\n }\n const ids: [string[] | undefined, string][] = [\n [o.company, 'currentCompany'],\n [o.pastCompany, 'pastCompany'],\n [o.school, 'schoolFilter'],\n [o.geo, 'geoUrn'],\n [o.industry, 'industry'],\n [o.language, 'profileLanguage'],\n [o.service, 'serviceCategory'],\n ];\n for (const [given, param] of ids)\n if (given !== undefined && given.length > 0) params[param] = given;\n for (const [given, param, flag] of [\n [o.connectionOf, 'connectionOf', '--connection-of'],\n [o.followerOf, 'followerOf', '--follower-of'],\n ] as const) {\n if (given === undefined) continue;\n const id = profileId(given.trim());\n if (id === undefined)\n throw new Refused(`${flag} takes a profile id (ACo…) or urn, from a people row's \\`id\\``);\n params[param] = [id];\n }\n const texts: [string | undefined, string][] = [\n [o.firstName, 'firstName'],\n [o.lastName, 'lastName'],\n [o.title, 'title'],\n [o.companyText, 'company'],\n [o.schoolText, 'schoolFreetext'],\n ];\n for (const [given, param] of texts)\n if (given !== undefined && given.trim() !== '') params[param] = [given.trim()];\n if (o.openToVolunteer === true) params.openToVolunteer = ['true'];\n for (const r of o.raw ?? []) {\n const m = r.match(/^([A-Za-z_]+)=(.+)$/);\n if (m?.[1] === undefined || m[2] === undefined)\n throw new Refused(`--filter '${r}' is not key=value[,value]`);\n params[m[1]] = m[2]\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v !== '');\n }\n return params;\n}\n\nexport function peopleFilterSelection(\n o: PeopleFilterOptions,\n): { ok: true; params: Record<string, string[]> } | Failure {\n try {\n return { ok: true, params: selection(o) };\n } catch (e) {\n if (e instanceof Refused) return { ok: false, code: 'INVALID_INPUT', message: e.message };\n throw e;\n }\n}\n","// ─── `lnrelay people`, `lnrelay people-filters` ───────────────────────────────\n//\n// See engine/people.ts. A people search call returns up to 50 people and\n// spends the search budget; so does each name lookup (a company or school\n// name to its id, a place to its geo id). Several keyword sets are searched\n// and merged by profile id, as `jobs` does (commands/paged.ts).\n\nimport { createLiveClient } from '../engine/index.ts';\nimport { jobSearchUrl, parseJobCards } from '../engine/jobs.ts';\nimport {\n PEOPLE_PAGE,\n type PeopleFilterOptions,\n type Person,\n parseOrgHits,\n parsePeople,\n parsePeopleFilters,\n peopleFilterSelection,\n peopleSearchUrl,\n} from '../engine/people.ts';\nimport type { Failure } from '../engine/sdui-form.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { project } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport {\n keywordSets,\n line,\n type Matched,\n metaOf,\n type PageFetch,\n type Paging,\n searchAll,\n} from './paged.ts';\n\ntype Fetched =\n | { ok: true; json: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted GET. Injectable so tests send nothing. */\nexport type PeopleFetch = (url: string, spendClass: 'search') => Promise<Fetched>;\n\nexport function liveFetch(command: string, quiet: boolean): PeopleFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err(command, 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, spendClass) => {\n const r = await client.request({ url, spendClass, operation: command });\n return r.ok ? { ok: true, json: r.json } : r;\n };\n}\n\nexport interface PeopleRequest {\n /** One keyword set, or several: each its own search, merged by profile id. */\n keywords?: string | string[];\n /** A place by name, looked up to its geo id. */\n location?: string;\n limit: number;\n start?: number;\n /** Company and school entries may be names; they are looked up to ids. */\n filter?: PeopleFilterOptions;\n}\n\n/** LinkedIn pages no further than 1000 people into any one query. */\nconst PAGING: Paging = { pageSize: PEOPLE_PAGE, max: 1000 };\n\ntype Row = Matched<Person>;\n\nfunction compactPerson(p: Row): string {\n return line([\n p.id,\n p.name,\n p.headline,\n p.location,\n p.degree,\n p.verified ? 'verified' : undefined,\n p.insight,\n p.url,\n p.matched !== undefined ? `matched: ${p.matched.join(' + ')}` : undefined,\n ]);\n}\n\nexport function shape<T extends object>(rows: T[], opts: OutputOpts, toLine: (r: T) => string) {\n if (opts.compact === true) return rows.map(toLine);\n if (opts.fields !== undefined && opts.fields !== '')\n return project(rows as unknown as Record<string, unknown>[], opts.fields);\n return rows;\n}\n\n// ─── Names to ids ─────────────────────────────────────────────────────────────\n\nexport interface Lookup {\n given: string;\n id: string;\n name: string;\n}\n\nconst isId = (v: string) => /^\\d+$/.test(v);\n\n/** Organisation names to ids, by LinkedIn's own company or school search: the top hit. */\nasync function resolveOrgs(\n get: PeopleFetch,\n given: string[] | undefined,\n kind: 'COMPANIES' | 'SCHOOLS',\n): Promise<{ ids: string[]; found: Lookup[] } | Failure | undefined> {\n if (given === undefined || given.length === 0) return undefined;\n const ids: string[] = [];\n const found: Lookup[] = [];\n for (const v of given) {\n if (isId(v)) {\n ids.push(v);\n continue;\n }\n const res = await get(peopleSearchUrl({ keywords: v, params: {}, start: 0, kind }), 'search');\n const hits = res.ok ? parseOrgHits(res.json) : res;\n if (!hits.ok) return hits;\n const top = hits.hits[0];\n if (top === undefined) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `no ${kind === 'SCHOOLS' ? 'school' : 'company'} on LinkedIn matches \"${v}\"`,\n hint: 'check the spelling, or pass its id (from `people-filters`)',\n };\n }\n ids.push(top.id);\n found.push({ given: v, id: top.id, name: top.name });\n }\n return { ids, found };\n}\n\n/** A place name to a geo id, the way the job search resolves a typed location. */\nexport async function resolvePlace(get: PeopleFetch, place: string): Promise<Lookup | Failure> {\n const res = await get(\n jobSearchUrl({ location: place, filters: {}, start: 0, count: 1 }),\n 'search',\n );\n const page = res.ok ? parseJobCards(res.json) : res;\n if (!page.ok) return page;\n if (page.location === undefined) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `LinkedIn could not place \"${place}\"`,\n hint: 'try a city, region or country, or pass --geo <id> (ids are in `people-filters`)',\n };\n }\n return { given: place, id: page.location.geoId, name: page.location.name };\n}\n\n/** Looks up every name in the request; ids pass straight through. */\nasync function resolveNames(\n get: PeopleFetch,\n req: Omit<PeopleRequest, 'limit'>,\n): Promise<{ filter: PeopleFilterOptions; resolved: Record<string, unknown> } | Failure> {\n const filter: PeopleFilterOptions = { ...(req.filter ?? {}) };\n const resolved: Record<string, unknown> = {};\n const orgs: ['company' | 'pastCompany' | 'school', 'COMPANIES' | 'SCHOOLS'][] = [\n ['company', 'COMPANIES'],\n ['pastCompany', 'COMPANIES'],\n ['school', 'SCHOOLS'],\n ];\n for (const [key, kind] of orgs) {\n const r = await resolveOrgs(get, filter[key], kind);\n if (r === undefined) continue;\n if ('ok' in r) return r;\n filter[key] = r.ids;\n if (r.found.length > 0) resolved[key] = r.found;\n }\n if (req.location !== undefined && req.location.trim() !== '') {\n const place = await resolvePlace(get, req.location.trim());\n if ('ok' in place) return place;\n filter.geo = [...(filter.geo ?? []), place.id];\n resolved.location = place;\n }\n return { filter, resolved };\n}\n\n/** Filters this tool also takes by name, and the flag that does it. */\nconst BY_NAME: Record<string, string> = {\n currentCompany: 'ids, or names via --company',\n pastCompany: 'ids, or names via --past-company',\n schoolFilter: 'ids, or names via --school',\n geoUrn: 'ids via --geo, or a place via --location',\n};\n\n// ─── Runners ──────────────────────────────────────────────────────────────────\n\nexport async function runPeople(\n req: PeopleRequest,\n opts: OutputOpts = {},\n fetch?: PeopleFetch,\n): Promise<Envelope> {\n const sets = keywordSets(req.keywords);\n const named = peopleFilterSelection(req.filter ?? {});\n if (!named.ok) return err('people', named.code, named.message, 'see `lnrelay help people`');\n const hasFilter = Object.keys(named.params).length > 0 || (req.location ?? '').trim() !== '';\n if (sets.length === 0 && !hasFilter) {\n return err(\n 'people',\n 'INVALID_INPUT',\n 'give keywords, a filter, or both',\n 'lnrelay people \"<keywords>\" [\"<more>\" ...] [--company \"<name|id>\"] [--location \"<place>\"] [filters]',\n );\n }\n const get = fetch ?? liveFetch('people', opts.quiet === true);\n if (typeof get !== 'function') return get;\n\n const names = await resolveNames(get, req);\n if ('ok' in names) return err('people', names.code, names.message, names.hint);\n const selection = peopleFilterSelection(names.filter);\n if (!selection.ok) return err('people', selection.code, selection.message);\n const params = selection.params;\n\n const first = Math.max(0, req.start ?? 0);\n const want = Math.max(1, Math.min(req.limit, PAGING.max - first));\n const fetchPage: PageFetch<Person> = async (keywords, start) => {\n const res = await get(\n peopleSearchUrl({ ...(keywords ? { keywords } : {}), params, start }),\n 'search',\n );\n const page = res.ok ? parsePeople(res.json) : res;\n if (!page.ok) return page;\n return {\n ok: true,\n items: page.people,\n ...(page.total !== undefined ? { total: page.total } : {}),\n ...(page.claimed !== undefined ? { claimed: page.claimed } : {}),\n unknownTypes: page.unknownTypes,\n };\n };\n const merged = await searchAll(\n fetchPage,\n sets.length > 0 ? sets : [undefined],\n first,\n want,\n PAGING,\n );\n if (merged.rows.length === 0 && merged.failure !== undefined) {\n const f = merged.failure;\n return err('people', f.code, f.message, f.hint);\n }\n\n const single = sets.length <= 1;\n return ok('people', {\n query: { ...(sets.length > 0 ? { keywords: single ? sets[0] : sets } : {}), params },\n ...(Object.keys(names.resolved).length > 0 ? { resolved: names.resolved } : {}),\n items: shape(merged.rows, opts, compactPerson),\n meta: metaOf('people', merged, single, first),\n });\n}\n\nexport async function runPeopleFilters(\n req: Omit<PeopleRequest, 'limit'>,\n opts: OutputOpts = {},\n fetch?: PeopleFetch,\n): Promise<Envelope> {\n const sets = keywordSets(req.keywords);\n if (sets.length > 1) {\n return err(\n 'people-filters',\n 'INVALID_INPUT',\n 'people-filters takes one keyword set: its counts belong to that one query',\n 'lnrelay people-filters \"<keywords>\" [filters]',\n );\n }\n const get = fetch ?? liveFetch('people-filters', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const names = await resolveNames(get, req);\n if ('ok' in names) return err('people-filters', names.code, names.message, names.hint);\n const selection = peopleFilterSelection(names.filter);\n if (!selection.ok) return err('people-filters', selection.code, selection.message);\n\n const url = peopleSearchUrl({\n ...(sets[0] !== undefined ? { keywords: sets[0] } : {}),\n params: selection.params,\n start: 0,\n withFilters: true,\n });\n const res = await get(url, 'search');\n const parsed = res.ok ? parsePeopleFilters(res.json) : res;\n if (!parsed.ok) return err('people-filters', parsed.code, parsed.message, parsed.hint);\n return ok('people-filters', {\n ...(Object.keys(names.resolved).length > 0 ? { resolved: names.resolved } : {}),\n items: shape(parsed.filters, opts, (f) => {\n const how = f.input === 'text' ? 'free text' : (BY_NAME[f.key] ?? 'ids');\n const options = f.options\n .map((o) => `${o.value}=${o.label}${o.count !== undefined ? ` (${o.count})` : ''}`)\n .join(', ');\n return `${f.key} [${how}]${options !== '' ? `: ${options}` : ''}`;\n }),\n meta: { state: 'complete', operation: 'people-filters', returnedCount: parsed.filters.length },\n });\n}\n","// ─── `lnrelay search posts` ───────────────────────────────────────────────────\n//\n// See engine/posts.ts. Each call returns up to 20 posts and spends the search\n// budget, as does each company given by name. The stream is heavy (about half\n// a megabyte a post), so ask for the depth you need.\n\nimport { createLiveClient } from '../engine/index.ts';\nimport { parseOrgHits, peopleSearchUrl } from '../engine/people.ts';\nimport {\n POSTS_PAGE,\n POSTS_URL,\n type PostFilter,\n type PostHit,\n parsePosts,\n postsPagerBody,\n} from '../engine/posts.ts';\nimport type { Failure } from '../engine/sdui-form.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport {\n keywordSets,\n line,\n type Matched,\n metaOf,\n type PageFetch,\n type Paging,\n searchAll,\n} from './paged.ts';\nimport { type Lookup, shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; raw: string; json?: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted call: the pager when a body is given, a GET otherwise. Injectable for tests. */\nexport type PostsFetch = (url: string, body: unknown, spendClass: 'search') => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): PostsFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('search posts', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, body, spendClass) => {\n const r = await client.request({\n url,\n ...(body !== undefined ? { method: 'POST' as const, body } : {}),\n spendClass,\n operation: 'search-posts',\n });\n if (!r.ok) return r;\n return { ok: true, raw: (r.classification as { raw?: string }).raw ?? '', json: r.json };\n };\n}\n\nexport interface PostsRequest {\n keywords?: string | string[];\n limit: number;\n start?: number;\n /** recent | relevant */\n sort?: string;\n /** 24h | week | month */\n posted?: string;\n /** videos, images, jobs, live, articles, documents */\n type?: string[];\n /** 1st, me */\n postedBy?: string[];\n /** Profile ids. */\n from?: string[];\n mentions?: string[];\n /** Company names or ids. */\n fromCompany?: string[];\n mentionsCompany?: string[];\n authorCompany?: string[];\n authorIndustry?: string[];\n authorTitle?: string;\n /** `key=v1,v2`, by the pager's own names. */\n raw?: string[];\n}\n\n/** LinkedIn's posts pager: no total is given, so paging ends on an empty or short page. */\nconst PAGING: Paging = { pageSize: POSTS_PAGE, max: 1000 };\n\nconst CHOICES: Record<string, { param: PostFilter; values: Record<string, string> }> = {\n sort: { param: 'sortBy', values: { recent: 'date_posted', relevant: 'relevance' } },\n posted: {\n param: 'datePosted',\n values: { '24h': 'past-24h', day: 'past-24h', week: 'past-week', month: 'past-month' },\n },\n type: {\n param: 'contentType',\n values: {\n videos: 'videos',\n images: 'photos',\n photos: 'photos',\n jobs: 'jobs',\n live: 'liveVideos',\n articles: 'articles',\n documents: 'documents',\n },\n },\n postedBy: { param: 'postedBy', values: { '1st': 'first', me: 'me', first: 'first' } },\n};\n\ntype Refusal = { ok: false; code: string; message: string; hint?: string };\n\nfunction choose(name: keyof typeof CHOICES, given: string[]): string[] | Refusal {\n const { values } = CHOICES[name] as (typeof CHOICES)[string];\n const out: string[] = [];\n for (const g of given) {\n const v = values[g.toLowerCase()];\n if (v === undefined)\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `--${name} '${g}' is not one of: ${Object.keys(values).join(', ')}`,\n };\n out.push(v);\n }\n return out;\n}\n\n/** Company names to ids by LinkedIn's company search: the top hit, reported. */\nasync function companies(\n get: PostsFetch,\n given: string[],\n): Promise<{ ids: string[]; found: Lookup[] } | Failure> {\n const ids: string[] = [];\n const found: Lookup[] = [];\n for (const v of given) {\n if (/^\\d+$/.test(v)) {\n ids.push(v);\n continue;\n }\n const res = await get(\n peopleSearchUrl({ keywords: v, params: {}, start: 0, kind: 'COMPANIES' }),\n undefined,\n 'search',\n );\n const hits = res.ok ? parseOrgHits(res.json) : res;\n if (!hits.ok) return hits;\n const top = hits.hits[0];\n if (top === undefined)\n return { ok: false, code: 'INVALID_INPUT', message: `no company on LinkedIn matches \"${v}\"` };\n ids.push(top.id);\n found.push({ given: v, id: top.id, name: top.name });\n }\n return { ids, found };\n}\n\nfunction choices(req: PostsRequest): Partial<Record<PostFilter, string[]>> | Refusal {\n const filters: Partial<Record<PostFilter, string[]>> = {};\n const picks: [keyof typeof CHOICES, string[] | undefined][] = [\n ['sort', req.sort !== undefined ? [req.sort] : undefined],\n ['posted', req.posted !== undefined ? [req.posted] : undefined],\n ['type', req.type],\n ['postedBy', req.postedBy],\n ];\n for (const [name, given] of picks) {\n if (given === undefined || given.length === 0) continue;\n const v = choose(name, given);\n if (!Array.isArray(v)) return v;\n filters[(CHOICES[name] as (typeof CHOICES)[string]).param] = v;\n }\n if (req.from !== undefined && req.from.length > 0) filters.fromMember = req.from;\n if (req.mentions !== undefined && req.mentions.length > 0) filters.mentionsMember = req.mentions;\n if (req.authorIndustry !== undefined && req.authorIndustry.length > 0)\n filters.authorIndustry = req.authorIndustry;\n if (req.authorTitle !== undefined && req.authorTitle.trim() !== '')\n filters.authorJobTitle = [req.authorTitle.trim()];\n for (const r of req.raw ?? []) {\n const m = r.match(/^([A-Za-z_]+)=(.+)$/);\n if (m?.[1] === undefined || m[2] === undefined)\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `--filter '${r}' is not key=value[,value]`,\n };\n filters[m[1] as PostFilter] = m[2]\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v !== '');\n }\n return filters;\n}\n\n/** The request as pager filters; company names are looked up. */\nasync function filtersOf(req: PostsRequest, get: PostsFetch) {\n const filters = choices(req);\n if ('ok' in filters) return filters;\n const resolved: Record<string, Lookup[]> = {};\n const orgs: [keyof PostsRequest, PostFilter][] = [\n ['fromCompany', 'fromOrganization'],\n ['mentionsCompany', 'mentionsOrganization'],\n ['authorCompany', 'authorCompany'],\n ];\n for (const [key, param] of orgs) {\n const given = req[key] as string[] | undefined;\n if (given === undefined || given.length === 0) continue;\n const r = await companies(get, given);\n if ('ok' in r) return r;\n filters[param] = r.ids;\n if (r.found.length > 0) resolved[key] = r.found;\n }\n return { filters, resolved };\n}\n\nfunction compactPost(p: Matched<PostHit>): string {\n const counts = [\n p.reactions !== undefined ? `${p.reactions} reactions` : undefined,\n p.comments !== undefined ? `${p.comments} comments` : undefined,\n p.reposts !== undefined ? `${p.reposts} reposts` : undefined,\n ].filter(Boolean);\n const text = p.text?.replace(/\\s+/g, ' ');\n return line([\n p.id,\n p.author,\n p.posted,\n counts.length > 0 ? counts.join(' · ') : undefined,\n text !== undefined && text.length > 160 ? `${text.slice(0, 157)}…` : text,\n p.url,\n p.matched !== undefined ? `matched: ${p.matched.join(' + ')}` : undefined,\n ]);\n}\n\nexport async function runPostsSearch(\n req: PostsRequest,\n opts: OutputOpts = {},\n fetch?: PostsFetch,\n): Promise<Envelope> {\n const command = 'search posts';\n const sets = keywordSets(req.keywords);\n const early = choices(req);\n if ('ok' in early) return err(command, early.code, early.message, early.hint);\n const anyFilter =\n Object.keys(early).length > 0 ||\n [req.fromCompany, req.mentionsCompany, req.authorCompany].some((v) => (v?.length ?? 0) > 0);\n if (sets.length === 0 && !anyFilter)\n return err(\n command,\n 'INVALID_INPUT',\n 'give keywords, a filter, or both',\n 'lnrelay search posts \"<keywords>\"',\n );\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n const f = await filtersOf(req, get);\n if ('ok' in f) return err(command, f.code, f.message, f.hint);\n\n const first = Math.max(0, req.start ?? 0);\n const want = Math.max(1, Math.min(req.limit, PAGING.max - first));\n const fetchPage: PageFetch<PostHit> = async (keywords, start) => {\n const body = postsPagerBody({ ...(keywords ? { keywords } : {}), filters: f.filters, start });\n const res = await get(POSTS_URL, body, 'search');\n const page = res.ok ? parsePosts(res.raw) : res;\n if (!page.ok) return page;\n const cards = page.posts.length + page.unread;\n const unknownTypes: Record<string, number> =\n page.unread > 0 ? { unreadPostCards: page.unread } : {};\n return {\n ok: true,\n items: page.posts,\n // No total is given: a short page is the last.\n ...(cards < POSTS_PAGE ? { total: start + cards } : {}),\n unknownTypes,\n };\n };\n const merged = await searchAll(\n fetchPage,\n sets.length > 0 ? sets : [undefined],\n first,\n want,\n PAGING,\n );\n if (merged.rows.length === 0 && merged.failure !== undefined) {\n const fail = merged.failure;\n return err(command, fail.code, fail.message, fail.hint);\n }\n const single = sets.length <= 1;\n return ok('search', {\n kind: 'posts',\n query: {\n ...(sets.length > 0 ? { keywords: single ? sets[0] : sets } : {}),\n filters: f.filters,\n },\n ...(Object.keys(f.resolved).length > 0 ? { resolved: f.resolved } : {}),\n items: shape(merged.rows, opts, compactPost),\n meta: metaOf(command, merged, single, first),\n });\n}\n","// ─── `lnrelay company <name|url|id> [...] [--posts N]` ────────────────────────\n//\n// A company page in full; see engine/company.ts. Each company is one page\n// call. `--posts N` adds its newest posts: the posts search, filtered to posts\n// from the company and sorted by date, on the search budget.\n\nimport { type Company, companyRefOf, companyUrl, parseCompany } from '../engine/company.ts';\nimport { createLiveClient } from '../engine/index.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { shape } from './people.ts';\nimport { runPostsSearch } from './posts-search.ts';\n\ntype Fetched =\n | { ok: true; raw: string; json?: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted call: a POST when a body is given, a GET otherwise. Injectable for tests. */\nexport type CompanyFetch = (\n url: string,\n body: unknown,\n spendClass: 'page' | 'search',\n) => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): CompanyFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('company', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, body, spendClass) => {\n const r = await client.request({\n url,\n ...(body !== undefined ? { method: 'POST' as const, body } : {}),\n spendClass,\n operation: 'company',\n });\n if (!r.ok) return r;\n return { ok: true, raw: (r.classification as { raw?: string }).raw ?? '', json: r.json };\n };\n}\n\nexport interface CompanyRequest {\n /** Add this many of the company's newest posts. */\n posts?: number;\n}\n\ntype Read = Company & { posts?: unknown[]; postsError?: string };\n\nfunction compactCompany(c: Read): string {\n return line([\n c.id,\n c.name,\n c.industry,\n c.size,\n c.employeesOnLinkedIn !== undefined ? `${c.employeesOnLinkedIn} on LinkedIn` : undefined,\n c.followers !== undefined ? `${c.followers} followers` : undefined,\n c.headquarters,\n c.website,\n c.url,\n ]);\n}\n\n/** Its newest posts onto the company; a failure says why on the company. */\nasync function addPosts(get: CompanyFetch, c: Read, n: number, opts: OutputOpts) {\n const r = await runPostsSearch(\n { fromCompany: [c.id], sort: 'recent', limit: n },\n opts.compact === true ? { compact: true } : {},\n (url, body) => get(url, body, 'search'),\n );\n if (r.ok) c.posts = (r.data as { items: unknown[] }).items;\n else c.postsError = `${r.error.code}: ${r.error.message}`;\n}\n\ntype Outcome =\n | { ok: true; company: Read }\n | { ok: false; code: string; message: string; hint?: string };\n\nasync function readOne(\n get: CompanyFetch,\n input: string,\n req: CompanyRequest,\n opts: OutputOpts,\n): Promise<Outcome> {\n const ref = companyRefOf(input) as NonNullable<ReturnType<typeof companyRefOf>>;\n const res = await get(companyUrl(ref), undefined, 'page');\n const parsed = res.ok ? parseCompany(res.json) : res;\n if (!parsed.ok) return parsed;\n const company: Read = parsed.company;\n if (req.posts !== undefined && req.posts > 0) await addPosts(get, company, req.posts, opts);\n return { ok: true, company };\n}\n\nexport async function runCompany(\n inputs: string[],\n req: CompanyRequest = {},\n opts: OutputOpts = {},\n fetch?: CompanyFetch,\n): Promise<Envelope> {\n const given = [...new Set(inputs.map((i) => i.trim()).filter((i) => i !== ''))];\n const bad = given.filter((g) => companyRefOf(g) === undefined);\n if (given.length === 0 || bad.length > 0)\n return err(\n 'company',\n 'INVALID_INPUT',\n bad.length > 0 ? `not a company: ${bad.join(', ')}` : 'a company is required',\n 'lnrelay company <universal-name|company-url|id> [...] [--posts N]',\n );\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n\n if (given.length === 1) {\n const one = await readOne(get, given[0] as string, req, opts);\n return one.ok ? ok('company', one.company) : err('company', one.code, one.message, one.hint);\n }\n const companies: Read[] = [];\n const unread: { company: string; code: string; message: string }[] = [];\n for (const g of given) {\n const one = await readOne(get, g, req, opts);\n // A name and an id can be the same company: it is listed once.\n if (one.ok && !companies.some((c) => c.id === one.company.id)) companies.push(one.company);\n else if (!one.ok) unread.push({ company: g, code: one.code, message: one.message });\n }\n if (companies.length === 0)\n return err('company', unread[0]?.code ?? 'FETCH_FAILED', 'no company could be read');\n return ok('company', {\n items: shape(companies, opts, compactCompany),\n meta: {\n state: unread.length === 0 ? 'complete' : 'partial',\n operation: 'company',\n returnedCount: companies.length,\n ...(unread.length > 0 ? { unread } : {}),\n },\n });\n}\n","// ─── Events: the events hub, and one event in full ────────────────────────────\n//\n// Captured 2026-10-14. Searching events by keyword is `search events`\n// (engine/search.ts). This adds the two things the events page itself has:\n//\n// the hub an SDUI component, `eventsHomeCardGroupsSection`: the Premium\n// LinkedIn Live events and \"recommended for you\", as cards\n// an event `voyagerEventsDashProfessionalEvents` by event id: times and\n// time zone, state, place or online, attendees, organiser,\n// description, the event's own site\n//\n// A hub card's own rows hold, in order: when, the organiser (not on LinkedIn\n// Live cards), the attendee line, the title. Labels come in the viewer's\n// LinkedIn language, so a card is read by that order and by shape (a clock\n// time; a number then a word), never by the words. Following a card's\n// references would run into the next card's rows; the walk stops there.\n\nimport { CONTRACTS } from './contracts.ts';\nimport { Rows } from './posts.ts';\nimport { encodeVariables } from './restli.ts';\nimport type { Failure } from './sdui-form.ts';\n\nexport const EVENTS_HUB = 'com.linkedin.sdui.generated.events.dsl.impl.eventsHomeCardGroupsSection';\nexport const EVENTS_HUB_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/component?componentId=${EVENTS_HUB}&sduiid=${EVENTS_HUB}`;\n\nexport function eventsHubBody() {\n return {\n componentId: EVENTS_HUB,\n clientArguments: { states: [], screenId: '', knownTemplateIds: [] },\n };\n}\n\n/** An event id from itself, an /events/ URL (the id ends its vanity name), or a urn. */\nexport function eventIdOf(input: string): string | undefined {\n const s = input.trim();\n return (\n s.match(/^(\\d{15,20})$/)?.[1] ??\n s.match(/\\/events\\/[a-z0-9-]*?(\\d{15,20})/)?.[1] ??\n s.match(/(?:fsd_professionalEvent|event):(\\d{15,20})/)?.[1]\n );\n}\n\nconst eventLink = (id: string) => `https://www.linkedin.com/events/${id}/`;\n\n// ─── The hub ──────────────────────────────────────────────────────────────────\n\nexport interface HubEvent {\n id: string;\n name: string;\n /** As the card shows it, in the viewer's language. */\n when?: string;\n organizer?: string;\n attendees?: number;\n /** A LinkedIn Live event in the Premium section. */\n premium: boolean;\n url: string;\n}\n\nconst CARD = /\"viewName\":\"event-(large|small)-card-container\"/;\nconst TIME = /\\d{1,2}:\\d{2}/;\nconst COUNT = /^(\\d[\\d,.\\s]*)\\s+\\S+$/;\n\nfunction texts(row: string): string[] {\n return [...row.matchAll(/\"children\":\\[\"((?:[^\"\\\\$]|\\\\.)(?:[^\"\\\\]|\\\\.)*)\"\\]/g)].map(\n (m) => JSON.parse(`\"${m[1]}\"`) as string,\n );\n}\n\n/** A card's rows: its own, and what it references, stopping at any other card. */\nfunction cardRows(rows: Rows, id: string): string[] {\n const seen = new Set([id]);\n const queue = [id];\n while (queue.length > 0 && seen.size < 40) {\n const row = rows.byId.get(queue.shift() as string) ?? '';\n for (const m of row.matchAll(/\"\\$L?([0-9a-f]+)(?::[^\"]*)?\"/g)) {\n const ref = m[1] as string;\n const next = rows.byId.get(ref);\n if (seen.has(ref) || next === undefined || CARD.test(next)) continue;\n seen.add(ref);\n queue.push(ref);\n }\n }\n return [...seen];\n}\n\nconst count = (t: string | undefined) =>\n t === undefined ? undefined : Number(t.match(COUNT)?.[1]?.replace(/[,.\\s]/g, ''));\n\nfunction cardToEvent(rows: Rows, id: string, premium: boolean): HubEvent | undefined {\n const all = cardRows(rows, id)\n .map((r) => rows.byId.get(r) ?? '')\n .join('\\n');\n const ids = [\n ...new Set([...all.matchAll(/\\/events\\/[a-z0-9-]*?(\\d{15,20})/g)].map((m) => m[1] as string)),\n ];\n if (ids.length !== 1) return undefined;\n const t = texts(all);\n const at = t.findIndex((x) => TIME.test(x));\n const n = t.findIndex((x, i) => i > at && COUNT.test(x));\n const name = n === -1 ? undefined : t[n + 1];\n if (at === -1 || name === undefined) return undefined;\n // Between the time and the count: the organiser, and separators like \"•\".\n const organizer = t.slice(at + 1, n).find((x) => /\\p{L}/u.test(x));\n const attendees = count(t[n]);\n return {\n id: ids[0] as string,\n name: name.trim(),\n when: t[at],\n ...(organizer !== undefined ? { organizer } : {}),\n ...(attendees !== undefined && Number.isFinite(attendees) ? { attendees } : {}),\n premium,\n url: eventLink(ids[0] as string),\n };\n}\n\nexport function parseEventsHub(\n stream: string,\n): { ok: true; events: HubEvent[]; used: Set<string> } | Failure {\n if (\n !stream.includes('event-large-card-container') &&\n !stream.includes('event-small-card-container')\n ) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the events page carried no event cards',\n hint: 're-capture the events hub',\n };\n }\n const rows = new Rows(stream);\n const events: HubEvent[] = [];\n const used = new Set<string>();\n let unread = 0;\n for (const m of stream.matchAll(new RegExp(CARD.source, 'g'))) {\n const id = rows.at(m.index ?? 0);\n if (id === undefined) continue;\n for (const r of cardRows(rows, id)) used.add(r);\n const e = cardToEvent(rows, id, m[1] === 'small');\n if (e === undefined) unread++;\n else if (!events.some((x) => x.id === e.id)) events.push(e);\n }\n if (events.length === 0)\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `${unread} event cards were shown but none could be read`,\n };\n return { ok: true, events, used };\n}\n\n// ─── One event ────────────────────────────────────────────────────────────────\n\nexport function eventUrl(id: string): string {\n const c = CONTRACTS.professionalEvent;\n if (c?.queryId === undefined) throw new Error(\"the 'professionalEvent' contract is missing\");\n const variables = encodeVariables({\n eventIdentifier: id,\n includeComments: false,\n includeCommentsFirstReply: false,\n });\n return `${c.path}?variables=${variables}&queryId=${c.queryId}`;\n}\n\nexport interface EventDetail {\n id: string;\n name: string;\n /** As LinkedIn shows it, in the viewer's time zone. */\n when?: string;\n start?: string;\n end?: string;\n timeZone?: string;\n /** FUTURE, ONGOING, PAST, as LinkedIn reports it. */\n state?: string;\n cancelled?: boolean;\n attendees?: number;\n organizer?: { name: string; kind: 'company' | 'person'; url?: string };\n online: boolean;\n /** City, region, country for an event in person. */\n place?: string;\n /** The event's own site or registration page. */\n site?: string;\n private?: boolean;\n premium?: boolean;\n /** The viewer's own response (ATTENDING, …); absent when they have given none. */\n you?: string;\n description?: string;\n url: string;\n}\n\ntype Node = Record<string, unknown>;\n/** A TextViewModel's string, at either nesting depth (`socialProof.text.text`). */\nconst txt = (v: unknown): string | undefined => {\n const t = (v as { text?: unknown } | null | undefined)?.text;\n if (t !== null && typeof t === 'object') return txt(t);\n return typeof t === 'string' && t.trim() !== '' ? t.trim() : undefined;\n};\n\nfunction organizerOf(e: Node, byUrn: Map<unknown, Node>): EventDetail['organizer'] {\n const o = (e.organizer ?? {}) as Node;\n const company = byUrn.get(o['*organizingCompanyUrn']);\n if (typeof company?.name === 'string') {\n const id = String(company.entityUrn).split(':').pop();\n return { name: company.name, kind: 'company', url: `https://www.linkedin.com/company/${id}/` };\n }\n const person = byUrn.get(o['*organizingProfileUrn'] ?? o.organizingProfileUrn);\n const name = [person?.firstName, person?.lastName].filter((x) => typeof x === 'string').join(' ');\n if (name !== '') {\n const vanity = person?.publicIdentifier;\n return {\n name,\n kind: 'person',\n ...(typeof vanity === 'string' ? { url: `https://www.linkedin.com/in/${vanity}/` } : {}),\n };\n }\n return undefined;\n}\n\nexport function parseEvent(json: unknown): { ok: true; event: EventDetail } | Failure {\n const included = (json as { included?: Node[] } | null)?.included ?? [];\n const e = included.find((n) => String(n.$type).endsWith('.ProfessionalEvent'));\n const id = e === undefined ? undefined : eventIdOf(String(e.entityUrn));\n if (e === undefined || id === undefined || typeof e.name !== 'string') {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the event response carried no event',\n hint: 're-capture the event page',\n };\n }\n const byUrn = new Map<unknown, Node>(included.map((n) => [n.entityUrn, n]));\n const range = (e.timeRange ?? {}) as { start?: unknown; end?: unknown };\n const address = (e.address ?? null) as Node | null;\n const place =\n address === null\n ? undefined\n : [address.city, address.geographicArea, address.country]\n .filter((x) => typeof x === 'string' && x !== '')\n .join(', ');\n const status = byUrn.get(e['*viewerStatus'])?.scheduledContentViewerStatus;\n const attendees = Number(\n txt(e.socialProof)\n ?.match(/^(\\d[\\d,.\\s]*)/)?.[1]\n ?.replace(/[,.\\s]/g, ''),\n );\n const out: EventDetail = {\n id,\n name: e.name,\n online: typeof e.broadcastTool === 'string' || (address === null && e.venueDetails === null),\n url: eventLink(id),\n };\n const set = <K extends keyof EventDetail>(k: K, v: EventDetail[K] | undefined) => {\n if (v !== undefined && v !== '') out[k] = v;\n };\n set(\n 'when',\n typeof e.displayEventTime === 'string' ? e.displayEventTime.replace(/\\n/g, ' – ') : undefined,\n );\n set('start', typeof range.start === 'number' ? new Date(range.start).toISOString() : undefined);\n set('end', typeof range.end === 'number' ? new Date(range.end).toISOString() : undefined);\n set('timeZone', typeof e.timeZone === 'string' ? e.timeZone : undefined);\n set('state', typeof e.lifecycleState === 'string' ? e.lifecycleState : undefined);\n if (e.cancelled === true) out.cancelled = true;\n set('attendees', Number.isFinite(attendees) ? attendees : undefined);\n set('organizer', organizerOf(e, byUrn));\n set('place', place);\n set('site', typeof e.externalUrl === 'string' ? e.externalUrl : undefined);\n if (e.privateEvent === true) out.private = true;\n if (e.premiumEvent === true) out.premium = true;\n // NOT_INTERESTED is LinkedIn's default for no response at all, not a \"no\".\n set('you', typeof status === 'string' && status !== 'NOT_INTERESTED' ? status : undefined);\n set('description', txt(e.description));\n return { ok: true, event: out };\n}\n","// ─── `lnrelay events` and `lnrelay event` ─────────────────────────────────────\n//\n// The events page's own lists, and one event in full; see engine/events.ts.\n// Searching events by keyword is `search events`. Everything spends the page\n// budget: the hub is one call, each event one call.\n\nimport {\n EVENTS_HUB_URL,\n type EventDetail,\n eventIdOf,\n eventsHubBody,\n eventUrl,\n type HubEvent,\n parseEvent,\n parseEventsHub,\n} from '../engine/events.ts';\nimport { createLiveClient } from '../engine/index.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; raw: string; json?: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted call: a POST when a body is given, a GET otherwise. Injectable for tests. */\nexport type EventsFetch = (url: string, body: unknown, spendClass: 'page') => Promise<Fetched>;\n\nfunction liveFetch(command: string, quiet: boolean): EventsFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err(command, 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, body, spendClass) => {\n const r = await client.request({\n url,\n ...(body !== undefined ? { method: 'POST' as const, body } : {}),\n spendClass,\n operation: command,\n });\n if (!r.ok) return r;\n return { ok: true, raw: (r.classification as { raw?: string }).raw ?? '', json: r.json };\n };\n}\n\nexport interface EventsRequest {\n limit: number;\n /** Only the Premium (LinkedIn Live) events. */\n premium?: boolean;\n}\n\nfunction compactEvent(e: HubEvent): string {\n return line([\n e.id,\n e.name,\n e.when,\n e.organizer,\n e.attendees !== undefined ? `${e.attendees} attendees` : undefined,\n e.premium ? 'Premium' : undefined,\n e.url,\n ]);\n}\n\nexport async function runEvents(\n req: EventsRequest,\n opts: OutputOpts = {},\n fetch?: EventsFetch,\n): Promise<Envelope> {\n const get = fetch ?? liveFetch('events', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const res = await get(EVENTS_HUB_URL, eventsHubBody(), 'page');\n const hub = res.ok ? parseEventsHub(res.raw) : res;\n if (!hub.ok) return err('events', hub.code, hub.message, hub.hint);\n const picked = hub.events.filter((e) => req.premium !== true || e.premium);\n const items = picked.slice(0, Math.max(1, req.limit));\n return ok('events', {\n items: shape(items, opts, compactEvent),\n meta: {\n // The hub is one page LinkedIn chose; it has no \"more\".\n state: 'complete',\n operation: 'events',\n returnedCount: items.length,\n shownCount: hub.events.length,\n },\n });\n}\n\nfunction compactDetail(e: EventDetail): string {\n return line([\n e.id,\n e.name,\n e.when,\n e.online ? 'online' : e.place,\n e.organizer?.name,\n e.attendees !== undefined ? `${e.attendees} attendees` : undefined,\n e.state,\n e.site ?? e.url,\n ]);\n}\n\nexport async function runEvent(\n inputs: string[],\n opts: OutputOpts = {},\n fetch?: EventsFetch,\n): Promise<Envelope> {\n const ids = inputs.map(eventIdOf);\n if (ids.length === 0 || ids.some((id) => id === undefined)) {\n const bad = inputs.filter((i) => eventIdOf(i) === undefined);\n return err(\n 'event',\n 'INVALID_INPUT',\n bad.length > 0\n ? `not an event id or URL: ${bad.join(', ')}`\n : 'an event id or URL is required',\n 'lnrelay event <id|url> [<id|url> ...]',\n );\n }\n const get = fetch ?? liveFetch('event', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const events: EventDetail[] = [];\n for (const id of [...new Set(ids as string[])]) {\n const res = await get(eventUrl(id), undefined, 'page');\n const parsed = res.ok ? parseEvent(res.json) : res;\n if (!parsed.ok) {\n if (events.length === 0) return err('event', parsed.code, parsed.message, parsed.hint);\n return ok('event', {\n items: shape(events, opts, compactDetail),\n meta: {\n state: 'partial',\n operation: 'event',\n returnedCount: events.length,\n stoppedBy: parsed.code,\n },\n });\n }\n events.push(parsed.event);\n }\n if (events.length === 1 && opts.compact !== true && opts.fields === undefined)\n return ok('event', events[0]);\n return ok('event', {\n items: shape(events, opts, compactDetail),\n meta: { state: 'complete', operation: 'event', returnedCount: events.length },\n });\n}\n","// ─── What Premium adds to jobs ────────────────────────────────────────────────\n//\n// Captured 2026-11-22 on a Premium account. Both are Voyager GraphQL, plain\n// JSON, and both are read by the classic job pages:\n//\n// collection voyagerJobsDashJobCards, by `jobCollectionSlug`. The\n// /jobs/collections/<slug>/ pages. `top-applicant` (jobs where\n// you would be a top applicant) is Premium's; it answered 83\n// jobs, all of them in one call of 100. The cards are job\n// search's, under `jobCard` instead of `jobCardUnion`.\n// `recommended` answered none, as it does in the browser; a\n// slug LinkedIn does not know answers a GraphQL error.\n// insights voyagerJobsDashJobPostingDetailSections, the detail pane's\n// cards by type. JOB_APPLICANT_INSIGHTS: how many applied, in\n// the last day, their seniority and education.\n// COMPANY_INSIGHTS_CARD: headcount by month over two years, for\n// the company and for the job's function, median tenure,\n// competitors, and LinkedIn's generated text on its hiring,\n// priorities and landscape. Both ride one call.\n//\n// The REST job search takes a `jobCollectionSlug` too and ignores it: it\n// answered 241 jobs where the collection holds 83. Not used.\n\nimport { CONTRACTS } from './contracts.ts';\nimport { type JobPage, parseJobCards } from './jobs.ts';\nimport type { Failure } from './sdui-form.ts';\n\nfunction graphql(name: 'jobCollection' | 'jobDetailSections') {\n const c = CONTRACTS[name];\n if (c?.queryId === undefined) throw new Error(`job contract '${name}' is missing`);\n return { path: c.path, queryId: c.queryId };\n}\n\n/** Jobs per collection call: the server serves 100 (2026-11-22). */\nexport const COLLECTION_PAGE = 100;\n\n/** The collections a command takes, by LinkedIn's slug. */\nexport const COLLECTIONS = { 'top-applicant': 'top-applicant' } as const;\nexport type Collection = keyof typeof COLLECTIONS;\n\nexport function jobCollectionUrl(slug: Collection, start: number, count: number): string {\n const c = graphql('jobCollection');\n const variables = `(count:${count},jobCollectionSlug:${slug},query:(origin:GENERIC_JOB_COLLECTIONS_LANDING),start:${start})`;\n return `${c.path}?variables=${variables}&queryId=${c.queryId}`;\n}\n\nexport function jobInsightsUrl(id: string): string {\n const c = graphql('jobDetailSections');\n const urn = encodeURIComponent(`urn:li:fsd_jobPosting:${id}`);\n const variables = `(cardSectionTypes:List(JOB_APPLICANT_INSIGHTS,COMPANY_INSIGHTS_CARD),jobPostingUrn:${urn},includeSecondaryActionsV2:true)`;\n return `${c.path}?includeWebMetadata=true&variables=${variables}&queryId=${c.queryId}`;\n}\n\ntype Node = Record<string, unknown>;\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst text = (v: unknown): string | undefined => {\n const t = (v as { text?: unknown } | null | undefined)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim() : undefined;\n};\nconst nodes = (v: unknown): Node[] => (Array.isArray(v) ? (v as Node[]) : []);\nfunction defined<T extends Record<string, unknown>>(obj: T): T {\n for (const k of Object.keys(obj)) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\n// ─── Collection ───────────────────────────────────────────────────────────────\n\nexport function parseJobCollection(json: unknown): JobPage | Failure {\n const root = json as { data?: { data?: Node; errors?: unknown[] }; included?: Node[] } | null;\n const collection = root?.data?.data?.jobsDashJobCardsByJobCollections;\n if (collection === undefined || collection === null) {\n const why = nodes(root?.data?.errors)[0]?.message;\n return drift(`the job collection was not served${typeof why === 'string' ? `: ${why}` : ''}`);\n }\n return parseJobCards({ data: collection, included: root?.included ?? [] });\n}\n\n// ─── Insights ─────────────────────────────────────────────────────────────────\n\nexport interface ApplicantInsights {\n /** Who clicked apply. */\n total: number;\n lastDay?: number;\n seniority?: { level: string; share: number; count?: number }[];\n education?: { degree: string; share: number }[];\n /** Where you rank among them, when LinkedIn says. */\n rankPercentile?: number;\n /** Passed through as LinkedIn sends them: seen empty so far. */\n skills?: unknown[];\n locations?: unknown[];\n}\n\nexport interface Headcount {\n /** The latest month, YYYY-MM. */\n asOf: string;\n now: number;\n sixMonthsAgo?: number;\n yearAgo?: number;\n twoYearsAgo?: number;\n /** Change over the year, in percent. */\n growth1y?: number;\n}\n\nexport interface CompanyInsights {\n name?: string;\n url?: string;\n headcount?: Headcount;\n /** The job's own function at the company: its name and headcount. */\n function?: { name: string } & Partial<Headcount>;\n medianTenure?: string;\n competitors?: { name: string; industry?: string; url?: string }[];\n /** LinkedIn's generated text: hiring and headcount by function. */\n hiring?: string;\n /** LinkedIn's generated text: the company's strategic priorities. */\n priorities?: string;\n /** LinkedIn's generated text: its competitive landscape. */\n landscape?: string;\n}\n\nexport interface JobInsights {\n ok: true;\n applicants?: ApplicantInsights;\n company?: CompanyInsights;\n /** Company insight sections we do not read, by name. */\n unknownSections: Record<string, number>;\n}\n\nfunction byUrn(included: Node[]): Map<string, Node> {\n const map = new Map<string, Node>();\n for (const n of included) if (typeof n.entityUrn === 'string') map.set(n.entityUrn, n);\n return map;\n}\n\nconst nameOf = (urns: Map<string, Node>, urn: unknown) => {\n const n = typeof urn === 'string' ? urns.get(urn)?.name : undefined;\n return typeof n === 'string' ? n : undefined;\n};\n\nfunction applicantsOf(a: Node, urns: Map<string, Node>): ApplicantInsights {\n const seniority = nodes(a.seniorityDetails).flatMap((s) => {\n const level = nameOf(urns, s['*seniority']);\n return level === undefined || typeof s.percentage !== 'number'\n ? []\n : [defined({ level, share: s.percentage, count: s.count as number | undefined })];\n });\n const education = nodes(a.degreeDetails).flatMap((d) => {\n const degree = nameOf(urns, d['*degree']);\n return degree === undefined || typeof d.percentage !== 'number'\n ? []\n : [{ degree, share: d.percentage }];\n });\n const skills = nodes(a.skillDetails);\n const locations = nodes(a.locationDetails);\n return defined({\n total: a.applicantCount as number,\n lastDay: typeof a.applicantsInPastDay === 'number' ? a.applicantsInPastDay : undefined,\n seniority: seniority.length > 0 ? seniority : undefined,\n education: education.length > 0 ? education : undefined,\n rankPercentile:\n typeof a.applicantRankPercentile === 'number' ? a.applicantRankPercentile : undefined,\n skills: skills.length > 0 ? skills : undefined,\n locations: locations.length > 0 ? locations : undefined,\n });\n}\n\n/** Newest month first, as LinkedIn lists it: now, 6 and 12 and 24 months back. */\nfunction headcountOf(growth: unknown): Headcount | undefined {\n const months = nodes((growth as Node | null | undefined)?.headcountGrowth).flatMap((m) => {\n const on = m.startedOn as { year?: number; month?: number } | undefined;\n return typeof m.employeeCount === 'number' && on?.year !== undefined && on.month !== undefined\n ? [{ month: `${on.year}-${String(on.month).padStart(2, '0')}`, count: m.employeeCount }]\n : [];\n });\n const latest = months[0];\n if (latest === undefined) return undefined;\n const back = (n: number) => months[n]?.count;\n const yearAgo = back(12);\n return defined({\n asOf: latest.month,\n now: latest.count,\n sixMonthsAgo: back(6),\n yearAgo,\n twoYearsAgo: back(24),\n growth1y:\n yearAgo !== undefined && yearAgo > 0\n ? Math.round(((latest.count - yearAgo) / yearAgo) * 1000) / 10\n : undefined,\n });\n}\n\nconst str = (v: unknown) => (typeof v === 'string' ? v : undefined);\n\nfunction trendOf(s: Node, urns: Map<string, Node>): CompanyInsights {\n const company = urns.get(String(s['*company']));\n const fn = str(s.formattedJobFunction);\n return defined({\n name: str(company?.name),\n url: str(company?.url),\n headcount: headcountOf(s.employeeGrowth),\n function:\n fn !== undefined ? { name: fn, ...headcountOf(s.employeeGrowthForFunction) } : undefined,\n medianTenure: text((s.employeeGrowth as Node | undefined)?.medianTenureYears),\n });\n}\n\nfunction landscapeOf(s: Node): CompanyInsights {\n const competitors = nodes(s.competitors).flatMap((c) => {\n const name = text(c.title);\n return name === undefined\n ? []\n : [defined({ name, industry: text(c.subtitle), url: str(c.navigationUrl) })];\n });\n return defined({\n landscape: text(s.aiqInsightsText),\n competitors: competitors.length > 0 ? competitors : undefined,\n });\n}\n\n/** Each section we read, into the company's insights. Any other is counted, never dropped silently. */\nconst SECTIONS: Record<string, (s: Node, urns: Map<string, Node>) => CompanyInsights> = {\n jobPostingCompanyInsights: trendOf,\n headcountAIQInsights: (s) => defined({ hiring: text(s.aiqInsightsText) }),\n strategicPrioritiesAIQInsights: (s) => defined({ priorities: text(s.insightsText) }),\n competitiveLandscapeAIQInsights: landscapeOf,\n};\n\nfunction companyOf(card: Node, urns: Map<string, Node>, unknown: Record<string, number>) {\n const out: CompanyInsights = {};\n for (const el of nodes(card.elements)) {\n for (const [kind, section] of Object.entries((el.companyInsights ?? {}) as Node)) {\n if (section === null || kind.startsWith('$')) continue;\n const read = SECTIONS[kind];\n if (read === undefined) unknown[kind] = (unknown[kind] ?? 0) + 1;\n else Object.assign(out, read(section as Node, urns));\n }\n }\n return out;\n}\n\nexport function parseJobInsights(json: unknown): JobInsights | Failure {\n const root = json as { data?: { data?: Node }; included?: Node[] } | null;\n const sections = root?.data?.data?.jobsDashJobPostingDetailSectionsByCardSectionTypes as\n | Node\n | undefined;\n if (sections === undefined || sections === null || !Array.isArray(sections.elements))\n return drift('the job detail sections were not in the answer');\n const urns = byUrn(root?.included ?? []);\n const unknownSections: Record<string, number> = {};\n let applicants: ApplicantInsights | undefined;\n let company: CompanyInsights | undefined;\n for (const el of nodes(sections.elements)) {\n for (const part of nodes(el.jobPostingDetailSection)) {\n const a = urns.get(String(part['*jobApplicantInsightsUrn']));\n if (a !== undefined && typeof a.applicantCount === 'number')\n applicants = applicantsOf(a, urns);\n const posting = urns.get(String(part['*companyInsightsCard']));\n const card = posting?.companyInsightsCard as Node | undefined;\n if (card !== undefined && card !== null) company = companyOf(card, urns, unknownSections);\n }\n }\n return {\n ok: true,\n ...(applicants !== undefined ? { applicants } : {}),\n ...(company !== undefined && Object.keys(company).length > 0 ? { company } : {}),\n unknownSections,\n };\n}\n","// ─── `lnrelay jobs`, `lnrelay job`, `lnrelay job-filters` ─────────────────────\n//\n// See engine/jobs.ts. A search call returns up to 100 jobs and spends the\n// job-search budget; a read returns up to 100 jobs in full (a batch get) and\n// spends the job-read budget. `--details` is opt-in because full descriptions\n// are large: search wide with cards, then read the finalists. `job --team`\n// adds each job's hiring team, one page call per job.\n//\n// Premium (engine/job-premium.ts): `jobs --top-applicant` lists the jobs\n// where LinkedIn says you would be a top applicant, and `job --insights` adds\n// who applied and the company's insights, one more job read per job.\n\nimport { createLiveClient } from '../engine/index.ts';\nimport {\n COLLECTION_PAGE,\n type Collection,\n type JobInsights,\n jobCollectionUrl,\n jobInsightsUrl,\n parseJobCollection,\n parseJobInsights,\n} from '../engine/job-premium.ts';\nimport {\n BATCH_SIZE,\n HIRING_TEAM_URL,\n type HiringMember,\n hiringTeamBody,\n type JobCard,\n type JobDetail,\n type JobFilterOptions,\n type JobQuery,\n jobBatchUrl,\n jobDetailUrl,\n jobFilterSelection,\n jobFiltersUrl,\n jobIdOf,\n jobSearchUrl,\n PAGE_SIZE,\n parseHiringTeam,\n parseJobBatch,\n parseJobCards,\n parseJobDetail,\n parseJobFilters,\n} from '../engine/jobs.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { project } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport {\n keywordSets,\n line,\n type Matched,\n metaOf,\n type PageFetch,\n type Paging,\n searchAll,\n} from './paged.ts';\n\ntype Fetched =\n | { ok: true; json?: unknown; raw?: string }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted call: a POST when a body is given. Injectable so tests send nothing. */\nexport type JobsFetch = (\n url: string,\n spendClass: 'jobSearch' | 'jobRead' | 'page',\n body?: unknown,\n) => Promise<Fetched>;\n\nfunction liveFetch(command: string, quiet: boolean): JobsFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err(command, 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, spendClass, body) => {\n const r = await client.request({\n url,\n ...(body !== undefined ? { method: 'POST' as const, body } : {}),\n spendClass,\n operation: command,\n });\n if (!r.ok) return r;\n return { ok: true, json: r.json, raw: (r.classification as { raw?: string }).raw ?? '' };\n };\n}\n\nexport interface JobsRequest {\n /** One keyword set, or several: each its own search, merged by job id. */\n keywords?: string | string[];\n location?: string;\n geoId?: string;\n limit: number;\n start?: number;\n /** Read each job too: apply link, applicants, employment type. */\n details?: boolean;\n /** With `details`, keep each job's full description. */\n description?: boolean;\n filter?: JobFilterOptions;\n /** A Premium collection instead of a search: it takes no keywords or filters. */\n collection?: Collection;\n}\n\n/** LinkedIn serves no further than 1000 into any one job search. */\nconst PAGING: Paging = { pageSize: PAGE_SIZE, max: 1000 };\n\ninterface Teamed {\n hiringTeam?: HiringMember[];\n /** Why the team could not be read; the job itself was. */\n hiringTeamError?: string;\n /** Premium (`--insights`): who applied, and the company's insights. */\n premium?: Omit<JobInsights, 'ok' | 'unknownSections'> & {\n unknownSections?: Record<string, number>;\n };\n premiumError?: string;\n}\n\ntype Row = Matched<JobCard & Partial<Omit<JobDetail, keyof JobCard>>> & Teamed;\n\nconst teamLine = (team: HiringMember[] | undefined) =>\n team === undefined || team.length === 0\n ? undefined\n : `team: ${team\n .map((m) =>\n [m.name, m.role !== undefined ? `(${m.role})` : undefined, m.url]\n .filter(Boolean)\n .join(' '),\n )\n .join('; ')}`;\n\nfunction compactJob(j: Row): string {\n return line([\n j.id,\n j.title,\n j.company,\n j.location,\n j.workplace,\n j.listed,\n j.easyApply ? 'easy apply' : undefined,\n j.promoted ? 'promoted' : undefined,\n j.salary,\n j.apply?.url !== undefined ? `apply: ${j.apply.url}` : undefined,\n j.matched !== undefined ? `matched: ${j.matched.join(' + ')}` : undefined,\n teamLine(j.hiringTeam),\n ]);\n}\n\nfunction shape<T extends object>(rows: T[], opts: OutputOpts, line: (r: T) => string) {\n if (opts.compact === true) return rows.map(line);\n if (opts.fields !== undefined && opts.fields !== '')\n return project(rows as unknown as Record<string, unknown>[], opts.fields);\n return rows;\n}\n\ntype Query = Omit<JobQuery, 'start' | 'count'>;\n\nfunction queryOf(\n req: Omit<JobsRequest, 'limit' | 'keywords'>,\n filters: Record<string, string[]>,\n keywords?: string,\n): Query {\n return {\n ...(keywords ? { keywords } : {}),\n ...(req.location ? { location: req.location } : {}),\n ...(req.geoId ? { geoId: req.geoId } : {}),\n filters,\n };\n}\n\n/** Reads `ids` in batches. Stops at the first failed batch, keeping the rest. */\nasync function readJobs(\n get: JobsFetch,\n ids: string[],\n): Promise<{ jobs: Map<string, JobDetail>; stoppedBy?: string }> {\n const jobs = new Map<string, JobDetail>();\n for (let at = 0; at < ids.length; at += BATCH_SIZE) {\n const res = await get(jobBatchUrl(ids.slice(at, at + BATCH_SIZE)), 'jobRead');\n const batch = res.ok ? parseJobBatch(res.json) : res;\n if (!batch.ok) return { jobs, stoppedBy: batch.code };\n for (const job of batch.jobs) if (ids.includes(job.id)) jobs.set(job.id, job);\n }\n return { jobs };\n}\n\n/** Reads every row in full and merges it in. Returns how many stayed unread. */\nasync function addDetails(\n get: JobsFetch,\n rows: Row[],\n withDescription: boolean,\n): Promise<{ unread: number; stoppedBy?: string }> {\n const read = await readJobs(\n get,\n rows.map((r) => r.id),\n );\n for (const row of rows) {\n const detail = read.jobs.get(row.id);\n if (detail === undefined) continue;\n const { description, id: _id, url: _url, ...rest } = detail;\n Object.assign(row, rest, withDescription ? { description } : {});\n }\n const unread = rows.filter((r) => !read.jobs.has(r.id)).length;\n return read.stoppedBy === undefined ? { unread } : { unread, stoppedBy: read.stoppedBy };\n}\n\nexport async function runJobs(\n req: JobsRequest,\n opts: OutputOpts = {},\n fetch?: JobsFetch,\n): Promise<Envelope> {\n if (req.collection !== undefined) return runCollection(req, req.collection, opts, fetch);\n const sets = keywordSets(req.keywords);\n const hasQuery =\n sets.length > 0 || [req.location, req.geoId].some((v) => v !== undefined && v !== '');\n if (!hasQuery) {\n return err(\n 'jobs',\n 'INVALID_INPUT',\n 'give keywords, a location, or both',\n 'lnrelay jobs \"<keywords>\" [\"<more keywords>\" ...] [--location \"<place>\" | --geo <id>] [filters]',\n );\n }\n const selection = jobFilterSelection(req.filter ?? {});\n if (!selection.ok)\n return err('jobs', selection.code, selection.message, 'see `lnrelay help jobs`');\n const get = fetch ?? liveFetch('jobs', opts.quiet === true);\n if (typeof get !== 'function') return get;\n\n const first = Math.max(0, req.start ?? 0);\n const want = Math.max(1, Math.min(req.limit, PAGING.max - first));\n const base = queryOf(req, selection.filters);\n const fetchPage: PageFetch<JobCard> = async (keywords, start) => {\n const url = jobSearchUrl({\n ...base,\n ...(keywords ? { keywords } : {}),\n start,\n count: PAGE_SIZE,\n });\n const res = await get(url, 'jobSearch');\n const page = res.ok ? parseJobCards(res.json) : res;\n if (!page.ok) return page;\n return {\n ok: true,\n items: page.jobs,\n ...(page.total !== undefined ? { total: page.total } : {}),\n ...(page.location !== undefined ? { resolved: page.location } : {}),\n unknownTypes: page.unknownTypes,\n };\n };\n const merged = await searchAll(\n fetchPage,\n sets.length > 0 ? sets : [undefined],\n first,\n want,\n PAGING,\n );\n if (merged.rows.length === 0 && merged.failure !== undefined) {\n const f = merged.failure;\n return err('jobs', f.code, f.message, f.hint);\n }\n\n let unread = 0;\n let readStop: string | undefined;\n if (req.details === true) {\n const added = await addDetails(get, merged.rows, req.description === true);\n unread = added.unread;\n readStop = added.stoppedBy;\n }\n\n const single = sets.length <= 1;\n const meta = metaOf('jobs', merged, single, first, {\n unread,\n ...(readStop !== undefined ? { readStop } : {}),\n });\n\n return ok('jobs', {\n query: { ...base, ...(sets.length > 0 ? { keywords: single ? sets[0] : sets } : {}) },\n ...(merged.resolved !== undefined ? { location: merged.resolved } : {}),\n items: shape(merged.rows as Row[], opts, compactJob),\n meta,\n });\n}\n\n/** A Premium collection, 100 a call, the cards job search returns. */\nasync function runCollection(\n req: JobsRequest,\n collection: Collection,\n opts: OutputOpts,\n fetch?: JobsFetch,\n): Promise<Envelope> {\n const searched = keywordSets(req.keywords).length > 0 || req.location || req.geoId;\n const selection = jobFilterSelection(req.filter ?? {});\n const filtered = !selection.ok || Object.keys(selection.filters).length > 0;\n if (searched || filtered)\n return err(\n 'jobs',\n 'INVALID_INPUT',\n `--${collection} is LinkedIn's own list: it takes no keywords, location or filters`,\n );\n const get = fetch ?? liveFetch('jobs', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const first = Math.max(0, req.start ?? 0);\n const want = Math.max(1, Math.min(req.limit, PAGING.max - first));\n const fetchPage: PageFetch<JobCard> = async (_keywords, start) => {\n const res = await get(jobCollectionUrl(collection, start, COLLECTION_PAGE), 'jobSearch');\n const page = res.ok ? parseJobCollection(res.json) : res;\n if (!page.ok) return page;\n return {\n ok: true,\n items: page.jobs,\n ...(page.total !== undefined ? { total: page.total } : {}),\n unknownTypes: page.unknownTypes,\n };\n };\n const merged = await searchAll(fetchPage, [undefined], first, want, PAGING);\n if (merged.rows.length === 0 && merged.failure !== undefined) {\n const f = merged.failure;\n return err('jobs', f.code, f.message, f.hint);\n }\n let extra = {};\n if (req.details === true) {\n const added = await addDetails(get, merged.rows, req.description === true);\n extra = {\n unread: added.unread,\n ...(added.stoppedBy !== undefined ? { readStop: added.stoppedBy } : {}),\n };\n }\n return ok('jobs', {\n collection,\n items: shape(merged.rows as Row[], opts, compactJob),\n meta: metaOf('jobs', merged, true, first, { unread: 0, ...extra }),\n });\n}\n\n/** Each job's Premium insights, one job read each; a failed one says why. */\nasync function addInsights(get: JobsFetch, jobs: (JobDetail & Teamed)[]): Promise<void> {\n for (const job of jobs) {\n const res = await get(jobInsightsUrl(job.id), 'jobRead');\n const read = res.ok ? parseJobInsights(res.json) : res;\n if (!read.ok) {\n job.premiumError = `${read.code}: ${read.message}`;\n continue;\n }\n const { ok: _ok, unknownSections, ...insights } = read;\n job.premium = {\n ...insights,\n ...(Object.keys(unknownSections).length > 0 ? { unknownSections } : {}),\n };\n }\n}\n\n/** Each job's hiring team, one call each, onto the job; a failed one says why. */\nasync function addTeams(get: JobsFetch, jobs: (JobDetail & Teamed)[]): Promise<void> {\n for (const job of jobs) {\n const res = await get(HIRING_TEAM_URL, 'page', hiringTeamBody(job.id));\n const team = res.ok ? parseHiringTeam(res.raw ?? '') : res;\n if (team.ok) job.hiringTeam = team.members;\n else job.hiringTeamError = `${team.code}: ${team.message}`;\n }\n}\n\n/** One job by its own endpoint; several in batches of 100, one call each. */\nexport async function runJob(\n input: string | string[] | undefined,\n opts: OutputOpts = {},\n fetch?: JobsFetch,\n req: { team?: boolean; insights?: boolean } = {},\n): Promise<Envelope> {\n const given = input === undefined ? [] : Array.isArray(input) ? input : [input];\n const ids = [...new Set(given.map(jobIdOf))];\n if (ids.length === 0 || ids.some((id) => id === undefined)) {\n const bad = given.filter((g) => jobIdOf(g) === undefined);\n return err(\n 'job',\n 'INVALID_INPUT',\n bad.length > 0 ? `not a job id or URL: ${bad.join(', ')}` : 'a job id or job URL is required',\n 'lnrelay job <id|url> [<id|url> ...]',\n );\n }\n const get = fetch ?? liveFetch('job', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const wanted = ids as string[];\n\n if (wanted.length === 1) {\n const res = await get(jobDetailUrl(wanted[0] as string), 'jobRead');\n if (!res.ok) return err('job', res.code, res.message, res.hint);\n const detail = parseJobDetail(res.json);\n if (!detail.ok) return err('job', detail.code, detail.message, detail.hint);\n const job: JobDetail & Teamed = detail.job;\n if (req.team === true) await addTeams(get, [job]);\n if (req.insights === true) await addInsights(get, [job]);\n return ok('job', job);\n }\n\n const read = await readJobs(get, wanted);\n if (read.jobs.size === 0 && read.stoppedBy !== undefined)\n return err('job', read.stoppedBy, 'no job could be read');\n const unread = wanted.filter((id) => !read.jobs.has(id));\n const jobs: (JobDetail & Teamed)[] = wanted.flatMap((id) => read.jobs.get(id) ?? []);\n if (req.team === true) await addTeams(get, jobs);\n if (req.insights === true) await addInsights(get, jobs);\n return ok('job', {\n items: shape(jobs, opts, (j) =>\n compactJob({ ...j, easyApply: j.apply?.type === 'easy-apply', promoted: false }),\n ),\n meta: {\n state: unread.length === 0 ? 'complete' : 'partial',\n operation: 'job',\n returnedCount: jobs.length,\n ...(unread.length > 0 ? { unread } : {}),\n ...(read.stoppedBy !== undefined ? { stoppedBy: read.stoppedBy } : {}),\n },\n });\n}\n\nexport async function runJobFilters(\n req: Omit<JobsRequest, 'limit'>,\n opts: OutputOpts = {},\n fetch?: JobsFetch,\n): Promise<Envelope> {\n const sets = keywordSets(req.keywords);\n if (sets.length > 1) {\n return err(\n 'job-filters',\n 'INVALID_INPUT',\n 'job-filters takes one keyword set: its counts belong to that one query',\n 'lnrelay job-filters \"<keywords>\" [filters]',\n );\n }\n const selection = jobFilterSelection(req.filter ?? {});\n if (!selection.ok) return err('job-filters', selection.code, selection.message);\n const get = fetch ?? liveFetch('job-filters', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const url = jobFiltersUrl({\n ...queryOf(req, selection.filters, sets[0]),\n start: 0,\n count: PAGE_SIZE,\n });\n const res = await get(url, 'jobSearch');\n const parsed = res.ok ? parseJobFilters(res.json) : res;\n if (!parsed.ok) return err('job-filters', parsed.code, parsed.message, parsed.hint);\n return ok('job-filters', {\n items: shape(\n parsed.filters,\n opts,\n (f) =>\n `${f.key}: ${f.options.map((o) => `${o.value}=${o.label}${o.count !== undefined ? ` (${o.count})` : ''}`).join(', ')}`,\n ),\n meta: { state: 'complete', operation: 'job-filters', returnedCount: parsed.filters.length },\n });\n}\n","// ─── The scheduled-posts queue ────────────────────────────────────────────────\n//\n// Voyager cannot read a scheduled post: `normShares/<urn>` answers 400, and\n// `my-posts` lists only what has published. The web client's \"Scheduled (N)\"\n// list is SDUI — a pager over React Server Components — and that is the only\n// place the queue is visible. Captured 2026-10-13 with three probes scheduled\n// (two over normShares, one from the web composer), then with none.\n//\n// The stream is not JSON, so it is read by exclusion-tolerant scanning, and\n// held to the same rule as every parser here: never an empty success on\n// failure. The stream carries LinkedIn's own count (`ShareBoxscheduledPostCount`,\n// the N in the tab); without it an empty queue and a page we no longer\n// understand look the same, so its absence is SCHEMA_DRIFT.\n\nimport type { FetchState } from '../types.ts';\nimport type { Client } from './client.ts';\n\nexport const PAGER_ID = 'com.linkedin.sdui.pagers.sharing.scheduledPosts';\nconst PAGER_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/pagination?sduiid=${PAGER_ID}`;\nconst SCREEN_ID = 'com.linkedin.sdui.flagshipnav.sharing.ShareSchedulePostList';\n\n/** A page as the web client asks for it when the list is scrolled. */\nexport function scheduledPageBody(start: number, count: number) {\n const args = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload: { start, count, shareLifeCycleState: 'ShareLifeCycleState_SCHEDULED' },\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n return {\n pagerId: PAGER_ID,\n clientArguments: { ...args, states: [], screenId: SCREEN_ID, knownTemplateIds: [] },\n paginationRequest: {\n $type: 'proto.sdui.actions.requests.PaginationRequest',\n pagerId: PAGER_ID,\n retryCount: 0,\n requestedArguments: args,\n },\n };\n}\n\nexport interface ScheduledPost {\n /** The urn `delete` cancels it by, and `edit` edits it by. */\n urn: string;\n /** Epoch ms. */\n scheduledAt: number;\n /**\n * The text as the list renders it: whole, but with links shortened to\n * lnkd.in. Null when it could not be paired with its row for certain.\n */\n text: string | null;\n}\n\ntype Failure = { ok: false; code: string; message: string; hint?: string };\n\nconst COUNT =\n /\"id\":\"ShareBoxscheduledPostCount\"\\}\\}\\},\"value\":\\{\"\\$case\":\"intValue\",\"intValue\":(\\d+)\\}/;\nconst ROW = /\"feedUpdateUrn\":\"(urn:li:(?:share|ugcPost):\\d+)\",\"scheduledAtEpochMillis\":\"(\\d+)\"/g;\n// Each row's preview block holds the text as a single string child. A row\n// whose text is shaped differently simply does not match, and the pairing\n// check below then refuses to guess.\nconst TEXT =\n /\"viewName\":\"mini-update-container\"[\\s\\S]*?\"textProps\":\\{[^{}]*?\"children\":\\[\"((?:[^\"\\\\]|\\\\.)*)\"\\]/g;\n\nexport function parseScheduledPage(\n stream: string,\n): { ok: true; claimedCount: number; posts: ScheduledPost[] } | Failure {\n const count = stream.match(COUNT);\n if (count?.[1] === undefined) {\n return drift('the scheduled-posts page carried no post count');\n }\n const claimedCount = Number(count[1]);\n\n const posts: ScheduledPost[] = [];\n const seen = new Set<string>();\n for (const [, urn, at] of stream.matchAll(ROW)) {\n if (urn === undefined || seen.has(urn)) continue;\n seen.add(urn);\n posts.push({ urn, scheduledAt: Number(at), text: null });\n }\n if (claimedCount > 0 && posts.length === 0) {\n return drift(`LinkedIn counts ${claimedCount} scheduled posts but no row could be read`);\n }\n\n // Texts arrive in row order. Pair them only when there is exactly one per\n // row: a text on the wrong post is worse than none.\n const texts = [...stream.matchAll(TEXT)].map((m) => JSON.parse(`\"${m[1]}\"`) as string);\n if (texts.length === posts.length) {\n posts.forEach((p, i) => {\n p.text = texts[i] ?? null;\n });\n }\n return { ok: true, claimedCount, posts };\n}\n\nfunction drift(message: string): Failure {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message,\n hint: 'Re-capture the scheduled list (open \"Scheduled\" in the composer) with scripts/observe-write.ts.',\n };\n}\n\nconst PAGE_SIZE = 10;\n/** LinkedIn's own UI pages by 5; 10 pages of 10 is far past any real queue. */\nconst MAX_PAGES = 10;\n\n/**\n * The whole queue, paged until it holds as many posts as LinkedIn counts.\n * `state` is `complete` only when it does.\n */\nexport async function fetchScheduled(\n client: Client,\n pageSize = PAGE_SIZE,\n): Promise<\n { ok: true; posts: ScheduledPost[]; claimedCount: number; state: FetchState } | Failure\n> {\n const posts: ScheduledPost[] = [];\n const seen = new Set<string>();\n let claimedCount = 0;\n\n for (let page = 0; page < MAX_PAGES; page++) {\n const result = await client.request({\n url: PAGER_URL,\n method: 'POST',\n body: scheduledPageBody(posts.length, pageSize),\n spendClass: 'page',\n operation: 'scheduled',\n });\n if (!result.ok) {\n const out: Failure = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n // Not JSON; the client keeps the raw stream on the classification.\n const parsed = parseScheduledPage((result.classification as { raw?: string }).raw ?? '');\n if (!parsed.ok) return parsed;\n\n // The highest count seen: a later page that comes back emptier must not\n // shrink what LinkedIn said was there and turn a short read into `complete`.\n claimedCount = Math.max(claimedCount, parsed.claimedCount);\n const fresh = parsed.posts.filter((p) => !seen.has(p.urn));\n for (const p of fresh) {\n seen.add(p.urn);\n posts.push(p);\n }\n if (posts.length >= claimedCount || fresh.length === 0) break;\n }\n\n const state: FetchState = posts.length >= claimedCount ? 'complete' : 'partial';\n return { ok: true, posts, claimedCount, state };\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 createLiveClient,\n type EngineResult,\n} from '../engine/index.ts';\nimport { fetchScheduled, type ScheduledPost } from '../engine/sdui-scheduled.ts';\n\nimport {\n LAUNCH_HINT,\n loadSession,\n mintSessionFromBrowser,\n saveSession,\n} from '../engine/session.ts';\nimport { compactRows, project, type Shaped, shapeAll, shapeEntity } 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 = sessionFor(command);\n if ('ok' in loaded) return loaded;\n return { engine: createEngine(loaded.session, undefined, quiet) };\n}\n\nfunction sessionFor(\n command: string,\n): { session: Extract<ReturnType<typeof loadSession>, { state: 'ok' }>['session'] } | 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 { session: loaded.session };\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 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 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/** Your own posts waiting to publish. Not in `my-posts` until they do. */\nexport async function runScheduled(quiet = false): Promise<Envelope> {\n const ctx = sessionFor('scheduled');\n if ('ok' in ctx) return ctx;\n const result = await fetchScheduled(createLiveClient(ctx.session, undefined, quiet));\n if (!result.ok) return err('scheduled', result.code, result.message, result.hint);\n return ok('scheduled', scheduledData(result));\n}\n\nexport function scheduledData(result: {\n posts: ScheduledPost[];\n claimedCount: number;\n state: 'complete' | 'partial' | 'unknown';\n}) {\n return {\n items: result.posts.map((p) => ({\n urn: p.urn,\n scheduledAt: new Date(p.scheduledAt).toISOString(),\n text: p.text,\n })),\n meta: {\n state: result.state,\n returnedCount: result.posts.length,\n claimedCount: result.claimedCount,\n },\n };\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. */\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[] = [\n 'profile',\n 'search',\n 'page',\n 'jobSearch',\n 'jobRead',\n 'write',\n 'global',\n ];\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","// ─── `lnrelay inbox`, `messages`, `draft`, `drafts` ───────────────────────────\n//\n// Reading the owner's messages, and drafting replies on this machine. See\n// engine/messaging.ts. There is NO send: a draft is a local note with the\n// conversation's link, for the owner to open, review and send themselves.\n// Nothing read is stored; it is fetched live, on the page budget. The\n// mailbox id (the owner's own profile id) is kept in me.json after the first\n// lookup so every read does not cost a `whoami`.\n\nimport { randomUUID } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport { createEngine, createLiveClient } from '../engine/index.ts';\nimport {\n type Conversation,\n conversationIdOf,\n conversationsUrl,\n FOLDERS,\n type Folder,\n mailboxOf,\n messagesUrl,\n parseConversations,\n parseMessages,\n} from '../engine/messaging.ts';\nimport type { Failure } from '../engine/sdui-form.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; json: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted GET. Injectable so tests send nothing. Messaging never POSTs. */\nexport type MessagingFetch = (url: string, spendClass: 'page') => Promise<Fetched>;\n\n/** Messages a page holds; fewer means nothing older is held back. */\nconst MESSAGES_PAGE = 20;\n/** Folders deeper than this are refused rather than paged forever. */\nconst MAX_CONVERSATIONS = 500;\n\nfunction live(command: string, quiet: boolean) {\n const session = loadSession();\n if (session.state !== 'ok')\n return err(command, 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n const fetch: MessagingFetch = async (url, spendClass) => {\n const r = await client.request({ url, spendClass, operation: command });\n return r.ok ? { ok: true, json: r.json } : r;\n };\n return { fetch, session: session.session };\n}\n\n/** The owner's mailbox: me.json, or one `whoami` the first time. */\nasync function mailbox(command: string, quiet: boolean): Promise<string | Envelope> {\n const known = loadJson<{ profileUrn?: string }>(cachePath('me.json'));\n if (known.state === 'ok' && typeof known.value.profileUrn === 'string')\n return known.value.profileUrn;\n const session = loadSession();\n if (session.state !== 'ok')\n return err(command, 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const me = await createEngine(session.session, undefined, quiet).whoami();\n const urn = me.ok ? (me.value as { entityUrn?: unknown } | undefined)?.entityUrn : undefined;\n if (typeof urn !== 'string')\n return err(command, 'AUTH_FAILED', 'could not tell whose mailbox this is');\n const profileUrn = mailboxOf(urn);\n saveJson(cachePath('me.json'), { profileUrn });\n return profileUrn;\n}\n\nasync function setup(command: string, opts: OutputOpts, fetch?: MessagingFetch) {\n const box = await mailbox(command, opts.quiet === true);\n if (typeof box !== 'string') return box;\n if (fetch !== undefined) return { box, get: fetch };\n const l = live(command, opts.quiet === true);\n if ('ok' in l) return l;\n return { box, get: l.fetch };\n}\n\n// ─── inbox ────────────────────────────────────────────────────────────────────\n\nexport interface InboxRequest {\n folder?: Folder;\n limit: number;\n /** Only conversations with unread messages. */\n unread?: boolean;\n}\n\nfunction compactConversation(c: Conversation): string {\n const last =\n c.last === undefined\n ? undefined\n : `${c.last.from}: ${(c.last.text ?? '').replace(/\\s+/g, ' ')}`;\n return line([\n c.id,\n c.with.map((p) => p.name).join(', ') || c.title,\n c.unread > 0 ? `${c.unread} unread` : undefined,\n c.lastActivity?.slice(0, 10),\n c.inmail ? 'InMail' : undefined,\n last !== undefined && last.length > 140 ? `${last.slice(0, 137)}…` : last,\n ]);\n}\n\nexport async function runInbox(\n req: InboxRequest,\n opts: OutputOpts = {},\n fetch?: MessagingFetch,\n): Promise<Envelope> {\n const folder = req.folder ?? 'inbox';\n if (!(folder in FOLDERS)) {\n return err(\n 'inbox',\n 'INVALID_INPUT',\n `no folder '${folder}'`,\n `one of: ${Object.keys(FOLDERS).join(', ')}`,\n );\n }\n const ready = await setup('inbox', opts, fetch);\n if ('ok' in ready) return ready;\n const want = Math.max(1, Math.min(req.limit, MAX_CONVERSATIONS));\n\n const all: Conversation[] = [];\n let cursor: string | undefined;\n let stoppedBy: string | undefined;\n let exhausted = false;\n while (all.length < want) {\n const res = await ready.get(\n conversationsUrl({ mailbox: ready.box, folder, ...(cursor ? { cursor } : {}) }),\n 'page',\n );\n const page = res.ok ? parseConversations(res.json, ready.box) : res;\n if (!page.ok) {\n if (all.length === 0) return err('inbox', page.code, page.message, page.hint);\n stoppedBy = page.code;\n break;\n }\n const room = want - all.length;\n all.push(...page.conversations.slice(0, room));\n if (page.conversations.length > room) break;\n if (page.cursor === undefined || page.conversations.length === 0) {\n exhausted = true;\n break;\n }\n cursor = page.cursor;\n }\n const shown = req.unread === true ? all.filter((c) => c.unread > 0) : all;\n return ok('inbox', {\n folder,\n items: shape(shown, opts, compactConversation),\n meta: {\n state: exhausted && stoppedBy === undefined ? 'complete' : 'partial',\n operation: 'inbox',\n returnedCount: shown.length,\n unread: all.filter((c) => c.unread > 0).length,\n ...(stoppedBy !== undefined ? { stoppedBy } : {}),\n },\n });\n}\n\n// ─── messages ─────────────────────────────────────────────────────────────────\n\nexport async function runMessages(\n input: string | undefined,\n opts: OutputOpts = {},\n fetch?: MessagingFetch,\n): Promise<Envelope> {\n const ready = await setup('messages', opts, fetch);\n if ('ok' in ready) return ready;\n const id = input === undefined ? undefined : conversationIdOf(input, ready.box);\n if (id === undefined) {\n return err(\n 'messages',\n 'INVALID_INPUT',\n 'a conversation id or /messaging/thread/ URL is required',\n 'ids come from `lnrelay inbox`',\n );\n }\n const res = await ready.get(messagesUrl(id), 'page');\n const parsed = res.ok ? parseMessages(res.json, ready.box) : res;\n if (!parsed.ok) return err('messages', parsed.code, parsed.message, parsed.hint);\n return ok('messages', {\n conversation: id,\n url: threadUrl(id),\n items: shape(parsed.messages, opts, (m) =>\n line([\n m.at.slice(0, 16).replace('T', ' '),\n m.from,\n m.subject,\n (m.text ?? '').replace(/\\s+/g, ' '),\n ]),\n ),\n meta: {\n // A full page may have older messages behind it; this reads the latest page only.\n state: parsed.messages.length < MESSAGES_PAGE ? 'complete' : 'partial',\n operation: 'messages',\n returnedCount: parsed.messages.length,\n },\n });\n}\n\nconst threadUrl = (conversationUrn: string) => {\n const thread = conversationUrn.match(/,(2-[^)]+)\\)$/)?.[1];\n return thread === undefined ? undefined : `https://www.linkedin.com/messaging/thread/${thread}/`;\n};\n\n// ─── drafts ───────────────────────────────────────────────────────────────────\n\nexport interface Draft {\n id: string;\n conversation: string;\n url?: string;\n /** Who the conversation is with, as it read when the draft was made. */\n to: string[];\n text: string;\n createdAt: string;\n}\n\nconst DRAFTS = () => cachePath('drafts.json');\n\nfunction loadDrafts(): Draft[] | Failure {\n const loaded = loadJson<Draft[]>(DRAFTS());\n if (loaded.state === 'missing') return [];\n if (loaded.state === 'corrupt')\n return {\n ok: false,\n code: 'CACHE_CORRUPT',\n message: `drafts were unreadable; moved to ${loaded.quarantinedTo}`,\n };\n return Array.isArray(loaded.value) ? loaded.value : [];\n}\n\nexport async function runDraft(\n conversation: string | undefined,\n text: string | undefined,\n fetch?: MessagingFetch,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n const body = text?.trim() ?? '';\n if (body === '')\n return err(\n 'draft',\n 'INVALID_INPUT',\n 'a draft needs text',\n 'lnrelay draft <conversation> \"<text>\" | --file <path>',\n );\n const box = await mailbox('draft', opts.quiet === true);\n if (typeof box !== 'string') return box;\n const id = conversation === undefined ? undefined : conversationIdOf(conversation, box);\n if (id === undefined)\n return err(\n 'draft',\n 'INVALID_INPUT',\n 'a conversation id or /messaging/thread/ URL is required',\n 'ids come from `lnrelay inbox`',\n );\n const ready = await setup('draft', opts, fetch);\n if ('ok' in ready) return ready;\n\n // One read: the conversation exists, and who it is with.\n const res = await ready.get(messagesUrl(id), 'page');\n const parsed = res.ok ? parseMessages(res.json, ready.box) : res;\n if (!parsed.ok) return err('draft', parsed.code, parsed.message, parsed.hint);\n const to = [...new Set(parsed.messages.filter((m) => !m.fromMe).map((m) => m.from))];\n\n const drafts = loadDrafts();\n if (!Array.isArray(drafts)) return err('draft', drafts.code, drafts.message);\n const url = threadUrl(id);\n const draft: Draft = {\n id: randomUUID().slice(0, 8),\n conversation: id,\n ...(url !== undefined ? { url } : {}),\n to,\n text: body,\n createdAt: new Date().toISOString(),\n };\n saveJson(DRAFTS(), [...drafts, draft]);\n return ok('draft', {\n saved: true,\n sent: false,\n draft,\n notice:\n 'Saved on this machine only. Nothing was sent: open the link, review, and send it yourself.',\n });\n}\n\nexport function draftText(text: string | undefined, file: string | undefined): string | undefined {\n return file !== undefined ? readFileSync(file, 'utf-8') : text;\n}\n\nexport function runDrafts(opts: OutputOpts = {}): Envelope {\n const drafts = loadDrafts();\n if (!Array.isArray(drafts)) return err('drafts', drafts.code, drafts.message);\n return ok('drafts', {\n items: shape(drafts, opts, (d) =>\n line([d.id, d.to.join(', '), d.createdAt.slice(0, 10), d.text.replace(/\\s+/g, ' '), d.url]),\n ),\n meta: { state: 'complete', operation: 'drafts', returnedCount: drafts.length },\n });\n}\n\nexport function runDraftRemove(id: string | undefined): Envelope {\n const drafts = loadDrafts();\n if (!Array.isArray(drafts)) return err('draft', drafts.code, drafts.message);\n if (id === undefined || !drafts.some((d) => d.id === id)) {\n return err(\n 'draft',\n 'NOT_FOUND',\n `no draft '${id ?? ''}'`,\n `drafts: ${drafts.map((d) => d.id).join(', ') || 'none'}`,\n );\n }\n saveJson(\n DRAFTS(),\n drafts.filter((d) => d.id !== id),\n );\n return ok('draft', { removed: id });\n}\n","// ─── Reading the owner's messages ─────────────────────────────────────────────\n//\n// Captured 2026-10-14 from the messaging page. Reading is two GraphQL queries\n// on `voyagerMessagingGraphQL`:\n//\n// messengerConversations a folder of conversations, 20 at a time, by cursor\n// messengerMessages a conversation's latest messages\n//\n// Opening a conversation in the browser does more than read: the page also\n// POSTs `markAllMessagesAsSeen`, `sendDeliveryAcknowledgement` and, for an\n// unread conversation, marks it read — which the sender sees. Those are\n// separate calls, and this module makes none of them. Nothing here sends,\n// marks, or acknowledges anything; reading through it leaves no trace a\n// correspondent can see.\n//\n// The conversation urn is `urn:li:msg_conversation:(<mailbox>,2-<id>==)`; the\n// browser leaves its `=` padding raw, and percent-encoding it is answered\n// with a 400. The Rest.li codec leaves `=` alone, which is what is wanted.\n\nimport { CONTRACTS } from './contracts.ts';\nimport { encodeVariables } from './restli.ts';\nimport type { Failure } from './sdui-form.ts';\n\n/** The folders, by the name LinkedIn's mailbox counts use. */\nexport const FOLDERS = {\n primary: 'PRIMARY_INBOX',\n other: 'SECONDARY_INBOX',\n inbox: 'INBOX',\n archive: 'ARCHIVE',\n requests: 'MESSAGE_REQUEST_PENDING',\n spam: 'SPAM',\n} as const;\n\nexport type Folder = keyof typeof FOLDERS;\n\nconst FOLDER_OF: Record<string, Folder> = Object.fromEntries(\n Object.entries(FOLDERS).map(([k, v]) => [v, k as Folder]),\n);\n\nfunction contract(name: 'messengerConversations' | 'messengerMessages') {\n const c = CONTRACTS[name];\n if (c?.queryId === undefined) throw new Error(`messaging contract '${name}' is missing`);\n return c;\n}\n\n/** The mailbox is the owner's profile: `whoami`'s urn, in its `fsd_profile` form. */\nexport function mailboxOf(meUrn: string): string {\n const id = meUrn.match(/(?:fs_miniProfile|fsd_profile|fs_profile):([A-Za-z0-9_-]+)/)?.[1];\n return `urn:li:fsd_profile:${id ?? meUrn}`;\n}\n\nexport function conversationsUrl(q: {\n mailbox: string;\n folder: Folder;\n cursor?: string;\n count?: number;\n}): string {\n const c = contract('messengerConversations');\n const variables = encodeVariables({\n query: {\n predicateUnions: [{ conversationCategoryPredicate: { category: FOLDERS[q.folder] } }],\n },\n count: q.count ?? 20,\n mailboxUrn: q.mailbox,\n nextCursor: q.cursor,\n });\n return `${c.path}?queryId=${c.queryId}&variables=${variables}`;\n}\n\nexport function messagesUrl(conversationUrn: string): string {\n const c = contract('messengerMessages');\n return `${c.path}?queryId=${c.queryId}&variables=${encodeVariables({ conversationUrn })}`;\n}\n\n/** A conversation urn from itself, a /messaging/thread/ URL, or a bare thread id. */\nexport function conversationIdOf(input: string, mailbox: string): string | undefined {\n const s = input.trim();\n if (/^urn:li:msg_conversation:\\(urn:li:fsd_profile:[^,]+,2-[^)]+\\)$/.test(s)) return s;\n const thread =\n s.match(/messaging\\/thread\\/(2-[^/?#]+)/)?.[1] ?? s.match(/^(2-[A-Za-z0-9+/=_-]+)$/)?.[1];\n return thread === undefined ? undefined : `urn:li:msg_conversation:(${mailbox},${thread})`;\n}\n\n// ─── Parsing ──────────────────────────────────────────────────────────────────\n\ntype Node = Record<string, unknown>;\n\nexport interface Participant {\n name: string;\n kind: 'person' | 'organization' | 'other';\n headline?: string;\n /** 1st, 2nd, 3rd+, out of network. */\n degree?: string;\n url?: string;\n}\n\nexport interface MessageLine {\n from: string;\n fromMe: boolean;\n at: string;\n text?: string;\n subject?: string;\n /** A sponsored message (an InMail ad). */\n sponsored?: boolean;\n}\n\nexport interface Conversation {\n id: string;\n url?: string;\n /** Everyone in it but the owner. */\n with: Participant[];\n /** A group conversation's name. */\n title?: string;\n unread: number;\n lastActivity?: string;\n last?: MessageLine;\n folders: Folder[];\n inmail: boolean;\n}\n\nexport interface Message extends MessageLine {\n id: string;\n}\n\nconst DEGREE: Record<string, string> = {\n DISTANCE_1: '1st',\n DISTANCE_2: '2nd',\n DISTANCE_3: '3rd+',\n OUT_OF_NETWORK: 'out of network',\n};\n\nconst txt = (v: unknown): string | undefined => {\n const t = typeof v === 'string' ? v : (v as { text?: unknown } | null | undefined)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim() : undefined;\n};\n\nconst iso = (ms: unknown) => (typeof ms === 'number' ? new Date(ms).toISOString() : undefined);\n\nfunction defined<T extends Record<string, unknown>>(obj: T): T {\n for (const k of Object.keys(obj)) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\nfunction participantOf(p: Node | undefined): Participant | undefined {\n const t = (p?.participantType ?? {}) as Record<string, Node | null>;\n if (t.member) {\n const m = t.member;\n const name = [txt(m.firstName), txt(m.lastName)].filter(Boolean).join(' ');\n const url =\n typeof m.profileUrl === 'string' ? `${m.profileUrl.replace(/\\/$/, '')}/` : undefined;\n return defined({\n name: name !== '' ? name : 'LinkedIn Member',\n kind: 'person' as const,\n headline: txt(m.headline),\n degree: DEGREE[String(m.distance)],\n url,\n });\n }\n if (t.organization) {\n const o = t.organization;\n return defined({\n name: txt(o.name) ?? 'an organization',\n kind: 'organization' as const,\n url: typeof o.pageUrl === 'string' ? o.pageUrl : undefined,\n });\n }\n if (t.custom) return { name: txt(t.custom.name) ?? 'LinkedIn', kind: 'other' };\n return undefined;\n}\n\nconst isMe = (urn: unknown, mailbox: string) => typeof urn === 'string' && urn.includes(mailbox);\n\nfunction messageOf(m: Node, byUrn: Map<unknown, Node>, mailbox: string): MessageLine {\n const sender = m['*sender'] ?? m['*actor'];\n const fromMe = isMe(sender, mailbox);\n const who = fromMe ? undefined : participantOf(byUrn.get(sender));\n const render = Array.isArray(m.renderContent) ? (m.renderContent as Node[]) : [];\n return defined({\n from: fromMe ? 'you' : (who?.name ?? 'unknown'),\n fromMe,\n at: iso(m.deliveredAt) as string,\n text: txt(m.body),\n subject: txt(m.subject),\n sponsored: render.some((r) => r.conversationAdsMessageContent) ? true : undefined,\n });\n}\n\nconst drift = (message: string): Failure => ({\n ok: false,\n code: 'SCHEMA_DRIFT',\n message,\n hint: 'the messaging response changed shape; re-capture it',\n});\n\n/** The `messenger…` collection in a response, whatever the query named it. */\nfunction collectionOf(json: unknown): Node | undefined {\n const d = (json as { data?: { data?: Node } } | null)?.data?.data;\n const key = d === undefined ? undefined : Object.keys(d).find((k) => k.startsWith('messenger'));\n const c = key === undefined ? undefined : d?.[key];\n return c !== null && typeof c === 'object' ? (c as Node) : undefined;\n}\n\n/** A collection's references; an empty one comes as `elements: []` instead. */\nfunction refsOf(top: Node | undefined): string[] | undefined {\n const refs = top?.['*elements'];\n if (Array.isArray(refs)) return refs as string[];\n return Array.isArray(top?.elements) && top.elements.length === 0 ? [] : undefined;\n}\n\nexport function parseConversations(\n json: unknown,\n mailbox: string,\n): { ok: true; conversations: Conversation[]; cursor?: string } | Failure {\n const top = collectionOf(json);\n const refs = refsOf(top);\n if (refs === undefined) return drift('the conversation list was missing');\n const included = (json as { included?: Node[] }).included ?? [];\n const byUrn = new Map<unknown, Node>(included.map((n) => [n.entityUrn, n]));\n const conversations: Conversation[] = [];\n for (const ref of refs) {\n const c = byUrn.get(ref);\n if (c === undefined) continue;\n const parts = ((c['*conversationParticipants'] as string[] | undefined) ?? [])\n .filter((u) => !isMe(u, mailbox))\n .map((u) => participantOf(byUrn.get(u)))\n .filter((p): p is Participant => p !== undefined);\n const lastRef = ((c.messages as Node | undefined)?.['*elements'] as string[] | undefined)?.[0];\n const last = lastRef === undefined ? undefined : byUrn.get(lastRef);\n const categories = Array.isArray(c.categories) ? (c.categories as string[]) : [];\n conversations.push(\n defined({\n id: String(c.entityUrn),\n url: typeof c.conversationUrl === 'string' ? c.conversationUrl : undefined,\n with: parts,\n title: c.groupChat === true ? txt(c.title) : undefined,\n unread: typeof c.unreadCount === 'number' ? c.unreadCount : 0,\n lastActivity: iso(c.lastActivityAt),\n last: last === undefined ? undefined : messageOf(last, byUrn, mailbox),\n // PRIMARY_INBOX sits inside INBOX; report the folder a person would name.\n folders: categories\n .map((k) => FOLDER_OF[k])\n .filter(\n (f): f is Folder =>\n f !== undefined && !(f === 'primary' && categories.includes('INBOX')),\n ),\n inmail: categories.includes('INMAIL'),\n }),\n );\n }\n if (refs.length > 0 && conversations.length === 0)\n return drift(`${refs.length} conversations were listed but none were sent`);\n const cursor = (top?.metadata as Node | undefined)?.nextCursor;\n return {\n ok: true,\n conversations,\n ...(typeof cursor === 'string' && cursor !== '' ? { cursor } : {}),\n };\n}\n\nexport function parseMessages(\n json: unknown,\n mailbox: string,\n): { ok: true; messages: Message[] } | Failure {\n const top = collectionOf(json);\n const refs = refsOf(top);\n if (refs === undefined) return drift('the message list was missing');\n const included = (json as { included?: Node[] }).included ?? [];\n const byUrn = new Map<unknown, Node>(included.map((n) => [n.entityUrn, n]));\n const messages: Message[] = [];\n for (const ref of refs) {\n const m = byUrn.get(ref);\n if (m === undefined || typeof m.deliveredAt !== 'number') continue;\n messages.push({ id: String(m.entityUrn), ...messageOf(m, byUrn, mailbox) });\n }\n if (refs.length > 0 && messages.length === 0)\n return drift(`${refs.length} messages were listed but none were sent`);\n // Oldest first, the way a conversation reads.\n messages.sort((a, b) => a.at.localeCompare(b.at));\n return { ok: true, messages };\n}\n","// ─── My items: saved posts, learning, the job tracker ─────────────────────────\n//\n// Captured 2026-10-14. Each list is the Voyager search (the `search`\n// contract) with a My-items intent and no keywords:\n//\n// SEARCH_MY_ITEMS_SAVED_POSTS posts the owner saved\n// SEARCH_MY_ITEMS_LEARNING their LinkedIn Learning courses\n// SEARCH_MY_ITEMS_JOB_SEEKER the job tracker, one stage at a time:\n// queryParameters cardType = SAVED, IN_PROGRESS,\n// APPLIED, INTERVIEW, ARCHIVED\n//\n// The stage names are the job tracker page's own (`?stage=archived`, …),\n// uppercased. LinkedIn does not validate them: a wrong name answers with no\n// jobs, not an error. ARCHIVED was verified with the owner's 6 archived jobs;\n// the other four agreed with the page's own counts (all 0) — which a wrong\n// name would also give. Pages hold 10; saved posts page with a token.\n\nimport { CONTRACTS } from './contracts.ts';\nimport { type Clusters, clustersOf, readItems } from './people.ts';\nimport { encodeVariables } from './restli.ts';\nimport type { Failure } from './sdui-form.ts';\n\nexport const ITEMS = {\n posts: 'SEARCH_MY_ITEMS_SAVED_POSTS',\n learning: 'SEARCH_MY_ITEMS_LEARNING',\n jobs: 'SEARCH_MY_ITEMS_JOB_SEEKER',\n} as const;\n\nexport type ItemList = keyof typeof ITEMS;\n\nexport const STAGES = {\n saved: 'SAVED',\n 'in-progress': 'IN_PROGRESS',\n applied: 'APPLIED',\n interview: 'INTERVIEW',\n archived: 'ARCHIVED',\n} as const;\n\nexport type Stage = keyof typeof STAGES;\n\nexport const ITEMS_PAGE = 10;\n\nexport function itemsUrl(\n list: ItemList,\n q: { start: number; stage?: Stage; token?: string },\n): string {\n const c = CONTRACTS.search;\n if (c?.queryId === undefined) throw new Error(\"the 'search' contract is missing\");\n const variables = encodeVariables({\n start: q.start,\n paginationToken: q.token,\n query: {\n flagshipSearchIntent: ITEMS[list],\n queryParameters:\n q.stage !== undefined ? [{ key: 'cardType', value: [STAGES[q.stage]] }] : undefined,\n },\n });\n return `${c.path}?variables=${variables}&queryId=${c.queryId}`;\n}\n\n// ─── Rows ─────────────────────────────────────────────────────────────────────\n\nexport interface SavedPost {\n /** The post's urn: what `post` and `reactions` take. */\n id: string;\n url: string;\n author?: string;\n authorHeadline?: string;\n /** When, as LinkedIn shows it (\"5d\"). */\n posted?: string;\n text?: string;\n}\n\nexport interface Course {\n id: string;\n name: string;\n length?: string;\n /** Instructor and release date, as LinkedIn writes them. */\n detail?: string;\n /** \"6m left\", or completion. */\n progress?: string;\n url?: string;\n}\n\nexport interface TrackedJob {\n /** The job id: what `job` takes. */\n id: string;\n title: string;\n company?: string;\n location?: string;\n workplace?: 'on-site' | 'remote' | 'hybrid';\n stage?: Stage;\n /** A line LinkedIn adds, such as \"No longer accepting applications\". */\n note?: string;\n url: string;\n}\n\ntype Node = Record<string, unknown>;\ntype Item = SavedPost | Course | TrackedJob;\n\nconst text = (v: unknown): string | undefined => {\n const t = (v as { text?: unknown } | null | undefined)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim().replace(/\\s+/g, ' ') : undefined;\n};\nconst inner = (urn: unknown) => String(urn ?? '').match(/\\((urn:li:[A-Za-z_]+:[^,)]+)/)?.[1];\nconst clean = (url: unknown) =>\n typeof url === 'string' && url.startsWith('https://') ? url.split('?')[0] : undefined;\nconst insight = (row: Node) =>\n (Array.isArray(row.insightsResolutionResults) ? (row.insightsResolutionResults as Node[]) : [])\n .map((i) => text((i.simpleInsight as Node | null)?.title))\n .find((t) => t !== undefined);\n\nfunction defined<T extends object>(obj: T): T {\n for (const k of Object.keys(obj) as (keyof T)[]) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\nconst WORKPLACE: Record<string, TrackedJob['workplace']> = {\n remote: 'remote',\n hybrid: 'hybrid',\n 'on-site': 'on-site',\n};\n\nfunction postRow(row: Node): SavedPost | undefined {\n const id = inner(row.entityUrn);\n if (id === undefined || !/^urn:li:(activity|ugcPost|share):/.test(id)) return undefined;\n const posted = text(row.secondarySubtitle)?.replace(/\\s*•\\s*$/, '');\n return defined({\n id,\n url: `https://www.linkedin.com/feed/update/${id}/`,\n author: text(row.title),\n authorHeadline: text(row.primarySubtitle),\n posted,\n text: text(row.summary),\n });\n}\n\nfunction courseRow(row: Node): Course | undefined {\n const id = inner(row.entityUrn)?.split(':').pop();\n const name = text(row.title);\n if (id === undefined || name === undefined) return undefined;\n return defined({\n id,\n name,\n length: text(row.primarySubtitle),\n detail: text(row.secondarySubtitle),\n progress: text(row.summary),\n url: clean(row.navigationUrl),\n });\n}\n\nfunction jobRow(row: Node, stage?: Stage): TrackedJob | undefined {\n const id = inner(row.entityUrn)?.split(':').pop();\n const title = text(row.title);\n if (id === undefined || title === undefined) return undefined;\n const place = text(row.secondarySubtitle);\n const m = place?.match(/^(.*?)\\s*\\(([^()]+)\\)$/);\n const workplace = m?.[2] === undefined ? undefined : WORKPLACE[m[2].toLowerCase()];\n return defined({\n id,\n title,\n company: text(row.primarySubtitle),\n location: workplace !== undefined ? m?.[1] : place,\n workplace,\n stage,\n note: insight(row),\n url: `https://www.linkedin.com/jobs/view/${id}/`,\n });\n}\n\nexport function parseItems(\n list: ItemList,\n json: unknown,\n stage?: Stage,\n): { ok: true; items: Item[]; total?: number; token?: string } | Failure {\n const c: Clusters | undefined = clustersOf(json);\n if (c === undefined || !Array.isArray(c.elements))\n return { ok: false, code: 'SCHEMA_DRIFT', message: 'the My items list was missing' };\n const included = (json as { included?: Node[] }).included ?? [];\n const toRow = (row: Node) =>\n list === 'posts' ? postRow(row) : list === 'learning' ? courseRow(row) : jobRow(row, stage);\n const { people: items, unresolved } = readItems(\n c,\n included,\n toRow as (row: Node) => (Item & { id: string }) | undefined,\n );\n if (unresolved > 0 && items.length === 0)\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `${unresolved} items were listed but none could be read`,\n };\n const total = typeof c.paging?.total === 'number' ? c.paging.total : undefined;\n const token = c.metadata?.paginationToken;\n return {\n ok: true,\n items,\n ...(total !== undefined ? { total } : {}),\n ...(typeof token === 'string' && token !== '' ? { token } : {}),\n };\n}\n","// ─── `lnrelay my-items posts|learning|jobs` ───────────────────────────────────\n//\n// The owner's My items, read only; see engine/my-items.ts. Saved posts and\n// learning are one list each; the job tracker is one list per stage, so jobs\n// with no --stage read all five. Everything spends the page budget.\n\nimport { createLiveClient } from '../engine/index.ts';\nimport {\n ITEMS,\n ITEMS_PAGE,\n type ItemList,\n itemsUrl,\n parseItems,\n STAGES,\n type Stage,\n} from '../engine/my-items.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; json: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted GET. Injectable so tests send nothing. */\nexport type ItemsFetch = (url: string, spendClass: 'page') => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): ItemsFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('my-items', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, spendClass) => {\n const r = await client.request({ url, spendClass, operation: 'my-items' });\n return r.ok ? { ok: true, json: r.json } : r;\n };\n}\n\nexport interface ItemsRequest {\n limit: number;\n stage?: Stage;\n}\n\ntype Row = Record<string, unknown>;\n\n/** One list (or one tracker stage), paged to the limit. */\nasync function collect(get: ItemsFetch, list: ItemList, want: number, stage?: Stage) {\n const items: Row[] = [];\n let token: string | undefined;\n for (let start = 0; items.length < want; start += ITEMS_PAGE) {\n const res = await get(\n itemsUrl(list, { start, ...(stage ? { stage } : {}), ...(token ? { token } : {}) }),\n 'page',\n );\n const page = res.ok ? parseItems(list, res.json, stage) : res;\n if (!page.ok)\n return items.length === 0 ? page : { items, complete: false, stoppedBy: page.code };\n const room = want - items.length;\n items.push(...(page.items as unknown as Row[]).slice(0, room));\n // The limit cut this page short: there is more.\n if (page.items.length > room) return { items, complete: false };\n const last =\n page.items.length < ITEMS_PAGE ||\n (page.total !== undefined && start + ITEMS_PAGE >= page.total);\n if (last) return { items, complete: true };\n token = page.token;\n }\n return { items, complete: false };\n}\n\nfunction compactRow(r: Row): string {\n return line(\n [\n r.id,\n r.title ?? r.name ?? r.author,\n r.company ?? r.length ?? r.authorHeadline,\n r.location ?? r.detail ?? r.posted,\n r.workplace,\n r.stage,\n r.note ?? r.progress,\n typeof r.text === 'string' ? r.text.replace(/\\s+/g, ' ').slice(0, 140) : undefined,\n r.url,\n ].map((x) => (typeof x === 'string' ? x : undefined)),\n );\n}\n\ninterface Gathered {\n items: Row[];\n byStage: Record<string, number>;\n complete: boolean;\n stoppedBy?: string;\n}\n\n/** Each stage in turn (one, for posts and learning) until the limit; a stage that fails is noted. */\nasync function collectStages(\n get: ItemsFetch,\n which: ItemList,\n want: number,\n stages: (Stage | undefined)[],\n): Promise<Gathered | { failure: { code: string; message: string; hint?: string } }> {\n const out: Gathered = { items: [], byStage: {}, complete: true };\n let failure: { code: string; message: string; hint?: string } | undefined;\n for (const stage of stages) {\n const got = await collect(get, which, want - out.items.length, stage);\n if ('ok' in got) {\n failure = failure ?? got;\n out.complete = false;\n out.stoppedBy = got.code;\n continue;\n }\n out.items.push(...got.items);\n if (stage !== undefined) out.byStage[stage] = got.items.length;\n out.complete &&= got.complete;\n if (got.stoppedBy !== undefined) out.stoppedBy = got.stoppedBy;\n if (out.items.length >= want) break;\n }\n // Nothing read at all, and something failed: a failure, not an empty list.\n if (out.items.length === 0 && failure !== undefined) return { failure };\n return out;\n}\n\nexport async function runMyItems(\n list: string | undefined,\n req: ItemsRequest,\n opts: OutputOpts = {},\n fetch?: ItemsFetch,\n): Promise<Envelope> {\n if (list === undefined || !(list in ITEMS))\n return err(\n 'my-items',\n 'INVALID_INPUT',\n `no list '${list ?? ''}'`,\n `one of: ${Object.keys(ITEMS).join(', ')}`,\n );\n if (req.stage !== undefined && !(req.stage in STAGES))\n return err(\n 'my-items',\n 'INVALID_INPUT',\n `no stage '${req.stage}'`,\n `one of: ${Object.keys(STAGES).join(', ')}`,\n );\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n const want = Math.max(1, req.limit);\n const which = list as ItemList;\n\n const stages: (Stage | undefined)[] =\n which === 'jobs'\n ? req.stage !== undefined\n ? [req.stage]\n : (Object.keys(STAGES) as Stage[])\n : [undefined];\n const got = await collectStages(get, which, want, stages);\n if ('failure' in got) {\n const f = got.failure;\n return err('my-items', f.code, f.message, f.hint);\n }\n const { items, byStage, complete, stoppedBy } = got;\n return ok('my-items', {\n list: which,\n items: shape(items, opts, compactRow),\n meta: {\n state: complete && stoppedBy === undefined ? 'complete' : 'partial',\n operation: `my-items ${which}`,\n returnedCount: items.length,\n ...(which === 'jobs' && req.stage === undefined ? { byStage } : {}),\n ...(stoppedBy !== undefined ? { stoppedBy } : {}),\n },\n });\n}\n","// ─── Searching companies, groups, events, courses, products, services, schools ─\n//\n// Probed 2026-10-14. Every kind in the search box beside people, jobs and\n// posts comes back from the same Voyager search as people (engine/people.ts),\n// one `resultType` each, in the same row shape: a title, a subtitle, a second\n// line and a summary, whose meaning depends on the kind:\n//\n// companies industry • HQ followers id: company\n// groups members — id: group\n// events when where • organiser id: event\n// courses length instructor • released id: course\n// products category by vendor — id: product page\n// services the provider's headline, place, service id: profile\n// schools place students and alumni id: school (organisation)\n//\n// So one parser serves them all and keeps LinkedIn's lines as they are rather\n// than guessing at fields inside them. Pages hold 50 (events return more than\n// asked); LinkedIn pages at most 1000 of any query. Filters differ per kind and\n// come back with `includeFiltersInResponse`, as for people.\n\nimport { type Clusters, clustersOf, PEOPLE_PAGE, peopleSearchUrl, readItems } from './people.ts';\nimport type { Failure } from './sdui-form.ts';\n\n/** The CLI's name for each kind, and LinkedIn's result type. */\nexport const SEARCH_KINDS = {\n companies: 'COMPANIES',\n groups: 'GROUPS',\n events: 'EVENTS',\n courses: 'LEARNING',\n products: 'PRODUCTS',\n services: 'SERVICES',\n schools: 'SCHOOLS',\n} as const;\n\nexport type SearchKindName = keyof typeof SEARCH_KINDS;\n\nexport const SEARCH_PAGE = PEOPLE_PAGE;\n\nexport interface SearchQuery {\n kind: SearchKindName;\n keywords?: string;\n params: Record<string, string[]>;\n start: number;\n withFilters?: boolean;\n}\n\nexport function searchUrl(q: SearchQuery): string {\n return peopleSearchUrl({\n ...(q.keywords !== undefined ? { keywords: q.keywords } : {}),\n params: q.params,\n start: q.start,\n ...(q.withFilters === true ? { withFilters: true } : {}),\n kind: SEARCH_KINDS[q.kind],\n });\n}\n\n/** One result, in LinkedIn's own lines; see the table above for what each holds. */\nexport interface Found {\n /** The entity's own id: a company, group, event, course, product page or profile. */\n id: string;\n name: string;\n subtitle?: string;\n detail?: string;\n summary?: string;\n url?: string;\n verified?: boolean;\n}\n\ntype Node = Record<string, unknown>;\n\nconst text = (v: unknown): string | undefined => {\n const t = (v as { text?: unknown } | null | undefined)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim().replace(/\\s+/g, ' ') : undefined;\n};\n\n/** The id inside `urn:li:fsd_entityResultViewModel:(<urn>,SEARCH_SRP,DEFAULT)`. */\nfunction idOf(entityUrn: unknown): string | undefined {\n const inner = String(entityUrn ?? '').match(/\\((urn:li:[A-Za-z_]+:[^,)]+)/)?.[1];\n return inner?.split(':').pop();\n}\n\n/** The page's own address, without per-viewer tracking or claim tokens. */\nfunction cleanUrl(nav: unknown): string | undefined {\n if (typeof nav !== 'string' || !nav.startsWith('https://')) return undefined;\n return nav.split('?')[0];\n}\n\nfunction rowToFound(row: Node): Found | undefined {\n const id = idOf(row.entityUrn);\n const name = text(row.title);\n if (id === undefined || name === undefined) return undefined;\n const found: Found = { id, name };\n const fields: [keyof Found, string | undefined][] = [\n ['subtitle', text(row.primarySubtitle)],\n ['detail', text(row.secondarySubtitle)],\n ['summary', text(row.summary)],\n ['url', cleanUrl(row.navigationUrl)],\n ];\n for (const [k, v] of fields)\n if (v !== undefined) (found as unknown as Record<string, string>)[k] = v;\n if (JSON.stringify(row.badgeIcon ?? null).includes('VERIFIED')) found.verified = true;\n return found;\n}\n\nexport interface ResultsPage {\n ok: true;\n items: Found[];\n total?: number;\n claimed?: number;\n start: number;\n excluded: number;\n unknownTypes: Record<string, number>;\n}\n\nconst drift = (message: string): Failure => ({\n ok: false,\n code: 'SCHEMA_DRIFT',\n message,\n hint: 'the search response changed shape; re-capture it',\n});\n\nexport function parseResults(json: unknown): ResultsPage | Failure {\n const c: Clusters | undefined = clustersOf(json);\n if (c === undefined || !Array.isArray(c.elements))\n return drift('the search returned no result list');\n const included = (json as { included?: Node[] }).included ?? [];\n const { people: items, unknownTypes, excluded, unresolved } = readItems(c, included, rowToFound);\n const total = typeof c.paging?.total === 'number' ? c.paging.total : undefined;\n const start = typeof c.paging?.start === 'number' ? c.paging.start : 0;\n const claimedRaw = c.metadata?.totalResultCount;\n const claimed = typeof claimedRaw === 'number' ? claimedRaw : total;\n if (unresolved > 0 && items.length === 0)\n return drift(`${unresolved} results were listed but none could be read`);\n if (items.length === 0 && total !== undefined && total > start) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `LinkedIn claims ${total} results but returned none from ${start}`,\n hint: 'a failed fetch, not an empty search; do not report \"none\"',\n };\n }\n return {\n ok: true,\n items,\n ...(total !== undefined ? { total } : {}),\n ...(claimed !== undefined ? { claimed } : {}),\n start,\n excluded,\n unknownTypes,\n };\n}\n","// ─── My Network: connections, following, followers, pages, invitations ────────\n//\n// Captured 2026-10-14. The My Network page's lists come from the same Voyager\n// search as people (engine/people.ts), with origin `CurationHub`, intent\n// `MYNETWORK_CURATION_HUB`, no keywords (an empty one is a 400) and a result\n// type per list. Sent invitations are the older relationships resource.\n//\n// Opening My Network in the browser also clears the \"new invitations\" badge\n// and marks notifications seen (`addaClearUnseenInvitationsMutation`,\n// `addaMarkNotificationsSeen`). Those are separate calls; nothing here makes\n// them. Not covered: received invitations (none were pending to verify\n// against), newsletters (the hub answers that type with a server error), and\n// \"people you may know\" (an SDUI pager).\n\nimport { CONTRACTS } from './contracts.ts';\nimport { PEOPLE_PAGE, type Person, parsePeople, peopleSearchUrl } from './people.ts';\nimport type { Failure } from './sdui-form.ts';\nimport { type Found, parseResults } from './search.ts';\n\n/** The CLI's name for each hub list, and LinkedIn's result type. */\nexport const HUB = {\n connections: 'CONNECTIONS',\n following: 'PEOPLE_FOLLOW',\n followers: 'FOLLOWERS',\n pages: 'PAGES',\n events: 'EVENTS',\n groups: 'GROUPS',\n} as const;\n\nexport type HubList = keyof typeof HUB;\n\nconst PEOPLE_LISTS = new Set<HubList>(['connections', 'following', 'followers']);\n\nexport function hubUrl(list: HubList, start: number): string {\n return peopleSearchUrl({\n params: {},\n start,\n kind: HUB[list],\n origin: 'CurationHub',\n intent: 'MYNETWORK_CURATION_HUB',\n });\n}\n\nexport const HUB_PAGE = PEOPLE_PAGE;\n\nexport interface HubPage {\n ok: true;\n items: (Person | Found)[];\n total?: number;\n unknownTypes: Record<string, number>;\n}\n\n/** People lists read as people; pages, events and groups as generic results. */\nexport function parseHub(list: HubList, json: unknown): HubPage | Failure {\n if (PEOPLE_LISTS.has(list)) {\n const r = parsePeople(json);\n if (!r.ok) return r;\n return {\n ok: true,\n items: r.people,\n ...(r.total !== undefined ? { total: r.total } : {}),\n unknownTypes: r.unknownTypes,\n };\n }\n const r = parseResults(json);\n if (!r.ok) return r;\n return {\n ok: true,\n items: r.items,\n ...(r.total !== undefined ? { total: r.total } : {}),\n unknownTypes: r.unknownTypes,\n };\n}\n\n// ─── Sent invitations ─────────────────────────────────────────────────────────\n\nexport function sentInvitationsUrl(start: number, count = 10): string {\n const c = CONTRACTS.sentInvitations;\n if (c === undefined) throw new Error(\"the 'sentInvitations' contract is missing\");\n return `${c.path}?count=${count}&invitationType=CONNECTION&q=invitationType&start=${start}`;\n}\n\nexport interface SentInvitation {\n to: string;\n /** The invitee's profile id. */\n id?: string;\n headline?: string;\n url?: string;\n sent?: string;\n /** The note sent with it, if any. */\n note?: string;\n}\n\ntype Node = Record<string, unknown>;\n\nexport function parseSentInvitations(\n json: unknown,\n): { ok: true; invitations: SentInvitation[] } | Failure {\n const data = (json as { data?: Node } | null)?.data;\n const refs = data?.['*elements'] ?? data?.elements;\n if (!Array.isArray(refs))\n return { ok: false, code: 'SCHEMA_DRIFT', message: 'the sent invitations list was missing' };\n const included = (json as { included?: Node[] }).included ?? [];\n const byUrn = new Map<unknown, Node>(included.map((n) => [n.entityUrn, n]));\n const invitations: SentInvitation[] = [];\n for (const ref of refs as unknown[]) {\n const view = byUrn.get(ref);\n const inv =\n byUrn.get(view?.['*invitation']) ??\n included.find(\n (n) =>\n String(n.$type).endsWith('.Invitation') &&\n typeof ref === 'string' &&\n ref.endsWith(String(n.entityUrn)),\n );\n if (inv === undefined) continue;\n const who = byUrn.get(inv['*toMember']);\n const name = [who?.firstName, who?.lastName]\n .filter((x) => typeof x === 'string' && x !== '')\n .join(' ');\n const id = String(inv['*toMember'] ?? '')\n .split(':')\n .pop();\n const note =\n typeof inv.message === 'string'\n ? inv.message\n : (inv.message as { text?: unknown } | null)?.text;\n const out: SentInvitation = { to: name !== '' ? name : 'LinkedIn Member' };\n if (id) out.id = id;\n if (typeof who?.occupation === 'string') out.headline = who.occupation;\n if (typeof who?.publicIdentifier === 'string')\n out.url = `https://www.linkedin.com/in/${who.publicIdentifier}/`;\n if (typeof inv.sentTime === 'number') out.sent = new Date(inv.sentTime).toISOString();\n if (typeof note === 'string' && note.trim() !== '') out.note = note.trim();\n invitations.push(out);\n }\n if (refs.length > 0 && invitations.length === 0)\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `${refs.length} invitations were listed but none were sent`,\n };\n return { ok: true, invitations };\n}\n","// ─── `lnrelay network [list]` ─────────────────────────────────────────────────\n//\n// The owner's My Network, read only; see engine/network.ts. With no list, the\n// count of each (one call each); with a list, its rows. Everything spends the\n// page budget. Nothing here clears a badge or marks anything seen.\n\nimport { createLiveClient } from '../engine/index.ts';\nimport {\n HUB,\n HUB_PAGE,\n type HubList,\n hubUrl,\n parseHub,\n parseSentInvitations,\n type SentInvitation,\n sentInvitationsUrl,\n} from '../engine/network.ts';\nimport type { Person } from '../engine/people.ts';\nimport type { Found } from '../engine/search.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line, metaOf, type PageFetch, type Paging, searchAll } from './paged.ts';\nimport { shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; json: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted GET. Injectable so tests send nothing. */\nexport type NetworkFetch = (url: string, spendClass: 'page') => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): NetworkFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('network', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, spendClass) => {\n const r = await client.request({ url, spendClass, operation: 'network' });\n return r.ok ? { ok: true, json: r.json } : r;\n };\n}\n\nexport interface NetworkRequest {\n limit: number;\n start?: number;\n}\n\nconst LISTS = [...Object.keys(HUB), 'invitations'];\nconst PAGING: Paging = { pageSize: HUB_PAGE, max: 1000 };\nconst INVITATIONS_PAGE = 10;\n\nfunction compactRow(r: Person | Found): string {\n const p = r as Person & Found;\n return line([p.id, p.name, p.headline ?? p.subtitle, p.location ?? p.detail, p.degree, p.url]);\n}\n\nasync function counts(get: NetworkFetch): Promise<{ counts: Record<string, number> } | Envelope> {\n const out: Record<string, number> = {};\n for (const list of Object.keys(HUB) as HubList[]) {\n const res = await get(hubUrl(list, 0), 'page');\n const page = res.ok ? parseHub(list, res.json) : res;\n if (!page.ok) return err('network', page.code, `${list}: ${page.message}`, page.hint);\n out[list] = page.total ?? page.items.length;\n }\n const res = await get(sentInvitationsUrl(0, INVITATIONS_PAGE), 'page');\n const inv = res.ok ? parseSentInvitations(res.json) : res;\n if (!inv.ok) return err('network', inv.code, `invitations: ${inv.message}`);\n // The resource gives no total: a full page means \"at least\".\n out.invitationsSent = inv.invitations.length;\n return { counts: out };\n}\n\nasync function invitations(\n get: NetworkFetch,\n req: NetworkRequest,\n opts: OutputOpts,\n): Promise<Envelope> {\n const all: SentInvitation[] = [];\n let exhausted = false;\n let stoppedBy: string | undefined;\n for (let start = req.start ?? 0; all.length < req.limit; start += INVITATIONS_PAGE) {\n const res = await get(sentInvitationsUrl(start, INVITATIONS_PAGE), 'page');\n const page = res.ok ? parseSentInvitations(res.json) : res;\n if (!page.ok) {\n if (all.length === 0) return err('network', page.code, page.message);\n stoppedBy = page.code;\n break;\n }\n all.push(...page.invitations.slice(0, req.limit - all.length));\n if (page.invitations.length < INVITATIONS_PAGE) {\n exhausted = true;\n break;\n }\n }\n return ok('network', {\n list: 'invitations',\n items: shape(all, opts, (i) =>\n line([i.id, i.to, i.headline, i.sent?.slice(0, 10), i.note, i.url]),\n ),\n meta: {\n state: exhausted && stoppedBy === undefined ? 'complete' : 'partial',\n operation: 'network invitations',\n returnedCount: all.length,\n ...(stoppedBy !== undefined ? { stoppedBy } : {}),\n },\n });\n}\n\nexport async function runNetwork(\n list: string | undefined,\n req: NetworkRequest,\n opts: OutputOpts = {},\n fetch?: NetworkFetch,\n): Promise<Envelope> {\n if (list !== undefined && !LISTS.includes(list)) {\n return err(\n 'network',\n 'INVALID_INPUT',\n `no list '${list}'`,\n `one of: ${LISTS.join(', ')} — or none, for the counts`,\n );\n }\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n\n if (list === undefined) {\n const c = await counts(get);\n if (!('counts' in c)) return c;\n return ok('network', { counts: c.counts, meta: { state: 'complete', operation: 'network' } });\n }\n if (list === 'invitations') return invitations(get, req, opts);\n\n const hub = list as HubList;\n const first = Math.max(0, req.start ?? 0);\n const fetchPage: PageFetch<Person | Found> = async (_keywords, start) => {\n const res = await get(hubUrl(hub, start), 'page');\n const page = res.ok ? parseHub(hub, res.json) : res;\n if (!page.ok) return page;\n return {\n ok: true,\n items: page.items,\n ...(page.total !== undefined ? { total: page.total } : {}),\n unknownTypes: page.unknownTypes,\n };\n };\n const merged = await searchAll(\n fetchPage,\n [undefined],\n first,\n Math.max(1, Math.min(req.limit, PAGING.max - first)),\n PAGING,\n );\n if (merged.rows.length === 0 && merged.failure !== undefined) {\n const f = merged.failure;\n return err('network', f.code, f.message, f.hint);\n }\n return ok('network', {\n list: hub,\n items: shape(merged.rows, opts, compactRow),\n meta: metaOf(`network ${hub}`, merged, true, first),\n });\n}\n","// ─── The owner's notifications ────────────────────────────────────────────────\n//\n// Probed 2026-10-29. The bell's list is a REST finder:\n//\n// voyagerIdentityDashNotificationCards?q=filterVanityName&count=N&start=S\n//\n// Each card is a node in `included`: a headline, optional sub-lines, `read`,\n// `publishedAt`, and where it goes (`cardAction.actionTarget`) and who or what\n// it is about (`headerImage.actionTarget`). Its kind is the first part of its\n// urn (FOLLOW_PAGE_HERO, …). `metadata.nextStart` is the next page; the last\n// page has none and an empty-section card instead. A page can hold fewer\n// cards than asked for (10 asked, 9 sent, next start 10), so paging follows\n// nextStart, not the count.\n//\n// Not read: the page's tabs (my posts, mentions, jobs). `filterVanityName`\n// is the finder's key, but `mentions` answered as `all`; the tab names are\n// unverified. Reading here never marks anything seen.\n\nimport { CONTRACTS } from './contracts.ts';\nimport type { Failure } from './sdui-form.ts';\n\ntype Node = Record<string, unknown>;\n\nexport function notificationsUrl(count: number, start: number): string {\n const c = CONTRACTS.notifications;\n if (c?.decorationId === undefined) throw new Error(\"the 'notifications' contract is missing\");\n return `${c.path}?decorationId=${c.decorationId}&q=filterVanityName&count=${count}&start=${start}`;\n}\n\nexport interface Notification {\n /** LinkedIn's own name for the kind of notification. */\n kind: string;\n text: string;\n /** Sub-lines, when the card has them. */\n detail?: string;\n /** ISO time it was published. */\n at?: string;\n read: boolean;\n /** Where the card goes. */\n url?: string;\n /** Who or what it is about: a profile, a company. */\n from?: string;\n}\n\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst textOf = (v: unknown) => {\n const t = (v as { text?: unknown } | null)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim() : undefined;\n};\nconst absolute = (v: unknown) =>\n typeof v === 'string' && v !== ''\n ? v.startsWith('/')\n ? `https://www.linkedin.com${v}`\n : v\n : undefined;\n\nfunction card(n: Node): Notification | undefined {\n const text = textOf(n.headline);\n if (text === undefined) return undefined;\n const kind = String(n.entityUrn ?? '').match(/fsd_notificationCard:\\(([^,]+),/)?.[1] ?? 'UNKNOWN';\n const detail = [n.subHeadline, n.contentPrimaryText, n.contentSecondaryText, n.kickerText]\n .map(textOf)\n .filter((t): t is string => t !== undefined)\n .join(' · ');\n const at = typeof n.publishedAt === 'number' ? new Date(n.publishedAt).toISOString() : undefined;\n const url = absolute((n.cardAction as Node | null)?.actionTarget);\n const from = absolute((n.headerImage as Node | null)?.actionTarget);\n return {\n kind,\n text,\n ...(detail !== '' ? { detail } : {}),\n ...(at !== undefined ? { at } : {}),\n read: n.read === true,\n ...(url !== undefined ? { url } : {}),\n ...(from !== undefined ? { from } : {}),\n };\n}\n\nexport function parseNotifications(\n json: unknown,\n): { ok: true; items: Notification[]; unseen?: number; next?: number } | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const data = root?.data;\n const listed = data?.['*elements'] ?? data?.elements;\n if (!Array.isArray(listed)) return drift('the notifications answer carried no card list');\n const byUrn = new Map((root?.included ?? []).map((n) => [n.entityUrn, n]));\n const items = listed.flatMap((u) => {\n const n = byUrn.get(u);\n const c = n === undefined ? undefined : card(n);\n return c === undefined ? [] : [c];\n });\n if (listed.length > 0 && items.length === 0)\n return drift(`${listed.length} notifications were listed but none could be read`);\n const meta = (data?.metadata ?? {}) as Node;\n return {\n ok: true,\n items,\n ...(typeof meta.numUnseen === 'number' ? { unseen: meta.numUnseen } : {}),\n ...(typeof meta.nextStart === 'number' ? { next: meta.nextStart } : {}),\n };\n}\n","// ─── `lnrelay notifications` ──────────────────────────────────────────────────\n//\n// The owner's notifications, newest first; see engine/notifications.ts. One\n// page call per 25, following LinkedIn's next start. Reading them here does\n// not mark them seen.\n\nimport { createLiveClient } from '../engine/index.ts';\nimport {\n type Notification,\n notificationsUrl,\n parseNotifications,\n} from '../engine/notifications.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope, FetchState } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; json: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted GET. Injectable so tests send nothing. */\nexport type NotificationsFetch = (url: string, spendClass: 'page') => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): NotificationsFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('notifications', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, spendClass) => {\n const r = await client.request({ url, spendClass, operation: 'notifications' });\n return r.ok ? { ok: true, json: r.json } : r;\n };\n}\n\nexport interface NotificationsRequest {\n limit: number;\n /** Only the ones not yet read. */\n unread?: boolean;\n}\n\nconst PAGE = 25;\n\nconst compactNotification = (n: Notification) =>\n line([n.read ? undefined : 'unread', n.at, n.kind, n.text, n.detail, n.url]);\n\nexport async function runNotifications(\n req: NotificationsRequest,\n opts: OutputOpts = {},\n fetch?: NotificationsFetch,\n): Promise<Envelope> {\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n const limit = Math.max(1, req.limit);\n const items: Notification[] = [];\n let unseen: number | undefined;\n let start: number | undefined = 0;\n let stoppedBy: string | undefined;\n while (start !== undefined && items.length < limit) {\n const res = await get(notificationsUrl(PAGE, start), 'page');\n const page = res.ok ? parseNotifications(res.json) : res;\n if (!page.ok) {\n if (items.length === 0 && start === 0)\n return err('notifications', page.code, page.message, page.hint);\n stoppedBy = page.code;\n break;\n }\n unseen ??= page.unseen;\n items.push(...page.items.filter((n) => req.unread !== true || !n.read));\n start = page.next !== undefined && page.next > start ? page.next : undefined;\n }\n const kept = items.slice(0, limit);\n const state: FetchState =\n stoppedBy !== undefined || (start !== undefined && kept.length === limit)\n ? 'partial'\n : 'complete';\n return ok('notifications', {\n ...(unseen !== undefined ? { unseen } : {}),\n items: shape(kept, opts, compactNotification),\n meta: {\n state,\n operation: 'notifications',\n returnedCount: kept.length,\n ...(stoppedBy !== undefined ? { stoppedBy } : {}),\n },\n });\n}\n","// ─── A profile's contact info ─────────────────────────────────────────────────\n//\n// Captured 2026-10-16. The profile page's \"Contact info\" link opens an SDUI\n// overlay, one POST naming the member by public id and name; the legacy\n// identity/profiles/<id>/profileContactInfo answers 410 Gone. The overlay is\n// a list of labelled fields, most wrapped in a tracking spec that names the\n// field (`contact-email`, `contact-website`, `contact-birthday`); \"Connected\n// since\" has none, so fields are read by tracking name where there is one\n// and by label otherwise. Labels are in the session's language. A Premium\n// upsell follows the fields and is cut off before reading.\n//\n// Seen with data: email, websites, birthday, connected since. Phone, address,\n// Twitter and messenger fields are read by the names the others use and stay\n// unverified until one comes with data; any other field passes through.\n\nimport type { Failure } from './sdui-form.ts';\n\nconst SCREEN = 'com.linkedin.sdui.flagshipnav.profile.ProfileContactDetailsOverlay';\nexport const CONTACT_INFO_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/navigation?screenId=${SCREEN}&sduiid=${SCREEN}`;\n\nexport function contactInfoBody(publicId: string, firstName: string, lastName: string) {\n return {\n clientArguments: {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload: {\n vanityName: publicId,\n givenName: firstName,\n familyName: lastName,\n isVanityNameResolved: true,\n },\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n states: [],\n screenId: SCREEN,\n knownTemplateIds: [],\n },\n isModal: true,\n };\n}\n\nexport interface ContactInfo {\n email?: string;\n phones?: { number: string; type?: string }[];\n websites?: { url: string; type?: string }[];\n twitter?: string[];\n address?: string;\n birthday?: string;\n connectedSince?: string;\n /** Labelled fields with no tracking name, by their label. */\n other?: Record<string, string>;\n [field: string]: unknown;\n}\n\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst unquote = (s: string) => JSON.parse(`\"${s}\"`) as string;\n\nconst LABEL = /\\[\"\\$\",\"p\",null,\\{\"className\":\"[^\"]*\",\"children\":\\[\"((?:[^\"\\\\]|\\\\.)+)\"\\]\\}\\]/g;\nconst VIEW = /\"viewName\":\"contact-([a-z-]+)\"/g;\nconst LINK = /\"urlValue\":\\{\"\\$case\":\"url\",\"url\":\"((?:[^\"\\\\]|\\\\.)+)\"/g;\nconst TEXT = /\"children\":\\[\"((?:[^\"\\\\$]|\\\\.)(?:[^\"\\\\]|\\\\.)*)\"\\]/g;\nconst TYPE = /\"\\(([^\"()]+)\\)\"/g;\n\ninterface Field {\n label: string;\n view?: string;\n links: string[];\n texts: string[];\n types: string[];\n}\n\n/** Where a link goes: past LinkedIn's safety redirect and a mailto/tel scheme. */\nfunction target(link: string): string {\n const url = unquote(link);\n const away = url.match(/\\/safety\\/go\\/?\\?url=([^&]+)/)?.[1];\n if (away !== undefined) return decodeURIComponent(away);\n return url.replace(/^(mailto|tel):/, '');\n}\n\nfunction fieldsOf(stream: string): Field[] {\n const start = stream.indexOf('profile-contact-info-details-view');\n const upsell = stream.indexOf('\"viewName\":\"premium-upsell-card\"', start);\n const region = stream.slice(start, upsell === -1 ? undefined : upsell);\n const labels = [...region.matchAll(LABEL)];\n const fields: Field[] = [];\n let before = 0;\n labels.forEach((m, i) => {\n const at = m.index ?? 0;\n const end = at + m[0].length;\n const seg = region.slice(end, labels[i + 1]?.index ?? region.length);\n const view = [...region.slice(before, at).matchAll(VIEW)].pop()?.[1];\n fields.push({\n label: unquote(m[1] as string).trim(),\n view,\n links: [...seg.matchAll(LINK)].map((l) => target(l[1] as string)),\n texts: [...seg.matchAll(TEXT)].map((t) => unquote(t[1] as string).trim()),\n types: [...seg.matchAll(TYPE)].map((t) => t[1] as string),\n });\n before = end;\n });\n return fields;\n}\n\nconst camel = (s: string) => s.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());\n\nfunction put(contact: ContactInfo, f: Field): void {\n const text = f.texts.join(', ');\n switch (f.view) {\n case 'your-profile':\n return; // `profile` already has the profile URL.\n case 'email':\n contact.email = f.links[0] ?? text;\n return;\n case 'website':\n contact.websites = [\n ...(contact.websites ?? []),\n ...f.links.map((url, i) => (f.types[i] ? { url, type: f.types[i] } : { url })),\n ];\n return;\n case 'phone':\n contact.phones = [\n ...(contact.phones ?? []),\n ...f.texts.map((number, i) => (f.types[i] ? { number, type: f.types[i] } : { number })),\n ];\n return;\n case 'twitter':\n contact.twitter = [...(contact.twitter ?? []), ...f.texts];\n return;\n case undefined:\n if (/^connected since$/i.test(f.label)) contact.connectedSince = text;\n else contact.other = { ...contact.other, [f.label]: text };\n return;\n default:\n contact[camel(f.view)] = text;\n }\n}\n\nexport function parseContactInfo(stream: string): { ok: true; contact: ContactInfo } | Failure {\n if (!stream.includes('profile-contact-info-details-view'))\n return drift('the contact info answer was not the contact info overlay');\n const fields = fieldsOf(stream);\n if (fields.length === 0) return drift('the contact info overlay had no fields');\n const contact: ContactInfo = {};\n for (const f of fields) put(contact, f);\n return { ok: true, contact };\n}\n","// ─── A profile in full ────────────────────────────────────────────────────────\n//\n// Probed 2026-10-16. The GraphQL profile projection behind the top card has\n// no name; the REST profile finder with the FullProfileWithEntities\n// decoration has the name, About and every section of the profile page:\n//\n// identity/dash/profiles?q=memberIdentity&memberIdentity=<public id>\n//\n// Each section is a collection (`*profileSkills` → `*elements` → nodes in\n// `included`), and the collections' order is the page's order; `included`\n// is in no particular order. The profile holds the first 10 position groups\n// (a company with its roles) and 20 skills. The rest of the experience pages\n// through identity/dash/profilePositionGroups; skills did not (400), so their\n// total is reported instead.\n//\n// Certifications, languages, projects, courses, organizations, patents and\n// test scores were empty in every profile read so far; they are read by the\n// names the other sections use and stay unverified until one comes with data.\n\nimport { CONTRACTS } from './contracts.ts';\nimport type { Failure } from './sdui-form.ts';\n\ntype Node = Record<string, unknown>;\n\nfunction contract(name: 'fullProfile' | 'profilePositions') {\n const c = CONTRACTS[name];\n if (c?.decorationId === undefined) throw new Error(`the '${name}' contract is missing`);\n return c as typeof c & { decorationId: string };\n}\n\nexport function fullProfileUrl(memberId: string): string {\n const c = contract('fullProfile');\n return (\n `${c.path}?q=memberIdentity&memberIdentity=${encodeURIComponent(memberId)}` +\n `&decorationId=${c.decorationId}`\n );\n}\n\n/** Position groups per call when reading the rest of the experience. */\nexport const POSITIONS_PAGE = 50;\n\nexport function positionsPageUrl(profileUrn: string, start: number): string {\n const c = contract('profilePositions');\n return (\n `${c.path}?q=viewee&profileUrn=${encodeURIComponent(profileUrn)}` +\n `&decorationId=${c.decorationId}&start=${start}&count=${POSITIONS_PAGE}`\n );\n}\n\n// ─── Rows ─────────────────────────────────────────────────────────────────────\n\nexport interface Role {\n title?: string;\n company?: string;\n /** What `company`, `people --company` and `jobs --company` take. */\n companyId?: string;\n employmentType?: string;\n location?: string;\n /** \"2017-08\", or \"2017\" when the month is not given. */\n start?: string;\n end?: string;\n current?: boolean;\n description?: string;\n}\n\nexport interface School {\n school?: string;\n schoolId?: string;\n degree?: string;\n field?: string;\n start?: string;\n end?: string;\n grade?: string;\n activities?: string;\n description?: string;\n}\n\nexport type Entry = Record<string, string | boolean | undefined>;\n\nexport interface FullProfile {\n /** The profile id: what `messages`, `people --connection-of` take. */\n id: string;\n urn: string;\n publicId?: string;\n name?: string;\n firstName?: string;\n lastName?: string;\n headline?: string;\n url?: string;\n location?: string;\n industry?: string;\n about?: string;\n /** The top card, as `profile` always gave it: the newest role and school. */\n title?: string;\n company?: string;\n school?: string;\n premium?: boolean;\n influencer?: boolean;\n creator?: boolean;\n experience?: Role[];\n education?: School[];\n skills?: string[];\n certifications?: Entry[];\n languages?: Entry[];\n honors?: Entry[];\n publications?: Entry[];\n projects?: Entry[];\n volunteering?: Entry[];\n courses?: Entry[];\n organizations?: Entry[];\n patents?: Entry[];\n testScores?: Entry[];\n /** Sections LinkedIn holds more of than it sent: shown and total. */\n counts?: Record<string, { shown: number; total: number }>;\n}\n\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst str = (v: unknown) =>\n typeof v === 'string' && v.trim() !== '' && v.trim() !== '-' ? v.trim() : undefined;\nconst idOf = (urn: unknown) => String(urn ?? '').match(/:(\\d+)$/)?.[1];\n\nfunction defined<T extends object>(obj: T): T {\n for (const k of Object.keys(obj) as (keyof T)[]) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\n/** {year, month, day} as \"2017\", \"2017-08\" or \"2017-08-14\". */\nfunction date(v: unknown): string | undefined {\n const d = v as { year?: unknown; month?: unknown; day?: unknown } | null | undefined;\n if (typeof d?.year !== 'number') return undefined;\n const two = (n: number) => String(n).padStart(2, '0');\n if (typeof d.month !== 'number') return String(d.year);\n return typeof d.day === 'number'\n ? `${d.year}-${two(d.month)}-${two(d.day)}`\n : `${d.year}-${two(d.month)}`;\n}\n\nfunction range(v: unknown): { start?: string; end?: string; current?: boolean } {\n const r = v as { start?: unknown; end?: unknown } | null | undefined;\n const start = date(r?.start);\n const end = date(r?.end);\n return defined({\n start,\n end,\n current: start !== undefined && end === undefined ? true : undefined,\n });\n}\n\nclass Index {\n readonly byUrn: Map<unknown, Node>;\n constructor(included: Node[]) {\n this.byUrn = new Map(included.map((n) => [n.entityUrn, n]));\n }\n get(urn: unknown): Node | undefined {\n return typeof urn === 'string' ? this.byUrn.get(urn) : undefined;\n }\n /** The node as a list of one, or none. */\n list(urn: unknown): Node[] {\n const n = this.get(urn);\n return n === undefined ? [] : [n];\n }\n /** A collection's nodes, in its order, and how many LinkedIn says there are. */\n collection(urn: unknown): { nodes: Node[]; total?: number } {\n const c = this.get(urn);\n const refs = Array.isArray(c?.['*elements']) ? (c?.['*elements'] as unknown[]) : [];\n const nodes = refs.flatMap((r): Node[] => this.list(r));\n const total = (c?.paging as { total?: unknown } | undefined)?.total;\n return typeof total === 'number' ? { nodes, total } : { nodes };\n }\n}\n\nfunction role(p: Node, group: Node | undefined, ix: Index): Role {\n const companyUrn = p.companyUrn ?? group?.companyUrn;\n return defined({\n title: str(p.title),\n company: str(p.companyName) ?? str(group?.companyName),\n companyId: idOf(companyUrn),\n employmentType: str(ix.get(p['*employmentType'])?.name),\n location: str(p.locationName) ?? str(p.geoLocationName),\n ...range(p.dateRange),\n description: str(p.description),\n });\n}\n\n/** Position groups (a company and its roles) as one list of roles, in order. */\nfunction rolesOf(groups: Node[], ix: Index): Role[] {\n return groups.flatMap((g) => {\n const inGroup = ix.collection(g['*profilePositionInPositionGroup']).nodes;\n return inGroup.map((p) => role(p, g, ix));\n });\n}\n\nfunction school(e: Node): School {\n return defined({\n school: str(e.schoolName),\n schoolId: idOf(e.schoolUrn),\n degree: str(e.degreeName),\n field: str(e.fieldOfStudy),\n ...range(e.dateRange),\n grade: str(e.grade),\n activities: str(e.activities),\n description: str(e.description),\n });\n}\n\n/** The fields the other sections use, read off any section's node. */\nfunction entry(n: Node): Entry {\n const proficiency = str(n.proficiency);\n return defined({\n name: str(n.name),\n title: str(n.title),\n role: str(n.role),\n organization: str(n.companyName),\n authority: str(n.authority),\n issuer: str(n.issuer),\n publisher: str(n.publisher),\n proficiency: proficiency?.toLowerCase().replace(/_/g, ' '),\n number: str(n.number) ?? str(n.licenseNumber) ?? str(n.patentNumber),\n score: str(n.score),\n cause: str(n.cause)?.toLowerCase().replace(/_/g, ' '),\n ...range(n.dateRange),\n issued: date(n.issuedOn),\n published: date(n.publishedOn),\n url: str(n.url),\n description: str(n.description),\n });\n}\n\nconst SECTIONS = {\n certifications: '*profileCertifications',\n languages: '*profileLanguages',\n honors: '*profileHonors',\n publications: '*profilePublications',\n projects: '*profileProjects',\n volunteering: '*profileVolunteerExperiences',\n courses: '*profileCourses',\n organizations: '*profileOrganizations',\n patents: '*profilePatents',\n testScores: '*profileTestScores',\n} as const;\n\nconst some = <T>(xs: T[]) => (xs.length > 0 ? xs : undefined);\n\nexport function parseFullProfile(json: unknown): { ok: true; profile: FullProfile } | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const listed = root?.data?.['*elements'];\n if (!Array.isArray(listed)) return drift('the profile answer carried no profile list');\n if (listed.length === 0)\n return { ok: false, code: 'NOT_FOUND', message: 'no profile has that id on LinkedIn' };\n const ix = new Index(root?.included ?? []);\n const p = ix.get(listed[0]);\n const urn = typeof p?.entityUrn === 'string' ? p.entityUrn : undefined;\n if (p === undefined || urn === undefined) return drift('the profile was listed but not sent');\n\n const counts: Record<string, { shown: number; total: number }> = {};\n const count = (key: string, shown: number, total: number | undefined) => {\n if (total !== undefined && total > shown) counts[key] = { shown, total };\n };\n const groups = ix.collection(p['*profilePositionGroups']);\n count('experience', groups.nodes.length, groups.total);\n const experience = rolesOf(groups.nodes, ix);\n const schools = ix.collection(p['*profileEducations']);\n const education = schools.nodes.map(school);\n const skillNodes = ix.collection(p['*profileSkills']);\n count('skills', skillNodes.nodes.length, skillNodes.total);\n const skills = skillNodes.nodes.flatMap((s) => str(s.name) ?? []);\n\n const sections: Partial<Record<keyof typeof SECTIONS, Entry[]>> = {};\n for (const [key, field] of Object.entries(SECTIONS) as [keyof typeof SECTIONS, string][]) {\n const c = ix.collection(p[field]);\n count(key, c.nodes.length, c.total);\n const rows = c.nodes.map(entry);\n if (rows.length > 0) sections[key] = rows;\n }\n\n const publicId = str(p.publicIdentifier);\n const name = [str(p.firstName), str(p.lastName)].filter(Boolean).join(' ');\n const geo = ix.get((p.geoLocation as Node | undefined)?.['*geo']);\n const bool = (v: unknown) => (v === true ? true : undefined);\n return {\n ok: true,\n profile: defined({\n id: urn.split(':').pop() as string,\n urn,\n publicId,\n name: name === '' ? undefined : name,\n firstName: str(p.firstName),\n lastName: str(p.lastName),\n headline: str(p.headline),\n url: publicId === undefined ? undefined : `https://www.linkedin.com/in/${publicId}/`,\n location: str(geo?.defaultLocalizedName),\n industry: str(ix.get(p['*industry'])?.name),\n about: str(p.summary),\n title: experience[0]?.title,\n company: experience[0]?.company,\n school: education[0]?.school,\n premium: bool(p.premium),\n influencer: bool(p.influencer),\n creator: bool(p.creator),\n experience: some(experience),\n education: some(education),\n skills: some(skills),\n ...sections,\n counts: Object.keys(counts).length > 0 ? counts : undefined,\n }),\n };\n}\n\n/** The rest of the experience: more position groups, read as the profile reads them. */\nexport function parsePositionsPage(\n json: unknown,\n): { ok: true; experience: Role[]; groups: number; total?: number } | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const refs = root?.data?.['*elements'];\n if (!Array.isArray(refs)) return drift('the experience page carried no position groups');\n const ix = new Index(root?.included ?? []);\n const groups = refs.flatMap((r): Node[] => ix.list(r));\n if (refs.length > 0 && groups.length === 0)\n return drift(`${refs.length} position groups were listed but none sent`);\n const total = (root?.data?.paging as { total?: unknown } | undefined)?.total;\n return {\n ok: true,\n experience: rolesOf(groups, ix),\n groups: groups.length,\n ...(typeof total === 'number' ? { total } : {}),\n };\n}\n","// ─── A profile's recommendations ──────────────────────────────────────────────\n//\n// Captured 2026-10-29 from /in/<id>/details/recommendations/. The full profile\n// carries none; the details page draws them from a pager,\n// `pagers.profile.details.recommendations`, with a payload the profile read\n// already has: `{type: Received|Given, vanityName, profileId, start, count}`.\n//\n// Each recommendation is a header row (the recommender: their name, headline\n// and profile URL as the loading states it sets on click, their degree, and\n// the date-and-relationship line) and the text beside it, in fragments, some\n// in rows of their own. The first sits inline in the page's root row with\n// the others referenced after it; each other one has its own row. A\n// recommendation's text is what lies between its header and the next one's.\n// The date line comes in the session's language and is not split.\n\nimport { Rows } from './posts.ts';\nimport type { Failure } from './sdui-form.ts';\n\nconst PAGER = 'com.linkedin.sdui.pagers.profile.details.recommendations';\nconst SCREEN = 'com.linkedin.sdui.flagshipnav.profile.ProfileRecommendationDetails';\nexport const RECOMMENDATIONS_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/pagination?sduiid=${PAGER}`;\nexport const RECOMMENDATIONS_PAGE = 15;\n\nexport type RecommendationKind = 'received' | 'given';\n\nexport function recommendationsBody(\n kind: RecommendationKind,\n vanityName: string,\n profileId: string,\n start: number,\n) {\n const args = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload: {\n type: kind === 'received' ? 'Received' : 'Given',\n vanityName,\n profileId,\n start,\n detailScreenTabIndex: kind === 'received' ? '0' : '1',\n count: RECOMMENDATIONS_PAGE,\n },\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n return {\n pagerId: PAGER,\n clientArguments: { ...args, states: [], screenId: SCREEN, knownTemplateIds: [] },\n paginationRequest: {\n $type: 'proto.sdui.actions.requests.PaginationRequest',\n pagerId: PAGER,\n retryCount: 2,\n requestedArguments: args,\n },\n };\n}\n\nexport interface Recommendation {\n /** The recommender, or for given ones, the person recommended. */\n name: string;\n url?: string;\n headline?: string;\n degree?: string;\n /** When, and how they worked together, as LinkedIn words it. */\n context?: string;\n text: string;\n}\n\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst unquote = (s: string) => JSON.parse(`\"${s}\"`) as string;\nconst STR = '((?:[^\"\\\\\\\\]|\\\\\\\\.)+)';\nconst loading = (id: string) =>\n new RegExp(\n `\"id\":\"${id}\"\\\\}\\\\},\"namespace\":\"LoadingNamespace\"\\\\},\"value\":\\\\{\"\\\\$case\":\"stringValue\",\"stringValue\":\"${STR}\"`,\n );\nconst NAME = loading('profile_name_loading_state');\nconst HEADLINE = loading('profile_headline_loading_state');\nconst PROFILE_URL = /\"url\":\"(https:\\/\\/www\\.linkedin\\.com\\/in\\/[^\"]+)\"/;\nconst TEXT = /\"children\":\\[\"((?:[^\"\\\\$]|\\\\.)(?:[^\"\\\\]|\\\\.)*)\"\\]/g;\nconst FRAGMENT =\n /\\[\"\\$\",\"\\$9\",\"\\d+\",\\{\"children\":\\[(?:null|\\[\"\\$\",\"br\",null,\\{\\}\\]),\"((?:[^\"\\\\]|\\\\.)*)\"\\]/g;\nconst REF = /\"\\$L([0-9a-f]+)\"/g;\n/** A row referenced whole: lazily (`$L`) or as its value, as a long text is (`$18`). */\nconst ANY_REF = /\"\\$L?([0-9a-f]+)\"/g;\n\n/** The recommender, from their header row and what it references. */\nfunction header(rows: Rows, id: string) {\n const row = rows.byId.get(id) ?? '';\n const name = row.match(NAME)?.[1];\n if (name === undefined) return undefined;\n const headline = row.match(HEADLINE)?.[1];\n const all = rows\n .reach(id)\n .map((r) => rows.byId.get(r) ?? '')\n .join('\\n');\n const texts = [...all.matchAll(TEXT)].map((m) => unquote(m[1] as string).trim());\n const degree = texts.find((t) => t.startsWith('·'));\n const shown = new Set([unquote(name), headline === undefined ? '' : unquote(headline)]);\n const context = texts.filter((t) => t !== degree && !shown.has(t)).pop();\n const url = row.match(PROFILE_URL)?.[1];\n return {\n name: unquote(name).trim(),\n ...(url !== undefined ? { url } : {}),\n ...(headline !== undefined ? { headline: unquote(headline).trim() } : {}),\n ...(degree !== undefined ? { degree: degree.replace(/^·\\s*/, '') } : {}),\n ...(context !== undefined ? { context } : {}),\n };\n}\n\n/**\n * A stretch of a row with its text written in, so it reads in order: fragment\n * rows inlined, and a text row (a long recommendation) as the string it is.\n */\nfunction inlined(rows: Rows, segment: string, depth = 0): string {\n if (depth > 3) return segment;\n return segment.replace(ANY_REF, (ref, id: string) => {\n const row = rows.byId.get(id);\n if (row === undefined) return ref;\n if (rows.isText(id)) return JSON.stringify(row);\n return row.startsWith('[\"$\",\"$9\"') ? inlined(rows, row, depth + 1) : ref;\n });\n}\n\n/** The text: its fragments, or failing those its plain text lines. */\nfunction bodyOf(segment: string): string {\n const fragments = [...segment.matchAll(FRAGMENT)].map((m) => unquote(m[1] as string));\n const lines =\n fragments.length > 0\n ? fragments\n : [...segment.matchAll(TEXT)].map((m) => unquote(m[1] as string));\n return lines\n .map((l) => l.replace(/\\r/g, '').trimEnd())\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n\nexport function parseRecommendations(\n stream: string,\n): { ok: true; items: Recommendation[] } | Failure {\n if (!stream.includes('isPartialPage') && !stream.includes(PAGER))\n return drift('the recommendations answer was not the recommendations list');\n const rows = new Rows(stream);\n const headers = [...rows.byId]\n .filter(([, row]) => NAME.test(row) && !row.startsWith('[[\"$\"'))\n .map(([id]) => id);\n const heads = new Set(headers);\n // Where each header sits: the row that references it, and from where.\n const placed = headers.flatMap((h) => {\n for (const [id, row] of rows.byId) {\n const at = row.indexOf(`\"$L${h}\"`);\n if (at !== -1) return [{ h, row: id, at }];\n }\n return [];\n });\n // Rows that hold a header: an item's text stops where the next item starts.\n const holders = new Set(placed.map((p) => p.row));\n const items: Recommendation[] = [];\n for (const p of placed) {\n const row = rows.byId.get(p.row) ?? '';\n let end = row.length;\n for (const m of row.slice(p.at + 1).matchAll(REF)) {\n const id = m[1] as string;\n if (heads.has(id) || (holders.has(id) && id !== p.row)) {\n end = p.at + 1 + (m.index ?? 0);\n break;\n }\n }\n const who = header(rows, p.h);\n const text = bodyOf(inlined(rows, row.slice(p.at, end)));\n if (who !== undefined && text !== '') items.push({ ...who, text });\n }\n if (headers.length > 0 && items.length === 0)\n return drift(`${headers.length} recommendations were shown but none could be read`);\n return { ok: true, items };\n}\n","// ─── Editing the profile ──────────────────────────────────────────────────────\n//\n// Profile edits are SDUI forms. Voyager's partial update on\n// `identity/dash/profiles` answers 400 (mguttmann/linkedin-internal-api), and\n// the web client saves through `saveProfileIntroForm` / `saveProfileAboutForm`.\n//\n// The intro save sends the WHOLE form back — name, location, current\n// position, education, industry, website — not just the field that changed.\n// A body built by hand would have to know every one of those, and getting one\n// wrong moves the owner to another city. So, as with the comment menu\n// (sdui-menu.ts), nothing here is hand-built: the form is opened the way the\n// browser opens it, and the server's own save action and initial values are\n// sent back with exactly one value replaced. If the form changes shape, the\n// read changes with it.\n//\n// Captured 2026-10-13 by editing each field by one character in the browser\n// and reverting; tests/sdui-profile.test.ts rebuilds those saves byte-for-byte\n// from the form reads.\n\nimport type { Client } from './client.ts';\nimport {\n type Failure,\n findRequest,\n keysOf,\n type Model,\n type ModelValue,\n navBody,\n type RequestArgs,\n readModel,\n requestBody,\n responseErrors,\n wireStates,\n} from './sdui-form.ts';\n\nexport const NAV_URL = 'https://www.linkedin.com/flagship-web/rsc-action/actions/navigation';\nexport const ACTION_URL = 'https://www.linkedin.com/flagship-web/rsc-action/actions/server-request';\n\nexport interface ProfileField {\n name: 'headline' | 'about';\n /** The form's SDUI screen. */\n screen: string;\n /** The save action the form carries. */\n save: string;\n /** The save payload's property that binds this field's value. */\n binding: string;\n maxLength: number;\n}\n\nexport const PROFILE_FIELDS = {\n headline: {\n name: 'headline',\n screen: 'com.linkedin.sdui.flagshipnav.profile.ProfileEditIntroForm',\n save: 'com.linkedin.sdui.requests.profile.saveProfileIntroForm',\n binding: 'headline',\n // The web form refuses more (\"Exceeded maximum length of 220 characters\").\n maxLength: 220,\n },\n about: {\n name: 'about',\n screen: 'com.linkedin.sdui.flagshipnav.profile.ProfileAboutForm',\n save: 'com.linkedin.sdui.requests.profile.saveProfileAboutForm',\n binding: 'about',\n maxLength: 2600,\n },\n} as const satisfies Record<string, ProfileField>;\n\n/** Open a form as the browser does. A read, though it is issued as a POST. */\nexport function formNavBody(screen: string, vanityName: string) {\n return navBody(screen, { vanityName, isVanityNameResolved: true });\n}\n\nexport interface ProfileForm {\n ok: true;\n /** The save action's arguments, verbatim: which states it reads, and its payload. */\n args: RequestArgs;\n states: Model;\n screen: string;\n save: string;\n}\n\nexport const drift = (message: string): Failure => ({\n ok: false,\n code: 'SCHEMA_DRIFT',\n message,\n hint: 'Re-capture the profile form with scripts/observe-write.ts (edit one character, then revert).',\n});\n\nexport function readForm(stream: string, field: ProfileField): ProfileForm | Failure {\n const states = readModel(stream);\n if (states === null) return drift('the profile form carried no initial values');\n const args = findRequest(stream, field.save);\n if (args === null)\n return drift(`the profile form carried no ${field.save.split('.').pop()} action`);\n return { ok: true, args, states, screen: field.screen, save: field.save };\n}\n\n/** The state key a payload property is bound to, e.g. headline → headlineIntroForm. */\nfunction boundKey(form: ProfileForm, property: string): string | undefined {\n const ref = form.args.payload[property] as { key?: string } | undefined;\n return ref?.key;\n}\n\nexport function currentValue(form: ProfileForm, field: ProfileField): string | undefined {\n const key = boundKey(form, field.binding);\n const v = key === undefined ? undefined : form.states.get(key)?.value;\n return typeof v === 'string' ? v : undefined;\n}\n\n/**\n * The About save carries the top-skills list as an expression over a\n * client-side collection, which starts as `initialSkills` and is sent unchanged\n * when skills are not touched.\n */\nfunction topSkills(form: ProfileForm) {\n return (key: string): { ok: true; value: unknown } | Failure | undefined => {\n if (!key.endsWith('ReorderableSkillsFormBindingsskillIdsBinding')) return undefined;\n const initial = [...form.states.entries()].find(([k]) => k.startsWith('initialSkills'))?.[1];\n if (initial === undefined) return drift('the About form carried no initial top skills');\n // Only the empty list has been seen on the wire. Sending a guessed list could\n // clear the owner's top skills, so a non-empty one is refused until observed.\n if (!Array.isArray(initial.value) || initial.value.length > 0) {\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: 'your About section has top skills, and saving it with them has not been verified',\n hint: 'Edit About in the browser for now; nothing was changed.',\n };\n }\n return { ok: true, value: [] };\n };\n}\n\n/** The save the browser would send after the owner changed this one field. */\nexport function saveBody(\n form: ProfileForm,\n field: ProfileField,\n value: string,\n): { ok: true; body: Record<string, unknown> } | Failure {\n if (value.length > field.maxLength) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `the ${field.name} is ${value.length} characters; LinkedIn allows ${field.maxLength}`,\n };\n }\n const target = boundKey(form, field.binding);\n const current = target === undefined ? undefined : form.states.get(target);\n if (target === undefined || current === undefined) {\n return drift(`the profile form has no ${field.name} field`);\n }\n const model: Model = new Map(form.states);\n model.set(target, { ...(current as ModelValue), value });\n const states = wireStates(keysOf(form.args), model, topSkills(form));\n if (!Array.isArray(states)) return states;\n return { ok: true, body: requestBody(form.save, form.args, states, form.screen) };\n}\n\n/** Open the form for a field. */\nexport async function fetchProfileForm(\n field: ProfileField,\n vanityName: string,\n client: Client,\n): Promise<ProfileForm | Failure> {\n const stream = await openForm(\n field.screen,\n { vanityName, isVanityNameResolved: true },\n client,\n `profile-${field.name}-form`,\n );\n return typeof stream === 'string' ? readForm(stream, field) : stream;\n}\n\n/** POST a navigation and hand back the raw stream. */\nexport async function openForm(\n screen: string,\n payload: Record<string, unknown>,\n client: Client,\n operation: string,\n): Promise<string | Failure> {\n const result = await client.request({\n url: `${NAV_URL}?screenId=${screen}&sduiid=${screen}`,\n method: 'POST',\n body: navBody(screen, payload),\n spendClass: 'page',\n operation,\n });\n if (!result.ok) {\n const out: Failure = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n return (result.classification as { raw?: string }).raw ?? '';\n}\n\n/** POST a server action; the raw stream back, or why it failed. A 200 can carry errors. */\nexport async function sendAction(\n requestId: string,\n body: unknown,\n client: Client,\n operation: string,\n spendClass: 'write' | 'page' = 'write',\n): Promise<string | Failure> {\n const result = await client.request({\n url: `${ACTION_URL}?sduiid=${requestId}`,\n method: 'POST',\n body,\n spendClass,\n operation,\n });\n if (!result.ok) {\n const out: Failure = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n const raw = (result.classification as { raw?: string }).raw ?? '';\n const errors = responseErrors(raw);\n if (errors !== null) {\n return { ok: false, code: 'INVALID_INPUT', message: `LinkedIn refused it: ${errors}` };\n }\n return raw;\n}\n\n/** Send a save built by `saveBody`. */\nexport async function sendProfileSave(\n form: ProfileForm,\n body: Record<string, unknown>,\n client: Client,\n): Promise<{ ok: true } | Failure> {\n const r = await sendAction(form.save, body, client, 'profile-save');\n return typeof r === 'string' ? { ok: true } : r;\n}\n","// ─── Skills: listing, adding and removing ─────────────────────────────────────\n//\n// Captured 2026-10-14 by adding a free-text test skill in the browser. Unlike\n// a role, the add form carries its save (`saveProfileSkillForm`) directly; an\n// existing skill's form carries `deleteProfileSkillForm`. The list is a pager\n// (`pagers.profile.details.skills`) whose payload the Skills screen hands out.\n// A skill is added on its own: no links to roles, schools or projects.\n\nimport type { Client } from './client.ts';\nimport { Rows } from './posts.ts';\nimport {\n balanced,\n type Failure,\n findRequest,\n keysOf,\n type Model,\n type RequestArgs,\n readModel,\n requestBody,\n wireStates,\n} from './sdui-form.ts';\nimport { drift, openForm, sendAction } from './sdui-profile.ts';\n\nexport const SKILL = {\n addScreen: 'com.linkedin.sdui.flagshipnav.profile.ProfileSkillAddForm',\n editScreen: 'com.linkedin.sdui.flagshipnav.profile.ProfileSkillDetailsEditForm',\n listScreen: 'com.linkedin.sdui.flagshipnav.profile.ProfileSkillDetails',\n pager: 'com.linkedin.sdui.pagers.profile.details.skills',\n save: 'com.linkedin.sdui.requests.profile.saveProfileSkillForm',\n delete: 'com.linkedin.sdui.requests.profile.deleteProfileSkillForm',\n} as const;\n\nexport interface Skill {\n skillId: string;\n /** Null when the name could not be paired with its row for certain. */\n name: string | null;\n /** What the list opens this skill's form with. */\n payload: Record<string, unknown>;\n}\n\nconst EDIT_NAV = `{\"$type\":\"proto.sdui.actions.core.NavigateToScreen\",\"screenId\":\"${SKILL.editScreen}\"`;\nconst TEXT = /\"children\":\\[\"((?:[^\"\\\\]|\\\\.)*)\"\\]/g;\n\n/**\n * One page of skills. Each row's name is the single text node between the\n * previous row's edit action and its own; any other count leaves it null.\n */\nexport function skillsFromPage(stream: string): { ok: true; skills: Skill[] } | Failure {\n if (\n !stream.includes(SKILL.pager) &&\n !stream.includes(EDIT_NAV) &&\n !stream.includes('isPartialPage')\n ) {\n return drift('the skills page could not be read');\n }\n const skills: Skill[] = [];\n let from = 0;\n let i = 0;\n for (;;) {\n i = stream.indexOf(EDIT_NAV, i);\n if (i === -1) break;\n const text = balanced(stream, i);\n const end = i;\n i += EDIT_NAV.length;\n if (text === null) continue;\n const payload = (\n JSON.parse(text) as { requestedArguments?: { payload?: Record<string, unknown> } }\n ).requestedArguments?.payload;\n const id = payload?.skillId;\n if (typeof id !== 'string' || payload === undefined || skills.some((s) => s.skillId === id))\n continue;\n const names = [...stream.slice(from, end).matchAll(TEXT)].map(\n (m) => JSON.parse(`\"${m[1]}\"`) as string,\n );\n skills.push({ skillId: id, name: names.length === 1 ? (names[0] ?? null) : null, payload });\n from = end + text.length;\n }\n return { ok: true, skills };\n}\n\n// ─── Anyone's skills, by name ─────────────────────────────────────────────────\n//\n// Probed 2026-10-29 on another member's profile. Without edit actions the rows\n// are found by their component, `com.linkedin.sdui.profile.skill(<id>, N)`,\n// whose `initialContent` names the row that draws it; the skill's name is\n// that content's medium bold text. The full profile holds 20 skills; this\n// pager holds all of them, 10 a page.\n\nconst SKILL_COMPONENT =\n /\"componentKey\":\"com\\.linkedin\\.sdui\\.profile\\.skill\\([^)]+\\)\",\"children\":\\[\"\\$\",\"\\$L[0-9a-f]+\",\"[^\"]+\",\\{\"componentKey\":\"[^\"]+\",\"initialContent\":\"\\$L([0-9a-f]+)\"/g;\nconst SKILL_NAME =\n /\"fontSize\":\"medium\",\"fontStyle\":\"normal\",\"fontWeight\":\"bold\",\"lineHeight\":\"[^\"]*\",\"textAlign\":\"[^\"]*\",\"children\":\\[\"((?:[^\"\\\\]|\\\\.)+)\"\\]/;\n\n/** Each skill on a page, in order, by name. A row whose name cannot be found is left out. */\nexport function skillNamesOf(stream: string): string[] {\n const rows = new Rows(stream);\n return [...stream.matchAll(SKILL_COMPONENT)].flatMap((m) => {\n const name = rows\n .reach(m[1] as string)\n .map((r) => rows.byId.get(r)?.match(SKILL_NAME)?.[1])\n .find((n) => n !== undefined);\n return name === undefined ? [] : [JSON.parse(`\"${name}\"`) as string];\n });\n}\n\n/** How many skill rows a page draws, read or not. */\nexport function skillRowsOf(stream: string): number {\n return [...stream.matchAll(SKILL_COMPONENT)].length;\n}\n\n/** The \"All\" filter's first-page request, as the Skills screen hands it out. */\nexport function listPayloadOf(screen: string): Record<string, unknown> | null {\n const at = screen.indexOf('\"filter\":\"ProfileSkillCategory_ALL\"');\n const open = at === -1 ? -1 : screen.lastIndexOf('\"payload\":{', at);\n const text = open === -1 ? null : balanced(screen, open + '\"payload\":'.length);\n return text === null ? null : (JSON.parse(text) as Record<string, unknown>);\n}\n\n/** The pager request for the page starting at `start`, from the screen's own payload. */\nexport function pagerFrom(payload: Record<string, unknown>, start: number) {\n const args = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload: { ...payload, start },\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n return {\n pagerId: SKILL.pager,\n clientArguments: { ...args, states: [], screenId: SKILL.listScreen, knownTemplateIds: [] },\n paginationRequest: {\n $type: 'proto.sdui.actions.requests.PaginationRequest',\n pagerId: SKILL.pager,\n retryCount: 0,\n requestedArguments: args,\n },\n };\n}\n\nexport interface SkillForm {\n ok: true;\n model: Model;\n save: RequestArgs | null;\n del: RequestArgs | null;\n screen: string;\n}\n\nexport function readSkillForm(stream: string): SkillForm | Failure {\n const model = readModel(stream);\n if (model === null) return drift('the skill form carried no initial values');\n const save = findRequest(stream, SKILL.save);\n const del = findRequest(stream, SKILL.delete);\n if (save === null && del === null)\n return drift('the skill form carried neither a save nor a delete');\n return { ok: true, model, save, del, screen: del === null ? SKILL.addScreen : SKILL.editScreen };\n}\n\nconst nameKey = (model: Model) =>\n [...model.keys()].find((k) => k.startsWith('addSkillsTypeaheadSkillName'));\n\nexport function skillNameOf(form: SkillForm): string | null {\n const key = nameKey(form.model);\n const v = key === undefined ? undefined : form.model.get(key)?.value;\n return typeof v === 'string' ? v : null;\n}\n\n/** The add, as typed free text: no catalogue id, linked to nothing. */\nexport function addSkillBody(form: SkillForm, name: string): { ok: true; body: unknown } | Failure {\n if (name.trim() === '')\n return { ok: false, code: 'INVALID_INPUT', message: 'a skill needs a name' };\n if (form.save === null) return drift('this form has no save action (it is not the add form)');\n const key = nameKey(form.model);\n const current = key === undefined ? undefined : form.model.get(key);\n if (key === undefined || current === undefined) return drift('the skill form has no name field');\n const model: Model = new Map(form.model);\n model.set(key, { ...current, value: name.trim() });\n const states = wireStates(keysOf(form.save), model, () => undefined);\n if (!Array.isArray(states)) return states;\n return { ok: true, body: requestBody(SKILL.save, form.save, states, form.screen) };\n}\n\nexport function removeSkillBody(form: SkillForm): { ok: true; body: unknown } | Failure {\n if (form.del === null)\n return drift('this form has no delete action (it is not an existing skill)');\n const states = wireStates(keysOf(form.del), form.model, () => undefined);\n if (!Array.isArray(states)) return states;\n return { ok: true, body: requestBody(SKILL.delete, form.del, states, form.screen) };\n}\n\n// ─── Over the wire ────────────────────────────────────────────────────────────\n\nexport const PAGER_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/pagination?sduiid=${SKILL.pager}`;\nconst MAX_PAGES = 10;\n\n/** Every skill: the Skills screen for the pager's payload, then its pages. */\nexport async function fetchSkills(\n vanityName: string,\n client: Client,\n): Promise<{ ok: true; skills: Skill[] } | Failure> {\n const screen = await openForm(\n SKILL.listScreen,\n { vanityName, isVanityNameResolved: true },\n client,\n 'skills-screen',\n );\n if (typeof screen !== 'string') return screen;\n const payload = listPayloadOf(screen);\n if (payload === null) return drift('the Skills screen carried no list request');\n const count = typeof payload.count === 'number' ? payload.count : 10;\n\n const skills: Skill[] = [];\n for (let page = 0; page < MAX_PAGES; page++) {\n const result = await client.request({\n url: PAGER_URL,\n method: 'POST',\n body: pagerFrom(payload, skills.length),\n spendClass: 'page',\n operation: 'skills',\n });\n if (!result.ok) return { ok: false, code: result.code, message: result.message };\n const parsed = skillsFromPage((result.classification as { raw?: string }).raw ?? '');\n if (!parsed.ok) return parsed;\n const fresh = parsed.skills.filter((s) => !skills.some((k) => k.skillId === s.skillId));\n skills.push(...fresh);\n if (parsed.skills.length < count || fresh.length === 0) break;\n }\n return { ok: true, skills };\n}\n\nexport async function openSkillForm(\n payload: Record<string, unknown>,\n client: Client,\n edit: boolean,\n) {\n const stream = await openForm(\n edit ? SKILL.editScreen : SKILL.addScreen,\n { ...payload, isVanityNameResolved: true },\n client,\n edit ? 'skill-edit-form' : 'skill-add-form',\n );\n return typeof stream === 'string' ? readSkillForm(stream) : stream;\n}\n\nexport async function sendSkill(\n body: unknown,\n requestId: string,\n client: Client,\n): Promise<{ ok: true } | Failure> {\n const sent = await sendAction(\n requestId,\n body,\n client,\n requestId === SKILL.save ? 'skill-add' : 'skill-remove',\n );\n return typeof sent === 'string' ? { ok: true } : sent;\n}\n","// ─── `lnrelay profile <public-id|url|urn>` ────────────────────────────────────\n//\n// A profile in full; see engine/full-profile.ts. One call on the profile\n// budget, and one more per 50 position groups past the first 10, so the\n// experience is whole. `--contact` adds the contact info overlay, one more\n// call on the profile budget. `--posts N` adds their newest posts: the posts\n// search, filtered to posts from them, on the search budget. `--skills` reads\n// every skill past the top 20, from the Skills screen's own list, 10 a page\n// on the page budget. `--recommendations` reads those received and given, 15\n// a page on the page budget. `--compact` turns every role, school and entry into a\n// line and drops the descriptions; `--fields` keeps only the named fields.\n\nimport {\n CONTACT_INFO_URL,\n type ContactInfo,\n contactInfoBody,\n parseContactInfo,\n} from '../engine/contact-info.ts';\nimport {\n type Entry,\n type FullProfile,\n fullProfileUrl,\n POSITIONS_PAGE,\n parseFullProfile,\n parsePositionsPage,\n positionsPageUrl,\n type Role,\n type School,\n} from '../engine/full-profile.ts';\nimport { createLiveClient } from '../engine/index.ts';\nimport {\n parseRecommendations,\n RECOMMENDATIONS_PAGE,\n RECOMMENDATIONS_URL,\n type Recommendation,\n type RecommendationKind,\n recommendationsBody,\n} from '../engine/recommendations.ts';\nimport { navBody } from '../engine/sdui-form.ts';\nimport { NAV_URL } from '../engine/sdui-profile.ts';\nimport {\n listPayloadOf,\n PAGER_URL,\n pagerFrom,\n SKILL,\n skillNamesOf,\n skillRowsOf,\n} from '../engine/sdui-skill.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { project } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { runPostsSearch } from './posts-search.ts';\n\ntype Fetched =\n | { ok: true; json?: unknown; raw?: string }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted call: a POST when a body is given. Injectable so tests send nothing. */\nexport type ProfileFetch = (\n url: string,\n spendClass: 'profile' | 'search' | 'page',\n body?: unknown,\n) => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): ProfileFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('profile', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, spendClass, body) => {\n const r = await client.request({\n url,\n ...(body !== undefined ? { method: 'POST' as const, body } : {}),\n spendClass,\n operation: 'profile',\n });\n if (!r.ok) return r;\n return { ok: true, json: r.json, raw: (r.classification as { raw?: string }).raw ?? '' };\n };\n}\n\n/** A public id from itself or a /in/ URL (decoded), or a profile id from a urn. */\nexport function memberIdOf(input: string): string {\n const s = input.trim();\n const slug = s.match(/linkedin\\.com\\/in\\/([^/?#]+)/)?.[1];\n if (slug !== undefined) {\n try {\n return decodeURIComponent(slug);\n } catch {\n return slug;\n }\n }\n return s.match(/urn:li:fsd?_(?:mini)?[Pp]rofile:([^,)]+)/)?.[1] ?? s;\n}\n\ntype Read = FullProfile & {\n experienceError?: string;\n contact?: ContactInfo;\n contactError?: string;\n posts?: unknown[];\n postsError?: string;\n skillsError?: string;\n recommendations?: Record<RecommendationKind, Recommendation[]>;\n recommendationsError?: string;\n raw?: unknown;\n};\n\n/** Reads the position groups the profile did not hold, until all are in. */\nasync function readRestOfExperience(get: ProfileFetch, p: Read): Promise<void> {\n const want = p.counts?.experience;\n if (want === undefined) return;\n let start = want.shown;\n while (start < want.total) {\n const res = await get(positionsPageUrl(p.urn, start), 'profile');\n const page = res.ok ? parsePositionsPage(res.json) : res;\n if (!page.ok) {\n p.experienceError = `${page.code}: ${page.message}`;\n return;\n }\n p.experience = [...(p.experience ?? []), ...page.experience];\n start += page.groups;\n if (page.groups < POSITIONS_PAGE) break;\n }\n const counts = { ...p.counts };\n if (start >= want.total) delete counts.experience;\n else counts.experience = { shown: start, total: want.total };\n if (Object.keys(counts).length > 0) p.counts = counts;\n else delete p.counts;\n}\n\n/** The contact info overlay, which names the member by public id and name. */\nasync function readContact(get: ProfileFetch, p: Read): Promise<void> {\n if (p.publicId === undefined || p.firstName === undefined) {\n p.contactError = 'NOT_FOUND: the profile has no public id or name to ask with';\n return;\n }\n const body = contactInfoBody(p.publicId, p.firstName, p.lastName ?? '');\n const res = await get(CONTACT_INFO_URL, 'profile', body);\n const read = res.ok ? parseContactInfo(res.raw ?? '') : res;\n if (read.ok) p.contact = read.contact;\n else p.contactError = `${read.code}: ${read.message}`;\n}\n\n/** Skill pages at most: 10 skills each, and LinkedIn shows up to 100. */\nconst SKILL_PAGES = 10;\n\n/** Every skill, from the Skills screen's own list, in place of the profile's top 20. */\nasync function readAllSkills(get: ProfileFetch, p: Read): Promise<void> {\n const fail = (code: string, message: string) => {\n p.skillsError = `${code}: ${message}`;\n };\n if (p.publicId === undefined)\n return fail('NOT_FOUND', 'the profile has no public id to ask with');\n const screen = SKILL.listScreen;\n const nav = await get(\n `${NAV_URL}?screenId=${screen}&sduiid=${screen}`,\n 'page',\n navBody(screen, { vanityName: p.publicId, isVanityNameResolved: true }),\n );\n if (!nav.ok) return fail(nav.code, nav.message);\n const payload = listPayloadOf(nav.raw ?? '');\n if (payload === null) return fail('SCHEMA_DRIFT', 'the Skills screen carried no list request');\n const count = typeof payload.count === 'number' ? payload.count : 10;\n const total = p.counts?.skills?.total;\n const skills: string[] = [];\n let start = 0;\n for (let page = 0; page < SKILL_PAGES; page++) {\n const res = await get(PAGER_URL, 'page', pagerFrom(payload, start));\n if (!res.ok) return fail(res.code, res.message);\n const rows = skillRowsOf(res.raw ?? '');\n const names = skillNamesOf(res.raw ?? '');\n if (rows > names.length)\n return fail('SCHEMA_DRIFT', `${rows} skills were shown, ${names.length} read`);\n skills.push(...names);\n start += rows;\n if (rows < count || (total !== undefined && start >= total)) break;\n }\n if (skills.length === 0) return fail('SCHEMA_DRIFT', 'the skills list held no skills');\n p.skills = skills;\n const counts = { ...p.counts };\n if (total === undefined || skills.length >= total) delete counts.skills;\n else counts.skills = { shown: skills.length, total };\n if (Object.keys(counts).length > 0) p.counts = counts;\n else delete p.counts;\n}\n\n/** Pages of recommendations at most, each way: 15 a page. */\nconst RECOMMENDATION_PAGES = 10;\n\n/** Every recommendation they received and gave, from the details page's own list. */\nasync function readRecommendations(get: ProfileFetch, p: Read): Promise<void> {\n if (p.publicId === undefined) {\n p.recommendationsError = 'NOT_FOUND: the profile has no public id to ask with';\n return;\n }\n const out: Record<RecommendationKind, Recommendation[]> = { received: [], given: [] };\n for (const kind of ['received', 'given'] as const) {\n for (let page = 0; page < RECOMMENDATION_PAGES; page++) {\n const body = recommendationsBody(kind, p.publicId, p.id, out[kind].length);\n const res = await get(RECOMMENDATIONS_URL, 'page', body);\n const read = res.ok ? parseRecommendations(res.raw ?? '') : res;\n if (!read.ok) {\n p.recommendationsError = `${read.code}: ${read.message}`;\n return;\n }\n out[kind].push(...read.items);\n if (read.items.length < RECOMMENDATIONS_PAGE) break;\n }\n }\n p.recommendations = out;\n}\n\n/** Their newest posts onto the profile; a failure says why on the profile. */\nasync function readPosts(get: ProfileFetch, p: Read, n: number, compact: boolean): Promise<void> {\n const r = await runPostsSearch(\n { from: [p.id], sort: 'recent', limit: n },\n compact ? { compact: true } : {},\n async (url, body) => {\n const res = await get(url, 'search', body);\n return res.ok ? { ok: true, raw: res.raw ?? '' } : res;\n },\n );\n if (r.ok) p.posts = (r.data as { items: unknown[] }).items;\n else p.postsError = `${r.error.code}: ${r.error.message}`;\n}\n\nconst span = (x: { start?: string; end?: string; current?: boolean }) =>\n x.start === undefined && x.end === undefined\n ? undefined\n : `${x.start ?? '?'} – ${x.current === true ? 'now' : (x.end ?? '?')}`;\n\nconst roleLine = (r: Role) => line([r.title, r.company, span(r), r.employmentType, r.location]);\nconst schoolLine = (s: School) => line([s.school, s.degree, s.field, span(s)]);\nconst entryLine = (e: Entry) => {\n const { description: _d, url, ...rest } = e;\n const dates = span(e as { start?: string; end?: string; current?: boolean });\n const fields = Object.entries(rest)\n .filter(([k, v]) => !['start', 'end', 'current'].includes(k) && typeof v === 'string')\n .map(([, v]) => v as string);\n return line([...fields, dates, typeof url === 'string' ? url : undefined]);\n};\n\nconst LISTS = [\n 'certifications',\n 'languages',\n 'honors',\n 'publications',\n 'projects',\n 'volunteering',\n 'courses',\n 'organizations',\n 'patents',\n 'testScores',\n] as const;\n\n/** Every role, school and entry as one line; descriptions dropped. */\nfunction compact(p: Read): Record<string, unknown> {\n const out: Record<string, unknown> = { ...p };\n if (p.experience !== undefined) out.experience = p.experience.map(roleLine);\n if (p.education !== undefined) out.education = p.education.map(schoolLine);\n for (const key of LISTS) {\n const rows = p[key];\n if (rows !== undefined) out[key] = rows.map(entryLine);\n }\n return out;\n}\n\nexport async function runProfile(\n input: string | undefined,\n opts: OutputOpts = {},\n fetch?: ProfileFetch,\n req: { contact?: boolean; posts?: number; skills?: boolean; recommendations?: boolean } = {},\n): Promise<Envelope> {\n if (input === undefined || input.trim() === '')\n return err(\n 'profile',\n 'INVALID_INPUT',\n 'a public id, profile URL or urn is required',\n 'lnrelay profile <public-id|url|urn>',\n );\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n\n const res = await get(fullProfileUrl(memberIdOf(input)), 'profile');\n if (!res.ok) return err('profile', res.code, res.message, res.hint);\n const parsed = parseFullProfile(res.json);\n if (!parsed.ok) return err('profile', parsed.code, parsed.message, parsed.hint);\n const p: Read = parsed.profile;\n await readRestOfExperience(get, p);\n if (req.skills === true) await readAllSkills(get, p);\n if (req.recommendations === true) await readRecommendations(get, p);\n if (req.contact === true) await readContact(get, p);\n if (req.posts !== undefined && req.posts > 0)\n await readPosts(get, p, req.posts, opts.compact === true);\n\n if (opts.raw === true) return ok('profile', { ...p, raw: res.json });\n if (opts.fields !== undefined && opts.fields !== '')\n return ok('profile', project([p as unknown as Record<string, unknown>], opts.fields)[0]);\n return ok('profile', opts.compact === true ? compact(p) : p);\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 profile read (+1 per 50 companies past the first 10; --contact +1; --posts +1 search; --skills +1 page per 10; --recommendations +2 pages)',\n summary:\n 'A profile in full: name, headline, about, every role with dates and descriptions, ' +\n 'education, skills, honors, publications, volunteering and the other sections. ' +\n '--contact adds contact info: email, websites, phone, birthday, connected since. ' +\n '--posts N adds their N newest posts; --skills reads every skill past the top 20; ' +\n '--recommendations adds those they received and gave.',\n usage:\n 'lnrelay profile <public-id|profile-id|urn|url> [--contact] [--posts N] [--skills]\\n' +\n ' [--recommendations]\\n' +\n ' [--compact | --fields a,b,c] [--raw]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'search',\n cost: '1 search call per 50 results (posts: per 20); +1 per name looked up',\n summary:\n 'Search any kind the search box has: people, jobs, posts, companies, groups, events, ' +\n 'courses, products, services, schools. Several keyword sets merge by id.',\n usage:\n 'lnrelay search <kind> \"<keywords>\" [\"<more>\" ...] [filters] [--limit N] [--start N]\\n' +\n ' [--compact | --fields a,b,c]\\n' +\n ' kinds: people, jobs (their own flags: see `people`, `jobs`), posts, companies,\\n' +\n ' groups, events, courses, products, services, schools\\n' +\n ' companies, services: [--location \"<place>\"] [--network 1st,2nd,3rd+]\\n' +\n ' companies: [--industry <ids>] any kind: [--filter key=v1,v2 ...]\\n' +\n ' posts: [--sort recent|relevant] [--posted 24h|week|month]\\n' +\n ' [--type videos,images,jobs,live,articles,documents] [--posted-by 1st,me]\\n' +\n ' [--from <profile-id>] [--mentions <profile-id>] [--from-company \"<name|id>\"]\\n' +\n ' [--mentions-company \"<name|id>\"] [--author-company \"<name|id>\"]\\n' +\n ' [--author-industry <ids>] [--author-title \"<text>\"]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'search-filters',\n cost: '1 search call',\n summary:\n 'Every filter a search kind has for a query, with option ids and live counts: what ' +\n '`search <kind> --filter key=…` takes.',\n usage: 'lnrelay search-filters <kind> [\"<keywords>\"] [filters]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'people',\n cost: '1 search call per 50 people; +1 per company, school or place given by name',\n summary:\n 'People search with every filter LinkedIn has: company, past company, school, place, ' +\n 'degree, industry, title, connections of someone, … Several keyword sets merge by person.',\n usage:\n 'lnrelay people [\"<keywords>\" ...] [--company \"<name|id>\" ...] [--past-company \"<name|id>\" ...]\\n' +\n ' [--school \"<name|id>\" ...] [--location \"<place>\" | --geo <ids>] [--network 1st,2nd,3rd+]\\n' +\n ' [--industry <ids>] [--language en,de] [--service <ids>] [--title \"<text>\"]\\n' +\n ' [--first-name \"<text>\"] [--last-name \"<text>\"] [--company-text \"<text>\"]\\n' +\n ' [--school-text \"<text>\"] [--connection-of <profile-id>] [--follower-of <profile-id>]\\n' +\n ' [--open-to-volunteer] [--filter key=v1,v2 ...] [--limit N] [--start N]\\n' +\n ' [--compact | --fields a,b,c]\\n' +\n ' Names are looked up and data.resolved says what each became: check it.\\n' +\n ' LinkedIn pages at most 1000 people per query; meta.servedLimit says when it held back.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'people-filters',\n cost: '1 search call (+1 per name looked up)',\n summary:\n 'Every people filter for a query, with option ids and live counts: what `people` and ' +\n '--filter take.',\n usage: 'lnrelay people-filters [\"<keywords>\"] [people filters]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'jobs',\n cost: '1 job-search call per 100 jobs; --details adds 1 job read per 100 jobs',\n summary:\n 'Job search with every filter the jobs page has. Cards carry id, title, company, place, ' +\n 'workplace, listed date, Easy Apply. Read finalists with `job`.',\n usage:\n 'lnrelay jobs \"<keywords>\" [\"<more keywords>\" ...] [--location \"<place>\" | --geo <id>]\\n' +\n ' [--distance <miles>]\\n' +\n ' [--posted 24h|week|month|<N>h|<N>d] [--experience internship,entry,associate,\\n' +\n ' mid-senior,director,executive] [--type full-time,part-time,contract,temporary,\\n' +\n ' volunteer,internship,other] [--workplace on-site,remote,hybrid] [--easy-apply]\\n' +\n ' [--under-10] [--verified] [--in-network] [--fair-chance] [--company <ids>]\\n' +\n ' [--industry <ids>] [--function <codes>] [--title <ids>] [--place <geo-ids>]\\n' +\n ' [--filter key=v1,v2 ...] [--sort recent|relevant] [--limit N] [--start N]\\n' +\n ' [--details [--description]] [--compact | --fields a,b,c]\\n' +\n ' Ids for --company/--industry/--title/--place/--filter come from `job-filters`.\\n' +\n ' The resolved place is in data.location: check it, \"Vienna\" may resolve narrow.\\n' +\n 'lnrelay jobs --top-applicant [--limit N] [--details] [--compact | --fields a,b,c]\\n' +\n ' Premium: the jobs where LinkedIn says you would be a top applicant, 100 a call.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'job',\n cost: '1 job read per 100 jobs; --team adds 1 page call per job; --insights 1 job read per job',\n summary:\n 'Jobs in full: description, apply link (external or Easy Apply), applicants, state. ' +\n 'Several ids are read together, 100 a call. --team adds who posted it and who is hiring. ' +\n '--insights (Premium) adds who applied (count, last day, seniority, education) and the ' +\n \"company's insights: headcount over two years, the job's function, tenure, competitors.\",\n usage:\n 'lnrelay job <id|job-url> [<id|job-url> ...] [--team] [--insights] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'job-filters',\n cost: '1 job-search call',\n summary:\n 'Every job filter for a query, with option ids and live counts: what `jobs --filter` and ' +\n '--company/--industry/--title/--place take.',\n usage: 'lnrelay job-filters \"<keywords>\" [--location \"<place>\" | --geo <id>] [jobs filters]',\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: '1 page call per company; --posts adds search calls (20 posts a call)',\n summary:\n 'A company page in full: about, website, industry, size, employees on LinkedIn, followers, ' +\n 'headquarters, specialties, locations, affiliated and showcase pages. --posts N adds its ' +\n 'newest posts.',\n usage: 'lnrelay company <universal-name|url|id> [...] [--posts N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\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: 'my-items',\n cost: '1 page call per 10 items; jobs with no --stage read all 5 stages',\n summary:\n 'Your My items: saved posts, LinkedIn Learning courses, and the job tracker (saved, in ' +\n 'progress, applied, interview, archived).',\n usage:\n 'lnrelay my-items posts|learning|jobs [--stage saved|in-progress|applied|interview|archived]\\n' +\n ' [--limit N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'events',\n cost: '1 page call',\n summary:\n \"The events page's own lists: events recommended for you, and the Premium LinkedIn Live \" +\n 'events. Searching events by keyword is `search events`.',\n usage: 'lnrelay events [--premium] [--limit N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'event',\n cost: '1 page call per event',\n summary:\n 'Events in full: when (both ends, time zone), upcoming or past, online or where, the ' +\n \"event's own site, attendees, organiser, description.\",\n usage: 'lnrelay event <id|url> [<id|url> ...] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'notifications',\n cost: '1 page call per 25',\n summary:\n 'Your notifications, newest first: what each says, when, read or not, where it goes and ' +\n 'who it is about. Reading them here does not mark them seen.',\n usage: 'lnrelay notifications [--unread] [--limit N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'viewers',\n cost: '2 page calls',\n summary:\n 'Who viewed your profile, as your profile-views page shows it: the total for the period, ' +\n 'the viewers LinkedIn names (up to 3 on a free account, all with Premium), anonymous ones ' +\n 'as LinkedIn describes them, and how many looked in private mode. Premium adds a range ' +\n 'and highlights: top location, industry and company, and the companies viewers work at.',\n usage: 'lnrelay viewers [--days 7|14|28|90|365] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'network',\n cost: '1 page call per 50 rows; the counts are 7 calls',\n summary:\n 'Your My Network: connections, people you follow, followers, pages, events, groups, and ' +\n 'invitations you sent. With no list, the count of each. Read only.',\n usage:\n 'lnrelay network [connections|following|followers|pages|events|groups|invitations]\\n' +\n ' [--limit N] [--start N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'inbox',\n cost: '1 page call per 20 conversations',\n summary:\n 'Your conversations in a folder: who with, unread, last message. Reads only: nothing is ' +\n 'marked read or seen, and nothing read is stored.',\n usage:\n 'lnrelay inbox [--folder inbox|primary|other|archive|requests|spam] [--unread] [--limit N]\\n' +\n ' [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'messages',\n cost: '1 page call',\n summary:\n \"A conversation's latest messages, oldest first, saying which are yours. Reading does not \" +\n 'mark it read.',\n usage: 'lnrelay messages <conversation-id|thread-url> [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'draft',\n cost: '1 page call to check the conversation; the draft stays on this machine',\n summary:\n 'Draft a reply, saved locally with the conversation link for you to review and send. ' +\n 'Nothing is sent: this tool cannot send a message.',\n usage:\n 'lnrelay draft <conversation-id|thread-url> (\"<text>\" | --file <path>)\\n' +\n ' lnrelay draft remove <draft-id>',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'drafts',\n cost: 'free — local',\n summary: 'Your saved reply drafts, with the link to each conversation.',\n usage: 'lnrelay drafts [--compact]',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'scheduled',\n cost: '1 call per 10 posts',\n summary: 'Your posts waiting to publish, with when. Not in `my-posts` until they go out.',\n usage:\n 'lnrelay scheduled\\n' +\n ' Each row: urn (cancel with `delete`, change with `edit`), scheduledAt, text. Links in\\n' +\n ' the text show as lnkd.in short links, as LinkedIn lists them.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'experience',\n cost: '2 calls',\n summary: 'The roles on your own profile, with the position id `role edit|remove` takes.',\n usage: 'lnrelay experience',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'skills',\n cost: '3 calls',\n summary: 'The skills on your own profile, with the skill id `skill remove` takes.',\n usage: 'lnrelay skills',\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: 'approval',\n cost: 'free — local',\n summary:\n 'Show or set how writes are approved: interactive (a human at a terminal), agent (the ' +\n 'owner approves a --plan preview in chat), or unattended. Only a terminal can change it.',\n usage:\n 'lnrelay approval [show]\\n' +\n ' lnrelay approval set <interactive|agent|unattended>\\n' +\n ' Setting needs an interactive terminal and a typed token. Every approval and outcome\\n' +\n ' is appended to ~/.lnrelay/writes.jsonl.',\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>\" [--image <path> ... [--alt \"<text>\" ...] | --video <path>\\n' +\n ' | --document <pdf> --title \"<title>\"] [--at \"YYYY-MM-DD HH:MM\"]\\n' +\n ' [--poll \"<question>\" --option \"<a>\" --option \"<b>\" ... [--duration 1d|3d|1w|2w]]\\n' +\n ' [--visibility public|connections] [--via oauth|voyager] [--no-card]\\n' +\n ' [--plan | --confirm <token>]\\n' +\n ' Approval follows `lnrelay approval`: --plan previews and returns a token without\\n' +\n ' sending; --confirm <token> sends it in agent mode. In interactive mode it asks at a\\n' +\n ' terminal. --image repeats for up to 20, --alt pairs with it by position (--alt \"\"\\n' +\n ' skips one). --at schedules it (local time, or ISO 8601 with an offset; at least 10\\n' +\n ' minutes out); LinkedIn publishes it then, and `lnrelay delete <urn>` cancels it.\\n' +\n ' --poll takes 2-4 --option and cannot be scheduled yet. The first link in the text\\n' +\n ' gets the preview card LinkedIn would show (one extra read, named in the preview);\\n' +\n ' --no-card posts it as plain text. Files, documents, polls, cards and scheduling go\\n' +\n ' over the private API only.',\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 or post you wrote, your profile headline or About, or your ' +\n 'profile photo or cover image. Its ' +\n 'own verb, so a comment urn can never be mistaken for something to comment ON.',\n usage:\n 'lnrelay edit <comment-urn | share-urn | ugcPost-urn> \"<text>\"\\n' +\n ' lnrelay edit headline|about (\"<text>\" | --file <path>)\\n' +\n ' lnrelay edit photo|banner <image.png|jpg> (photo square, banner 4:1, max 8 MB)\\n' +\n ' A post is edited by the urn it was created as (`share` prints it; `my-posts` lists\\n' +\n ' it as shareUrn), not its activity urn. The whole text is replaced. A profile edit\\n' +\n ' shows the current text beside the new one, sends every other profile field back as\\n' +\n ' LinkedIn holds it, and reads the profile back to confirm. Headline max 220 characters.\\n' +\n ' An image is uploaded as it is, uncropped, and read back: it must be the one showing.',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'role',\n cost: '3-4 reads + 1 write',\n summary:\n 'Add, edit or remove a role in your Experience. Never rewrites your headline; notify network ' +\n 'is off unless --notify.',\n usage:\n 'lnrelay role add --title \"<t>\" --company \"<c>\" --start YYYY-MM [--end YYYY-MM | --current]\\n' +\n ' [--location \"<l>\"] [--description \"<d>\" | --description-file <path>] [--notify]\\n' +\n ' lnrelay role edit <position-id> [any of the flags above]\\n' +\n ' lnrelay role remove <position-id>\\n' +\n ' Position ids come from `lnrelay experience`. The preview shows the role as it is and\\n' +\n ' as it will be; the result is read back from the profile. A role with media attached\\n' +\n ' is refused. The company is free text (not linked to a company page).',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'skill',\n cost: '4-5 reads + 1 write',\n summary: 'Add a skill to your profile, or remove one.',\n usage:\n 'lnrelay skill add \"<name>\"\\n' +\n ' lnrelay skill remove <skill-id>\\n' +\n ' Skill ids come from `lnrelay skills`. A skill is added as free text, linked to no role,\\n' +\n ' school or project. Removing a skill removes its endorsements with it.',\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","// ─── Experience: adding, editing and removing a role ──────────────────────────\n//\n// Captured 2026-10-14 by adding a test role in the browser and deleting it.\n// Three things learned the hard way:\n//\n// 1. The save is not in the form. The form's Save fires `uploadPositionMedia`,\n// and the REPLY to that carries the `saveProfilePositionForm` action. So a\n// save is: open the form (read), send the media step, take the save from its\n// reply, send it.\n// 2. The add form defaults `dynamicallyCreateHeadline` to true. Saving the test\n// role replaced the owner's headline with \"<title> at <org>\", on the live\n// profile, unnoticed until the owner saw it. Here it is always false.\n// 3. \"Notify network\" (`allowProfileEditBroadcasts`) also defaults on in the\n// browser. Here it is off unless asked for.\n//\n// As with the intro and About (sdui-profile.ts), nothing is hand-built: every\n// value is the form's own, and only the fields asked for are replaced.\n\nimport type { Client } from './client.ts';\nimport {\n balanced,\n type Failure,\n findRequest,\n keysOf,\n type Model,\n type RequestArgs,\n readModel,\n requestBody,\n wireStates,\n} from './sdui-form.ts';\nimport { drift, openForm, sendAction } from './sdui-profile.ts';\n\nexport const POSITION = {\n addScreen: 'com.linkedin.sdui.flagshipnav.profile.ProfilePositionAddForm',\n editScreen: 'com.linkedin.sdui.flagshipnav.profile.ProfilePositionDetailsEditForm',\n listScreen: 'com.linkedin.sdui.flagshipnav.profile.ProfileExperienceDetails',\n media: 'com.linkedin.sdui.impl.profile.components.forms.uploadPositionMedia',\n save: 'com.linkedin.sdui.requests.profile.saveProfilePositionForm',\n delete: 'com.linkedin.sdui.requests.profile.deleteProfilePositionForm',\n} as const;\n\nexport interface Position {\n positionId: string;\n title: string;\n /** What the Experience list opens this role's edit form with. */\n payload: Record<string, unknown>;\n}\n\nconst EDIT_NAV = `{\"$type\":\"proto.sdui.actions.core.NavigateToScreen\",\"screenId\":\"${POSITION.editScreen}\"`;\n\n/** Every role on the Experience screen, with the id it is edited by. */\nexport function listPositions(stream: string): { ok: true; positions: Position[] } | Failure {\n if (readModel(stream) === null && !stream.includes(EDIT_NAV) && !stream.includes('\"rows\"')) {\n return drift('the Experience screen could not be read');\n }\n const positions: Position[] = [];\n const seen = new Set<string>();\n let i = 0;\n for (;;) {\n i = stream.indexOf(EDIT_NAV, i);\n if (i === -1) break;\n const text = balanced(stream, i);\n i += EDIT_NAV.length;\n if (text === null) continue;\n const payload = (\n JSON.parse(text) as { requestedArguments?: { payload?: Record<string, unknown> } }\n ).requestedArguments?.payload;\n const id = payload?.positionId;\n if (typeof id !== 'string' || seen.has(id) || payload === undefined) continue;\n seen.add(id);\n positions.push({ positionId: id, title: String(payload.title ?? ''), payload });\n }\n if (positions.length === 0 && !stream.includes('\"rows\"') && !stream.includes('Experience')) {\n return drift('the Experience screen listed no roles and did not look like one');\n }\n return { ok: true, positions };\n}\n\nexport interface PositionForm {\n ok: true;\n model: Model;\n /** Shared by every field key: `auto-binding-<uuid>ProfilePositionForm`. */\n prefix: string;\n media: RequestArgs;\n del: RequestArgs | null;\n screen: string;\n}\n\nexport function readPositionForm(stream: string): PositionForm | Failure {\n const model = readModel(stream);\n if (model === null) return drift('the position form carried no initial values');\n const media = findRequest(stream, POSITION.media);\n const prefix = media?.payload.formIdPrefix;\n if (media === null || typeof prefix !== 'string') {\n return drift('the position form carried no save step (uploadPositionMedia)');\n }\n const del = findRequest(stream, POSITION.delete);\n return {\n ok: true,\n model,\n prefix,\n media,\n del,\n screen: del === null ? POSITION.addScreen : POSITION.editScreen,\n };\n}\n\nexport interface YearMonth {\n month: number;\n year: number;\n}\n\nexport interface PositionChanges {\n title?: string;\n company?: string;\n description?: string;\n location?: string;\n start?: YearMonth;\n /** `present` marks it a current role. */\n end?: YearMonth | 'present';\n /** Tell the network about it. Off unless asked. */\n notify?: boolean;\n}\n\nconst date = (d: YearMonth) => ({\n $type: 'proto.sdui.common.Date',\n day: 0,\n month: d.month,\n year: d.year,\n});\nconst ym = (v: unknown) => {\n const d = v as { month?: number; year?: number } | undefined;\n return d?.year ? `${d.year}-${String(d.month ?? 0).padStart(2, '0')}` : null;\n};\n\n/** The form's values with the asked-for changes, and the two safety overrides. */\nexport function applyChanges(\n form: PositionForm,\n changes: PositionChanges,\n): { ok: true; model: Model } | Failure {\n const model: Model = new Map(form.model);\n const set = (field: string, value: unknown) => {\n const key = `${form.prefix}${field}`;\n const current = model.get(key);\n if (current === undefined) return false;\n model.set(key, { ...current, value });\n return true;\n };\n const missing: string[] = [];\n const need = (field: string, value: unknown) => {\n if (!set(field, value)) missing.push(field);\n };\n\n if (changes.title !== undefined) need('title', changes.title);\n if (changes.description !== undefined) need('description', changes.description);\n if (changes.location !== undefined) need('location', changes.location);\n if (changes.company !== undefined) {\n // Free text: not linked to a company page, as when typed without picking one.\n need('companyName', changes.company);\n need('organizationId', -1);\n need('organizationEntityId', { type: 'bigint', value: '-1' });\n }\n if (changes.start !== undefined) need('startDate', date(changes.start));\n if (changes.end === 'present') need('isCurrentPosition', true);\n else if (changes.end !== undefined) {\n need('isCurrentPosition', false);\n need('endDate', date(changes.end));\n }\n need('dynamicallyCreateHeadline', false);\n need('allowProfileEditBroadcasts', changes.notify === true);\n if (missing.length > 0) return drift(`the position form has no ${missing.join(', ')} field`);\n\n const s = roleSummary(model);\n if (!s.current && s.start !== null && s.end !== null && s.end < s.start) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `the role ends (${s.end}) before it starts (${s.start})`,\n };\n }\n return { ok: true, model };\n}\n\n/** What a role says now, for the preview. */\nexport function roleSummary(model: Model) {\n const get = (field: string) =>\n [...model.entries()].find(([k]) => k.endsWith(`ProfilePositionForm${field}`))?.[1].value;\n const current = get('isCurrentPosition') === true;\n return {\n title: String(get('title') ?? ''),\n company: String(get('companyName') ?? ''),\n start: ym(get('startDate')),\n end: current ? null : ym(get('endDate')),\n current,\n location: String(get('location') ?? ''),\n description: String(get('description') ?? ''),\n };\n}\n\n/** Media on a role is a computed list nothing here has observed; refuse rather than drop it. */\nfunction noMedia(model: Model): Failure | null {\n const count = [...model.entries()].find(([k]) =>\n k.endsWith('position-mediaUiCollection-mediaCount'),\n )?.[1].value;\n return typeof count === 'number' && count > 0\n ? {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: 'this role has media attached, and saving one with media has not been verified',\n hint: 'Edit it in the browser for now; nothing was changed.',\n }\n : null;\n}\n\nconst resolver = (key: string) =>\n key.endsWith('position-mediaIds') ? { ok: true as const, value: [] } : undefined;\n\n/** The media step the browser sends on Save; its reply carries the save. */\nexport function mediaBody(form: PositionForm, model: Model): { ok: true; body: unknown } | Failure {\n const refused = noMedia(model);\n if (refused !== null) return refused;\n const states = wireStates(keysOf(form.media), model, resolver);\n if (!Array.isArray(states)) return states;\n return { ok: true, body: requestBody(POSITION.media, form.media, states, form.screen) };\n}\n\nexport function saveFromReply(reply: string): { ok: true; args: RequestArgs } | Failure {\n const args = findRequest(reply, POSITION.save);\n return args === null\n ? drift('the media step did not hand back the save action')\n : { ok: true, args };\n}\n\n/** The save, from the action the media step returned. */\nexport function positionSaveBody(\n save: RequestArgs,\n model: Model,\n screen: string,\n): { ok: true; body: unknown } | Failure {\n // The browser flips its \"saving\" flag on before the request leaves; mirror it.\n const sending: Model = new Map(model);\n for (const [k, v] of sending)\n if (k.endsWith('isActiveProfileFormLoading')) sending.set(k, { ...v, value: true });\n const states = wireStates(keysOf(save), sending, resolver);\n if (!Array.isArray(states)) return states;\n return { ok: true, body: requestBody(POSITION.save, save, states, screen) };\n}\n\nexport function deleteBody(form: PositionForm): { ok: true; body: unknown } | Failure {\n if (form.del === null)\n return drift('this form has no delete action (it is not an existing role)');\n const states = wireStates(keysOf(form.del), form.model, resolver);\n if (!Array.isArray(states)) return states;\n return { ok: true, body: requestBody(POSITION.delete, form.del, states, form.screen) };\n}\n\n// ─── Over the wire ────────────────────────────────────────────────────────────\n\nexport async function fetchPositions(vanityName: string, client: Client) {\n const stream = await openForm(\n POSITION.listScreen,\n { vanityName, isVanityNameResolved: true },\n client,\n 'experience-list',\n );\n return typeof stream === 'string' ? listPositions(stream) : stream;\n}\n\nexport async function openPositionForm(\n payload: Record<string, unknown>,\n client: Client,\n edit: boolean,\n): Promise<PositionForm | Failure> {\n const stream = await openForm(\n edit ? POSITION.editScreen : POSITION.addScreen,\n { ...payload, isVanityNameResolved: true },\n client,\n edit ? 'position-edit-form' : 'position-add-form',\n );\n return typeof stream === 'string' ? readPositionForm(stream) : stream;\n}\n\n/** Media step, then the save it hands back. */\nexport async function sendPositionSave(\n form: PositionForm,\n model: Model,\n client: Client,\n): Promise<{ ok: true } | Failure> {\n const media = mediaBody(form, model);\n if (!media.ok) return media;\n const reply = await sendAction(POSITION.media, media.body, client, 'position-media-step', 'page');\n if (typeof reply !== 'string') return reply;\n const save = saveFromReply(reply);\n if (!save.ok) return save;\n const body = positionSaveBody(save.args, model, form.screen);\n if (!body.ok) return body;\n const sent = await sendAction(POSITION.save, body.body, client, 'position-save');\n return typeof sent === 'string' ? { ok: true } : sent;\n}\n\nexport async function sendPositionDelete(\n form: PositionForm,\n client: Client,\n): Promise<{ ok: true } | Failure> {\n const body = deleteBody(form);\n if (!body.ok) return body;\n const sent = await sendAction(POSITION.delete, body.body, client, 'position-delete');\n return typeof sent === 'string' ? { ok: true } : sent;\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, MIN_GAP_MS, spend, summarise } from '../engine/budget.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport { auditApproval } from './approval.ts';\nimport { type ConfirmDeps, canApprove, 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/**\n * For commands that must READ before they can ask (comment harvests the post\n * page, delete reads the comment menu): refuse up front when this invocation\n * cannot end in an approval, so it causes no LinkedIn traffic it cannot use.\n */\nexport function refuseUnapprovable(\n command: string,\n action: string,\n deps: ConfirmDeps,\n): Envelope | null {\n if (canApprove(deps)) return null;\n return deps.approval?.mode === 'agent'\n ? err(\n command,\n 'CONFIRMATION_REQUIRED',\n `${action} needs the owner's approval of this exact content`,\n 'Nothing was sent and no network call was made. Run the same command with --plan, show ' +\n 'the preview to the owner, and when they approve re-run it with --confirm <token>.',\n )\n : err(\n command,\n 'CONFIRMATION_REQUIRED',\n `${action} 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/** 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, calls = 1): Envelope | null {\n // Simulated on a copy and never saved: this asks, the client accounts.\n let current = ledger();\n for (let i = 0; i < calls; i++) {\n // The client paces calls at least MIN_GAP_MS apart; simulate that too.\n const attempt = spend(current, 'write', now + i * MIN_GAP_MS);\n if ('error' in attempt) {\n return err(command, attempt.error.code, attempt.error.message, attempt.error.hint);\n }\n current = attempt.ledger;\n }\n return 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 // A plan is a success: the preview IS the result. Nothing is spent or sent.\n if (!outcome.ok && outcome.code === 'PLANNED') {\n return ok(command, {\n planned: true,\n token: outcome.token,\n preview: outcome.preview,\n next: `show this to the owner; on their approval re-run the same command with --confirm ${outcome.token}`,\n });\n }\n if (!outcome.ok) return err(command, outcome.code, outcome.message, outcome.hint);\n auditApproval(\n command,\n deps.approval?.mode ?? 'interactive',\n plan.summary,\n outcome.confirmed.token,\n );\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","// ─── How writes are approved, and the record of what was written ─────────────\n//\n// The mode lives in ~/.lnrelay/config.json and ONLY `lnrelay approval set`\n// writes it — at a terminal, behind a typed token. That is the property the\n// agent and unattended modes rest on: an agent can use whatever mode the owner\n// chose, but cannot choose it. See confirm.ts for what each mode lets through.\n//\n// Every approval and every outcome is appended to ~/.lnrelay/writes.jsonl, so\n// what an agent did under the owner's name can be read back afterwards.\n\nimport { appendFileSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport { APPROVAL_MODES, type ApprovalMode, type ConfirmDeps, confirmToken } from './confirm.ts';\n\nconst MEANING: Record<ApprovalMode, string> = {\n interactive: 'every write waits for a human to type a token at a terminal',\n agent:\n 'an agent may write after the owner approves the exact content: --plan to preview, ' +\n '--confirm <token> once they say so',\n unattended:\n 'agents may write without asking; budget caps, cooldowns and the audit log still apply',\n};\n\nconst isMode = (v: unknown): v is ApprovalMode =>\n typeof v === 'string' && (APPROVAL_MODES as readonly string[]).includes(v);\n\n/**\n * The owner's chosen mode. Absent means interactive. Anything unreadable is an\n * error — never a guess — because guessing wrong in the permissive direction\n * publishes under someone's name without their approval.\n */\nexport function loadApprovalMode():\n | { ok: true; mode: ApprovalMode }\n | { ok: false; message: string; hint: string } {\n const loaded = loadJson<{ approval?: unknown }>(cachePath('config.json'));\n if (loaded.state === 'missing') return { ok: true, mode: 'interactive' };\n if (loaded.state === 'corrupt') {\n return {\n ok: false,\n message: 'the approval setting was unreadable and has been quarantined',\n hint: `Moved to ${loaded.quarantinedTo}. Writes fall back to interactive from the next run; set another mode with \\`lnrelay approval set\\`.`,\n };\n }\n const mode = loaded.value.approval ?? 'interactive';\n if (!isMode(mode)) {\n return {\n ok: false,\n message: `unknown approval mode '${String(mode)}' in config.json`,\n hint: `one of: ${APPROVAL_MODES.join(', ')}. Set it with \\`lnrelay approval set <mode>\\`.`,\n };\n }\n return { ok: true, mode };\n}\n\n/** The token that confirms switching to a mode. Differs per mode. */\nexport function setToken(mode: ApprovalMode): string {\n return confirmToken('set approval mode', mode);\n}\n\nfunction append(entry: Record<string, unknown>): void {\n const path = cachePath('writes.jsonl');\n mkdirSync(dirname(path), { recursive: true });\n appendFileSync(path, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\\n`, {\n mode: 0o600,\n });\n}\n\n/** Whether this process approved a write — so its outcome belongs in the log. */\nlet approvedInThisRun = false;\nexport function wasApproved(): boolean {\n return approvedInThisRun;\n}\n\nexport function auditApproval(\n command: string,\n mode: ApprovalMode,\n summary: string[],\n token: string,\n): void {\n approvedInThisRun = true;\n append({ event: 'approved', command, mode, summary, token });\n}\n\nexport function auditOutcome(command: string, mode: ApprovalMode, envelope: Envelope): void {\n append(\n envelope.ok\n ? { event: 'outcome', command, mode, ok: true, data: envelope.data }\n : { event: 'outcome', command, mode, ok: false, error: envelope.error },\n );\n}\n\nexport function runApprovalShow(): Envelope {\n const loaded = loadApprovalMode();\n if (!loaded.ok) return err('approval', 'CACHE_CORRUPT', loaded.message, loaded.hint);\n return ok('approval', {\n mode: loaded.mode,\n meaning: MEANING[loaded.mode],\n audit: cachePath('writes.jsonl'),\n });\n}\n\n/** Switch mode. Needs a human at a terminal, like the writes it governs. */\nexport async function runApprovalSet(\n mode: string | undefined,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n if (!isMode(mode)) {\n return err(\n 'approval',\n 'INVALID_INPUT',\n `unknown approval mode '${mode ?? ''}'`,\n `one of: ${APPROVAL_MODES.map((m) => `${m} (${MEANING[m]})`).join('; ')}`,\n );\n }\n if (!deps.isTty) {\n return err(\n 'approval',\n 'CONFIRMATION_REQUIRED',\n 'the approval mode can only be changed by a human at an interactive terminal',\n 'Nothing was changed. An agent cannot choose how its own writes are approved.',\n );\n }\n\n const token = setToken(mode);\n const answer = (\n await deps.prompt(\n [\n '',\n ` SET LINKEDIN WRITE APPROVAL TO: ${mode.toUpperCase()}`,\n ` ${MEANING[mode]}`,\n '',\n ` Type ${token} to confirm, anything else to abort: `,\n ].join('\\n'),\n )\n ).trim();\n if (answer !== token) {\n return err('approval', 'CONFIRMATION_REQUIRED', 'aborted — nothing was changed');\n }\n\n const current = loadJson<Record<string, unknown>>(cachePath('config.json'));\n saveJson(cachePath('config.json'), {\n ...(current.state === 'ok' ? current.value : {}),\n approval: mode,\n });\n append({ event: 'mode', mode });\n return ok('approval', { mode, meaning: MEANING[mode] });\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.\n//\n// APPROVAL MODES (decided 2026-09-25, docs/DECISION-writes.md §9). The owner's\n// personal agents must be able to act on \"post it\" said in chat, and, if the\n// owner chooses, to manage the account on their own. So a write is approved by\n// whichever of these the OWNER has selected:\n//\n// interactive (default) a human types the token at a terminal — as above\n// agent `--plan` returns the preview + token without sending; the agent\n// shows it to the owner and, on their word, re-runs with\n// `--confirm <token>`. The token binds the approval to the exact\n// content previewed: edit anything and it no longer matches.\n// unattended no approval step; budget, cooldown and the audit log still apply\n//\n// The mode is a file only `lnrelay approval set` writes, and that command needs\n// a terminal and a typed token — so an agent cannot promote itself. In agent\n// mode the token is a content binding, not an authentication: the agent is\n// trusted to relay the owner's word, and the audit log records what it sent.\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 type ApprovalMode = 'interactive' | 'agent' | 'unattended';\n\nexport const APPROVAL_MODES: readonly ApprovalMode[] = ['interactive', 'agent', 'unattended'];\n\nexport interface WritePlan<T> {\n action: string;\n payload: T;\n /**\n * What the token is derived from, when the payload holds values that change\n * between runs (a comment's per-render trackingId). Defaults to the payload.\n */\n tokenBasis?: unknown;\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\n/** The token for a plan: over its stable basis when it names one. */\nexport function planToken<T>(plan: WritePlan<T>): string {\n return confirmToken(plan.action, plan.tokenBasis ?? plan.payload);\n}\n\n/** The plan as lines, without the prompt — shared by the prompt and `--plan`. */\nexport function previewLines<T>(plan: WritePlan<T>, budgetLine: string): string[] {\n return [\n `ABOUT TO ${plan.action.toUpperCase()} ON LINKEDIN`,\n ...plan.summary,\n `via ${plan.transport === 'oauth' ? 'official OAuth (w_member_social)' : 'Voyager (private API)'}`,\n `undo ${plan.reversibility}`,\n ...riskLines(plan.transport).map((l) => l.trim()),\n budgetLine,\n ];\n}\n\nexport function renderPlan<T>(plan: WritePlan<T>, budgetLine: string): string {\n const token = planToken(plan);\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 ApprovalRequest {\n mode: ApprovalMode;\n /** `--confirm <token>`: the token `--plan` returned. */\n token?: string | undefined;\n /** `--plan`: preview and token only; nothing is sent. */\n planOnly?: boolean | undefined;\n}\n\nexport interface ConfirmDeps {\n isTty: boolean;\n prompt: (question: string) => Promise<string>;\n write: (s: string) => void;\n /** Absent means interactive with no flags — the pre-2026-09-25 behaviour. */\n approval?: ApprovalRequest;\n}\n\nexport type ConfirmOutcome<T> =\n | { ok: true; confirmed: ConfirmedWrite<T> }\n | { ok: false; code: 'CONFIRMATION_REQUIRED'; message: string; hint: string }\n | { ok: false; code: 'PLANNED'; token: string; preview: string[] };\n\n/**\n * Whether this invocation could end in an approval (or a plan). Commands that\n * must read before they can ask — comment harvests the post page — check this\n * first, so a request that can only be refused makes no network call.\n */\nexport function canApprove(deps: ConfirmDeps): boolean {\n const a = deps.approval ?? { mode: 'interactive' };\n if (a.planOnly === true || a.mode === 'unattended') return true;\n if (a.mode === 'agent' && a.token !== undefined) return true;\n return deps.isTty;\n}\n\nconst refuse = (message: string, hint: string) =>\n ({ ok: false, code: 'CONFIRMATION_REQUIRED', message, hint }) as const;\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 const a = deps.approval ?? { mode: 'interactive' };\n const token = planToken(plan);\n const mint = (): ConfirmOutcome<T> => ({\n ok: true,\n confirmed: { action: plan.action, payload: plan.payload, token } as ConfirmedWrite<T>,\n });\n\n if (a.planOnly === true) {\n return { ok: false, code: 'PLANNED', token, preview: previewLines(plan, budgetLine) };\n }\n\n if (a.token !== undefined) {\n if (a.mode === 'interactive') {\n return refuse(\n `--confirm is not accepted in interactive approval mode; nothing was sent`,\n 'In this mode only a human at a terminal approves a write. The owner can allow agents ' +\n 'to confirm on their word with `lnrelay approval set agent`, run at a terminal.',\n );\n }\n if (a.token !== token) {\n return refuse(\n 'the content changed since it was previewed — the token no longer matches; nothing was sent',\n 'Run again with --plan, show the new preview, and confirm with the new token.',\n );\n }\n return mint();\n }\n\n if (a.mode === 'unattended') return mint();\n\n if (!deps.isTty) {\n return a.mode === 'agent'\n ? refuse(\n `'${plan.action}' needs the owner's approval of this exact content`,\n 'Nothing was sent. Run the same command with --plan, show the preview to the owner, ' +\n 'and when they approve re-run it with --confirm <token>.',\n )\n : refuse(\n `'${plan.action}' 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. Run this ' +\n 'command yourself in a shell. There is no --yes flag; only the owner can change how ' +\n 'writes are approved, with `lnrelay approval set`, at a terminal.',\n );\n }\n\n const answer = (await deps.prompt(renderPlan(plan, budgetLine))).trim();\n\n if (answer !== token) {\n return refuse(\n 'aborted — the confirmation token did not match',\n 'Nothing was sent. Re-run and type the token shown in the prompt.',\n );\n }\n\n return mint();\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 { readFileSync, statSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport type { Session } from '../engine/auth.ts';\nimport { buildHeaders } from '../engine/auth.ts';\nimport { createEngine, 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 currentValue,\n fetchProfileForm,\n PROFILE_FIELDS,\n type ProfileField,\n type ProfileForm,\n saveBody,\n sendProfileSave,\n} from '../engine/sdui-profile.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 { type MediaKind, mediaKindOf } from '../engine/voyager-media.ts';\nimport { replyToComment } from '../engine/voyager-reply.ts';\nimport {\n type ApprovedMedia,\n editPost,\n fetchLinkCard,\n firstUrl,\n type LinkCard,\n mediaDigest,\n type PollSpec,\n pollDuration,\n share as voyagerShare,\n} 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 { lookup, previewLines } from './delete.ts';\nimport {\n gateWrite,\n recordHarvestSpend,\n refuseUnapprovable,\n reserve,\n terminalDeps,\n} from './gate.ts';\nimport { runEditImage } from './profile-image.ts';\nimport { loadToken, OAUTH_SETUP } from './token.ts';\nimport { chooseTransport, type Transport } from './transport.ts';\n\nexport interface WriteContext {\n transport: Transport;\n now: number;\n note?: string;\n}\n\n/** The urn a write is authored as, for the confirmation summary. */\nexport function authorLine(transport: Transport): string {\n return transport.kind === 'oauth'\n ? `as ${transport.token.memberUrn}`\n : `as ${transport.session.ownerUrn ?? 'you (browser session)'}`;\n}\n\nexport function prepare(\n command: string,\n now: number,\n via?: 'oauth' | 'voyager',\n calls = 1,\n): 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, calls);\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\nexport async 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\n/** Read and identify a media file, or say why it cannot be posted. */\n/** What the CLI asked to attach: `--image` (repeatable) or one `--video`, plus `--alt`s. */\nexport interface MediaRequest {\n flag: 'image' | 'video' | 'document';\n paths: string[];\n /** Index-aligned with `paths`; \"\" means no alt text for that image. */\n alts?: string[];\n /** A document's title — LinkedIn will not post a document without one. */\n title?: string;\n}\n\nconst FLAG_KIND: Record<MediaRequest['flag'], MediaKind> = {\n image: 'IMAGE',\n video: 'VIDEO',\n document: 'DOCUMENT',\n};\nconst KIND_FLAG: Record<MediaKind, string> = {\n IMAGE: '--image',\n VIDEO: '--video',\n DOCUMENT: '--document',\n};\nconst KIND_WORD: Record<MediaKind, string> = {\n IMAGE: 'image ',\n VIDEO: 'video ',\n DOCUMENT: 'document',\n};\n\n/** One line per file for the preview, each followed by its alt text or title. */\nfunction mediaLines(media: ApprovedMedia[]): string[] {\n return media.flatMap(({ filename, kind, size, sha256, alt, title }) => [\n `${KIND_WORD[kind]} ${filename} (${Math.ceil(size / 1024)} KB, sha256 ${sha256.slice(0, 12)})`,\n ...(alt === undefined ? [] : [` alt \"${alt}\"`]),\n ...(title === undefined ? [] : [` title \"${title}\"`]),\n ]);\n}\n\n/** LinkedIn's own composer limit for a multi-image post. */\nconst MAX_IMAGES = 20;\n\n/** The request as a whole, before any file is read. Null when it is coherent. */\nfunction mediaRequestError(media: MediaRequest): Envelope | null {\n const alts = media.alts ?? [];\n const single = media.flag !== 'image';\n if (single && media.paths.length > 1) {\n return err(\n 'share',\n 'INVALID_INPUT',\n `a post carries one ${media.flag}`,\n `pass a single --${media.flag}`,\n );\n }\n if (media.flag !== 'image' && alts.length > 0) {\n return err('share', 'INVALID_INPUT', `--alt applies to images, not a ${media.flag}`);\n }\n if (media.flag === 'document' && (media.title ?? '').trim() === '') {\n return err(\n 'share',\n 'INVALID_INPUT',\n 'a document needs a title',\n 'pass --title \"<what readers see above the document>\"',\n );\n }\n if (media.flag !== 'document' && media.title !== undefined) {\n return err('share', 'INVALID_INPUT', '--title applies to a --document');\n }\n if (media.paths.length > MAX_IMAGES) {\n return err('share', 'INVALID_INPUT', `a post carries at most ${MAX_IMAGES} images`);\n }\n if (alts.length > 0 && alts.length !== media.paths.length) {\n return err(\n 'share',\n 'INVALID_INPUT',\n `${alts.length} --alt for ${media.paths.length} images; they pair up by position`,\n 'give one --alt per --image, in the same order; pass --alt \"\" for an image without one',\n );\n }\n return null;\n}\n\n/** Validate the request as a whole, then load every file, or say why not. */\nfunction loadAllMedia(\n media: MediaRequest,\n): { approved: ApprovedMedia[]; bytes: Uint8Array[] } | Envelope {\n const refused = mediaRequestError(media);\n if (refused !== null) return refused;\n\n const alts = media.alts ?? [];\n const approved: ApprovedMedia[] = [];\n const bytes: Uint8Array[] = [];\n for (const [i, path] of media.paths.entries()) {\n const one = loadMedia(media.flag, path);\n if ('ok' in one) return one;\n const alt = alts[i];\n let a = alt === undefined || alt === '' ? one.approved : { ...one.approved, alt };\n if (media.flag === 'document') a = { ...a, title: (media.title ?? '').trim() };\n approved.push(a);\n bytes.push(one.bytes);\n }\n return { approved, bytes };\n}\n\nfunction loadMedia(\n flag: MediaRequest['flag'],\n path: string,\n): { approved: ApprovedMedia; bytes: Uint8Array } | Envelope {\n const kind = mediaKindOf(path);\n if (kind === null) {\n return err(\n 'share',\n 'INVALID_INPUT',\n `unsupported file type: ${basename(path)}`,\n 'images: png, jpg, jpeg, gif, webp. videos: mp4, mov. documents: pdf.',\n );\n }\n if (kind.kind !== FLAG_KIND[flag]) {\n return err(\n 'share',\n 'INVALID_INPUT',\n `${basename(path)} is not ${flag === 'image' ? 'an image' : `a ${flag}`}`,\n `pass it with ${KIND_FLAG[kind.kind]}`,\n );\n }\n let bytes: Uint8Array;\n try {\n if (!statSync(path).isFile()) throw new Error('not a file');\n bytes = new Uint8Array(readFileSync(path));\n } catch {\n return err('share', 'INVALID_INPUT', `cannot read ${path}`);\n }\n return {\n bytes,\n approved: {\n filename: basename(path),\n kind: kind.kind,\n contentType: kind.contentType,\n size: bytes.byteLength,\n sha256: mediaDigest(bytes),\n },\n };\n}\n\n/**\n * A schedule time, as epoch ms, or null. Accepts ISO 8601 with an offset or Z,\n * taken exactly, or \"YYYY-MM-DD HH:MM\" in the machine's local time. Anything\n * else is refused rather than guessed: a misread time publishes at the wrong\n * moment, which cannot be taken back.\n */\nexport function parseScheduleTime(input: string): number | null {\n const iso = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:\\d{2})$/;\n if (iso.test(input)) {\n const t = Date.parse(input);\n return Number.isNaN(t) ? null : t;\n }\n const local = /^(\\d{4})-(\\d{2})-(\\d{2})[ T](\\d{2}):(\\d{2})$/.exec(input);\n if (local === null) return null;\n const [y, mo, d, h, mi] = local.slice(1).map(Number) as [number, number, number, number, number];\n const date = new Date(y, mo - 1, d, h, mi);\n // Date rolls 2026-13-40 over into a real date; refuse instead of moving it.\n const same =\n date.getFullYear() === y &&\n date.getMonth() === mo - 1 &&\n date.getDate() === d &&\n date.getHours() === h &&\n date.getMinutes() === mi;\n return same ? date.getTime() : null;\n}\n\n/** Uploads plus pacing take minutes; a closer time could pass before the post lands. */\nconst MIN_LEAD_MS = 10 * 60_000;\n\n/** The loaded files, undefined when none were asked for, or the refusal. */\nfunction mediaFrom(\n media: MediaRequest | undefined,\n via: 'oauth' | 'voyager' | undefined,\n): { approved: ApprovedMedia[]; bytes: Uint8Array[] } | undefined | Envelope {\n if (media === undefined || media.paths.length === 0) return undefined;\n const loaded = loadAllMedia(media);\n if ('ok' in loaded) return loaded;\n // Media upload exists only over Voyager. An explicit --via oauth is refused\n // rather than rerouted: switching transport silently is what the design bans.\n if (via === 'oauth') {\n return err(\n 'share',\n 'NOT_IMPLEMENTED',\n 'posting media is only implemented over the private API',\n 'drop --via oauth, or pass --via voyager',\n );\n }\n return loaded;\n}\n\nexport interface SharePayloadIn {\n text: string;\n visibility: 'PUBLIC' | 'CONNECTIONS';\n media?: ApprovedMedia[];\n scheduledAt?: number;\n poll?: PollSpec;\n card?: LinkCard;\n}\n\n/** The approved payload and what the owner is shown about it. */\nfunction sharePlan(p: {\n author: string;\n transport: 'oauth' | 'voyager';\n text: string;\n visibility: 'PUBLIC' | 'CONNECTIONS';\n media: ApprovedMedia[] | undefined;\n scheduledAt: number | undefined;\n poll: PollSpec | undefined;\n /** Absent: no link, or no card asked for. `null`: asked, and LinkedIn has none. */\n card?: LinkCard | null;\n now: number;\n}): WritePlan<SharePayloadIn> {\n const payload: SharePayloadIn = { text: p.text, visibility: p.visibility };\n if (p.media !== undefined) payload.media = p.media;\n if (p.scheduledAt !== undefined) payload.scheduledAt = p.scheduledAt;\n if (p.poll !== undefined) payload.poll = p.poll;\n if (p.card !== undefined && p.card !== null) payload.card = p.card;\n\n const scheduled = p.scheduledAt !== undefined;\n return {\n action: scheduled ? 'schedule a post' : 'post to your feed',\n payload,\n summary: [\n p.author,\n `content \"${p.text}\"`,\n `audience ${p.visibility}`,\n ...(p.scheduledAt === undefined ? [] : [whenLine(p.scheduledAt, p.now)]),\n ...(p.poll === undefined ? [] : pollLines(p.poll)),\n ...(p.media === undefined ? [] : mediaLines(p.media)),\n ...cardLines(p.card),\n ],\n reversibility: scheduled\n ? 'cancel any time before it publishes with `lnrelay delete <urn>`; after that it is ' +\n 'public under your name like any post'\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: p.transport,\n };\n}\n\nfunction cardLines(card: LinkCard | null | undefined): string[] {\n if (card === undefined) return [];\n if (card === null) return ['card none — LinkedIn has no preview for this link'];\n return [`card \"${card.title}\" (${card.source})`];\n}\n\n/** How a link in the text is handled. `lookup` is injectable for tests. */\nexport interface LinkOptions {\n /** false: post the link as text (`--no-card`). */\n card?: boolean;\n lookup?: (url: string, session: Session) => ReturnType<typeof fetchLinkCard>;\n}\n\nconst liveCardLookup: NonNullable<LinkOptions['lookup']> = (url, session) =>\n fetchLinkCard(url, createLiveClient(session));\n\n/**\n * What a share costs and whether it must go over Voyager. Register + upload per\n * file, then the post: all must fit, or uploads are orphans. Media, scheduling,\n * polls and cards exist only over Voyager, so any one pins it.\n */\nfunction shareNeeds(\n files: number | undefined,\n scheduledAt: number | undefined,\n poll: PollSpec | undefined,\n cardUrl: string | null,\n): { voyagerOnly: boolean; calls: number } {\n const extra = (poll === undefined ? 0 : 1) + (cardUrl === null ? 0 : 1);\n return {\n voyagerOnly: files !== undefined || scheduledAt !== undefined || extra > 0,\n calls: 2 * (files ?? 0) + extra + 1,\n };\n}\n\n/**\n * The card for a link: undefined when none was asked for, null when LinkedIn\n * has none, or why it could not be asked.\n */\nasync function cardFor(\n url: string | null,\n transport: { kind: 'oauth' } | { kind: 'voyager'; session: Session },\n link: LinkOptions,\n): Promise<LinkCard | null | undefined | Envelope> {\n if (url === null || transport.kind !== 'voyager') return undefined;\n const found = await (link.lookup ?? liveCardLookup)(url, transport.session);\n if (found.ok) return found.card;\n return err(\n 'share',\n found.code,\n `could not look up the card for ${url}: ${found.message}; nothing was posted`,\n 'Re-run later, or add --no-card to post the link as plain text.',\n );\n}\n\n/** What the CLI asked for, before validation: `--poll`, `--option`s, `--duration`. */\nexport interface PollRequest {\n question: string;\n options: string[];\n duration?: string;\n}\n\nfunction pollLines(poll: PollSpec): string[] {\n return [\n `poll \"${poll.question}\"`,\n ...poll.options.map((o, i) => ` ${i + 1}. ${o}`),\n ` runs ${poll.duration}`,\n ];\n}\n\n/** A valid poll, undefined when none was asked for, or the refusal. */\nfunction pollFrom(\n poll: PollRequest | undefined,\n ctx: { hasMedia: boolean; scheduled: boolean; via: 'oauth' | 'voyager' | undefined },\n): PollSpec | undefined | Envelope {\n if (poll === undefined) return undefined;\n const refuse = (message: string, hint?: string) => err('share', 'INVALID_INPUT', message, hint);\n if (poll.question.trim() === '') return refuse('a poll needs a question');\n const options = poll.options.map((o) => o.trim());\n if (options.length < 2 || options.length > 4 || options.some((o) => o === '')) {\n return refuse('a poll needs 2 to 4 non-empty options', 'repeat --option \"<text>\" for each');\n }\n const duration = pollDuration(poll.duration ?? '1w');\n if (duration === null) {\n return refuse(`unknown --duration '${poll.duration}'`, 'one of: 1d, 3d, 1w, 2w');\n }\n if (ctx.hasMedia) return refuse('a post carries a poll or files, not both');\n // A scheduled probe showed the poll as \"1w left\" a week before it would\n // publish: its clock seems to start at creation. Until that is settled, a\n // scheduled poll could open already closed.\n if (ctx.scheduled) {\n return refuse(\n 'a poll cannot be scheduled yet — its clock may start when it is created, not published',\n 'post the poll now, or schedule a text post that asks the question',\n );\n }\n if (ctx.via === 'oauth') {\n return err(\n 'share',\n 'NOT_IMPLEMENTED',\n 'polls are only implemented over the private API',\n 'drop --via oauth, or pass --via voyager',\n );\n }\n return { question: poll.question.trim(), options, duration };\n}\n\n/** `--at` as epoch ms, undefined when absent, or the refusal. */\nfunction scheduleFrom(\n at: string | undefined,\n now: number,\n via: 'oauth' | 'voyager' | undefined,\n): number | undefined | Envelope {\n if (at === undefined) return undefined;\n const t = parseScheduleTime(at);\n if (t === null) {\n return err(\n 'share',\n 'INVALID_INPUT',\n `cannot read --at '${at}'`,\n 'use \"YYYY-MM-DD HH:MM\" (local time) or ISO 8601 with an offset, e.g. 2026-10-20T14:00+02:00',\n );\n }\n if (t < now + MIN_LEAD_MS) {\n return err(\n 'share',\n 'INVALID_INPUT',\n '--at must be at least 10 minutes from now',\n 'to post right away, leave --at out',\n );\n }\n if (via === 'oauth') {\n return err(\n 'share',\n 'NOT_IMPLEMENTED',\n 'scheduling is only implemented over the private API',\n 'drop --via oauth, or pass --via voyager',\n );\n }\n return t;\n}\n\n/** \"Tue, Oct 20, 2026, 14:00 (Europe/Budapest) — in 7 days\" */\nfunction whenLine(at: number, now: number): string {\n const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n const local = new Date(at).toLocaleString('en-US', {\n weekday: 'short',\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n hour: '2-digit',\n minute: '2-digit',\n hour12: false,\n });\n const hours = Math.round((at - now) / 3_600_000);\n const away = hours < 48 ? `in ${hours} h` : `in ${Math.round(hours / 24)} days`;\n return `when ${local} (${zone}) — ${away}`;\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 media?: MediaRequest,\n at?: string,\n poll?: PollRequest,\n link: LinkOptions = {},\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\n const scheduled = scheduleFrom(at, now, via);\n if (typeof scheduled === 'object') return scheduled;\n const scheduledAt = scheduled;\n\n const loaded = mediaFrom(media, via);\n if (loaded !== undefined && 'ok' in loaded) return loaded;\n const pollSpec = pollFrom(poll, {\n hasMedia: loaded !== undefined,\n scheduled: scheduledAt !== undefined,\n via,\n });\n if (pollSpec !== undefined && 'ok' in pollSpec) return pollSpec;\n\n // A link gets the card the composer would show, unless the post already\n // carries media or a poll (one kind per post), or the owner chose OAuth.\n const cardUrl =\n link.card !== false && loaded === undefined && pollSpec === undefined && via !== 'oauth'\n ? firstUrl(text)\n : null;\n\n const needs = shareNeeds(loaded?.approved.length, scheduledAt, pollSpec, cardUrl);\n const ctx = prepare('share', now, needs.voyagerOnly ? 'voyager' : via, needs.calls);\n if ('ok' in ctx) return ctx;\n\n const card = await cardFor(cardUrl, ctx.transport, link);\n if (card !== undefined && card !== null && 'ok' in card) return card;\n\n const plan = sharePlan({\n author: authorLine(ctx.transport),\n transport: ctx.transport.kind,\n text,\n visibility: vis,\n media: loaded?.approved,\n scheduledAt,\n poll: pollSpec,\n ...(card === undefined ? {} : { card: card as LinkCard | null }),\n now,\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), loaded?.bytes);\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 scheduledFor: scheduledAt === undefined ? undefined : new Date(scheduledAt).toISOString(),\n url: 'url' in result ? result.url : undefined,\n note: 'note' in result ? result.note : ctx.note,\n });\n}\n\n/**\n * Replace the text of one of the owner's own posts. The preview shows the text\n * being replaced when the post is among recent ones, so the owner approves a\n * change, not just a new string.\n */\nasync function runEditPost(\n urn: string,\n text: string,\n now: number,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n const unapprovable = refuseUnapprovable('edit', 'editing', deps);\n if (unapprovable !== null) return unapprovable;\n\n const ctx = prepare('edit', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager') {\n return err(\n 'edit',\n 'NOT_IMPLEMENTED',\n 'editing a post is only implemented over the private API',\n );\n }\n\n const before = await lookup(urn, true);\n const plan: WritePlan<{ urn: string; text: string }> = {\n action: 'edit your post',\n payload: { urn, text },\n summary: [\n authorLine(ctx.transport),\n `post ${urn}`,\n ...previewLines(before).map((l) => l.replace(/^content /, 'was ')),\n `new text \"${text}\"`,\n ],\n reversibility:\n 'editable again, but the previous text is NOT kept here, LinkedIn marks the post as ' +\n 'edited, and an @mention in the old text is not carried over',\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 editPost(gated.confirmed as never, createLiveClient(ctx.transport.session));\n return result.ok\n ? ok('edit', { edited: urn })\n : err('edit', result.code, result.message, result.hint);\n}\n\ntype ProfileFailure = { ok: false; code: string; message: string; hint?: string };\n\n/** What a profile edit needs from LinkedIn. Injectable so tests send nothing. */\nexport interface ProfileSurface {\n vanity(): Promise<{ ok: true; vanity: string } | ProfileFailure>;\n open(field: ProfileField, vanity: string): Promise<ProfileForm | ProfileFailure>;\n send(form: ProfileForm, body: Record<string, unknown>): Promise<{ ok: true } | ProfileFailure>;\n}\n\nexport function liveProfile(session: Session): ProfileSurface {\n const client = createLiveClient(session);\n return {\n vanity: async () => {\n const me = await createEngine(session).whoami();\n if (!me.ok) return me;\n const id = (me.value?.publicIdentifier ?? null) as string | null;\n return typeof id === 'string' && id !== ''\n ? { ok: true, vanity: id }\n : { ok: false, code: 'SCHEMA_DRIFT', message: 'whoami returned no public profile id' };\n },\n open: (field, vanity) => fetchProfileForm(field, vanity, client),\n send: (form, body) => sendProfileSave(form, body, client),\n };\n}\n\nconst PROFILE_HINT = `profile fields: ${Object.keys(PROFILE_FIELDS).join(', ')}`;\n\n/**\n * Replace one text field on the owner's profile. The form is read first, so\n * the owner approves a change from what is there now to what will be, and the\n * save sends every other field back exactly as LinkedIn holds it.\n */\nexport async function runEditProfile(\n name: string,\n text: string | undefined,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n surface?: ProfileSurface,\n): Promise<Envelope> {\n const field = (PROFILE_FIELDS as Record<string, ProfileField>)[name];\n if (field === undefined) {\n return err(\n 'edit',\n 'INVALID_INPUT',\n `'${name}' is not a profile field this edits`,\n PROFILE_HINT,\n );\n }\n if (text === undefined || text.trim() === '') {\n return err(\n 'edit',\n 'INVALID_INPUT',\n `the new ${name} is required`,\n `lnrelay edit ${name} \"<text>\"`,\n );\n }\n if (text.length > field.maxLength) {\n return err(\n 'edit',\n 'INVALID_INPUT',\n `the ${name} is ${text.length} characters; LinkedIn allows ${field.maxLength}`,\n );\n }\n\n const unapprovable = refuseUnapprovable('edit', 'editing', deps);\n if (unapprovable !== null) return unapprovable;\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', 'profile edits go over the browser session only');\n }\n const profile = surface ?? liveProfile(ctx.transport.session);\n\n const me = await profile.vanity();\n if (!me.ok) return err('edit', me.code, me.message, me.hint);\n const form = await profile.open(field, me.vanity);\n if (!form.ok) return err('edit', form.code, form.message, form.hint);\n const was = currentValue(form, field) ?? '';\n if (was === text) {\n return err('edit', 'INVALID_INPUT', `your ${name} already reads exactly that; nothing to save`);\n }\n const built = saveBody(form, field, text);\n if (!built.ok) return err('edit', built.code, built.message, built.hint);\n\n // `was` is in the payload so the token binds it: a profile that changed\n // after the owner looked is a different edit from the one they approved.\n const plan: WritePlan<{ field: string; was: string; text: string }> = {\n action: `change your ${name}`,\n payload: { field: name, was, text },\n summary: [\n authorLine(ctx.transport),\n `field ${name}`,\n `was \"${was}\"`,\n `new \"${text}\"`,\n ],\n reversibility:\n 'editable again, but the old text is kept only in this preview and the audit log ' +\n '(~/.lnrelay/writes.jsonl). Every other profile field is sent back as LinkedIn holds it.',\n transport: 'voyager',\n };\n const gated = await gate('edit', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const sent = await profile.send(form, built.body);\n if (!sent.ok) return err('edit', sent.code, sent.message, sent.hint);\n\n // Never an empty success: read it back.\n const after = await profile.open(field, me.vanity);\n const reads = after.ok ? currentValue(after, field) : undefined;\n if (reads !== text) {\n return err(\n 'edit',\n 'SCHEMA_DRIFT',\n `LinkedIn accepted the save, but your ${name} does not read back as the new text`,\n after.ok ? `It reads: \"${reads ?? ''}\"` : `The read-back failed: ${after.message}`,\n );\n }\n return ok('edit', { field: name, verified: true });\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 const unapprovable = refuseUnapprovable('comment', 'commenting', deps);\n if (unapprovable !== null) return unapprovable;\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 // The harvested trackingId changes on every render, so --plan and --confirm\n // would never agree on a token derived from it. The intent is what's approved.\n tokenBasis: { activityId, text },\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 if (commentUrn === 'photo' || commentUrn === 'banner') {\n return runEditImage(commentUrn, text, now, deps);\n }\n const ref: CommentRef | null = parseCommentUrn(commentUrn);\n if (ref === null && !commentUrn.startsWith('urn:')) {\n return runEditProfile(commentUrn, text, now, deps);\n }\n if (ref === null) {\n // Like delete, edit routes by the KIND of urn: a comment and a post are\n // edited over different surfaces, and each is unambiguous.\n if (/^urn:li:(share|ugcPost):\\d+$/.test(commentUrn)) {\n return runEditPost(commentUrn, text, now, deps);\n }\n return err(\n 'edit',\n 'INVALID_INPUT',\n `'${commentUrn}' is neither a comment urn nor a post's share/ugcPost urn`,\n /^urn:li:activity:/.test(commentUrn)\n ? 'A post is edited by the urn it was created as, not its activity urn. `lnrelay share` ' +\n 'prints it, and `lnrelay my-posts` lists it as shareUrn.'\n : 'Pass a comment urn (from `lnrelay post <activity-urn>`) or a post urn ' +\n '(urn:li:share:… / urn:li:ugcPost:…).',\n );\n }\n\n const unapprovable = refuseUnapprovable('edit', 'editing', deps);\n if (unapprovable !== null) return unapprovable;\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 const unapprovable = refuseUnapprovable('reply', 'replying', deps);\n if (unapprovable !== null) return unapprovable;\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","// ─── 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","// ─── 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, captured 2026-08-14. VERSIONED (`-43`), so it rotates like\n * the queryIds in contracts.ts — re-capture this first if replies start failing.\n *\n * A WARNING worth more than the constant: omitting it returns HTTP 500 **after\n * the reply has already been created**. Verified — the failed attempt appeared\n * on the post alongside the successful one. The write happens; only the\n * decorated response fails to build.\n *\n * So a 5xx from this endpoint does NOT mean nothing happened, and a retry\n * double-posts publicly. See the hint on the failure path below.\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 // Observed live: this endpoint can answer 500 with the reply ALREADY\n // POSTED. Telling the user to retry would double-post under their name.\n out.hint = /5\\d\\d|unexpected status/.test(result.message)\n ? 'DO NOT RETRY BLINDLY. This endpoint has been observed returning 5xx after the reply ' +\n 'was already created. Check the thread on LinkedIn before sending again.'\n : (result.hint ?? '');\n if (out.hint === '') delete out.hint;\n return out;\n }\n return { ok: true, parent: parentThreadUrn(ref) };\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 { createHash } from 'node:crypto';\nimport type { ConfirmedWrite } from '../commands/confirm.ts';\nimport type { Client } from './client.ts';\nimport { contractFor } from './contracts.ts';\nimport { type MediaKind, uploadMedia } from './voyager-media.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 /** Epoch ms. Present only on a scheduled post. */\n scheduledAt?: number;\n}\n\n/** What a post can carry: an upload, a poll, or a link card. */\nexport type ShareMediaCategory = MediaKind | 'POLL' | 'ARTICLE';\n\n/** The share-media `category` for each upload kind. A document is not \"DOCUMENT\". */\nconst CATEGORY: Record<ShareMediaCategory, string> = {\n POLL: 'URN_REFERENCE',\n ARTICLE: 'ARTICLE',\n IMAGE: 'IMAGE',\n VIDEO: 'VIDEO',\n DOCUMENT: 'NATIVE_DOCUMENT',\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(\n text: string,\n visibility: 'PUBLIC' | 'CONNECTIONS',\n media: { category: ShareMediaCategory; urn: string; alt?: string; title?: string }[] = [],\n scheduledAt?: number,\n): SharePayload {\n // LinkedIn publishes a SCHEDULED post itself at scheduledAt (verified 2026-10-13).\n const schedule =\n scheduledAt === undefined\n ? { postState: 'PUBLISHED' }\n : { postState: 'SCHEDULED', scheduledAt };\n return {\n visibleToConnectionsOnly: visibility === 'CONNECTIONS',\n externalAudienceProviders: [],\n commentaryV2: { text, attributes: [] },\n origin: 'FEED',\n allowedCommentersScope: 'ALL',\n ...schedule,\n // altText only when given, so a post without it keeps the body verified in 2026-08.\n media: media.map((m) => ({\n category: CATEGORY[m.category],\n mediaUrn: m.urn,\n tapTargets: [],\n ...(m.alt === undefined ? {} : { altText: m.alt }),\n ...(m.title === undefined ? {} : { title: { text: m.title } }),\n })),\n };\n}\n\n/** What the human approves about a file: its identity, not its bytes. */\nexport interface ApprovedMedia {\n filename: string;\n kind: MediaKind;\n contentType: string;\n size: number;\n sha256: string;\n /** Alt text for screen readers; images only. */\n alt?: string;\n /** A document's title, which LinkedIn requires; documents only. */\n title?: string;\n}\n\nexport function mediaDigest(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('hex');\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<{\n text: string;\n visibility: 'PUBLIC' | 'CONNECTIONS';\n media?: ApprovedMedia[];\n /** Epoch ms; makes this a scheduled post. */\n scheduledAt?: number;\n poll?: PollSpec;\n /** The link card the owner was shown; the article urn is what is sent. */\n card?: LinkCard;\n }>,\n client: Client,\n bytes?: Uint8Array[],\n): Promise<WriteResult> {\n const approved = confirmed.payload.media ?? [];\n const files = bytes ?? [];\n\n // The approval names each file by digest and the bytes travel separately —\n // so ALL of them are checked before anything leaves the machine. Checking\n // one at a time would upload the first before discovering the second changed.\n for (const [i, a] of approved.entries()) {\n const b = files[i];\n if (b === undefined || mediaDigest(b) !== a.sha256) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `${a.filename} changed after it was approved; nothing was sent`,\n };\n }\n }\n\n const media: { category: ShareMediaCategory; urn: string; alt?: string; title?: string }[] = [];\n const { card } = confirmed.payload;\n if (card !== undefined) media.push({ category: 'ARTICLE', urn: card.urn });\n\n // A poll is created first, as its own object, then referenced like media.\n const { poll } = confirmed.payload;\n if (poll !== undefined) {\n const created = await createPoll(poll, client);\n if (!created.ok) return created;\n media.push({ category: 'POLL', urn: created.urn });\n }\n for (const [i, a] of approved.entries()) {\n const uploaded = await uploadMedia(\n {\n bytes: files[i] as Uint8Array,\n filename: a.filename,\n kind: a.kind,\n contentType: a.contentType,\n },\n client,\n );\n if (!uploaded.ok) return uploaded;\n media.push({\n category: a.kind,\n urn: uploaded.urn,\n ...(a.alt === undefined ? {} : { alt: a.alt }),\n ...(a.title === undefined ? {} : { title: a.title }),\n });\n }\n\n const body = sharePayload(\n confirmed.payload.text,\n confirmed.payload.visibility,\n media,\n confirmed.payload.scheduledAt,\n );\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\n// ─── Editing a post ───────────────────────────────────────────────────────────\n//\n// VERIFIED LIVE 2026-10-13: a Rest.li partial update on normShares/<urn>\n// replaced a post's text, and the response returned the post as LinkedIn then\n// held it, media untouched. The same resource `delete` uses, so no rotating\n// queryId is involved. It replaces the WHOLE text: an @mention in the old text\n// is not carried over, because `attributes` is sent empty.\n\nexport function editPostBody(text: string) {\n return { patch: { $set: { commentaryV2: { text, attributes: [] } } } };\n}\n\nexport async function editPost(\n confirmed: ConfirmedWrite<{ urn: string; text: string }>,\n client: Client,\n): Promise<WriteResult> {\n const { urn, text } = confirmed.payload;\n const result = await client.request({\n url: deleteUrl(urn),\n method: 'POST',\n body: editPostBody(text),\n spendClass: 'write',\n operation: 'edit-post',\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 const held = (result.json as { data?: { commentary?: { text?: unknown } } } | null)?.data\n ?.commentary?.text;\n if (held !== text) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'LinkedIn answered, but the post does not hold the text that was sent',\n hint: `Look at the post before trying again: \\`lnrelay post\\` or the browser. ${urn}`,\n };\n }\n return { ok: true, id: urn };\n}\n\n// ─── Polls ────────────────────────────────────────────────────────────────────\n//\n// VERIFIED LIVE 2026-10-13: the PollsPollSummary mutation returned a\n// pollSummary urn, and normShares with media { category: URN_REFERENCE } posted\n// it — LinkedIn's own scheduled list showed it as a poll. Creating the poll\n// publishes nothing; it is an orphan until a post references it.\n\nexport type PollDuration = 'ONE_DAY' | 'THREE_DAYS' | 'ONE_WEEK' | 'TWO_WEEKS';\n\nexport interface PollSpec {\n question: string;\n options: string[];\n duration: PollDuration;\n}\n\nconst DURATIONS: Record<string, PollDuration> = {\n '1d': 'ONE_DAY',\n '3d': 'THREE_DAYS',\n '1w': 'ONE_WEEK',\n '2w': 'TWO_WEEKS',\n};\n\n/** The `--duration` shorthand as LinkedIn's enum, or null. */\nexport function pollDuration(shorthand: string): PollDuration | null {\n return DURATIONS[shorthand] ?? null;\n}\n\n/** The first GraphQL error message, wherever this envelope put it. */\nfunction gqlError(json: unknown): string | null {\n const j = json as { errors?: { message?: string }[]; data?: { errors?: { message?: string }[] } };\n const errors = j?.errors ?? j?.data?.errors;\n return errors !== undefined && errors.length > 0 ? (errors[0]?.message ?? 'GraphQL error') : null;\n}\n\n/** The created poll's urn, or null — including when the 200 carries errors. */\nexport function pollUrnOf(json: unknown): string | null {\n if (gqlError(json) !== null) return null;\n return JSON.stringify(json ?? null).match(/urn:li:fsd_pollSummary:\\d+/)?.[0] ?? null;\n}\n\nasync function createPoll(\n poll: PollSpec,\n client: Client,\n): Promise<\n { ok: true; urn: string } | { ok: false; code: string; message: string; hint?: string }\n> {\n const contract = contractFor('createPoll');\n if (contract?.queryId === undefined) {\n return { ok: false, code: 'NOT_IMPLEMENTED', message: 'no verified poll contract' };\n }\n const result = await client.request({\n url: `${contract.path}?action=execute&queryId=${contract.queryId}`,\n method: 'POST',\n body: { variables: { poll }, queryId: contract.queryId, includeWebMetadata: true },\n spendClass: 'write',\n operation: 'create-poll',\n });\n if (!result.ok)\n return { ok: false, code: result.code, message: `${result.message}; nothing was posted` };\n\n // GraphQL answers a validation failure with HTTP 200 — read the body, or a\n // refused poll would be reported as created.\n const error = gqlError(result.json);\n if (error !== null) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `LinkedIn refused the poll: ${error}; nothing was posted`,\n };\n }\n const urn = pollUrnOf(result.json);\n if (urn === null) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the poll mutation answered without a poll urn; nothing was posted',\n hint: 'The queryId may have rotated — recapture it (docs/ENGINE-RESEARCH.md).',\n };\n }\n return { ok: true, urn };\n}\n\n// ─── Link cards ───────────────────────────────────────────────────────────────\n//\n// A URL in the text is only text: a post sent without media renders it as a\n// bare link (verified 2026-10-13 on a scheduled probe — no card). The composer\n// makes the card by asking LinkedIn to resolve the URL into an article\n// (`urn:li:article:<id>`), and the post carries that urn as ARTICLE media.\n\nexport interface LinkCard {\n urn: string;\n title: string;\n /** The site, as LinkedIn names it under the title. */\n source: string;\n}\n\n/** The first link in the text — the one the web composer previews. */\nexport function firstUrl(text: string): string | null {\n const found = text.match(/https?:\\/\\/[^\\s<>\"]+/)?.[0];\n if (found === undefined) return null;\n // Closing punctuation belongs to the sentence, unless the link opened it.\n let url = found.replace(/[.,;:!?'\"]+$/, '');\n if (url.endsWith(')') && !url.includes('(')) url = url.slice(0, -1);\n return url;\n}\n\nexport function urlPreviewUrl(url: string): string {\n const contract = contractFor('urlPreview');\n return (\n `${contract?.path}?includeWebMetadata=true` +\n `&variables=(url:${encodeURIComponent(url)})&queryId=${contract?.queryId}`\n );\n}\n\ntype CardResult =\n | { ok: true; card: LinkCard | null }\n | { ok: false; code: string; message: string; hint?: string };\n\nexport function parseUrlPreview(json: unknown): CardResult {\n const error = gqlError(json);\n if (error !== null) {\n return { ok: false, code: 'SCHEMA_DRIFT', message: `the link preview failed: ${error}` };\n }\n const j = json as {\n data?: { data?: { contentcreationDashUpdateUrlPreviewByUrl?: { elements?: unknown[] } } };\n included?: {\n content?: {\n articleComponent?: {\n articleUrn?: string;\n title?: { text?: string };\n subtitle?: { text?: string };\n };\n };\n }[];\n };\n const elements = j?.data?.data?.contentcreationDashUpdateUrlPreviewByUrl?.elements;\n if (!Array.isArray(elements)) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the link preview response had no preview collection',\n hint: 'Re-capture the urlPreview contract: paste a link into the web composer.',\n };\n }\n if (elements.length === 0) return { ok: true, card: null };\n\n const article = (j.included ?? []).find((e) => e.content?.articleComponent?.articleUrn)?.content\n ?.articleComponent;\n if (article?.articleUrn === undefined) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'LinkedIn previewed the link but no article came with it',\n };\n }\n return {\n ok: true,\n card: {\n urn: article.articleUrn,\n title: article.title?.text ?? '',\n source: article.subtitle?.text ?? '',\n },\n };\n}\n\n/** Ask LinkedIn what card it would show for a link. A read. */\nexport async function fetchLinkCard(url: string, client: Client): Promise<CardResult> {\n const result = await client.request({\n url: urlPreviewUrl(url),\n spendClass: 'page',\n operation: 'link-preview',\n });\n if (!result.ok) {\n const out: CardResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n return parseUrlPreview(result.json);\n}\n","// ─── `lnrelay edit photo|banner <file>` ───────────────────────────────────────\n//\n// Replace the owner's profile photo or cover image with a file, as the\n// browser does (engine/sdui-profile-image.ts): register, upload, save. The\n// file is checked before anything is sent, the owner approves it by its\n// digest, and the profile is read back afterwards: the new image must be the\n// one showing, or the command fails.\n\nimport { readFileSync, statSync } from 'node:fs';\nimport { basename, resolve } from 'node:path';\nimport type { Session } from '../engine/auth.ts';\nimport { fullProfileUrl } from '../engine/full-profile.ts';\nimport { createEngine, createLiveClient } from '../engine/index.ts';\nimport type { Failure } from '../engine/sdui-form.ts';\nimport { sendAction } from '../engine/sdui-profile.ts';\nimport {\n IMAGE_KINDS,\n type ImageKeys,\n type ImageKind,\n type ImageRequest,\n imageSizeOf,\n newKeys,\n parseRegister,\n picturesOf,\n REGISTER_REQUEST,\n registerBody,\n saveBody,\n type Upload,\n} from '../engine/sdui-profile-image.ts';\nimport { mediaDigest } 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 { refuseUnapprovable, terminalDeps } from './gate.ts';\nimport { authorLine, gate, prepare } from './write.ts';\n\n/** What an image change needs from LinkedIn. Injectable so tests send nothing. */\nexport interface ImageSurface {\n vanity(): Promise<{ ok: true; vanity: string } | Failure>;\n pictures(\n vanity: string,\n ): Promise<{ ok: true; profileId: string; photo?: string; banner?: string } | Failure>;\n register(body: unknown): Promise<{ ok: true; raw: string } | Failure>;\n put(upload: Upload, bytes: Uint8Array, mimeType: string): Promise<{ ok: true } | Failure>;\n save(kind: ImageKind, body: unknown): Promise<{ ok: true } | Failure>;\n}\n\nfunction liveImages(session: Session): ImageSurface {\n const client = createLiveClient(session);\n return {\n vanity: async () => {\n const me = await createEngine(session).whoami();\n if (!me.ok) return me;\n const id = me.value?.publicIdentifier;\n return typeof id === 'string' && id !== ''\n ? { ok: true, vanity: id }\n : { ok: false, code: 'SCHEMA_DRIFT', message: 'whoami returned no public profile id' };\n },\n pictures: async (vanity) => {\n const r = await client.request({\n url: fullProfileUrl(vanity),\n spendClass: 'profile',\n operation: 'profile-pictures',\n });\n return r.ok ? picturesOf(r.json) : r;\n },\n register: async (body) => {\n const raw = await sendAction(REGISTER_REQUEST, body, client, 'image-register');\n return typeof raw === 'string' ? { ok: true, raw } : raw;\n },\n put: async (upload, bytes, mimeType) => {\n const r = await client.request({\n url: upload.url,\n method: 'PUT',\n bytes,\n headers: { 'content-type': mimeType, ...upload.headers },\n spendClass: 'write',\n operation: 'image-upload',\n });\n return r.ok ? { ok: true } : r;\n },\n save: async (kind, body) => {\n const raw = await sendAction(kind.save, body, client, `${kind.name}-save`);\n return typeof raw === 'string' ? { ok: true } : raw;\n },\n };\n}\n\n/** LinkedIn's own limit on either image. */\nconst MAX_BYTES = 8 * 1024 * 1024;\n\ntype Picked = { bytes: Uint8Array; width: number; height: number; mimeType: string };\n\n/** Read the file and check it is a PNG or JPEG of the shape `kind` takes. */\nfunction pick(kind: ImageKind, path: string): Picked | Envelope {\n let bytes: Uint8Array;\n try {\n if (!statSync(path).isFile()) throw new Error('not a file');\n bytes = new Uint8Array(readFileSync(path));\n } catch {\n return err('edit', 'INVALID_INPUT', `cannot read ${path}`);\n }\n if (bytes.byteLength > MAX_BYTES)\n return err('edit', 'INVALID_INPUT', `${basename(path)} is over LinkedIn's 8 MB limit`);\n const size = imageSizeOf(bytes);\n if (size === null)\n return err('edit', 'INVALID_INPUT', `${basename(path)} is not a PNG or JPEG image`);\n const ratio = size.width / size.height;\n if (Math.abs(ratio / kind.aspect - 1) > 0.02) {\n const want = kind.name === 'photo' ? 'square' : '4:1 (1584 × 396)';\n return err(\n 'edit',\n 'INVALID_INPUT',\n `${basename(path)} is ${size.width} × ${size.height}; a ${kind.label} must be ${want}`,\n 'It is uploaded as it is, uncropped: crop it to that shape first.',\n );\n }\n return { bytes, ...size };\n}\n\ntype Approved = { image: string; file: string; sha256: string; was: string | null };\n\nfunction planOf(\n kind: ImageKind,\n file: string,\n picked: Picked,\n was: string | undefined,\n author: string,\n): WritePlan<Approved> {\n const sha256 = mediaDigest(picked.bytes);\n return {\n action: `replace your ${kind.label}`,\n payload: { image: kind.name, file, sha256, was: was ?? null },\n summary: [\n author,\n `image ${kind.label}`,\n `file ${file}`,\n ` ${picked.width} × ${picked.height}, ${picked.bytes.byteLength} bytes, sha256 ${sha256.slice(0, 16)}…`,\n `now ${was === undefined ? 'none' : `asset ${was}`}`,\n ],\n reversibility:\n 'replaceable again with any file, but the current image is not kept here: have the ' +\n 'original file before replacing it. Everyone who can see your profile sees the change.',\n transport: 'voyager',\n };\n}\n\n/** Register, upload both copies, save. The display asset id, or why not. */\nasync function send(\n li: ImageSurface,\n kind: ImageKind,\n req: Omit<ImageRequest, 'displayName'> & { displayName: string },\n picked: Picked,\n): Promise<{ ok: true; displayId: string } | Envelope> {\n const nothing = (f: Failure, step: string) =>\n err('edit', f.code, `${step} failed (${f.message}); nothing changed on your profile`, f.hint);\n const registered = await li.register(registerBody(kind, req));\n if (!registered.ok) return nothing(registered, 'registering the image');\n const ticket = parseRegister(registered.raw, req.keys);\n if (!ticket.ok) return nothing(ticket, 'registering the image');\n for (const upload of [ticket.uploads.original, ticket.uploads.display]) {\n const put = await li.put(upload, picked.bytes, picked.mimeType);\n if (!put.ok) return nothing(put, 'uploading the image');\n }\n const saved = await li.save(kind, saveBody(kind, { ...req, ...ticket }));\n if (!saved.ok)\n return err('edit', saved.code, `saving the ${kind.label} failed: ${saved.message}`);\n return { ok: true, displayId: ticket.displayId };\n}\n\nexport async function runEditImage(\n name: string,\n path: string | undefined,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n surface?: ImageSurface,\n keys?: ImageKeys,\n): Promise<Envelope> {\n const kind = (IMAGE_KINDS as Record<string, ImageKind>)[name];\n if (kind === undefined)\n return err('edit', 'INVALID_INPUT', `'${name}' is not an image this edits`, 'photo, banner');\n if (path === undefined || path.trim() === '')\n return err('edit', 'INVALID_INPUT', 'an image file is required', `lnrelay edit ${name} <file>`);\n const file = resolve(path);\n const picked = pick(kind, file);\n if ('ok' in picked) return picked;\n\n const unapprovable = refuseUnapprovable('edit', 'editing', deps);\n if (unapprovable !== null) return unapprovable;\n // register, two uploads, save\n const ctx = prepare('edit', now, 'voyager', 4);\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager')\n return err('edit', 'NOT_IMPLEMENTED', 'profile edits go over the browser session only');\n const li = surface ?? liveImages(ctx.transport.session);\n\n const me = await li.vanity();\n if (!me.ok) return err('edit', me.code, me.message, me.hint);\n const before = await li.pictures(me.vanity);\n if (!before.ok) return err('edit', before.code, before.message, before.hint);\n\n const plan = planOf(kind, file, picked, before[kind.name], authorLine(ctx.transport));\n const gated = await gate('edit', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const ext = picked.mimeType === 'image/png' ? 'png' : 'jpg';\n const sent = await send(\n li,\n kind,\n {\n profileId: before.profileId,\n vanity: me.vanity,\n file: { name: basename(file), mimeType: picked.mimeType, size: picked.bytes.byteLength },\n keys: keys ?? newKeys(kind),\n displayName: `edited-image-${new Date(now).toISOString().replace(/[:.]/g, '-')}.${ext}`,\n },\n picked,\n );\n if (!('displayId' in sent)) return sent;\n\n // Never an empty success: the new image must be the one showing.\n const after = await li.pictures(me.vanity);\n if (!after.ok || after[kind.name] !== sent.displayId) {\n return err(\n 'edit',\n 'SCHEMA_DRIFT',\n `LinkedIn accepted the save, but your ${kind.label} does not read back as the new image`,\n after.ok\n ? `It shows asset ${after[kind.name] ?? 'none'}; the upload was ${sent.displayId}.`\n : `The read-back failed: ${after.message}`,\n );\n }\n return ok('edit', { image: kind.name, verified: true, asset: sent.displayId });\n}\n","// ─── The profile photo and the cover image ────────────────────────────────────\n//\n// Captured 2026-10-19 by changing each in the browser. Both are three steps,\n// over the same SDUI register request:\n//\n// 1. server-request profileImageRegister: the file described (name, type,\n// size) as an ORIGINAL and a DISPLAY image, each with an empty\n// asset-urn state. The answer sets those states to two digitalmedia\n// asset ids and carries an upload instruction for each: a /dms-uploads/\n// URL and its headers (`mediaTypeFamily: STILLIMAGE`).\n// 2. PUT each file to its URL.\n// 3. server-request saveProfilePicture / saveProfileBackgroundImage, naming\n// the display image and both asset ids. This is the step that changes\n// the profile; 1 and 2 leave orphan assets nobody sees.\n//\n// The browser uploads its editor's render (cropped, scaled) as the display\n// image and the picked file as the original. Here the file is both, with the\n// crop set to the whole image, so the file must already be the right shape:\n// square for the photo, 4:1 for the cover (LinkedIn's 1584 × 396).\n//\n// The keys (`auto-binding-…`) and file pointers are the client's own choice;\n// LinkedIn echoes them back, which is how the answer is read.\n\nimport { randomUUID } from 'node:crypto';\nimport { type Failure, responseErrors } from './sdui-form.ts';\n\nexport interface ImageKind {\n name: 'photo' | 'banner';\n /** What the owner calls it. */\n label: string;\n screen: string;\n originalType: string;\n displayType: string;\n save: string;\n /** Width over height the file must have, ±2%. */\n aspect: number;\n}\n\nexport const IMAGE_KINDS = {\n photo: {\n name: 'photo',\n label: 'profile photo',\n screen: 'com.linkedin.sdui.flagshipnav.profile.ProfileAddPicture',\n originalType: 'ProfileOriginalPhoto',\n displayType: 'ProfileDisplayPhoto',\n save: 'com.linkedin.sdui.requests.profile.saveProfilePicture',\n aspect: 1,\n },\n banner: {\n name: 'banner',\n label: 'cover image',\n screen: 'com.linkedin.sdui.flagshipnav.profile.ProfileAddBackgroundImage',\n originalType: 'ProfileOriginalBackground',\n displayType: 'ProfileDisplayBackground',\n save: 'com.linkedin.sdui.requests.profile.saveProfileBackgroundImage',\n aspect: 4,\n },\n} as const satisfies Record<string, ImageKind>;\n\nconst REGISTER = 'com.linkedin.sdui.requests.profile.profileImageRegister';\nexport const REGISTER_REQUEST = REGISTER;\nconst NS = 'MemoryNamespace';\n/** The photo editor's saving flag has a fixed name; the cover's is generated. */\nconst PHOTO_SAVING = 'ADD_PHOTOPROFILE_PHOTO_UPLOAD_IS_SAVING';\n\nexport interface ImageKeys {\n originalMedia: string;\n originalAssetUrns: string;\n displayMedia: string;\n displayAssetUrns: string;\n saving: string;\n originalPointer: string;\n displayPointer: string;\n}\n\nconst binding = () => `auto-binding-${randomUUID()}`;\nconst pointer = () => Math.random().toString(36).slice(2, 13).padEnd(11, '0');\n\nexport function newKeys(kind: ImageKind): ImageKeys {\n return {\n originalMedia: binding(),\n originalAssetUrns: binding(),\n displayMedia: binding(),\n displayAssetUrns: binding(),\n saving: kind.name === 'photo' ? PHOTO_SAVING : binding(),\n originalPointer: pointer(),\n displayPointer: pointer(),\n };\n}\n\nexport interface ImageFile {\n name: string;\n mimeType: string;\n size: number;\n}\n\nexport interface ImageRequest {\n profileId: string;\n vanity: string;\n file: ImageFile;\n keys: ImageKeys;\n /** What the display copy is called; the browser names its render this way. */\n displayName?: string;\n}\n\nconst focusKey = (vanity: string) =>\n `ProfileComponentStateLastPerformedActionRef${vanity}ProfileComponentState`;\nconst bind = (key: string) => ({ key, namespace: NS });\nconst stateKey = (id: string) => ({ key: { value: { $case: 'id', id } } });\nconst META = { $type: 'proto.sdui.common.RequestMetadata' } as const;\n\n/** The whole image, unscaled and unfiltered: the file is already the shape it should be. */\nconst WHOLE_IMAGE = {\n $type: 'proto.sdui.media.MediaEditData',\n croppedRegion: {\n $type: 'proto.sdui.common.Rect',\n topLeft: { $type: 'proto.sdui.common.Coordinate2D', x: 0, y: 0 },\n topRight: { $type: 'proto.sdui.common.Coordinate2D', x: 1, y: 0 },\n bottomLeft: { $type: 'proto.sdui.common.Coordinate2D', x: 0, y: 1 },\n bottomRight: { $type: 'proto.sdui.common.Coordinate2D', x: 1, y: 1 },\n },\n scaleRatio: 1,\n brightness: 0,\n contrast: 0,\n saturation: 0,\n vignette: 0,\n imageFilter: 'ImageFilter_None',\n};\n\nfunction mediaList(file: ImageFile, name: string, ptr: string, edited: boolean) {\n const size = String(file.size);\n return {\n $type: 'proto.sdui.media.MediaList',\n mediaFiles: [\n {\n mediaAttributions: [],\n analysisData: {},\n fileName: name,\n source: {\n $case: 'localFile',\n localFile: {\n fileName: name,\n mimeType: file.mimeType,\n filePointer: ptr,\n size,\n shouldIncludeFileContents: false,\n },\n },\n size,\n mimeType: file.mimeType,\n filePointer: ptr,\n mediaFileId: ptr,\n ...(edited ? { editData: WHOLE_IMAGE } : {}),\n captions: [],\n thumbnails: [],\n },\n ],\n };\n}\n\ntype Value = Record<string, unknown> | string[] | string | boolean;\nconst CASES: Record<string, string> = {\n object: 'mediaListValue',\n array: 'stringListValue',\n string: 'stringValue',\n boolean: 'booleanValue',\n};\n\nfunction state(key: string, value: Value) {\n const kind = Array.isArray(value) ? 'array' : typeof value;\n return {\n key,\n namespace: NS,\n value,\n originalProtoCase: CASES[kind] as string,\n protoKey: { $type: 'proto.sdui.Key', value: { $case: 'id', id: key } },\n };\n}\n\nfunction serverRequest(\n requestId: string,\n payload: Record<string, unknown>,\n states: ReturnType<typeof state>[],\n screenId: string,\n) {\n const requestedStateKeys = states.map((s) => stateKey(s.key));\n const requestedArguments = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys,\n payload,\n requestMetadata: META,\n };\n return {\n requestId,\n serverRequest: {\n requestId,\n requestedArguments,\n isApfcEnabled: false,\n isStreaming: false,\n rumPageKey: '',\n },\n states,\n requestedArguments: { ...requestedArguments, states, screenId, knownTemplateIds: [] },\n };\n}\n\nconst displayNameOf = (req: ImageRequest) =>\n req.displayName ??\n `edited-image-${new Date().toISOString().replace(/[:.]/g, '-')}.${req.file.name.split('.').pop()}`;\n\n/** The save's payload, and which states it reads, in the browser's order. */\nfunction savePlan(kind: ImageKind, req: ImageRequest) {\n const k = req.keys;\n const focus = focusKey(req.vanity);\n if (kind.name === 'photo') {\n return {\n payload: {\n profileId: req.profileId,\n vanityName: req.vanity,\n newMedia: bind(k.displayMedia),\n originalAssetUrns: bind(k.originalAssetUrns),\n displayAssetUrns: bind(k.displayAssetUrns),\n isSavingProfilePhoto: bind(k.saving),\n focusableComponentRefKey: bind(focus),\n },\n keys: [k.displayMedia, k.originalAssetUrns, k.displayAssetUrns, k.saving, focus],\n focusValue: 'topcard-logo-image-referencekey',\n };\n }\n return {\n payload: {\n vanityName: req.vanity,\n profileId: req.profileId,\n editedMedia: bind(k.displayMedia),\n displayAssetUrns: bind(k.displayAssetUrns),\n originalAssetUrns: bind(k.originalAssetUrns),\n focusableComponentRefKey: bind(focus),\n isSaving: bind(k.saving),\n omitDefaultPhotoFilterEditInfo: true,\n },\n keys: [k.displayMedia, k.displayAssetUrns, k.originalAssetUrns, focus],\n focusValue: `${req.vanity}_cover_edit_button`,\n };\n}\n\n/** Step 1: describe the file and ask where to upload it. Changes nothing visible. */\nexport function registerBody(kind: ImageKind, req: ImageRequest) {\n const k = req.keys;\n const save = savePlan(kind, req);\n const payload = {\n profileId: req.profileId,\n originalMedia: bind(k.originalMedia),\n originalAssetUrns: bind(k.originalAssetUrns),\n originalMediaType: kind.originalType,\n displayMedia: bind(k.displayMedia),\n displayMediaType: kind.displayType,\n displayAssetUrns: bind(k.displayAssetUrns),\n uploadOriginal: true,\n followUpRequest: { key: kind.save, data: save.payload, stateKeys: save.keys.map(bind) },\n skipEdit: false,\n isSaving: bind(k.saving),\n };\n return serverRequest(\n REGISTER,\n payload,\n [\n state(k.originalMedia, mediaList(req.file, req.file.name, k.originalPointer, false)),\n state(k.originalAssetUrns, []),\n state(k.displayMedia, mediaList(req.file, displayNameOf(req), k.displayPointer, true)),\n state(k.displayAssetUrns, []),\n state(k.saving, true),\n ],\n kind.screen,\n );\n}\n\n/** Step 3: put the uploaded image on the profile. */\nexport function saveBody(\n kind: ImageKind,\n req: ImageRequest & { originalId: string; displayId: string },\n) {\n const k = req.keys;\n const save = savePlan(kind, req);\n const values: Record<string, Value> = {\n [k.displayMedia]: mediaList(req.file, displayNameOf(req), k.displayPointer, true),\n [k.originalAssetUrns]: [req.originalId],\n [k.displayAssetUrns]: [req.displayId],\n [k.saving]: true,\n [focusKey(req.vanity)]: save.focusValue,\n };\n return serverRequest(\n kind.save,\n save.payload,\n save.keys.map((key) => state(key, values[key] as Value)),\n kind.screen,\n );\n}\n\n// ─── The register answer ──────────────────────────────────────────────────────\n\nexport interface Upload {\n url: string;\n headers: Record<string, string>;\n}\n\nexport type Registered =\n | {\n ok: true;\n originalId: string;\n displayId: string;\n uploads: { original: Upload; display: Upload };\n }\n | Failure;\n\ntype Node = Record<string, unknown>;\n\nfunction* walk(v: unknown): Generator<Node> {\n if (Array.isArray(v)) for (const x of v) yield* walk(x);\n else if (v !== null && typeof v === 'object') {\n yield v as Node;\n for (const x of Object.values(v)) yield* walk(x);\n }\n}\n\n/** `mediaTypeFamily` as the HTTP header the upload takes, `media-type-family`. */\nconst headerName = (key: string) => key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);\n\n/** The asset id a SetState puts in each key, keyed by that key. */\nfunction assetIdOf(n: Node): [string, string] | undefined {\n if (n.$type !== 'proto.sdui.actions.core.SetState') return undefined;\n const s = (n.value as Node | undefined)?.state as Node | undefined;\n const id = ((s?.key as Node | undefined)?.key as Node | undefined)?.value as Node | undefined;\n const list = ((s?.value as Node | undefined)?.stringListValue as Node | undefined)\n ?.stringValues as unknown[] | undefined;\n return typeof id?.id === 'string' && typeof list?.[0] === 'string' ? [id.id, list[0]] : undefined;\n}\n\n/** An upload instruction's file pointer, and its URL and headers ('multipart' if not one PUT). */\nfunction uploadOf(n: Node): [string, Upload | 'multipart'] | undefined {\n if (typeof n.fileReference !== 'string') return undefined;\n const instruction = (n.uploadInstruction as Node | undefined)?.instruction as Node | undefined;\n const single = instruction?.singleRequestUploadInstruction as Node | undefined;\n if (typeof single?.uploadUrl !== 'string') return [n.fileReference, 'multipart'];\n const headers: Record<string, string> = {};\n for (const h of (single.uploadHeaders as Node[] | undefined) ?? [])\n if (typeof h.key === 'string' && typeof h.value === 'string')\n headers[headerName(h.key)] = h.value;\n return [n.fileReference, { url: single.uploadUrl, headers }];\n}\n\nfunction rowZero(raw: string): unknown {\n const row = raw.match(/(?:^|\\n)0:(\\{.*)/)?.[1];\n try {\n return row === undefined ? undefined : JSON.parse(row);\n } catch {\n return undefined;\n }\n}\n\nexport function parseRegister(raw: string, keys: ImageKeys): Registered {\n const refused = responseErrors(raw);\n if (refused !== null)\n return { ok: false, code: 'INVALID_INPUT', message: `LinkedIn refused the image: ${refused}` };\n const ids = new Map<string, string>();\n const uploads = new Map<string, Upload | 'multipart'>();\n for (const n of walk(rowZero(raw))) {\n const id = assetIdOf(n);\n if (id !== undefined) ids.set(...id);\n const up = uploadOf(n);\n if (up !== undefined) uploads.set(...up);\n }\n const originalId = ids.get(keys.originalAssetUrns);\n const displayId = ids.get(keys.displayAssetUrns);\n const original = uploads.get(keys.originalPointer);\n const display = uploads.get(keys.displayPointer);\n if (original === 'multipart' || display === 'multipart')\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message:\n 'LinkedIn asked for a multi-part upload, which has not been observed here. Nothing was ' +\n 'uploaded. Try a smaller file.',\n };\n if (originalId === undefined || displayId === undefined || !original || !display)\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the image registration carried no asset ids or upload urls; nothing was uploaded',\n };\n return { ok: true, originalId, displayId, uploads: { original, display } };\n}\n\n// ─── The file ─────────────────────────────────────────────────────────────────\n\n/** A PNG's or JPEG's dimensions from its header, or null for anything else. */\nexport function imageSizeOf(\n bytes: Uint8Array,\n): { width: number; height: number; mimeType: string } | null {\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const png = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\n if (bytes.length >= 24 && png.every((b, i) => bytes[i] === b))\n return { width: view.getUint32(16), height: view.getUint32(20), mimeType: 'image/png' };\n if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return null;\n let at = 2;\n while (at + 9 <= bytes.length) {\n if (bytes[at] !== 0xff) return null;\n const marker = bytes[at + 1] as number;\n // SOF0–SOF15, except DHT (C4), JPG (C8) and DAC (CC).\n if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker))\n return {\n height: view.getUint16(at + 5),\n width: view.getUint16(at + 7),\n mimeType: 'image/jpeg',\n };\n at += 2 + view.getUint16(at + 2);\n }\n return null;\n}\n\n// ─── Reading it back ──────────────────────────────────────────────────────────\n\n/**\n * The owner's profile id and the asset id of each picture showing now, from\n * the full profile (engine/full-profile.ts). A picture not set is left out.\n */\nexport function picturesOf(\n json: unknown,\n): { ok: true; profileId: string; photo?: string; banner?: string } | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const urn = (root?.data?.['*elements'] as unknown[] | undefined)?.[0];\n const p = (root?.included ?? []).find((n) => n.entityUrn === urn);\n const profileId = typeof urn === 'string' ? urn.split(':').pop() : undefined;\n if (p === undefined || profileId === undefined)\n return { ok: false, code: 'SCHEMA_DRIFT', message: 'the profile answer carried no profile' };\n const asset = (pic: unknown) =>\n String((pic as Node | null)?.displayImageUrn ?? '').match(/digitalmediaAsset:(.+)$/)?.[1];\n const photo = asset(p.profilePicture);\n const banner = asset(p.backgroundPicture);\n return {\n ok: true,\n profileId,\n ...(photo !== undefined ? { photo } : {}),\n ...(banner !== undefined ? { banner } : {}),\n };\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","// ─── 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","// ─── 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","// ─── `lnrelay role add|edit|remove`, and `lnrelay experience` ─────────────────\n//\n// Roles on the owner's Experience section. Every change is planned from the\n// form LinkedIn holds now and read back afterwards; see engine/sdui-position.ts\n// for how a save is put together and why the headline is never touched.\n\nimport type { Session } from '../engine/auth.ts';\nimport { createEngine, createLiveClient } from '../engine/index.ts';\nimport type { Failure, Model } from '../engine/sdui-form.ts';\nimport {\n applyChanges,\n fetchPositions,\n openPositionForm,\n type Position,\n type PositionChanges,\n type PositionForm,\n roleSummary,\n sendPositionDelete,\n sendPositionSave,\n type YearMonth,\n} from '../engine/sdui-position.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { ConfirmDeps, WritePlan } from './confirm.ts';\nimport { refuseUnapprovable, terminalDeps } from './gate.ts';\nimport { authorLine, gate, prepare } from './write.ts';\n\n/** What a role change needs from LinkedIn. Injectable so tests send nothing. */\nexport interface RoleSurface {\n vanity(): Promise<{ ok: true; vanity: string } | Failure>;\n list(vanity: string): Promise<{ ok: true; positions: Position[] } | Failure>;\n open(payload: Record<string, unknown>, edit: boolean): Promise<PositionForm | Failure>;\n save(form: PositionForm, model: Model): Promise<{ ok: true } | Failure>;\n remove(form: PositionForm): Promise<{ ok: true } | Failure>;\n}\n\nfunction liveRoles(session: Session, quiet = false): RoleSurface {\n const client = createLiveClient(session, undefined, quiet);\n return {\n vanity: async () => {\n const me = await createEngine(session, undefined, quiet).whoami();\n if (!me.ok) return me;\n const id = me.value?.publicIdentifier;\n return typeof id === 'string' && id !== ''\n ? { ok: true, vanity: id }\n : { ok: false, code: 'SCHEMA_DRIFT', message: 'whoami returned no public profile id' };\n },\n list: (vanity) => fetchPositions(vanity, client),\n open: (payload, edit) => openPositionForm(payload, client, edit),\n save: (form, model) => sendPositionSave(form, model, client),\n remove: (form) => sendPositionDelete(form, client),\n };\n}\n\n/** What the CLI asked for, before validation. Dates are YYYY-MM. */\nexport interface RoleRequest {\n title?: string;\n company?: string;\n start?: string;\n end?: string;\n current?: boolean;\n description?: string;\n location?: string;\n notify?: boolean;\n}\n\nconst SUBCOMMANDS = 'add, edit <position-id>, remove <position-id>';\n\nfunction yearMonth(flag: string, v: string): YearMonth | Envelope {\n const m = /^(\\d{4})-(\\d{2})$/.exec(v);\n const month = Number(m?.[2]);\n if (m === null || month < 1 || month > 12) {\n return err(\n 'role',\n 'INVALID_INPUT',\n `--${flag} '${v}' is not a month`,\n 'use YYYY-MM, e.g. 2021-06',\n );\n }\n return { year: Number(m[1]), month };\n}\n\nfunction changesFrom(req: RoleRequest): PositionChanges | Envelope {\n const c: PositionChanges = {};\n if (req.title !== undefined) c.title = req.title;\n if (req.company !== undefined) c.company = req.company;\n if (req.description !== undefined) c.description = req.description;\n if (req.location !== undefined) c.location = req.location;\n if (req.notify === true) c.notify = true;\n if (req.start !== undefined) {\n const d = yearMonth('start', req.start);\n if ('ok' in d) return d;\n c.start = d;\n }\n if (req.current === true && req.end !== undefined) {\n return err('role', 'INVALID_INPUT', '--current and --end contradict each other');\n }\n if (req.current === true) c.end = 'present';\n else if (req.end !== undefined) {\n const d = yearMonth('end', req.end);\n if ('ok' in d) return d;\n c.end = d;\n }\n return c;\n}\n\nconst span = (s: ReturnType<typeof roleSummary>) =>\n `${s.start ?? '?'} – ${s.current ? 'present' : (s.end ?? '?')}`;\nconst q = (v: string) => `\"${v.length > 160 ? `${v.slice(0, 160)}…` : v.replace(/\\n/g, ' ')}\"`;\n\nfunction roleLines(s: ReturnType<typeof roleSummary>): string[] {\n return [\n `title ${q(s.title)}`,\n `company ${q(s.company)}`,\n `dates ${span(s)}`,\n ...(s.location === '' ? [] : [`location ${q(s.location)}`]),\n ...(s.description === '' ? [] : [`about ${q(s.description)}`]),\n ];\n}\n\n/** Only what differs, from → to. */\nfunction diffLines(a: ReturnType<typeof roleSummary>, b: ReturnType<typeof roleSummary>): string[] {\n const out: string[] = [];\n const row = (label: string, x: string, y: string) => {\n if (x !== y) out.push(`${label.padEnd(8)} ${q(x)} → ${q(y)}`);\n };\n row('title', a.title, b.title);\n row('company', a.company, b.company);\n row('dates', span(a), span(b));\n row('location', a.location, b.location);\n row('about', a.description, b.description);\n return out;\n}\n\nconst SAFETY = (notify: boolean) => [\n 'headline unchanged (LinkedIn would otherwise rewrite it from this role)',\n `notify ${notify ? 'ON — your network may be told' : 'off'}`,\n];\n\nexport async function runRole(\n sub: string | undefined,\n target: string | undefined,\n req: RoleRequest,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n surface?: RoleSurface,\n): Promise<Envelope> {\n if (sub !== 'add' && sub !== 'edit' && sub !== 'remove') {\n return err(\n 'role',\n 'INVALID_INPUT',\n `unknown role subcommand '${sub ?? ''}'`,\n `lnrelay role ${SUBCOMMANDS}`,\n );\n }\n if (sub === 'add') {\n const missing = (['title', 'company', 'start'] as const).filter(\n (f) => req[f] === undefined || req[f] === '',\n );\n if (missing.length > 0) {\n return err(\n 'role',\n 'INVALID_INPUT',\n `a new role needs ${missing.map((f) => `--${f}`).join(', ')}`,\n );\n }\n } else if (target === undefined || !/^\\d+$/.test(target)) {\n return err(\n 'role',\n 'INVALID_INPUT',\n `role ${sub} needs a position id`,\n 'list them with `lnrelay experience`',\n );\n }\n const changes = changesFrom(req);\n if ('ok' in changes) return changes;\n if (sub === 'edit' && Object.keys(changes).filter((k) => k !== 'notify').length === 0) {\n return err(\n 'role',\n 'INVALID_INPUT',\n 'nothing to change',\n 'pass --title, --company, --start, --end, --current, --location or --description',\n );\n }\n\n const unapprovable = refuseUnapprovable('role', 'changing a role', deps);\n if (unapprovable !== null) return unapprovable;\n const ctx = prepare('role', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager') {\n return err('role', 'NOT_IMPLEMENTED', 'role changes go over the browser session only');\n }\n const roles = surface ?? liveRoles(ctx.transport.session);\n const me = await roles.vanity();\n if (!me.ok) return err('role', me.code, me.message, me.hint);\n const listed = await roles.list(me.vanity);\n if (!listed.ok) return err('role', listed.code, listed.message, listed.hint);\n\n if (sub === 'add') return addRole(changes, me.vanity, listed.positions, roles, ctx, deps);\n const position = listed.positions.find((p) => p.positionId === target);\n if (position === undefined) {\n return err(\n 'role',\n 'NOT_FOUND',\n `no role ${target} on your profile`,\n `your roles: ${listed.positions.map((p) => `${p.positionId} (${p.title})`).join(', ') || 'none'}`,\n );\n }\n const form = await roles.open({ ...position.payload, vanityName: me.vanity }, true);\n if (!form.ok) return err('role', form.code, form.message, form.hint);\n return sub === 'edit'\n ? editRole(position, form, changes, me.vanity, roles, ctx, deps)\n : removeRole(position, form, me.vanity, roles, ctx, deps);\n}\n\ntype Ctx = Exclude<ReturnType<typeof prepare>, Envelope>;\n\nasync function addRole(\n changes: PositionChanges,\n vanity: string,\n before: Position[],\n roles: RoleSurface,\n ctx: Ctx,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n const form = await roles.open({ vanityName: vanity }, false);\n if (!form.ok) return err('role', form.code, form.message, form.hint);\n const applied = applyChanges(form, changes);\n if (!applied.ok) return err('role', applied.code, applied.message, applied.hint);\n const role = roleSummary(applied.model);\n\n const plan: WritePlan<{ changes: PositionChanges }> = {\n action: 'add a role to your profile',\n payload: { changes },\n summary: [authorLine(ctx.transport), ...roleLines(role), ...SAFETY(changes.notify === true)],\n reversibility: 'removable with `lnrelay role remove <position-id>`',\n transport: 'voyager',\n };\n const gated = await gate('role', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const saved = await roles.save(form, applied.model);\n if (!saved.ok) return err('role', saved.code, saved.message, saved.hint);\n const after = await roles.list(vanity);\n const known = new Set(before.map((p) => p.positionId));\n const added = after.ok\n ? after.positions.find((p) => !known.has(p.positionId) && p.title === role.title)\n : undefined;\n if (added === undefined) {\n return err(\n 'role',\n 'SCHEMA_DRIFT',\n 'LinkedIn accepted the role, but it does not appear on your profile',\n );\n }\n return ok('role', { added: added.positionId, verified: true });\n}\n\nasync function editRole(\n position: Position,\n form: PositionForm,\n changes: PositionChanges,\n vanity: string,\n roles: RoleSurface,\n ctx: Ctx,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n const applied = applyChanges(form, changes);\n if (!applied.ok) return err('role', applied.code, applied.message, applied.hint);\n const was = roleSummary(form.model);\n const will = roleSummary(applied.model);\n const diff = diffLines(was, will);\n if (diff.length === 0)\n return err('role', 'INVALID_INPUT', 'the role already reads exactly that; nothing to save');\n\n // `was` is bound: a role that changed after the preview is a different edit.\n const plan: WritePlan<{ positionId: string; was: typeof was; changes: PositionChanges }> = {\n action: 'edit a role on your profile',\n payload: { positionId: position.positionId, was, changes },\n summary: [\n authorLine(ctx.transport),\n `role ${position.positionId}`,\n ...diff,\n ...SAFETY(changes.notify === true),\n ],\n reversibility: 'editable again; the old values are kept only in this preview and the audit log',\n transport: 'voyager',\n };\n const gated = await gate('role', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const saved = await roles.save(form, applied.model);\n if (!saved.ok) return err('role', saved.code, saved.message, saved.hint);\n const reread = await roles.open({ ...position.payload, vanityName: vanity }, true);\n const now = reread.ok ? roleSummary(reread.model) : null;\n if (now === null || diffLines(will, now).length > 0) {\n return err(\n 'role',\n 'SCHEMA_DRIFT',\n 'LinkedIn accepted the edit, but the role does not read back as edited',\n );\n }\n return ok('role', { edited: position.positionId, verified: true });\n}\n\nasync function removeRole(\n position: Position,\n form: PositionForm,\n vanity: string,\n roles: RoleSurface,\n ctx: Ctx,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n const role = roleSummary(form.model);\n const plan: WritePlan<{ positionId: string; role: typeof role }> = {\n action: 'remove a role from your profile',\n payload: { positionId: position.positionId, role },\n summary: [authorLine(ctx.transport), `role ${position.positionId}`, ...roleLines(role)],\n reversibility: 'NONE. LinkedIn deletes it; re-adding makes a new role.',\n transport: 'voyager',\n };\n const gated = await gate('role', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const removed = await roles.remove(form);\n if (!removed.ok) return err('role', removed.code, removed.message, removed.hint);\n const after = await roles.list(vanity);\n if (!after.ok || after.positions.some((p) => p.positionId === position.positionId)) {\n return err(\n 'role',\n 'SCHEMA_DRIFT',\n 'LinkedIn accepted the removal, but the role is still listed',\n );\n }\n return ok('role', { removed: position.positionId, verified: true });\n}\n\n/** `lnrelay experience`: the roles on the owner's profile, with their ids. */\nexport async function runExperience(quiet = false): Promise<Envelope> {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('experience', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const roles = liveRoles(session.session, quiet);\n const me = await roles.vanity();\n if (!me.ok) return err('experience', me.code, me.message, me.hint);\n const listed = await roles.list(me.vanity);\n if (!listed.ok) return err('experience', listed.code, listed.message, listed.hint);\n return ok('experience', {\n items: listed.positions.map((p) => ({ positionId: p.positionId, title: p.title })),\n meta: { state: 'complete', returnedCount: listed.positions.length },\n });\n}\n","// ─── `lnrelay search <kind>` and `lnrelay search-filters <kind>` ──────────────\n//\n// For companies, groups, events, courses, products, services and schools; see\n// engine/search.ts. People and jobs have their own commands, which `search\n// people` and `search jobs` hand over to. Each call returns up to 50 results\n// and spends the search budget, as does a place looked up by name.\n\nimport { parsePeopleFilters } from '../engine/people.ts';\nimport {\n type Found,\n parseResults,\n SEARCH_PAGE,\n type SearchKindName,\n searchUrl,\n} from '../engine/search.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport {\n keywordSets,\n line,\n type Matched,\n metaOf,\n type PageFetch,\n type Paging,\n searchAll,\n} from './paged.ts';\nimport { type Lookup, liveFetch, type PeopleFetch, resolvePlace, shape } from './people.ts';\n\nexport interface FindRequest {\n keywords?: string | string[];\n limit: number;\n start?: number;\n /** A place by name, looked up, for the kinds that filter by place. */\n location?: string;\n industry?: string[];\n /** 1st, 2nd, 3rd+. */\n network?: string[];\n /** `key=v1,v2`, by LinkedIn's own names, from `search-filters <kind>`. */\n raw?: string[];\n}\n\n/** LinkedIn pages no further than 1000 into any one query. */\nconst PAGING: Paging = { pageSize: SEARCH_PAGE, max: 1000 };\n\n/** The friendly flags, and the parameter each kind knows them by. */\nconst FLAGS: Record<\n 'location' | 'industry' | 'network',\n Partial<Record<SearchKindName, string>>\n> = {\n location: { companies: 'companyHqGeo', services: 'geoUrn' },\n industry: { companies: 'industryCompanyVertical' },\n network: { companies: 'network', services: 'network' },\n};\n\nconst NETWORK: Record<string, string> = {\n '1st': 'F',\n '2nd': 'S',\n '3rd+': 'O',\n F: 'F',\n S: 'S',\n O: 'O',\n};\n\ntype Refusal = { ok: false; code: string; message: string; hint?: string };\n\nfunction paramFor(flag: keyof typeof FLAGS, kind: SearchKindName): string | Refusal {\n const param = FLAGS[flag][kind];\n if (param !== undefined) return param;\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `${kind} cannot be filtered by --${flag}`,\n hint: `--${flag} works for: ${Object.keys(FLAGS[flag]).join(', ')}; other filters are in \\`search-filters ${kind}\\``,\n };\n}\n\n/** The request's filters as LinkedIn's parameters; a place is looked up. */\nasync function paramsOf(\n kind: SearchKindName,\n req: Omit<FindRequest, 'limit'>,\n get: PeopleFetch,\n): Promise<{ params: Record<string, string[]>; resolved: Record<string, Lookup> } | Refusal> {\n const params: Record<string, string[]> = {};\n const resolved: Record<string, Lookup> = {};\n if (req.industry !== undefined && req.industry.length > 0) {\n const p = paramFor('industry', kind);\n if (typeof p !== 'string') return p;\n params[p] = req.industry;\n }\n if (req.network !== undefined && req.network.length > 0) {\n const p = paramFor('network', kind);\n if (typeof p !== 'string') return p;\n const codes = req.network.map((n) => NETWORK[n]);\n if (codes.some((c) => c === undefined))\n return { ok: false, code: 'INVALID_INPUT', message: '--network takes 1st, 2nd, 3rd+' };\n params[p] = codes as string[];\n }\n for (const r of req.raw ?? []) {\n const m = r.match(/^([A-Za-z_]+)=(.+)$/);\n if (m?.[1] === undefined || m[2] === undefined)\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `--filter '${r}' is not key=value[,value]`,\n };\n params[m[1]] = m[2]\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v !== '');\n }\n if (req.location !== undefined && req.location.trim() !== '') {\n const p = paramFor('location', kind);\n if (typeof p !== 'string') return p;\n const place = await resolvePlace(get, req.location.trim());\n if ('ok' in place) return place;\n params[p] = [...(params[p] ?? []), place.id];\n resolved.location = place;\n }\n return { params, resolved };\n}\n\nfunction compactFound(f: Matched<Found>): string {\n return line([\n f.id,\n f.name,\n f.subtitle,\n f.detail,\n f.verified ? 'verified' : undefined,\n f.summary !== undefined && f.summary.length > 120 ? `${f.summary.slice(0, 117)}…` : f.summary,\n f.url,\n f.matched !== undefined ? `matched: ${f.matched.join(' + ')}` : undefined,\n ]);\n}\n\nexport async function runFind(\n kind: SearchKindName,\n req: FindRequest,\n opts: OutputOpts = {},\n fetch?: PeopleFetch,\n): Promise<Envelope> {\n const command = `search ${kind}`;\n const sets = keywordSets(req.keywords);\n const anyFilter =\n (req.location ?? '').trim() !== '' ||\n (req.industry?.length ?? 0) > 0 ||\n (req.network?.length ?? 0) > 0 ||\n (req.raw?.length ?? 0) > 0;\n if (sets.length === 0 && !anyFilter) {\n return err(\n command,\n 'INVALID_INPUT',\n 'give keywords, a filter, or both',\n `lnrelay search ${kind} \"<keywords>\"`,\n );\n }\n const get = fetch ?? liveFetch(command, opts.quiet === true);\n if (typeof get !== 'function') return get;\n const p = await paramsOf(kind, req, get);\n if ('ok' in p) return err(command, p.code, p.message, p.hint);\n\n const first = Math.max(0, req.start ?? 0);\n const want = Math.max(1, Math.min(req.limit, PAGING.max - first));\n const fetchPage: PageFetch<Found> = async (keywords, start) => {\n const res = await get(\n searchUrl({ kind, ...(keywords ? { keywords } : {}), params: p.params, start }),\n 'search',\n );\n const page = res.ok ? parseResults(res.json) : res;\n if (!page.ok) return page;\n return {\n ok: true,\n items: page.items,\n ...(page.total !== undefined ? { total: page.total } : {}),\n ...(page.claimed !== undefined ? { claimed: page.claimed } : {}),\n unknownTypes: page.unknownTypes,\n };\n };\n const merged = await searchAll(\n fetchPage,\n sets.length > 0 ? sets : [undefined],\n first,\n want,\n PAGING,\n );\n if (merged.rows.length === 0 && merged.failure !== undefined) {\n const f = merged.failure;\n return err(command, f.code, f.message, f.hint);\n }\n const single = sets.length <= 1;\n return ok('search', {\n kind,\n query: { ...(sets.length > 0 ? { keywords: single ? sets[0] : sets } : {}), params: p.params },\n ...(Object.keys(p.resolved).length > 0 ? { resolved: p.resolved } : {}),\n items: shape(merged.rows, opts, compactFound),\n meta: metaOf(command, merged, single, first),\n });\n}\n\nexport async function runFindFilters(\n kind: SearchKindName,\n req: Omit<FindRequest, 'limit'>,\n opts: OutputOpts = {},\n fetch?: PeopleFetch,\n): Promise<Envelope> {\n const command = `search-filters ${kind}`;\n const sets = keywordSets(req.keywords);\n if (sets.length > 1)\n return err(\n command,\n 'INVALID_INPUT',\n 'search-filters takes one keyword set: its counts belong to that one query',\n );\n const get = fetch ?? liveFetch(command, opts.quiet === true);\n if (typeof get !== 'function') return get;\n const p = await paramsOf(kind, req, get);\n if ('ok' in p) return err(command, p.code, p.message, p.hint);\n const res = await get(\n searchUrl({\n kind,\n ...(sets[0] !== undefined ? { keywords: sets[0] } : {}),\n params: p.params,\n start: 0,\n withFilters: true,\n }),\n 'search',\n );\n const parsed = res.ok ? parsePeopleFilters(res.json) : res;\n if (!parsed.ok) return err(command, parsed.code, parsed.message, parsed.hint);\n return ok('search-filters', {\n kind,\n ...(Object.keys(p.resolved).length > 0 ? { resolved: p.resolved } : {}),\n items: shape(parsed.filters, opts, (f) => {\n const how = f.input === 'text' ? 'free text' : 'ids';\n const options = f.options\n .map((o) => `${o.value}=${o.label}${o.count !== undefined ? ` (${o.count})` : ''}`)\n .join(', ');\n return `${f.key} [${how}]${options !== '' ? `: ${options}` : ''}`;\n }),\n meta: { state: 'complete', operation: command, returnedCount: parsed.filters.length },\n });\n}\n","// ─── `lnrelay skill add|remove`, and `lnrelay skills` ─────────────────────────\n//\n// See engine/sdui-skill.ts. Every change is planned from what the profile\n// holds now and read back afterwards.\n\nimport type { Session } from '../engine/auth.ts';\nimport { createEngine, createLiveClient } from '../engine/index.ts';\nimport type { Failure } from '../engine/sdui-form.ts';\nimport {\n addSkillBody,\n fetchSkills,\n openSkillForm,\n removeSkillBody,\n SKILL,\n type Skill,\n type SkillForm,\n sendSkill,\n skillNameOf,\n} from '../engine/sdui-skill.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { ConfirmDeps, WritePlan } from './confirm.ts';\nimport { refuseUnapprovable, terminalDeps } from './gate.ts';\nimport { authorLine, gate, prepare } from './write.ts';\n\n/** What a skill change needs from LinkedIn. Injectable so tests send nothing. */\nexport interface SkillSurface {\n vanity(): Promise<{ ok: true; vanity: string } | Failure>;\n list(vanity: string): Promise<{ ok: true; skills: Skill[] } | Failure>;\n open(payload: Record<string, unknown>, edit: boolean): Promise<SkillForm | Failure>;\n send(body: unknown, requestId: string): Promise<{ ok: true } | Failure>;\n}\n\nfunction liveSkills(session: Session, quiet = false): SkillSurface {\n const client = createLiveClient(session, undefined, quiet);\n return {\n vanity: async () => {\n const me = await createEngine(session, undefined, quiet).whoami();\n if (!me.ok) return me;\n const id = me.value?.publicIdentifier;\n return typeof id === 'string' && id !== ''\n ? { ok: true, vanity: id }\n : { ok: false, code: 'SCHEMA_DRIFT', message: 'whoami returned no public profile id' };\n },\n list: (vanity) => fetchSkills(vanity, client),\n open: (payload, edit) => openSkillForm(payload, client, edit),\n send: (body, requestId) => sendSkill(body, requestId, client),\n };\n}\n\nconst listed = (skills: Skill[]) =>\n skills.map((s) => `${s.skillId} (${s.name ?? '?'})`).join(', ') || 'none';\n\nexport async function runSkill(\n sub: string | undefined,\n arg: string | undefined,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n surface?: SkillSurface,\n): Promise<Envelope> {\n if (sub !== 'add' && sub !== 'remove') {\n return err(\n 'skill',\n 'INVALID_INPUT',\n `unknown skill subcommand '${sub ?? ''}'`,\n 'lnrelay skill add \"<name>\" | lnrelay skill remove <skill-id>',\n );\n }\n if (arg === undefined || arg.trim() === '') {\n return err(\n 'skill',\n 'INVALID_INPUT',\n sub === 'add' ? 'the skill name is required' : 'the skill id is required',\n 'ids come from `lnrelay skills`',\n );\n }\n const unapprovable = refuseUnapprovable('skill', 'changing your skills', deps);\n if (unapprovable !== null) return unapprovable;\n const ctx = prepare('skill', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager')\n return err('skill', 'NOT_IMPLEMENTED', 'skill changes go over the browser session only');\n\n const skills = surface ?? liveSkills(ctx.transport.session);\n const me = await skills.vanity();\n if (!me.ok) return err('skill', me.code, me.message, me.hint);\n const before = await skills.list(me.vanity);\n if (!before.ok) return err('skill', before.code, before.message, before.hint);\n\n return sub === 'add'\n ? addSkill(arg.trim(), before.skills, me.vanity, skills, ctx, deps)\n : removeSkill(arg, before.skills, me.vanity, skills, ctx, deps);\n}\n\ntype Ctx = Exclude<ReturnType<typeof prepare>, Envelope>;\n\nasync function addSkill(\n name: string,\n current: Skill[],\n vanity: string,\n skills: SkillSurface,\n ctx: Ctx,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n const dup = current.find((s) => s.name?.toLowerCase() === name.toLowerCase());\n if (dup !== undefined)\n return err(\n 'skill',\n 'INVALID_INPUT',\n `\"${dup.name}\" is already on your profile (${dup.skillId})`,\n );\n const form = await skills.open({ vanityName: vanity }, false);\n if (!form.ok) return err('skill', form.code, form.message, form.hint);\n const body = addSkillBody(form, name);\n if (!body.ok) return err('skill', body.code, body.message, body.hint);\n\n const plan: WritePlan<{ name: string }> = {\n action: 'add a skill to your profile',\n payload: { name },\n summary: [\n authorLine(ctx.transport),\n `skill \"${name}\"`,\n 'linked to nothing (no roles, schools or projects)',\n ],\n reversibility: 'removable with `lnrelay skill remove <skill-id>`',\n transport: 'voyager',\n };\n const gated = await gate('skill', plan, ctx, deps);\n if ('ok' in gated) return gated;\n const sent = await skills.send(body.body, SKILL.save);\n if (!sent.ok) return err('skill', sent.code, sent.message, sent.hint);\n const after = await skills.list(vanity);\n const known = new Set(current.map((s) => s.skillId));\n const added = after.ok ? after.skills.find((s) => !known.has(s.skillId)) : undefined;\n if (added === undefined)\n return err(\n 'skill',\n 'SCHEMA_DRIFT',\n 'LinkedIn accepted the skill, but it does not appear on your profile',\n );\n return ok('skill', { added: added.skillId, name: added.name, verified: true });\n}\n\nasync function removeSkill(\n arg: string,\n current: Skill[],\n vanity: string,\n skills: SkillSurface,\n ctx: Ctx,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n const target = current.find((s) => s.skillId === arg);\n if (target === undefined)\n return err(\n 'skill',\n 'NOT_FOUND',\n `no skill ${arg} on your profile`,\n `your skills: ${listed(current)}`,\n );\n const form = await skills.open({ ...target.payload, vanityName: vanity }, true);\n if (!form.ok) return err('skill', form.code, form.message, form.hint);\n const body = removeSkillBody(form);\n if (!body.ok) return err('skill', body.code, body.message, body.hint);\n const name = skillNameOf(form) ?? target.name ?? '?';\n\n const plan: WritePlan<{ skillId: string; name: string }> = {\n action: 'remove a skill from your profile',\n payload: { skillId: target.skillId, name },\n summary: [authorLine(ctx.transport), `skill \"${name}\" (${target.skillId})`],\n reversibility:\n 'NONE for its endorsements, which go with it; the skill itself can be added again',\n transport: 'voyager',\n };\n const gated = await gate('skill', plan, ctx, deps);\n if ('ok' in gated) return gated;\n const sent = await skills.send(body.body, SKILL.delete);\n if (!sent.ok) return err('skill', sent.code, sent.message, sent.hint);\n const after = await skills.list(vanity);\n if (!after.ok || after.skills.some((s) => s.skillId === target.skillId)) {\n return err(\n 'skill',\n 'SCHEMA_DRIFT',\n 'LinkedIn accepted the removal, but the skill is still listed',\n );\n }\n return ok('skill', { removed: target.skillId, verified: true });\n}\n\n/** `lnrelay skills`: the skills on the owner's profile, with their ids. */\nexport async function runSkills(quiet = false): Promise<Envelope> {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('skills', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const skills = liveSkills(session.session, quiet);\n const me = await skills.vanity();\n if (!me.ok) return err('skills', me.code, me.message, me.hint);\n const listedSkills = await skills.list(me.vanity);\n if (!listedSkills.ok)\n return err('skills', listedSkills.code, listedSkills.message, listedSkills.hint);\n return ok('skills', {\n items: listedSkills.skills.map((s) => ({ skillId: s.skillId, name: s.name })),\n meta: { state: 'complete', returnedCount: listedSkills.skills.length },\n });\n}\n","// ─── Who viewed the owner's profile ───────────────────────────────────────────\n//\n// Captured 2026-10-16. /me/profile-views/ (now /analytics/profile-views/) is\n// drawn by two SDUI server requests: WvmpAnalytics, the total over the page's\n// default range (past 90 days), and WvmpEntityList, the viewers newest first.\n// Both answer in the session's language, so nothing here reads LinkedIn's\n// words for meaning beyond the \"•\" before a degree.\n//\n// The list: each viewer is its own RSC row, tracked `viewer-list-item`. A\n// named viewer links to their /in/ profile; an anonymous one (\"Founder in the\n// Software industry from Budapest\") links to a people search instead. The\n// viewer's profile id is not in their row: it is in the Connect or Message\n// action, the rows the list references right after the viewer's. Private-mode\n// viewers are only a count (\"4 LinkedIn members\"), outside every row.\n//\n// A free account shows up to 3 viewers; the list has a next-page marker\n// (`wvmp-entity-list-next-page-loaded`) that was not exercised.\n//\n// Premium (captured 2026-11-22) names every viewer in the range, in one\n// answer, and takes a date range: 7, 14, 28, 90 or 365 days, the value of the\n// range state (`WvmpSearchFilterTimeRange_LAST_365_DAYS`). Its totals add\n// highlights (top location, industry, company: value then label, between the\n// `highlights` and `details` markers) and the companies viewers work at, each\n// a name and \"(25%)\". Since then both requests answer 500 without a referer.\n\nimport { Rows } from './posts.ts';\nimport type { Failure } from './sdui-form.ts';\n\nconst SERVER_REQUEST = 'https://www.linkedin.com/flagship-web/rsc-action/actions/server-request';\nexport const VIEWERS_URL = `${SERVER_REQUEST}?sduiid=WvmpEntityList`;\nexport const VIEW_TOTALS_URL = `${SERVER_REQUEST}?sduiid=WvmpAnalytics`;\n\n/** Both requests answer 500 without a referer (since 2026-11); any LinkedIn page will do. */\nexport const VIEWERS_REFERER = 'https://www.linkedin.com/analytics/profile-views/';\n\n/** The ranges the page offers, in days. */\nexport const VIEW_RANGES = [7, 14, 28, 90, 365] as const;\nexport type ViewRange = (typeof VIEW_RANGES)[number];\n\nconst RANGE = 'WvmpSearchFilterType_DATE_RANGE';\nconst META = { $type: 'proto.sdui.common.RequestMetadata' } as const;\n\n/** The page's own request: its id, payload, and the date-range state it is keyed by. */\nfunction serverRequest(\n requestId: string,\n stateKey: string,\n payload: Record<string, unknown>,\n days: ViewRange | undefined,\n) {\n const state = {\n key: stateKey,\n namespace: 'MemoryNamespace',\n value: days === undefined ? [] : [`WvmpSearchFilterTimeRange_LAST_${days}_DAYS`],\n originalProtoCase: 'stringListValue',\n protoKey: { $type: 'proto.sdui.Key', value: { $case: 'id', id: stateKey } },\n };\n const requestedArguments = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [{ key: { value: { $case: 'id', id: stateKey } } }],\n payload: {\n ...payload,\n filterTypeList: [RANGE],\n dateRangeSelectionFilters: { key: stateKey, namespace: 'MemoryNamespace' },\n },\n requestMetadata: META,\n };\n return {\n requestId,\n serverRequest: {\n requestId,\n requestedArguments,\n isApfcEnabled: false,\n isStreaming: false,\n rumPageKey: '',\n },\n states: [state],\n requestedArguments: {\n ...requestedArguments,\n states: [state],\n screenId: 'com.linkedin.sdui.flagshipnav.home.Home',\n knownTemplateIds: [],\n },\n };\n}\n\nexport function viewersBody(days?: ViewRange) {\n return serverRequest(\n 'WvmpEntityList',\n `entityListQueryFilterPrefix${RANGE}`,\n { sortType: 'ProfileViewSortType_TIME_DESCENDING' },\n days,\n );\n}\n\nexport function viewTotalsBody(days?: ViewRange) {\n return serverRequest(\n 'WvmpAnalytics',\n `analyticsFieldsFilterPrefix${RANGE}`,\n {\n highlightCardDimensions: [\n 'DimensionType_LOCATION',\n 'DimensionType_INDUSTRY',\n 'DimensionType_ORGANIZATION',\n ],\n detailsCardDimensions: ['DimensionType_ORGANIZATION'],\n highlightCardResultCount: 4,\n detailsCardResultCount: 23,\n },\n days,\n );\n}\n\nexport type Viewer =\n | {\n name: string;\n /** Their profile id: what `profile`, `messages` and `people --connection-of` take. */\n id?: string;\n url: string;\n /** Connection degree, as LinkedIn words it in the session's language. */\n degree?: string;\n headline?: string;\n /** When, as LinkedIn words it (\"2d ago\"). */\n viewed?: string;\n }\n | {\n anonymous: true;\n /** What LinkedIn says of them instead (\"Founder in the Software industry from …\"). */\n description: string;\n viewed?: string;\n /** The people search LinkedIn links them to. */\n searchUrl?: string;\n };\n\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst unquote = (s: string) => JSON.parse(`\"${s}\"`) as string;\nconst STR = '((?:[^\"\\\\\\\\]|\\\\\\\\.)+)';\n\nconst ITEM =\n /\"viewName\":\"viewer-list-item\"(?:,\"impressionThresholds\":\\[[^\\]]*\\])?[^{}]*\"semanticPosition\"/;\n/** Size and weight, whatever style props sit between them and the text (Premium adds two). */\nconst TEXT_PROPS =\n /\"textProps\":\\{\"fontFamily\":\"[^\"]*\",\"fontSize\":\"(\\w+)\",\"fontStyle\":\"[^\"]*\",\"fontWeight\":\"(\\w+)\"(?:,\"\\w+\":\"[^\"]*\")*?,\"children\":/g;\nconst OWN_TEXT = new RegExp(`^\\\\[\"${STR}\"\\\\]`);\nconst NESTED_TEXT = new RegExp(`\\\\[null,\"${STR}\"`);\nconst LINK = new RegExp(`\"urlValue\":\\\\{\"\\\\$case\":\"url\",\"url\":\"${STR}\"`);\nconst PROFILE_ID = /ACoA[A-Za-z0-9_-]{10,}/;\nconst PLAIN_TEXT = new RegExp(`\"children\":\\\\[\"${STR}\"\\\\]`, 'g');\n\n/** Each text in a viewer's row: its size and weight, then what it says. */\nfunction textsOf(row: string): { size: string; weight: string; text: string }[] {\n return [...row.matchAll(TEXT_PROPS)].flatMap((m) => {\n const after = row.slice((m.index ?? 0) + m[0].length, (m.index ?? 0) + m[0].length + 600);\n const raw = after.match(OWN_TEXT)?.[1] ?? after.match(NESTED_TEXT)?.[1];\n if (raw === undefined) return [];\n const text = unquote(raw).trim();\n return text === '' ? [] : [{ size: m[1] as string, weight: m[2] as string, text }];\n });\n}\n\nfunction viewerOf(row: string, id: string | undefined): Viewer | undefined {\n // In order: the name (or the anonymous description), the degree, the\n // headline, and last when they looked.\n const texts = textsOf(row);\n const at = texts.findIndex((t) => t.size === 'medium' && t.weight === 'bold');\n const first = texts[at]?.text;\n if (first === undefined) return undefined;\n const rest = texts.slice(at + 1).map((t) => t.text);\n const degreeText = rest.find((t) => t.startsWith('•'));\n const lines = rest.filter((t) => t !== degreeText);\n const viewed = lines.at(-1);\n const link = row.match(LINK)?.[1];\n const url = link === undefined ? undefined : unquote(link);\n if (url === undefined || !/linkedin\\.com\\/in\\//.test(url)) {\n const v: Viewer = { anonymous: true, description: first };\n if (viewed !== undefined) v.viewed = viewed;\n if (url !== undefined) v.searchUrl = url;\n return v;\n }\n const degree = degreeText?.replace(/^•\\s*/, '');\n const headline = lines.length > 1 ? lines[0] : undefined;\n return {\n name: first,\n ...(id !== undefined ? { id } : {}),\n url,\n ...(degree !== undefined ? { degree } : {}),\n ...(headline !== undefined ? { headline } : {}),\n ...(viewed !== undefined ? { viewed } : {}),\n };\n}\n\n/**\n * Whole-row references only: `$L` (lazy), `$Q` (a map) or bare. A `$b:4:props…`\n * path points back INTO a row, here into the list itself, and is not followed.\n */\nconst REF = /\"\\$[LQ]?([0-9a-f]+)\"/g;\n\n/** The first profile id in `ref` or the rows it references, never via a viewer's row. */\nfunction idUnder(rows: Rows, ref: string, items: Set<string>): string | undefined {\n const seen = new Set([ref]);\n const queue = [ref];\n while (queue.length > 0 && seen.size < 200) {\n const row = rows.byId.get(queue.shift() as string) ?? '';\n const id = row.match(PROFILE_ID)?.[0];\n if (id !== undefined) return id;\n for (const m of row.matchAll(REF)) {\n const next = m[1] as string;\n if (!seen.has(next) && !items.has(next) && rows.byId.has(next)) {\n seen.add(next);\n queue.push(next);\n }\n }\n }\n return undefined;\n}\n\n/**\n * Each viewer's profile id, from the action that follows their row: written\n * inline after the reference to it (Premium), or in a row referenced there.\n */\nfunction idsByViewer(rows: Rows, items: Set<string>): Map<string, string> {\n const ids = new Map<string, string>();\n for (const row of rows.byId.values()) {\n let current: string | undefined;\n let from = 0;\n // The first id found after a viewer's reference, inline or referenced, is theirs.\n const settle = (id: string | undefined) => {\n if (current !== undefined && id !== undefined && !ids.has(current)) ids.set(current, id);\n };\n for (const m of row.matchAll(REF)) {\n const ref = m[1] as string;\n const at = m.index ?? 0;\n settle(row.slice(from, at).match(PROFILE_ID)?.[0]);\n from = at + m[0].length;\n if (items.has(ref)) current = ref;\n else if (current !== undefined && !ids.has(current)) settle(idUnder(rows, ref, items));\n }\n settle(row.slice(from).match(PROFILE_ID)?.[0]);\n }\n return ids;\n}\n\nexport function parseViewers(\n stream: string,\n): { ok: true; viewers: Viewer[]; privateViewers?: number } | Failure {\n if (!stream.includes('\"viewName\":\"viewer-list\"'))\n return drift('the profile viewers answer was not the viewer list');\n const rows = new Rows(stream);\n const items = new Set([...rows.byId].filter(([, row]) => ITEM.test(row)).map(([id]) => id));\n const ids = idsByViewer(rows, items);\n const viewers = [...items].flatMap((id) => viewerOf(rows.byId.get(id) ?? '', ids.get(id)) ?? []);\n const shown = Math.max(items.size, (stream.match(new RegExp(ITEM, 'g')) ?? []).length);\n if (shown > 0 && viewers.length === 0)\n return drift(`${shown} profile viewers were shown but none could be read`);\n\n // \"4 LinkedIn members\": the one number outside every viewer's row.\n let privateViewers: number | undefined;\n for (const [id, row] of rows.byId) {\n if (items.has(id) || privateViewers !== undefined) continue;\n for (const m of row.matchAll(PLAIN_TEXT)) {\n const n = unquote(m[1] as string).match(/^(\\d[\\d.,\\s]*)\\s+\\D/)?.[1];\n if (n !== undefined) {\n privateViewers = Number(n.replace(/\\D/g, ''));\n break;\n }\n }\n }\n return privateViewers === undefined\n ? { ok: true, viewers }\n : { ok: true, viewers, privateViewers };\n}\n\nexport interface ViewTotals {\n ok: true;\n total: number;\n /** The total's own label, when it names the period (\"… in the past 90 days\"). */\n period?: string;\n /** Premium: top location, industry and company, labelled as LinkedIn words it. */\n highlights?: { label: string; value: string }[];\n /** Premium: the companies viewers work at, with their share in percent. */\n companies?: { name: string; share: number }[];\n}\n\nconst textsIn = (s: string) =>\n [...s.matchAll(PLAIN_TEXT)].map((m) => unquote(m[1] as string).trim());\n\n/** Value, label, value, label…, after the section's heading. */\nfunction highlightsOf(stream: string): { label: string; value: string }[] {\n const from = stream.indexOf('\"viewName\":\"highlights\"');\n if (from === -1) return [];\n const to = stream.indexOf('\"viewName\":\"details\"', from);\n const texts = textsIn(stream.slice(from, to === -1 ? undefined : to)).slice(1);\n const out: { label: string; value: string }[] = [];\n for (let i = 0; i + 1 < texts.length; i += 2)\n out.push({ value: texts[i] as string, label: texts[i + 1] as string });\n return out;\n}\n\n/** Each name followed by \"(N%)\", once. */\nfunction companiesOf(texts: string[]): { name: string; share: number }[] {\n const seen = new Map<string, number>();\n texts.forEach((t, i) => {\n const share = t.match(/^\\((\\d+)\\s*%\\)$/)?.[1];\n const name = texts[i - 1];\n if (share !== undefined && name !== undefined && !seen.has(name)) seen.set(name, Number(share));\n });\n return [...seen].map(([name, share]) => ({ name, share }));\n}\n\nexport function parseViewTotals(stream: string): ViewTotals | Failure {\n const texts = textsIn(stream);\n const at = texts.findIndex((t) => /^\\d[\\d.,\\s]*$/.test(t));\n if (at === -1) return drift('the profile view totals carried no number');\n const total = Number((texts[at] as string).replace(/\\D/g, ''));\n // The free page labels its total with the period; Premium only \"profile viewers\".\n const label = texts[at + 1];\n const highlights = highlightsOf(stream);\n const companies = companiesOf(texts);\n return {\n ok: true,\n total,\n ...(label !== undefined && /\\d/.test(label) ? { period: label } : {}),\n ...(highlights.length > 0 ? { highlights } : {}),\n ...(companies.length > 0 ? { companies } : {}),\n };\n}\n","// ─── `lnrelay viewers` ────────────────────────────────────────────────────────\n//\n// Who viewed the owner's profile, as their profile-views page shows it; see\n// engine/profile-views.ts. Two page calls: the total, then the viewers. A free\n// account is shown up to 3 viewers of the total, Premium every one; the result\n// is `partial` whenever LinkedIn counts more than it names and counts as\n// private. Premium also takes a range (--days) and adds highlights and the\n// companies viewers work at.\n\nimport { createLiveClient } from '../engine/index.ts';\nimport {\n parseViewers,\n parseViewTotals,\n VIEW_TOTALS_URL,\n VIEWERS_REFERER,\n VIEWERS_URL,\n type Viewer,\n type ViewRange,\n viewersBody,\n viewTotalsBody,\n} from '../engine/profile-views.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope, FetchState } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; raw: string }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted POST. Injectable so tests send nothing. */\nexport type ViewersFetch = (url: string, body: unknown, spendClass: 'page') => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): ViewersFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('viewers', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, body, spendClass) => {\n const r = await client.request({\n url,\n method: 'POST',\n body,\n headers: { referer: VIEWERS_REFERER },\n spendClass,\n operation: 'viewers',\n });\n if (!r.ok) return r;\n return { ok: true, raw: (r.classification as { raw?: string }).raw ?? '' };\n };\n}\n\nconst compactViewer = (v: Viewer) =>\n 'anonymous' in v\n ? line(['anonymous', v.description, v.viewed])\n : line([v.name, v.degree, v.headline, v.viewed, v.url]);\n\nexport async function runViewers(\n opts: OutputOpts & { days?: ViewRange } = {},\n fetch?: ViewersFetch,\n): Promise<Envelope> {\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n\n const totalsRes = await get(VIEW_TOTALS_URL, viewTotalsBody(opts.days), 'page');\n const totals = totalsRes.ok ? parseViewTotals(totalsRes.raw) : totalsRes;\n const listRes = await get(VIEWERS_URL, viewersBody(opts.days), 'page');\n const list = listRes.ok ? parseViewers(listRes.raw) : listRes;\n if (!list.ok) return err('viewers', list.code, list.message, list.hint);\n\n const shown = list.viewers.length;\n // Complete when the named and the private add up to the total exactly. A\n // free account's counts do not (3 named and 4 private of 5): it holds back.\n const accounted =\n totals.ok && (totals.total <= shown || shown + (list.privateViewers ?? 0) === totals.total);\n const state: FetchState = !totals.ok ? 'unknown' : accounted ? 'complete' : 'partial';\n const { ok: _ok, ...summary } = totals.ok ? totals : { ok: false };\n return ok('viewers', {\n ...(opts.days !== undefined ? { days: opts.days } : {}),\n ...(totals.ok ? summary : { totalError: `${totals.code}: ${totals.message}` }),\n ...(list.privateViewers !== undefined ? { privateViewers: list.privateViewers } : {}),\n items: shape(list.viewers, opts, compactViewer),\n meta: { state, operation: 'viewers', returnedCount: shown },\n });\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"],"mappings":";;;AAkBA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,SAAS;;;ACHlB,SAAS,gBAAgB;AACzB,SAAS,aAAAA,YAAW,cAAAC,mBAAkB;;;ACAtC,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC/E,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAEvB,SAAS,WAAmB;AACjC,SAAO,QAAQ,IAAI,qBAAqB,KAAK,QAAQ,GAAG,UAAU;AACpE;AAEO,SAAS,aAAa,OAAyB;AACpD,SAAO,KAAK,SAAS,GAAG,GAAG,KAAK;AAClC;AAaO,SAAS,SAAY,MAA6B;AACvD,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO,EAAE,OAAO,UAAU;AAEjD,MAAI;AACJ,MAAI;AACF,UAAM,aAAa,MAAM,OAAO;AAAA,EAClC,SAAS,GAAG;AACV,WAAO,WAAW,MAAM,eAAgB,EAAY,OAAO,EAAE;AAAA,EAC/D;AAEA,MAAI;AACF,WAAO,EAAE,OAAO,MAAM,OAAO,KAAK,MAAM,GAAG,EAAO;AAAA,EACpD,SAAS,GAAG;AACV,WAAO,WAAW,MAAM,qBAAsB,EAAY,OAAO,EAAE;AAAA,EACrE;AACF;AAEA,SAAS,WAAW,MAAc,QAAmC;AACnE,QAAM,SAAQ,oBAAI,KAAK,GAAE,YAAY,EAAE,QAAQ,SAAS,GAAG;AAC3D,QAAMC,UAAS,UAAU,cAAc,OAAO,KAAK,MAAM,GAAG,EAAE,IAAI,KAAK,MAAM;AAC7E,MAAI;AACF,cAAU,QAAQA,OAAM,GAAG,EAAE,WAAW,KAAK,CAAC;AAC9C,eAAW,MAAMA,OAAM;AAAA,EACzB,QAAQ;AAAA,EAGR;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IAC7E;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IAGA,CAAC;AAAA,IACD,YAAY,MAAM,eAAe,CAAC;AAAA,EACpC;AAEA,SAAO;AACT;AAEA,IAAMC,SAAQ,iBAAiB,QAAQ,KAAK,CAAC,GAAG,YAAY,KAAK,YAAY,MAAM;AAAA,EACjF;AAAA,EACA;AACF,CAAC;AAED,IAAIA,OAAM,KAAK;AACb,QAAM,SAAS,YAAY;AAC3B,QAAM,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AACjD;","names":["mkdirSync","renameSync","target","mkdirSync","quarantine","target","renameSync","inner","counts","defined","line","range","byUrn","typeOf","nodes","count","contract","postUrn","text","entry","str","resolve","part","named","text","text","defined","line","card","insight","drift","byUrn","role","text","defined","drift","classify","byUrn","Refused","selection","texts","fetch","named","selection","liveFetch","PAGING","counts","text","fetch","fail","liveFetch","fetch","companies","texts","count","byUrn","range","address","liveFetch","fetch","count","drift","text","defined","collection","urns","str","card","part","liveFetch","PAGING","shape","line","fetch","selection","collection","count","COUNT","drift","texts","PAGE_SIZE","postUrn","existsSync","existsSync","readFileSync","contract","mailbox","DEGREE","txt","defined","byUrn","render","drift","fetch","text","text","defined","liveFetch","collect","fetch","text","idOf","inner","cleanUrl","drift","r","count","byUrn","invitations","liveFetch","PAGING","compactRow","res","fetch","count","drift","text","byUrn","liveFetch","fetch","SCREEN","drift","unquote","TEXT","text","contract","drift","str","idOf","defined","nodes","SECTIONS","counts","count","bool","SCREEN","profileId","drift","unquote","TEXT","texts","text","drift","TEXT","drift","text","PAGER_URL","MAX_PAGES","drift","count","liveFetch","counts","fail","count","PAGER_URL","compact","LISTS","fetch","EDIT_NAV","drift","text","count","reply","drift","mkdirSync","dirname","readFileSync","statSync","basename","createHash","VOYAGER","readFileSync","randomUUID","existsSync","PAGING","NETWORK","fetch","drift","unquote","STR","LINK","PROFILE_ID","text","texts","REF","share","companies","liveFetch","fetch","basename","compact","text","entry"]}
1
+ {"version":3,"sources":["../src/mcp-shim.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/contracts.ts","../src/engine/company.ts","../src/progress.ts","../src/engine/budget.ts","../src/engine/auth.ts","../src/engine/classify.ts","../src/engine/client.ts","../src/engine/parse.ts","../src/engine/index.ts","../src/engine/session.ts","../src/commands/paged.ts","../src/engine/sdui-form.ts","../src/engine/posts.ts","../src/engine/jobs.ts","../src/engine/people.ts","../src/commands/people.ts","../src/commands/posts-search.ts","../src/commands/company.ts","../src/engine/events.ts","../src/commands/events.ts","../src/engine/job-premium.ts","../src/commands/jobs.ts","../src/engine/sdui-scheduled.ts","../src/commands/live.ts","../src/commands/local.ts","../src/commands/messaging.ts","../src/engine/messaging.ts","../src/engine/my-items.ts","../src/commands/my-items.ts","../src/engine/search.ts","../src/engine/network.ts","../src/commands/network.ts","../src/engine/notifications.ts","../src/commands/notifications.ts","../src/engine/contact-info.ts","../src/engine/full-profile.ts","../src/engine/recommendations.ts","../src/engine/sdui-profile.ts","../src/engine/sdui-skill.ts","../src/commands/profile.ts","../src/commands/registry.ts","../src/engine/sdui-position.ts","../src/commands/gate.ts","../src/commands/approval.ts","../src/commands/confirm.ts","../src/commands/write.ts","../src/engine/sdui-comment.ts","../src/engine/voyager-reply.ts","../src/engine/voyager-write.ts","../src/commands/profile-image.ts","../src/engine/sdui-profile-image.ts","../src/commands/token.ts","../src/engine/oauth.ts","../src/commands/transport.ts","../src/commands/role.ts","../src/commands/search-kinds.ts","../src/commands/skill.ts","../src/engine/profile-views.ts","../src/commands/viewers.ts","../src/entry.ts"],"sourcesContent":["#!/usr/bin/env bun\n// ─── MCP surface ──────────────────────────────────────────────────────────────\n//\n// Thin by contract: this file validates arguments, calls the same runners the\n// CLI calls, and returns the same envelope. No parsing, no transport, no\n// pacing, no cache logic lives here.\n//\n// Writes are not registered. Not disabled, not permission-gated — absent. The\n// registry marks each command's audience and risk, `mcpCommands()` filters on\n// both, and a test asserts no write survives that filter. An agent talking to\n// this server cannot post, comment, react, connect or message, whatever\n// arguments it composes.\n//\n// Tool descriptions do real work here. The agent reads them BEFORE it ever sees\n// a response, so each one states the specific misreading that would cause harm\n// — chiefly that an empty result and a failed fetch look identical unless you\n// check the counts.\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { z } from 'zod';\nimport { runCacheStatus, runLocal, runSourceRead } from './commands/cache.ts';\nimport { runCompany } from './commands/company.ts';\nimport { runEvent, runEvents } from './commands/events.ts';\nimport { type JobsRequest, runJob, runJobFilters, runJobs } from './commands/jobs.ts';\nimport { runFeed, runPost, runReactions, runScheduled, runWhoami } from './commands/live.ts';\nimport { runBudget, runDoctor, runRisk } from './commands/local.ts';\nimport {\n runDraft,\n runDraftRemove,\n runDrafts,\n runInbox,\n runMessages,\n} from './commands/messaging.ts';\nimport { runMyItems } from './commands/my-items.ts';\nimport { runNetwork } from './commands/network.ts';\nimport { runNotifications } from './commands/notifications.ts';\nimport { type PeopleRequest, runPeople, runPeopleFilters } from './commands/people.ts';\nimport { runPostsSearch } from './commands/posts-search.ts';\nimport { runProfile } from './commands/profile.ts';\nimport { mcpCommands } from './commands/registry.ts';\nimport { runExperience } from './commands/role.ts';\nimport { runFind, runFindFilters } from './commands/search-kinds.ts';\nimport { runSkills } from './commands/skill.ts';\nimport { runViewers } from './commands/viewers.ts';\nimport { shouldRunAsEntry } from './entry.ts';\nimport type { Envelope } from './types.ts';\n\nconst READING_CONTRACT =\n 'ALWAYS read `meta` before reporting. `state:\"complete\"` with an empty `items` genuinely means ' +\n 'none. `state:\"partial\"` means references failed to resolve — the record is INCOMPLETE, not ' +\n 'small. `claimedCount > 0` with `returnedCount === 0` is a FAILED FETCH, never \"no results\". ' +\n 'A non-empty `unknownTypes` means LinkedIn changed shape and the parser is behind — say so. ' +\n 'If `meta.budget.remaining` is low, tell the user and stop.';\n\nconst NO_RETRY =\n 'Never retry on failure. RATE_LIMITED, REQUEST_DENIED, CHALLENGE_DETECTED and COOLDOWN_ACTIVE ' +\n 'all mean a cross-process cooldown has opened; every further call will refuse until it lifts. ' +\n 'Report it and stop.';\n\n/** Render an envelope as MCP content. Errors stay envelopes, not exceptions. */\nfunction reply(envelope: Envelope) {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(envelope) }],\n isError: !envelope.ok,\n };\n}\n\nexport function buildServer(): McpServer {\n const server = new McpServer({ name: 'linkedin-relay', version: '0.1.0' });\n\n // Guard rather than trust: if a write ever reached this list, fail loudly at\n // startup instead of quietly exposing it.\n const exposed = mcpCommands();\n const write = exposed.find((c) => c.risk === 'write');\n if (write !== undefined) {\n throw new Error(`refusing to start: write command '${write.name}' reached the MCP surface`);\n }\n\n server.tool(\n 'risk',\n 'Circuit-breaker state and the ToS notice. Free, no network. CALL THIS FIRST in a research ' +\n 'session — it reports whether LinkedIn has thrown a throttle, block or challenge, so you ' +\n 'find out before spending calls rather than one wasted call at a time.',\n {},\n async () => reply(runRisk(Date.now())),\n );\n\n server.tool(\n 'budget',\n \"Remaining request budget per class, with each cap's provenance. Free, no network. The caps \" +\n 'are deliberately low because LinkedIn restricts accounts for READ velocity alone — they are ' +\n \"guesses, not measured safe limits, and they cannot see the user's own browser activity.\",\n {},\n async () => reply(runBudget(Date.now(), false, false)),\n );\n\n server.tool(\n 'doctor',\n 'Diagnose setup end to end: session, cooldown, budget, engine readiness. Free with offline. ' +\n 'Run this first when anything behaves oddly. Never reveals credential values.',\n { offline: z.boolean().optional().describe('skip live checks (default true)') },\n async ({ offline }) => reply(runDoctor(Date.now(), offline ?? true)),\n );\n\n server.tool(\n 'whoami',\n 'The authenticated LinkedIn member: name, headline, public id, urn. Cheap (1 call). Good ' +\n `first call to confirm the session works and which account it is. ${NO_RETRY}`,\n {},\n async () => reply(await runWhoami()),\n );\n\n server.tool(\n 'search',\n 'Search LinkedIn posts, companies, groups, events, courses, products, services or schools ' +\n '(people and jobs have their own tools, `people` and `jobs`). 1 search call per 50 results ' +\n '(posts: per 20; a posts call is heavy, ask for the depth you need). Rows: id, name, ' +\n 'subtitle, detail, summary, url — what subtitle and detail hold depends on the kind ' +\n '(companies: industry • HQ, followers; groups: members; events: when, where • organiser; ' +\n 'courses: length, instructor • released; schools: place, alumni; services: the provider). ' +\n 'Posts rows: id (the post urn, which `post` takes), url, author, authorHeadline, authorUrl, ' +\n \"posted (as LinkedIn shows it, in the user's language), text, reactions, comments, reposts. \" +\n 'Several keyword sets as a list are searched and merged by id, with `matched`. Filter ' +\n 'options and their ids for each kind come from `search_filters`. LinkedIn pages at most ' +\n `1000 results per query; \\`meta.servedLimit\\` means it claimed more. ${READING_CONTRACT} ${NO_RETRY}`,\n {\n kind: z.enum([\n 'posts',\n 'companies',\n 'groups',\n 'events',\n 'courses',\n 'products',\n 'services',\n 'schools',\n ]),\n keywords: z.union([z.string(), z.array(z.string()).min(1)]).optional(),\n location: z.string().optional().describe('companies (HQ) and services: a place by name'),\n industry: z.array(z.string()).optional().describe('companies: industry ids'),\n network: z\n .array(z.enum(['1st', '2nd', '3rd+']))\n .optional()\n .describe('companies, services'),\n filter: z\n .array(z.string())\n .optional()\n .describe('raw key=v1,v2 by the names search_filters lists'),\n sort: z.enum(['recent', 'relevant']).optional().describe('posts'),\n posted: z.enum(['24h', 'week', 'month']).optional().describe('posts'),\n type: z\n .array(z.enum(['videos', 'images', 'jobs', 'live', 'articles', 'documents']))\n .optional()\n .describe('posts'),\n postedBy: z\n .array(z.enum(['1st', 'me']))\n .optional()\n .describe('posts'),\n from: z.array(z.string()).optional().describe('posts by these people (profile ids)'),\n mentions: z\n .array(z.string())\n .optional()\n .describe('posts mentioning these people (profile ids)'),\n fromCompany: z\n .array(z.string())\n .optional()\n .describe('posts by these companies (names or ids)'),\n mentionsCompany: z.array(z.string()).optional().describe('posts mentioning these companies'),\n authorCompany: z.array(z.string()).optional().describe('posts by people at these companies'),\n authorIndustry: z\n .array(z.string())\n .optional()\n .describe('posts by people in these industries'),\n authorTitle: z.string().optional().describe('posts by people with this job title'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .optional()\n .describe('per keyword set; default 25 (posts 20)'),\n start: z.number().int().min(0).optional(),\n compact: z.boolean().optional().describe('one line per result'),\n },\n async ({\n kind,\n keywords,\n location,\n industry,\n network,\n filter,\n limit,\n start,\n compact,\n ...posts\n }) => {\n const opts = compact === true ? { compact: true } : {};\n const common = {\n ...(keywords !== undefined ? { keywords } : {}),\n ...(start !== undefined ? { start } : {}),\n ...(filter !== undefined ? { raw: filter } : {}),\n };\n if (kind === 'posts')\n return reply(await runPostsSearch({ ...common, ...posts, limit: limit ?? 20 }, opts));\n return reply(\n await runFind(\n kind,\n {\n ...common,\n limit: limit ?? 25,\n ...(location !== undefined ? { location } : {}),\n ...(industry !== undefined ? { industry } : {}),\n ...(network !== undefined ? { network } : {}),\n },\n opts,\n ),\n );\n },\n );\n\n server.tool(\n 'search_filters',\n \"Every filter a search kind has for a query, with each option's id and live count: the \" +\n 'values `search` takes as raw `filter` (key=value by the listed key), or `industry`, … ' +\n `1 search call. ${NO_RETRY}`,\n {\n kind: z.enum(['companies', 'groups', 'events', 'courses', 'products', 'services', 'schools']),\n keywords: z.string().optional(),\n location: z.string().optional(),\n },\n async ({ kind, keywords, location }) =>\n reply(\n await runFindFilters(kind, {\n ...(keywords !== undefined ? { keywords } : {}),\n ...(location !== undefined ? { location } : {}),\n }),\n ),\n );\n\n const peopleQuery = {\n keywords: z\n .union([z.string(), z.array(z.string()).min(1)])\n .optional()\n .describe('search terms; a list runs one search per entry and merges them by person'),\n company: z.array(z.string()).optional().describe('current company: names or ids'),\n pastCompany: z.array(z.string()).optional().describe('past company: names or ids'),\n school: z.array(z.string()).optional().describe('school: names or ids'),\n location: z.string().optional().describe('a place by name, looked up to its geo id'),\n geo: z.array(z.string()).optional().describe('geo ids, from people_filters'),\n network: z.array(z.enum(['1st', '2nd', '3rd+'])).optional(),\n industry: z.array(z.string()).optional().describe('industry ids, from people_filters'),\n language: z.array(z.string()).optional().describe('profile language codes: en, de, …'),\n service: z.array(z.string()).optional().describe('service category ids'),\n connectionOf: z.string().optional().describe(\"a profile id: that person's connections\"),\n followerOf: z.string().optional().describe(\"a profile id: that person's followers\"),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n title: z.string().optional().describe('free text matched against current title'),\n companyText: z.string().optional().describe('free text matched against company names'),\n schoolText: z.string().optional().describe('free text matched against school names'),\n openToVolunteer: z.boolean().optional(),\n filter: z\n .array(z.string())\n .optional()\n .describe('raw key=v1,v2 by the parameter names people_filters lists'),\n };\n type PeopleArgs = { [K in keyof typeof peopleQuery]?: z.infer<(typeof peopleQuery)[K]> };\n const peopleRequest = (a: PeopleArgs, limit: number): PeopleRequest => {\n const { keywords, location, filter, ...rest } = a;\n return {\n limit,\n ...(keywords !== undefined ? { keywords } : {}),\n ...(location !== undefined ? { location } : {}),\n filter: { ...rest, ...(filter !== undefined ? { raw: filter } : {}) },\n };\n };\n\n server.tool(\n 'people',\n 'Search LinkedIn people with every filter the people search has. 1 search call per 50 ' +\n 'people, plus 1 per company, school or place given by name. Filter by current or past ' +\n 'company, school, place, connection degree, industry, title, profile language, or the ' +\n \"connections / followers of a person (their profile id, a row's `id`). Names are looked \" +\n 'up to ids and `data.resolved` says what each became: CHECK IT, a name can match a ' +\n 'different organisation. Rows: id, name, headline, location, degree, verified, insight ' +\n '(mutual connections, services), url. Several keyword sets as a list are searched and ' +\n 'merged by person, with `matched`. Out-of-network people come back as \"LinkedIn Member\" ' +\n 'with no url: LinkedIn will not name them to this account. LinkedIn pages at most 1000 ' +\n 'people per query; `meta.servedLimit` means it claimed more, so narrow with filters. ' +\n `\\`meta.next\\` is the start for the next page. ${READING_CONTRACT} ${NO_RETRY}`,\n {\n ...peopleQuery,\n limit: z.number().int().min(1).max(1000).optional().describe('per keyword set; default 25'),\n start: z.number().int().min(0).optional(),\n compact: z.boolean().optional().describe('one line per person'),\n },\n async ({ limit, start, compact, ...q }) =>\n reply(\n await runPeople(\n { ...peopleRequest(q, limit ?? 25), ...(start !== undefined ? { start } : {}) },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'people_filters',\n \"Every people-search filter for a query, with each option's id and live count, and which \" +\n 'filters take free text. The ids go into `people` (geo, industry, service, company, …) ' +\n `or raw \\`filter\\` (key=value by the listed key). 1 search call. ${NO_RETRY}`,\n peopleQuery,\n async (q) => reply(await runPeopleFilters(peopleRequest(q, 25))),\n );\n\n const jobQuery = {\n keywords: z\n .union([z.string(), z.array(z.string()).min(1)])\n .optional()\n .describe('search terms; a list runs one search per entry and merges them by job id'),\n location: z\n .string()\n .optional()\n .describe('a place, resolved by LinkedIn; check data.location for what it chose'),\n geoId: z.string().optional().describe('an exact geo id, in place of location'),\n distance: z.number().int().optional().describe('miles around the location'),\n posted: z.string().optional().describe('24h | week | month | <N>h | <N>d'),\n experience: z\n .array(z.enum(['internship', 'entry', 'associate', 'mid-senior', 'director', 'executive']))\n .optional(),\n type: z\n .array(\n z.enum([\n 'full-time',\n 'part-time',\n 'contract',\n 'temporary',\n 'volunteer',\n 'internship',\n 'other',\n ]),\n )\n .optional(),\n workplace: z.array(z.enum(['on-site', 'remote', 'hybrid'])).optional(),\n easyApply: z.boolean().optional(),\n under10: z.boolean().optional().describe('fewer than 10 applicants'),\n verified: z.boolean().optional(),\n inNetwork: z.boolean().optional(),\n fairChance: z.boolean().optional(),\n company: z.array(z.string()).optional().describe('company ids, from job_filters'),\n industry: z.array(z.string()).optional().describe('industry ids, from job_filters'),\n function: z.array(z.string()).optional().describe('function codes, from job_filters'),\n title: z.array(z.string()).optional().describe('title ids, from job_filters'),\n place: z.array(z.string()).optional().describe('city geo ids, from job_filters'),\n filter: z\n .array(z.string())\n .optional()\n .describe('raw key=v1,v2 by the parameter names job_filters lists'),\n sort: z.enum(['recent', 'relevant']).optional(),\n };\n type JobArgs = { [K in keyof typeof jobQuery]?: z.infer<(typeof jobQuery)[K]> };\n const jobRequest = (a: JobArgs, limit: number): JobsRequest => {\n const { keywords, location, geoId, filter, ...rest } = a;\n return {\n limit,\n ...(keywords !== undefined ? { keywords } : {}),\n ...(location !== undefined ? { location } : {}),\n ...(geoId !== undefined ? { geoId } : {}),\n filter: { ...rest, ...(filter !== undefined ? { raw: filter } : {}) },\n };\n };\n\n server.tool(\n 'jobs',\n 'Search LinkedIn jobs with every filter the jobs page has. 1 job-search call per 100 results (150 a day). ' +\n 'Rows carry id, title, company, location, workplace, listed (date), easyApply, promoted, ' +\n 'salary when shown, url. RANK ON THOSE, then call `job` on finalists for the description ' +\n 'and apply link; `details:true` reads every row in full, 100 per job read (60 a day). ' +\n 'Pass several keyword sets as a list to search them all with the same filters in one ' +\n 'call: jobs found by several come back once, with `matched` naming the sets that found ' +\n 'them, most-matched first; `meta.searches` reports each set and `meta.duplicates` how ' +\n 'many repeats were merged. ' +\n 'Ids for company/industry/title/place/filter come from `job_filters`. `data.location` is ' +\n \"the place a typed location resolved to: check it. `meta.claimedCount` is LinkedIn's total; \" +\n '`meta.next` is the start for the next page; LinkedIn serves at most 1000 per search. ' +\n 'topApplicant: true (Premium) lists instead the jobs where LinkedIn says the user would be ' +\n 'a top applicant, 100 per call; hearBack: true (Premium) lists the jobs where the user ' +\n 'is more likely to hear back, 25 per job-search call plus a job read per 100 (rows are ' +\n 'full jobs, as `job` returns them). Neither takes keywords, location or filters. ' +\n `${READING_CONTRACT} ${NO_RETRY}`,\n {\n ...jobQuery,\n topApplicant: z\n .boolean()\n .optional()\n .describe(\"Premium: LinkedIn's list of jobs where the user would be a top applicant\"),\n hearBack: z\n .boolean()\n .optional()\n .describe(\"Premium: LinkedIn's list of jobs where the user is more likely to hear back\"),\n limit: z.number().int().min(1).max(1000).optional().describe('per keyword set; default 25'),\n start: z.number().int().min(0).optional(),\n details: z.boolean().optional().describe('read each job: apply link, applicants'),\n description: z.boolean().optional().describe('with details, keep full descriptions'),\n compact: z.boolean().optional().describe('one line per job'),\n },\n async ({ limit, start, details, description, compact, topApplicant, hearBack, ...q }) =>\n reply(\n await runJobs(\n {\n ...jobRequest(q, limit ?? 25),\n ...(topApplicant === true ? { collection: 'top-applicant' as const } : {}),\n ...(hearBack === true ? { collection: 'hear-back' as const } : {}),\n ...(start !== undefined ? { start } : {}),\n ...(details !== undefined ? { details } : {}),\n ...(description !== undefined ? { description } : {}),\n },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'job',\n 'LinkedIn jobs by id or URL, in full: description, apply {type: external | easy-apply, url}, ' +\n 'company, location, workplace, employmentType, applicants, listed/expires, state (LISTED or ' +\n 'CLOSED), and whether the user already applied or saved it. One id returns the job; ' +\n 'several return {items, meta}, read 100 per job read (60 a day), so pass all finalists in ' +\n `one call. meta.unread lists ids LinkedIn did not return. team: true adds hiringTeam ` +\n '[{name, id, url, headline, degree, role (\"Job poster\"), verified}] per job — who posted ' +\n 'it and who is hiring — one page call (60 a day) per job; [] means LinkedIn shows no one, ' +\n 'and hiringTeamError says why one could not be read. insights: true (Premium) adds ' +\n 'premium {applicants {total, lastDay, seniority [{level, share, count}], education ' +\n '[{degree, share}]}, company {name, headcount {asOf, now, sixMonthsAgo, yearAgo, ' +\n \"twoYearsAgo, growth1y (%)}, function {name, now, …} (the job's function), medianTenure, \" +\n \"competitors [{name, industry, url}], hiring, priorities, landscape (LinkedIn's generated \" +\n 'text)}}, one more job read per job; premiumError says why they could not be read. ' +\n \"match: true (Premium) asks LinkedIn's AI assistant how well the user fits each job, as \" +\n '\"Show match details\" does: match {summary (the verdict), met and missing (required ' +\n \"qualifications), text}, in the user's language; about 3 page calls and a few seconds per \" +\n \"job, and the exchange is added to the user's assistant history. matchError says why not. \" +\n NO_RETRY,\n {\n job: z\n .union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .describe('job id, /jobs/view/ URL or ?currentJobId= URL, or a list of them'),\n team: z.boolean().optional().describe(\"also read each job's hiring team\"),\n insights: z\n .boolean()\n .optional()\n .describe(\"Premium: who applied, and the company's headcount and insights\"),\n match: z\n .boolean()\n .optional()\n .describe(\"Premium: LinkedIn's AI assessment of how well the user fits each job\"),\n },\n async ({ job, team, insights, match }) =>\n reply(\n await runJob(job, {}, undefined, {\n team: team === true,\n insights: insights === true,\n match: match === true,\n }),\n ),\n );\n\n server.tool(\n 'job_filters',\n \"Every job-search filter for a query, with each option's id and live result count: the \" +\n 'values `jobs` takes for company, industry, function, title, place, and raw `filter` ' +\n `(key=value by the listed key). 1 job-search call. ${NO_RETRY}`,\n jobQuery,\n async (q) => reply(await runJobFilters(jobRequest(q, 25))),\n );\n\n server.tool(\n 'profile',\n 'Read one LinkedIn profile in full: name, headline, about, location, industry, the top card ' +\n '(title, company, school), and every section — experience [{title, company, companyId, ' +\n 'employmentType, location, start, end | current, description}] whole (read on past the ' +\n 'first 10 companies), education, skills (top 20; counts.skills has the total; skills: ' +\n 'true reads them all), ' +\n 'certifications, languages, honors, publications, projects, volunteering, courses, ' +\n 'organizations, patents, testScores. Empty sections are left out. 1 profile read (30 a day), ' +\n '+1 per 50 more companies. contact: true adds contact {email, websites [{url, type}], ' +\n 'phones, birthday, connectedSince, …} as the profile shows it to you, for 1 more profile ' +\n 'read; it failing leaves contactError. posts: N adds posts, their N newest (the posts search, ' +\n 'from them; postsError if it fails). recommendations: true adds recommendations {received, ' +\n 'given}: [{name, url, headline, degree, context (when and how they worked together, in the ' +\n \"user's language), text}]. MEDIUM cost — use only on finalists surfaced by `people` or \" +\n '`search`. compact: true makes each role, school and entry one line and drops ' +\n `descriptions; fields keeps only those named. ${NO_RETRY}`,\n {\n id: z.string().min(1).describe('public id, urn, or profile URL'),\n compact: z.boolean().optional().describe('one line per role, school and entry'),\n fields: z.string().optional().describe('comma-separated top-level fields to keep'),\n contact: z.boolean().optional().describe('also read the contact info (1 more profile read)'),\n posts: z\n .number()\n .int()\n .min(1)\n .max(50)\n .optional()\n .describe('also read their N newest posts (1 search call per 20)'),\n skills: z\n .boolean()\n .optional()\n .describe('read every skill, not just the top 20 (1 page call per 10)'),\n recommendations: z\n .boolean()\n .optional()\n .describe('also read the recommendations they received and gave (2+ page calls)'),\n },\n async ({ id, compact, fields, contact, posts, skills, recommendations }) =>\n reply(\n await runProfile(\n id,\n {\n ...(compact === true ? { compact: true } : {}),\n ...(fields !== undefined ? { fields } : {}),\n },\n undefined,\n {\n contact: contact === true,\n skills: skills === true,\n recommendations: recommendations === true,\n ...(posts !== undefined ? { posts } : {}),\n },\n ),\n ),\n );\n\n server.tool(\n 'feed',\n \"The user's own chronological LinkedIn feed: author, when, text, url. MEDIUM cost. Promoted \" +\n 'posts are dropped and counted in `meta.excludedCount`, so fewer items than `limit` usually ' +\n `means ads were filtered, not that the fetch failed. ${READING_CONTRACT} ${NO_RETRY}`,\n { limit: z.number().int().min(1).max(20).optional().describe('default 10') },\n async ({ limit }) => reply(await runFeed(limit ?? 10)),\n );\n\n server.tool(\n 'post',\n \"A LinkedIn post's comment thread. EXPENSIVE — read only finalists. Accepts a bare \" +\n 'urn:li:activity:…, a urn:li:ugcPost:…, or a linkedin.com/feed/update/… URL; no prior lookup ' +\n 'is needed. Feed and search rows already report how many comments a post has, so use that to ' +\n 'decide whether the thread is worth a call. `meta.state` is always \"unknown\" — this is the ' +\n 'first page and pagination is not followed, so NEVER report a comment count as complete. ' +\n `Nested replies are not supported and a comment with replies does not carry them. ${READING_CONTRACT} ${NO_RETRY}`,\n {\n urn: z.string().min(1).describe('activity/ugcPost urn, or a feed-update URL'),\n limit: z.number().int().min(1).max(100).optional().describe('default 20'),\n },\n async ({ urn, limit }) => reply(await runPost(urn, limit ?? 20)),\n );\n\n server.tool(\n 'reactions',\n 'Who reacted to a LinkedIn post, and with which reaction. MEDIUM cost. Often more informative ' +\n 'than the comments for mapping who is paying attention to a topic. Same input forms as ' +\n '`post`. `meta.state` is always \"unknown\" — first page only, so do not report a total. ' +\n `${READING_CONTRACT} ${NO_RETRY}`,\n {\n urn: z.string().min(1).describe('activity/ugcPost urn, or a feed-update URL'),\n limit: z.number().int().min(1).max(100).optional().describe('default 20'),\n },\n async ({ urn, limit }) => reply(await runReactions(urn, limit ?? 20)),\n );\n\n server.tool(\n 'local',\n 'Search the LOCAL cache. Free — no network call, no budget spent. PREFER THIS before any live ' +\n 'command: if the answer is already cached, there is no reason to spend a request on it. The ' +\n 'cache only fills when the user runs a live read with --retain, so an empty result here means ' +\n 'nothing has been retained yet — NOT that LinkedIn has nothing. Check `meta.cachedTotal`.',\n {\n query: z.string().optional().describe('substring match; omit to list everything'),\n source: z.string().optional().describe('comma-separated: connections,my-posts,third-party'),\n since: z.string().optional().describe('YYYY-MM-DD'),\n limit: z.number().int().min(1).max(1000).optional().describe('per keyword set; default 25'),\n },\n async ({ query, source, since, limit }) => reply(runLocal(query, source, since, limit ?? 25)),\n );\n\n server.tool(\n 'experience',\n \"The roles on the user's own LinkedIn profile: positionId and title. LIVE — 2 calls. The \" +\n 'positionId is what `lnrelay role edit|remove` takes (CLI-only; changing a role is a write ' +\n `the user approves). ${NO_RETRY}`,\n {},\n async () => reply(await runExperience()),\n );\n\n server.tool(\n 'skills',\n \"The skills on the user's own LinkedIn profile: skillId and name. LIVE — about 3 calls. \" +\n '`name` is null when it could not be matched to its row for certain. Adding or removing a ' +\n `skill is the CLI-only \\`lnrelay skill\\`, a write the user approves. ${NO_RETRY}`,\n {},\n async () => reply(await runSkills()),\n );\n\n server.tool(\n 'my_items',\n \"The user's My items. posts: posts they saved — id (the post urn, which `post` takes), url, \" +\n 'author, authorHeadline, posted, text. learning: their LinkedIn Learning courses — name, ' +\n 'length, detail (instructor, released), progress, url. jobs: the job tracker — id (which ' +\n '`job` takes), title, company, location, workplace, stage, note (\"No longer accepting ' +\n 'applications\"), url; with no stage, all five stages (5 page calls) and `meta.byStage`. ' +\n `1 page call per 10 items. ${NO_RETRY}`,\n {\n list: z.enum(['posts', 'learning', 'jobs']),\n stage: z.enum(['saved', 'in-progress', 'applied', 'interview', 'archived']).optional(),\n limit: z.number().int().min(1).max(500).optional().describe('default 50'),\n compact: z.boolean().optional(),\n },\n async ({ list, stage, limit, compact }) =>\n reply(\n await runMyItems(\n list,\n { limit: limit ?? 50, ...(stage !== undefined ? { stage } : {}) },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'notifications',\n \"The user's LinkedIn notifications, newest first: unseen (the bell's count), and items \" +\n \"{kind (LinkedIn's name, e.g. FOLLOW_PAGE_HERO), text, detail, at (ISO), read, url, from \" +\n '(who or what it is about)}. Reading here does not mark them seen. 1 page call per 25. ' +\n NO_RETRY,\n {\n unread: z.boolean().optional().describe('only the unread ones'),\n limit: z.number().int().min(1).max(200).optional().describe('default 25'),\n compact: z.boolean().optional().describe('one line each'),\n },\n async ({ unread, limit, compact }) =>\n reply(\n await runNotifications(\n { limit: limit ?? 25, ...(unread === true ? { unread: true } : {}) },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'viewers',\n \"Who viewed the user's profile, as their profile-views page shows it: total, \" +\n 'privateViewers (a count only), and items — named viewers {name, id, url, degree, ' +\n 'headline, viewed} and anonymous ones {anonymous, description, viewed, searchUrl}. ' +\n \"Premium names every viewer, takes days (7, 14, 28, 90 or 365; default the page's 90) \" +\n 'and adds highlights [{label, value}] (top location, industry, company) and companies ' +\n '[{name, share}]. A free account is shown up to 3. meta.state is complete only when the ' +\n \"named and private add up to total. Degree, labels and times are in the user's language. \" +\n `2 page calls. ${NO_RETRY}`,\n {\n days: z\n .union([z.literal(7), z.literal(14), z.literal(28), z.literal(90), z.literal(365)])\n .optional()\n .describe('the range in days (Premium)'),\n compact: z.boolean().optional().describe('one line a viewer'),\n },\n async ({ days, compact }) =>\n reply(\n await runViewers({\n ...(compact === true ? { compact: true } : {}),\n ...(days !== undefined ? { days } : {}),\n }),\n ),\n );\n\n server.tool(\n 'events',\n \"The events page's own lists: events LinkedIn recommends to the user, and its Premium \" +\n \"LinkedIn Live events. Rows: id, name, when (as shown, in the user's language), organizer, \" +\n 'attendees, premium, url. 1 page call. To find events by topic use `search` with kind ' +\n `events; to read one in full use \\`event\\`. ${NO_RETRY}`,\n {\n premium: z.boolean().optional().describe('only the Premium LinkedIn Live events'),\n limit: z.number().int().min(1).max(100).optional().describe('default 25'),\n compact: z.boolean().optional(),\n },\n async ({ premium, limit, compact }) =>\n reply(\n await runEvents(\n { limit: limit ?? 25, ...(premium === true ? { premium: true } : {}) },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'event',\n 'Events in full, by id or URL: name, when (as shown), start/end (ISO), timeZone, state ' +\n '(FUTURE, ONGOING, PAST), cancelled, online, place (city, region, country), site (its own ' +\n 'registration page), attendees, organizer {name, kind, url}, private, premium, you (the ' +\n \"user's own response, when they gave one), description. 1 page call per event. \" +\n NO_RETRY,\n {\n event: z\n .union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .describe('event id or URL, or a list'),\n },\n async ({ event }) => reply(await runEvent(Array.isArray(event) ? event : [event])),\n );\n\n server.tool(\n 'company',\n 'A LinkedIn company page in full, by universal name, /company/ or /showcase/ URL, or id: ' +\n 'id (what people/jobs company filters and search posts fromCompany take), name, about, ' +\n 'website, industry, type, size (the band it chose), employeesOnLinkedIn, followers, ' +\n 'headquarters, specialties, locations, affiliated and showcasePages [{id, name, url, ' +\n 'followers}], jobsUrl. 1 page call per company; several return {items, meta}, with ' +\n 'meta.unread for any not found. posts: N adds its N newest posts (a posts search, on the ' +\n `search budget); postsError says why they could not be read. ${NO_RETRY}`,\n {\n company: z\n .union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .describe('universal name (microsoft), company URL or id, or a list'),\n posts: z.number().int().min(1).max(50).optional().describe('also its newest N posts'),\n compact: z.boolean().optional().describe('one line per company (several) and per post'),\n },\n async ({ company, posts, compact }) =>\n reply(\n await runCompany(\n Array.isArray(company) ? company : [company],\n posts !== undefined ? { posts } : {},\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'network',\n \"The user's own My Network. With no `list`: the count of connections, people they follow, \" +\n 'followers, pages, events, groups and invitations they sent (7 page calls). With a `list`: ' +\n 'its rows — people as id, name, headline, location, degree, url; pages, events and groups ' +\n 'as id, name, subtitle, detail, url; invitations as to, id, headline, sent, note, url. ' +\n '1 page call per 50 rows. Read only: no badge is cleared and nothing is marked seen. ' +\n `Received invitations and \"people you may know\" are not available. ${NO_RETRY}`,\n {\n list: z\n .enum(['connections', 'following', 'followers', 'pages', 'events', 'groups', 'invitations'])\n .optional(),\n limit: z.number().int().min(1).max(1000).optional().describe('default 50'),\n start: z.number().int().min(0).optional(),\n compact: z.boolean().optional(),\n },\n async ({ list, limit, start, compact }) =>\n reply(\n await runNetwork(\n list,\n { limit: limit ?? 50, ...(start !== undefined ? { start } : {}) },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'inbox',\n \"The user's LinkedIn conversations in a folder, newest first: id, url, with (each person or \" +\n 'organisation: name, kind, headline, degree, url), unread, lastActivity, last message ' +\n '(from, fromMe, at, text, sponsored), folders, inmail. 1 page call per 20. READS ONLY: ' +\n 'nothing is marked read or seen, and nothing is stored. These are private messages: quote ' +\n 'them to the user, never elsewhere. `meta.unread` counts conversations with unread messages. ' +\n `Folders: inbox (default), primary, other, archive, requests, spam. ${NO_RETRY}`,\n {\n folder: z.enum(['inbox', 'primary', 'other', 'archive', 'requests', 'spam']).optional(),\n unread: z.boolean().optional().describe('only conversations with unread messages'),\n limit: z.number().int().min(1).max(500).optional().describe('default 20'),\n compact: z.boolean().optional(),\n },\n async ({ folder, unread, limit, compact }) =>\n reply(\n await runInbox(\n {\n folder: folder ?? 'inbox',\n limit: limit ?? 20,\n ...(unread === true ? { unread: true } : {}),\n },\n compact === true ? { compact: true } : {},\n ),\n ),\n );\n\n server.tool(\n 'messages',\n \"One conversation's latest messages, oldest first: from, fromMe, at, text, subject. 1 page \" +\n 'call. Reading does not mark it read. `meta.state` \"partial\" means a full page came back ' +\n `and older messages may exist; only the latest page is read. ${NO_RETRY}`,\n { conversation: z.string().min(1).describe('a conversation id from inbox, or its thread URL') },\n async ({ conversation }) => reply(await runMessages(conversation)),\n );\n\n server.tool(\n 'draft',\n 'Save a reply draft for a conversation ON THIS MACHINE, with its link, for the user to review ' +\n 'and send themselves. NOTHING IS SENT — this tool cannot send messages, on any surface. Show ' +\n 'the user the draft and the link. 1 page call, to check the conversation and who it is ' +\n 'with. Pass `remove` with a draft id to delete a draft instead.',\n {\n conversation: z.string().optional().describe('a conversation id or thread URL'),\n text: z.string().optional().describe('the reply'),\n remove: z.string().optional().describe('a draft id to delete'),\n },\n async ({ conversation, text, remove }) =>\n reply(remove !== undefined ? runDraftRemove(remove) : await runDraft(conversation, text)),\n );\n\n server.tool(\n 'drafts',\n 'The reply drafts saved on this machine: id, to, text, the conversation link. Free, local.',\n {},\n async () => reply(runDrafts()),\n );\n\n server.tool(\n 'scheduled',\n \"The user's own posts waiting to publish, soonest first: urn, scheduledAt (ISO), text. LIVE \" +\n '— about 1 call per 10 posts. These are NOT in `my_posts` until they go out. Links in `text` ' +\n 'show as lnkd.in short links, as LinkedIn lists them. `text` is null when it could not be ' +\n \"matched to its post for certain. `meta.claimedCount` is LinkedIn's own count; if \" +\n `\\`meta.state\\` is not \"complete\", say the list may be short. ${NO_RETRY}`,\n {},\n async () => reply(await runScheduled()),\n );\n\n for (const source of ['connections', 'my-posts'] as const) {\n server.tool(\n source.replace('-', '_'),\n `The user's own ${source === 'connections' ? 'connections' : 'authored posts'}, read from the ` +\n 'LOCAL cache. Free — no network call, no budget spent. An empty result means the cache has ' +\n `not been filled, NOT that the user has none: tell them to run \\`lnrelay sync ${source}\\` ` +\n 'themselves (it is CLI-only). Check `meta.cachedTotal` to tell the two apart.',\n {\n query: z.string().optional().describe('substring match; omit to list everything'),\n limit: z.number().int().min(1).max(1000).optional().describe('per keyword set; default 25'),\n },\n async ({ query, limit }) => reply(runSourceRead(source, query, limit ?? 25)),\n );\n }\n\n server.tool(\n 'cache_status',\n 'What is cached per source, with sync checkpoints and the retention policy. Free, no network. ' +\n 'Third-party records expire 30 days after capture — the body goes, an identity stub stays, so ' +\n 'a re-fetch is a visible choice rather than a silent budget charge.',\n {},\n async () => reply(runCacheStatus()),\n );\n\n return server;\n}\n\nconst entry = shouldRunAsEntry(process.argv[1], import.meta.url, import.meta.main, [\n 'linkedin-relay-mcp',\n 'lnrelay',\n]);\n\nif (entry.run) {\n const server = buildServer();\n await server.connect(new StdioServerTransport());\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 const meta = node.metadata as { shareUrn?: unknown } | undefined;\n\n return defined({\n type: typeOf(node),\n urn,\n // The urn the post was CREATED as (share or ugcPost) — what `share` prints,\n // and a different number from the activity urn above.\n shareUrn: typeof meta?.shareUrn === 'string' ? meta.shareUrn : undefined,\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\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","// ─── 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. Since 2026-10-16\n // `lnrelay profile` reads `fullProfile` below instead, which has the name\n // and every section; this one stays recorded for the projection trap.\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 // A WRITE contract: creates a poll object that a post then references. The\n // queryId is from mguttmann/linkedin-internal-api (docs/24) and returned a\n // pollSummary urn on this machine on the date below.\n createPoll: {\n name: 'createPoll',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerFeedDashPollsPollSummary.f8ad99cf791d833d37dddb373d06fb3a',\n provenance: 'verified',\n capturedAt: '2026-10-13',\n },\n\n // The composer's link lookup: a URL in, the article LinkedIn made of it out\n // (`urn:li:article:<id>`), which a post then carries as ARTICLE media. queryId\n // from mguttmann/linkedin-internal-api; same article urn the web composer\n // attached when captured on the date below.\n urlPreview: {\n name: 'urlPreview',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerContentcreationDashUpdateUrlPreview.b092c1aea4b6c087ec0d09614b3b3320',\n provenance: 'verified',\n capturedAt: '2026-10-13',\n },\n\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 // A profile in full, probed 2026-10-16: name, About and every section, each\n // a collection in `included`. It holds the first 10 position groups and 20\n // skills; the rest of the experience pages through `profilePositions`\n // (32 of 32 in two calls). Skills did not page (profileSkills answered 400).\n // See engine/full-profile.ts.\n fullProfile: {\n name: 'fullProfile',\n transport: 'voyager-restli',\n path: `${VOYAGER}/identity/dash/profiles`,\n decorationId: 'com.linkedin.voyager.dash.deco.identity.profile.FullProfileWithEntities-93',\n provenance: 'verified',\n capturedAt: '2026-10-16',\n },\n profilePositions: {\n name: 'profilePositions',\n transport: 'voyager-restli',\n path: `${VOYAGER}/identity/dash/profilePositionGroups`,\n decorationId: 'com.linkedin.voyager.dash.deco.identity.profile.FullProfilePositionGroup-50',\n provenance: 'verified',\n capturedAt: '2026-10-16',\n },\n\n // The owner's notifications, probed 2026-10-29: the cards the bell opens,\n // newest first. The page itself also marks them seen; reading them here\n // does not. See engine/notifications.ts.\n notifications: {\n name: 'notifications',\n transport: 'voyager-restli',\n path: `${VOYAGER}/voyagerIdentityDashNotificationCards`,\n decorationId:\n 'com.linkedin.voyager.dash.deco.identity.notifications.CardsCollectionWithInjectionsNoPills-25',\n provenance: 'verified',\n capturedAt: '2026-10-29',\n },\n\n // A company page, captured 2026-10-14. The GraphQL company query by\n // universalName answers only the company's urn, so this is the REST\n // resource: by id (`/<id>`) or by name (`q=universalName`). It carries the\n // About tab's fields, the affiliated and showcase pages, and followers. See\n // engine/company.ts.\n company: {\n name: 'company',\n transport: 'voyager-restli',\n path: `${VOYAGER}/organization/companies`,\n decorationId: 'com.linkedin.voyager.deco.organization.web.WebFullCompanyMain-12',\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n\n // Job search, captured 2026-10-14. The jobs page itself now opens an SDUI\n // \"AI job search\" that drops filters it does not support; these are the\n // classic Voyager resources still behind /jobs/search/, which take them all.\n // See engine/jobs.ts.\n // The owner's messages, captured 2026-10-14; see engine/messaging.ts. Reads\n // only: the page's own \"seen\", read and delivery calls are not made.\n messengerConversations: {\n name: 'messengerConversations',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/voyagerMessagingGraphQL/graphql`,\n queryId: 'messengerConversations.9501074288a12f3ae9e3c7ea243bccbf',\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n messengerMessages: {\n name: 'messengerMessages',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/voyagerMessagingGraphQL/graphql`,\n queryId: 'messengerMessages.5846eeb71c981f11e0134cb6626cc314',\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n\n // Connection invitations the owner has sent, captured 2026-10-14; see\n // engine/network.ts.\n sentInvitations: {\n name: 'sentInvitations',\n transport: 'voyager-restli',\n path: `${VOYAGER}/relationships/sentInvitationViewsV2`,\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n\n // One event in full, captured 2026-10-14; see engine/events.ts.\n professionalEvent: {\n name: 'professionalEvent',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerEventsDashProfessionalEvents.210672c5faddd345ead9663d93cd2241',\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n\n jobCards: {\n name: 'jobCards',\n transport: 'voyager-restli',\n path: `${VOYAGER}/voyagerJobsDashJobCards`,\n decorationId: 'com.linkedin.voyager.dash.deco.jobs.search.JobSearchCardsCollection-220',\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n jobFilters: {\n name: 'jobFilters',\n transport: 'voyager-restli',\n path: `${VOYAGER}/voyagerJobsDashSearchFilterClustersResource`,\n decorationId: 'com.linkedin.voyager.dash.deco.search.SearchFilterCluster-44',\n provenance: 'verified',\n capturedAt: '2026-10-14',\n },\n // Premium job reads, captured 2026-11-22 from /jobs/collections/top-applicant/\n // and a job's detail pane. See engine/job-premium.ts.\n jobCollection: {\n name: 'jobCollection',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerJobsDashJobCards.fc1f897bcf2dc9afd5184ef3e9ed589b',\n provenance: 'verified',\n capturedAt: '2026-11-22',\n },\n jobDetailSections: {\n name: 'jobDetailSections',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerJobsDashJobPostingDetailSections.bc2eee77d01abc6616b8c8855344dfd5',\n provenance: 'verified',\n capturedAt: '2026-11-22',\n },\n // LinkedIn's AI assistant, as a job's \"Show match details\" asks it\n // (2026-11-22). See engine/job-premium.ts.\n guideMessage: {\n name: 'guideMessage',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerGuideDashMessage.7eaf64013d9f7cc6c5c32038dfc3fb81',\n provenance: 'verified',\n capturedAt: '2026-11-22',\n },\n guideMessages: {\n name: 'guideMessages',\n transport: 'voyager-graphql',\n path: `${VOYAGER}/graphql`,\n queryId: 'voyagerGuideDashBionicMessageV2.6c3ccc4bfc5030c09d28a50e5332ac06',\n provenance: 'verified',\n capturedAt: '2026-11-22',\n },\n jobPosting: {\n name: 'jobPosting',\n transport: 'voyager-restli',\n path: `${VOYAGER}/jobs/jobPostings`,\n decorationId: 'com.linkedin.voyager.deco.jobs.web.shared.WebFullJobPosting-65',\n provenance: 'verified',\n capturedAt: '2026-10-14',\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","// ─── A company page ───────────────────────────────────────────────────────────\n//\n// Captured 2026-10-14. The company page itself is server-rendered SDUI; the\n// GraphQL company query by universalName answers only the company's urn. The\n// REST resource behind the `company` contract answers in JSON with what the\n// About tab shows:\n//\n// organization/companies/<id> the company\n// organization/companies?q=universalName&… a collection of one\n//\n// Both carry the affiliated and showcase pages in `included`, each with its\n// follower count. LinkedIn left `tagline` and `foundedOn` null for Microsoft,\n// whose page shows neither; they are read when present.\n\nimport { CONTRACTS } from './contracts.ts';\nimport type { Failure } from './sdui-form.ts';\n\nexport type CompanyRef = { id: string } | { name: string };\n\n/** A company from its universal name, page URL, numeric id or urn. */\nexport function companyRefOf(input: string): CompanyRef | undefined {\n const s = input.trim();\n if (/^\\d+$/.test(s)) return { id: s };\n const urn = s.match(/^urn:li:(?:fsd_company|fs_normalized_company|company|organization):(\\d+)$/);\n if (urn?.[1] !== undefined) return { id: urn[1] };\n const page = s.match(/linkedin\\.com\\/(?:company|showcase)\\/([^/?#\\s]+)/);\n const slug = page?.[1] ?? (/^[A-Za-z0-9][A-Za-z0-9_%.-]*$/.test(s) ? s : undefined);\n if (slug === undefined) return undefined;\n const name = decodeURIComponent(slug);\n return /^\\d+$/.test(name) ? { id: name } : { name };\n}\n\nexport function companyUrl(ref: CompanyRef): string {\n const c = CONTRACTS.company;\n if (c?.decorationId === undefined) throw new Error(\"the 'company' contract is missing\");\n const deco = `decorationId=${c.decorationId}`;\n return 'id' in ref\n ? `${c.path}/${ref.id}?${deco}`\n : `${c.path}?${deco}&q=universalName&universalName=${encodeURIComponent(ref.name)}`;\n}\n\n// ─── Reading it ───────────────────────────────────────────────────────────────\n\nexport interface RelatedPage {\n id: string;\n name: string;\n url?: string;\n followers?: number;\n}\n\nexport interface Company {\n /** What `people --company`, `jobs --company` and `search posts --from-company` take. */\n id: string;\n name: string;\n universalName?: string;\n url: string;\n tagline?: string;\n /** The About tab's overview. */\n about?: string;\n website?: string;\n industry?: string;\n /** \"Public Company\", \"Privately Held\", … */\n type?: string;\n /** The size band the company chose, \"10,001+\" or \"51-200\". */\n size?: string;\n /** Members who list the company: the page's \"employees\" link. */\n employeesOnLinkedIn?: number;\n followers?: number;\n headquarters?: string;\n founded?: number;\n phone?: string;\n specialties?: string[];\n locations?: string[];\n affiliated?: RelatedPage[];\n showcasePages?: RelatedPage[];\n /** The company's own job search, every affiliate included. */\n jobsUrl?: string;\n}\n\ntype Node = Record<string, unknown>;\n\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst idOf = (urn: unknown) => String(urn ?? '').match(/:(\\d+)$/)?.[1];\nconst str = (v: unknown) => (typeof v === 'string' && v.trim() !== '' ? v.trim() : undefined);\nconst slash = (u: unknown) => {\n const s = str(u);\n return s === undefined ? undefined : s.endsWith('/') ? s : `${s}/`;\n};\n\nfunction defined<T extends object>(obj: T): T {\n for (const k of Object.keys(obj) as (keyof T)[]) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\n/** \"1 Microsoft Way, Redmond, Washington 98052, US\" */\nfunction address(a: unknown): string | undefined {\n const n = a as Node | null | undefined;\n if (n === null || n === undefined) return undefined;\n const region = [str(n.geographicArea), str(n.postalCode)].filter(Boolean).join(' ');\n const parts = [str(n.line1), str(n.line2), str(n.city), str(region), str(n.country)];\n const line = parts.filter(Boolean).join(', ');\n return line === '' ? undefined : line;\n}\n\nfunction sizeOf(range: unknown): string | undefined {\n const r = range as { start?: unknown; end?: unknown } | null | undefined;\n if (typeof r?.start !== 'number') return undefined;\n const n = (x: number) => x.toLocaleString('en-US');\n return typeof r.end === 'number' ? `${n(r.start)}-${n(r.end)}` : `${n(r.start)}+`;\n}\n\nconst urns = (v: unknown) => (Array.isArray(v) ? v.filter((u) => typeof u === 'string') : []);\n\nexport function parseCompany(json: unknown): { ok: true; company: Company } | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const data = root?.data;\n if (data === undefined || data === null) return drift('the company answer carried no data');\n const included = root?.included ?? [];\n const byUrn = new Map(included.map((n) => [n.entityUrn, n]));\n\n // By id the data is the company; by name, a collection of (at most) one.\n let c: Node | undefined = data;\n if (!String(data.$type ?? '').endsWith('organization.Company')) {\n const listed = urns(data['*elements']);\n if (listed.length === 0)\n return { ok: false, code: 'NOT_FOUND', message: 'no company has that name on LinkedIn' };\n c = byUrn.get(listed[0]);\n if (c === undefined) return drift('the company was listed but not sent');\n }\n const id = idOf(c.entityUrn);\n const name = str(c.name);\n if (id === undefined || name === undefined) return drift('the company carried no id or name');\n\n const followersOf = (n: Node) => {\n const f = byUrn.get(n['*followingInfo']) as Node | undefined;\n return typeof f?.followerCount === 'number' ? f.followerCount : undefined;\n };\n const related = (list: unknown): RelatedPage[] | undefined => {\n const pages = urns(list).flatMap((u) => {\n const p = byUrn.get(u);\n const pid = idOf(u);\n const pname = str(p?.name);\n if (p === undefined || pid === undefined || pname === undefined) return [];\n return [defined({ id: pid, name: pname, url: slash(p.url), followers: followersOf(p) })];\n });\n return pages.length > 0 ? pages : undefined;\n };\n const industry = urns(c['*companyIndustries'])\n .map((u) => str(byUrn.get(u)?.localizedName))\n .find((x) => x !== undefined);\n const locations = (Array.isArray(c.confirmedLocations) ? c.confirmedLocations : [])\n .map(address)\n .filter((x): x is string => x !== undefined);\n const specialties = Array.isArray(c.specialities)\n ? c.specialities.filter((x): x is string => typeof x === 'string')\n : [];\n const founded = (c.foundedOn as { year?: unknown } | null | undefined)?.year;\n\n return {\n ok: true,\n company: defined({\n id,\n name,\n universalName: str(c.universalName),\n url: slash(c.url) ?? `https://www.linkedin.com/company/${id}/`,\n tagline: str(c.tagline),\n about: str(c.description),\n website: str(c.companyPageUrl),\n industry,\n type: str((c.companyType as Node | null | undefined)?.localizedName),\n size: sizeOf(c.staffCountRange),\n employeesOnLinkedIn: typeof c.staffCount === 'number' ? c.staffCount : undefined,\n followers: followersOf(c),\n headquarters: address(c.headquarter),\n founded: typeof founded === 'number' ? founded : undefined,\n phone: str((c.phone as Node | null | undefined)?.number),\n specialties: specialties.length > 0 ? specialties : undefined,\n locations: locations.length > 0 ? locations : undefined,\n affiliated: related(c.affiliatedCompanies),\n showcasePages: related(c.showcasePages),\n jobsUrl: str(c.jobSearchPageUrl),\n }),\n };\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 =\n | 'profile'\n | 'search'\n | 'page'\n | 'jobSearch'\n | 'jobRead'\n | 'write'\n | '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 // Set on 2026-10-14 by the owner's decision, for job hunting: about ten\n // keyword searches read in full (25 jobs a page, often 100-300 a search),\n // then the finalists read for their apply links. Kept apart from `search`\n // so a hunt neither uses up nor is stopped by people and company research.\n // Guesses like every other cap; the client's 3-15s gap still paces each call.\n jobSearch: {\n perDay: 150,\n provenance: 'guessed',\n note: 'job search pages and filter lists; set for ~10 keyword searches a day',\n },\n jobRead: {\n perDay: 60,\n provenance: 'guessed',\n note: 'one job read in full, for its apply link',\n },\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 // Raised from 250 with the job classes, so a full hunt (~120 searches and\n // 60 reads) still leaves room for everything else.\n global: { perDay: 350, 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","// ─── 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","// ─── 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 // A challenge is an HTML page. JSON and RSC answers are data, and data says\n // \"challenges\" (a job description opened an indefinite cooldown, 2026-11-22).\n if (!/^\\s*</.test(body)) return 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 /** Sent verbatim — a media upload PUTs the file itself. Exclusive with `body`. */\n bytes?: Uint8Array;\n /** Extra headers, layered over the session's. An upload names its own content type. */\n headers?: Record<string, string>;\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\n/** Bytes go verbatim, a JSON body is serialised, and a read carries nothing. */\nfunction encodeBody(spec: RequestSpec): Uint8Array | string | undefined {\n if (spec.bytes !== undefined) return spec.bytes;\n return spec.body === undefined ? undefined : JSON.stringify(spec.body);\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 // The page-data endpoints answer 500 without a referer (2026-11), as no\n // browser ever sends them one. Any LinkedIn page will do; a caller may name its own.\n if (spec.url.includes('linkedin.com/flagship-web/'))\n requestHeaders.referer = 'https://www.linkedin.com/feed/';\n Object.assign(requestHeaders, spec.headers);\n const body = encodeBody(spec);\n\n try {\n const res = await deps.fetch(spec.url, {\n method: spec.method ?? 'GET',\n headers: requestHeaders,\n ...(body === undefined ? {} : { 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","// ─── 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 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 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 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","// 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","// ─── Paged searches over several keyword sets, merged by id ───────────────────\n//\n// Shared by `jobs` and `people`. Each keyword set is searched on its own,\n// paged to the limit, and the results are merged by id: a row found by several\n// sets comes back once, naming them in `matched`, most-matched first. A set\n// that fails is reported and the others are kept; only all failing is an error.\n\nimport type { Failure } from '../engine/sdui-form.ts';\n\n/** One page of a search, as a source parsed it. */\nexport interface Paged<T extends { id: string }> {\n ok: true;\n items: T[];\n /** How far LinkedIn will page this query. */\n total?: number;\n /** LinkedIn's own count of matches, when it is more than it will page. */\n claimed?: number;\n /** What the source resolved part of the query to (a place, say). */\n resolved?: unknown;\n unknownTypes: Record<string, number>;\n}\n\nexport type PageFetch<T extends { id: string }> = (\n keywords: string | undefined,\n start: number,\n) => Promise<Paged<T> | Failure>;\n\nexport interface Paging {\n pageSize: number;\n /** LinkedIn serves no further than this into any one query. */\n max: number;\n}\n\nexport type Matched<T> = T & {\n /** With several keyword sets: the ones that found this row, in the order given. */\n matched?: string[];\n};\n\n/** The keyword sets, trimmed, each once (case-insensitively), in the order given. */\nexport function keywordSets(keywords: string | string[] | undefined): string[] {\n const given = keywords === undefined ? [] : Array.isArray(keywords) ? keywords : [keywords];\n const out: string[] = [];\n for (const k of given.map((g) => g.trim())) {\n if (k !== '' && !out.some((o) => o.toLowerCase() === k.toLowerCase())) out.push(k);\n }\n return out;\n}\n\ninterface Collected<T> {\n items: T[];\n total?: number;\n claimed?: number;\n resolved?: unknown;\n stoppedBy?: string;\n exhausted: boolean;\n unknownTypes: Record<string, number>;\n}\n\nfunction addCounts(into: Record<string, number>, from: Record<string, number>) {\n for (const [k, n] of Object.entries(from)) into[k] = (into[k] ?? 0) + n;\n}\n\n/** Pages from `first` until `want` rows, the end of the results, or a failure. */\nasync function collect<T extends { id: string }>(\n fetchPage: PageFetch<T>,\n keywords: string | undefined,\n first: number,\n want: number,\n paging: Paging,\n): Promise<Collected<T> | Failure> {\n const out: Collected<T> = { items: [], exhausted: false, unknownTypes: {} };\n for (let start = first; out.items.length < want && start < paging.max; start += paging.pageSize) {\n const page = await fetchPage(keywords, start);\n if (!page.ok) {\n // The first page failing is a failure; a later one leaves a partial list.\n if (out.items.length === 0) return page;\n out.stoppedBy = page.code;\n break;\n }\n out.total = page.total ?? out.total;\n out.claimed = page.claimed ?? out.claimed;\n out.resolved = page.resolved ?? out.resolved;\n addCounts(out.unknownTypes, page.unknownTypes);\n const fresh = page.items.filter((j) => !out.items.some((x) => x.id === j.id));\n const room = want - out.items.length;\n out.items.push(...fresh.slice(0, room));\n // The limit cut this page short: there is more, even on the last page.\n if (fresh.length > room) break;\n if (\n page.items.length === 0 ||\n (out.total !== undefined && start + paging.pageSize >= out.total)\n ) {\n out.exhausted = true;\n break;\n }\n }\n return out;\n}\n\n/** One keyword set's search, as `meta.searches` reports it. */\nexport interface SearchReport {\n keywords?: string;\n claimedCount?: number;\n returnedCount: number;\n state: 'complete' | 'partial' | 'failed';\n next?: number;\n /** LinkedIn claims more than it will serve; narrow the query to see the rest. */\n servedLimit?: number;\n stoppedBy?: string;\n}\n\nfunction reportOf<T>(\n keywords: string | undefined,\n found: Collected<T>,\n first: number,\n): SearchReport {\n const capped =\n found.exhausted &&\n found.claimed !== undefined &&\n found.total !== undefined &&\n found.claimed > found.total;\n const report: SearchReport = {\n ...(keywords !== undefined ? { keywords } : {}),\n claimedCount: found.claimed ?? found.total,\n returnedCount: found.items.length,\n state: found.stoppedBy === undefined && found.exhausted && !capped ? 'complete' : 'partial',\n };\n if (!found.exhausted) report.next = first + found.items.length;\n if (capped) report.servedLimit = found.total;\n if (found.stoppedBy !== undefined) report.stoppedBy = found.stoppedBy;\n return report;\n}\n\nexport interface Merged<T> {\n rows: Matched<T>[];\n searches: SearchReport[];\n /** Rows dropped because an earlier keyword set had already found them. */\n duplicates: number;\n resolved?: unknown;\n unknownTypes: Record<string, number>;\n failure?: Failure;\n}\n\n/** Adds one search's rows; a row already found gains this keyword set instead. */\nfunction mergeInto<T extends { id: string }>(\n out: Merged<T>,\n byId: Map<string, Matched<T>>,\n items: T[],\n keywords?: string,\n) {\n for (const item of items) {\n const seen = byId.get(item.id);\n if (seen !== undefined) {\n out.duplicates++;\n if (keywords !== undefined) seen.matched?.push(keywords);\n continue;\n }\n const row: Matched<T> = keywords !== undefined ? { ...item, matched: [keywords] } : item;\n byId.set(item.id, row);\n out.rows.push(row);\n }\n}\n\n/**\n * Runs each keyword set's search and merges the results by id. With several\n * sets, each row says which found it and the most-found come first; ties keep\n * the order LinkedIn ranked them in.\n */\nexport async function searchAll<T extends { id: string }>(\n fetchPage: PageFetch<T>,\n sets: (string | undefined)[],\n first: number,\n want: number,\n paging: Paging,\n): Promise<Merged<T>> {\n const out: Merged<T> = { rows: [], searches: [], duplicates: 0, unknownTypes: {} };\n const byId = new Map<string, Matched<T>>();\n for (const keywords of sets) {\n const found = await collect(fetchPage, keywords, first, want, paging);\n if ('ok' in found) {\n out.failure = out.failure ?? found;\n out.searches.push({\n ...(keywords !== undefined ? { keywords } : {}),\n returnedCount: 0,\n state: 'failed',\n stoppedBy: found.code,\n });\n continue;\n }\n out.searches.push(reportOf(keywords, found, first));\n out.resolved = out.resolved ?? found.resolved;\n addCounts(out.unknownTypes, found.unknownTypes);\n mergeInto(out, byId, found.items, sets.length > 1 ? keywords : undefined);\n }\n if (sets.length > 1) out.rows.sort((x, y) => (y.matched?.length ?? 0) - (x.matched?.length ?? 0));\n return out;\n}\n\n/**\n * The envelope's `meta`. One keyword set keeps the plain shape with its own\n * paging; several add `searches` (each set's report) and `duplicates`.\n */\nexport function metaOf<T>(\n operation: string,\n merged: Merged<T>,\n single: boolean,\n first: number,\n extra: { unread?: number; readStop?: string } = {},\n): Record<string, unknown> {\n const { unread = 0, readStop } = extra;\n const searched = merged.searches;\n const allComplete = searched.every((r) => r.state === 'complete');\n const meta: Record<string, unknown> = {\n state: allComplete && unread === 0 && readStop === undefined ? 'complete' : 'partial',\n operation,\n };\n if (single) {\n const { keywords: _k, state: _s, ...report } = searched[0] as SearchReport;\n Object.assign(meta, report, { start: first });\n if (readStop !== undefined) meta.stoppedBy = meta.stoppedBy ?? readStop;\n } else {\n Object.assign(meta, {\n returnedCount: merged.rows.length,\n duplicates: merged.duplicates,\n start: first,\n searches: searched,\n ...(readStop !== undefined ? { stoppedBy: readStop } : {}),\n });\n }\n if (unread > 0) meta.unread = unread;\n if (Object.keys(merged.unknownTypes).length > 0) meta.unknownTypes = merged.unknownTypes;\n return meta;\n}\n\n/** One flat line from the given parts; a bar inside a value would read as a column break. */\nexport function line(parts: (string | undefined)[]): string {\n return parts\n .filter((p): p is string => p !== undefined && p !== '')\n .map((p) => p.replaceAll(' | ', ' / '))\n .join(' | ');\n}\n","// ─── SDUI forms, read and sent back ───────────────────────────────────────────\n//\n// LinkedIn's profile forms are SDUI. Opening one returns every field's current\n// value (`modelStates`) and the server actions its buttons fire, each with the\n// state keys it reads and its payload. A save is that action, those values,\n// some replaced. Nothing here knows any particular form; sdui-profile.ts and\n// sdui-position.ts do.\n//\n// The browser sends some values it COMPUTES from others (a company is\n// required unless the role is freelance). Those are evaluated here from the\n// expression the form ships, and an expression we do not recognise is refused:\n// a guessed value is a save that quietly says something else.\n\nexport interface ModelValue {\n protoCase: string;\n value: unknown;\n}\n\nexport type Model = Map<string, ModelValue>;\n\nexport interface RequestArgs {\n requestedStateKeys: { key: { value: { id: string } } }[];\n payload: Record<string, unknown>;\n}\n\nexport type Failure = { ok: false; code: string; message: string; hint?: string };\n\n/** The balanced JSON array or object starting at `start`. */\nexport function balanced(s: string, start: number): string | null {\n const open = s[start];\n const close = open === '[' ? ']' : '}';\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let i = start; i < s.length; i++) {\n const ch = s[i];\n if (escaped) escaped = false;\n else if (ch === '\\\\') escaped = true;\n else if (ch === '\"') inString = !inString;\n else if (!inString && ch === open) depth++;\n else if (!inString && ch === close) {\n depth--;\n if (depth === 0) return s.slice(start, i + 1);\n }\n }\n return null;\n}\n\nexport function parseAt<T>(s: string, start: number): T | null {\n const text = start < 0 ? null : balanced(s, start);\n if (text === null) return null;\n try {\n return JSON.parse(text) as T;\n } catch {\n return null;\n }\n}\n\n/** A model state's value in the shape the browser sends it back. */\nfunction plain(v: Record<string, unknown>): ModelValue {\n const protoCase = String(v.$case);\n const raw = v[protoCase];\n if (protoCase === 'stringListValue') {\n return { protoCase, value: (raw as { stringValues?: string[] })?.stringValues ?? [] };\n }\n // React Server Components encode a bigint as \"$n<digits>\".\n if (protoCase === 'signedLongValue' && typeof raw === 'string' && raw.startsWith('$n')) {\n return { protoCase, value: { type: 'bigint', value: raw.slice(2) } };\n }\n return { protoCase, value: raw };\n}\n\n/**\n * The form's initial values. The same keys reappear inside actions (a\n * checkbox's SetState, a reset); only `modelStates` holds what the profile\n * has now. Null when there is none — a form we no longer understand.\n */\nexport function readModel(stream: string): Model | null {\n const at = stream.indexOf('\"modelStates\":[');\n const entries = parseAt<\n { key?: { key?: { value?: { id?: string } } }; value?: Record<string, unknown> }[]\n >(stream, at === -1 ? -1 : stream.indexOf('[', at));\n if (entries === null) return null;\n const model: Model = new Map();\n for (const entry of entries) {\n const id = entry.key?.key?.value?.id;\n if (id !== undefined && entry.value !== undefined && !model.has(id)) {\n model.set(id, plain(entry.value));\n }\n }\n return model;\n}\n\n/** A server action's arguments, verbatim, or null when the stream has none. */\nexport function findRequest(stream: string, requestId: string): RequestArgs | null {\n const at = stream.indexOf(`\"requestId\":\"${requestId}\",\"requestedArguments\":`);\n if (at === -1) return null;\n const args = parseAt<RequestArgs>(\n stream,\n stream.indexOf('{', stream.indexOf('\"requestedArguments\":', at)),\n );\n return args !== null && Array.isArray(args.requestedStateKeys) && args.payload !== undefined\n ? args\n : null;\n}\n\ntype Evaluated = { ok: true; value: unknown } | Failure;\ntype Node = { expression?: { $case?: string } & Record<string, unknown> };\n\nconst unknownExpression = (what: string): Failure => ({\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `the form computes a value with an expression this tool does not evaluate (${what})`,\n hint: 'Nothing was sent. Re-capture the form to see what it has become.',\n});\n\nfunction boundId(body: unknown): string | undefined {\n return (body as { key?: { key?: { value?: { id?: string } } } })?.key?.key?.value?.id;\n}\n\nfunction str(node: Node, model: Model): string | null {\n const e = node.expression;\n if (e?.$case === 'stringValue') return String(e.stringValue);\n if (e?.$case === 'bindableString') {\n const v = model.get(boundId(e.bindableString) ?? '')?.value;\n return typeof v === 'string' ? v : '';\n }\n return null;\n}\n\nfunction bool(node: Node, model: Model): boolean | null {\n const e = node.expression;\n const body = e?.[e?.$case ?? ''] as Record<string, Node> | undefined;\n switch (e?.$case) {\n case 'booleanExpression':\n return bool(body as Node, model);\n case 'booleanValue':\n return e.booleanValue === true;\n case 'bindableBoolean':\n return model.get(boundId(e.bindableBoolean) ?? '')?.value === true;\n case 'notExpression': {\n const a = bool(body?.a ?? {}, model);\n return a === null ? null : !a;\n }\n case 'orExpression':\n case 'andExpression': {\n const a = bool(body?.a ?? {}, model);\n const b = bool(body?.b ?? {}, model);\n if (a === null || b === null) return null;\n return e.$case === 'orExpression' ? a || b : a && b;\n }\n case 'stringEqualsExpression': {\n const a = str(body?.a ?? {}, model);\n const b = str(body?.b ?? {}, model);\n if (a === null || b === null) return null;\n return (body as { ignoreCase?: boolean }).ignoreCase === true\n ? a.toLowerCase() === b.toLowerCase()\n : a === b;\n }\n default:\n return null;\n }\n}\n\n/** Evaluate a computed value the way the browser would. */\nexport function evaluate(expression: unknown, model: Model): Evaluated {\n const value = bool(expression as Node, model);\n return value === null\n ? unknownExpression(JSON.stringify(expression).slice(0, 80))\n : { ok: true, value };\n}\n\n/** A computed value the caller resolves itself; undefined to evaluate it here. */\nexport type Resolver = (key: string, value: ModelValue) => Evaluated | undefined;\n\nexport interface WireState {\n key: string;\n namespace: 'MemoryNamespace';\n value: unknown;\n originalProtoCase: string;\n protoKey: { $type: 'proto.sdui.Key'; value: { $case: 'id'; id: string } };\n}\n\n/**\n * The states a request sends: one per requested key the form has a value for\n * (the browser omits the rest), computed ones evaluated.\n */\nexport function wireStates(keys: string[], model: Model, resolve: Resolver): WireState[] | Failure {\n const out: WireState[] = [];\n for (const id of keys) {\n const state = model.get(id);\n if (state === undefined) continue;\n let value = state.value;\n if (state.protoCase === 'expression') {\n const r = resolve(id, state) ?? evaluate(state.value, model);\n if (!r.ok) return r;\n value = r.value;\n }\n out.push({\n key: id,\n namespace: 'MemoryNamespace',\n value,\n originalProtoCase: state.protoCase,\n protoKey: { $type: 'proto.sdui.Key', value: { $case: 'id', id } },\n });\n }\n return out;\n}\n\nexport const keysOf = (args: RequestArgs): string[] =>\n args.requestedStateKeys.map((k) => k.key.value.id);\n\n/** A server-request body as the browser sends it. */\nexport function requestBody(\n requestId: string,\n args: RequestArgs,\n states: unknown[],\n screen: string,\n) {\n const requestedArguments = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: args.requestedStateKeys,\n payload: args.payload,\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n return {\n requestId,\n serverRequest: {\n requestId,\n requestedArguments,\n isApfcEnabled: false,\n isStreaming: false,\n rumPageKey: '',\n },\n states,\n requestedArguments: { ...requestedArguments, states, screenId: screen, knownTemplateIds: [] },\n };\n}\n\n/** Open a profile form as the browser does. A read, though it is issued as a POST. */\nexport function navBody(screen: string, payload: Record<string, unknown>) {\n return {\n clientArguments: {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload,\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n states: [],\n screenId: screen,\n knownTemplateIds: [],\n },\n isModal: true,\n };\n}\n\n/** Errors a 200 can still carry: a non-empty `errors` list in the response. */\nexport function responseErrors(raw: string): string | null {\n return raw.match(/\"errors\":\\[([^\\]]+)\\]/)?.[1]?.slice(0, 300) ?? null;\n}\n","// ─── Searching posts ──────────────────────────────────────────────────────────\n//\n// Captured 2026-10-14. Posts are the one search kind the Voyager search no\n// longer serves: asked for `resultType:CONTENT` it claims hundreds of matches\n// and returns none, at any page size. The results page loads them from an SDUI\n// pager, `contentSearchResults`, whose payload takes the keywords, the start,\n// the count and every filter as a list under the filter panel's own names.\n//\n// The answer is an RSC stream, and a heavy one (about half a megabyte a post).\n// A post is not one record in it. Each post's top row (`feed-full-update`)\n// holds the card's skeleton; its author, text and counts sit in other rows,\n// reached through `$L<id>` references, and the numbers live in the stream's\n// model state, keyed by the post's content urn:\n//\n// ReactionType_<TYPE>_<urn> commentCount-<urn> repostCount-<urn>\n//\n// So a post is read by following its top row's references and reading each\n// part from the rows it reaches. The content urn (a ugcPost, share or group\n// post) is the post's id: /feed/update/<urn>/ opens it and `post` reads its\n// comments. Labels such as the time (\"5 hours ago\") come in the viewer's\n// LinkedIn language and are kept as shown.\n\nimport type { Failure } from './sdui-form.ts';\nimport { balanced, readModel } from './sdui-form.ts';\n\nexport const POSTS_PAGER = 'com.linkedin.sdui.search.contentSearchResults';\nconst SCREEN = 'com.linkedin.sdui.flagshipnav.search.SearchResultsContent';\nexport const POSTS_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/pagination?sduiid=${POSTS_PAGER}`;\n\n/** Posts per call. The page asks for 3; 20 came back whole (2026-10-14). */\nexport const POSTS_PAGE = 20;\n\n/** The filters the pager takes, each a list, as the filter panel names them. */\nexport const POST_FILTERS = [\n 'sortBy',\n 'postedBy',\n 'datePosted',\n 'contentType',\n 'fromMember',\n 'mentionsOrganization',\n 'mentionsMember',\n 'fromOrganization',\n 'authorCompany',\n 'authorIndustry',\n 'authorJobTitle',\n] as const;\n\nexport type PostFilter = (typeof POST_FILTERS)[number];\n\nexport interface PostsQuery {\n keywords?: string;\n filters: Partial<Record<PostFilter, string[]>>;\n start: number;\n count?: number;\n}\n\n/** The pager request, shaped as the results page sends it. */\nexport function postsPagerBody(q: PostsQuery) {\n const payload: Record<string, unknown> = {\n startIndex: q.start,\n keywords: q.keywords ?? '',\n count: q.count ?? POSTS_PAGE,\n };\n for (const f of POST_FILTERS) payload[f] = q.filters[f] ?? [];\n payload.spellCheckEnabled = true;\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 pagerId: POSTS_PAGER,\n clientArguments: { ...args, states: [], screenId: SCREEN, knownTemplateIds: [] },\n paginationRequest: {\n $type: 'proto.sdui.actions.requests.PaginationRequest',\n pagerId: POSTS_PAGER,\n retryCount: 0,\n requestedArguments: args,\n },\n };\n}\n\n// ─── The stream's rows ────────────────────────────────────────────────────────\n\n/** How many UTF-16 units `bytes` UTF-8 bytes take, starting at `from`. */\nfunction unitsFor(stream: string, from: number, bytes: number): number {\n let i = from;\n let left = bytes;\n while (left > 0 && i < stream.length) {\n const c = stream.codePointAt(i) as number;\n left -= c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n i += c > 0xffff ? 2 : 1;\n }\n return i - from;\n}\n\n/**\n * An RSC stream split into its `<hex id>:<payload>` rows. A row ends at a\n * newline, except a text row, `<id>:T<hex byte length>,<text>`, which is\n * exactly that many bytes (newlines and all) with the next row straight after.\n */\nexport class Rows {\n readonly byId = new Map<string, string>();\n private readonly starts: { id: string; at: number }[] = [];\n private readonly texts = new Set<string>();\n\n constructor(readonly stream: string) {\n const head = /([0-9a-f]+):(?:T([0-9a-f]+),)?/y;\n let pos = 0;\n while (pos < stream.length) {\n if (stream[pos] === '\\n') {\n pos++;\n continue;\n }\n head.lastIndex = pos;\n const m = head.exec(stream);\n if (m === null) {\n // Not a row start: skip to the next line.\n const nl = stream.indexOf('\\n', pos);\n pos = nl === -1 ? stream.length : nl + 1;\n continue;\n }\n const id = m[1] as string;\n const body = pos + m[0].length;\n this.starts.push({ id, at: pos });\n let end: number;\n if (m[2] !== undefined) {\n end = body + unitsFor(stream, body, Number.parseInt(m[2], 16));\n this.texts.add(id);\n } else {\n const nl = stream.indexOf('\\n', body);\n end = nl === -1 ? stream.length : nl;\n }\n this.byId.set(id, stream.slice(body, end));\n pos = end;\n }\n }\n\n /** Whether a row is raw text (a `T` row) rather than JSON. */\n isText(id: string): boolean {\n return this.texts.has(id);\n }\n\n /** The row a stream position falls in. */\n at(pos: number): string | undefined {\n let lo = 0;\n let hi = this.starts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if ((this.starts[mid] as { at: number }).at <= pos) lo = mid;\n else hi = mid - 1;\n }\n return this.starts[lo]?.id;\n }\n\n /** Every row reachable from `id` through references, nearest first. */\n reach(id: string, limit = 400): string[] {\n const seen = new Set<string>([id]);\n const queue = [id];\n while (queue.length > 0 && seen.size < limit) {\n const row = this.byId.get(queue.shift() as string) ?? '';\n for (const m of row.matchAll(/\"\\$L?([0-9a-f]+)(?::[^\"]*)?\"/g)) {\n const ref = m[1] as string;\n if (!seen.has(ref) && this.byId.has(ref)) {\n seen.add(ref);\n queue.push(ref);\n }\n }\n }\n return [...seen];\n }\n}\n\n// ─── Reading a post ───────────────────────────────────────────────────────────\n\nexport interface PostHit {\n /** The content urn: ugcPost, share or groupPost. */\n id: string;\n url: string;\n author?: string;\n authorHeadline?: string;\n authorUrl?: string;\n /** When, as LinkedIn shows it, in the viewer's language (\"5h\", \"5 órája\"). */\n posted?: string;\n text?: string;\n reactions?: number;\n comments?: number;\n reposts?: number;\n}\n\n/**\n * The visible strings under a node, in order. An element is `[\"$\", type,\n * key, props]`: only its props' children are text; references are skipped.\n */\nfunction strings(v: unknown, out: string[] = []): string[] {\n if (typeof v === 'string') {\n if (!v.startsWith('$')) out.push(v);\n } else if (Array.isArray(v)) {\n if (v[0] === '$' && v[1] === 'br') out.push('\\n');\n else if (v[0] === '$') strings(v[3], out);\n else for (const x of v) strings(x, out);\n } else if (v !== null && typeof v === 'object' && 'children' in v) {\n strings((v as { children: unknown }).children, out);\n }\n return out;\n}\n\n/** Every text block in a row from `from` on, as the reader would see it. */\nfunction texts(row: string, from = 0): string[] {\n const part = row.slice(Math.max(0, from));\n const out: string[] = [];\n for (const m of part.matchAll(/\"textProps\":/g)) {\n const obj = balanced(part, part.indexOf('{', m.index ?? 0));\n if (obj === null) continue;\n const t = strings(JSON.parse(obj)).join('').trim();\n if (t !== '') out.push(t);\n }\n return out;\n}\n\nconst jsonString = (s: string) => JSON.parse(`\"${s}\"`) as string;\n\nconst REACTIONS = [\n 'LIKE',\n 'PRAISE',\n 'EMPATHY',\n 'INTEREST',\n 'APPRECIATION',\n 'ENTERTAINMENT',\n 'SUPER_LIKE',\n];\n\ninterface Read {\n post: PostHit | undefined;\n /** The rows the post was read from, and the path to them. */\n used: string[];\n}\n\n/** The first row under `from` holding `view`, and that row's own subtree. */\nfunction part(\n rows: Rows,\n from: string[],\n view: string,\n depth = 60,\n): { row: string; under: string[] } | undefined {\n const id = from.find((r) => rows.byId.get(r)?.includes(`\"viewName\":\"${view}\"`));\n return id === undefined ? undefined : { row: id, under: rows.reach(id, depth) };\n}\n\n/** The first row in `ids` that `find` reads something from, and what it read. */\nfunction firstIn<T>(rows: Rows, ids: string[], find: (row: string) => T | undefined) {\n for (const id of ids) {\n const v = find(rows.byId.get(id) ?? '');\n if (v !== undefined) return { id, v };\n }\n return undefined;\n}\n\nfunction authorOf(rows: Rows, actor: { under: string[] } | undefined) {\n if (actor === undefined) return { fields: {}, used: [] as string[] };\n const state = (key: string) => (row: string) => {\n const m = row.match(new RegExp(`\"${key}\"[^]*?\"stringValue\":\"((?:[^\"\\\\\\\\]|\\\\\\\\.)*)\"`));\n return m?.[1] === undefined ? undefined : jsonString(m[1]);\n };\n // Person links come relative (\"/in/<vanity>/\"), page links absolute.\n const link = firstIn(\n rows,\n actor.under,\n (row) =>\n row.match(\n /\"(?:https:\\/\\/www\\.linkedin\\.com)?(\\/(?:in|company|school|showcase)\\/[^\"?/]+)/,\n )?.[1],\n );\n const person = firstIn(rows, actor.under, state('profile_name_loading_state'));\n const headline = firstIn(rows, actor.under, state('profile_headline_loading_state'));\n // A company or page has no profile state: its name is the visible text\n // the author link's own label starts with.\n const page =\n person !== undefined\n ? undefined\n : firstIn(rows, actor.under, (row) => {\n const labels = [...row.matchAll(/\"aria-label\":\"((?:[^\"\\\\]|\\\\.)+)\"/g)].map((m) =>\n jsonString(m[1] as string).trim(),\n );\n // The label may carry a badge after the name (\"Microsoft Premium\").\n return texts(row).find((t) => labels.some((l) => l === t || l.startsWith(`${t} `)));\n });\n const named = person ?? page;\n return {\n fields: {\n ...(named !== undefined ? { author: named.v.trim() } : {}),\n ...(headline !== undefined ? { authorHeadline: headline.v } : {}),\n ...(link !== undefined ? { authorUrl: `https://www.linkedin.com${link.v}/` } : {}),\n },\n used: [link?.id, named?.id, headline?.id].filter((x): x is string => x !== undefined),\n };\n}\n\nfunction readPost(rows: Rows, top: string, model: ReturnType<typeof readModel>): Read {\n const reach = rows.reach(top);\n const counted = reach.find((r) => /commentCount-urn:li:\\w+:\\d+/.test(rows.byId.get(r) ?? ''));\n const id =\n counted === undefined\n ? undefined\n : rows.byId.get(counted)?.match(/commentCount-(urn:li:\\w+:\\d+)/)?.[1];\n if (id === undefined) return { post: undefined, used: [top] };\n\n const actor = part(rows, reach, 'feed-actor');\n const author = authorOf(rows, actor);\n const sub = part(rows, reach, 'feed-actor-sub-description', 4);\n const commentary = part(rows, reach, 'feed-commentary');\n const n = (k: string) => {\n const v = (model?.get(k) as { value?: unknown } | undefined)?.value;\n return typeof v === 'number' ? v : undefined;\n };\n const byType = REACTIONS.map((r) => n(`ReactionType_${r}_${id}`));\n const reactions = byType.some((v) => v !== undefined)\n ? byType.reduce<number>((a, v) => a + (v ?? 0), 0)\n : undefined;\n const subRow = sub === undefined ? '' : (rows.byId.get(sub.row) ?? '');\n const posted =\n sub === undefined\n ? undefined\n : texts(subRow, subRow.indexOf('\"viewName\":\"feed-actor-sub-description\"'))[0];\n const said =\n commentary === undefined ? undefined : firstIn(rows, commentary.under, (row) => texts(row)[0]);\n const text = said?.v;\n\n const post: PostHit = {\n id,\n url: `https://www.linkedin.com/feed/update/${id}/`,\n ...author.fields,\n ...(posted !== undefined ? { posted } : {}),\n ...(text !== undefined ? { text } : {}),\n ...(reactions !== undefined ? { reactions } : {}),\n };\n const comments = n(`commentCount-${id}`);\n const reposts = n(`repostCount-${id}`);\n if (comments !== undefined) post.comments = comments;\n if (reposts !== undefined) post.reposts = reposts;\n const parts = [actor?.row, sub?.row, commentary?.row, said?.id].filter(\n (x): x is string => x !== undefined,\n );\n const used = [top, counted as string, ...author.used, ...parts];\n return { post, used };\n}\n\nexport interface PostsPage {\n ok: true;\n posts: PostHit[];\n /** Cards that looked like posts but carried no content urn. */\n unread: number;\n /** The rows the posts were read from: what a fixture needs to keep. */\n used: Set<string>;\n}\n\nexport function parsePosts(stream: string): PostsPage | Failure {\n if (\n !stream.includes(POSTS_PAGER) &&\n !stream.includes('\"isPartialPage\"') &&\n !stream.includes('feed-full-update')\n ) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the posts search page could not be read',\n hint: 'the posts search response changed shape; re-capture it',\n };\n }\n const rows = new Rows(stream);\n const model = readModel(stream);\n const posts: PostHit[] = [];\n const used = new Set<string>();\n const tops = new Set<string>();\n let unread = 0;\n for (const m of stream.matchAll(/\"viewName\":\"feed-full-update\"/g)) {\n const top = rows.at(m.index ?? 0);\n if (top === undefined || tops.has(top)) continue;\n tops.add(top);\n const r = readPost(rows, top, model);\n for (const u of r.used) used.add(u);\n if (r.post === undefined) unread++;\n else if (!posts.some((p) => p.id === r.post?.id)) posts.push(r.post);\n }\n if (unread > 0 && posts.length === 0) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `${unread} posts were listed but none could be read`,\n hint: 'the posts search response changed shape; re-capture it',\n };\n }\n return { ok: true, posts, unread, used };\n}\n","// ─── Job search ───────────────────────────────────────────────────────────────\n//\n// Captured 2026-10-14. The jobs page now opens LinkedIn's \"AI job search\", an\n// SDUI screen that answers in an RSC stream and silently drops filters it does\n// not support (it lost the location and experience level of the URL we gave\n// it). The classic search behind /jobs/search/ is still served as plain\n// Voyager JSON, takes every filter, and is what this module speaks:\n//\n// jobCards voyagerJobsDashJobCards?q=jobSearch 25 cards a page\n// filters voyagerJobsDashSearchFilterClustersResource every filter, its\n// option ids, counts\n// detail jobs/jobPostings/<id> description, apply\n// link, applicants\n// hiring team SDUI component peopleWhoCanHelp who posted it, who\n// is hiring for it\n//\n// A typed location goes as `seoLocation`; LinkedIn resolves it and echoes the\n// geo it chose, which we report, because \"Vienna, Austria\" resolved to one\n// district of Vienna. A `geoId` is exact.\n\nimport { CONTRACTS } from './contracts.ts';\nimport { Rows } from './posts.ts';\nimport { encodeVariables, type RestliValue } from './restli.ts';\nimport type { Failure } from './sdui-form.ts';\n\n/** The three job contracts, verified; a missing one is a build error, not drift. */\nfunction contract(name: 'jobCards' | 'jobFilters' | 'jobPosting') {\n const c = CONTRACTS[name];\n if (c?.decorationId === undefined) throw new Error(`job contract '${name}' is missing`);\n return { path: c.path, decorationId: c.decorationId };\n}\n\n/**\n * Jobs per search call. The browser asks for 25; the server serves up to 100\n * and answers 101 with a 400 (probed 2026-10-14). Four times fewer calls.\n */\nexport const PAGE_SIZE = 100;\n\n/** Jobs per batch read. 100 returned all 100 in one call (2026-10-14). */\nexport const BATCH_SIZE = 100;\n\nexport interface JobQuery {\n keywords?: string;\n /** Free text, resolved by LinkedIn. Ignored when `geoId` is given. */\n location?: string;\n geoId?: string;\n /** selectedFilters, by LinkedIn's own parameter names. */\n filters: Record<string, string[]>;\n start: number;\n count: number;\n}\n\nfunction queryTuple(q: JobQuery): string {\n const locationUnion: RestliValue =\n q.geoId !== undefined\n ? { geoId: q.geoId }\n : q.location !== undefined\n ? { seoLocation: { location: q.location } }\n : undefined;\n const selected = Object.entries(q.filters).filter(([, v]) => v.length > 0);\n return encodeVariables({\n origin: 'JOB_SEARCH_PAGE_JOB_FILTER',\n keywords: q.keywords,\n locationUnion,\n selectedFilters: selected.length > 0 ? Object.fromEntries(selected) : undefined,\n spellCorrectionEnabled: true,\n });\n}\n\nexport function jobSearchUrl(q: JobQuery): string {\n const c = contract('jobCards');\n return (\n `${c.path}?decorationId=${c.decorationId}` +\n `&count=${q.count}&q=jobSearch&query=${queryTuple(q)}&start=${q.start}`\n );\n}\n\nexport function jobFiltersUrl(q: JobQuery): string {\n const c = contract('jobFilters');\n return `${c.path}?decorationId=${c.decorationId}&q=filters&query=${queryTuple(q)}`;\n}\n\nexport function jobDetailUrl(id: string): string {\n const c = contract('jobPosting');\n return `${c.path}/${id}?decorationId=${c.decorationId}`;\n}\n\n/** Many jobs in one call, the same projection as one: a Rest.li batch get. */\nexport function jobBatchUrl(ids: string[]): string {\n const c = contract('jobPosting');\n return `${c.path}?ids=List(${ids.join(',')})&decorationId=${c.decorationId}`;\n}\n\n/** A bare id, a /jobs/view/ URL, a ?currentJobId= URL or a job urn. */\nexport function jobIdOf(input: string): string | undefined {\n const s = input.trim();\n if (/^\\d+$/.test(s)) return s;\n const found =\n s.match(/\\/jobs\\/view\\/(?:[^/?#]*-)?(\\d+)/) ??\n s.match(/[?&]currentJobId=(\\d+)/) ??\n s.match(/urn:li:(?:fsd_|fs_normalized_)?jobPosting:(\\d+)/);\n return found?.[1];\n}\n\nconst viewUrl = (id: string) => `https://www.linkedin.com/jobs/view/${id}/`;\nconst day = (ms: unknown) =>\n typeof ms === 'number' ? new Date(ms).toISOString().slice(0, 10) : undefined;\n\ntype Node = Record<string, unknown>;\nconst text = (v: unknown): string | undefined => {\n const t = (v as { text?: unknown } | null | undefined)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim() : undefined;\n};\n\nfunction defined<T extends Record<string, unknown>>(obj: T): T {\n for (const k of Object.keys(obj)) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\n// ─── Cards ────────────────────────────────────────────────────────────────────\n\nexport type Workplace = 'on-site' | 'remote' | 'hybrid';\n\nexport interface JobCard {\n id: string;\n title: string;\n company?: string;\n location?: string;\n workplace?: Workplace;\n /** The day it was listed, YYYY-MM-DD. */\n listed?: string;\n easyApply: boolean;\n promoted: boolean;\n /** The pay line some cards carry, as LinkedIn wrote it. */\n salary?: string;\n /** Other card lines, e.g. \"Be an early applicant\", \"5 applicants\". */\n insights?: string[];\n url: string;\n}\n\nconst WORKPLACE_SUFFIX: Record<string, Workplace> = {\n remote: 'remote',\n hybrid: 'hybrid',\n 'on-site': 'on-site',\n};\n\n/** \"Warsaw, Poland (Remote)\" -> the place and the workplace, apart. */\nfunction splitLocation(line: string | undefined): { location?: string; workplace?: Workplace } {\n if (line === undefined) return {};\n const m = line.match(/^(.*?)\\s*\\(([^()]+)\\)$/);\n const kind = m?.[2] === undefined ? undefined : WORKPLACE_SUFFIX[m[2].toLowerCase()];\n return kind === undefined || m?.[1] === undefined\n ? { location: line }\n : { location: m[1], workplace: kind };\n}\n\nfunction cardToJob(card: Node): JobCard | undefined {\n const urn = card.jobPostingUrn ?? card['*jobPosting'];\n const id = typeof urn === 'string' ? jobIdOf(urn) : undefined;\n const title = typeof card.jobPostingTitle === 'string' ? card.jobPostingTitle : text(card.title);\n if (id === undefined || title === undefined) return undefined;\n\n const footer = Array.isArray(card.footerItems) ? (card.footerItems as Node[]) : [];\n const listed = footer.find((f) => f.type === 'LISTED_DATE');\n const insights = footer\n .filter((f) => !['LISTED_DATE', 'PROMOTED', 'EASY_APPLY_TEXT'].includes(String(f.type)))\n .map((f) => text(f.text))\n .filter((t): t is string => t !== undefined);\n const insight = text((card.relevanceInsight as Node | null)?.text);\n if (insight !== undefined) insights.push(insight);\n\n return defined({\n id,\n title,\n company: text(card.primaryDescription),\n ...splitLocation(text(card.secondaryDescription)),\n listed: day(listed?.timeAt),\n easyApply: footer.some((f) => f.type === 'EASY_APPLY_TEXT'),\n promoted: footer.some((f) => f.type === 'PROMOTED'),\n salary: text(card.tertiaryDescription),\n insights: insights.length > 0 ? insights : undefined,\n url: viewUrl(id),\n });\n}\n\nexport interface JobPage {\n ok: true;\n jobs: JobCard[];\n /** LinkedIn's claimed total for the query. */\n total: number | undefined;\n start: number;\n /** The place a typed location resolved to. */\n location?: { geoId: string; name: string };\n /** Card kinds we do not read, by name: counted, never silently dropped. */\n unknownTypes: Record<string, number>;\n}\n\nconst drift = (message: string): Failure => ({\n ok: false,\n code: 'SCHEMA_DRIFT',\n message,\n hint: 'the job search response changed shape; re-capture it',\n});\n\n/** The cards the page lists, in order; other card kinds counted by name. */\nfunction readCards(elements: Node[], included: Node[]) {\n const byUrn = new Map<string, Node>();\n for (const node of included) {\n if (typeof node.entityUrn === 'string') byUrn.set(node.entityUrn, node);\n }\n const jobs: JobCard[] = [];\n const unknownTypes: Record<string, number> = {};\n let unresolved = 0;\n for (const el of elements) {\n // Search calls it `jobCardUnion`; a collection, `jobCard`, with every other kind null.\n const union = (el.jobCardUnion ?? el.jobCard ?? {}) as Record<string, unknown>;\n const ref = union['*jobPostingCard'];\n if (typeof ref !== 'string') {\n for (const [kind, v] of Object.entries(union))\n if (v !== null && !kind.startsWith('$')) unknownTypes[kind] = (unknownTypes[kind] ?? 0) + 1;\n continue;\n }\n const card = byUrn.get(ref);\n const job = card === undefined ? undefined : cardToJob(card);\n if (job === undefined) unresolved++;\n else if (!jobs.some((j) => j.id === job.id)) jobs.push(job);\n }\n return { jobs, unknownTypes, unresolved };\n}\n\n/** The geo a typed location resolved to, as the response echoes it. */\nfunction resolvedGeo(included: Node[]): { location: { geoId: string; name: string } } | object {\n const geo = included.find((n) => typeof n.$type === 'string' && n.$type.endsWith('.common.Geo'));\n const geoId = typeof geo?.entityUrn === 'string' ? geo.entityUrn.split(':').pop() : undefined;\n const name = typeof geo?.fullLocalizedName === 'string' ? geo.fullLocalizedName : undefined;\n return geoId !== undefined && name !== undefined ? { location: { geoId, name } } : {};\n}\n\nexport function parseJobCards(json: unknown): JobPage | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const data = root?.data;\n const elements = data?.elements;\n if (data === undefined || !Array.isArray(elements))\n return drift('the job search returned no result list');\n const paging = (data.paging ?? {}) as { total?: unknown; start?: unknown };\n const total = typeof paging.total === 'number' ? paging.total : undefined;\n const start = typeof paging.start === 'number' ? paging.start : 0;\n const included = root?.included ?? [];\n\n const { jobs, unknownTypes, unresolved } = readCards(elements as Node[], included);\n if (unresolved > 0 && jobs.length === 0)\n return drift(`${unresolved} job cards were listed but none could be read`);\n if (elements.length === 0 && total !== undefined && total > start) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `LinkedIn claims ${total} jobs but returned none from ${start}`,\n hint: 'a failed fetch, not an empty search; do not report \"no jobs\"',\n };\n }\n return { ok: true, jobs, total, start, ...resolvedGeo(included), unknownTypes };\n}\n\n// ─── Detail ───────────────────────────────────────────────────────────────────\n\nexport interface JobDetail {\n id: string;\n title: string;\n company?: string;\n companyUrl?: string;\n location?: string;\n workplace?: Workplace;\n employmentType?: string;\n experienceLevel?: string;\n industries?: string[];\n functions?: string[];\n listed?: string;\n expires?: string;\n /** LISTED, CLOSED, … as LinkedIn reports it. */\n state?: string;\n applicants?: number;\n apply?: { type: 'easy-apply' | 'external'; url?: string };\n /** The employer's applicant tracking system, when LinkedIn names it. */\n ats?: string;\n applied?: boolean;\n saved?: boolean;\n description?: string;\n url: string;\n}\n\nconst WORKPLACE_URN: Record<string, Workplace> = { '1': 'on-site', '2': 'remote', '3': 'hybrid' };\n\nfunction applyOf(method: unknown, id: string): JobDetail['apply'] {\n const m = method as Node | null | undefined;\n if (m === null || m === undefined) return undefined;\n const type = String(m.$type ?? '');\n if (type.endsWith('OffsiteApply')) {\n const url = typeof m.companyApplyUrl === 'string' ? m.companyApplyUrl : undefined;\n return defined({ type: 'external' as const, url });\n }\n if (type.endsWith('OnsiteApply')) {\n // Some Easy Apply jobs carry no apply URL; the button is on the job page.\n const url = typeof m.easyApplyUrl === 'string' ? m.easyApplyUrl : viewUrl(id);\n return { type: 'easy-apply' as const, url };\n }\n return undefined;\n}\n\n/** One posting, its company and the user's own state looked up in `included`. */\nfunction postingToJob(d: Node, included: Node[]): JobDetail | undefined {\n const rawId = d.jobPostingId ?? d.entityUrn;\n const id = rawId === undefined ? undefined : jobIdOf(String(rawId));\n if (id === undefined || typeof d.title !== 'string') return undefined;\n const find = (urn: unknown) =>\n typeof urn === 'string' ? included.find((n) => n.entityUrn === urn) : undefined;\n\n const details = (d.companyDetails ?? {}) as Node;\n const company = find(details.company ?? details['*companyResolutionResult']);\n const companyName =\n typeof company?.name === 'string'\n ? company.name\n : typeof details.companyName === 'string'\n ? details.companyName\n : undefined;\n const workplaces = Array.isArray(d.workplaceTypes) ? (d.workplaceTypes as string[]) : [];\n const workplace = WORKPLACE_URN[String(workplaces[0]?.split(':').pop())];\n const applying = find(d['*applyingInfo']);\n const saving = find(d['*savingInfo']);\n const list = (v: unknown) =>\n Array.isArray(v) && v.length > 0 ? v.filter((x) => typeof x === 'string') : undefined;\n const nonEmpty = (v: unknown) => (typeof v === 'string' && v !== '' ? v : undefined);\n\n return defined({\n id,\n title: d.title,\n company: companyName,\n companyUrl: typeof company?.url === 'string' ? company.url : undefined,\n location: nonEmpty(d.formattedLocation),\n workplace: workplace ?? (d.workRemoteAllowed === true ? 'remote' : undefined),\n employmentType: nonEmpty(d.formattedEmploymentStatus),\n experienceLevel: nonEmpty(d.formattedExperienceLevel),\n industries: list(d.formattedIndustries),\n functions: list(d.formattedJobFunctions),\n listed: day(d.listedAt),\n expires: day(d.expireAt),\n state: nonEmpty(d.jobState),\n applicants: typeof d.applies === 'number' && d.applies > 0 ? d.applies : undefined,\n apply: applyOf(d.applyMethod, id),\n ats: nonEmpty(d.applicantTrackingSystem),\n applied: typeof applying?.applied === 'boolean' ? applying.applied : undefined,\n saved: typeof saving?.saved === 'boolean' ? saving.saved : undefined,\n description: text(d.description),\n url: viewUrl(id),\n });\n}\n\nexport function parseJobDetail(json: unknown): { ok: true; job: JobDetail } | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const job = root?.data === undefined ? undefined : postingToJob(root.data, root.included ?? []);\n return job === undefined ? drift('the job response carried no posting') : { ok: true, job };\n}\n\nexport interface JobBatch {\n ok: true;\n jobs: JobDetail[];\n /** Ids the batch answered with an error. */\n missing: string[];\n}\n\nexport function parseJobBatch(json: unknown): JobBatch | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const results = root?.data?.results;\n if (results === null || typeof results !== 'object')\n return drift('the batch job response carried no results');\n const included = root?.included ?? [];\n const byUrn = new Map(included.map((n) => [n.entityUrn, n]));\n const jobs: JobDetail[] = [];\n for (const ref of Object.values(results as Record<string, unknown>)) {\n const node = typeof ref === 'string' ? byUrn.get(ref) : (ref as Node);\n const job = node === undefined ? undefined : postingToJob(node, included);\n if (job !== undefined) jobs.push(job);\n }\n const claimed = Object.keys(results as object).length;\n if (claimed > 0 && jobs.length === 0)\n return drift(`the batch listed ${claimed} jobs but none could be read`);\n const errors = (root?.data?.errors ?? {}) as Record<string, unknown>;\n return { ok: true, jobs, missing: Object.keys(errors).map((k) => k.replace(/^\\*/, '')) };\n}\n\n// ─── The hiring team ──────────────────────────────────────────────────────────\n//\n// Captured 2026-10-14. The detail's own JobHiringTeam is always empty (160 jobs\n// read, 0 members); the job page draws \"Meet the hiring team\" from an SDUI\n// component instead, one POST per job. It answers `0:null` when the job shows\n// no one, and in the session's language: the degree is LinkedIn's own words.\n\nexport const HIRING_TEAM = 'com.linkedin.sdui.generated.jobseeker.dsl.impl.peopleWhoCanHelp';\nexport const HIRING_TEAM_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/component?componentId=${HIRING_TEAM}&sduiid=${HIRING_TEAM}`;\n\nexport function hiringTeamBody(jobId: string) {\n return {\n componentId: HIRING_TEAM,\n clientArguments: {\n payload: { jobId, isTwoPane: false },\n states: [],\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n screenId: 'com.linkedin.sdui.flagshipnav.jobs.JobDetails',\n knownTemplateIds: [],\n },\n };\n}\n\nexport interface HiringMember {\n name: string;\n /** Their profile id: what `profile` and messages take. */\n id?: string;\n url: string;\n headline?: string;\n /** Connection degree, as LinkedIn words it in the session's language. */\n degree?: string;\n /** \"Job poster\", when LinkedIn says so. */\n role?: string;\n verified?: boolean;\n}\n\nconst unquote = (s: string) => JSON.parse(`\"${s}\"`) as string;\n\n/** One person's card row: name, then degree (\"• 3rd\"), headline and role. */\nfunction memberOf(card: string, id: string | undefined): HiringMember | undefined {\n const url = card.match(/\"url\":\"(https:\\/\\/www\\.linkedin\\.com\\/in\\/[^\"/]+\\/)\"/)?.[1];\n const name = card.match(/\\[null,\"((?:[^\"\\\\]|\\\\.)+)\"/)?.[1];\n if (url === undefined || name === undefined) return undefined;\n const lines = [...card.matchAll(/\"children\":\\[\"((?:[^\"\\\\$]|\\\\.)(?:[^\"\\\\]|\\\\.)*)\"\\]/g)].map((m) =>\n unquote(m[1] as string).trim(),\n );\n const degree = lines.find((l) => l.startsWith('•'));\n const [headline, role] = lines.filter((l) => l !== degree && l !== '');\n return defined({\n name: unquote(name).trim(),\n id,\n url,\n headline,\n degree: degree?.replace(/^•\\s*/, ''),\n role,\n verified: /\"role\":\"img\",\"aria-label\"/.test(card) ? true : undefined,\n });\n}\n\nexport function parseHiringTeam(stream: string): { ok: true; members: HiringMember[] } | Failure {\n if (/^0:null\\s*$/.test(stream.trim())) return { ok: true, members: [] };\n if (!stream.includes('peopleWhoCanHelp'))\n return drift('the hiring team answer was not the hiring team component');\n const rows = new Rows(stream);\n const cards = [...rows.byId].filter(([, row]) => /linkedin\\.com\\\\?\\/in\\\\?\\//.test(row));\n // Each card sits beside its Message button, which names their profile id.\n const at = (card: string) => stream.indexOf(`\"$L${card}\"`);\n const placed = cards.map(([key]) => at(key)).sort((a, b) => a - b);\n const members: HiringMember[] = [];\n for (const [key, row] of cards) {\n const from = at(key);\n const to = placed.find((p) => p > from) ?? stream.length;\n const id = stream.slice(from, to).match(/recipient=([A-Za-z0-9_-]+)/)?.[1];\n const m = memberOf(row, from === -1 ? undefined : id);\n if (m !== undefined) members.push(m);\n }\n const shown = (stream.match(/screenContext=JOB_DETAILS_HIRING_TEAM/g) ?? []).length;\n if (members.length === 0 && Math.max(shown, cards.length) > 0)\n return drift(\n `${Math.max(shown, cards.length)} hiring team members were shown but none could be read`,\n );\n return { ok: true, members };\n}\n\n// ─── Filters ──────────────────────────────────────────────────────────────────\n\nexport interface JobFilter {\n /** The parameter name `--filter key=…` and selectedFilters take. */\n key: string;\n label: string;\n options: { value: string; label: string; count?: number }[];\n}\n\nexport function parseJobFilters(json: unknown): { ok: true; filters: JobFilter[] } | Failure {\n const elements = (json as { data?: { elements?: unknown } } | null)?.data?.elements;\n if (!Array.isArray(elements)) return drift('the job filter list was missing');\n const filters: JobFilter[] = [];\n for (const el of elements as Node[]) {\n const groups = [\n ...((el.secondaryFilterGroups as Node[] | undefined) ?? []),\n ...((el.primaryFilterGroups as Node[] | undefined) ?? []),\n ];\n for (const group of groups) {\n for (const f of (group.filters as Node[] | undefined) ?? []) {\n const key = f.parameterName;\n if (typeof key !== 'string' || filters.some((x) => x.key === key)) continue;\n const values = [\n ...((f.secondaryFilterValues as Node[] | undefined) ?? []),\n ...((f.primaryFilterValues as Node[] | undefined) ?? []),\n ];\n const options = values\n .filter((v) => typeof v.value === 'string')\n .map((v) =>\n defined({\n value: v.value as string,\n label:\n text(v.displayName) ??\n (typeof v.displayName === 'string' ? v.displayName : String(v.value)),\n count: typeof v.count === 'number' ? v.count : undefined,\n }),\n );\n // An option-less filter is an upsell placeholder, not a knob.\n if (options.length === 0) continue;\n filters.push({ key, label: text(f.displayName) ?? key, options });\n }\n }\n }\n if (filters.length === 0) return drift('the job filter list was empty');\n return { ok: true, filters };\n}\n\n// ─── Friendly filter names ────────────────────────────────────────────────────\n\nexport interface JobFilterOptions {\n posted?: string;\n experience?: string[];\n type?: string[];\n workplace?: string[];\n easyApply?: boolean;\n under10?: boolean;\n verified?: boolean;\n inNetwork?: boolean;\n fairChance?: boolean;\n company?: string[];\n industry?: string[];\n function?: string[];\n title?: string[];\n place?: string[];\n sort?: string;\n distance?: number;\n /** `key=v1,v2`, by LinkedIn's own parameter names, from `job-filters`. */\n raw?: string[];\n}\n\nconst NAMED: Record<string, { param: string; values: Record<string, string> }> = {\n experience: {\n param: 'experience',\n values: {\n internship: '1',\n entry: '2',\n associate: '3',\n 'mid-senior': '4',\n senior: '4',\n director: '5',\n executive: '6',\n },\n },\n type: {\n param: 'jobType',\n values: {\n 'full-time': 'F',\n 'part-time': 'P',\n contract: 'C',\n temporary: 'T',\n volunteer: 'V',\n internship: 'I',\n other: 'O',\n },\n },\n workplace: {\n param: 'workplaceType',\n values: { 'on-site': '1', onsite: '1', remote: '2', hybrid: '3' },\n },\n};\n\nconst POSTED: Record<string, number> = {\n day: 86_400,\n '24h': 86_400,\n week: 604_800,\n month: 2_592_000,\n};\n\n/** A filter value we cannot map; caught once, in `jobFilterSelection`. */\nclass Refused extends Error {}\n\nfunction postedRange(given: string): string {\n const p = given.toLowerCase();\n const n = p.match(/^(\\d+)([hd])$/);\n const seconds = POSTED[p] ?? (n ? Number(n[1]) * (n[2] === 'h' ? 3600 : 86_400) : undefined);\n if (seconds === undefined)\n throw new Refused(`--posted '${given}' is not one of: 24h, week, month, or <N>h / <N>d`);\n return `r${seconds}`;\n}\n\n/** Friendly names, or LinkedIn's own codes, onto the codes; duplicates once. */\nfunction named(name: keyof typeof NAMED, given: string[]): string[] {\n const { values } = NAMED[name] as (typeof NAMED)[string];\n const out: string[] = [];\n for (const v of given) {\n const mapped = values[v.toLowerCase()] ?? (Object.values(values).includes(v) ? v : undefined);\n if (mapped === undefined)\n throw new Refused(`--${name} '${v}' is not one of: ${Object.keys(values).join(', ')}`);\n if (!out.includes(mapped)) out.push(mapped);\n }\n return out;\n}\n\nfunction rawFilter(r: string): [string, string[]] {\n const m = r.match(/^([A-Za-z_]+)=(.+)$/);\n if (m?.[1] === undefined || m[2] === undefined)\n throw new Refused(`--filter '${r}' is not key=value[,value]`);\n const values = m[2]\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v !== '');\n return [m[1], values];\n}\n\nfunction selection(o: JobFilterOptions): Record<string, string[]> {\n const filters: Record<string, string[]> = {};\n if (o.posted !== undefined) filters.timePostedRange = [postedRange(o.posted)];\n for (const name of ['experience', 'type', 'workplace'] as const) {\n const given = o[name];\n if (given !== undefined && given.length > 0)\n filters[(NAMED[name] as (typeof NAMED)[string]).param] = named(name, given);\n }\n const flags: [boolean | undefined, string][] = [\n [o.easyApply, 'applyWithLinkedin'],\n [o.under10, 'earlyApplicant'],\n [o.verified, 'verifiedJob'],\n [o.inNetwork, 'jobInYourNetwork'],\n [o.fairChance, 'fairChanceEmployer'],\n ];\n for (const [on, param] of flags) if (on === true) filters[param] = ['true'];\n const ids: [string[] | undefined, string][] = [\n [o.company, 'company'],\n [o.industry, 'industry'],\n [o.function, 'function'],\n [o.title, 'title'],\n [o.place, 'populatedPlace'],\n ];\n for (const [given, param] of ids)\n if (given !== undefined && given.length > 0) filters[param] = given;\n if (o.sort !== undefined) {\n const sort = { recent: 'DD', relevant: 'R' }[o.sort.toLowerCase()];\n if (sort === undefined) throw new Refused(`--sort '${o.sort}' is not one of: recent, relevant`);\n filters.sortBy = [sort];\n }\n if (o.distance !== undefined) filters.distance = [String(o.distance)];\n for (const r of o.raw ?? []) {\n const [key, values] = rawFilter(r);\n filters[key] = values;\n }\n return filters;\n}\n\nexport function jobFilterSelection(\n o: JobFilterOptions,\n): { ok: true; filters: Record<string, string[]> } | Failure {\n try {\n return { ok: true, filters: selection(o) };\n } catch (e) {\n if (e instanceof Refused) return { ok: false, code: 'INVALID_INPUT', message: e.message };\n throw e;\n }\n}\n","// ─── People search ────────────────────────────────────────────────────────────\n//\n// Probed 2026-10-14. The people results page itself now renders over SDUI,\n// but the Voyager search it grew out of (`voyagerSearchDashClusters`, the\n// `search` contract) still answers with every filter the page offers, passed\n// as `queryParameters` under LinkedIn's own names:\n//\n// network F, S, O 1st, 2nd, 3rd+\n// geoUrn geo ids places\n// currentCompany company ids\n// pastCompany company ids\n// schoolFilter school ids (a school is an organisation id)\n// industry industry ids\n// profileLanguage en, de, …\n// serviceCategory service ids\n// connectionOf one profile id their connections\n// followerOf one profile id their followers\n// openToVolunteer true\n// activelyHiringForJobTitles -100 for any\n// firstName lastName title company schoolFreetext free text\n//\n// `includeFiltersInResponse:true` returns every filter with its options' ids\n// and live counts. Pages hold up to 50: asking for 100 is answered with an\n// EMPTY SUCCESS (total 0, no error), the most dangerous shape a search can\n// fail in, so 50 is a constant, not an option. LinkedIn pages at most 1000\n// people of any query, whatever it claims to have matched.\n\nimport { CONTRACTS } from './contracts.ts';\nimport { encodeVariables } from './restli.ts';\nimport type { Failure } from './sdui-form.ts';\n\n/** People per call. 100 returns an empty success; see above. */\nexport const PEOPLE_PAGE = 50;\n\ntype Node = Record<string, unknown>;\nconst text = (v: unknown): string | undefined => {\n const t = (v as { text?: unknown } | null | undefined)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim() : undefined;\n};\n\nfunction defined<T extends Record<string, unknown>>(obj: T): T {\n for (const k of Object.keys(obj)) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\nconst drift = (message: string): Failure => ({\n ok: false,\n code: 'SCHEMA_DRIFT',\n message,\n hint: 'the people search response changed shape; re-capture it',\n});\n\n// ─── The request ──────────────────────────────────────────────────────────────\n\nexport interface PeopleQuery {\n keywords?: string;\n /** queryParameters by LinkedIn's own names; resultType is added. */\n params: Record<string, string[]>;\n start: number;\n /** Ask for the filter list with this page. */\n withFilters?: boolean;\n /** Another result type: COMPANIES, SCHOOLS, GROUPS, … (see engine/search.ts). */\n kind?: string;\n /** The My Network hub's lists use their own origin and intent (engine/network.ts). */\n origin?: string;\n intent?: string;\n}\n\nexport function peopleSearchUrl(q: PeopleQuery): string {\n const c = CONTRACTS.search;\n if (c?.queryId === undefined) throw new Error(\"the 'search' contract is missing\");\n const queryParameters = [\n ...Object.entries(q.params)\n .filter(([, v]) => v.length > 0)\n .map(([key, value]) => ({ key, value })),\n { key: 'resultType', value: [q.kind ?? 'PEOPLE'] },\n ];\n const variables = encodeVariables({\n start: q.start,\n count: PEOPLE_PAGE,\n origin: q.origin ?? 'FACETED_SEARCH',\n query: {\n // An empty `keywords` is answered with a 400: none is sent then.\n keywords: q.keywords === '' ? undefined : q.keywords,\n flagshipSearchIntent: q.intent ?? 'SEARCH_SRP',\n queryParameters,\n includeFiltersInResponse: q.withFilters === true,\n },\n });\n return `${c.path}?variables=${variables}&queryId=${c.queryId}`;\n}\n\n// ─── Results ──────────────────────────────────────────────────────────────────\n\nexport type Degree = '1st' | '2nd' | '3rd+' | 'out of network';\n\nexport interface Person {\n /** The profile id: what `connectionOf`, `followerOf` and `profile` take. */\n id: string;\n name: string;\n headline?: string;\n location?: string;\n degree?: Degree;\n verified?: boolean;\n /** The line under a result: mutual connections, services offered, … */\n insight?: string;\n /** Absent for members LinkedIn will not name to this account. */\n url?: string;\n}\n\nconst DEGREE: Record<string, Degree> = {\n DISTANCE_1: '1st',\n DISTANCE_2: '2nd',\n DISTANCE_3: '3rd+',\n OUT_OF_NETWORK: 'out of network',\n};\n\nconst PROFILE_ID = /urn:li:fsd_profile:([A-Za-z0-9_-]+)/;\n\nfunction insightOf(row: Node): string | undefined {\n const all = Array.isArray(row.insightsResolutionResults)\n ? (row.insightsResolutionResults as Node[])\n : [];\n const lines = all\n .map((i) => text((i.simpleInsight as Node | null)?.title))\n .filter((t): t is string => t !== undefined);\n return text(row.summary) ?? (lines.length > 0 ? lines.join('; ') : undefined);\n}\n\n/** `/in/<vanity>/` without the tracking query; a headless search URL is no profile. */\nfunction profileUrl(nav: unknown): string | undefined {\n if (typeof nav !== 'string') return undefined;\n const m = nav.match(/^(https:\\/\\/www\\.linkedin\\.com\\/in\\/[^/?#]+)/);\n return m?.[1] === undefined ? undefined : `${m[1]}/`;\n}\n\nfunction rowToPerson(row: Node): Person | undefined {\n const id = String(row.entityUrn ?? '').match(PROFILE_ID)?.[1];\n const name = text(row.title);\n if (id === undefined || name === undefined) return undefined;\n const tracking = (row.entityCustomTrackingInfo ?? {}) as Node;\n const badge = JSON.stringify(row.badgeIcon ?? null);\n return defined({\n id,\n name,\n headline: text(row.primarySubtitle),\n location: text(row.secondarySubtitle),\n degree: DEGREE[String(tracking.memberDistance)],\n verified: badge.includes('VERIFIED') ? true : undefined,\n insight: insightOf(row),\n url: profileUrl(row.navigationUrl),\n });\n}\n\nexport interface Clusters {\n elements?: { items?: { item?: Node }[] }[];\n paging?: { total?: unknown; start?: unknown };\n metadata?: Node;\n}\n\nexport function clustersOf(json: unknown): Clusters | undefined {\n const d = (json as { data?: { data?: Node } } | null)?.data?.data;\n const c = d?.searchDashClustersByAll;\n return c !== null && typeof c === 'object' ? (c as Clusters) : undefined;\n}\n\nexport interface PeoplePage {\n ok: true;\n people: Person[];\n /** How far LinkedIn will page this query: at most 1000. */\n total?: number;\n /** LinkedIn's own count of matches, often far more than it pages. */\n claimed?: number;\n start: number;\n /** Page furniture dropped on purpose: feedback cards, empty slots. */\n excluded: number;\n unknownTypes: Record<string, number>;\n}\n\n/** Items that are page furniture, not results. */\nconst FURNITURE = new Set([\n '*feedbackCard',\n '*bannerCard',\n '*searchSuggestionCard',\n '*promoCard',\n 'simpleText',\n 'simpleTextV2',\n '*simpleText',\n]);\n\n/** What one cluster item is: a result's urn, furniture, or kinds we do not read. */\nfunction classify(item: Node | undefined): { ref: string } | 'furniture' | string[] {\n const ref = item?.['*entityResult'];\n if (typeof ref === 'string') return { ref };\n const kinds = Object.entries(item ?? {})\n .filter(([k, v]) => v !== null && !k.startsWith('$'))\n .map(([k]) => k);\n return kinds.every((k) => FURNITURE.has(k)) ? 'furniture' : kinds;\n}\n\n/**\n * The results in a page, in LinkedIn's order, each mapped by `toRow`; page\n * furniture counted apart; item kinds we do not read counted by name.\n */\nexport function readItems<T extends { id: string }>(\n c: Clusters,\n included: Node[],\n toRow: (row: Node) => T | undefined,\n) {\n const byUrn = new Map(included.map((n) => [n.entityUrn, n]));\n const people: T[] = [];\n const unknownTypes: Record<string, number> = {};\n let excluded = 0;\n let unresolved = 0;\n const items = (c.elements ?? []).flatMap((el) => el.items ?? []);\n for (const { item } of items) {\n const kind = classify(item);\n if (kind === 'furniture') {\n excluded++;\n } else if (Array.isArray(kind)) {\n for (const k of kind) unknownTypes[k] = (unknownTypes[k] ?? 0) + 1;\n } else {\n const row = byUrn.get(kind.ref);\n const person = row === undefined ? undefined : toRow(row);\n if (person === undefined) unresolved++;\n else if (!people.some((p) => p.id === person.id)) people.push(person);\n }\n }\n return { people, unknownTypes, excluded, unresolved };\n}\n\nexport function parsePeople(json: unknown): PeoplePage | Failure {\n const c = clustersOf(json);\n if (c === undefined || !Array.isArray(c.elements))\n return drift('the people search returned no result list');\n const included = (json as { included?: Node[] }).included ?? [];\n const { people, unknownTypes, excluded, unresolved } = readItems(c, included, rowToPerson);\n const total = typeof c.paging?.total === 'number' ? c.paging.total : undefined;\n const start = typeof c.paging?.start === 'number' ? c.paging.start : 0;\n const claimedRaw = c.metadata?.totalResultCount;\n const claimed = typeof claimedRaw === 'number' ? claimedRaw : total;\n\n if (unresolved > 0 && people.length === 0)\n return drift(`${unresolved} people were listed but none could be read`);\n if (people.length === 0 && total !== undefined && total > start) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `LinkedIn claims ${total} people but returned none from ${start}`,\n hint: 'a failed fetch, not an empty search; do not report \"nobody\"',\n };\n }\n return {\n ok: true,\n people,\n ...(total !== undefined ? { total } : {}),\n ...(claimed !== undefined ? { claimed } : {}),\n start,\n excluded,\n unknownTypes,\n };\n}\n\n// ─── Filters ──────────────────────────────────────────────────────────────────\n\nexport interface PeopleFilter {\n /** The parameter name `--filter key=…` takes. */\n key: string;\n label: string;\n /** select: pick option ids; text: free text. */\n input: 'select' | 'text';\n /** What a name is looked up as, when the filter takes ids LinkedIn can search for. */\n lookup?: string;\n options: { value: string; label: string; count?: number }[];\n}\n\nexport function parsePeopleFilters(json: unknown): { ok: true; filters: PeopleFilter[] } | Failure {\n const cluster = clustersOf(json)?.metadata?.primaryFilterCluster as Node | null | undefined;\n if (cluster === null || cluster === undefined)\n return drift('the people search returned no filter list');\n const groups = [\n ...((cluster.secondaryFilterGroups as Node[] | undefined) ?? []),\n ...((cluster.primaryFilterGroups as Node[] | undefined) ?? []),\n ];\n const filters: PeopleFilter[] = [];\n for (const g of groups) {\n for (const f of (g.filters as Node[] | undefined) ?? []) {\n const key = f.parameterName;\n // A navigation filter switches to another kind of search; not a knob.\n if (typeof key !== 'string' || f.renderType === 'NAVIGATION') continue;\n if (filters.some((x) => x.key === key)) continue;\n const values = [\n ...((f.secondaryFilterValues as Node[] | undefined) ?? []),\n ...((f.primaryFilterValues as Node[] | undefined) ?? []),\n ];\n filters.push(\n defined({\n key,\n label: text(f.displayName) ?? key,\n input: f.renderType === 'FREE_TEXT' ? ('text' as const) : ('select' as const),\n lookup: typeof f.typeaheadType === 'string' ? f.typeaheadType : undefined,\n options: values\n .filter((v) => typeof v.value === 'string')\n .map((v) =>\n defined({\n value: v.value as string,\n label: typeof v.displayName === 'string' ? v.displayName : String(v.value),\n count: typeof v.count === 'number' && v.count > 0 ? v.count : undefined,\n }),\n ),\n }),\n );\n }\n }\n if (filters.length === 0) return drift('the people filter list was empty');\n return { ok: true, filters };\n}\n\n// ─── Companies and schools by name ────────────────────────────────────────────\n\n/** A company or school search: each hit with the organisation id filters take. */\nexport function parseOrgHits(\n json: unknown,\n): { ok: true; hits: { id: string; name: string }[] } | Failure {\n const c = clustersOf(json);\n if (c === undefined) return drift('the organisation search returned no result list');\n const included = (json as { included?: Node[] }).included ?? [];\n const byUrn = new Map(included.map((n) => [n.entityUrn, n]));\n const hits: { id: string; name: string }[] = [];\n for (const el of c.elements ?? []) {\n for (const { item } of el.items ?? []) {\n const row = byUrn.get(item?.['*entityResult']);\n const id = String(row?.entityUrn ?? '').match(/urn:li:fsd_company:(\\d+)/)?.[1];\n const name = text(row?.title);\n if (id !== undefined && name !== undefined && !hits.some((h) => h.id === id))\n hits.push({ id, name });\n }\n }\n return { ok: true, hits };\n}\n\n// ─── Friendly filter names ────────────────────────────────────────────────────\n\nexport interface PeopleFilterOptions {\n /** 1st, 2nd, 3rd+. */\n network?: string[];\n /** Current company ids. */\n company?: string[];\n pastCompany?: string[];\n school?: string[];\n /** Geo ids. */\n geo?: string[];\n industry?: string[];\n /** Profile language codes: en, de, … */\n language?: string[];\n /** Service category ids. */\n service?: string[];\n /** A profile id or urn: their connections. */\n connectionOf?: string;\n /** A profile id or urn: their followers. */\n followerOf?: string;\n firstName?: string;\n lastName?: string;\n /** Free text matched against the current title. */\n title?: string;\n /** Free text matched against company names, current or past. */\n companyText?: string;\n schoolText?: string;\n openToVolunteer?: boolean;\n /** `key=v1,v2`, by LinkedIn's own parameter names, from `people-filters`. */\n raw?: string[];\n}\n\nconst NETWORK: Record<string, string> = {\n '1st': 'F',\n '1': 'F',\n '2nd': 'S',\n '2': 'S',\n '3rd+': 'O',\n '3rd': 'O',\n '3': 'O',\n};\n\nconst profileId = (v: string) => v.match(/^(?:urn:li:fsd_profile:)?(AC[A-Za-z0-9_-]{10,})$/)?.[1];\n\nclass Refused extends Error {}\n\nfunction selection(o: PeopleFilterOptions): Record<string, string[]> {\n const params: Record<string, string[]> = {};\n if (o.network !== undefined && o.network.length > 0) {\n params.network = o.network.map((n) => {\n const code = NETWORK[n.toLowerCase()] ?? (['F', 'S', 'O'].includes(n) ? n : undefined);\n if (code === undefined) throw new Refused(`--network '${n}' is not one of: 1st, 2nd, 3rd+`);\n return code;\n });\n }\n const ids: [string[] | undefined, string][] = [\n [o.company, 'currentCompany'],\n [o.pastCompany, 'pastCompany'],\n [o.school, 'schoolFilter'],\n [o.geo, 'geoUrn'],\n [o.industry, 'industry'],\n [o.language, 'profileLanguage'],\n [o.service, 'serviceCategory'],\n ];\n for (const [given, param] of ids)\n if (given !== undefined && given.length > 0) params[param] = given;\n for (const [given, param, flag] of [\n [o.connectionOf, 'connectionOf', '--connection-of'],\n [o.followerOf, 'followerOf', '--follower-of'],\n ] as const) {\n if (given === undefined) continue;\n const id = profileId(given.trim());\n if (id === undefined)\n throw new Refused(`${flag} takes a profile id (ACo…) or urn, from a people row's \\`id\\``);\n params[param] = [id];\n }\n const texts: [string | undefined, string][] = [\n [o.firstName, 'firstName'],\n [o.lastName, 'lastName'],\n [o.title, 'title'],\n [o.companyText, 'company'],\n [o.schoolText, 'schoolFreetext'],\n ];\n for (const [given, param] of texts)\n if (given !== undefined && given.trim() !== '') params[param] = [given.trim()];\n if (o.openToVolunteer === true) params.openToVolunteer = ['true'];\n for (const r of o.raw ?? []) {\n const m = r.match(/^([A-Za-z_]+)=(.+)$/);\n if (m?.[1] === undefined || m[2] === undefined)\n throw new Refused(`--filter '${r}' is not key=value[,value]`);\n params[m[1]] = m[2]\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v !== '');\n }\n return params;\n}\n\nexport function peopleFilterSelection(\n o: PeopleFilterOptions,\n): { ok: true; params: Record<string, string[]> } | Failure {\n try {\n return { ok: true, params: selection(o) };\n } catch (e) {\n if (e instanceof Refused) return { ok: false, code: 'INVALID_INPUT', message: e.message };\n throw e;\n }\n}\n","// ─── `lnrelay people`, `lnrelay people-filters` ───────────────────────────────\n//\n// See engine/people.ts. A people search call returns up to 50 people and\n// spends the search budget; so does each name lookup (a company or school\n// name to its id, a place to its geo id). Several keyword sets are searched\n// and merged by profile id, as `jobs` does (commands/paged.ts).\n\nimport { createLiveClient } from '../engine/index.ts';\nimport { jobSearchUrl, parseJobCards } from '../engine/jobs.ts';\nimport {\n PEOPLE_PAGE,\n type PeopleFilterOptions,\n type Person,\n parseOrgHits,\n parsePeople,\n parsePeopleFilters,\n peopleFilterSelection,\n peopleSearchUrl,\n} from '../engine/people.ts';\nimport type { Failure } from '../engine/sdui-form.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { project } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport {\n keywordSets,\n line,\n type Matched,\n metaOf,\n type PageFetch,\n type Paging,\n searchAll,\n} from './paged.ts';\n\ntype Fetched =\n | { ok: true; json: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted GET. Injectable so tests send nothing. */\nexport type PeopleFetch = (url: string, spendClass: 'search') => Promise<Fetched>;\n\nexport function liveFetch(command: string, quiet: boolean): PeopleFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err(command, 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, spendClass) => {\n const r = await client.request({ url, spendClass, operation: command });\n return r.ok ? { ok: true, json: r.json } : r;\n };\n}\n\nexport interface PeopleRequest {\n /** One keyword set, or several: each its own search, merged by profile id. */\n keywords?: string | string[];\n /** A place by name, looked up to its geo id. */\n location?: string;\n limit: number;\n start?: number;\n /** Company and school entries may be names; they are looked up to ids. */\n filter?: PeopleFilterOptions;\n}\n\n/** LinkedIn pages no further than 1000 people into any one query. */\nconst PAGING: Paging = { pageSize: PEOPLE_PAGE, max: 1000 };\n\ntype Row = Matched<Person>;\n\nfunction compactPerson(p: Row): string {\n return line([\n p.id,\n p.name,\n p.headline,\n p.location,\n p.degree,\n p.verified ? 'verified' : undefined,\n p.insight,\n p.url,\n p.matched !== undefined ? `matched: ${p.matched.join(' + ')}` : undefined,\n ]);\n}\n\nexport function shape<T extends object>(rows: T[], opts: OutputOpts, toLine: (r: T) => string) {\n if (opts.compact === true) return rows.map(toLine);\n if (opts.fields !== undefined && opts.fields !== '')\n return project(rows as unknown as Record<string, unknown>[], opts.fields);\n return rows;\n}\n\n// ─── Names to ids ─────────────────────────────────────────────────────────────\n\nexport interface Lookup {\n given: string;\n id: string;\n name: string;\n}\n\nconst isId = (v: string) => /^\\d+$/.test(v);\n\n/** Organisation names to ids, by LinkedIn's own company or school search: the top hit. */\nasync function resolveOrgs(\n get: PeopleFetch,\n given: string[] | undefined,\n kind: 'COMPANIES' | 'SCHOOLS',\n): Promise<{ ids: string[]; found: Lookup[] } | Failure | undefined> {\n if (given === undefined || given.length === 0) return undefined;\n const ids: string[] = [];\n const found: Lookup[] = [];\n for (const v of given) {\n if (isId(v)) {\n ids.push(v);\n continue;\n }\n const res = await get(peopleSearchUrl({ keywords: v, params: {}, start: 0, kind }), 'search');\n const hits = res.ok ? parseOrgHits(res.json) : res;\n if (!hits.ok) return hits;\n const top = hits.hits[0];\n if (top === undefined) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `no ${kind === 'SCHOOLS' ? 'school' : 'company'} on LinkedIn matches \"${v}\"`,\n hint: 'check the spelling, or pass its id (from `people-filters`)',\n };\n }\n ids.push(top.id);\n found.push({ given: v, id: top.id, name: top.name });\n }\n return { ids, found };\n}\n\n/** A place name to a geo id, the way the job search resolves a typed location. */\nexport async function resolvePlace(get: PeopleFetch, place: string): Promise<Lookup | Failure> {\n const res = await get(\n jobSearchUrl({ location: place, filters: {}, start: 0, count: 1 }),\n 'search',\n );\n const page = res.ok ? parseJobCards(res.json) : res;\n if (!page.ok) return page;\n if (page.location === undefined) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `LinkedIn could not place \"${place}\"`,\n hint: 'try a city, region or country, or pass --geo <id> (ids are in `people-filters`)',\n };\n }\n return { given: place, id: page.location.geoId, name: page.location.name };\n}\n\n/** Looks up every name in the request; ids pass straight through. */\nasync function resolveNames(\n get: PeopleFetch,\n req: Omit<PeopleRequest, 'limit'>,\n): Promise<{ filter: PeopleFilterOptions; resolved: Record<string, unknown> } | Failure> {\n const filter: PeopleFilterOptions = { ...(req.filter ?? {}) };\n const resolved: Record<string, unknown> = {};\n const orgs: ['company' | 'pastCompany' | 'school', 'COMPANIES' | 'SCHOOLS'][] = [\n ['company', 'COMPANIES'],\n ['pastCompany', 'COMPANIES'],\n ['school', 'SCHOOLS'],\n ];\n for (const [key, kind] of orgs) {\n const r = await resolveOrgs(get, filter[key], kind);\n if (r === undefined) continue;\n if ('ok' in r) return r;\n filter[key] = r.ids;\n if (r.found.length > 0) resolved[key] = r.found;\n }\n if (req.location !== undefined && req.location.trim() !== '') {\n const place = await resolvePlace(get, req.location.trim());\n if ('ok' in place) return place;\n filter.geo = [...(filter.geo ?? []), place.id];\n resolved.location = place;\n }\n return { filter, resolved };\n}\n\n/** Filters this tool also takes by name, and the flag that does it. */\nconst BY_NAME: Record<string, string> = {\n currentCompany: 'ids, or names via --company',\n pastCompany: 'ids, or names via --past-company',\n schoolFilter: 'ids, or names via --school',\n geoUrn: 'ids via --geo, or a place via --location',\n};\n\n// ─── Runners ──────────────────────────────────────────────────────────────────\n\nexport async function runPeople(\n req: PeopleRequest,\n opts: OutputOpts = {},\n fetch?: PeopleFetch,\n): Promise<Envelope> {\n const sets = keywordSets(req.keywords);\n const named = peopleFilterSelection(req.filter ?? {});\n if (!named.ok) return err('people', named.code, named.message, 'see `lnrelay help people`');\n const hasFilter = Object.keys(named.params).length > 0 || (req.location ?? '').trim() !== '';\n if (sets.length === 0 && !hasFilter) {\n return err(\n 'people',\n 'INVALID_INPUT',\n 'give keywords, a filter, or both',\n 'lnrelay people \"<keywords>\" [\"<more>\" ...] [--company \"<name|id>\"] [--location \"<place>\"] [filters]',\n );\n }\n const get = fetch ?? liveFetch('people', opts.quiet === true);\n if (typeof get !== 'function') return get;\n\n const names = await resolveNames(get, req);\n if ('ok' in names) return err('people', names.code, names.message, names.hint);\n const selection = peopleFilterSelection(names.filter);\n if (!selection.ok) return err('people', selection.code, selection.message);\n const params = selection.params;\n\n const first = Math.max(0, req.start ?? 0);\n const want = Math.max(1, Math.min(req.limit, PAGING.max - first));\n const fetchPage: PageFetch<Person> = async (keywords, start) => {\n const res = await get(\n peopleSearchUrl({ ...(keywords ? { keywords } : {}), params, start }),\n 'search',\n );\n const page = res.ok ? parsePeople(res.json) : res;\n if (!page.ok) return page;\n return {\n ok: true,\n items: page.people,\n ...(page.total !== undefined ? { total: page.total } : {}),\n ...(page.claimed !== undefined ? { claimed: page.claimed } : {}),\n unknownTypes: page.unknownTypes,\n };\n };\n const merged = await searchAll(\n fetchPage,\n sets.length > 0 ? sets : [undefined],\n first,\n want,\n PAGING,\n );\n if (merged.rows.length === 0 && merged.failure !== undefined) {\n const f = merged.failure;\n return err('people', f.code, f.message, f.hint);\n }\n\n const single = sets.length <= 1;\n return ok('people', {\n query: { ...(sets.length > 0 ? { keywords: single ? sets[0] : sets } : {}), params },\n ...(Object.keys(names.resolved).length > 0 ? { resolved: names.resolved } : {}),\n items: shape(merged.rows, opts, compactPerson),\n meta: metaOf('people', merged, single, first),\n });\n}\n\nexport async function runPeopleFilters(\n req: Omit<PeopleRequest, 'limit'>,\n opts: OutputOpts = {},\n fetch?: PeopleFetch,\n): Promise<Envelope> {\n const sets = keywordSets(req.keywords);\n if (sets.length > 1) {\n return err(\n 'people-filters',\n 'INVALID_INPUT',\n 'people-filters takes one keyword set: its counts belong to that one query',\n 'lnrelay people-filters \"<keywords>\" [filters]',\n );\n }\n const get = fetch ?? liveFetch('people-filters', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const names = await resolveNames(get, req);\n if ('ok' in names) return err('people-filters', names.code, names.message, names.hint);\n const selection = peopleFilterSelection(names.filter);\n if (!selection.ok) return err('people-filters', selection.code, selection.message);\n\n const url = peopleSearchUrl({\n ...(sets[0] !== undefined ? { keywords: sets[0] } : {}),\n params: selection.params,\n start: 0,\n withFilters: true,\n });\n const res = await get(url, 'search');\n const parsed = res.ok ? parsePeopleFilters(res.json) : res;\n if (!parsed.ok) return err('people-filters', parsed.code, parsed.message, parsed.hint);\n return ok('people-filters', {\n ...(Object.keys(names.resolved).length > 0 ? { resolved: names.resolved } : {}),\n items: shape(parsed.filters, opts, (f) => {\n const how = f.input === 'text' ? 'free text' : (BY_NAME[f.key] ?? 'ids');\n const options = f.options\n .map((o) => `${o.value}=${o.label}${o.count !== undefined ? ` (${o.count})` : ''}`)\n .join(', ');\n return `${f.key} [${how}]${options !== '' ? `: ${options}` : ''}`;\n }),\n meta: { state: 'complete', operation: 'people-filters', returnedCount: parsed.filters.length },\n });\n}\n","// ─── `lnrelay search posts` ───────────────────────────────────────────────────\n//\n// See engine/posts.ts. Each call returns up to 20 posts and spends the search\n// budget, as does each company given by name. The stream is heavy (about half\n// a megabyte a post), so ask for the depth you need.\n\nimport { createLiveClient } from '../engine/index.ts';\nimport { parseOrgHits, peopleSearchUrl } from '../engine/people.ts';\nimport {\n POSTS_PAGE,\n POSTS_URL,\n type PostFilter,\n type PostHit,\n parsePosts,\n postsPagerBody,\n} from '../engine/posts.ts';\nimport type { Failure } from '../engine/sdui-form.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport {\n keywordSets,\n line,\n type Matched,\n metaOf,\n type PageFetch,\n type Paging,\n searchAll,\n} from './paged.ts';\nimport { type Lookup, shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; raw: string; json?: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted call: the pager when a body is given, a GET otherwise. Injectable for tests. */\nexport type PostsFetch = (url: string, body: unknown, spendClass: 'search') => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): PostsFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('search posts', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, body, spendClass) => {\n const r = await client.request({\n url,\n ...(body !== undefined ? { method: 'POST' as const, body } : {}),\n spendClass,\n operation: 'search-posts',\n });\n if (!r.ok) return r;\n return { ok: true, raw: (r.classification as { raw?: string }).raw ?? '', json: r.json };\n };\n}\n\nexport interface PostsRequest {\n keywords?: string | string[];\n limit: number;\n start?: number;\n /** recent | relevant */\n sort?: string;\n /** 24h | week | month */\n posted?: string;\n /** videos, images, jobs, live, articles, documents */\n type?: string[];\n /** 1st, me */\n postedBy?: string[];\n /** Profile ids. */\n from?: string[];\n mentions?: string[];\n /** Company names or ids. */\n fromCompany?: string[];\n mentionsCompany?: string[];\n authorCompany?: string[];\n authorIndustry?: string[];\n authorTitle?: string;\n /** `key=v1,v2`, by the pager's own names. */\n raw?: string[];\n}\n\n/** LinkedIn's posts pager: no total is given, so paging ends on an empty or short page. */\nconst PAGING: Paging = { pageSize: POSTS_PAGE, max: 1000 };\n\nconst CHOICES: Record<string, { param: PostFilter; values: Record<string, string> }> = {\n sort: { param: 'sortBy', values: { recent: 'date_posted', relevant: 'relevance' } },\n posted: {\n param: 'datePosted',\n values: { '24h': 'past-24h', day: 'past-24h', week: 'past-week', month: 'past-month' },\n },\n type: {\n param: 'contentType',\n values: {\n videos: 'videos',\n images: 'photos',\n photos: 'photos',\n jobs: 'jobs',\n live: 'liveVideos',\n articles: 'articles',\n documents: 'documents',\n },\n },\n postedBy: { param: 'postedBy', values: { '1st': 'first', me: 'me', first: 'first' } },\n};\n\ntype Refusal = { ok: false; code: string; message: string; hint?: string };\n\nfunction choose(name: keyof typeof CHOICES, given: string[]): string[] | Refusal {\n const { values } = CHOICES[name] as (typeof CHOICES)[string];\n const out: string[] = [];\n for (const g of given) {\n const v = values[g.toLowerCase()];\n if (v === undefined)\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `--${name} '${g}' is not one of: ${Object.keys(values).join(', ')}`,\n };\n out.push(v);\n }\n return out;\n}\n\n/** Company names to ids by LinkedIn's company search: the top hit, reported. */\nasync function companies(\n get: PostsFetch,\n given: string[],\n): Promise<{ ids: string[]; found: Lookup[] } | Failure> {\n const ids: string[] = [];\n const found: Lookup[] = [];\n for (const v of given) {\n if (/^\\d+$/.test(v)) {\n ids.push(v);\n continue;\n }\n const res = await get(\n peopleSearchUrl({ keywords: v, params: {}, start: 0, kind: 'COMPANIES' }),\n undefined,\n 'search',\n );\n const hits = res.ok ? parseOrgHits(res.json) : res;\n if (!hits.ok) return hits;\n const top = hits.hits[0];\n if (top === undefined)\n return { ok: false, code: 'INVALID_INPUT', message: `no company on LinkedIn matches \"${v}\"` };\n ids.push(top.id);\n found.push({ given: v, id: top.id, name: top.name });\n }\n return { ids, found };\n}\n\nfunction choices(req: PostsRequest): Partial<Record<PostFilter, string[]>> | Refusal {\n const filters: Partial<Record<PostFilter, string[]>> = {};\n const picks: [keyof typeof CHOICES, string[] | undefined][] = [\n ['sort', req.sort !== undefined ? [req.sort] : undefined],\n ['posted', req.posted !== undefined ? [req.posted] : undefined],\n ['type', req.type],\n ['postedBy', req.postedBy],\n ];\n for (const [name, given] of picks) {\n if (given === undefined || given.length === 0) continue;\n const v = choose(name, given);\n if (!Array.isArray(v)) return v;\n filters[(CHOICES[name] as (typeof CHOICES)[string]).param] = v;\n }\n if (req.from !== undefined && req.from.length > 0) filters.fromMember = req.from;\n if (req.mentions !== undefined && req.mentions.length > 0) filters.mentionsMember = req.mentions;\n if (req.authorIndustry !== undefined && req.authorIndustry.length > 0)\n filters.authorIndustry = req.authorIndustry;\n if (req.authorTitle !== undefined && req.authorTitle.trim() !== '')\n filters.authorJobTitle = [req.authorTitle.trim()];\n for (const r of req.raw ?? []) {\n const m = r.match(/^([A-Za-z_]+)=(.+)$/);\n if (m?.[1] === undefined || m[2] === undefined)\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `--filter '${r}' is not key=value[,value]`,\n };\n filters[m[1] as PostFilter] = m[2]\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v !== '');\n }\n return filters;\n}\n\n/** The request as pager filters; company names are looked up. */\nasync function filtersOf(req: PostsRequest, get: PostsFetch) {\n const filters = choices(req);\n if ('ok' in filters) return filters;\n const resolved: Record<string, Lookup[]> = {};\n const orgs: [keyof PostsRequest, PostFilter][] = [\n ['fromCompany', 'fromOrganization'],\n ['mentionsCompany', 'mentionsOrganization'],\n ['authorCompany', 'authorCompany'],\n ];\n for (const [key, param] of orgs) {\n const given = req[key] as string[] | undefined;\n if (given === undefined || given.length === 0) continue;\n const r = await companies(get, given);\n if ('ok' in r) return r;\n filters[param] = r.ids;\n if (r.found.length > 0) resolved[key] = r.found;\n }\n return { filters, resolved };\n}\n\nfunction compactPost(p: Matched<PostHit>): string {\n const counts = [\n p.reactions !== undefined ? `${p.reactions} reactions` : undefined,\n p.comments !== undefined ? `${p.comments} comments` : undefined,\n p.reposts !== undefined ? `${p.reposts} reposts` : undefined,\n ].filter(Boolean);\n const text = p.text?.replace(/\\s+/g, ' ');\n return line([\n p.id,\n p.author,\n p.posted,\n counts.length > 0 ? counts.join(' · ') : undefined,\n text !== undefined && text.length > 160 ? `${text.slice(0, 157)}…` : text,\n p.url,\n p.matched !== undefined ? `matched: ${p.matched.join(' + ')}` : undefined,\n ]);\n}\n\nexport async function runPostsSearch(\n req: PostsRequest,\n opts: OutputOpts = {},\n fetch?: PostsFetch,\n): Promise<Envelope> {\n const command = 'search posts';\n const sets = keywordSets(req.keywords);\n const early = choices(req);\n if ('ok' in early) return err(command, early.code, early.message, early.hint);\n const anyFilter =\n Object.keys(early).length > 0 ||\n [req.fromCompany, req.mentionsCompany, req.authorCompany].some((v) => (v?.length ?? 0) > 0);\n if (sets.length === 0 && !anyFilter)\n return err(\n command,\n 'INVALID_INPUT',\n 'give keywords, a filter, or both',\n 'lnrelay search posts \"<keywords>\"',\n );\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n const f = await filtersOf(req, get);\n if ('ok' in f) return err(command, f.code, f.message, f.hint);\n\n const first = Math.max(0, req.start ?? 0);\n const want = Math.max(1, Math.min(req.limit, PAGING.max - first));\n const fetchPage: PageFetch<PostHit> = async (keywords, start) => {\n const body = postsPagerBody({ ...(keywords ? { keywords } : {}), filters: f.filters, start });\n const res = await get(POSTS_URL, body, 'search');\n const page = res.ok ? parsePosts(res.raw) : res;\n if (!page.ok) return page;\n const cards = page.posts.length + page.unread;\n const unknownTypes: Record<string, number> =\n page.unread > 0 ? { unreadPostCards: page.unread } : {};\n return {\n ok: true,\n items: page.posts,\n // No total is given: a short page is the last.\n ...(cards < POSTS_PAGE ? { total: start + cards } : {}),\n unknownTypes,\n };\n };\n const merged = await searchAll(\n fetchPage,\n sets.length > 0 ? sets : [undefined],\n first,\n want,\n PAGING,\n );\n if (merged.rows.length === 0 && merged.failure !== undefined) {\n const fail = merged.failure;\n return err(command, fail.code, fail.message, fail.hint);\n }\n const single = sets.length <= 1;\n return ok('search', {\n kind: 'posts',\n query: {\n ...(sets.length > 0 ? { keywords: single ? sets[0] : sets } : {}),\n filters: f.filters,\n },\n ...(Object.keys(f.resolved).length > 0 ? { resolved: f.resolved } : {}),\n items: shape(merged.rows, opts, compactPost),\n meta: metaOf(command, merged, single, first),\n });\n}\n","// ─── `lnrelay company <name|url|id> [...] [--posts N]` ────────────────────────\n//\n// A company page in full; see engine/company.ts. Each company is one page\n// call. `--posts N` adds its newest posts: the posts search, filtered to posts\n// from the company and sorted by date, on the search budget.\n\nimport { type Company, companyRefOf, companyUrl, parseCompany } from '../engine/company.ts';\nimport { createLiveClient } from '../engine/index.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { shape } from './people.ts';\nimport { runPostsSearch } from './posts-search.ts';\n\ntype Fetched =\n | { ok: true; raw: string; json?: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted call: a POST when a body is given, a GET otherwise. Injectable for tests. */\nexport type CompanyFetch = (\n url: string,\n body: unknown,\n spendClass: 'page' | 'search',\n) => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): CompanyFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('company', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, body, spendClass) => {\n const r = await client.request({\n url,\n ...(body !== undefined ? { method: 'POST' as const, body } : {}),\n spendClass,\n operation: 'company',\n });\n if (!r.ok) return r;\n return { ok: true, raw: (r.classification as { raw?: string }).raw ?? '', json: r.json };\n };\n}\n\nexport interface CompanyRequest {\n /** Add this many of the company's newest posts. */\n posts?: number;\n}\n\ntype Read = Company & { posts?: unknown[]; postsError?: string };\n\nfunction compactCompany(c: Read): string {\n return line([\n c.id,\n c.name,\n c.industry,\n c.size,\n c.employeesOnLinkedIn !== undefined ? `${c.employeesOnLinkedIn} on LinkedIn` : undefined,\n c.followers !== undefined ? `${c.followers} followers` : undefined,\n c.headquarters,\n c.website,\n c.url,\n ]);\n}\n\n/** Its newest posts onto the company; a failure says why on the company. */\nasync function addPosts(get: CompanyFetch, c: Read, n: number, opts: OutputOpts) {\n const r = await runPostsSearch(\n { fromCompany: [c.id], sort: 'recent', limit: n },\n opts.compact === true ? { compact: true } : {},\n (url, body) => get(url, body, 'search'),\n );\n if (r.ok) c.posts = (r.data as { items: unknown[] }).items;\n else c.postsError = `${r.error.code}: ${r.error.message}`;\n}\n\ntype Outcome =\n | { ok: true; company: Read }\n | { ok: false; code: string; message: string; hint?: string };\n\nasync function readOne(\n get: CompanyFetch,\n input: string,\n req: CompanyRequest,\n opts: OutputOpts,\n): Promise<Outcome> {\n const ref = companyRefOf(input) as NonNullable<ReturnType<typeof companyRefOf>>;\n const res = await get(companyUrl(ref), undefined, 'page');\n const parsed = res.ok ? parseCompany(res.json) : res;\n if (!parsed.ok) return parsed;\n const company: Read = parsed.company;\n if (req.posts !== undefined && req.posts > 0) await addPosts(get, company, req.posts, opts);\n return { ok: true, company };\n}\n\nexport async function runCompany(\n inputs: string[],\n req: CompanyRequest = {},\n opts: OutputOpts = {},\n fetch?: CompanyFetch,\n): Promise<Envelope> {\n const given = [...new Set(inputs.map((i) => i.trim()).filter((i) => i !== ''))];\n const bad = given.filter((g) => companyRefOf(g) === undefined);\n if (given.length === 0 || bad.length > 0)\n return err(\n 'company',\n 'INVALID_INPUT',\n bad.length > 0 ? `not a company: ${bad.join(', ')}` : 'a company is required',\n 'lnrelay company <universal-name|company-url|id> [...] [--posts N]',\n );\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n\n if (given.length === 1) {\n const one = await readOne(get, given[0] as string, req, opts);\n return one.ok ? ok('company', one.company) : err('company', one.code, one.message, one.hint);\n }\n const companies: Read[] = [];\n const unread: { company: string; code: string; message: string }[] = [];\n for (const g of given) {\n const one = await readOne(get, g, req, opts);\n // A name and an id can be the same company: it is listed once.\n if (one.ok && !companies.some((c) => c.id === one.company.id)) companies.push(one.company);\n else if (!one.ok) unread.push({ company: g, code: one.code, message: one.message });\n }\n if (companies.length === 0)\n return err('company', unread[0]?.code ?? 'FETCH_FAILED', 'no company could be read');\n return ok('company', {\n items: shape(companies, opts, compactCompany),\n meta: {\n state: unread.length === 0 ? 'complete' : 'partial',\n operation: 'company',\n returnedCount: companies.length,\n ...(unread.length > 0 ? { unread } : {}),\n },\n });\n}\n","// ─── Events: the events hub, and one event in full ────────────────────────────\n//\n// Captured 2026-10-14. Searching events by keyword is `search events`\n// (engine/search.ts). This adds the two things the events page itself has:\n//\n// the hub an SDUI component, `eventsHomeCardGroupsSection`: the Premium\n// LinkedIn Live events and \"recommended for you\", as cards\n// an event `voyagerEventsDashProfessionalEvents` by event id: times and\n// time zone, state, place or online, attendees, organiser,\n// description, the event's own site\n//\n// A hub card's own rows hold, in order: when, the organiser (not on LinkedIn\n// Live cards), the attendee line, the title. Labels come in the viewer's\n// LinkedIn language, so a card is read by that order and by shape (a clock\n// time; a number then a word), never by the words. Following a card's\n// references would run into the next card's rows; the walk stops there.\n\nimport { CONTRACTS } from './contracts.ts';\nimport { Rows } from './posts.ts';\nimport { encodeVariables } from './restli.ts';\nimport type { Failure } from './sdui-form.ts';\n\nexport const EVENTS_HUB = 'com.linkedin.sdui.generated.events.dsl.impl.eventsHomeCardGroupsSection';\nexport const EVENTS_HUB_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/component?componentId=${EVENTS_HUB}&sduiid=${EVENTS_HUB}`;\n\nexport function eventsHubBody() {\n return {\n componentId: EVENTS_HUB,\n clientArguments: { states: [], screenId: '', knownTemplateIds: [] },\n };\n}\n\n/** An event id from itself, an /events/ URL (the id ends its vanity name), or a urn. */\nexport function eventIdOf(input: string): string | undefined {\n const s = input.trim();\n return (\n s.match(/^(\\d{15,20})$/)?.[1] ??\n s.match(/\\/events\\/[a-z0-9-]*?(\\d{15,20})/)?.[1] ??\n s.match(/(?:fsd_professionalEvent|event):(\\d{15,20})/)?.[1]\n );\n}\n\nconst eventLink = (id: string) => `https://www.linkedin.com/events/${id}/`;\n\n// ─── The hub ──────────────────────────────────────────────────────────────────\n\nexport interface HubEvent {\n id: string;\n name: string;\n /** As the card shows it, in the viewer's language. */\n when?: string;\n organizer?: string;\n attendees?: number;\n /** A LinkedIn Live event in the Premium section. */\n premium: boolean;\n url: string;\n}\n\nconst CARD = /\"viewName\":\"event-(large|small)-card-container\"/;\nconst TIME = /\\d{1,2}:\\d{2}/;\nconst COUNT = /^(\\d[\\d,.\\s]*)\\s+\\S+$/;\n\nfunction texts(row: string): string[] {\n return [...row.matchAll(/\"children\":\\[\"((?:[^\"\\\\$]|\\\\.)(?:[^\"\\\\]|\\\\.)*)\"\\]/g)].map(\n (m) => JSON.parse(`\"${m[1]}\"`) as string,\n );\n}\n\n/** A card's rows: its own, and what it references, stopping at any other card. */\nfunction cardRows(rows: Rows, id: string): string[] {\n const seen = new Set([id]);\n const queue = [id];\n while (queue.length > 0 && seen.size < 40) {\n const row = rows.byId.get(queue.shift() as string) ?? '';\n for (const m of row.matchAll(/\"\\$L?([0-9a-f]+)(?::[^\"]*)?\"/g)) {\n const ref = m[1] as string;\n const next = rows.byId.get(ref);\n if (seen.has(ref) || next === undefined || CARD.test(next)) continue;\n seen.add(ref);\n queue.push(ref);\n }\n }\n return [...seen];\n}\n\nconst count = (t: string | undefined) =>\n t === undefined ? undefined : Number(t.match(COUNT)?.[1]?.replace(/[,.\\s]/g, ''));\n\nfunction cardToEvent(rows: Rows, id: string, premium: boolean): HubEvent | undefined {\n const all = cardRows(rows, id)\n .map((r) => rows.byId.get(r) ?? '')\n .join('\\n');\n const ids = [\n ...new Set([...all.matchAll(/\\/events\\/[a-z0-9-]*?(\\d{15,20})/g)].map((m) => m[1] as string)),\n ];\n if (ids.length !== 1) return undefined;\n const t = texts(all);\n const at = t.findIndex((x) => TIME.test(x));\n const n = t.findIndex((x, i) => i > at && COUNT.test(x));\n const name = n === -1 ? undefined : t[n + 1];\n if (at === -1 || name === undefined) return undefined;\n // Between the time and the count: the organiser, and separators like \"•\".\n const organizer = t.slice(at + 1, n).find((x) => /\\p{L}/u.test(x));\n const attendees = count(t[n]);\n return {\n id: ids[0] as string,\n name: name.trim(),\n when: t[at],\n ...(organizer !== undefined ? { organizer } : {}),\n ...(attendees !== undefined && Number.isFinite(attendees) ? { attendees } : {}),\n premium,\n url: eventLink(ids[0] as string),\n };\n}\n\nexport function parseEventsHub(\n stream: string,\n): { ok: true; events: HubEvent[]; used: Set<string> } | Failure {\n if (\n !stream.includes('event-large-card-container') &&\n !stream.includes('event-small-card-container')\n ) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the events page carried no event cards',\n hint: 're-capture the events hub',\n };\n }\n const rows = new Rows(stream);\n const events: HubEvent[] = [];\n const used = new Set<string>();\n let unread = 0;\n for (const m of stream.matchAll(new RegExp(CARD.source, 'g'))) {\n const id = rows.at(m.index ?? 0);\n if (id === undefined) continue;\n for (const r of cardRows(rows, id)) used.add(r);\n const e = cardToEvent(rows, id, m[1] === 'small');\n if (e === undefined) unread++;\n else if (!events.some((x) => x.id === e.id)) events.push(e);\n }\n if (events.length === 0)\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `${unread} event cards were shown but none could be read`,\n };\n return { ok: true, events, used };\n}\n\n// ─── One event ────────────────────────────────────────────────────────────────\n\nexport function eventUrl(id: string): string {\n const c = CONTRACTS.professionalEvent;\n if (c?.queryId === undefined) throw new Error(\"the 'professionalEvent' contract is missing\");\n const variables = encodeVariables({\n eventIdentifier: id,\n includeComments: false,\n includeCommentsFirstReply: false,\n });\n return `${c.path}?variables=${variables}&queryId=${c.queryId}`;\n}\n\nexport interface EventDetail {\n id: string;\n name: string;\n /** As LinkedIn shows it, in the viewer's time zone. */\n when?: string;\n start?: string;\n end?: string;\n timeZone?: string;\n /** FUTURE, ONGOING, PAST, as LinkedIn reports it. */\n state?: string;\n cancelled?: boolean;\n attendees?: number;\n organizer?: { name: string; kind: 'company' | 'person'; url?: string };\n online: boolean;\n /** City, region, country for an event in person. */\n place?: string;\n /** The event's own site or registration page. */\n site?: string;\n private?: boolean;\n premium?: boolean;\n /** The viewer's own response (ATTENDING, …); absent when they have given none. */\n you?: string;\n description?: string;\n url: string;\n}\n\ntype Node = Record<string, unknown>;\n/** A TextViewModel's string, at either nesting depth (`socialProof.text.text`). */\nconst txt = (v: unknown): string | undefined => {\n const t = (v as { text?: unknown } | null | undefined)?.text;\n if (t !== null && typeof t === 'object') return txt(t);\n return typeof t === 'string' && t.trim() !== '' ? t.trim() : undefined;\n};\n\nfunction organizerOf(e: Node, byUrn: Map<unknown, Node>): EventDetail['organizer'] {\n const o = (e.organizer ?? {}) as Node;\n const company = byUrn.get(o['*organizingCompanyUrn']);\n if (typeof company?.name === 'string') {\n const id = String(company.entityUrn).split(':').pop();\n return { name: company.name, kind: 'company', url: `https://www.linkedin.com/company/${id}/` };\n }\n const person = byUrn.get(o['*organizingProfileUrn'] ?? o.organizingProfileUrn);\n const name = [person?.firstName, person?.lastName].filter((x) => typeof x === 'string').join(' ');\n if (name !== '') {\n const vanity = person?.publicIdentifier;\n return {\n name,\n kind: 'person',\n ...(typeof vanity === 'string' ? { url: `https://www.linkedin.com/in/${vanity}/` } : {}),\n };\n }\n return undefined;\n}\n\nexport function parseEvent(json: unknown): { ok: true; event: EventDetail } | Failure {\n const included = (json as { included?: Node[] } | null)?.included ?? [];\n const e = included.find((n) => String(n.$type).endsWith('.ProfessionalEvent'));\n const id = e === undefined ? undefined : eventIdOf(String(e.entityUrn));\n if (e === undefined || id === undefined || typeof e.name !== 'string') {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the event response carried no event',\n hint: 're-capture the event page',\n };\n }\n const byUrn = new Map<unknown, Node>(included.map((n) => [n.entityUrn, n]));\n const range = (e.timeRange ?? {}) as { start?: unknown; end?: unknown };\n const address = (e.address ?? null) as Node | null;\n const place =\n address === null\n ? undefined\n : [address.city, address.geographicArea, address.country]\n .filter((x) => typeof x === 'string' && x !== '')\n .join(', ');\n const status = byUrn.get(e['*viewerStatus'])?.scheduledContentViewerStatus;\n const attendees = Number(\n txt(e.socialProof)\n ?.match(/^(\\d[\\d,.\\s]*)/)?.[1]\n ?.replace(/[,.\\s]/g, ''),\n );\n const out: EventDetail = {\n id,\n name: e.name,\n online: typeof e.broadcastTool === 'string' || (address === null && e.venueDetails === null),\n url: eventLink(id),\n };\n const set = <K extends keyof EventDetail>(k: K, v: EventDetail[K] | undefined) => {\n if (v !== undefined && v !== '') out[k] = v;\n };\n set(\n 'when',\n typeof e.displayEventTime === 'string' ? e.displayEventTime.replace(/\\n/g, ' – ') : undefined,\n );\n set('start', typeof range.start === 'number' ? new Date(range.start).toISOString() : undefined);\n set('end', typeof range.end === 'number' ? new Date(range.end).toISOString() : undefined);\n set('timeZone', typeof e.timeZone === 'string' ? e.timeZone : undefined);\n set('state', typeof e.lifecycleState === 'string' ? e.lifecycleState : undefined);\n if (e.cancelled === true) out.cancelled = true;\n set('attendees', Number.isFinite(attendees) ? attendees : undefined);\n set('organizer', organizerOf(e, byUrn));\n set('place', place);\n set('site', typeof e.externalUrl === 'string' ? e.externalUrl : undefined);\n if (e.privateEvent === true) out.private = true;\n if (e.premiumEvent === true) out.premium = true;\n // NOT_INTERESTED is LinkedIn's default for no response at all, not a \"no\".\n set('you', typeof status === 'string' && status !== 'NOT_INTERESTED' ? status : undefined);\n set('description', txt(e.description));\n return { ok: true, event: out };\n}\n","// ─── `lnrelay events` and `lnrelay event` ─────────────────────────────────────\n//\n// The events page's own lists, and one event in full; see engine/events.ts.\n// Searching events by keyword is `search events`. Everything spends the page\n// budget: the hub is one call, each event one call.\n\nimport {\n EVENTS_HUB_URL,\n type EventDetail,\n eventIdOf,\n eventsHubBody,\n eventUrl,\n type HubEvent,\n parseEvent,\n parseEventsHub,\n} from '../engine/events.ts';\nimport { createLiveClient } from '../engine/index.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; raw: string; json?: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted call: a POST when a body is given, a GET otherwise. Injectable for tests. */\nexport type EventsFetch = (url: string, body: unknown, spendClass: 'page') => Promise<Fetched>;\n\nfunction liveFetch(command: string, quiet: boolean): EventsFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err(command, 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, body, spendClass) => {\n const r = await client.request({\n url,\n ...(body !== undefined ? { method: 'POST' as const, body } : {}),\n spendClass,\n operation: command,\n });\n if (!r.ok) return r;\n return { ok: true, raw: (r.classification as { raw?: string }).raw ?? '', json: r.json };\n };\n}\n\nexport interface EventsRequest {\n limit: number;\n /** Only the Premium (LinkedIn Live) events. */\n premium?: boolean;\n}\n\nfunction compactEvent(e: HubEvent): string {\n return line([\n e.id,\n e.name,\n e.when,\n e.organizer,\n e.attendees !== undefined ? `${e.attendees} attendees` : undefined,\n e.premium ? 'Premium' : undefined,\n e.url,\n ]);\n}\n\nexport async function runEvents(\n req: EventsRequest,\n opts: OutputOpts = {},\n fetch?: EventsFetch,\n): Promise<Envelope> {\n const get = fetch ?? liveFetch('events', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const res = await get(EVENTS_HUB_URL, eventsHubBody(), 'page');\n const hub = res.ok ? parseEventsHub(res.raw) : res;\n if (!hub.ok) return err('events', hub.code, hub.message, hub.hint);\n const picked = hub.events.filter((e) => req.premium !== true || e.premium);\n const items = picked.slice(0, Math.max(1, req.limit));\n return ok('events', {\n items: shape(items, opts, compactEvent),\n meta: {\n // The hub is one page LinkedIn chose; it has no \"more\".\n state: 'complete',\n operation: 'events',\n returnedCount: items.length,\n shownCount: hub.events.length,\n },\n });\n}\n\nfunction compactDetail(e: EventDetail): string {\n return line([\n e.id,\n e.name,\n e.when,\n e.online ? 'online' : e.place,\n e.organizer?.name,\n e.attendees !== undefined ? `${e.attendees} attendees` : undefined,\n e.state,\n e.site ?? e.url,\n ]);\n}\n\nexport async function runEvent(\n inputs: string[],\n opts: OutputOpts = {},\n fetch?: EventsFetch,\n): Promise<Envelope> {\n const ids = inputs.map(eventIdOf);\n if (ids.length === 0 || ids.some((id) => id === undefined)) {\n const bad = inputs.filter((i) => eventIdOf(i) === undefined);\n return err(\n 'event',\n 'INVALID_INPUT',\n bad.length > 0\n ? `not an event id or URL: ${bad.join(', ')}`\n : 'an event id or URL is required',\n 'lnrelay event <id|url> [<id|url> ...]',\n );\n }\n const get = fetch ?? liveFetch('event', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const events: EventDetail[] = [];\n for (const id of [...new Set(ids as string[])]) {\n const res = await get(eventUrl(id), undefined, 'page');\n const parsed = res.ok ? parseEvent(res.json) : res;\n if (!parsed.ok) {\n if (events.length === 0) return err('event', parsed.code, parsed.message, parsed.hint);\n return ok('event', {\n items: shape(events, opts, compactDetail),\n meta: {\n state: 'partial',\n operation: 'event',\n returnedCount: events.length,\n stoppedBy: parsed.code,\n },\n });\n }\n events.push(parsed.event);\n }\n if (events.length === 1 && opts.compact !== true && opts.fields === undefined)\n return ok('event', events[0]);\n return ok('event', {\n items: shape(events, opts, compactDetail),\n meta: { state: 'complete', operation: 'event', returnedCount: events.length },\n });\n}\n","// ─── What Premium adds to jobs ────────────────────────────────────────────────\n//\n// Captured 2026-11-22 on a Premium account. Both are Voyager GraphQL, plain\n// JSON, and both are read by the classic job pages:\n//\n// collection voyagerJobsDashJobCards, by `jobCollectionSlug`. The\n// /jobs/collections/<slug>/ pages. `top-applicant` (jobs where\n// you would be a top applicant) is Premium's; it answered 83\n// jobs, all of them in one call of 100. The cards are job\n// search's, under `jobCard` instead of `jobCardUnion`.\n// `recommended` answered none, as it does in the browser; a\n// slug LinkedIn does not know answers a GraphQL error.\n// insights voyagerJobsDashJobPostingDetailSections, the detail pane's\n// cards by type. JOB_APPLICANT_INSIGHTS: how many applied, in\n// the last day, their seniority and education.\n// COMPANY_INSIGHTS_CARD: headcount by month over two years, for\n// the company and for the job's function, median tenure,\n// competitors, and LinkedIn's generated text on its hiring,\n// priorities and landscape. Both ride one call.\n//\n// The REST job search takes a `jobCollectionSlug` too and ignores it: it\n// answered 241 jobs where the collection holds 83. Not used.\n//\n// Two more are not Voyager:\n//\n// hear back \"Jobs where you're more likely to hear back\", the jobs home's\n// Premium list, is the new job search page with\n// origin=QUALIFICATION_LANDING: POST flagship-web/jobs/\n// search-results/?…&start=N, answered as page data only with\n// `x-li-rsc-stream: true` (the HTML page otherwise, ignoring\n// start). 25 cards a page, each `job-card-component-ref-<id>`;\n// their text is deep in markup, so the ids are read and the jobs\n// then read in full. Keywords and place change nothing: 84 jobs\n// in four pages, the last short.\n// match \"Show match details\" asks LinkedIn's AI assistant. The job's\n// howYouFitGuide component links the question (in the session's\n// language) and the assistant's context; voyagerGuideDashMessage\n// (`action=execute`) sends it, the answer is streamed elsewhere,\n// and the conversation's messages (voyagerGuideDashBionicMessageV2)\n// hold it once `finalComponentPosition` is set: about 4 seconds.\n// Asking adds the exchange to the user's assistant history.\n\nimport { CONTRACTS } from './contracts.ts';\nimport { type JobPage, parseJobCards } from './jobs.ts';\nimport type { Failure } from './sdui-form.ts';\n\nfunction graphql(name: 'jobCollection' | 'jobDetailSections' | 'guideMessage' | 'guideMessages') {\n const c = CONTRACTS[name];\n if (c?.queryId === undefined) throw new Error(`job contract '${name}' is missing`);\n return { path: c.path, queryId: c.queryId };\n}\n\n/** Jobs per collection call: the server serves 100 (2026-11-22). */\nexport const COLLECTION_PAGE = 100;\n\n/** The collections a command takes, by LinkedIn's slug. */\nexport const COLLECTIONS = ['top-applicant', 'hear-back'] as const;\nexport type Collection = (typeof COLLECTIONS)[number];\n\nexport function jobCollectionUrl(slug: 'top-applicant', start: number, count: number): string {\n const c = graphql('jobCollection');\n const variables = `(count:${count},jobCollectionSlug:${slug},query:(origin:GENERIC_JOB_COLLECTIONS_LANDING),start:${start})`;\n return `${c.path}?variables=${variables}&queryId=${c.queryId}`;\n}\n\nexport function jobInsightsUrl(id: string): string {\n const c = graphql('jobDetailSections');\n const urn = encodeURIComponent(`urn:li:fsd_jobPosting:${id}`);\n const variables = `(cardSectionTypes:List(JOB_APPLICANT_INSIGHTS,COMPANY_INSIGHTS_CARD),jobPostingUrn:${urn},includeSecondaryActionsV2:true)`;\n return `${c.path}?includeWebMetadata=true&variables=${variables}&queryId=${c.queryId}`;\n}\n\ntype Node = Record<string, unknown>;\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst text = (v: unknown): string | undefined => {\n const t = (v as { text?: unknown } | null | undefined)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim() : undefined;\n};\nconst nodes = (v: unknown): Node[] => (Array.isArray(v) ? (v as Node[]) : []);\nfunction defined<T extends Record<string, unknown>>(obj: T): T {\n for (const k of Object.keys(obj)) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\n// ─── Collection ───────────────────────────────────────────────────────────────\n\nexport function parseJobCollection(json: unknown): JobPage | Failure {\n const root = json as { data?: { data?: Node; errors?: unknown[] }; included?: Node[] } | null;\n const collection = root?.data?.data?.jobsDashJobCardsByJobCollections;\n if (collection === undefined || collection === null) {\n const why = nodes(root?.data?.errors)[0]?.message;\n return drift(`the job collection was not served${typeof why === 'string' ? `: ${why}` : ''}`);\n }\n return parseJobCards({ data: collection, included: root?.included ?? [] });\n}\n\n// ─── Insights ─────────────────────────────────────────────────────────────────\n\nexport interface ApplicantInsights {\n /** Who clicked apply. */\n total: number;\n lastDay?: number;\n seniority?: { level: string; share: number; count?: number }[];\n education?: { degree: string; share: number }[];\n /** Where you rank among them, when LinkedIn says. */\n rankPercentile?: number;\n /** Passed through as LinkedIn sends them: seen empty so far. */\n skills?: unknown[];\n locations?: unknown[];\n}\n\nexport interface Headcount {\n /** The latest month, YYYY-MM. */\n asOf: string;\n now: number;\n sixMonthsAgo?: number;\n yearAgo?: number;\n twoYearsAgo?: number;\n /** Change over the year, in percent. */\n growth1y?: number;\n}\n\nexport interface CompanyInsights {\n name?: string;\n url?: string;\n headcount?: Headcount;\n /** The job's own function at the company: its name and headcount. */\n function?: { name: string } & Partial<Headcount>;\n medianTenure?: string;\n competitors?: { name: string; industry?: string; url?: string }[];\n /** LinkedIn's generated text: hiring and headcount by function. */\n hiring?: string;\n /** LinkedIn's generated text: the company's strategic priorities. */\n priorities?: string;\n /** LinkedIn's generated text: its competitive landscape. */\n landscape?: string;\n}\n\nexport interface JobInsights {\n ok: true;\n applicants?: ApplicantInsights;\n company?: CompanyInsights;\n /** Company insight sections we do not read, by name. */\n unknownSections: Record<string, number>;\n}\n\nfunction byUrn(included: Node[]): Map<string, Node> {\n const map = new Map<string, Node>();\n for (const n of included) if (typeof n.entityUrn === 'string') map.set(n.entityUrn, n);\n return map;\n}\n\nconst nameOf = (urns: Map<string, Node>, urn: unknown) => {\n const n = typeof urn === 'string' ? urns.get(urn)?.name : undefined;\n return typeof n === 'string' ? n : undefined;\n};\n\nfunction applicantsOf(a: Node, urns: Map<string, Node>): ApplicantInsights {\n const seniority = nodes(a.seniorityDetails).flatMap((s) => {\n const level = nameOf(urns, s['*seniority']);\n return level === undefined || typeof s.percentage !== 'number'\n ? []\n : [defined({ level, share: s.percentage, count: s.count as number | undefined })];\n });\n const education = nodes(a.degreeDetails).flatMap((d) => {\n const degree = nameOf(urns, d['*degree']);\n return degree === undefined || typeof d.percentage !== 'number'\n ? []\n : [{ degree, share: d.percentage }];\n });\n const skills = nodes(a.skillDetails);\n const locations = nodes(a.locationDetails);\n return defined({\n total: a.applicantCount as number,\n lastDay: typeof a.applicantsInPastDay === 'number' ? a.applicantsInPastDay : undefined,\n seniority: seniority.length > 0 ? seniority : undefined,\n education: education.length > 0 ? education : undefined,\n rankPercentile:\n typeof a.applicantRankPercentile === 'number' ? a.applicantRankPercentile : undefined,\n skills: skills.length > 0 ? skills : undefined,\n locations: locations.length > 0 ? locations : undefined,\n });\n}\n\n/** Newest month first, as LinkedIn lists it: now, 6 and 12 and 24 months back. */\nfunction headcountOf(growth: unknown): Headcount | undefined {\n const months = nodes((growth as Node | null | undefined)?.headcountGrowth).flatMap((m) => {\n const on = m.startedOn as { year?: number; month?: number } | undefined;\n return typeof m.employeeCount === 'number' && on?.year !== undefined && on.month !== undefined\n ? [{ month: `${on.year}-${String(on.month).padStart(2, '0')}`, count: m.employeeCount }]\n : [];\n });\n const latest = months[0];\n if (latest === undefined) return undefined;\n const back = (n: number) => months[n]?.count;\n const yearAgo = back(12);\n return defined({\n asOf: latest.month,\n now: latest.count,\n sixMonthsAgo: back(6),\n yearAgo,\n twoYearsAgo: back(24),\n growth1y:\n yearAgo !== undefined && yearAgo > 0\n ? Math.round(((latest.count - yearAgo) / yearAgo) * 1000) / 10\n : undefined,\n });\n}\n\nconst str = (v: unknown) => (typeof v === 'string' ? v : undefined);\n\nfunction trendOf(s: Node, urns: Map<string, Node>): CompanyInsights {\n const company = urns.get(String(s['*company']));\n const fn = str(s.formattedJobFunction);\n return defined({\n name: str(company?.name),\n url: str(company?.url),\n headcount: headcountOf(s.employeeGrowth),\n function:\n fn !== undefined ? { name: fn, ...headcountOf(s.employeeGrowthForFunction) } : undefined,\n medianTenure: text((s.employeeGrowth as Node | undefined)?.medianTenureYears),\n });\n}\n\nfunction landscapeOf(s: Node): CompanyInsights {\n const competitors = nodes(s.competitors).flatMap((c) => {\n const name = text(c.title);\n return name === undefined\n ? []\n : [defined({ name, industry: text(c.subtitle), url: str(c.navigationUrl) })];\n });\n return defined({\n landscape: text(s.aiqInsightsText),\n competitors: competitors.length > 0 ? competitors : undefined,\n });\n}\n\n/** Each section we read, into the company's insights. Any other is counted, never dropped silently. */\nconst SECTIONS: Record<string, (s: Node, urns: Map<string, Node>) => CompanyInsights> = {\n jobPostingCompanyInsights: trendOf,\n headcountAIQInsights: (s) => defined({ hiring: text(s.aiqInsightsText) }),\n strategicPrioritiesAIQInsights: (s) => defined({ priorities: text(s.insightsText) }),\n competitiveLandscapeAIQInsights: landscapeOf,\n};\n\nfunction companyOf(card: Node, urns: Map<string, Node>, unknown: Record<string, number>) {\n const out: CompanyInsights = {};\n for (const el of nodes(card.elements)) {\n for (const [kind, section] of Object.entries((el.companyInsights ?? {}) as Node)) {\n if (section === null || kind.startsWith('$')) continue;\n const read = SECTIONS[kind];\n if (read === undefined) unknown[kind] = (unknown[kind] ?? 0) + 1;\n else Object.assign(out, read(section as Node, urns));\n }\n }\n return out;\n}\n\nexport function parseJobInsights(json: unknown): JobInsights | Failure {\n const root = json as { data?: { data?: Node }; included?: Node[] } | null;\n const sections = root?.data?.data?.jobsDashJobPostingDetailSectionsByCardSectionTypes as\n | Node\n | undefined;\n if (sections === undefined || sections === null || !Array.isArray(sections.elements))\n return drift('the job detail sections were not in the answer');\n const urns = byUrn(root?.included ?? []);\n const unknownSections: Record<string, number> = {};\n let applicants: ApplicantInsights | undefined;\n let company: CompanyInsights | undefined;\n for (const el of nodes(sections.elements)) {\n for (const part of nodes(el.jobPostingDetailSection)) {\n const a = urns.get(String(part['*jobApplicantInsightsUrn']));\n if (a !== undefined && typeof a.applicantCount === 'number')\n applicants = applicantsOf(a, urns);\n const posting = urns.get(String(part['*companyInsightsCard']));\n const card = posting?.companyInsightsCard as Node | undefined;\n if (card !== undefined && card !== null) company = companyOf(card, urns, unknownSections);\n }\n }\n return {\n ok: true,\n ...(applicants !== undefined ? { applicants } : {}),\n ...(company !== undefined && Object.keys(company).length > 0 ? { company } : {}),\n unknownSections,\n };\n}\n\n// ─── Hear back ────────────────────────────────────────────────────────────────\n\nexport const HEAR_BACK_PAGE = 25;\nconst SEARCH_RESULTS = 'https://www.linkedin.com/flagship-web/jobs/search-results/';\nexport const HEAR_BACK_HEADERS = {\n 'x-li-rsc-stream': 'true',\n referer: 'https://www.linkedin.com/jobs/',\n} as const;\n\nexport function hearBackUrl(start: number): string {\n return `${SEARCH_RESULTS}?showHowYouFit=HOW_YOU_FIT&origin=QUALIFICATION_LANDING&start=${start}`;\n}\n\nexport function hearBackBody() {\n return {\n requestedArguments: {\n payload: {\n showHowYouFit: 'HOW_YOU_FIT',\n shouldHideLoadingSpinner: true,\n origin: 'JobSearchOrigin_QUALIFICATION_LANDING',\n },\n states: [],\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n screenId: 'com.linkedin.sdui.flagshipnav.jobs.SemanticJobDetails',\n knownTemplateIds: [],\n },\n };\n}\n\n/** The job ids a results page lists, in order, each once. */\nexport function parseJobIds(stream: string): { ok: true; ids: string[] } | Failure {\n if (/^\\s*</.test(stream)) return drift('LinkedIn answered the page, not its data');\n const ids = [...stream.matchAll(/job-card-component-ref-(\\d+)/g)].map((m) => m[1] as string);\n return { ok: true, ids: [...new Set(ids)] };\n}\n\n// ─── Match ────────────────────────────────────────────────────────────────────\n\nconst HOW_YOU_FIT = 'com.linkedin.sdui.generated.jobseeker.dsl.impl.howYouFitGuide';\nexport const HOW_YOU_FIT_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/component?componentId=${HOW_YOU_FIT}&sduiid=${HOW_YOU_FIT}`;\n\nexport function howYouFitBody(jobId: string) {\n const key = `jdpApplyState_${jobId}`;\n return {\n componentId: HOW_YOU_FIT,\n clientArguments: {\n payload: { jobId, isPremium: true, applyState: { key, namespace: 'MemoryNamespace' } },\n states: [\n {\n key,\n namespace: 'MemoryNamespace',\n value: 'Initial',\n originalProtoCase: 'stringValue',\n protoKey: { $type: 'proto.sdui.Key', value: { $case: 'id', id: key } },\n },\n ],\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n screenId: 'com.linkedin.sdui.flagshipnav.jobs.SemanticJobDetails',\n knownTemplateIds: [],\n },\n };\n}\n\nexport interface MatchLink {\n /** The question, in the session's language. */\n query: string;\n intent: string;\n mailbox: string;\n contextUrns: string[];\n customContext: { key: string; value: string }[];\n}\n\nconst FIT = 'JobSeekerAgentIntent_JOB_FIT_EXPLANATION';\n\n/** The job's \"Show match details\" link, found by its sub-intent, not its words. */\nexport function parseMatchLink(\n stream: string,\n jobId: string,\n): { ok: true; link: MatchLink } | Failure {\n for (const m of stream.matchAll(/\"url\":\"(\\/preload\\/guideOverlay\\/\\?[^\"]*)\"/g)) {\n const q = new URL(`https://www.linkedin.com${m[1]}`).searchParams;\n const customContext = (q.get('customContext') ?? '').split(',').flatMap((pair) => {\n const at = pair.indexOf('~:');\n return at === -1 ? [] : [{ key: pair.slice(0, at), value: pair.slice(at + 2) }];\n });\n const sub = customContext.find((c) => c.key === 'subIntent')?.value;\n const job = customContext.find((c) => c.key === 'jobPostingId')?.value;\n const query = q.get('query');\n const mailbox = q.get('originalThreadMailbox');\n if (sub !== FIT || job !== jobId || query === null || mailbox === null) continue;\n return {\n ok: true,\n link: {\n query,\n intent: q.get('intent') ?? 'GuideIntent_JOB_SEEKING_AGENT',\n mailbox,\n contextUrns: (q.get('contextUrns') ?? '').split(',').filter((u) => u !== ''),\n customContext,\n },\n };\n }\n return {\n ok: false,\n code: 'NOT_FOUND',\n message: 'the job offers no match details (Premium only, and not on every job)',\n };\n}\n\n/** 16 random bytes as a string, as the overlay makes its ids. */\nconst randomId = () => String.fromCharCode(...crypto.getRandomValues(new Uint8Array(16)));\n\nexport function matchMessageUrl(): string {\n const c = graphql('guideMessage');\n return `${c.path}?action=execute&queryId=${c.queryId}`;\n}\n\nexport function matchMessageBody(\n link: MatchLink,\n jobId: string,\n ids: { interaction: string; session: string } = { interaction: randomId(), session: randomId() },\n) {\n const c = graphql('guideMessage');\n return {\n variables: {\n guideInteractionId: ids.interaction,\n guideQueryContext: {\n customContext: link.customContext,\n intent: link.intent,\n pageContext: {\n origin: '',\n companyUrns: null,\n profileUrns: null,\n jobPostingUrns: [`urn:li:fsd_jobPosting:${jobId}`],\n },\n contextUrns: link.contextUrns,\n originalIntent: link.intent,\n originalThreadMailbox: link.mailbox,\n isZeroState: false,\n },\n guideSessionId: ids.session,\n query: link.query,\n },\n queryId: c.queryId,\n includeWebMetadata: true,\n };\n}\n\nexport function parseMatchSent(\n json: unknown,\n): { ok: true; conversation: string; response: string } | Failure {\n const root = json as { data?: { data?: Node; errors?: unknown[] }; included?: Node[] } | null;\n const message = nodes(root?.included).find(\n (n) => typeof n.conversationV2Urn === 'string' && (n.content as Node | null)?.['*aiResponse'],\n );\n const conversation = message?.conversationV2Urn;\n const response = (message?.content as Node | undefined)?.['*aiResponse'];\n if (typeof conversation !== 'string' || typeof response !== 'string') {\n const why = nodes(root?.data?.errors)[0]?.message;\n return drift(\n `the assistant did not take the question${typeof why === 'string' ? `: ${why}` : ''}`,\n );\n }\n return { ok: true, conversation, response };\n}\n\nexport function matchAnswerUrl(conversation: string): string {\n const c = graphql('guideMessages');\n const urn = encodeURIComponent(conversation);\n return `${c.path}?includeWebMetadata=true&variables=(guideConversationV2Urn:${urn},syncToken:null)&queryId=${c.queryId}`;\n}\n\nexport interface Match {\n /** The verdict line (\"Job match is low\"), in the session's language. */\n summary?: string;\n /** Required qualifications met (✓) and not (?), as the assistant words them. */\n met: string[];\n missing: string[];\n /** The rest of the answer, one paragraph a line. */\n text: string;\n}\n\ntype Attribute = { start?: number; length?: number; detailData?: Node };\n\nfunction matchOf(t: { text: string; attributesV2?: Attribute[] }): Match {\n const spans = (style: string) =>\n (t.attributesV2 ?? [])\n .filter((a) => a.detailData?.style === style)\n .map((a) => t.text.slice(a.start ?? 0, (a.start ?? 0) + (a.length ?? 0)).trim());\n const first = (t.attributesV2 ?? [])[0];\n const lines = spans('PARAGRAPH').filter((l) => l !== '');\n const marked = (mark: string) =>\n lines.filter((l) => l.startsWith(mark)).map((l) => l.slice(mark.length).trim());\n return defined({\n summary:\n first?.detailData?.style === 'BOLD' && first.start === 0 ? spans('BOLD')[0] : undefined,\n met: marked('✓'),\n missing: marked('?'),\n text: lines.join('\\n'),\n }) as Match;\n}\n\nexport function parseMatchAnswer(\n json: unknown,\n response: string,\n): { ok: true; done: false } | { ok: true; done: true; match: Match } | Failure {\n const root = json as { included?: Node[] } | null;\n if (!Array.isArray(root?.included)) return drift('the conversation came back without messages');\n const answer = root.included.find((n) => n.entityUrn === response);\n const streaming = ((answer?.responseV2 as Node | undefined)?.streamingResponse ?? {}) as Node;\n if (typeof streaming.finalComponentPosition !== 'number') return { ok: true, done: false };\n for (const part of nodes(streaming.responseComponent)) {\n const t = ((part.component as Node | undefined)?.aiResponse as Node | undefined)?.text as\n | { text?: unknown; attributesV2?: Attribute[] }\n | undefined;\n if (typeof t?.text === 'string')\n return { ok: true, done: true, match: matchOf(t as { text: string }) };\n }\n return drift('the assistant finished without a written answer');\n}\n","// ─── `lnrelay jobs`, `lnrelay job`, `lnrelay job-filters` ─────────────────────\n//\n// See engine/jobs.ts. A search call returns up to 100 jobs and spends the\n// job-search budget; a read returns up to 100 jobs in full (a batch get) and\n// spends the job-read budget. `--details` is opt-in because full descriptions\n// are large: search wide with cards, then read the finalists. `job --team`\n// adds each job's hiring team, one page call per job.\n//\n// Premium (engine/job-premium.ts): `jobs --top-applicant` lists the jobs\n// where LinkedIn says you would be a top applicant, and `job --insights` adds\n// who applied and the company's insights, one more job read per job.\n\nimport { createLiveClient } from '../engine/index.ts';\nimport {\n COLLECTION_PAGE,\n type Collection,\n HEAR_BACK_HEADERS,\n HEAR_BACK_PAGE,\n HOW_YOU_FIT_URL,\n hearBackBody,\n hearBackUrl,\n howYouFitBody,\n type JobInsights,\n jobCollectionUrl,\n jobInsightsUrl,\n type Match,\n matchAnswerUrl,\n matchMessageBody,\n matchMessageUrl,\n parseJobCollection,\n parseJobIds,\n parseJobInsights,\n parseMatchAnswer,\n parseMatchLink,\n parseMatchSent,\n} from '../engine/job-premium.ts';\nimport {\n BATCH_SIZE,\n HIRING_TEAM_URL,\n type HiringMember,\n hiringTeamBody,\n type JobCard,\n type JobDetail,\n type JobFilterOptions,\n type JobQuery,\n jobBatchUrl,\n jobDetailUrl,\n jobFilterSelection,\n jobFiltersUrl,\n jobIdOf,\n jobSearchUrl,\n PAGE_SIZE,\n parseHiringTeam,\n parseJobBatch,\n parseJobCards,\n parseJobDetail,\n parseJobFilters,\n} from '../engine/jobs.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { project } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport {\n keywordSets,\n line,\n type Matched,\n metaOf,\n type PageFetch,\n type Paging,\n searchAll,\n} from './paged.ts';\n\ntype Fetched =\n | { ok: true; json?: unknown; raw?: string }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted call: a POST when a body is given. Injectable so tests send nothing. */\nexport type JobsFetch = (\n url: string,\n spendClass: 'jobSearch' | 'jobRead' | 'page',\n body?: unknown,\n headers?: Record<string, string>,\n) => Promise<Fetched>;\n\nfunction liveFetch(command: string, quiet: boolean): JobsFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err(command, 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, spendClass, body, headers) => {\n const r = await client.request({\n url,\n ...(body !== undefined ? { method: 'POST' as const, body } : {}),\n ...(headers !== undefined ? { headers } : {}),\n spendClass,\n operation: command,\n });\n if (!r.ok) return r;\n return { ok: true, json: r.json, raw: (r.classification as { raw?: string }).raw ?? '' };\n };\n}\n\nexport interface JobsRequest {\n /** One keyword set, or several: each its own search, merged by job id. */\n keywords?: string | string[];\n location?: string;\n geoId?: string;\n limit: number;\n start?: number;\n /** Read each job too: apply link, applicants, employment type. */\n details?: boolean;\n /** With `details`, keep each job's full description. */\n description?: boolean;\n filter?: JobFilterOptions;\n /** A Premium collection instead of a search: it takes no keywords or filters. */\n collection?: Collection;\n}\n\n/** LinkedIn serves no further than 1000 into any one job search. */\nconst PAGING: Paging = { pageSize: PAGE_SIZE, max: 1000 };\n\ninterface Teamed {\n hiringTeam?: HiringMember[];\n /** Why the team could not be read; the job itself was. */\n hiringTeamError?: string;\n /** Premium (`--insights`): who applied, and the company's insights. */\n premium?: Omit<JobInsights, 'ok' | 'unknownSections'> & {\n unknownSections?: Record<string, number>;\n };\n premiumError?: string;\n /** Premium (`--match`): LinkedIn's AI assessment of the user against the job. */\n match?: Match;\n matchError?: string;\n}\n\ntype Row = Matched<JobCard & Partial<Omit<JobDetail, keyof JobCard>>> & Teamed;\n\nconst teamLine = (team: HiringMember[] | undefined) =>\n team === undefined || team.length === 0\n ? undefined\n : `team: ${team\n .map((m) =>\n [m.name, m.role !== undefined ? `(${m.role})` : undefined, m.url]\n .filter(Boolean)\n .join(' '),\n )\n .join('; ')}`;\n\nfunction compactJob(j: Row): string {\n return line([\n j.id,\n j.title,\n j.company,\n j.location,\n j.workplace,\n j.listed,\n j.easyApply ? 'easy apply' : undefined,\n j.promoted ? 'promoted' : undefined,\n j.salary,\n j.apply?.url !== undefined ? `apply: ${j.apply.url}` : undefined,\n j.matched !== undefined ? `matched: ${j.matched.join(' + ')}` : undefined,\n teamLine(j.hiringTeam),\n ]);\n}\n\nfunction shape<T extends object>(rows: T[], opts: OutputOpts, line: (r: T) => string) {\n if (opts.compact === true) return rows.map(line);\n if (opts.fields !== undefined && opts.fields !== '')\n return project(rows as unknown as Record<string, unknown>[], opts.fields);\n return rows;\n}\n\ntype Query = Omit<JobQuery, 'start' | 'count'>;\n\nfunction queryOf(\n req: Omit<JobsRequest, 'limit' | 'keywords'>,\n filters: Record<string, string[]>,\n keywords?: string,\n): Query {\n return {\n ...(keywords ? { keywords } : {}),\n ...(req.location ? { location: req.location } : {}),\n ...(req.geoId ? { geoId: req.geoId } : {}),\n filters,\n };\n}\n\n/** Reads `ids` in batches. Stops at the first failed batch, keeping the rest. */\nasync function readJobs(\n get: JobsFetch,\n ids: string[],\n): Promise<{ jobs: Map<string, JobDetail>; stoppedBy?: string }> {\n const jobs = new Map<string, JobDetail>();\n for (let at = 0; at < ids.length; at += BATCH_SIZE) {\n const res = await get(jobBatchUrl(ids.slice(at, at + BATCH_SIZE)), 'jobRead');\n const batch = res.ok ? parseJobBatch(res.json) : res;\n if (!batch.ok) return { jobs, stoppedBy: batch.code };\n for (const job of batch.jobs) if (ids.includes(job.id)) jobs.set(job.id, job);\n }\n return { jobs };\n}\n\n/** Reads every row in full and merges it in. Returns how many stayed unread. */\nasync function addDetails(\n get: JobsFetch,\n rows: Row[],\n withDescription: boolean,\n): Promise<{ unread: number; stoppedBy?: string }> {\n const read = await readJobs(\n get,\n rows.map((r) => r.id),\n );\n for (const row of rows) {\n const detail = read.jobs.get(row.id);\n if (detail === undefined) continue;\n const { description, id: _id, url: _url, ...rest } = detail;\n Object.assign(row, rest, withDescription ? { description } : {});\n }\n const unread = rows.filter((r) => !read.jobs.has(r.id)).length;\n return read.stoppedBy === undefined ? { unread } : { unread, stoppedBy: read.stoppedBy };\n}\n\nexport async function runJobs(\n req: JobsRequest,\n opts: OutputOpts = {},\n fetch?: JobsFetch,\n): Promise<Envelope> {\n if (req.collection !== undefined) {\n const misuse = collectionMisuse(req, req.collection);\n if (misuse !== null) return misuse;\n return req.collection === 'hear-back'\n ? runHearBack(req, opts, fetch)\n : runCollection(req, req.collection, opts, fetch);\n }\n const sets = keywordSets(req.keywords);\n const hasQuery =\n sets.length > 0 || [req.location, req.geoId].some((v) => v !== undefined && v !== '');\n if (!hasQuery) {\n return err(\n 'jobs',\n 'INVALID_INPUT',\n 'give keywords, a location, or both',\n 'lnrelay jobs \"<keywords>\" [\"<more keywords>\" ...] [--location \"<place>\" | --geo <id>] [filters]',\n );\n }\n const selection = jobFilterSelection(req.filter ?? {});\n if (!selection.ok)\n return err('jobs', selection.code, selection.message, 'see `lnrelay help jobs`');\n const get = fetch ?? liveFetch('jobs', opts.quiet === true);\n if (typeof get !== 'function') return get;\n\n const first = Math.max(0, req.start ?? 0);\n const want = Math.max(1, Math.min(req.limit, PAGING.max - first));\n const base = queryOf(req, selection.filters);\n const fetchPage: PageFetch<JobCard> = async (keywords, start) => {\n const url = jobSearchUrl({\n ...base,\n ...(keywords ? { keywords } : {}),\n start,\n count: PAGE_SIZE,\n });\n const res = await get(url, 'jobSearch');\n const page = res.ok ? parseJobCards(res.json) : res;\n if (!page.ok) return page;\n return {\n ok: true,\n items: page.jobs,\n ...(page.total !== undefined ? { total: page.total } : {}),\n ...(page.location !== undefined ? { resolved: page.location } : {}),\n unknownTypes: page.unknownTypes,\n };\n };\n const merged = await searchAll(\n fetchPage,\n sets.length > 0 ? sets : [undefined],\n first,\n want,\n PAGING,\n );\n if (merged.rows.length === 0 && merged.failure !== undefined) {\n const f = merged.failure;\n return err('jobs', f.code, f.message, f.hint);\n }\n\n let unread = 0;\n let readStop: string | undefined;\n if (req.details === true) {\n const added = await addDetails(get, merged.rows, req.description === true);\n unread = added.unread;\n readStop = added.stoppedBy;\n }\n\n const single = sets.length <= 1;\n const meta = metaOf('jobs', merged, single, first, {\n unread,\n ...(readStop !== undefined ? { readStop } : {}),\n });\n\n return ok('jobs', {\n query: { ...base, ...(sets.length > 0 ? { keywords: single ? sets[0] : sets } : {}) },\n ...(merged.resolved !== undefined ? { location: merged.resolved } : {}),\n items: shape(merged.rows as Row[], opts, compactJob),\n meta,\n });\n}\n\n/** A collection is LinkedIn's own list: keywords, a place or filters would be ignored. */\nfunction collectionMisuse(req: JobsRequest, collection: Collection): Envelope | null {\n const searched = keywordSets(req.keywords).length > 0 || req.location || req.geoId;\n const selection = jobFilterSelection(req.filter ?? {});\n const filtered = !selection.ok || Object.keys(selection.filters).length > 0;\n return searched || filtered\n ? err(\n 'jobs',\n 'INVALID_INPUT',\n `--${collection} is LinkedIn's own list: it takes no keywords, location or filters`,\n )\n : null;\n}\n\n/** The ids of the hear-back list, 25 a page, until a short page or `upTo`. */\nasync function hearBackIds(get: JobsFetch, upTo: number) {\n const ids: string[] = [];\n for (let start = 0; start < PAGING.max; start += HEAR_BACK_PAGE) {\n const res = await get(hearBackUrl(start), 'jobSearch', hearBackBody(), {\n ...HEAR_BACK_HEADERS,\n });\n const page = res.ok ? parseJobIds(res.raw ?? '') : res;\n if (!page.ok) return { ids, ended: false, failure: page };\n const fresh = page.ids.filter((id) => !ids.includes(id));\n ids.push(...fresh);\n if (page.ids.length < HEAR_BACK_PAGE || fresh.length === 0) return { ids, ended: true };\n if (ids.length >= upTo) return { ids, ended: false };\n }\n return { ids, ended: false };\n}\n\n/** \"Jobs where you're more likely to hear back\": the list's ids, then the jobs in full. */\nasync function runHearBack(\n req: JobsRequest,\n opts: OutputOpts,\n fetch?: JobsFetch,\n): Promise<Envelope> {\n const get = fetch ?? liveFetch('jobs', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const first = Math.max(0, req.start ?? 0);\n const want = Math.max(1, Math.min(req.limit, PAGING.max - first));\n const listed = await hearBackIds(get, first + want);\n if (listed.ids.length === 0 && listed.failure !== undefined) {\n const f = listed.failure;\n return err('jobs', f.code, f.message, f.hint);\n }\n const slice = listed.ids.slice(first, first + want);\n const read = await readJobs(get, slice);\n const rows: (JobDetail & Teamed)[] = slice.flatMap((id) => read.jobs.get(id) ?? []);\n const unread = slice.filter((id) => !read.jobs.has(id));\n const whole = listed.ended && first + want >= listed.ids.length;\n return ok('jobs', {\n collection: 'hear-back',\n items: shape(rows, opts, (j) =>\n compactJob({ ...j, easyApply: j.apply?.type === 'easy-apply', promoted: false }),\n ),\n meta: {\n state: whole && unread.length === 0 ? 'complete' : 'partial',\n operation: 'jobs',\n ...(listed.ended ? { claimedCount: listed.ids.length } : {}),\n returnedCount: rows.length,\n start: first,\n ...(unread.length > 0 ? { unread } : {}),\n ...(listed.failure !== undefined ? { stoppedBy: listed.failure.code } : {}),\n ...(read.stoppedBy !== undefined ? { readStop: read.stoppedBy } : {}),\n },\n });\n}\n\n/** A Premium collection, 100 a call, the cards job search returns. */\nasync function runCollection(\n req: JobsRequest,\n collection: 'top-applicant',\n opts: OutputOpts,\n fetch?: JobsFetch,\n): Promise<Envelope> {\n const get = fetch ?? liveFetch('jobs', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const first = Math.max(0, req.start ?? 0);\n const want = Math.max(1, Math.min(req.limit, PAGING.max - first));\n const fetchPage: PageFetch<JobCard> = async (_keywords, start) => {\n const res = await get(jobCollectionUrl(collection, start, COLLECTION_PAGE), 'jobSearch');\n const page = res.ok ? parseJobCollection(res.json) : res;\n if (!page.ok) return page;\n return {\n ok: true,\n items: page.jobs,\n ...(page.total !== undefined ? { total: page.total } : {}),\n unknownTypes: page.unknownTypes,\n };\n };\n const merged = await searchAll(fetchPage, [undefined], first, want, PAGING);\n if (merged.rows.length === 0 && merged.failure !== undefined) {\n const f = merged.failure;\n return err('jobs', f.code, f.message, f.hint);\n }\n let extra = {};\n if (req.details === true) {\n const added = await addDetails(get, merged.rows, req.description === true);\n extra = {\n unread: added.unread,\n ...(added.stoppedBy !== undefined ? { readStop: added.stoppedBy } : {}),\n };\n }\n return ok('jobs', {\n collection,\n items: shape(merged.rows as Row[], opts, compactJob),\n meta: metaOf('jobs', merged, true, first, { unread: 0, ...extra }),\n });\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/** Polls for the assistant's answer this many times, `pollMs` apart. */\nconst MATCH_POLLS = 8;\n\n/** Ask the assistant for one job's match and wait for its answer. */\nasync function matchFor(\n get: JobsFetch,\n jobId: string,\n pollMs: number,\n): Promise<{ ok: true; match: Match } | { ok: false; code: string; message: string }> {\n const linked = await get(HOW_YOU_FIT_URL, 'page', howYouFitBody(jobId));\n const link = linked.ok ? parseMatchLink(linked.raw ?? '', jobId) : linked;\n if (!link.ok) return link;\n const sentRes = await get(matchMessageUrl(), 'page', matchMessageBody(link.link, jobId));\n const sent = sentRes.ok ? parseMatchSent(sentRes.json) : sentRes;\n if (!sent.ok) return sent;\n for (let i = 0; i < MATCH_POLLS; i++) {\n await sleep(pollMs);\n const res = await get(matchAnswerUrl(sent.conversation), 'page');\n const answer = res.ok ? parseMatchAnswer(res.json, sent.response) : res;\n if (!answer.ok) return answer;\n if (answer.done) return { ok: true, match: answer.match };\n }\n return {\n ok: false,\n code: 'TIMEOUT',\n message: `the assistant had not finished after ${MATCH_POLLS} looks; it may still be in its history`,\n };\n}\n\nasync function addMatches(\n get: JobsFetch,\n jobs: (JobDetail & Teamed)[],\n pollMs: number,\n): Promise<void> {\n for (const job of jobs) {\n const r = await matchFor(get, job.id, pollMs);\n if (r.ok) job.match = r.match;\n else job.matchError = `${r.code}: ${r.message}`;\n }\n}\n\n/** Each job's Premium insights, one job read each; a failed one says why. */\nasync function addInsights(get: JobsFetch, jobs: (JobDetail & Teamed)[]): Promise<void> {\n for (const job of jobs) {\n const res = await get(jobInsightsUrl(job.id), 'jobRead');\n const read = res.ok ? parseJobInsights(res.json) : res;\n if (!read.ok) {\n job.premiumError = `${read.code}: ${read.message}`;\n continue;\n }\n const { ok: _ok, unknownSections, ...insights } = read;\n job.premium = {\n ...insights,\n ...(Object.keys(unknownSections).length > 0 ? { unknownSections } : {}),\n };\n }\n}\n\n/** Each job's hiring team, one call each, onto the job; a failed one says why. */\nasync function addTeams(get: JobsFetch, jobs: (JobDetail & Teamed)[]): Promise<void> {\n for (const job of jobs) {\n const res = await get(HIRING_TEAM_URL, 'page', hiringTeamBody(job.id));\n const team = res.ok ? parseHiringTeam(res.raw ?? '') : res;\n if (team.ok) job.hiringTeam = team.members;\n else job.hiringTeamError = `${team.code}: ${team.message}`;\n }\n}\n\ntype JobExtras = { team?: boolean; insights?: boolean; match?: boolean; pollMs?: number };\n\n/** What `job` adds on request: the hiring team, Premium insights, the AI match. */\nasync function enrich(get: JobsFetch, jobs: (JobDetail & Teamed)[], req: JobExtras) {\n if (req.team === true) await addTeams(get, jobs);\n if (req.insights === true) await addInsights(get, jobs);\n if (req.match === true) await addMatches(get, jobs, req.pollMs ?? 4000);\n}\n\n/** One job by its own endpoint; several in batches of 100, one call each. */\nexport async function runJob(\n input: string | string[] | undefined,\n opts: OutputOpts = {},\n fetch?: JobsFetch,\n req: JobExtras = {},\n): Promise<Envelope> {\n const given = input === undefined ? [] : Array.isArray(input) ? input : [input];\n const ids = [...new Set(given.map(jobIdOf))];\n if (ids.length === 0 || ids.some((id) => id === undefined)) {\n const bad = given.filter((g) => jobIdOf(g) === undefined);\n return err(\n 'job',\n 'INVALID_INPUT',\n bad.length > 0 ? `not a job id or URL: ${bad.join(', ')}` : 'a job id or job URL is required',\n 'lnrelay job <id|url> [<id|url> ...]',\n );\n }\n const get = fetch ?? liveFetch('job', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const wanted = ids as string[];\n\n if (wanted.length === 1) {\n const res = await get(jobDetailUrl(wanted[0] as string), 'jobRead');\n if (!res.ok) return err('job', res.code, res.message, res.hint);\n const detail = parseJobDetail(res.json);\n if (!detail.ok) return err('job', detail.code, detail.message, detail.hint);\n const job: JobDetail & Teamed = detail.job;\n await enrich(get, [job], req);\n return ok('job', job);\n }\n\n const read = await readJobs(get, wanted);\n if (read.jobs.size === 0 && read.stoppedBy !== undefined)\n return err('job', read.stoppedBy, 'no job could be read');\n const unread = wanted.filter((id) => !read.jobs.has(id));\n const jobs: (JobDetail & Teamed)[] = wanted.flatMap((id) => read.jobs.get(id) ?? []);\n await enrich(get, jobs, req);\n return ok('job', {\n items: shape(jobs, opts, (j) =>\n compactJob({ ...j, easyApply: j.apply?.type === 'easy-apply', promoted: false }),\n ),\n meta: {\n state: unread.length === 0 ? 'complete' : 'partial',\n operation: 'job',\n returnedCount: jobs.length,\n ...(unread.length > 0 ? { unread } : {}),\n ...(read.stoppedBy !== undefined ? { stoppedBy: read.stoppedBy } : {}),\n },\n });\n}\n\nexport async function runJobFilters(\n req: Omit<JobsRequest, 'limit'>,\n opts: OutputOpts = {},\n fetch?: JobsFetch,\n): Promise<Envelope> {\n const sets = keywordSets(req.keywords);\n if (sets.length > 1) {\n return err(\n 'job-filters',\n 'INVALID_INPUT',\n 'job-filters takes one keyword set: its counts belong to that one query',\n 'lnrelay job-filters \"<keywords>\" [filters]',\n );\n }\n const selection = jobFilterSelection(req.filter ?? {});\n if (!selection.ok) return err('job-filters', selection.code, selection.message);\n const get = fetch ?? liveFetch('job-filters', opts.quiet === true);\n if (typeof get !== 'function') return get;\n const url = jobFiltersUrl({\n ...queryOf(req, selection.filters, sets[0]),\n start: 0,\n count: PAGE_SIZE,\n });\n const res = await get(url, 'jobSearch');\n const parsed = res.ok ? parseJobFilters(res.json) : res;\n if (!parsed.ok) return err('job-filters', parsed.code, parsed.message, parsed.hint);\n return ok('job-filters', {\n items: shape(\n parsed.filters,\n opts,\n (f) =>\n `${f.key}: ${f.options.map((o) => `${o.value}=${o.label}${o.count !== undefined ? ` (${o.count})` : ''}`).join(', ')}`,\n ),\n meta: { state: 'complete', operation: 'job-filters', returnedCount: parsed.filters.length },\n });\n}\n","// ─── The scheduled-posts queue ────────────────────────────────────────────────\n//\n// Voyager cannot read a scheduled post: `normShares/<urn>` answers 400, and\n// `my-posts` lists only what has published. The web client's \"Scheduled (N)\"\n// list is SDUI — a pager over React Server Components — and that is the only\n// place the queue is visible. Captured 2026-10-13 with three probes scheduled\n// (two over normShares, one from the web composer), then with none.\n//\n// The stream is not JSON, so it is read by exclusion-tolerant scanning, and\n// held to the same rule as every parser here: never an empty success on\n// failure. The stream carries LinkedIn's own count (`ShareBoxscheduledPostCount`,\n// the N in the tab); without it an empty queue and a page we no longer\n// understand look the same, so its absence is SCHEMA_DRIFT.\n\nimport type { FetchState } from '../types.ts';\nimport type { Client } from './client.ts';\n\nexport const PAGER_ID = 'com.linkedin.sdui.pagers.sharing.scheduledPosts';\nconst PAGER_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/pagination?sduiid=${PAGER_ID}`;\nconst SCREEN_ID = 'com.linkedin.sdui.flagshipnav.sharing.ShareSchedulePostList';\n\n/** A page as the web client asks for it when the list is scrolled. */\nexport function scheduledPageBody(start: number, count: number) {\n const args = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload: { start, count, shareLifeCycleState: 'ShareLifeCycleState_SCHEDULED' },\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n return {\n pagerId: PAGER_ID,\n clientArguments: { ...args, states: [], screenId: SCREEN_ID, knownTemplateIds: [] },\n paginationRequest: {\n $type: 'proto.sdui.actions.requests.PaginationRequest',\n pagerId: PAGER_ID,\n retryCount: 0,\n requestedArguments: args,\n },\n };\n}\n\nexport interface ScheduledPost {\n /** The urn `delete` cancels it by, and `edit` edits it by. */\n urn: string;\n /** Epoch ms. */\n scheduledAt: number;\n /**\n * The text as the list renders it: whole, but with links shortened to\n * lnkd.in. Null when it could not be paired with its row for certain.\n */\n text: string | null;\n}\n\ntype Failure = { ok: false; code: string; message: string; hint?: string };\n\nconst COUNT =\n /\"id\":\"ShareBoxscheduledPostCount\"\\}\\}\\},\"value\":\\{\"\\$case\":\"intValue\",\"intValue\":(\\d+)\\}/;\nconst ROW = /\"feedUpdateUrn\":\"(urn:li:(?:share|ugcPost):\\d+)\",\"scheduledAtEpochMillis\":\"(\\d+)\"/g;\n// Each row's preview block holds the text as a single string child. A row\n// whose text is shaped differently simply does not match, and the pairing\n// check below then refuses to guess.\nconst TEXT =\n /\"viewName\":\"mini-update-container\"[\\s\\S]*?\"textProps\":\\{[^{}]*?\"children\":\\[\"((?:[^\"\\\\]|\\\\.)*)\"\\]/g;\n\nexport function parseScheduledPage(\n stream: string,\n): { ok: true; claimedCount: number; posts: ScheduledPost[] } | Failure {\n const count = stream.match(COUNT);\n if (count?.[1] === undefined) {\n return drift('the scheduled-posts page carried no post count');\n }\n const claimedCount = Number(count[1]);\n\n const posts: ScheduledPost[] = [];\n const seen = new Set<string>();\n for (const [, urn, at] of stream.matchAll(ROW)) {\n if (urn === undefined || seen.has(urn)) continue;\n seen.add(urn);\n posts.push({ urn, scheduledAt: Number(at), text: null });\n }\n if (claimedCount > 0 && posts.length === 0) {\n return drift(`LinkedIn counts ${claimedCount} scheduled posts but no row could be read`);\n }\n\n // Texts arrive in row order. Pair them only when there is exactly one per\n // row: a text on the wrong post is worse than none.\n const texts = [...stream.matchAll(TEXT)].map((m) => JSON.parse(`\"${m[1]}\"`) as string);\n if (texts.length === posts.length) {\n posts.forEach((p, i) => {\n p.text = texts[i] ?? null;\n });\n }\n return { ok: true, claimedCount, posts };\n}\n\nfunction drift(message: string): Failure {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message,\n hint: 'Re-capture the scheduled list (open \"Scheduled\" in the composer) with scripts/observe-write.ts.',\n };\n}\n\nconst PAGE_SIZE = 10;\n/** LinkedIn's own UI pages by 5; 10 pages of 10 is far past any real queue. */\nconst MAX_PAGES = 10;\n\n/**\n * The whole queue, paged until it holds as many posts as LinkedIn counts.\n * `state` is `complete` only when it does.\n */\nexport async function fetchScheduled(\n client: Client,\n pageSize = PAGE_SIZE,\n): Promise<\n { ok: true; posts: ScheduledPost[]; claimedCount: number; state: FetchState } | Failure\n> {\n const posts: ScheduledPost[] = [];\n const seen = new Set<string>();\n let claimedCount = 0;\n\n for (let page = 0; page < MAX_PAGES; page++) {\n const result = await client.request({\n url: PAGER_URL,\n method: 'POST',\n body: scheduledPageBody(posts.length, pageSize),\n spendClass: 'page',\n operation: 'scheduled',\n });\n if (!result.ok) {\n const out: Failure = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n // Not JSON; the client keeps the raw stream on the classification.\n const parsed = parseScheduledPage((result.classification as { raw?: string }).raw ?? '');\n if (!parsed.ok) return parsed;\n\n // The highest count seen: a later page that comes back emptier must not\n // shrink what LinkedIn said was there and turn a short read into `complete`.\n claimedCount = Math.max(claimedCount, parsed.claimedCount);\n const fresh = parsed.posts.filter((p) => !seen.has(p.urn));\n for (const p of fresh) {\n seen.add(p.urn);\n posts.push(p);\n }\n if (posts.length >= claimedCount || fresh.length === 0) break;\n }\n\n const state: FetchState = posts.length >= claimedCount ? 'complete' : 'partial';\n return { ok: true, posts, claimedCount, state };\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 createLiveClient,\n type EngineResult,\n} from '../engine/index.ts';\nimport { fetchScheduled, type ScheduledPost } from '../engine/sdui-scheduled.ts';\n\nimport {\n LAUNCH_HINT,\n loadSession,\n mintSessionFromBrowser,\n saveSession,\n} from '../engine/session.ts';\nimport { compactRows, project, type Shaped, shapeAll, shapeEntity } 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 = sessionFor(command);\n if ('ok' in loaded) return loaded;\n return { engine: createEngine(loaded.session, undefined, quiet) };\n}\n\nfunction sessionFor(\n command: string,\n): { session: Extract<ReturnType<typeof loadSession>, { state: 'ok' }>['session'] } | 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 { session: loaded.session };\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 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 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/** Your own posts waiting to publish. Not in `my-posts` until they do. */\nexport async function runScheduled(quiet = false): Promise<Envelope> {\n const ctx = sessionFor('scheduled');\n if ('ok' in ctx) return ctx;\n const result = await fetchScheduled(createLiveClient(ctx.session, undefined, quiet));\n if (!result.ok) return err('scheduled', result.code, result.message, result.hint);\n return ok('scheduled', scheduledData(result));\n}\n\nexport function scheduledData(result: {\n posts: ScheduledPost[];\n claimedCount: number;\n state: 'complete' | 'partial' | 'unknown';\n}) {\n return {\n items: result.posts.map((p) => ({\n urn: p.urn,\n scheduledAt: new Date(p.scheduledAt).toISOString(),\n text: p.text,\n })),\n meta: {\n state: result.state,\n returnedCount: result.posts.length,\n claimedCount: result.claimedCount,\n },\n };\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. */\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[] = [\n 'profile',\n 'search',\n 'page',\n 'jobSearch',\n 'jobRead',\n 'write',\n 'global',\n ];\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","// ─── `lnrelay inbox`, `messages`, `draft`, `drafts` ───────────────────────────\n//\n// Reading the owner's messages, and drafting replies on this machine. See\n// engine/messaging.ts. There is NO send: a draft is a local note with the\n// conversation's link, for the owner to open, review and send themselves.\n// Nothing read is stored; it is fetched live, on the page budget. The\n// mailbox id (the owner's own profile id) is kept in me.json after the first\n// lookup so every read does not cost a `whoami`.\n\nimport { randomUUID } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport { createEngine, createLiveClient } from '../engine/index.ts';\nimport {\n type Conversation,\n conversationIdOf,\n conversationsUrl,\n FOLDERS,\n type Folder,\n mailboxOf,\n messagesUrl,\n parseConversations,\n parseMessages,\n} from '../engine/messaging.ts';\nimport type { Failure } from '../engine/sdui-form.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; json: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted GET. Injectable so tests send nothing. Messaging never POSTs. */\nexport type MessagingFetch = (url: string, spendClass: 'page') => Promise<Fetched>;\n\n/** Messages a page holds; fewer means nothing older is held back. */\nconst MESSAGES_PAGE = 20;\n/** Folders deeper than this are refused rather than paged forever. */\nconst MAX_CONVERSATIONS = 500;\n\nfunction live(command: string, quiet: boolean) {\n const session = loadSession();\n if (session.state !== 'ok')\n return err(command, 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n const fetch: MessagingFetch = async (url, spendClass) => {\n const r = await client.request({ url, spendClass, operation: command });\n return r.ok ? { ok: true, json: r.json } : r;\n };\n return { fetch, session: session.session };\n}\n\n/** The owner's mailbox: me.json, or one `whoami` the first time. */\nasync function mailbox(command: string, quiet: boolean): Promise<string | Envelope> {\n const known = loadJson<{ profileUrn?: string }>(cachePath('me.json'));\n if (known.state === 'ok' && typeof known.value.profileUrn === 'string')\n return known.value.profileUrn;\n const session = loadSession();\n if (session.state !== 'ok')\n return err(command, 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const me = await createEngine(session.session, undefined, quiet).whoami();\n const urn = me.ok ? (me.value as { entityUrn?: unknown } | undefined)?.entityUrn : undefined;\n if (typeof urn !== 'string')\n return err(command, 'AUTH_FAILED', 'could not tell whose mailbox this is');\n const profileUrn = mailboxOf(urn);\n saveJson(cachePath('me.json'), { profileUrn });\n return profileUrn;\n}\n\nasync function setup(command: string, opts: OutputOpts, fetch?: MessagingFetch) {\n const box = await mailbox(command, opts.quiet === true);\n if (typeof box !== 'string') return box;\n if (fetch !== undefined) return { box, get: fetch };\n const l = live(command, opts.quiet === true);\n if ('ok' in l) return l;\n return { box, get: l.fetch };\n}\n\n// ─── inbox ────────────────────────────────────────────────────────────────────\n\nexport interface InboxRequest {\n folder?: Folder;\n limit: number;\n /** Only conversations with unread messages. */\n unread?: boolean;\n}\n\nfunction compactConversation(c: Conversation): string {\n const last =\n c.last === undefined\n ? undefined\n : `${c.last.from}: ${(c.last.text ?? '').replace(/\\s+/g, ' ')}`;\n return line([\n c.id,\n c.with.map((p) => p.name).join(', ') || c.title,\n c.unread > 0 ? `${c.unread} unread` : undefined,\n c.lastActivity?.slice(0, 10),\n c.inmail ? 'InMail' : undefined,\n last !== undefined && last.length > 140 ? `${last.slice(0, 137)}…` : last,\n ]);\n}\n\nexport async function runInbox(\n req: InboxRequest,\n opts: OutputOpts = {},\n fetch?: MessagingFetch,\n): Promise<Envelope> {\n const folder = req.folder ?? 'inbox';\n if (!(folder in FOLDERS)) {\n return err(\n 'inbox',\n 'INVALID_INPUT',\n `no folder '${folder}'`,\n `one of: ${Object.keys(FOLDERS).join(', ')}`,\n );\n }\n const ready = await setup('inbox', opts, fetch);\n if ('ok' in ready) return ready;\n const want = Math.max(1, Math.min(req.limit, MAX_CONVERSATIONS));\n\n const all: Conversation[] = [];\n let cursor: string | undefined;\n let stoppedBy: string | undefined;\n let exhausted = false;\n while (all.length < want) {\n const res = await ready.get(\n conversationsUrl({ mailbox: ready.box, folder, ...(cursor ? { cursor } : {}) }),\n 'page',\n );\n const page = res.ok ? parseConversations(res.json, ready.box) : res;\n if (!page.ok) {\n if (all.length === 0) return err('inbox', page.code, page.message, page.hint);\n stoppedBy = page.code;\n break;\n }\n const room = want - all.length;\n all.push(...page.conversations.slice(0, room));\n if (page.conversations.length > room) break;\n if (page.cursor === undefined || page.conversations.length === 0) {\n exhausted = true;\n break;\n }\n cursor = page.cursor;\n }\n const shown = req.unread === true ? all.filter((c) => c.unread > 0) : all;\n return ok('inbox', {\n folder,\n items: shape(shown, opts, compactConversation),\n meta: {\n state: exhausted && stoppedBy === undefined ? 'complete' : 'partial',\n operation: 'inbox',\n returnedCount: shown.length,\n unread: all.filter((c) => c.unread > 0).length,\n ...(stoppedBy !== undefined ? { stoppedBy } : {}),\n },\n });\n}\n\n// ─── messages ─────────────────────────────────────────────────────────────────\n\nexport async function runMessages(\n input: string | undefined,\n opts: OutputOpts = {},\n fetch?: MessagingFetch,\n): Promise<Envelope> {\n const ready = await setup('messages', opts, fetch);\n if ('ok' in ready) return ready;\n const id = input === undefined ? undefined : conversationIdOf(input, ready.box);\n if (id === undefined) {\n return err(\n 'messages',\n 'INVALID_INPUT',\n 'a conversation id or /messaging/thread/ URL is required',\n 'ids come from `lnrelay inbox`',\n );\n }\n const res = await ready.get(messagesUrl(id), 'page');\n const parsed = res.ok ? parseMessages(res.json, ready.box) : res;\n if (!parsed.ok) return err('messages', parsed.code, parsed.message, parsed.hint);\n return ok('messages', {\n conversation: id,\n url: threadUrl(id),\n items: shape(parsed.messages, opts, (m) =>\n line([\n m.at.slice(0, 16).replace('T', ' '),\n m.from,\n m.subject,\n (m.text ?? '').replace(/\\s+/g, ' '),\n ]),\n ),\n meta: {\n // A full page may have older messages behind it; this reads the latest page only.\n state: parsed.messages.length < MESSAGES_PAGE ? 'complete' : 'partial',\n operation: 'messages',\n returnedCount: parsed.messages.length,\n },\n });\n}\n\nconst threadUrl = (conversationUrn: string) => {\n const thread = conversationUrn.match(/,(2-[^)]+)\\)$/)?.[1];\n return thread === undefined ? undefined : `https://www.linkedin.com/messaging/thread/${thread}/`;\n};\n\n// ─── drafts ───────────────────────────────────────────────────────────────────\n\nexport interface Draft {\n id: string;\n conversation: string;\n url?: string;\n /** Who the conversation is with, as it read when the draft was made. */\n to: string[];\n text: string;\n createdAt: string;\n}\n\nconst DRAFTS = () => cachePath('drafts.json');\n\nfunction loadDrafts(): Draft[] | Failure {\n const loaded = loadJson<Draft[]>(DRAFTS());\n if (loaded.state === 'missing') return [];\n if (loaded.state === 'corrupt')\n return {\n ok: false,\n code: 'CACHE_CORRUPT',\n message: `drafts were unreadable; moved to ${loaded.quarantinedTo}`,\n };\n return Array.isArray(loaded.value) ? loaded.value : [];\n}\n\nexport async function runDraft(\n conversation: string | undefined,\n text: string | undefined,\n fetch?: MessagingFetch,\n opts: OutputOpts = {},\n): Promise<Envelope> {\n const body = text?.trim() ?? '';\n if (body === '')\n return err(\n 'draft',\n 'INVALID_INPUT',\n 'a draft needs text',\n 'lnrelay draft <conversation> \"<text>\" | --file <path>',\n );\n const box = await mailbox('draft', opts.quiet === true);\n if (typeof box !== 'string') return box;\n const id = conversation === undefined ? undefined : conversationIdOf(conversation, box);\n if (id === undefined)\n return err(\n 'draft',\n 'INVALID_INPUT',\n 'a conversation id or /messaging/thread/ URL is required',\n 'ids come from `lnrelay inbox`',\n );\n const ready = await setup('draft', opts, fetch);\n if ('ok' in ready) return ready;\n\n // One read: the conversation exists, and who it is with.\n const res = await ready.get(messagesUrl(id), 'page');\n const parsed = res.ok ? parseMessages(res.json, ready.box) : res;\n if (!parsed.ok) return err('draft', parsed.code, parsed.message, parsed.hint);\n const to = [...new Set(parsed.messages.filter((m) => !m.fromMe).map((m) => m.from))];\n\n const drafts = loadDrafts();\n if (!Array.isArray(drafts)) return err('draft', drafts.code, drafts.message);\n const url = threadUrl(id);\n const draft: Draft = {\n id: randomUUID().slice(0, 8),\n conversation: id,\n ...(url !== undefined ? { url } : {}),\n to,\n text: body,\n createdAt: new Date().toISOString(),\n };\n saveJson(DRAFTS(), [...drafts, draft]);\n return ok('draft', {\n saved: true,\n sent: false,\n draft,\n notice:\n 'Saved on this machine only. Nothing was sent: open the link, review, and send it yourself.',\n });\n}\n\nexport function draftText(text: string | undefined, file: string | undefined): string | undefined {\n return file !== undefined ? readFileSync(file, 'utf-8') : text;\n}\n\nexport function runDrafts(opts: OutputOpts = {}): Envelope {\n const drafts = loadDrafts();\n if (!Array.isArray(drafts)) return err('drafts', drafts.code, drafts.message);\n return ok('drafts', {\n items: shape(drafts, opts, (d) =>\n line([d.id, d.to.join(', '), d.createdAt.slice(0, 10), d.text.replace(/\\s+/g, ' '), d.url]),\n ),\n meta: { state: 'complete', operation: 'drafts', returnedCount: drafts.length },\n });\n}\n\nexport function runDraftRemove(id: string | undefined): Envelope {\n const drafts = loadDrafts();\n if (!Array.isArray(drafts)) return err('draft', drafts.code, drafts.message);\n if (id === undefined || !drafts.some((d) => d.id === id)) {\n return err(\n 'draft',\n 'NOT_FOUND',\n `no draft '${id ?? ''}'`,\n `drafts: ${drafts.map((d) => d.id).join(', ') || 'none'}`,\n );\n }\n saveJson(\n DRAFTS(),\n drafts.filter((d) => d.id !== id),\n );\n return ok('draft', { removed: id });\n}\n","// ─── Reading the owner's messages ─────────────────────────────────────────────\n//\n// Captured 2026-10-14 from the messaging page. Reading is two GraphQL queries\n// on `voyagerMessagingGraphQL`:\n//\n// messengerConversations a folder of conversations, 20 at a time, by cursor\n// messengerMessages a conversation's latest messages\n//\n// Opening a conversation in the browser does more than read: the page also\n// POSTs `markAllMessagesAsSeen`, `sendDeliveryAcknowledgement` and, for an\n// unread conversation, marks it read — which the sender sees. Those are\n// separate calls, and this module makes none of them. Nothing here sends,\n// marks, or acknowledges anything; reading through it leaves no trace a\n// correspondent can see.\n//\n// The conversation urn is `urn:li:msg_conversation:(<mailbox>,2-<id>==)`; the\n// browser leaves its `=` padding raw, and percent-encoding it is answered\n// with a 400. The Rest.li codec leaves `=` alone, which is what is wanted.\n\nimport { CONTRACTS } from './contracts.ts';\nimport { encodeVariables } from './restli.ts';\nimport type { Failure } from './sdui-form.ts';\n\n/** The folders, by the name LinkedIn's mailbox counts use. */\nexport const FOLDERS = {\n primary: 'PRIMARY_INBOX',\n other: 'SECONDARY_INBOX',\n inbox: 'INBOX',\n archive: 'ARCHIVE',\n requests: 'MESSAGE_REQUEST_PENDING',\n spam: 'SPAM',\n} as const;\n\nexport type Folder = keyof typeof FOLDERS;\n\nconst FOLDER_OF: Record<string, Folder> = Object.fromEntries(\n Object.entries(FOLDERS).map(([k, v]) => [v, k as Folder]),\n);\n\nfunction contract(name: 'messengerConversations' | 'messengerMessages') {\n const c = CONTRACTS[name];\n if (c?.queryId === undefined) throw new Error(`messaging contract '${name}' is missing`);\n return c;\n}\n\n/** The mailbox is the owner's profile: `whoami`'s urn, in its `fsd_profile` form. */\nexport function mailboxOf(meUrn: string): string {\n const id = meUrn.match(/(?:fs_miniProfile|fsd_profile|fs_profile):([A-Za-z0-9_-]+)/)?.[1];\n return `urn:li:fsd_profile:${id ?? meUrn}`;\n}\n\nexport function conversationsUrl(q: {\n mailbox: string;\n folder: Folder;\n cursor?: string;\n count?: number;\n}): string {\n const c = contract('messengerConversations');\n const variables = encodeVariables({\n query: {\n predicateUnions: [{ conversationCategoryPredicate: { category: FOLDERS[q.folder] } }],\n },\n count: q.count ?? 20,\n mailboxUrn: q.mailbox,\n nextCursor: q.cursor,\n });\n return `${c.path}?queryId=${c.queryId}&variables=${variables}`;\n}\n\nexport function messagesUrl(conversationUrn: string): string {\n const c = contract('messengerMessages');\n return `${c.path}?queryId=${c.queryId}&variables=${encodeVariables({ conversationUrn })}`;\n}\n\n/** A conversation urn from itself, a /messaging/thread/ URL, or a bare thread id. */\nexport function conversationIdOf(input: string, mailbox: string): string | undefined {\n const s = input.trim();\n if (/^urn:li:msg_conversation:\\(urn:li:fsd_profile:[^,]+,2-[^)]+\\)$/.test(s)) return s;\n const thread =\n s.match(/messaging\\/thread\\/(2-[^/?#]+)/)?.[1] ?? s.match(/^(2-[A-Za-z0-9+/=_-]+)$/)?.[1];\n return thread === undefined ? undefined : `urn:li:msg_conversation:(${mailbox},${thread})`;\n}\n\n// ─── Parsing ──────────────────────────────────────────────────────────────────\n\ntype Node = Record<string, unknown>;\n\nexport interface Participant {\n name: string;\n kind: 'person' | 'organization' | 'other';\n headline?: string;\n /** 1st, 2nd, 3rd+, out of network. */\n degree?: string;\n url?: string;\n}\n\nexport interface MessageLine {\n from: string;\n fromMe: boolean;\n at: string;\n text?: string;\n subject?: string;\n /** A sponsored message (an InMail ad). */\n sponsored?: boolean;\n}\n\nexport interface Conversation {\n id: string;\n url?: string;\n /** Everyone in it but the owner. */\n with: Participant[];\n /** A group conversation's name. */\n title?: string;\n unread: number;\n lastActivity?: string;\n last?: MessageLine;\n folders: Folder[];\n inmail: boolean;\n}\n\nexport interface Message extends MessageLine {\n id: string;\n}\n\nconst DEGREE: Record<string, string> = {\n DISTANCE_1: '1st',\n DISTANCE_2: '2nd',\n DISTANCE_3: '3rd+',\n OUT_OF_NETWORK: 'out of network',\n};\n\nconst txt = (v: unknown): string | undefined => {\n const t = typeof v === 'string' ? v : (v as { text?: unknown } | null | undefined)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim() : undefined;\n};\n\nconst iso = (ms: unknown) => (typeof ms === 'number' ? new Date(ms).toISOString() : undefined);\n\nfunction defined<T extends Record<string, unknown>>(obj: T): T {\n for (const k of Object.keys(obj)) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\nfunction participantOf(p: Node | undefined): Participant | undefined {\n const t = (p?.participantType ?? {}) as Record<string, Node | null>;\n if (t.member) {\n const m = t.member;\n const name = [txt(m.firstName), txt(m.lastName)].filter(Boolean).join(' ');\n const url =\n typeof m.profileUrl === 'string' ? `${m.profileUrl.replace(/\\/$/, '')}/` : undefined;\n return defined({\n name: name !== '' ? name : 'LinkedIn Member',\n kind: 'person' as const,\n headline: txt(m.headline),\n degree: DEGREE[String(m.distance)],\n url,\n });\n }\n if (t.organization) {\n const o = t.organization;\n return defined({\n name: txt(o.name) ?? 'an organization',\n kind: 'organization' as const,\n url: typeof o.pageUrl === 'string' ? o.pageUrl : undefined,\n });\n }\n if (t.custom) return { name: txt(t.custom.name) ?? 'LinkedIn', kind: 'other' };\n return undefined;\n}\n\nconst isMe = (urn: unknown, mailbox: string) => typeof urn === 'string' && urn.includes(mailbox);\n\nfunction messageOf(m: Node, byUrn: Map<unknown, Node>, mailbox: string): MessageLine {\n const sender = m['*sender'] ?? m['*actor'];\n const fromMe = isMe(sender, mailbox);\n const who = fromMe ? undefined : participantOf(byUrn.get(sender));\n const render = Array.isArray(m.renderContent) ? (m.renderContent as Node[]) : [];\n return defined({\n from: fromMe ? 'you' : (who?.name ?? 'unknown'),\n fromMe,\n at: iso(m.deliveredAt) as string,\n text: txt(m.body),\n subject: txt(m.subject),\n sponsored: render.some((r) => r.conversationAdsMessageContent) ? true : undefined,\n });\n}\n\nconst drift = (message: string): Failure => ({\n ok: false,\n code: 'SCHEMA_DRIFT',\n message,\n hint: 'the messaging response changed shape; re-capture it',\n});\n\n/** The `messenger…` collection in a response, whatever the query named it. */\nfunction collectionOf(json: unknown): Node | undefined {\n const d = (json as { data?: { data?: Node } } | null)?.data?.data;\n const key = d === undefined ? undefined : Object.keys(d).find((k) => k.startsWith('messenger'));\n const c = key === undefined ? undefined : d?.[key];\n return c !== null && typeof c === 'object' ? (c as Node) : undefined;\n}\n\n/** A collection's references; an empty one comes as `elements: []` instead. */\nfunction refsOf(top: Node | undefined): string[] | undefined {\n const refs = top?.['*elements'];\n if (Array.isArray(refs)) return refs as string[];\n return Array.isArray(top?.elements) && top.elements.length === 0 ? [] : undefined;\n}\n\nexport function parseConversations(\n json: unknown,\n mailbox: string,\n): { ok: true; conversations: Conversation[]; cursor?: string } | Failure {\n const top = collectionOf(json);\n const refs = refsOf(top);\n if (refs === undefined) return drift('the conversation list was missing');\n const included = (json as { included?: Node[] }).included ?? [];\n const byUrn = new Map<unknown, Node>(included.map((n) => [n.entityUrn, n]));\n const conversations: Conversation[] = [];\n for (const ref of refs) {\n const c = byUrn.get(ref);\n if (c === undefined) continue;\n const parts = ((c['*conversationParticipants'] as string[] | undefined) ?? [])\n .filter((u) => !isMe(u, mailbox))\n .map((u) => participantOf(byUrn.get(u)))\n .filter((p): p is Participant => p !== undefined);\n const lastRef = ((c.messages as Node | undefined)?.['*elements'] as string[] | undefined)?.[0];\n const last = lastRef === undefined ? undefined : byUrn.get(lastRef);\n const categories = Array.isArray(c.categories) ? (c.categories as string[]) : [];\n conversations.push(\n defined({\n id: String(c.entityUrn),\n url: typeof c.conversationUrl === 'string' ? c.conversationUrl : undefined,\n with: parts,\n title: c.groupChat === true ? txt(c.title) : undefined,\n unread: typeof c.unreadCount === 'number' ? c.unreadCount : 0,\n lastActivity: iso(c.lastActivityAt),\n last: last === undefined ? undefined : messageOf(last, byUrn, mailbox),\n // PRIMARY_INBOX sits inside INBOX; report the folder a person would name.\n folders: categories\n .map((k) => FOLDER_OF[k])\n .filter(\n (f): f is Folder =>\n f !== undefined && !(f === 'primary' && categories.includes('INBOX')),\n ),\n inmail: categories.includes('INMAIL'),\n }),\n );\n }\n if (refs.length > 0 && conversations.length === 0)\n return drift(`${refs.length} conversations were listed but none were sent`);\n const cursor = (top?.metadata as Node | undefined)?.nextCursor;\n return {\n ok: true,\n conversations,\n ...(typeof cursor === 'string' && cursor !== '' ? { cursor } : {}),\n };\n}\n\nexport function parseMessages(\n json: unknown,\n mailbox: string,\n): { ok: true; messages: Message[] } | Failure {\n const top = collectionOf(json);\n const refs = refsOf(top);\n if (refs === undefined) return drift('the message list was missing');\n const included = (json as { included?: Node[] }).included ?? [];\n const byUrn = new Map<unknown, Node>(included.map((n) => [n.entityUrn, n]));\n const messages: Message[] = [];\n for (const ref of refs) {\n const m = byUrn.get(ref);\n if (m === undefined || typeof m.deliveredAt !== 'number') continue;\n messages.push({ id: String(m.entityUrn), ...messageOf(m, byUrn, mailbox) });\n }\n if (refs.length > 0 && messages.length === 0)\n return drift(`${refs.length} messages were listed but none were sent`);\n // Oldest first, the way a conversation reads.\n messages.sort((a, b) => a.at.localeCompare(b.at));\n return { ok: true, messages };\n}\n","// ─── My items: saved posts, learning, the job tracker ─────────────────────────\n//\n// Captured 2026-10-14. Each list is the Voyager search (the `search`\n// contract) with a My-items intent and no keywords:\n//\n// SEARCH_MY_ITEMS_SAVED_POSTS posts the owner saved\n// SEARCH_MY_ITEMS_LEARNING their LinkedIn Learning courses\n// SEARCH_MY_ITEMS_JOB_SEEKER the job tracker, one stage at a time:\n// queryParameters cardType = SAVED, IN_PROGRESS,\n// APPLIED, INTERVIEW, ARCHIVED\n//\n// The stage names are the job tracker page's own (`?stage=archived`, …),\n// uppercased. LinkedIn does not validate them: a wrong name answers with no\n// jobs, not an error. ARCHIVED was verified with the owner's 6 archived jobs;\n// the other four agreed with the page's own counts (all 0) — which a wrong\n// name would also give. Pages hold 10; saved posts page with a token.\n\nimport { CONTRACTS } from './contracts.ts';\nimport { type Clusters, clustersOf, readItems } from './people.ts';\nimport { encodeVariables } from './restli.ts';\nimport type { Failure } from './sdui-form.ts';\n\nexport const ITEMS = {\n posts: 'SEARCH_MY_ITEMS_SAVED_POSTS',\n learning: 'SEARCH_MY_ITEMS_LEARNING',\n jobs: 'SEARCH_MY_ITEMS_JOB_SEEKER',\n} as const;\n\nexport type ItemList = keyof typeof ITEMS;\n\nexport const STAGES = {\n saved: 'SAVED',\n 'in-progress': 'IN_PROGRESS',\n applied: 'APPLIED',\n interview: 'INTERVIEW',\n archived: 'ARCHIVED',\n} as const;\n\nexport type Stage = keyof typeof STAGES;\n\nexport const ITEMS_PAGE = 10;\n\nexport function itemsUrl(\n list: ItemList,\n q: { start: number; stage?: Stage; token?: string },\n): string {\n const c = CONTRACTS.search;\n if (c?.queryId === undefined) throw new Error(\"the 'search' contract is missing\");\n const variables = encodeVariables({\n start: q.start,\n paginationToken: q.token,\n query: {\n flagshipSearchIntent: ITEMS[list],\n queryParameters:\n q.stage !== undefined ? [{ key: 'cardType', value: [STAGES[q.stage]] }] : undefined,\n },\n });\n return `${c.path}?variables=${variables}&queryId=${c.queryId}`;\n}\n\n// ─── Rows ─────────────────────────────────────────────────────────────────────\n\nexport interface SavedPost {\n /** The post's urn: what `post` and `reactions` take. */\n id: string;\n url: string;\n author?: string;\n authorHeadline?: string;\n /** When, as LinkedIn shows it (\"5d\"). */\n posted?: string;\n text?: string;\n}\n\nexport interface Course {\n id: string;\n name: string;\n length?: string;\n /** Instructor and release date, as LinkedIn writes them. */\n detail?: string;\n /** \"6m left\", or completion. */\n progress?: string;\n url?: string;\n}\n\nexport interface TrackedJob {\n /** The job id: what `job` takes. */\n id: string;\n title: string;\n company?: string;\n location?: string;\n workplace?: 'on-site' | 'remote' | 'hybrid';\n stage?: Stage;\n /** A line LinkedIn adds, such as \"No longer accepting applications\". */\n note?: string;\n url: string;\n}\n\ntype Node = Record<string, unknown>;\ntype Item = SavedPost | Course | TrackedJob;\n\nconst text = (v: unknown): string | undefined => {\n const t = (v as { text?: unknown } | null | undefined)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim().replace(/\\s+/g, ' ') : undefined;\n};\nconst inner = (urn: unknown) => String(urn ?? '').match(/\\((urn:li:[A-Za-z_]+:[^,)]+)/)?.[1];\nconst clean = (url: unknown) =>\n typeof url === 'string' && url.startsWith('https://') ? url.split('?')[0] : undefined;\nconst insight = (row: Node) =>\n (Array.isArray(row.insightsResolutionResults) ? (row.insightsResolutionResults as Node[]) : [])\n .map((i) => text((i.simpleInsight as Node | null)?.title))\n .find((t) => t !== undefined);\n\nfunction defined<T extends object>(obj: T): T {\n for (const k of Object.keys(obj) as (keyof T)[]) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\nconst WORKPLACE: Record<string, TrackedJob['workplace']> = {\n remote: 'remote',\n hybrid: 'hybrid',\n 'on-site': 'on-site',\n};\n\nfunction postRow(row: Node): SavedPost | undefined {\n const id = inner(row.entityUrn);\n if (id === undefined || !/^urn:li:(activity|ugcPost|share):/.test(id)) return undefined;\n const posted = text(row.secondarySubtitle)?.replace(/\\s*•\\s*$/, '');\n return defined({\n id,\n url: `https://www.linkedin.com/feed/update/${id}/`,\n author: text(row.title),\n authorHeadline: text(row.primarySubtitle),\n posted,\n text: text(row.summary),\n });\n}\n\nfunction courseRow(row: Node): Course | undefined {\n const id = inner(row.entityUrn)?.split(':').pop();\n const name = text(row.title);\n if (id === undefined || name === undefined) return undefined;\n return defined({\n id,\n name,\n length: text(row.primarySubtitle),\n detail: text(row.secondarySubtitle),\n progress: text(row.summary),\n url: clean(row.navigationUrl),\n });\n}\n\nfunction jobRow(row: Node, stage?: Stage): TrackedJob | undefined {\n const id = inner(row.entityUrn)?.split(':').pop();\n const title = text(row.title);\n if (id === undefined || title === undefined) return undefined;\n const place = text(row.secondarySubtitle);\n const m = place?.match(/^(.*?)\\s*\\(([^()]+)\\)$/);\n const workplace = m?.[2] === undefined ? undefined : WORKPLACE[m[2].toLowerCase()];\n return defined({\n id,\n title,\n company: text(row.primarySubtitle),\n location: workplace !== undefined ? m?.[1] : place,\n workplace,\n stage,\n note: insight(row),\n url: `https://www.linkedin.com/jobs/view/${id}/`,\n });\n}\n\nexport function parseItems(\n list: ItemList,\n json: unknown,\n stage?: Stage,\n): { ok: true; items: Item[]; total?: number; token?: string } | Failure {\n const c: Clusters | undefined = clustersOf(json);\n if (c === undefined || !Array.isArray(c.elements))\n return { ok: false, code: 'SCHEMA_DRIFT', message: 'the My items list was missing' };\n const included = (json as { included?: Node[] }).included ?? [];\n const toRow = (row: Node) =>\n list === 'posts' ? postRow(row) : list === 'learning' ? courseRow(row) : jobRow(row, stage);\n const { people: items, unresolved } = readItems(\n c,\n included,\n toRow as (row: Node) => (Item & { id: string }) | undefined,\n );\n if (unresolved > 0 && items.length === 0)\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `${unresolved} items were listed but none could be read`,\n };\n const total = typeof c.paging?.total === 'number' ? c.paging.total : undefined;\n const token = c.metadata?.paginationToken;\n return {\n ok: true,\n items,\n ...(total !== undefined ? { total } : {}),\n ...(typeof token === 'string' && token !== '' ? { token } : {}),\n };\n}\n","// ─── `lnrelay my-items posts|learning|jobs` ───────────────────────────────────\n//\n// The owner's My items, read only; see engine/my-items.ts. Saved posts and\n// learning are one list each; the job tracker is one list per stage, so jobs\n// with no --stage read all five. Everything spends the page budget.\n\nimport { createLiveClient } from '../engine/index.ts';\nimport {\n ITEMS,\n ITEMS_PAGE,\n type ItemList,\n itemsUrl,\n parseItems,\n STAGES,\n type Stage,\n} from '../engine/my-items.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; json: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted GET. Injectable so tests send nothing. */\nexport type ItemsFetch = (url: string, spendClass: 'page') => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): ItemsFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('my-items', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, spendClass) => {\n const r = await client.request({ url, spendClass, operation: 'my-items' });\n return r.ok ? { ok: true, json: r.json } : r;\n };\n}\n\nexport interface ItemsRequest {\n limit: number;\n stage?: Stage;\n}\n\ntype Row = Record<string, unknown>;\n\n/** One list (or one tracker stage), paged to the limit. */\nasync function collect(get: ItemsFetch, list: ItemList, want: number, stage?: Stage) {\n const items: Row[] = [];\n let token: string | undefined;\n for (let start = 0; items.length < want; start += ITEMS_PAGE) {\n const res = await get(\n itemsUrl(list, { start, ...(stage ? { stage } : {}), ...(token ? { token } : {}) }),\n 'page',\n );\n const page = res.ok ? parseItems(list, res.json, stage) : res;\n if (!page.ok)\n return items.length === 0 ? page : { items, complete: false, stoppedBy: page.code };\n const room = want - items.length;\n items.push(...(page.items as unknown as Row[]).slice(0, room));\n // The limit cut this page short: there is more.\n if (page.items.length > room) return { items, complete: false };\n const last =\n page.items.length < ITEMS_PAGE ||\n (page.total !== undefined && start + ITEMS_PAGE >= page.total);\n if (last) return { items, complete: true };\n token = page.token;\n }\n return { items, complete: false };\n}\n\nfunction compactRow(r: Row): string {\n return line(\n [\n r.id,\n r.title ?? r.name ?? r.author,\n r.company ?? r.length ?? r.authorHeadline,\n r.location ?? r.detail ?? r.posted,\n r.workplace,\n r.stage,\n r.note ?? r.progress,\n typeof r.text === 'string' ? r.text.replace(/\\s+/g, ' ').slice(0, 140) : undefined,\n r.url,\n ].map((x) => (typeof x === 'string' ? x : undefined)),\n );\n}\n\ninterface Gathered {\n items: Row[];\n byStage: Record<string, number>;\n complete: boolean;\n stoppedBy?: string;\n}\n\n/** Each stage in turn (one, for posts and learning) until the limit; a stage that fails is noted. */\nasync function collectStages(\n get: ItemsFetch,\n which: ItemList,\n want: number,\n stages: (Stage | undefined)[],\n): Promise<Gathered | { failure: { code: string; message: string; hint?: string } }> {\n const out: Gathered = { items: [], byStage: {}, complete: true };\n let failure: { code: string; message: string; hint?: string } | undefined;\n for (const stage of stages) {\n const got = await collect(get, which, want - out.items.length, stage);\n if ('ok' in got) {\n failure = failure ?? got;\n out.complete = false;\n out.stoppedBy = got.code;\n continue;\n }\n out.items.push(...got.items);\n if (stage !== undefined) out.byStage[stage] = got.items.length;\n out.complete &&= got.complete;\n if (got.stoppedBy !== undefined) out.stoppedBy = got.stoppedBy;\n if (out.items.length >= want) break;\n }\n // Nothing read at all, and something failed: a failure, not an empty list.\n if (out.items.length === 0 && failure !== undefined) return { failure };\n return out;\n}\n\nexport async function runMyItems(\n list: string | undefined,\n req: ItemsRequest,\n opts: OutputOpts = {},\n fetch?: ItemsFetch,\n): Promise<Envelope> {\n if (list === undefined || !(list in ITEMS))\n return err(\n 'my-items',\n 'INVALID_INPUT',\n `no list '${list ?? ''}'`,\n `one of: ${Object.keys(ITEMS).join(', ')}`,\n );\n if (req.stage !== undefined && !(req.stage in STAGES))\n return err(\n 'my-items',\n 'INVALID_INPUT',\n `no stage '${req.stage}'`,\n `one of: ${Object.keys(STAGES).join(', ')}`,\n );\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n const want = Math.max(1, req.limit);\n const which = list as ItemList;\n\n const stages: (Stage | undefined)[] =\n which === 'jobs'\n ? req.stage !== undefined\n ? [req.stage]\n : (Object.keys(STAGES) as Stage[])\n : [undefined];\n const got = await collectStages(get, which, want, stages);\n if ('failure' in got) {\n const f = got.failure;\n return err('my-items', f.code, f.message, f.hint);\n }\n const { items, byStage, complete, stoppedBy } = got;\n return ok('my-items', {\n list: which,\n items: shape(items, opts, compactRow),\n meta: {\n state: complete && stoppedBy === undefined ? 'complete' : 'partial',\n operation: `my-items ${which}`,\n returnedCount: items.length,\n ...(which === 'jobs' && req.stage === undefined ? { byStage } : {}),\n ...(stoppedBy !== undefined ? { stoppedBy } : {}),\n },\n });\n}\n","// ─── Searching companies, groups, events, courses, products, services, schools ─\n//\n// Probed 2026-10-14. Every kind in the search box beside people, jobs and\n// posts comes back from the same Voyager search as people (engine/people.ts),\n// one `resultType` each, in the same row shape: a title, a subtitle, a second\n// line and a summary, whose meaning depends on the kind:\n//\n// companies industry • HQ followers id: company\n// groups members — id: group\n// events when where • organiser id: event\n// courses length instructor • released id: course\n// products category by vendor — id: product page\n// services the provider's headline, place, service id: profile\n// schools place students and alumni id: school (organisation)\n//\n// So one parser serves them all and keeps LinkedIn's lines as they are rather\n// than guessing at fields inside them. Pages hold 50 (events return more than\n// asked); LinkedIn pages at most 1000 of any query. Filters differ per kind and\n// come back with `includeFiltersInResponse`, as for people.\n\nimport { type Clusters, clustersOf, PEOPLE_PAGE, peopleSearchUrl, readItems } from './people.ts';\nimport type { Failure } from './sdui-form.ts';\n\n/** The CLI's name for each kind, and LinkedIn's result type. */\nexport const SEARCH_KINDS = {\n companies: 'COMPANIES',\n groups: 'GROUPS',\n events: 'EVENTS',\n courses: 'LEARNING',\n products: 'PRODUCTS',\n services: 'SERVICES',\n schools: 'SCHOOLS',\n} as const;\n\nexport type SearchKindName = keyof typeof SEARCH_KINDS;\n\nexport const SEARCH_PAGE = PEOPLE_PAGE;\n\nexport interface SearchQuery {\n kind: SearchKindName;\n keywords?: string;\n params: Record<string, string[]>;\n start: number;\n withFilters?: boolean;\n}\n\nexport function searchUrl(q: SearchQuery): string {\n return peopleSearchUrl({\n ...(q.keywords !== undefined ? { keywords: q.keywords } : {}),\n params: q.params,\n start: q.start,\n ...(q.withFilters === true ? { withFilters: true } : {}),\n kind: SEARCH_KINDS[q.kind],\n });\n}\n\n/** One result, in LinkedIn's own lines; see the table above for what each holds. */\nexport interface Found {\n /** The entity's own id: a company, group, event, course, product page or profile. */\n id: string;\n name: string;\n subtitle?: string;\n detail?: string;\n summary?: string;\n url?: string;\n verified?: boolean;\n}\n\ntype Node = Record<string, unknown>;\n\nconst text = (v: unknown): string | undefined => {\n const t = (v as { text?: unknown } | null | undefined)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim().replace(/\\s+/g, ' ') : undefined;\n};\n\n/** The id inside `urn:li:fsd_entityResultViewModel:(<urn>,SEARCH_SRP,DEFAULT)`. */\nfunction idOf(entityUrn: unknown): string | undefined {\n const inner = String(entityUrn ?? '').match(/\\((urn:li:[A-Za-z_]+:[^,)]+)/)?.[1];\n return inner?.split(':').pop();\n}\n\n/** The page's own address, without per-viewer tracking or claim tokens. */\nfunction cleanUrl(nav: unknown): string | undefined {\n if (typeof nav !== 'string' || !nav.startsWith('https://')) return undefined;\n return nav.split('?')[0];\n}\n\nfunction rowToFound(row: Node): Found | undefined {\n const id = idOf(row.entityUrn);\n const name = text(row.title);\n if (id === undefined || name === undefined) return undefined;\n const found: Found = { id, name };\n const fields: [keyof Found, string | undefined][] = [\n ['subtitle', text(row.primarySubtitle)],\n ['detail', text(row.secondarySubtitle)],\n ['summary', text(row.summary)],\n ['url', cleanUrl(row.navigationUrl)],\n ];\n for (const [k, v] of fields)\n if (v !== undefined) (found as unknown as Record<string, string>)[k] = v;\n if (JSON.stringify(row.badgeIcon ?? null).includes('VERIFIED')) found.verified = true;\n return found;\n}\n\nexport interface ResultsPage {\n ok: true;\n items: Found[];\n total?: number;\n claimed?: number;\n start: number;\n excluded: number;\n unknownTypes: Record<string, number>;\n}\n\nconst drift = (message: string): Failure => ({\n ok: false,\n code: 'SCHEMA_DRIFT',\n message,\n hint: 'the search response changed shape; re-capture it',\n});\n\nexport function parseResults(json: unknown): ResultsPage | Failure {\n const c: Clusters | undefined = clustersOf(json);\n if (c === undefined || !Array.isArray(c.elements))\n return drift('the search returned no result list');\n const included = (json as { included?: Node[] }).included ?? [];\n const { people: items, unknownTypes, excluded, unresolved } = readItems(c, included, rowToFound);\n const total = typeof c.paging?.total === 'number' ? c.paging.total : undefined;\n const start = typeof c.paging?.start === 'number' ? c.paging.start : 0;\n const claimedRaw = c.metadata?.totalResultCount;\n const claimed = typeof claimedRaw === 'number' ? claimedRaw : total;\n if (unresolved > 0 && items.length === 0)\n return drift(`${unresolved} results were listed but none could be read`);\n if (items.length === 0 && total !== undefined && total > start) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `LinkedIn claims ${total} results but returned none from ${start}`,\n hint: 'a failed fetch, not an empty search; do not report \"none\"',\n };\n }\n return {\n ok: true,\n items,\n ...(total !== undefined ? { total } : {}),\n ...(claimed !== undefined ? { claimed } : {}),\n start,\n excluded,\n unknownTypes,\n };\n}\n","// ─── My Network: connections, following, followers, pages, invitations ────────\n//\n// Captured 2026-10-14. The My Network page's lists come from the same Voyager\n// search as people (engine/people.ts), with origin `CurationHub`, intent\n// `MYNETWORK_CURATION_HUB`, no keywords (an empty one is a 400) and a result\n// type per list. Sent invitations are the older relationships resource.\n//\n// Opening My Network in the browser also clears the \"new invitations\" badge\n// and marks notifications seen (`addaClearUnseenInvitationsMutation`,\n// `addaMarkNotificationsSeen`). Those are separate calls; nothing here makes\n// them. Not covered: received invitations (none were pending to verify\n// against), newsletters (the hub answers that type with a server error), and\n// \"people you may know\" (an SDUI pager).\n\nimport { CONTRACTS } from './contracts.ts';\nimport { PEOPLE_PAGE, type Person, parsePeople, peopleSearchUrl } from './people.ts';\nimport type { Failure } from './sdui-form.ts';\nimport { type Found, parseResults } from './search.ts';\n\n/** The CLI's name for each hub list, and LinkedIn's result type. */\nexport const HUB = {\n connections: 'CONNECTIONS',\n following: 'PEOPLE_FOLLOW',\n followers: 'FOLLOWERS',\n pages: 'PAGES',\n events: 'EVENTS',\n groups: 'GROUPS',\n} as const;\n\nexport type HubList = keyof typeof HUB;\n\nconst PEOPLE_LISTS = new Set<HubList>(['connections', 'following', 'followers']);\n\nexport function hubUrl(list: HubList, start: number): string {\n return peopleSearchUrl({\n params: {},\n start,\n kind: HUB[list],\n origin: 'CurationHub',\n intent: 'MYNETWORK_CURATION_HUB',\n });\n}\n\nexport const HUB_PAGE = PEOPLE_PAGE;\n\nexport interface HubPage {\n ok: true;\n items: (Person | Found)[];\n total?: number;\n unknownTypes: Record<string, number>;\n}\n\n/** People lists read as people; pages, events and groups as generic results. */\nexport function parseHub(list: HubList, json: unknown): HubPage | Failure {\n if (PEOPLE_LISTS.has(list)) {\n const r = parsePeople(json);\n if (!r.ok) return r;\n return {\n ok: true,\n items: r.people,\n ...(r.total !== undefined ? { total: r.total } : {}),\n unknownTypes: r.unknownTypes,\n };\n }\n const r = parseResults(json);\n if (!r.ok) return r;\n return {\n ok: true,\n items: r.items,\n ...(r.total !== undefined ? { total: r.total } : {}),\n unknownTypes: r.unknownTypes,\n };\n}\n\n// ─── Sent invitations ─────────────────────────────────────────────────────────\n\nexport function sentInvitationsUrl(start: number, count = 10): string {\n const c = CONTRACTS.sentInvitations;\n if (c === undefined) throw new Error(\"the 'sentInvitations' contract is missing\");\n return `${c.path}?count=${count}&invitationType=CONNECTION&q=invitationType&start=${start}`;\n}\n\nexport interface SentInvitation {\n to: string;\n /** The invitee's profile id. */\n id?: string;\n headline?: string;\n url?: string;\n sent?: string;\n /** The note sent with it, if any. */\n note?: string;\n}\n\ntype Node = Record<string, unknown>;\n\nexport function parseSentInvitations(\n json: unknown,\n): { ok: true; invitations: SentInvitation[] } | Failure {\n const data = (json as { data?: Node } | null)?.data;\n const refs = data?.['*elements'] ?? data?.elements;\n if (!Array.isArray(refs))\n return { ok: false, code: 'SCHEMA_DRIFT', message: 'the sent invitations list was missing' };\n const included = (json as { included?: Node[] }).included ?? [];\n const byUrn = new Map<unknown, Node>(included.map((n) => [n.entityUrn, n]));\n const invitations: SentInvitation[] = [];\n for (const ref of refs as unknown[]) {\n const view = byUrn.get(ref);\n const inv =\n byUrn.get(view?.['*invitation']) ??\n included.find(\n (n) =>\n String(n.$type).endsWith('.Invitation') &&\n typeof ref === 'string' &&\n ref.endsWith(String(n.entityUrn)),\n );\n if (inv === undefined) continue;\n const who = byUrn.get(inv['*toMember']);\n const name = [who?.firstName, who?.lastName]\n .filter((x) => typeof x === 'string' && x !== '')\n .join(' ');\n const id = String(inv['*toMember'] ?? '')\n .split(':')\n .pop();\n const note =\n typeof inv.message === 'string'\n ? inv.message\n : (inv.message as { text?: unknown } | null)?.text;\n const out: SentInvitation = { to: name !== '' ? name : 'LinkedIn Member' };\n if (id) out.id = id;\n if (typeof who?.occupation === 'string') out.headline = who.occupation;\n if (typeof who?.publicIdentifier === 'string')\n out.url = `https://www.linkedin.com/in/${who.publicIdentifier}/`;\n if (typeof inv.sentTime === 'number') out.sent = new Date(inv.sentTime).toISOString();\n if (typeof note === 'string' && note.trim() !== '') out.note = note.trim();\n invitations.push(out);\n }\n if (refs.length > 0 && invitations.length === 0)\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: `${refs.length} invitations were listed but none were sent`,\n };\n return { ok: true, invitations };\n}\n","// ─── `lnrelay network [list]` ─────────────────────────────────────────────────\n//\n// The owner's My Network, read only; see engine/network.ts. With no list, the\n// count of each (one call each); with a list, its rows. Everything spends the\n// page budget. Nothing here clears a badge or marks anything seen.\n\nimport { createLiveClient } from '../engine/index.ts';\nimport {\n HUB,\n HUB_PAGE,\n type HubList,\n hubUrl,\n parseHub,\n parseSentInvitations,\n type SentInvitation,\n sentInvitationsUrl,\n} from '../engine/network.ts';\nimport type { Person } from '../engine/people.ts';\nimport type { Found } from '../engine/search.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line, metaOf, type PageFetch, type Paging, searchAll } from './paged.ts';\nimport { shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; json: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted GET. Injectable so tests send nothing. */\nexport type NetworkFetch = (url: string, spendClass: 'page') => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): NetworkFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('network', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, spendClass) => {\n const r = await client.request({ url, spendClass, operation: 'network' });\n return r.ok ? { ok: true, json: r.json } : r;\n };\n}\n\nexport interface NetworkRequest {\n limit: number;\n start?: number;\n}\n\nconst LISTS = [...Object.keys(HUB), 'invitations'];\nconst PAGING: Paging = { pageSize: HUB_PAGE, max: 1000 };\nconst INVITATIONS_PAGE = 10;\n\nfunction compactRow(r: Person | Found): string {\n const p = r as Person & Found;\n return line([p.id, p.name, p.headline ?? p.subtitle, p.location ?? p.detail, p.degree, p.url]);\n}\n\nasync function counts(get: NetworkFetch): Promise<{ counts: Record<string, number> } | Envelope> {\n const out: Record<string, number> = {};\n for (const list of Object.keys(HUB) as HubList[]) {\n const res = await get(hubUrl(list, 0), 'page');\n const page = res.ok ? parseHub(list, res.json) : res;\n if (!page.ok) return err('network', page.code, `${list}: ${page.message}`, page.hint);\n out[list] = page.total ?? page.items.length;\n }\n const res = await get(sentInvitationsUrl(0, INVITATIONS_PAGE), 'page');\n const inv = res.ok ? parseSentInvitations(res.json) : res;\n if (!inv.ok) return err('network', inv.code, `invitations: ${inv.message}`);\n // The resource gives no total: a full page means \"at least\".\n out.invitationsSent = inv.invitations.length;\n return { counts: out };\n}\n\nasync function invitations(\n get: NetworkFetch,\n req: NetworkRequest,\n opts: OutputOpts,\n): Promise<Envelope> {\n const all: SentInvitation[] = [];\n let exhausted = false;\n let stoppedBy: string | undefined;\n for (let start = req.start ?? 0; all.length < req.limit; start += INVITATIONS_PAGE) {\n const res = await get(sentInvitationsUrl(start, INVITATIONS_PAGE), 'page');\n const page = res.ok ? parseSentInvitations(res.json) : res;\n if (!page.ok) {\n if (all.length === 0) return err('network', page.code, page.message);\n stoppedBy = page.code;\n break;\n }\n all.push(...page.invitations.slice(0, req.limit - all.length));\n if (page.invitations.length < INVITATIONS_PAGE) {\n exhausted = true;\n break;\n }\n }\n return ok('network', {\n list: 'invitations',\n items: shape(all, opts, (i) =>\n line([i.id, i.to, i.headline, i.sent?.slice(0, 10), i.note, i.url]),\n ),\n meta: {\n state: exhausted && stoppedBy === undefined ? 'complete' : 'partial',\n operation: 'network invitations',\n returnedCount: all.length,\n ...(stoppedBy !== undefined ? { stoppedBy } : {}),\n },\n });\n}\n\nexport async function runNetwork(\n list: string | undefined,\n req: NetworkRequest,\n opts: OutputOpts = {},\n fetch?: NetworkFetch,\n): Promise<Envelope> {\n if (list !== undefined && !LISTS.includes(list)) {\n return err(\n 'network',\n 'INVALID_INPUT',\n `no list '${list}'`,\n `one of: ${LISTS.join(', ')} — or none, for the counts`,\n );\n }\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n\n if (list === undefined) {\n const c = await counts(get);\n if (!('counts' in c)) return c;\n return ok('network', { counts: c.counts, meta: { state: 'complete', operation: 'network' } });\n }\n if (list === 'invitations') return invitations(get, req, opts);\n\n const hub = list as HubList;\n const first = Math.max(0, req.start ?? 0);\n const fetchPage: PageFetch<Person | Found> = async (_keywords, start) => {\n const res = await get(hubUrl(hub, start), 'page');\n const page = res.ok ? parseHub(hub, res.json) : res;\n if (!page.ok) return page;\n return {\n ok: true,\n items: page.items,\n ...(page.total !== undefined ? { total: page.total } : {}),\n unknownTypes: page.unknownTypes,\n };\n };\n const merged = await searchAll(\n fetchPage,\n [undefined],\n first,\n Math.max(1, Math.min(req.limit, PAGING.max - first)),\n PAGING,\n );\n if (merged.rows.length === 0 && merged.failure !== undefined) {\n const f = merged.failure;\n return err('network', f.code, f.message, f.hint);\n }\n return ok('network', {\n list: hub,\n items: shape(merged.rows, opts, compactRow),\n meta: metaOf(`network ${hub}`, merged, true, first),\n });\n}\n","// ─── The owner's notifications ────────────────────────────────────────────────\n//\n// Probed 2026-10-29. The bell's list is a REST finder:\n//\n// voyagerIdentityDashNotificationCards?q=filterVanityName&count=N&start=S\n//\n// Each card is a node in `included`: a headline, optional sub-lines, `read`,\n// `publishedAt`, and where it goes (`cardAction.actionTarget`) and who or what\n// it is about (`headerImage.actionTarget`). Its kind is the first part of its\n// urn (FOLLOW_PAGE_HERO, …). `metadata.nextStart` is the next page; the last\n// page has none and an empty-section card instead. A page can hold fewer\n// cards than asked for (10 asked, 9 sent, next start 10), so paging follows\n// nextStart, not the count.\n//\n// Not read: the page's tabs (my posts, mentions, jobs). `filterVanityName`\n// is the finder's key, but `mentions` answered as `all`; the tab names are\n// unverified. Reading here never marks anything seen.\n\nimport { CONTRACTS } from './contracts.ts';\nimport type { Failure } from './sdui-form.ts';\n\ntype Node = Record<string, unknown>;\n\nexport function notificationsUrl(count: number, start: number): string {\n const c = CONTRACTS.notifications;\n if (c?.decorationId === undefined) throw new Error(\"the 'notifications' contract is missing\");\n return `${c.path}?decorationId=${c.decorationId}&q=filterVanityName&count=${count}&start=${start}`;\n}\n\nexport interface Notification {\n /** LinkedIn's own name for the kind of notification. */\n kind: string;\n text: string;\n /** Sub-lines, when the card has them. */\n detail?: string;\n /** ISO time it was published. */\n at?: string;\n read: boolean;\n /** Where the card goes. */\n url?: string;\n /** Who or what it is about: a profile, a company. */\n from?: string;\n}\n\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst textOf = (v: unknown) => {\n const t = (v as { text?: unknown } | null)?.text;\n return typeof t === 'string' && t.trim() !== '' ? t.trim() : undefined;\n};\nconst absolute = (v: unknown) =>\n typeof v === 'string' && v !== ''\n ? v.startsWith('/')\n ? `https://www.linkedin.com${v}`\n : v\n : undefined;\n\nfunction card(n: Node): Notification | undefined {\n const text = textOf(n.headline);\n if (text === undefined) return undefined;\n const kind = String(n.entityUrn ?? '').match(/fsd_notificationCard:\\(([^,]+),/)?.[1] ?? 'UNKNOWN';\n const detail = [n.subHeadline, n.contentPrimaryText, n.contentSecondaryText, n.kickerText]\n .map(textOf)\n .filter((t): t is string => t !== undefined)\n .join(' · ');\n const at = typeof n.publishedAt === 'number' ? new Date(n.publishedAt).toISOString() : undefined;\n const url = absolute((n.cardAction as Node | null)?.actionTarget);\n const from = absolute((n.headerImage as Node | null)?.actionTarget);\n return {\n kind,\n text,\n ...(detail !== '' ? { detail } : {}),\n ...(at !== undefined ? { at } : {}),\n read: n.read === true,\n ...(url !== undefined ? { url } : {}),\n ...(from !== undefined ? { from } : {}),\n };\n}\n\nexport function parseNotifications(\n json: unknown,\n): { ok: true; items: Notification[]; unseen?: number; next?: number } | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const data = root?.data;\n const listed = data?.['*elements'] ?? data?.elements;\n if (!Array.isArray(listed)) return drift('the notifications answer carried no card list');\n const byUrn = new Map((root?.included ?? []).map((n) => [n.entityUrn, n]));\n const items = listed.flatMap((u) => {\n const n = byUrn.get(u);\n const c = n === undefined ? undefined : card(n);\n return c === undefined ? [] : [c];\n });\n if (listed.length > 0 && items.length === 0)\n return drift(`${listed.length} notifications were listed but none could be read`);\n const meta = (data?.metadata ?? {}) as Node;\n return {\n ok: true,\n items,\n ...(typeof meta.numUnseen === 'number' ? { unseen: meta.numUnseen } : {}),\n ...(typeof meta.nextStart === 'number' ? { next: meta.nextStart } : {}),\n };\n}\n","// ─── `lnrelay notifications` ──────────────────────────────────────────────────\n//\n// The owner's notifications, newest first; see engine/notifications.ts. One\n// page call per 25, following LinkedIn's next start. Reading them here does\n// not mark them seen.\n\nimport { createLiveClient } from '../engine/index.ts';\nimport {\n type Notification,\n notificationsUrl,\n parseNotifications,\n} from '../engine/notifications.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope, FetchState } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; json: unknown }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted GET. Injectable so tests send nothing. */\nexport type NotificationsFetch = (url: string, spendClass: 'page') => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): NotificationsFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('notifications', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, spendClass) => {\n const r = await client.request({ url, spendClass, operation: 'notifications' });\n return r.ok ? { ok: true, json: r.json } : r;\n };\n}\n\nexport interface NotificationsRequest {\n limit: number;\n /** Only the ones not yet read. */\n unread?: boolean;\n}\n\nconst PAGE = 25;\n\nconst compactNotification = (n: Notification) =>\n line([n.read ? undefined : 'unread', n.at, n.kind, n.text, n.detail, n.url]);\n\nexport async function runNotifications(\n req: NotificationsRequest,\n opts: OutputOpts = {},\n fetch?: NotificationsFetch,\n): Promise<Envelope> {\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n const limit = Math.max(1, req.limit);\n const items: Notification[] = [];\n let unseen: number | undefined;\n let start: number | undefined = 0;\n let stoppedBy: string | undefined;\n while (start !== undefined && items.length < limit) {\n const res = await get(notificationsUrl(PAGE, start), 'page');\n const page = res.ok ? parseNotifications(res.json) : res;\n if (!page.ok) {\n if (items.length === 0 && start === 0)\n return err('notifications', page.code, page.message, page.hint);\n stoppedBy = page.code;\n break;\n }\n unseen ??= page.unseen;\n items.push(...page.items.filter((n) => req.unread !== true || !n.read));\n start = page.next !== undefined && page.next > start ? page.next : undefined;\n }\n const kept = items.slice(0, limit);\n const state: FetchState =\n stoppedBy !== undefined || (start !== undefined && kept.length === limit)\n ? 'partial'\n : 'complete';\n return ok('notifications', {\n ...(unseen !== undefined ? { unseen } : {}),\n items: shape(kept, opts, compactNotification),\n meta: {\n state,\n operation: 'notifications',\n returnedCount: kept.length,\n ...(stoppedBy !== undefined ? { stoppedBy } : {}),\n },\n });\n}\n","// ─── A profile's contact info ─────────────────────────────────────────────────\n//\n// Captured 2026-10-16. The profile page's \"Contact info\" link opens an SDUI\n// overlay, one POST naming the member by public id and name; the legacy\n// identity/profiles/<id>/profileContactInfo answers 410 Gone. The overlay is\n// a list of labelled fields, most wrapped in a tracking spec that names the\n// field (`contact-email`, `contact-website`, `contact-birthday`); \"Connected\n// since\" has none, so fields are read by tracking name where there is one\n// and by label otherwise. Labels are in the session's language. A Premium\n// upsell follows the fields and is cut off before reading.\n//\n// Seen with data: email, websites, birthday, connected since. Phone, address,\n// Twitter and messenger fields are read by the names the others use and stay\n// unverified until one comes with data; any other field passes through.\n\nimport type { Failure } from './sdui-form.ts';\n\nconst SCREEN = 'com.linkedin.sdui.flagshipnav.profile.ProfileContactDetailsOverlay';\nexport const CONTACT_INFO_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/navigation?screenId=${SCREEN}&sduiid=${SCREEN}`;\n\nexport function contactInfoBody(publicId: string, firstName: string, lastName: string) {\n return {\n clientArguments: {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload: {\n vanityName: publicId,\n givenName: firstName,\n familyName: lastName,\n isVanityNameResolved: true,\n },\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n states: [],\n screenId: SCREEN,\n knownTemplateIds: [],\n },\n isModal: true,\n };\n}\n\nexport interface ContactInfo {\n email?: string;\n phones?: { number: string; type?: string }[];\n websites?: { url: string; type?: string }[];\n twitter?: string[];\n address?: string;\n birthday?: string;\n connectedSince?: string;\n /** Labelled fields with no tracking name, by their label. */\n other?: Record<string, string>;\n [field: string]: unknown;\n}\n\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst unquote = (s: string) => JSON.parse(`\"${s}\"`) as string;\n\nconst LABEL = /\\[\"\\$\",\"p\",null,\\{\"className\":\"[^\"]*\",\"children\":\\[\"((?:[^\"\\\\]|\\\\.)+)\"\\]\\}\\]/g;\nconst VIEW = /\"viewName\":\"contact-([a-z-]+)\"/g;\nconst LINK = /\"urlValue\":\\{\"\\$case\":\"url\",\"url\":\"((?:[^\"\\\\]|\\\\.)+)\"/g;\nconst TEXT = /\"children\":\\[\"((?:[^\"\\\\$]|\\\\.)(?:[^\"\\\\]|\\\\.)*)\"\\]/g;\nconst TYPE = /\"\\(([^\"()]+)\\)\"/g;\n\ninterface Field {\n label: string;\n view?: string;\n links: string[];\n texts: string[];\n types: string[];\n}\n\n/** Where a link goes: past LinkedIn's safety redirect and a mailto/tel scheme. */\nfunction target(link: string): string {\n const url = unquote(link);\n const away = url.match(/\\/safety\\/go\\/?\\?url=([^&]+)/)?.[1];\n if (away !== undefined) return decodeURIComponent(away);\n return url.replace(/^(mailto|tel):/, '');\n}\n\nfunction fieldsOf(stream: string): Field[] {\n const start = stream.indexOf('profile-contact-info-details-view');\n const upsell = stream.indexOf('\"viewName\":\"premium-upsell-card\"', start);\n const region = stream.slice(start, upsell === -1 ? undefined : upsell);\n const labels = [...region.matchAll(LABEL)];\n const fields: Field[] = [];\n let before = 0;\n labels.forEach((m, i) => {\n const at = m.index ?? 0;\n const end = at + m[0].length;\n const seg = region.slice(end, labels[i + 1]?.index ?? region.length);\n const view = [...region.slice(before, at).matchAll(VIEW)].pop()?.[1];\n fields.push({\n label: unquote(m[1] as string).trim(),\n view,\n links: [...seg.matchAll(LINK)].map((l) => target(l[1] as string)),\n texts: [...seg.matchAll(TEXT)].map((t) => unquote(t[1] as string).trim()),\n types: [...seg.matchAll(TYPE)].map((t) => t[1] as string),\n });\n before = end;\n });\n return fields;\n}\n\nconst camel = (s: string) => s.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());\n\nfunction put(contact: ContactInfo, f: Field): void {\n const text = f.texts.join(', ');\n switch (f.view) {\n case 'your-profile':\n return; // `profile` already has the profile URL.\n case 'email':\n contact.email = f.links[0] ?? text;\n return;\n case 'website':\n contact.websites = [\n ...(contact.websites ?? []),\n ...f.links.map((url, i) => (f.types[i] ? { url, type: f.types[i] } : { url })),\n ];\n return;\n case 'phone':\n contact.phones = [\n ...(contact.phones ?? []),\n ...f.texts.map((number, i) => (f.types[i] ? { number, type: f.types[i] } : { number })),\n ];\n return;\n case 'twitter':\n contact.twitter = [...(contact.twitter ?? []), ...f.texts];\n return;\n case undefined:\n if (/^connected since$/i.test(f.label)) contact.connectedSince = text;\n else contact.other = { ...contact.other, [f.label]: text };\n return;\n default:\n contact[camel(f.view)] = text;\n }\n}\n\nexport function parseContactInfo(stream: string): { ok: true; contact: ContactInfo } | Failure {\n if (!stream.includes('profile-contact-info-details-view'))\n return drift('the contact info answer was not the contact info overlay');\n const fields = fieldsOf(stream);\n if (fields.length === 0) return drift('the contact info overlay had no fields');\n const contact: ContactInfo = {};\n for (const f of fields) put(contact, f);\n return { ok: true, contact };\n}\n","// ─── A profile in full ────────────────────────────────────────────────────────\n//\n// Probed 2026-10-16. The GraphQL profile projection behind the top card has\n// no name; the REST profile finder with the FullProfileWithEntities\n// decoration has the name, About and every section of the profile page:\n//\n// identity/dash/profiles?q=memberIdentity&memberIdentity=<public id>\n//\n// Each section is a collection (`*profileSkills` → `*elements` → nodes in\n// `included`), and the collections' order is the page's order; `included`\n// is in no particular order. The profile holds the first 10 position groups\n// (a company with its roles) and 20 skills. The rest of the experience pages\n// through identity/dash/profilePositionGroups; skills did not (400), so their\n// total is reported instead.\n//\n// Certifications, languages, projects, courses, organizations, patents and\n// test scores were empty in every profile read so far; they are read by the\n// names the other sections use and stay unverified until one comes with data.\n\nimport { CONTRACTS } from './contracts.ts';\nimport type { Failure } from './sdui-form.ts';\n\ntype Node = Record<string, unknown>;\n\nfunction contract(name: 'fullProfile' | 'profilePositions') {\n const c = CONTRACTS[name];\n if (c?.decorationId === undefined) throw new Error(`the '${name}' contract is missing`);\n return c as typeof c & { decorationId: string };\n}\n\nexport function fullProfileUrl(memberId: string): string {\n const c = contract('fullProfile');\n return (\n `${c.path}?q=memberIdentity&memberIdentity=${encodeURIComponent(memberId)}` +\n `&decorationId=${c.decorationId}`\n );\n}\n\n/** Position groups per call when reading the rest of the experience. */\nexport const POSITIONS_PAGE = 50;\n\nexport function positionsPageUrl(profileUrn: string, start: number): string {\n const c = contract('profilePositions');\n return (\n `${c.path}?q=viewee&profileUrn=${encodeURIComponent(profileUrn)}` +\n `&decorationId=${c.decorationId}&start=${start}&count=${POSITIONS_PAGE}`\n );\n}\n\n// ─── Rows ─────────────────────────────────────────────────────────────────────\n\nexport interface Role {\n title?: string;\n company?: string;\n /** What `company`, `people --company` and `jobs --company` take. */\n companyId?: string;\n employmentType?: string;\n location?: string;\n /** \"2017-08\", or \"2017\" when the month is not given. */\n start?: string;\n end?: string;\n current?: boolean;\n description?: string;\n}\n\nexport interface School {\n school?: string;\n schoolId?: string;\n degree?: string;\n field?: string;\n start?: string;\n end?: string;\n grade?: string;\n activities?: string;\n description?: string;\n}\n\nexport type Entry = Record<string, string | boolean | undefined>;\n\nexport interface FullProfile {\n /** The profile id: what `messages`, `people --connection-of` take. */\n id: string;\n urn: string;\n publicId?: string;\n name?: string;\n firstName?: string;\n lastName?: string;\n headline?: string;\n url?: string;\n location?: string;\n industry?: string;\n about?: string;\n /** The top card, as `profile` always gave it: the newest role and school. */\n title?: string;\n company?: string;\n school?: string;\n premium?: boolean;\n influencer?: boolean;\n creator?: boolean;\n experience?: Role[];\n education?: School[];\n skills?: string[];\n certifications?: Entry[];\n languages?: Entry[];\n honors?: Entry[];\n publications?: Entry[];\n projects?: Entry[];\n volunteering?: Entry[];\n courses?: Entry[];\n organizations?: Entry[];\n patents?: Entry[];\n testScores?: Entry[];\n /** Sections LinkedIn holds more of than it sent: shown and total. */\n counts?: Record<string, { shown: number; total: number }>;\n}\n\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst str = (v: unknown) =>\n typeof v === 'string' && v.trim() !== '' && v.trim() !== '-' ? v.trim() : undefined;\nconst idOf = (urn: unknown) => String(urn ?? '').match(/:(\\d+)$/)?.[1];\n\nfunction defined<T extends object>(obj: T): T {\n for (const k of Object.keys(obj) as (keyof T)[]) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\n/** {year, month, day} as \"2017\", \"2017-08\" or \"2017-08-14\". */\nfunction date(v: unknown): string | undefined {\n const d = v as { year?: unknown; month?: unknown; day?: unknown } | null | undefined;\n if (typeof d?.year !== 'number') return undefined;\n const two = (n: number) => String(n).padStart(2, '0');\n if (typeof d.month !== 'number') return String(d.year);\n return typeof d.day === 'number'\n ? `${d.year}-${two(d.month)}-${two(d.day)}`\n : `${d.year}-${two(d.month)}`;\n}\n\nfunction range(v: unknown): { start?: string; end?: string; current?: boolean } {\n const r = v as { start?: unknown; end?: unknown } | null | undefined;\n const start = date(r?.start);\n const end = date(r?.end);\n return defined({\n start,\n end,\n current: start !== undefined && end === undefined ? true : undefined,\n });\n}\n\nclass Index {\n readonly byUrn: Map<unknown, Node>;\n constructor(included: Node[]) {\n this.byUrn = new Map(included.map((n) => [n.entityUrn, n]));\n }\n get(urn: unknown): Node | undefined {\n return typeof urn === 'string' ? this.byUrn.get(urn) : undefined;\n }\n /** The node as a list of one, or none. */\n list(urn: unknown): Node[] {\n const n = this.get(urn);\n return n === undefined ? [] : [n];\n }\n /** A collection's nodes, in its order, and how many LinkedIn says there are. */\n collection(urn: unknown): { nodes: Node[]; total?: number } {\n const c = this.get(urn);\n const refs = Array.isArray(c?.['*elements']) ? (c?.['*elements'] as unknown[]) : [];\n const nodes = refs.flatMap((r): Node[] => this.list(r));\n const total = (c?.paging as { total?: unknown } | undefined)?.total;\n return typeof total === 'number' ? { nodes, total } : { nodes };\n }\n}\n\nfunction role(p: Node, group: Node | undefined, ix: Index): Role {\n const companyUrn = p.companyUrn ?? group?.companyUrn;\n return defined({\n title: str(p.title),\n company: str(p.companyName) ?? str(group?.companyName),\n companyId: idOf(companyUrn),\n employmentType: str(ix.get(p['*employmentType'])?.name),\n location: str(p.locationName) ?? str(p.geoLocationName),\n ...range(p.dateRange),\n description: str(p.description),\n });\n}\n\n/** Position groups (a company and its roles) as one list of roles, in order. */\nfunction rolesOf(groups: Node[], ix: Index): Role[] {\n return groups.flatMap((g) => {\n const inGroup = ix.collection(g['*profilePositionInPositionGroup']).nodes;\n return inGroup.map((p) => role(p, g, ix));\n });\n}\n\nfunction school(e: Node): School {\n return defined({\n school: str(e.schoolName),\n schoolId: idOf(e.schoolUrn),\n degree: str(e.degreeName),\n field: str(e.fieldOfStudy),\n ...range(e.dateRange),\n grade: str(e.grade),\n activities: str(e.activities),\n description: str(e.description),\n });\n}\n\n/** The fields the other sections use, read off any section's node. */\nfunction entry(n: Node): Entry {\n const proficiency = str(n.proficiency);\n return defined({\n name: str(n.name),\n title: str(n.title),\n role: str(n.role),\n organization: str(n.companyName),\n authority: str(n.authority),\n issuer: str(n.issuer),\n publisher: str(n.publisher),\n proficiency: proficiency?.toLowerCase().replace(/_/g, ' '),\n number: str(n.number) ?? str(n.licenseNumber) ?? str(n.patentNumber),\n score: str(n.score),\n cause: str(n.cause)?.toLowerCase().replace(/_/g, ' '),\n ...range(n.dateRange),\n issued: date(n.issuedOn),\n published: date(n.publishedOn),\n url: str(n.url),\n description: str(n.description),\n });\n}\n\nconst SECTIONS = {\n certifications: '*profileCertifications',\n languages: '*profileLanguages',\n honors: '*profileHonors',\n publications: '*profilePublications',\n projects: '*profileProjects',\n volunteering: '*profileVolunteerExperiences',\n courses: '*profileCourses',\n organizations: '*profileOrganizations',\n patents: '*profilePatents',\n testScores: '*profileTestScores',\n} as const;\n\nconst some = <T>(xs: T[]) => (xs.length > 0 ? xs : undefined);\n\nexport function parseFullProfile(json: unknown): { ok: true; profile: FullProfile } | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const listed = root?.data?.['*elements'];\n if (!Array.isArray(listed)) return drift('the profile answer carried no profile list');\n if (listed.length === 0)\n return { ok: false, code: 'NOT_FOUND', message: 'no profile has that id on LinkedIn' };\n const ix = new Index(root?.included ?? []);\n const p = ix.get(listed[0]);\n const urn = typeof p?.entityUrn === 'string' ? p.entityUrn : undefined;\n if (p === undefined || urn === undefined) return drift('the profile was listed but not sent');\n\n const counts: Record<string, { shown: number; total: number }> = {};\n const count = (key: string, shown: number, total: number | undefined) => {\n if (total !== undefined && total > shown) counts[key] = { shown, total };\n };\n const groups = ix.collection(p['*profilePositionGroups']);\n count('experience', groups.nodes.length, groups.total);\n const experience = rolesOf(groups.nodes, ix);\n const schools = ix.collection(p['*profileEducations']);\n const education = schools.nodes.map(school);\n const skillNodes = ix.collection(p['*profileSkills']);\n count('skills', skillNodes.nodes.length, skillNodes.total);\n const skills = skillNodes.nodes.flatMap((s) => str(s.name) ?? []);\n\n const sections: Partial<Record<keyof typeof SECTIONS, Entry[]>> = {};\n for (const [key, field] of Object.entries(SECTIONS) as [keyof typeof SECTIONS, string][]) {\n const c = ix.collection(p[field]);\n count(key, c.nodes.length, c.total);\n const rows = c.nodes.map(entry);\n if (rows.length > 0) sections[key] = rows;\n }\n\n const publicId = str(p.publicIdentifier);\n const name = [str(p.firstName), str(p.lastName)].filter(Boolean).join(' ');\n const geo = ix.get((p.geoLocation as Node | undefined)?.['*geo']);\n const bool = (v: unknown) => (v === true ? true : undefined);\n return {\n ok: true,\n profile: defined({\n id: urn.split(':').pop() as string,\n urn,\n publicId,\n name: name === '' ? undefined : name,\n firstName: str(p.firstName),\n lastName: str(p.lastName),\n headline: str(p.headline),\n url: publicId === undefined ? undefined : `https://www.linkedin.com/in/${publicId}/`,\n location: str(geo?.defaultLocalizedName),\n industry: str(ix.get(p['*industry'])?.name),\n about: str(p.summary),\n title: experience[0]?.title,\n company: experience[0]?.company,\n school: education[0]?.school,\n premium: bool(p.premium),\n influencer: bool(p.influencer),\n creator: bool(p.creator),\n experience: some(experience),\n education: some(education),\n skills: some(skills),\n ...sections,\n counts: Object.keys(counts).length > 0 ? counts : undefined,\n }),\n };\n}\n\n/** The rest of the experience: more position groups, read as the profile reads them. */\nexport function parsePositionsPage(\n json: unknown,\n): { ok: true; experience: Role[]; groups: number; total?: number } | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const refs = root?.data?.['*elements'];\n if (!Array.isArray(refs)) return drift('the experience page carried no position groups');\n const ix = new Index(root?.included ?? []);\n const groups = refs.flatMap((r): Node[] => ix.list(r));\n if (refs.length > 0 && groups.length === 0)\n return drift(`${refs.length} position groups were listed but none sent`);\n const total = (root?.data?.paging as { total?: unknown } | undefined)?.total;\n return {\n ok: true,\n experience: rolesOf(groups, ix),\n groups: groups.length,\n ...(typeof total === 'number' ? { total } : {}),\n };\n}\n","// ─── A profile's recommendations ──────────────────────────────────────────────\n//\n// Captured 2026-10-29 from /in/<id>/details/recommendations/. The full profile\n// carries none; the details page draws them from a pager,\n// `pagers.profile.details.recommendations`, with a payload the profile read\n// already has: `{type: Received|Given, vanityName, profileId, start, count}`.\n//\n// Each recommendation is a header row (the recommender: their name, headline\n// and profile URL as the loading states it sets on click, their degree, and\n// the date-and-relationship line) and the text beside it, in fragments, some\n// in rows of their own. The first sits inline in the page's root row with\n// the others referenced after it; each other one has its own row. A\n// recommendation's text is what lies between its header and the next one's.\n// The date line comes in the session's language and is not split.\n\nimport { Rows } from './posts.ts';\nimport type { Failure } from './sdui-form.ts';\n\nconst PAGER = 'com.linkedin.sdui.pagers.profile.details.recommendations';\nconst SCREEN = 'com.linkedin.sdui.flagshipnav.profile.ProfileRecommendationDetails';\nexport const RECOMMENDATIONS_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/pagination?sduiid=${PAGER}`;\nexport const RECOMMENDATIONS_PAGE = 15;\n\nexport type RecommendationKind = 'received' | 'given';\n\nexport function recommendationsBody(\n kind: RecommendationKind,\n vanityName: string,\n profileId: string,\n start: number,\n) {\n const args = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload: {\n type: kind === 'received' ? 'Received' : 'Given',\n vanityName,\n profileId,\n start,\n detailScreenTabIndex: kind === 'received' ? '0' : '1',\n count: RECOMMENDATIONS_PAGE,\n },\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n return {\n pagerId: PAGER,\n clientArguments: { ...args, states: [], screenId: SCREEN, knownTemplateIds: [] },\n paginationRequest: {\n $type: 'proto.sdui.actions.requests.PaginationRequest',\n pagerId: PAGER,\n retryCount: 2,\n requestedArguments: args,\n },\n };\n}\n\nexport interface Recommendation {\n /** The recommender, or for given ones, the person recommended. */\n name: string;\n url?: string;\n headline?: string;\n degree?: string;\n /** When, and how they worked together, as LinkedIn words it. */\n context?: string;\n text: string;\n}\n\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst unquote = (s: string) => JSON.parse(`\"${s}\"`) as string;\nconst STR = '((?:[^\"\\\\\\\\]|\\\\\\\\.)+)';\nconst loading = (id: string) =>\n new RegExp(\n `\"id\":\"${id}\"\\\\}\\\\},\"namespace\":\"LoadingNamespace\"\\\\},\"value\":\\\\{\"\\\\$case\":\"stringValue\",\"stringValue\":\"${STR}\"`,\n );\nconst NAME = loading('profile_name_loading_state');\nconst HEADLINE = loading('profile_headline_loading_state');\nconst PROFILE_URL = /\"url\":\"(https:\\/\\/www\\.linkedin\\.com\\/in\\/[^\"]+)\"/;\nconst TEXT = /\"children\":\\[\"((?:[^\"\\\\$]|\\\\.)(?:[^\"\\\\]|\\\\.)*)\"\\]/g;\nconst FRAGMENT =\n /\\[\"\\$\",\"\\$9\",\"\\d+\",\\{\"children\":\\[(?:null|\\[\"\\$\",\"br\",null,\\{\\}\\]),\"((?:[^\"\\\\]|\\\\.)*)\"\\]/g;\nconst REF = /\"\\$L([0-9a-f]+)\"/g;\n/** A row referenced whole: lazily (`$L`) or as its value, as a long text is (`$18`). */\nconst ANY_REF = /\"\\$L?([0-9a-f]+)\"/g;\n\n/** The recommender, from their header row and what it references. */\nfunction header(rows: Rows, id: string) {\n const row = rows.byId.get(id) ?? '';\n const name = row.match(NAME)?.[1];\n if (name === undefined) return undefined;\n const headline = row.match(HEADLINE)?.[1];\n const all = rows\n .reach(id)\n .map((r) => rows.byId.get(r) ?? '')\n .join('\\n');\n const texts = [...all.matchAll(TEXT)].map((m) => unquote(m[1] as string).trim());\n const degree = texts.find((t) => t.startsWith('·'));\n const shown = new Set([unquote(name), headline === undefined ? '' : unquote(headline)]);\n const context = texts.filter((t) => t !== degree && !shown.has(t)).pop();\n const url = row.match(PROFILE_URL)?.[1];\n return {\n name: unquote(name).trim(),\n ...(url !== undefined ? { url } : {}),\n ...(headline !== undefined ? { headline: unquote(headline).trim() } : {}),\n ...(degree !== undefined ? { degree: degree.replace(/^·\\s*/, '') } : {}),\n ...(context !== undefined ? { context } : {}),\n };\n}\n\n/**\n * A stretch of a row with its text written in, so it reads in order: fragment\n * rows inlined, and a text row (a long recommendation) as the string it is.\n */\nfunction inlined(rows: Rows, segment: string, depth = 0): string {\n if (depth > 3) return segment;\n return segment.replace(ANY_REF, (ref, id: string) => {\n const row = rows.byId.get(id);\n if (row === undefined) return ref;\n if (rows.isText(id)) return JSON.stringify(row);\n return row.startsWith('[\"$\",\"$9\"') ? inlined(rows, row, depth + 1) : ref;\n });\n}\n\n/** The text: its fragments, or failing those its plain text lines. */\nfunction bodyOf(segment: string): string {\n const fragments = [...segment.matchAll(FRAGMENT)].map((m) => unquote(m[1] as string));\n const lines =\n fragments.length > 0\n ? fragments\n : [...segment.matchAll(TEXT)].map((m) => unquote(m[1] as string));\n return lines\n .map((l) => l.replace(/\\r/g, '').trimEnd())\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n\nexport function parseRecommendations(\n stream: string,\n): { ok: true; items: Recommendation[] } | Failure {\n if (!stream.includes('isPartialPage') && !stream.includes(PAGER))\n return drift('the recommendations answer was not the recommendations list');\n const rows = new Rows(stream);\n const headers = [...rows.byId]\n .filter(([, row]) => NAME.test(row) && !row.startsWith('[[\"$\"'))\n .map(([id]) => id);\n const heads = new Set(headers);\n // Where each header sits: the row that references it, and from where.\n const placed = headers.flatMap((h) => {\n for (const [id, row] of rows.byId) {\n const at = row.indexOf(`\"$L${h}\"`);\n if (at !== -1) return [{ h, row: id, at }];\n }\n return [];\n });\n // Rows that hold a header: an item's text stops where the next item starts.\n const holders = new Set(placed.map((p) => p.row));\n const items: Recommendation[] = [];\n for (const p of placed) {\n const row = rows.byId.get(p.row) ?? '';\n let end = row.length;\n for (const m of row.slice(p.at + 1).matchAll(REF)) {\n const id = m[1] as string;\n if (heads.has(id) || (holders.has(id) && id !== p.row)) {\n end = p.at + 1 + (m.index ?? 0);\n break;\n }\n }\n const who = header(rows, p.h);\n const text = bodyOf(inlined(rows, row.slice(p.at, end)));\n if (who !== undefined && text !== '') items.push({ ...who, text });\n }\n if (headers.length > 0 && items.length === 0)\n return drift(`${headers.length} recommendations were shown but none could be read`);\n return { ok: true, items };\n}\n","// ─── Editing the profile ──────────────────────────────────────────────────────\n//\n// Profile edits are SDUI forms. Voyager's partial update on\n// `identity/dash/profiles` answers 400 (mguttmann/linkedin-internal-api), and\n// the web client saves through `saveProfileIntroForm` / `saveProfileAboutForm`.\n//\n// The intro save sends the WHOLE form back — name, location, current\n// position, education, industry, website — not just the field that changed.\n// A body built by hand would have to know every one of those, and getting one\n// wrong moves the owner to another city. So, as with the comment menu\n// (sdui-menu.ts), nothing here is hand-built: the form is opened the way the\n// browser opens it, and the server's own save action and initial values are\n// sent back with exactly one value replaced. If the form changes shape, the\n// read changes with it.\n//\n// Captured 2026-10-13 by editing each field by one character in the browser\n// and reverting; tests/sdui-profile.test.ts rebuilds those saves byte-for-byte\n// from the form reads.\n\nimport type { Client } from './client.ts';\nimport {\n type Failure,\n findRequest,\n keysOf,\n type Model,\n type ModelValue,\n navBody,\n type RequestArgs,\n readModel,\n requestBody,\n responseErrors,\n wireStates,\n} from './sdui-form.ts';\n\nexport const NAV_URL = 'https://www.linkedin.com/flagship-web/rsc-action/actions/navigation';\nexport const ACTION_URL = 'https://www.linkedin.com/flagship-web/rsc-action/actions/server-request';\n\nexport interface ProfileField {\n name: 'headline' | 'about';\n /** The form's SDUI screen. */\n screen: string;\n /** The save action the form carries. */\n save: string;\n /** The save payload's property that binds this field's value. */\n binding: string;\n maxLength: number;\n}\n\nexport const PROFILE_FIELDS = {\n headline: {\n name: 'headline',\n screen: 'com.linkedin.sdui.flagshipnav.profile.ProfileEditIntroForm',\n save: 'com.linkedin.sdui.requests.profile.saveProfileIntroForm',\n binding: 'headline',\n // The web form refuses more (\"Exceeded maximum length of 220 characters\").\n maxLength: 220,\n },\n about: {\n name: 'about',\n screen: 'com.linkedin.sdui.flagshipnav.profile.ProfileAboutForm',\n save: 'com.linkedin.sdui.requests.profile.saveProfileAboutForm',\n binding: 'about',\n maxLength: 2600,\n },\n} as const satisfies Record<string, ProfileField>;\n\n/** Open a form as the browser does. A read, though it is issued as a POST. */\nexport function formNavBody(screen: string, vanityName: string) {\n return navBody(screen, { vanityName, isVanityNameResolved: true });\n}\n\nexport interface ProfileForm {\n ok: true;\n /** The save action's arguments, verbatim: which states it reads, and its payload. */\n args: RequestArgs;\n states: Model;\n screen: string;\n save: string;\n}\n\nexport const drift = (message: string): Failure => ({\n ok: false,\n code: 'SCHEMA_DRIFT',\n message,\n hint: 'Re-capture the profile form with scripts/observe-write.ts (edit one character, then revert).',\n});\n\nexport function readForm(stream: string, field: ProfileField): ProfileForm | Failure {\n const states = readModel(stream);\n if (states === null) return drift('the profile form carried no initial values');\n const args = findRequest(stream, field.save);\n if (args === null)\n return drift(`the profile form carried no ${field.save.split('.').pop()} action`);\n return { ok: true, args, states, screen: field.screen, save: field.save };\n}\n\n/** The state key a payload property is bound to, e.g. headline → headlineIntroForm. */\nfunction boundKey(form: ProfileForm, property: string): string | undefined {\n const ref = form.args.payload[property] as { key?: string } | undefined;\n return ref?.key;\n}\n\nexport function currentValue(form: ProfileForm, field: ProfileField): string | undefined {\n const key = boundKey(form, field.binding);\n const v = key === undefined ? undefined : form.states.get(key)?.value;\n return typeof v === 'string' ? v : undefined;\n}\n\n/**\n * The About save carries the top-skills list as an expression over a\n * client-side collection, which starts as `initialSkills` and is sent unchanged\n * when skills are not touched.\n */\nfunction topSkills(form: ProfileForm) {\n return (key: string): { ok: true; value: unknown } | Failure | undefined => {\n if (!key.endsWith('ReorderableSkillsFormBindingsskillIdsBinding')) return undefined;\n const initial = [...form.states.entries()].find(([k]) => k.startsWith('initialSkills'))?.[1];\n if (initial === undefined) return drift('the About form carried no initial top skills');\n // Only the empty list has been seen on the wire. Sending a guessed list could\n // clear the owner's top skills, so a non-empty one is refused until observed.\n if (!Array.isArray(initial.value) || initial.value.length > 0) {\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: 'your About section has top skills, and saving it with them has not been verified',\n hint: 'Edit About in the browser for now; nothing was changed.',\n };\n }\n return { ok: true, value: [] };\n };\n}\n\n/** The save the browser would send after the owner changed this one field. */\nexport function saveBody(\n form: ProfileForm,\n field: ProfileField,\n value: string,\n): { ok: true; body: Record<string, unknown> } | Failure {\n if (value.length > field.maxLength) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `the ${field.name} is ${value.length} characters; LinkedIn allows ${field.maxLength}`,\n };\n }\n const target = boundKey(form, field.binding);\n const current = target === undefined ? undefined : form.states.get(target);\n if (target === undefined || current === undefined) {\n return drift(`the profile form has no ${field.name} field`);\n }\n const model: Model = new Map(form.states);\n model.set(target, { ...(current as ModelValue), value });\n const states = wireStates(keysOf(form.args), model, topSkills(form));\n if (!Array.isArray(states)) return states;\n return { ok: true, body: requestBody(form.save, form.args, states, form.screen) };\n}\n\n/** Open the form for a field. */\nexport async function fetchProfileForm(\n field: ProfileField,\n vanityName: string,\n client: Client,\n): Promise<ProfileForm | Failure> {\n const stream = await openForm(\n field.screen,\n { vanityName, isVanityNameResolved: true },\n client,\n `profile-${field.name}-form`,\n );\n return typeof stream === 'string' ? readForm(stream, field) : stream;\n}\n\n/** POST a navigation and hand back the raw stream. */\nexport async function openForm(\n screen: string,\n payload: Record<string, unknown>,\n client: Client,\n operation: string,\n): Promise<string | Failure> {\n const result = await client.request({\n url: `${NAV_URL}?screenId=${screen}&sduiid=${screen}`,\n method: 'POST',\n body: navBody(screen, payload),\n spendClass: 'page',\n operation,\n });\n if (!result.ok) {\n const out: Failure = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n return (result.classification as { raw?: string }).raw ?? '';\n}\n\n/** POST a server action; the raw stream back, or why it failed. A 200 can carry errors. */\nexport async function sendAction(\n requestId: string,\n body: unknown,\n client: Client,\n operation: string,\n spendClass: 'write' | 'page' = 'write',\n): Promise<string | Failure> {\n const result = await client.request({\n url: `${ACTION_URL}?sduiid=${requestId}`,\n method: 'POST',\n body,\n spendClass,\n operation,\n });\n if (!result.ok) {\n const out: Failure = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n const raw = (result.classification as { raw?: string }).raw ?? '';\n const errors = responseErrors(raw);\n if (errors !== null) {\n return { ok: false, code: 'INVALID_INPUT', message: `LinkedIn refused it: ${errors}` };\n }\n return raw;\n}\n\n/** Send a save built by `saveBody`. */\nexport async function sendProfileSave(\n form: ProfileForm,\n body: Record<string, unknown>,\n client: Client,\n): Promise<{ ok: true } | Failure> {\n const r = await sendAction(form.save, body, client, 'profile-save');\n return typeof r === 'string' ? { ok: true } : r;\n}\n","// ─── Skills: listing, adding and removing ─────────────────────────────────────\n//\n// Captured 2026-10-14 by adding a free-text test skill in the browser. Unlike\n// a role, the add form carries its save (`saveProfileSkillForm`) directly; an\n// existing skill's form carries `deleteProfileSkillForm`. The list is a pager\n// (`pagers.profile.details.skills`) whose payload the Skills screen hands out.\n// A skill is added on its own: no links to roles, schools or projects.\n\nimport type { Client } from './client.ts';\nimport { Rows } from './posts.ts';\nimport {\n balanced,\n type Failure,\n findRequest,\n keysOf,\n type Model,\n type RequestArgs,\n readModel,\n requestBody,\n wireStates,\n} from './sdui-form.ts';\nimport { drift, openForm, sendAction } from './sdui-profile.ts';\n\nexport const SKILL = {\n addScreen: 'com.linkedin.sdui.flagshipnav.profile.ProfileSkillAddForm',\n editScreen: 'com.linkedin.sdui.flagshipnav.profile.ProfileSkillDetailsEditForm',\n listScreen: 'com.linkedin.sdui.flagshipnav.profile.ProfileSkillDetails',\n pager: 'com.linkedin.sdui.pagers.profile.details.skills',\n save: 'com.linkedin.sdui.requests.profile.saveProfileSkillForm',\n delete: 'com.linkedin.sdui.requests.profile.deleteProfileSkillForm',\n} as const;\n\nexport interface Skill {\n skillId: string;\n /** Null when the name could not be paired with its row for certain. */\n name: string | null;\n /** What the list opens this skill's form with. */\n payload: Record<string, unknown>;\n}\n\nconst EDIT_NAV = `{\"$type\":\"proto.sdui.actions.core.NavigateToScreen\",\"screenId\":\"${SKILL.editScreen}\"`;\nconst TEXT = /\"children\":\\[\"((?:[^\"\\\\]|\\\\.)*)\"\\]/g;\n\n/**\n * One page of skills. Each row's name is the single text node between the\n * previous row's edit action and its own; any other count leaves it null.\n */\nexport function skillsFromPage(stream: string): { ok: true; skills: Skill[] } | Failure {\n if (\n !stream.includes(SKILL.pager) &&\n !stream.includes(EDIT_NAV) &&\n !stream.includes('isPartialPage')\n ) {\n return drift('the skills page could not be read');\n }\n const skills: Skill[] = [];\n let from = 0;\n let i = 0;\n for (;;) {\n i = stream.indexOf(EDIT_NAV, i);\n if (i === -1) break;\n const text = balanced(stream, i);\n const end = i;\n i += EDIT_NAV.length;\n if (text === null) continue;\n const payload = (\n JSON.parse(text) as { requestedArguments?: { payload?: Record<string, unknown> } }\n ).requestedArguments?.payload;\n const id = payload?.skillId;\n if (typeof id !== 'string' || payload === undefined || skills.some((s) => s.skillId === id))\n continue;\n const names = [...stream.slice(from, end).matchAll(TEXT)].map(\n (m) => JSON.parse(`\"${m[1]}\"`) as string,\n );\n skills.push({ skillId: id, name: names.length === 1 ? (names[0] ?? null) : null, payload });\n from = end + text.length;\n }\n return { ok: true, skills };\n}\n\n// ─── Anyone's skills, by name ─────────────────────────────────────────────────\n//\n// Probed 2026-10-29 on another member's profile. Without edit actions the rows\n// are found by their component, `com.linkedin.sdui.profile.skill(<id>, N)`,\n// whose `initialContent` names the row that draws it; the skill's name is\n// that content's medium bold text. The full profile holds 20 skills; this\n// pager holds all of them, 10 a page.\n\nconst SKILL_COMPONENT =\n /\"componentKey\":\"com\\.linkedin\\.sdui\\.profile\\.skill\\([^)]+\\)\",\"children\":\\[\"\\$\",\"\\$L[0-9a-f]+\",\"[^\"]+\",\\{\"componentKey\":\"[^\"]+\",\"initialContent\":\"\\$L([0-9a-f]+)\"/g;\nconst SKILL_NAME =\n /\"fontSize\":\"medium\",\"fontStyle\":\"normal\",\"fontWeight\":\"bold\",\"lineHeight\":\"[^\"]*\",\"textAlign\":\"[^\"]*\",\"children\":\\[\"((?:[^\"\\\\]|\\\\.)+)\"\\]/;\n\n/** Each skill on a page, in order, by name. A row whose name cannot be found is left out. */\nexport function skillNamesOf(stream: string): string[] {\n const rows = new Rows(stream);\n return [...stream.matchAll(SKILL_COMPONENT)].flatMap((m) => {\n const name = rows\n .reach(m[1] as string)\n .map((r) => rows.byId.get(r)?.match(SKILL_NAME)?.[1])\n .find((n) => n !== undefined);\n return name === undefined ? [] : [JSON.parse(`\"${name}\"`) as string];\n });\n}\n\n/** How many skill rows a page draws, read or not. */\nexport function skillRowsOf(stream: string): number {\n return [...stream.matchAll(SKILL_COMPONENT)].length;\n}\n\n/** The \"All\" filter's first-page request, as the Skills screen hands it out. */\nexport function listPayloadOf(screen: string): Record<string, unknown> | null {\n const at = screen.indexOf('\"filter\":\"ProfileSkillCategory_ALL\"');\n const open = at === -1 ? -1 : screen.lastIndexOf('\"payload\":{', at);\n const text = open === -1 ? null : balanced(screen, open + '\"payload\":'.length);\n return text === null ? null : (JSON.parse(text) as Record<string, unknown>);\n}\n\n/** The pager request for the page starting at `start`, from the screen's own payload. */\nexport function pagerFrom(payload: Record<string, unknown>, start: number) {\n const args = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [],\n payload: { ...payload, start },\n requestMetadata: { $type: 'proto.sdui.common.RequestMetadata' },\n };\n return {\n pagerId: SKILL.pager,\n clientArguments: { ...args, states: [], screenId: SKILL.listScreen, knownTemplateIds: [] },\n paginationRequest: {\n $type: 'proto.sdui.actions.requests.PaginationRequest',\n pagerId: SKILL.pager,\n retryCount: 0,\n requestedArguments: args,\n },\n };\n}\n\nexport interface SkillForm {\n ok: true;\n model: Model;\n save: RequestArgs | null;\n del: RequestArgs | null;\n screen: string;\n}\n\nexport function readSkillForm(stream: string): SkillForm | Failure {\n const model = readModel(stream);\n if (model === null) return drift('the skill form carried no initial values');\n const save = findRequest(stream, SKILL.save);\n const del = findRequest(stream, SKILL.delete);\n if (save === null && del === null)\n return drift('the skill form carried neither a save nor a delete');\n return { ok: true, model, save, del, screen: del === null ? SKILL.addScreen : SKILL.editScreen };\n}\n\nconst nameKey = (model: Model) =>\n [...model.keys()].find((k) => k.startsWith('addSkillsTypeaheadSkillName'));\n\nexport function skillNameOf(form: SkillForm): string | null {\n const key = nameKey(form.model);\n const v = key === undefined ? undefined : form.model.get(key)?.value;\n return typeof v === 'string' ? v : null;\n}\n\n/** The add, as typed free text: no catalogue id, linked to nothing. */\nexport function addSkillBody(form: SkillForm, name: string): { ok: true; body: unknown } | Failure {\n if (name.trim() === '')\n return { ok: false, code: 'INVALID_INPUT', message: 'a skill needs a name' };\n if (form.save === null) return drift('this form has no save action (it is not the add form)');\n const key = nameKey(form.model);\n const current = key === undefined ? undefined : form.model.get(key);\n if (key === undefined || current === undefined) return drift('the skill form has no name field');\n const model: Model = new Map(form.model);\n model.set(key, { ...current, value: name.trim() });\n const states = wireStates(keysOf(form.save), model, () => undefined);\n if (!Array.isArray(states)) return states;\n return { ok: true, body: requestBody(SKILL.save, form.save, states, form.screen) };\n}\n\nexport function removeSkillBody(form: SkillForm): { ok: true; body: unknown } | Failure {\n if (form.del === null)\n return drift('this form has no delete action (it is not an existing skill)');\n const states = wireStates(keysOf(form.del), form.model, () => undefined);\n if (!Array.isArray(states)) return states;\n return { ok: true, body: requestBody(SKILL.delete, form.del, states, form.screen) };\n}\n\n// ─── Over the wire ────────────────────────────────────────────────────────────\n\nexport const PAGER_URL = `https://www.linkedin.com/flagship-web/rsc-action/actions/pagination?sduiid=${SKILL.pager}`;\nconst MAX_PAGES = 10;\n\n/** Every skill: the Skills screen for the pager's payload, then its pages. */\nexport async function fetchSkills(\n vanityName: string,\n client: Client,\n): Promise<{ ok: true; skills: Skill[] } | Failure> {\n const screen = await openForm(\n SKILL.listScreen,\n { vanityName, isVanityNameResolved: true },\n client,\n 'skills-screen',\n );\n if (typeof screen !== 'string') return screen;\n const payload = listPayloadOf(screen);\n if (payload === null) return drift('the Skills screen carried no list request');\n const count = typeof payload.count === 'number' ? payload.count : 10;\n\n const skills: Skill[] = [];\n for (let page = 0; page < MAX_PAGES; page++) {\n const result = await client.request({\n url: PAGER_URL,\n method: 'POST',\n body: pagerFrom(payload, skills.length),\n spendClass: 'page',\n operation: 'skills',\n });\n if (!result.ok) return { ok: false, code: result.code, message: result.message };\n const parsed = skillsFromPage((result.classification as { raw?: string }).raw ?? '');\n if (!parsed.ok) return parsed;\n const fresh = parsed.skills.filter((s) => !skills.some((k) => k.skillId === s.skillId));\n skills.push(...fresh);\n if (parsed.skills.length < count || fresh.length === 0) break;\n }\n return { ok: true, skills };\n}\n\nexport async function openSkillForm(\n payload: Record<string, unknown>,\n client: Client,\n edit: boolean,\n) {\n const stream = await openForm(\n edit ? SKILL.editScreen : SKILL.addScreen,\n { ...payload, isVanityNameResolved: true },\n client,\n edit ? 'skill-edit-form' : 'skill-add-form',\n );\n return typeof stream === 'string' ? readSkillForm(stream) : stream;\n}\n\nexport async function sendSkill(\n body: unknown,\n requestId: string,\n client: Client,\n): Promise<{ ok: true } | Failure> {\n const sent = await sendAction(\n requestId,\n body,\n client,\n requestId === SKILL.save ? 'skill-add' : 'skill-remove',\n );\n return typeof sent === 'string' ? { ok: true } : sent;\n}\n","// ─── `lnrelay profile <public-id|url|urn>` ────────────────────────────────────\n//\n// A profile in full; see engine/full-profile.ts. One call on the profile\n// budget, and one more per 50 position groups past the first 10, so the\n// experience is whole. `--contact` adds the contact info overlay, one more\n// call on the profile budget. `--posts N` adds their newest posts: the posts\n// search, filtered to posts from them, on the search budget. `--skills` reads\n// every skill past the top 20, from the Skills screen's own list, 10 a page\n// on the page budget. `--recommendations` reads those received and given, 15\n// a page on the page budget. `--compact` turns every role, school and entry into a\n// line and drops the descriptions; `--fields` keeps only the named fields.\n\nimport {\n CONTACT_INFO_URL,\n type ContactInfo,\n contactInfoBody,\n parseContactInfo,\n} from '../engine/contact-info.ts';\nimport {\n type Entry,\n type FullProfile,\n fullProfileUrl,\n POSITIONS_PAGE,\n parseFullProfile,\n parsePositionsPage,\n positionsPageUrl,\n type Role,\n type School,\n} from '../engine/full-profile.ts';\nimport { createLiveClient } from '../engine/index.ts';\nimport {\n parseRecommendations,\n RECOMMENDATIONS_PAGE,\n RECOMMENDATIONS_URL,\n type Recommendation,\n type RecommendationKind,\n recommendationsBody,\n} from '../engine/recommendations.ts';\nimport { navBody } from '../engine/sdui-form.ts';\nimport { NAV_URL } from '../engine/sdui-profile.ts';\nimport {\n listPayloadOf,\n PAGER_URL,\n pagerFrom,\n SKILL,\n skillNamesOf,\n skillRowsOf,\n} from '../engine/sdui-skill.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { project } from '../format.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { runPostsSearch } from './posts-search.ts';\n\ntype Fetched =\n | { ok: true; json?: unknown; raw?: string }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted call: a POST when a body is given. Injectable so tests send nothing. */\nexport type ProfileFetch = (\n url: string,\n spendClass: 'profile' | 'search' | 'page',\n body?: unknown,\n) => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): ProfileFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('profile', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, spendClass, body) => {\n const r = await client.request({\n url,\n ...(body !== undefined ? { method: 'POST' as const, body } : {}),\n spendClass,\n operation: 'profile',\n });\n if (!r.ok) return r;\n return { ok: true, json: r.json, raw: (r.classification as { raw?: string }).raw ?? '' };\n };\n}\n\n/** A public id from itself or a /in/ URL (decoded), or a profile id from a urn. */\nexport function memberIdOf(input: string): string {\n const s = input.trim();\n const slug = s.match(/linkedin\\.com\\/in\\/([^/?#]+)/)?.[1];\n if (slug !== undefined) {\n try {\n return decodeURIComponent(slug);\n } catch {\n return slug;\n }\n }\n return s.match(/urn:li:fsd?_(?:mini)?[Pp]rofile:([^,)]+)/)?.[1] ?? s;\n}\n\ntype Read = FullProfile & {\n experienceError?: string;\n contact?: ContactInfo;\n contactError?: string;\n posts?: unknown[];\n postsError?: string;\n skillsError?: string;\n recommendations?: Record<RecommendationKind, Recommendation[]>;\n recommendationsError?: string;\n raw?: unknown;\n};\n\n/** Reads the position groups the profile did not hold, until all are in. */\nasync function readRestOfExperience(get: ProfileFetch, p: Read): Promise<void> {\n const want = p.counts?.experience;\n if (want === undefined) return;\n let start = want.shown;\n while (start < want.total) {\n const res = await get(positionsPageUrl(p.urn, start), 'profile');\n const page = res.ok ? parsePositionsPage(res.json) : res;\n if (!page.ok) {\n p.experienceError = `${page.code}: ${page.message}`;\n return;\n }\n p.experience = [...(p.experience ?? []), ...page.experience];\n start += page.groups;\n if (page.groups < POSITIONS_PAGE) break;\n }\n const counts = { ...p.counts };\n if (start >= want.total) delete counts.experience;\n else counts.experience = { shown: start, total: want.total };\n if (Object.keys(counts).length > 0) p.counts = counts;\n else delete p.counts;\n}\n\n/** The contact info overlay, which names the member by public id and name. */\nasync function readContact(get: ProfileFetch, p: Read): Promise<void> {\n if (p.publicId === undefined || p.firstName === undefined) {\n p.contactError = 'NOT_FOUND: the profile has no public id or name to ask with';\n return;\n }\n const body = contactInfoBody(p.publicId, p.firstName, p.lastName ?? '');\n const res = await get(CONTACT_INFO_URL, 'profile', body);\n const read = res.ok ? parseContactInfo(res.raw ?? '') : res;\n if (read.ok) p.contact = read.contact;\n else p.contactError = `${read.code}: ${read.message}`;\n}\n\n/** Skill pages at most: 10 skills each, and LinkedIn shows up to 100. */\nconst SKILL_PAGES = 10;\n\n/** Every skill, from the Skills screen's own list, in place of the profile's top 20. */\nasync function readAllSkills(get: ProfileFetch, p: Read): Promise<void> {\n const fail = (code: string, message: string) => {\n p.skillsError = `${code}: ${message}`;\n };\n if (p.publicId === undefined)\n return fail('NOT_FOUND', 'the profile has no public id to ask with');\n const screen = SKILL.listScreen;\n const nav = await get(\n `${NAV_URL}?screenId=${screen}&sduiid=${screen}`,\n 'page',\n navBody(screen, { vanityName: p.publicId, isVanityNameResolved: true }),\n );\n if (!nav.ok) return fail(nav.code, nav.message);\n const payload = listPayloadOf(nav.raw ?? '');\n if (payload === null) return fail('SCHEMA_DRIFT', 'the Skills screen carried no list request');\n const count = typeof payload.count === 'number' ? payload.count : 10;\n const total = p.counts?.skills?.total;\n const skills: string[] = [];\n let start = 0;\n for (let page = 0; page < SKILL_PAGES; page++) {\n const res = await get(PAGER_URL, 'page', pagerFrom(payload, start));\n if (!res.ok) return fail(res.code, res.message);\n const rows = skillRowsOf(res.raw ?? '');\n const names = skillNamesOf(res.raw ?? '');\n if (rows > names.length)\n return fail('SCHEMA_DRIFT', `${rows} skills were shown, ${names.length} read`);\n skills.push(...names);\n start += rows;\n if (rows < count || (total !== undefined && start >= total)) break;\n }\n if (skills.length === 0) return fail('SCHEMA_DRIFT', 'the skills list held no skills');\n p.skills = skills;\n const counts = { ...p.counts };\n if (total === undefined || skills.length >= total) delete counts.skills;\n else counts.skills = { shown: skills.length, total };\n if (Object.keys(counts).length > 0) p.counts = counts;\n else delete p.counts;\n}\n\n/** Pages of recommendations at most, each way: 15 a page. */\nconst RECOMMENDATION_PAGES = 10;\n\n/** Every recommendation they received and gave, from the details page's own list. */\nasync function readRecommendations(get: ProfileFetch, p: Read): Promise<void> {\n if (p.publicId === undefined) {\n p.recommendationsError = 'NOT_FOUND: the profile has no public id to ask with';\n return;\n }\n const out: Record<RecommendationKind, Recommendation[]> = { received: [], given: [] };\n for (const kind of ['received', 'given'] as const) {\n for (let page = 0; page < RECOMMENDATION_PAGES; page++) {\n const body = recommendationsBody(kind, p.publicId, p.id, out[kind].length);\n const res = await get(RECOMMENDATIONS_URL, 'page', body);\n const read = res.ok ? parseRecommendations(res.raw ?? '') : res;\n if (!read.ok) {\n p.recommendationsError = `${read.code}: ${read.message}`;\n return;\n }\n out[kind].push(...read.items);\n if (read.items.length < RECOMMENDATIONS_PAGE) break;\n }\n }\n p.recommendations = out;\n}\n\n/** Their newest posts onto the profile; a failure says why on the profile. */\nasync function readPosts(get: ProfileFetch, p: Read, n: number, compact: boolean): Promise<void> {\n const r = await runPostsSearch(\n { from: [p.id], sort: 'recent', limit: n },\n compact ? { compact: true } : {},\n async (url, body) => {\n const res = await get(url, 'search', body);\n return res.ok ? { ok: true, raw: res.raw ?? '' } : res;\n },\n );\n if (r.ok) p.posts = (r.data as { items: unknown[] }).items;\n else p.postsError = `${r.error.code}: ${r.error.message}`;\n}\n\nconst span = (x: { start?: string; end?: string; current?: boolean }) =>\n x.start === undefined && x.end === undefined\n ? undefined\n : `${x.start ?? '?'} – ${x.current === true ? 'now' : (x.end ?? '?')}`;\n\nconst roleLine = (r: Role) => line([r.title, r.company, span(r), r.employmentType, r.location]);\nconst schoolLine = (s: School) => line([s.school, s.degree, s.field, span(s)]);\nconst entryLine = (e: Entry) => {\n const { description: _d, url, ...rest } = e;\n const dates = span(e as { start?: string; end?: string; current?: boolean });\n const fields = Object.entries(rest)\n .filter(([k, v]) => !['start', 'end', 'current'].includes(k) && typeof v === 'string')\n .map(([, v]) => v as string);\n return line([...fields, dates, typeof url === 'string' ? url : undefined]);\n};\n\nconst LISTS = [\n 'certifications',\n 'languages',\n 'honors',\n 'publications',\n 'projects',\n 'volunteering',\n 'courses',\n 'organizations',\n 'patents',\n 'testScores',\n] as const;\n\n/** Every role, school and entry as one line; descriptions dropped. */\nfunction compact(p: Read): Record<string, unknown> {\n const out: Record<string, unknown> = { ...p };\n if (p.experience !== undefined) out.experience = p.experience.map(roleLine);\n if (p.education !== undefined) out.education = p.education.map(schoolLine);\n for (const key of LISTS) {\n const rows = p[key];\n if (rows !== undefined) out[key] = rows.map(entryLine);\n }\n return out;\n}\n\nexport async function runProfile(\n input: string | undefined,\n opts: OutputOpts = {},\n fetch?: ProfileFetch,\n req: { contact?: boolean; posts?: number; skills?: boolean; recommendations?: boolean } = {},\n): Promise<Envelope> {\n if (input === undefined || input.trim() === '')\n return err(\n 'profile',\n 'INVALID_INPUT',\n 'a public id, profile URL or urn is required',\n 'lnrelay profile <public-id|url|urn>',\n );\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n\n const res = await get(fullProfileUrl(memberIdOf(input)), 'profile');\n if (!res.ok) return err('profile', res.code, res.message, res.hint);\n const parsed = parseFullProfile(res.json);\n if (!parsed.ok) return err('profile', parsed.code, parsed.message, parsed.hint);\n const p: Read = parsed.profile;\n await readRestOfExperience(get, p);\n if (req.skills === true) await readAllSkills(get, p);\n if (req.recommendations === true) await readRecommendations(get, p);\n if (req.contact === true) await readContact(get, p);\n if (req.posts !== undefined && req.posts > 0)\n await readPosts(get, p, req.posts, opts.compact === true);\n\n if (opts.raw === true) return ok('profile', { ...p, raw: res.json });\n if (opts.fields !== undefined && opts.fields !== '')\n return ok('profile', project([p as unknown as Record<string, unknown>], opts.fields)[0]);\n return ok('profile', opts.compact === true ? compact(p) : p);\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 profile read (+1 per 50 companies past the first 10; --contact +1; --posts +1 search; --skills +1 page per 10; --recommendations +2 pages)',\n summary:\n 'A profile in full: name, headline, about, every role with dates and descriptions, ' +\n 'education, skills, honors, publications, volunteering and the other sections. ' +\n '--contact adds contact info: email, websites, phone, birthday, connected since. ' +\n '--posts N adds their N newest posts; --skills reads every skill past the top 20; ' +\n '--recommendations adds those they received and gave.',\n usage:\n 'lnrelay profile <public-id|profile-id|urn|url> [--contact] [--posts N] [--skills]\\n' +\n ' [--recommendations]\\n' +\n ' [--compact | --fields a,b,c] [--raw]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'search',\n cost: '1 search call per 50 results (posts: per 20); +1 per name looked up',\n summary:\n 'Search any kind the search box has: people, jobs, posts, companies, groups, events, ' +\n 'courses, products, services, schools. Several keyword sets merge by id.',\n usage:\n 'lnrelay search <kind> \"<keywords>\" [\"<more>\" ...] [filters] [--limit N] [--start N]\\n' +\n ' [--compact | --fields a,b,c]\\n' +\n ' kinds: people, jobs (their own flags: see `people`, `jobs`), posts, companies,\\n' +\n ' groups, events, courses, products, services, schools\\n' +\n ' companies, services: [--location \"<place>\"] [--network 1st,2nd,3rd+]\\n' +\n ' companies: [--industry <ids>] any kind: [--filter key=v1,v2 ...]\\n' +\n ' posts: [--sort recent|relevant] [--posted 24h|week|month]\\n' +\n ' [--type videos,images,jobs,live,articles,documents] [--posted-by 1st,me]\\n' +\n ' [--from <profile-id>] [--mentions <profile-id>] [--from-company \"<name|id>\"]\\n' +\n ' [--mentions-company \"<name|id>\"] [--author-company \"<name|id>\"]\\n' +\n ' [--author-industry <ids>] [--author-title \"<text>\"]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'search-filters',\n cost: '1 search call',\n summary:\n 'Every filter a search kind has for a query, with option ids and live counts: what ' +\n '`search <kind> --filter key=…` takes.',\n usage: 'lnrelay search-filters <kind> [\"<keywords>\"] [filters]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'people',\n cost: '1 search call per 50 people; +1 per company, school or place given by name',\n summary:\n 'People search with every filter LinkedIn has: company, past company, school, place, ' +\n 'degree, industry, title, connections of someone, … Several keyword sets merge by person.',\n usage:\n 'lnrelay people [\"<keywords>\" ...] [--company \"<name|id>\" ...] [--past-company \"<name|id>\" ...]\\n' +\n ' [--school \"<name|id>\" ...] [--location \"<place>\" | --geo <ids>] [--network 1st,2nd,3rd+]\\n' +\n ' [--industry <ids>] [--language en,de] [--service <ids>] [--title \"<text>\"]\\n' +\n ' [--first-name \"<text>\"] [--last-name \"<text>\"] [--company-text \"<text>\"]\\n' +\n ' [--school-text \"<text>\"] [--connection-of <profile-id>] [--follower-of <profile-id>]\\n' +\n ' [--open-to-volunteer] [--filter key=v1,v2 ...] [--limit N] [--start N]\\n' +\n ' [--compact | --fields a,b,c]\\n' +\n ' Names are looked up and data.resolved says what each became: check it.\\n' +\n ' LinkedIn pages at most 1000 people per query; meta.servedLimit says when it held back.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'people-filters',\n cost: '1 search call (+1 per name looked up)',\n summary:\n 'Every people filter for a query, with option ids and live counts: what `people` and ' +\n '--filter take.',\n usage: 'lnrelay people-filters [\"<keywords>\"] [people filters]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'jobs',\n cost: '1 job-search call per 100 jobs; --details adds 1 job read per 100 jobs',\n summary:\n 'Job search with every filter the jobs page has. Cards carry id, title, company, place, ' +\n 'workplace, listed date, Easy Apply. Read finalists with `job`.',\n usage:\n 'lnrelay jobs \"<keywords>\" [\"<more keywords>\" ...] [--location \"<place>\" | --geo <id>]\\n' +\n ' [--distance <miles>]\\n' +\n ' [--posted 24h|week|month|<N>h|<N>d] [--experience internship,entry,associate,\\n' +\n ' mid-senior,director,executive] [--type full-time,part-time,contract,temporary,\\n' +\n ' volunteer,internship,other] [--workplace on-site,remote,hybrid] [--easy-apply]\\n' +\n ' [--under-10] [--verified] [--in-network] [--fair-chance] [--company <ids>]\\n' +\n ' [--industry <ids>] [--function <codes>] [--title <ids>] [--place <geo-ids>]\\n' +\n ' [--filter key=v1,v2 ...] [--sort recent|relevant] [--limit N] [--start N]\\n' +\n ' [--details [--description]] [--compact | --fields a,b,c]\\n' +\n ' Ids for --company/--industry/--title/--place/--filter come from `job-filters`.\\n' +\n ' The resolved place is in data.location: check it, \"Vienna\" may resolve narrow.\\n' +\n 'lnrelay jobs --top-applicant | --hear-back [--limit N] [--details] [--compact | --fields a,b,c]\\n' +\n ' Premium: the jobs where LinkedIn says you would be a top applicant (100 a call), or\\n' +\n ' where you are more likely to hear back (25 a call, then read in full).',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'job',\n cost:\n '1 job read per 100 jobs; --team adds 1 page call per job; --insights 1 job read per job; ' +\n '--match about 3 page calls per job',\n summary:\n 'Jobs in full: description, apply link (external or Easy Apply), applicants, state. ' +\n 'Several ids are read together, 100 a call. --team adds who posted it and who is hiring. ' +\n '--insights (Premium) adds who applied (count, last day, seniority, education) and the ' +\n \"company's insights: headcount over two years, the job's function, tenure, competitors. \" +\n \"--match (Premium) asks LinkedIn's AI how well you fit: verdict, met and missing qualifications.\",\n usage:\n 'lnrelay job <id|job-url> [<id|job-url> ...] [--team] [--insights] [--match]\\n' +\n ' [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'job-filters',\n cost: '1 job-search call',\n summary:\n 'Every job filter for a query, with option ids and live counts: what `jobs --filter` and ' +\n '--company/--industry/--title/--place take.',\n usage: 'lnrelay job-filters \"<keywords>\" [--location \"<place>\" | --geo <id>] [jobs filters]',\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: '1 page call per company; --posts adds search calls (20 posts a call)',\n summary:\n 'A company page in full: about, website, industry, size, employees on LinkedIn, followers, ' +\n 'headquarters, specialties, locations, affiliated and showcase pages. --posts N adds its ' +\n 'newest posts.',\n usage: 'lnrelay company <universal-name|url|id> [...] [--posts N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\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: 'my-items',\n cost: '1 page call per 10 items; jobs with no --stage read all 5 stages',\n summary:\n 'Your My items: saved posts, LinkedIn Learning courses, and the job tracker (saved, in ' +\n 'progress, applied, interview, archived).',\n usage:\n 'lnrelay my-items posts|learning|jobs [--stage saved|in-progress|applied|interview|archived]\\n' +\n ' [--limit N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'events',\n cost: '1 page call',\n summary:\n \"The events page's own lists: events recommended for you, and the Premium LinkedIn Live \" +\n 'events. Searching events by keyword is `search events`.',\n usage: 'lnrelay events [--premium] [--limit N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'event',\n cost: '1 page call per event',\n summary:\n 'Events in full: when (both ends, time zone), upcoming or past, online or where, the ' +\n \"event's own site, attendees, organiser, description.\",\n usage: 'lnrelay event <id|url> [<id|url> ...] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'notifications',\n cost: '1 page call per 25',\n summary:\n 'Your notifications, newest first: what each says, when, read or not, where it goes and ' +\n 'who it is about. Reading them here does not mark them seen.',\n usage: 'lnrelay notifications [--unread] [--limit N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'viewers',\n cost: '2 page calls',\n summary:\n 'Who viewed your profile, as your profile-views page shows it: the total for the period, ' +\n 'the viewers LinkedIn names (up to 3 on a free account, all with Premium), anonymous ones ' +\n 'as LinkedIn describes them, and how many looked in private mode. Premium adds a range ' +\n 'and highlights: top location, industry and company, and the companies viewers work at.',\n usage: 'lnrelay viewers [--days 7|14|28|90|365] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'network',\n cost: '1 page call per 50 rows; the counts are 7 calls',\n summary:\n 'Your My Network: connections, people you follow, followers, pages, events, groups, and ' +\n 'invitations you sent. With no list, the count of each. Read only.',\n usage:\n 'lnrelay network [connections|following|followers|pages|events|groups|invitations]\\n' +\n ' [--limit N] [--start N] [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'inbox',\n cost: '1 page call per 20 conversations',\n summary:\n 'Your conversations in a folder: who with, unread, last message. Reads only: nothing is ' +\n 'marked read or seen, and nothing read is stored.',\n usage:\n 'lnrelay inbox [--folder inbox|primary|other|archive|requests|spam] [--unread] [--limit N]\\n' +\n ' [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'messages',\n cost: '1 page call',\n summary:\n \"A conversation's latest messages, oldest first, saying which are yours. Reading does not \" +\n 'mark it read.',\n usage: 'lnrelay messages <conversation-id|thread-url> [--compact | --fields a,b,c]',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'draft',\n cost: '1 page call to check the conversation; the draft stays on this machine',\n summary:\n 'Draft a reply, saved locally with the conversation link for you to review and send. ' +\n 'Nothing is sent: this tool cannot send a message.',\n usage:\n 'lnrelay draft <conversation-id|thread-url> (\"<text>\" | --file <path>)\\n' +\n ' lnrelay draft remove <draft-id>',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'drafts',\n cost: 'free — local',\n summary: 'Your saved reply drafts, with the link to each conversation.',\n usage: 'lnrelay drafts [--compact]',\n audience: ['cli', 'mcp'],\n risk: 'local',\n implemented: true,\n },\n {\n name: 'scheduled',\n cost: '1 call per 10 posts',\n summary: 'Your posts waiting to publish, with when. Not in `my-posts` until they go out.',\n usage:\n 'lnrelay scheduled\\n' +\n ' Each row: urn (cancel with `delete`, change with `edit`), scheduledAt, text. Links in\\n' +\n ' the text show as lnkd.in short links, as LinkedIn lists them.',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'experience',\n cost: '2 calls',\n summary: 'The roles on your own profile, with the position id `role edit|remove` takes.',\n usage: 'lnrelay experience',\n audience: ['cli', 'mcp'],\n risk: 'read',\n implemented: true,\n },\n {\n name: 'skills',\n cost: '3 calls',\n summary: 'The skills on your own profile, with the skill id `skill remove` takes.',\n usage: 'lnrelay skills',\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: 'approval',\n cost: 'free — local',\n summary:\n 'Show or set how writes are approved: interactive (a human at a terminal), agent (the ' +\n 'owner approves a --plan preview in chat), or unattended. Only a terminal can change it.',\n usage:\n 'lnrelay approval [show]\\n' +\n ' lnrelay approval set <interactive|agent|unattended>\\n' +\n ' Setting needs an interactive terminal and a typed token. Every approval and outcome\\n' +\n ' is appended to ~/.lnrelay/writes.jsonl.',\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>\" [--image <path> ... [--alt \"<text>\" ...] | --video <path>\\n' +\n ' | --document <pdf> --title \"<title>\"] [--at \"YYYY-MM-DD HH:MM\"]\\n' +\n ' [--poll \"<question>\" --option \"<a>\" --option \"<b>\" ... [--duration 1d|3d|1w|2w]]\\n' +\n ' [--visibility public|connections] [--via oauth|voyager] [--no-card]\\n' +\n ' [--plan | --confirm <token>]\\n' +\n ' Approval follows `lnrelay approval`: --plan previews and returns a token without\\n' +\n ' sending; --confirm <token> sends it in agent mode. In interactive mode it asks at a\\n' +\n ' terminal. --image repeats for up to 20, --alt pairs with it by position (--alt \"\"\\n' +\n ' skips one). --at schedules it (local time, or ISO 8601 with an offset; at least 10\\n' +\n ' minutes out); LinkedIn publishes it then, and `lnrelay delete <urn>` cancels it.\\n' +\n ' --poll takes 2-4 --option and cannot be scheduled yet. The first link in the text\\n' +\n ' gets the preview card LinkedIn would show (one extra read, named in the preview);\\n' +\n ' --no-card posts it as plain text. Files, documents, polls, cards and scheduling go\\n' +\n ' over the private API only.',\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 or post you wrote, your profile headline or About, or your ' +\n 'profile photo or cover image. Its ' +\n 'own verb, so a comment urn can never be mistaken for something to comment ON.',\n usage:\n 'lnrelay edit <comment-urn | share-urn | ugcPost-urn> \"<text>\"\\n' +\n ' lnrelay edit headline|about (\"<text>\" | --file <path>)\\n' +\n ' lnrelay edit photo|banner <image.png|jpg> (photo square, banner 4:1, max 8 MB)\\n' +\n ' A post is edited by the urn it was created as (`share` prints it; `my-posts` lists\\n' +\n ' it as shareUrn), not its activity urn. The whole text is replaced. A profile edit\\n' +\n ' shows the current text beside the new one, sends every other profile field back as\\n' +\n ' LinkedIn holds it, and reads the profile back to confirm. Headline max 220 characters.\\n' +\n ' An image is uploaded as it is, uncropped, and read back: it must be the one showing.',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'role',\n cost: '3-4 reads + 1 write',\n summary:\n 'Add, edit or remove a role in your Experience. Never rewrites your headline; notify network ' +\n 'is off unless --notify.',\n usage:\n 'lnrelay role add --title \"<t>\" --company \"<c>\" --start YYYY-MM [--end YYYY-MM | --current]\\n' +\n ' [--location \"<l>\"] [--description \"<d>\" | --description-file <path>] [--notify]\\n' +\n ' lnrelay role edit <position-id> [any of the flags above]\\n' +\n ' lnrelay role remove <position-id>\\n' +\n ' Position ids come from `lnrelay experience`. The preview shows the role as it is and\\n' +\n ' as it will be; the result is read back from the profile. A role with media attached\\n' +\n ' is refused. The company is free text (not linked to a company page).',\n audience: ['cli'],\n risk: 'write',\n implemented: true,\n },\n {\n name: 'skill',\n cost: '4-5 reads + 1 write',\n summary: 'Add a skill to your profile, or remove one.',\n usage:\n 'lnrelay skill add \"<name>\"\\n' +\n ' lnrelay skill remove <skill-id>\\n' +\n ' Skill ids come from `lnrelay skills`. A skill is added as free text, linked to no role,\\n' +\n ' school or project. Removing a skill removes its endorsements with it.',\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","// ─── Experience: adding, editing and removing a role ──────────────────────────\n//\n// Captured 2026-10-14 by adding a test role in the browser and deleting it.\n// Three things learned the hard way:\n//\n// 1. The save is not in the form. The form's Save fires `uploadPositionMedia`,\n// and the REPLY to that carries the `saveProfilePositionForm` action. So a\n// save is: open the form (read), send the media step, take the save from its\n// reply, send it.\n// 2. The add form defaults `dynamicallyCreateHeadline` to true. Saving the test\n// role replaced the owner's headline with \"<title> at <org>\", on the live\n// profile, unnoticed until the owner saw it. Here it is always false.\n// 3. \"Notify network\" (`allowProfileEditBroadcasts`) also defaults on in the\n// browser. Here it is off unless asked for.\n//\n// As with the intro and About (sdui-profile.ts), nothing is hand-built: every\n// value is the form's own, and only the fields asked for are replaced.\n\nimport type { Client } from './client.ts';\nimport {\n balanced,\n type Failure,\n findRequest,\n keysOf,\n type Model,\n type RequestArgs,\n readModel,\n requestBody,\n wireStates,\n} from './sdui-form.ts';\nimport { drift, openForm, sendAction } from './sdui-profile.ts';\n\nexport const POSITION = {\n addScreen: 'com.linkedin.sdui.flagshipnav.profile.ProfilePositionAddForm',\n editScreen: 'com.linkedin.sdui.flagshipnav.profile.ProfilePositionDetailsEditForm',\n listScreen: 'com.linkedin.sdui.flagshipnav.profile.ProfileExperienceDetails',\n media: 'com.linkedin.sdui.impl.profile.components.forms.uploadPositionMedia',\n save: 'com.linkedin.sdui.requests.profile.saveProfilePositionForm',\n delete: 'com.linkedin.sdui.requests.profile.deleteProfilePositionForm',\n} as const;\n\nexport interface Position {\n positionId: string;\n title: string;\n /** What the Experience list opens this role's edit form with. */\n payload: Record<string, unknown>;\n}\n\nconst EDIT_NAV = `{\"$type\":\"proto.sdui.actions.core.NavigateToScreen\",\"screenId\":\"${POSITION.editScreen}\"`;\n\n/** Every role on the Experience screen, with the id it is edited by. */\nexport function listPositions(stream: string): { ok: true; positions: Position[] } | Failure {\n if (readModel(stream) === null && !stream.includes(EDIT_NAV) && !stream.includes('\"rows\"')) {\n return drift('the Experience screen could not be read');\n }\n const positions: Position[] = [];\n const seen = new Set<string>();\n let i = 0;\n for (;;) {\n i = stream.indexOf(EDIT_NAV, i);\n if (i === -1) break;\n const text = balanced(stream, i);\n i += EDIT_NAV.length;\n if (text === null) continue;\n const payload = (\n JSON.parse(text) as { requestedArguments?: { payload?: Record<string, unknown> } }\n ).requestedArguments?.payload;\n const id = payload?.positionId;\n if (typeof id !== 'string' || seen.has(id) || payload === undefined) continue;\n seen.add(id);\n positions.push({ positionId: id, title: String(payload.title ?? ''), payload });\n }\n if (positions.length === 0 && !stream.includes('\"rows\"') && !stream.includes('Experience')) {\n return drift('the Experience screen listed no roles and did not look like one');\n }\n return { ok: true, positions };\n}\n\nexport interface PositionForm {\n ok: true;\n model: Model;\n /** Shared by every field key: `auto-binding-<uuid>ProfilePositionForm`. */\n prefix: string;\n media: RequestArgs;\n del: RequestArgs | null;\n screen: string;\n}\n\nexport function readPositionForm(stream: string): PositionForm | Failure {\n const model = readModel(stream);\n if (model === null) return drift('the position form carried no initial values');\n const media = findRequest(stream, POSITION.media);\n const prefix = media?.payload.formIdPrefix;\n if (media === null || typeof prefix !== 'string') {\n return drift('the position form carried no save step (uploadPositionMedia)');\n }\n const del = findRequest(stream, POSITION.delete);\n return {\n ok: true,\n model,\n prefix,\n media,\n del,\n screen: del === null ? POSITION.addScreen : POSITION.editScreen,\n };\n}\n\nexport interface YearMonth {\n month: number;\n year: number;\n}\n\nexport interface PositionChanges {\n title?: string;\n company?: string;\n description?: string;\n location?: string;\n start?: YearMonth;\n /** `present` marks it a current role. */\n end?: YearMonth | 'present';\n /** Tell the network about it. Off unless asked. */\n notify?: boolean;\n}\n\nconst date = (d: YearMonth) => ({\n $type: 'proto.sdui.common.Date',\n day: 0,\n month: d.month,\n year: d.year,\n});\nconst ym = (v: unknown) => {\n const d = v as { month?: number; year?: number } | undefined;\n return d?.year ? `${d.year}-${String(d.month ?? 0).padStart(2, '0')}` : null;\n};\n\n/** The form's values with the asked-for changes, and the two safety overrides. */\nexport function applyChanges(\n form: PositionForm,\n changes: PositionChanges,\n): { ok: true; model: Model } | Failure {\n const model: Model = new Map(form.model);\n const set = (field: string, value: unknown) => {\n const key = `${form.prefix}${field}`;\n const current = model.get(key);\n if (current === undefined) return false;\n model.set(key, { ...current, value });\n return true;\n };\n const missing: string[] = [];\n const need = (field: string, value: unknown) => {\n if (!set(field, value)) missing.push(field);\n };\n\n if (changes.title !== undefined) need('title', changes.title);\n if (changes.description !== undefined) need('description', changes.description);\n if (changes.location !== undefined) need('location', changes.location);\n if (changes.company !== undefined) {\n // Free text: not linked to a company page, as when typed without picking one.\n need('companyName', changes.company);\n need('organizationId', -1);\n need('organizationEntityId', { type: 'bigint', value: '-1' });\n }\n if (changes.start !== undefined) need('startDate', date(changes.start));\n if (changes.end === 'present') need('isCurrentPosition', true);\n else if (changes.end !== undefined) {\n need('isCurrentPosition', false);\n need('endDate', date(changes.end));\n }\n need('dynamicallyCreateHeadline', false);\n need('allowProfileEditBroadcasts', changes.notify === true);\n if (missing.length > 0) return drift(`the position form has no ${missing.join(', ')} field`);\n\n const s = roleSummary(model);\n if (!s.current && s.start !== null && s.end !== null && s.end < s.start) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `the role ends (${s.end}) before it starts (${s.start})`,\n };\n }\n return { ok: true, model };\n}\n\n/** What a role says now, for the preview. */\nexport function roleSummary(model: Model) {\n const get = (field: string) =>\n [...model.entries()].find(([k]) => k.endsWith(`ProfilePositionForm${field}`))?.[1].value;\n const current = get('isCurrentPosition') === true;\n return {\n title: String(get('title') ?? ''),\n company: String(get('companyName') ?? ''),\n start: ym(get('startDate')),\n end: current ? null : ym(get('endDate')),\n current,\n location: String(get('location') ?? ''),\n description: String(get('description') ?? ''),\n };\n}\n\n/** Media on a role is a computed list nothing here has observed; refuse rather than drop it. */\nfunction noMedia(model: Model): Failure | null {\n const count = [...model.entries()].find(([k]) =>\n k.endsWith('position-mediaUiCollection-mediaCount'),\n )?.[1].value;\n return typeof count === 'number' && count > 0\n ? {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message: 'this role has media attached, and saving one with media has not been verified',\n hint: 'Edit it in the browser for now; nothing was changed.',\n }\n : null;\n}\n\nconst resolver = (key: string) =>\n key.endsWith('position-mediaIds') ? { ok: true as const, value: [] } : undefined;\n\n/** The media step the browser sends on Save; its reply carries the save. */\nexport function mediaBody(form: PositionForm, model: Model): { ok: true; body: unknown } | Failure {\n const refused = noMedia(model);\n if (refused !== null) return refused;\n const states = wireStates(keysOf(form.media), model, resolver);\n if (!Array.isArray(states)) return states;\n return { ok: true, body: requestBody(POSITION.media, form.media, states, form.screen) };\n}\n\nexport function saveFromReply(reply: string): { ok: true; args: RequestArgs } | Failure {\n const args = findRequest(reply, POSITION.save);\n return args === null\n ? drift('the media step did not hand back the save action')\n : { ok: true, args };\n}\n\n/** The save, from the action the media step returned. */\nexport function positionSaveBody(\n save: RequestArgs,\n model: Model,\n screen: string,\n): { ok: true; body: unknown } | Failure {\n // The browser flips its \"saving\" flag on before the request leaves; mirror it.\n const sending: Model = new Map(model);\n for (const [k, v] of sending)\n if (k.endsWith('isActiveProfileFormLoading')) sending.set(k, { ...v, value: true });\n const states = wireStates(keysOf(save), sending, resolver);\n if (!Array.isArray(states)) return states;\n return { ok: true, body: requestBody(POSITION.save, save, states, screen) };\n}\n\nexport function deleteBody(form: PositionForm): { ok: true; body: unknown } | Failure {\n if (form.del === null)\n return drift('this form has no delete action (it is not an existing role)');\n const states = wireStates(keysOf(form.del), form.model, resolver);\n if (!Array.isArray(states)) return states;\n return { ok: true, body: requestBody(POSITION.delete, form.del, states, form.screen) };\n}\n\n// ─── Over the wire ────────────────────────────────────────────────────────────\n\nexport async function fetchPositions(vanityName: string, client: Client) {\n const stream = await openForm(\n POSITION.listScreen,\n { vanityName, isVanityNameResolved: true },\n client,\n 'experience-list',\n );\n return typeof stream === 'string' ? listPositions(stream) : stream;\n}\n\nexport async function openPositionForm(\n payload: Record<string, unknown>,\n client: Client,\n edit: boolean,\n): Promise<PositionForm | Failure> {\n const stream = await openForm(\n edit ? POSITION.editScreen : POSITION.addScreen,\n { ...payload, isVanityNameResolved: true },\n client,\n edit ? 'position-edit-form' : 'position-add-form',\n );\n return typeof stream === 'string' ? readPositionForm(stream) : stream;\n}\n\n/** Media step, then the save it hands back. */\nexport async function sendPositionSave(\n form: PositionForm,\n model: Model,\n client: Client,\n): Promise<{ ok: true } | Failure> {\n const media = mediaBody(form, model);\n if (!media.ok) return media;\n const reply = await sendAction(POSITION.media, media.body, client, 'position-media-step', 'page');\n if (typeof reply !== 'string') return reply;\n const save = saveFromReply(reply);\n if (!save.ok) return save;\n const body = positionSaveBody(save.args, model, form.screen);\n if (!body.ok) return body;\n const sent = await sendAction(POSITION.save, body.body, client, 'position-save');\n return typeof sent === 'string' ? { ok: true } : sent;\n}\n\nexport async function sendPositionDelete(\n form: PositionForm,\n client: Client,\n): Promise<{ ok: true } | Failure> {\n const body = deleteBody(form);\n if (!body.ok) return body;\n const sent = await sendAction(POSITION.delete, body.body, client, 'position-delete');\n return typeof sent === 'string' ? { ok: true } : sent;\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, MIN_GAP_MS, spend, summarise } from '../engine/budget.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport { auditApproval } from './approval.ts';\nimport { type ConfirmDeps, canApprove, 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/**\n * For commands that must READ before they can ask (comment harvests the post\n * page, delete reads the comment menu): refuse up front when this invocation\n * cannot end in an approval, so it causes no LinkedIn traffic it cannot use.\n */\nexport function refuseUnapprovable(\n command: string,\n action: string,\n deps: ConfirmDeps,\n): Envelope | null {\n if (canApprove(deps)) return null;\n return deps.approval?.mode === 'agent'\n ? err(\n command,\n 'CONFIRMATION_REQUIRED',\n `${action} needs the owner's approval of this exact content`,\n 'Nothing was sent and no network call was made. Run the same command with --plan, show ' +\n 'the preview to the owner, and when they approve re-run it with --confirm <token>.',\n )\n : err(\n command,\n 'CONFIRMATION_REQUIRED',\n `${action} 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/** 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, calls = 1): Envelope | null {\n // Simulated on a copy and never saved: this asks, the client accounts.\n let current = ledger();\n for (let i = 0; i < calls; i++) {\n // The client paces calls at least MIN_GAP_MS apart; simulate that too.\n const attempt = spend(current, 'write', now + i * MIN_GAP_MS);\n if ('error' in attempt) {\n return err(command, attempt.error.code, attempt.error.message, attempt.error.hint);\n }\n current = attempt.ledger;\n }\n return 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 // A plan is a success: the preview IS the result. Nothing is spent or sent.\n if (!outcome.ok && outcome.code === 'PLANNED') {\n return ok(command, {\n planned: true,\n token: outcome.token,\n preview: outcome.preview,\n next: `show this to the owner; on their approval re-run the same command with --confirm ${outcome.token}`,\n });\n }\n if (!outcome.ok) return err(command, outcome.code, outcome.message, outcome.hint);\n auditApproval(\n command,\n deps.approval?.mode ?? 'interactive',\n plan.summary,\n outcome.confirmed.token,\n );\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","// ─── How writes are approved, and the record of what was written ─────────────\n//\n// The mode lives in ~/.lnrelay/config.json and ONLY `lnrelay approval set`\n// writes it — at a terminal, behind a typed token. That is the property the\n// agent and unattended modes rest on: an agent can use whatever mode the owner\n// chose, but cannot choose it. See confirm.ts for what each mode lets through.\n//\n// Every approval and every outcome is appended to ~/.lnrelay/writes.jsonl, so\n// what an agent did under the owner's name can be read back afterwards.\n\nimport { appendFileSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { cachePath, loadJson, saveJson } from '../cache/store.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport { APPROVAL_MODES, type ApprovalMode, type ConfirmDeps, confirmToken } from './confirm.ts';\n\nconst MEANING: Record<ApprovalMode, string> = {\n interactive: 'every write waits for a human to type a token at a terminal',\n agent:\n 'an agent may write after the owner approves the exact content: --plan to preview, ' +\n '--confirm <token> once they say so',\n unattended:\n 'agents may write without asking; budget caps, cooldowns and the audit log still apply',\n};\n\nconst isMode = (v: unknown): v is ApprovalMode =>\n typeof v === 'string' && (APPROVAL_MODES as readonly string[]).includes(v);\n\n/**\n * The owner's chosen mode. Absent means interactive. Anything unreadable is an\n * error — never a guess — because guessing wrong in the permissive direction\n * publishes under someone's name without their approval.\n */\nexport function loadApprovalMode():\n | { ok: true; mode: ApprovalMode }\n | { ok: false; message: string; hint: string } {\n const loaded = loadJson<{ approval?: unknown }>(cachePath('config.json'));\n if (loaded.state === 'missing') return { ok: true, mode: 'interactive' };\n if (loaded.state === 'corrupt') {\n return {\n ok: false,\n message: 'the approval setting was unreadable and has been quarantined',\n hint: `Moved to ${loaded.quarantinedTo}. Writes fall back to interactive from the next run; set another mode with \\`lnrelay approval set\\`.`,\n };\n }\n const mode = loaded.value.approval ?? 'interactive';\n if (!isMode(mode)) {\n return {\n ok: false,\n message: `unknown approval mode '${String(mode)}' in config.json`,\n hint: `one of: ${APPROVAL_MODES.join(', ')}. Set it with \\`lnrelay approval set <mode>\\`.`,\n };\n }\n return { ok: true, mode };\n}\n\n/** The token that confirms switching to a mode. Differs per mode. */\nexport function setToken(mode: ApprovalMode): string {\n return confirmToken('set approval mode', mode);\n}\n\nfunction append(entry: Record<string, unknown>): void {\n const path = cachePath('writes.jsonl');\n mkdirSync(dirname(path), { recursive: true });\n appendFileSync(path, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\\n`, {\n mode: 0o600,\n });\n}\n\n/** Whether this process approved a write — so its outcome belongs in the log. */\nlet approvedInThisRun = false;\nexport function wasApproved(): boolean {\n return approvedInThisRun;\n}\n\nexport function auditApproval(\n command: string,\n mode: ApprovalMode,\n summary: string[],\n token: string,\n): void {\n approvedInThisRun = true;\n append({ event: 'approved', command, mode, summary, token });\n}\n\nexport function auditOutcome(command: string, mode: ApprovalMode, envelope: Envelope): void {\n append(\n envelope.ok\n ? { event: 'outcome', command, mode, ok: true, data: envelope.data }\n : { event: 'outcome', command, mode, ok: false, error: envelope.error },\n );\n}\n\nexport function runApprovalShow(): Envelope {\n const loaded = loadApprovalMode();\n if (!loaded.ok) return err('approval', 'CACHE_CORRUPT', loaded.message, loaded.hint);\n return ok('approval', {\n mode: loaded.mode,\n meaning: MEANING[loaded.mode],\n audit: cachePath('writes.jsonl'),\n });\n}\n\n/** Switch mode. Needs a human at a terminal, like the writes it governs. */\nexport async function runApprovalSet(\n mode: string | undefined,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n if (!isMode(mode)) {\n return err(\n 'approval',\n 'INVALID_INPUT',\n `unknown approval mode '${mode ?? ''}'`,\n `one of: ${APPROVAL_MODES.map((m) => `${m} (${MEANING[m]})`).join('; ')}`,\n );\n }\n if (!deps.isTty) {\n return err(\n 'approval',\n 'CONFIRMATION_REQUIRED',\n 'the approval mode can only be changed by a human at an interactive terminal',\n 'Nothing was changed. An agent cannot choose how its own writes are approved.',\n );\n }\n\n const token = setToken(mode);\n const answer = (\n await deps.prompt(\n [\n '',\n ` SET LINKEDIN WRITE APPROVAL TO: ${mode.toUpperCase()}`,\n ` ${MEANING[mode]}`,\n '',\n ` Type ${token} to confirm, anything else to abort: `,\n ].join('\\n'),\n )\n ).trim();\n if (answer !== token) {\n return err('approval', 'CONFIRMATION_REQUIRED', 'aborted — nothing was changed');\n }\n\n const current = loadJson<Record<string, unknown>>(cachePath('config.json'));\n saveJson(cachePath('config.json'), {\n ...(current.state === 'ok' ? current.value : {}),\n approval: mode,\n });\n append({ event: 'mode', mode });\n return ok('approval', { mode, meaning: MEANING[mode] });\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.\n//\n// APPROVAL MODES (decided 2026-09-25, docs/DECISION-writes.md §9). The owner's\n// personal agents must be able to act on \"post it\" said in chat, and, if the\n// owner chooses, to manage the account on their own. So a write is approved by\n// whichever of these the OWNER has selected:\n//\n// interactive (default) a human types the token at a terminal — as above\n// agent `--plan` returns the preview + token without sending; the agent\n// shows it to the owner and, on their word, re-runs with\n// `--confirm <token>`. The token binds the approval to the exact\n// content previewed: edit anything and it no longer matches.\n// unattended no approval step; budget, cooldown and the audit log still apply\n//\n// The mode is a file only `lnrelay approval set` writes, and that command needs\n// a terminal and a typed token — so an agent cannot promote itself. In agent\n// mode the token is a content binding, not an authentication: the agent is\n// trusted to relay the owner's word, and the audit log records what it sent.\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 type ApprovalMode = 'interactive' | 'agent' | 'unattended';\n\nexport const APPROVAL_MODES: readonly ApprovalMode[] = ['interactive', 'agent', 'unattended'];\n\nexport interface WritePlan<T> {\n action: string;\n payload: T;\n /**\n * What the token is derived from, when the payload holds values that change\n * between runs (a comment's per-render trackingId). Defaults to the payload.\n */\n tokenBasis?: unknown;\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\n/** The token for a plan: over its stable basis when it names one. */\nexport function planToken<T>(plan: WritePlan<T>): string {\n return confirmToken(plan.action, plan.tokenBasis ?? plan.payload);\n}\n\n/** The plan as lines, without the prompt — shared by the prompt and `--plan`. */\nexport function previewLines<T>(plan: WritePlan<T>, budgetLine: string): string[] {\n return [\n `ABOUT TO ${plan.action.toUpperCase()} ON LINKEDIN`,\n ...plan.summary,\n `via ${plan.transport === 'oauth' ? 'official OAuth (w_member_social)' : 'Voyager (private API)'}`,\n `undo ${plan.reversibility}`,\n ...riskLines(plan.transport).map((l) => l.trim()),\n budgetLine,\n ];\n}\n\nexport function renderPlan<T>(plan: WritePlan<T>, budgetLine: string): string {\n const token = planToken(plan);\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 ApprovalRequest {\n mode: ApprovalMode;\n /** `--confirm <token>`: the token `--plan` returned. */\n token?: string | undefined;\n /** `--plan`: preview and token only; nothing is sent. */\n planOnly?: boolean | undefined;\n}\n\nexport interface ConfirmDeps {\n isTty: boolean;\n prompt: (question: string) => Promise<string>;\n write: (s: string) => void;\n /** Absent means interactive with no flags — the pre-2026-09-25 behaviour. */\n approval?: ApprovalRequest;\n}\n\nexport type ConfirmOutcome<T> =\n | { ok: true; confirmed: ConfirmedWrite<T> }\n | { ok: false; code: 'CONFIRMATION_REQUIRED'; message: string; hint: string }\n | { ok: false; code: 'PLANNED'; token: string; preview: string[] };\n\n/**\n * Whether this invocation could end in an approval (or a plan). Commands that\n * must read before they can ask — comment harvests the post page — check this\n * first, so a request that can only be refused makes no network call.\n */\nexport function canApprove(deps: ConfirmDeps): boolean {\n const a = deps.approval ?? { mode: 'interactive' };\n if (a.planOnly === true || a.mode === 'unattended') return true;\n if (a.mode === 'agent' && a.token !== undefined) return true;\n return deps.isTty;\n}\n\nconst refuse = (message: string, hint: string) =>\n ({ ok: false, code: 'CONFIRMATION_REQUIRED', message, hint }) as const;\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 const a = deps.approval ?? { mode: 'interactive' };\n const token = planToken(plan);\n const mint = (): ConfirmOutcome<T> => ({\n ok: true,\n confirmed: { action: plan.action, payload: plan.payload, token } as ConfirmedWrite<T>,\n });\n\n if (a.planOnly === true) {\n return { ok: false, code: 'PLANNED', token, preview: previewLines(plan, budgetLine) };\n }\n\n if (a.token !== undefined) {\n if (a.mode === 'interactive') {\n return refuse(\n `--confirm is not accepted in interactive approval mode; nothing was sent`,\n 'In this mode only a human at a terminal approves a write. The owner can allow agents ' +\n 'to confirm on their word with `lnrelay approval set agent`, run at a terminal.',\n );\n }\n if (a.token !== token) {\n return refuse(\n 'the content changed since it was previewed — the token no longer matches; nothing was sent',\n 'Run again with --plan, show the new preview, and confirm with the new token.',\n );\n }\n return mint();\n }\n\n if (a.mode === 'unattended') return mint();\n\n if (!deps.isTty) {\n return a.mode === 'agent'\n ? refuse(\n `'${plan.action}' needs the owner's approval of this exact content`,\n 'Nothing was sent. Run the same command with --plan, show the preview to the owner, ' +\n 'and when they approve re-run it with --confirm <token>.',\n )\n : refuse(\n `'${plan.action}' 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. Run this ' +\n 'command yourself in a shell. There is no --yes flag; only the owner can change how ' +\n 'writes are approved, with `lnrelay approval set`, at a terminal.',\n );\n }\n\n const answer = (await deps.prompt(renderPlan(plan, budgetLine))).trim();\n\n if (answer !== token) {\n return refuse(\n 'aborted — the confirmation token did not match',\n 'Nothing was sent. Re-run and type the token shown in the prompt.',\n );\n }\n\n return mint();\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 { readFileSync, statSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport type { Session } from '../engine/auth.ts';\nimport { buildHeaders } from '../engine/auth.ts';\nimport { createEngine, 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 currentValue,\n fetchProfileForm,\n PROFILE_FIELDS,\n type ProfileField,\n type ProfileForm,\n saveBody,\n sendProfileSave,\n} from '../engine/sdui-profile.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 { type MediaKind, mediaKindOf } from '../engine/voyager-media.ts';\nimport { replyToComment } from '../engine/voyager-reply.ts';\nimport {\n type ApprovedMedia,\n editPost,\n fetchLinkCard,\n firstUrl,\n type LinkCard,\n mediaDigest,\n type PollSpec,\n pollDuration,\n share as voyagerShare,\n} 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 { lookup, previewLines } from './delete.ts';\nimport {\n gateWrite,\n recordHarvestSpend,\n refuseUnapprovable,\n reserve,\n terminalDeps,\n} from './gate.ts';\nimport { runEditImage } from './profile-image.ts';\nimport { loadToken, OAUTH_SETUP } from './token.ts';\nimport { chooseTransport, type Transport } from './transport.ts';\n\nexport interface WriteContext {\n transport: Transport;\n now: number;\n note?: string;\n}\n\n/** The urn a write is authored as, for the confirmation summary. */\nexport function authorLine(transport: Transport): string {\n return transport.kind === 'oauth'\n ? `as ${transport.token.memberUrn}`\n : `as ${transport.session.ownerUrn ?? 'you (browser session)'}`;\n}\n\nexport function prepare(\n command: string,\n now: number,\n via?: 'oauth' | 'voyager',\n calls = 1,\n): 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, calls);\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\nexport async 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\n/** Read and identify a media file, or say why it cannot be posted. */\n/** What the CLI asked to attach: `--image` (repeatable) or one `--video`, plus `--alt`s. */\nexport interface MediaRequest {\n flag: 'image' | 'video' | 'document';\n paths: string[];\n /** Index-aligned with `paths`; \"\" means no alt text for that image. */\n alts?: string[];\n /** A document's title — LinkedIn will not post a document without one. */\n title?: string;\n}\n\nconst FLAG_KIND: Record<MediaRequest['flag'], MediaKind> = {\n image: 'IMAGE',\n video: 'VIDEO',\n document: 'DOCUMENT',\n};\nconst KIND_FLAG: Record<MediaKind, string> = {\n IMAGE: '--image',\n VIDEO: '--video',\n DOCUMENT: '--document',\n};\nconst KIND_WORD: Record<MediaKind, string> = {\n IMAGE: 'image ',\n VIDEO: 'video ',\n DOCUMENT: 'document',\n};\n\n/** One line per file for the preview, each followed by its alt text or title. */\nfunction mediaLines(media: ApprovedMedia[]): string[] {\n return media.flatMap(({ filename, kind, size, sha256, alt, title }) => [\n `${KIND_WORD[kind]} ${filename} (${Math.ceil(size / 1024)} KB, sha256 ${sha256.slice(0, 12)})`,\n ...(alt === undefined ? [] : [` alt \"${alt}\"`]),\n ...(title === undefined ? [] : [` title \"${title}\"`]),\n ]);\n}\n\n/** LinkedIn's own composer limit for a multi-image post. */\nconst MAX_IMAGES = 20;\n\n/** The request as a whole, before any file is read. Null when it is coherent. */\nfunction mediaRequestError(media: MediaRequest): Envelope | null {\n const alts = media.alts ?? [];\n const single = media.flag !== 'image';\n if (single && media.paths.length > 1) {\n return err(\n 'share',\n 'INVALID_INPUT',\n `a post carries one ${media.flag}`,\n `pass a single --${media.flag}`,\n );\n }\n if (media.flag !== 'image' && alts.length > 0) {\n return err('share', 'INVALID_INPUT', `--alt applies to images, not a ${media.flag}`);\n }\n if (media.flag === 'document' && (media.title ?? '').trim() === '') {\n return err(\n 'share',\n 'INVALID_INPUT',\n 'a document needs a title',\n 'pass --title \"<what readers see above the document>\"',\n );\n }\n if (media.flag !== 'document' && media.title !== undefined) {\n return err('share', 'INVALID_INPUT', '--title applies to a --document');\n }\n if (media.paths.length > MAX_IMAGES) {\n return err('share', 'INVALID_INPUT', `a post carries at most ${MAX_IMAGES} images`);\n }\n if (alts.length > 0 && alts.length !== media.paths.length) {\n return err(\n 'share',\n 'INVALID_INPUT',\n `${alts.length} --alt for ${media.paths.length} images; they pair up by position`,\n 'give one --alt per --image, in the same order; pass --alt \"\" for an image without one',\n );\n }\n return null;\n}\n\n/** Validate the request as a whole, then load every file, or say why not. */\nfunction loadAllMedia(\n media: MediaRequest,\n): { approved: ApprovedMedia[]; bytes: Uint8Array[] } | Envelope {\n const refused = mediaRequestError(media);\n if (refused !== null) return refused;\n\n const alts = media.alts ?? [];\n const approved: ApprovedMedia[] = [];\n const bytes: Uint8Array[] = [];\n for (const [i, path] of media.paths.entries()) {\n const one = loadMedia(media.flag, path);\n if ('ok' in one) return one;\n const alt = alts[i];\n let a = alt === undefined || alt === '' ? one.approved : { ...one.approved, alt };\n if (media.flag === 'document') a = { ...a, title: (media.title ?? '').trim() };\n approved.push(a);\n bytes.push(one.bytes);\n }\n return { approved, bytes };\n}\n\nfunction loadMedia(\n flag: MediaRequest['flag'],\n path: string,\n): { approved: ApprovedMedia; bytes: Uint8Array } | Envelope {\n const kind = mediaKindOf(path);\n if (kind === null) {\n return err(\n 'share',\n 'INVALID_INPUT',\n `unsupported file type: ${basename(path)}`,\n 'images: png, jpg, jpeg, gif, webp. videos: mp4, mov. documents: pdf.',\n );\n }\n if (kind.kind !== FLAG_KIND[flag]) {\n return err(\n 'share',\n 'INVALID_INPUT',\n `${basename(path)} is not ${flag === 'image' ? 'an image' : `a ${flag}`}`,\n `pass it with ${KIND_FLAG[kind.kind]}`,\n );\n }\n let bytes: Uint8Array;\n try {\n if (!statSync(path).isFile()) throw new Error('not a file');\n bytes = new Uint8Array(readFileSync(path));\n } catch {\n return err('share', 'INVALID_INPUT', `cannot read ${path}`);\n }\n return {\n bytes,\n approved: {\n filename: basename(path),\n kind: kind.kind,\n contentType: kind.contentType,\n size: bytes.byteLength,\n sha256: mediaDigest(bytes),\n },\n };\n}\n\n/**\n * A schedule time, as epoch ms, or null. Accepts ISO 8601 with an offset or Z,\n * taken exactly, or \"YYYY-MM-DD HH:MM\" in the machine's local time. Anything\n * else is refused rather than guessed: a misread time publishes at the wrong\n * moment, which cannot be taken back.\n */\nexport function parseScheduleTime(input: string): number | null {\n const iso = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:\\d{2})$/;\n if (iso.test(input)) {\n const t = Date.parse(input);\n return Number.isNaN(t) ? null : t;\n }\n const local = /^(\\d{4})-(\\d{2})-(\\d{2})[ T](\\d{2}):(\\d{2})$/.exec(input);\n if (local === null) return null;\n const [y, mo, d, h, mi] = local.slice(1).map(Number) as [number, number, number, number, number];\n const date = new Date(y, mo - 1, d, h, mi);\n // Date rolls 2026-13-40 over into a real date; refuse instead of moving it.\n const same =\n date.getFullYear() === y &&\n date.getMonth() === mo - 1 &&\n date.getDate() === d &&\n date.getHours() === h &&\n date.getMinutes() === mi;\n return same ? date.getTime() : null;\n}\n\n/** Uploads plus pacing take minutes; a closer time could pass before the post lands. */\nconst MIN_LEAD_MS = 10 * 60_000;\n\n/** The loaded files, undefined when none were asked for, or the refusal. */\nfunction mediaFrom(\n media: MediaRequest | undefined,\n via: 'oauth' | 'voyager' | undefined,\n): { approved: ApprovedMedia[]; bytes: Uint8Array[] } | undefined | Envelope {\n if (media === undefined || media.paths.length === 0) return undefined;\n const loaded = loadAllMedia(media);\n if ('ok' in loaded) return loaded;\n // Media upload exists only over Voyager. An explicit --via oauth is refused\n // rather than rerouted: switching transport silently is what the design bans.\n if (via === 'oauth') {\n return err(\n 'share',\n 'NOT_IMPLEMENTED',\n 'posting media is only implemented over the private API',\n 'drop --via oauth, or pass --via voyager',\n );\n }\n return loaded;\n}\n\nexport interface SharePayloadIn {\n text: string;\n visibility: 'PUBLIC' | 'CONNECTIONS';\n media?: ApprovedMedia[];\n scheduledAt?: number;\n poll?: PollSpec;\n card?: LinkCard;\n}\n\n/** The approved payload and what the owner is shown about it. */\nfunction sharePlan(p: {\n author: string;\n transport: 'oauth' | 'voyager';\n text: string;\n visibility: 'PUBLIC' | 'CONNECTIONS';\n media: ApprovedMedia[] | undefined;\n scheduledAt: number | undefined;\n poll: PollSpec | undefined;\n /** Absent: no link, or no card asked for. `null`: asked, and LinkedIn has none. */\n card?: LinkCard | null;\n now: number;\n}): WritePlan<SharePayloadIn> {\n const payload: SharePayloadIn = { text: p.text, visibility: p.visibility };\n if (p.media !== undefined) payload.media = p.media;\n if (p.scheduledAt !== undefined) payload.scheduledAt = p.scheduledAt;\n if (p.poll !== undefined) payload.poll = p.poll;\n if (p.card !== undefined && p.card !== null) payload.card = p.card;\n\n const scheduled = p.scheduledAt !== undefined;\n return {\n action: scheduled ? 'schedule a post' : 'post to your feed',\n payload,\n summary: [\n p.author,\n `content \"${p.text}\"`,\n `audience ${p.visibility}`,\n ...(p.scheduledAt === undefined ? [] : [whenLine(p.scheduledAt, p.now)]),\n ...(p.poll === undefined ? [] : pollLines(p.poll)),\n ...(p.media === undefined ? [] : mediaLines(p.media)),\n ...cardLines(p.card),\n ],\n reversibility: scheduled\n ? 'cancel any time before it publishes with `lnrelay delete <urn>`; after that it is ' +\n 'public under your name like any post'\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: p.transport,\n };\n}\n\nfunction cardLines(card: LinkCard | null | undefined): string[] {\n if (card === undefined) return [];\n if (card === null) return ['card none — LinkedIn has no preview for this link'];\n return [`card \"${card.title}\" (${card.source})`];\n}\n\n/** How a link in the text is handled. `lookup` is injectable for tests. */\nexport interface LinkOptions {\n /** false: post the link as text (`--no-card`). */\n card?: boolean;\n lookup?: (url: string, session: Session) => ReturnType<typeof fetchLinkCard>;\n}\n\nconst liveCardLookup: NonNullable<LinkOptions['lookup']> = (url, session) =>\n fetchLinkCard(url, createLiveClient(session));\n\n/**\n * What a share costs and whether it must go over Voyager. Register + upload per\n * file, then the post: all must fit, or uploads are orphans. Media, scheduling,\n * polls and cards exist only over Voyager, so any one pins it.\n */\nfunction shareNeeds(\n files: number | undefined,\n scheduledAt: number | undefined,\n poll: PollSpec | undefined,\n cardUrl: string | null,\n): { voyagerOnly: boolean; calls: number } {\n const extra = (poll === undefined ? 0 : 1) + (cardUrl === null ? 0 : 1);\n return {\n voyagerOnly: files !== undefined || scheduledAt !== undefined || extra > 0,\n calls: 2 * (files ?? 0) + extra + 1,\n };\n}\n\n/**\n * The card for a link: undefined when none was asked for, null when LinkedIn\n * has none, or why it could not be asked.\n */\nasync function cardFor(\n url: string | null,\n transport: { kind: 'oauth' } | { kind: 'voyager'; session: Session },\n link: LinkOptions,\n): Promise<LinkCard | null | undefined | Envelope> {\n if (url === null || transport.kind !== 'voyager') return undefined;\n const found = await (link.lookup ?? liveCardLookup)(url, transport.session);\n if (found.ok) return found.card;\n return err(\n 'share',\n found.code,\n `could not look up the card for ${url}: ${found.message}; nothing was posted`,\n 'Re-run later, or add --no-card to post the link as plain text.',\n );\n}\n\n/** What the CLI asked for, before validation: `--poll`, `--option`s, `--duration`. */\nexport interface PollRequest {\n question: string;\n options: string[];\n duration?: string;\n}\n\nfunction pollLines(poll: PollSpec): string[] {\n return [\n `poll \"${poll.question}\"`,\n ...poll.options.map((o, i) => ` ${i + 1}. ${o}`),\n ` runs ${poll.duration}`,\n ];\n}\n\n/** A valid poll, undefined when none was asked for, or the refusal. */\nfunction pollFrom(\n poll: PollRequest | undefined,\n ctx: { hasMedia: boolean; scheduled: boolean; via: 'oauth' | 'voyager' | undefined },\n): PollSpec | undefined | Envelope {\n if (poll === undefined) return undefined;\n const refuse = (message: string, hint?: string) => err('share', 'INVALID_INPUT', message, hint);\n if (poll.question.trim() === '') return refuse('a poll needs a question');\n const options = poll.options.map((o) => o.trim());\n if (options.length < 2 || options.length > 4 || options.some((o) => o === '')) {\n return refuse('a poll needs 2 to 4 non-empty options', 'repeat --option \"<text>\" for each');\n }\n const duration = pollDuration(poll.duration ?? '1w');\n if (duration === null) {\n return refuse(`unknown --duration '${poll.duration}'`, 'one of: 1d, 3d, 1w, 2w');\n }\n if (ctx.hasMedia) return refuse('a post carries a poll or files, not both');\n // A scheduled probe showed the poll as \"1w left\" a week before it would\n // publish: its clock seems to start at creation. Until that is settled, a\n // scheduled poll could open already closed.\n if (ctx.scheduled) {\n return refuse(\n 'a poll cannot be scheduled yet — its clock may start when it is created, not published',\n 'post the poll now, or schedule a text post that asks the question',\n );\n }\n if (ctx.via === 'oauth') {\n return err(\n 'share',\n 'NOT_IMPLEMENTED',\n 'polls are only implemented over the private API',\n 'drop --via oauth, or pass --via voyager',\n );\n }\n return { question: poll.question.trim(), options, duration };\n}\n\n/** `--at` as epoch ms, undefined when absent, or the refusal. */\nfunction scheduleFrom(\n at: string | undefined,\n now: number,\n via: 'oauth' | 'voyager' | undefined,\n): number | undefined | Envelope {\n if (at === undefined) return undefined;\n const t = parseScheduleTime(at);\n if (t === null) {\n return err(\n 'share',\n 'INVALID_INPUT',\n `cannot read --at '${at}'`,\n 'use \"YYYY-MM-DD HH:MM\" (local time) or ISO 8601 with an offset, e.g. 2026-10-20T14:00+02:00',\n );\n }\n if (t < now + MIN_LEAD_MS) {\n return err(\n 'share',\n 'INVALID_INPUT',\n '--at must be at least 10 minutes from now',\n 'to post right away, leave --at out',\n );\n }\n if (via === 'oauth') {\n return err(\n 'share',\n 'NOT_IMPLEMENTED',\n 'scheduling is only implemented over the private API',\n 'drop --via oauth, or pass --via voyager',\n );\n }\n return t;\n}\n\n/** \"Tue, Oct 20, 2026, 14:00 (Europe/Budapest) — in 7 days\" */\nfunction whenLine(at: number, now: number): string {\n const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n const local = new Date(at).toLocaleString('en-US', {\n weekday: 'short',\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n hour: '2-digit',\n minute: '2-digit',\n hour12: false,\n });\n const hours = Math.round((at - now) / 3_600_000);\n const away = hours < 48 ? `in ${hours} h` : `in ${Math.round(hours / 24)} days`;\n return `when ${local} (${zone}) — ${away}`;\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 media?: MediaRequest,\n at?: string,\n poll?: PollRequest,\n link: LinkOptions = {},\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\n const scheduled = scheduleFrom(at, now, via);\n if (typeof scheduled === 'object') return scheduled;\n const scheduledAt = scheduled;\n\n const loaded = mediaFrom(media, via);\n if (loaded !== undefined && 'ok' in loaded) return loaded;\n const pollSpec = pollFrom(poll, {\n hasMedia: loaded !== undefined,\n scheduled: scheduledAt !== undefined,\n via,\n });\n if (pollSpec !== undefined && 'ok' in pollSpec) return pollSpec;\n\n // A link gets the card the composer would show, unless the post already\n // carries media or a poll (one kind per post), or the owner chose OAuth.\n const cardUrl =\n link.card !== false && loaded === undefined && pollSpec === undefined && via !== 'oauth'\n ? firstUrl(text)\n : null;\n\n const needs = shareNeeds(loaded?.approved.length, scheduledAt, pollSpec, cardUrl);\n const ctx = prepare('share', now, needs.voyagerOnly ? 'voyager' : via, needs.calls);\n if ('ok' in ctx) return ctx;\n\n const card = await cardFor(cardUrl, ctx.transport, link);\n if (card !== undefined && card !== null && 'ok' in card) return card;\n\n const plan = sharePlan({\n author: authorLine(ctx.transport),\n transport: ctx.transport.kind,\n text,\n visibility: vis,\n media: loaded?.approved,\n scheduledAt,\n poll: pollSpec,\n ...(card === undefined ? {} : { card: card as LinkCard | null }),\n now,\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), loaded?.bytes);\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 scheduledFor: scheduledAt === undefined ? undefined : new Date(scheduledAt).toISOString(),\n url: 'url' in result ? result.url : undefined,\n note: 'note' in result ? result.note : ctx.note,\n });\n}\n\n/**\n * Replace the text of one of the owner's own posts. The preview shows the text\n * being replaced when the post is among recent ones, so the owner approves a\n * change, not just a new string.\n */\nasync function runEditPost(\n urn: string,\n text: string,\n now: number,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n const unapprovable = refuseUnapprovable('edit', 'editing', deps);\n if (unapprovable !== null) return unapprovable;\n\n const ctx = prepare('edit', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager') {\n return err(\n 'edit',\n 'NOT_IMPLEMENTED',\n 'editing a post is only implemented over the private API',\n );\n }\n\n const before = await lookup(urn, true);\n const plan: WritePlan<{ urn: string; text: string }> = {\n action: 'edit your post',\n payload: { urn, text },\n summary: [\n authorLine(ctx.transport),\n `post ${urn}`,\n ...previewLines(before).map((l) => l.replace(/^content /, 'was ')),\n `new text \"${text}\"`,\n ],\n reversibility:\n 'editable again, but the previous text is NOT kept here, LinkedIn marks the post as ' +\n 'edited, and an @mention in the old text is not carried over',\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 editPost(gated.confirmed as never, createLiveClient(ctx.transport.session));\n return result.ok\n ? ok('edit', { edited: urn })\n : err('edit', result.code, result.message, result.hint);\n}\n\ntype ProfileFailure = { ok: false; code: string; message: string; hint?: string };\n\n/** What a profile edit needs from LinkedIn. Injectable so tests send nothing. */\nexport interface ProfileSurface {\n vanity(): Promise<{ ok: true; vanity: string } | ProfileFailure>;\n open(field: ProfileField, vanity: string): Promise<ProfileForm | ProfileFailure>;\n send(form: ProfileForm, body: Record<string, unknown>): Promise<{ ok: true } | ProfileFailure>;\n}\n\nexport function liveProfile(session: Session): ProfileSurface {\n const client = createLiveClient(session);\n return {\n vanity: async () => {\n const me = await createEngine(session).whoami();\n if (!me.ok) return me;\n const id = (me.value?.publicIdentifier ?? null) as string | null;\n return typeof id === 'string' && id !== ''\n ? { ok: true, vanity: id }\n : { ok: false, code: 'SCHEMA_DRIFT', message: 'whoami returned no public profile id' };\n },\n open: (field, vanity) => fetchProfileForm(field, vanity, client),\n send: (form, body) => sendProfileSave(form, body, client),\n };\n}\n\nconst PROFILE_HINT = `profile fields: ${Object.keys(PROFILE_FIELDS).join(', ')}`;\n\n/**\n * Replace one text field on the owner's profile. The form is read first, so\n * the owner approves a change from what is there now to what will be, and the\n * save sends every other field back exactly as LinkedIn holds it.\n */\nexport async function runEditProfile(\n name: string,\n text: string | undefined,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n surface?: ProfileSurface,\n): Promise<Envelope> {\n const field = (PROFILE_FIELDS as Record<string, ProfileField>)[name];\n if (field === undefined) {\n return err(\n 'edit',\n 'INVALID_INPUT',\n `'${name}' is not a profile field this edits`,\n PROFILE_HINT,\n );\n }\n if (text === undefined || text.trim() === '') {\n return err(\n 'edit',\n 'INVALID_INPUT',\n `the new ${name} is required`,\n `lnrelay edit ${name} \"<text>\"`,\n );\n }\n if (text.length > field.maxLength) {\n return err(\n 'edit',\n 'INVALID_INPUT',\n `the ${name} is ${text.length} characters; LinkedIn allows ${field.maxLength}`,\n );\n }\n\n const unapprovable = refuseUnapprovable('edit', 'editing', deps);\n if (unapprovable !== null) return unapprovable;\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', 'profile edits go over the browser session only');\n }\n const profile = surface ?? liveProfile(ctx.transport.session);\n\n const me = await profile.vanity();\n if (!me.ok) return err('edit', me.code, me.message, me.hint);\n const form = await profile.open(field, me.vanity);\n if (!form.ok) return err('edit', form.code, form.message, form.hint);\n const was = currentValue(form, field) ?? '';\n if (was === text) {\n return err('edit', 'INVALID_INPUT', `your ${name} already reads exactly that; nothing to save`);\n }\n const built = saveBody(form, field, text);\n if (!built.ok) return err('edit', built.code, built.message, built.hint);\n\n // `was` is in the payload so the token binds it: a profile that changed\n // after the owner looked is a different edit from the one they approved.\n const plan: WritePlan<{ field: string; was: string; text: string }> = {\n action: `change your ${name}`,\n payload: { field: name, was, text },\n summary: [\n authorLine(ctx.transport),\n `field ${name}`,\n `was \"${was}\"`,\n `new \"${text}\"`,\n ],\n reversibility:\n 'editable again, but the old text is kept only in this preview and the audit log ' +\n '(~/.lnrelay/writes.jsonl). Every other profile field is sent back as LinkedIn holds it.',\n transport: 'voyager',\n };\n const gated = await gate('edit', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const sent = await profile.send(form, built.body);\n if (!sent.ok) return err('edit', sent.code, sent.message, sent.hint);\n\n // Never an empty success: read it back.\n const after = await profile.open(field, me.vanity);\n const reads = after.ok ? currentValue(after, field) : undefined;\n if (reads !== text) {\n return err(\n 'edit',\n 'SCHEMA_DRIFT',\n `LinkedIn accepted the save, but your ${name} does not read back as the new text`,\n after.ok ? `It reads: \"${reads ?? ''}\"` : `The read-back failed: ${after.message}`,\n );\n }\n return ok('edit', { field: name, verified: true });\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 const unapprovable = refuseUnapprovable('comment', 'commenting', deps);\n if (unapprovable !== null) return unapprovable;\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 // The harvested trackingId changes on every render, so --plan and --confirm\n // would never agree on a token derived from it. The intent is what's approved.\n tokenBasis: { activityId, text },\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 if (commentUrn === 'photo' || commentUrn === 'banner') {\n return runEditImage(commentUrn, text, now, deps);\n }\n const ref: CommentRef | null = parseCommentUrn(commentUrn);\n if (ref === null && !commentUrn.startsWith('urn:')) {\n return runEditProfile(commentUrn, text, now, deps);\n }\n if (ref === null) {\n // Like delete, edit routes by the KIND of urn: a comment and a post are\n // edited over different surfaces, and each is unambiguous.\n if (/^urn:li:(share|ugcPost):\\d+$/.test(commentUrn)) {\n return runEditPost(commentUrn, text, now, deps);\n }\n return err(\n 'edit',\n 'INVALID_INPUT',\n `'${commentUrn}' is neither a comment urn nor a post's share/ugcPost urn`,\n /^urn:li:activity:/.test(commentUrn)\n ? 'A post is edited by the urn it was created as, not its activity urn. `lnrelay share` ' +\n 'prints it, and `lnrelay my-posts` lists it as shareUrn.'\n : 'Pass a comment urn (from `lnrelay post <activity-urn>`) or a post urn ' +\n '(urn:li:share:… / urn:li:ugcPost:…).',\n );\n }\n\n const unapprovable = refuseUnapprovable('edit', 'editing', deps);\n if (unapprovable !== null) return unapprovable;\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 const unapprovable = refuseUnapprovable('reply', 'replying', deps);\n if (unapprovable !== null) return unapprovable;\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","// ─── 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","// ─── 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, captured 2026-08-14. VERSIONED (`-43`), so it rotates like\n * the queryIds in contracts.ts — re-capture this first if replies start failing.\n *\n * A WARNING worth more than the constant: omitting it returns HTTP 500 **after\n * the reply has already been created**. Verified — the failed attempt appeared\n * on the post alongside the successful one. The write happens; only the\n * decorated response fails to build.\n *\n * So a 5xx from this endpoint does NOT mean nothing happened, and a retry\n * double-posts publicly. See the hint on the failure path below.\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 // Observed live: this endpoint can answer 500 with the reply ALREADY\n // POSTED. Telling the user to retry would double-post under their name.\n out.hint = /5\\d\\d|unexpected status/.test(result.message)\n ? 'DO NOT RETRY BLINDLY. This endpoint has been observed returning 5xx after the reply ' +\n 'was already created. Check the thread on LinkedIn before sending again.'\n : (result.hint ?? '');\n if (out.hint === '') delete out.hint;\n return out;\n }\n return { ok: true, parent: parentThreadUrn(ref) };\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 { createHash } from 'node:crypto';\nimport type { ConfirmedWrite } from '../commands/confirm.ts';\nimport type { Client } from './client.ts';\nimport { contractFor } from './contracts.ts';\nimport { type MediaKind, uploadMedia } from './voyager-media.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 /** Epoch ms. Present only on a scheduled post. */\n scheduledAt?: number;\n}\n\n/** What a post can carry: an upload, a poll, or a link card. */\nexport type ShareMediaCategory = MediaKind | 'POLL' | 'ARTICLE';\n\n/** The share-media `category` for each upload kind. A document is not \"DOCUMENT\". */\nconst CATEGORY: Record<ShareMediaCategory, string> = {\n POLL: 'URN_REFERENCE',\n ARTICLE: 'ARTICLE',\n IMAGE: 'IMAGE',\n VIDEO: 'VIDEO',\n DOCUMENT: 'NATIVE_DOCUMENT',\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(\n text: string,\n visibility: 'PUBLIC' | 'CONNECTIONS',\n media: { category: ShareMediaCategory; urn: string; alt?: string; title?: string }[] = [],\n scheduledAt?: number,\n): SharePayload {\n // LinkedIn publishes a SCHEDULED post itself at scheduledAt (verified 2026-10-13).\n const schedule =\n scheduledAt === undefined\n ? { postState: 'PUBLISHED' }\n : { postState: 'SCHEDULED', scheduledAt };\n return {\n visibleToConnectionsOnly: visibility === 'CONNECTIONS',\n externalAudienceProviders: [],\n commentaryV2: { text, attributes: [] },\n origin: 'FEED',\n allowedCommentersScope: 'ALL',\n ...schedule,\n // altText only when given, so a post without it keeps the body verified in 2026-08.\n media: media.map((m) => ({\n category: CATEGORY[m.category],\n mediaUrn: m.urn,\n tapTargets: [],\n ...(m.alt === undefined ? {} : { altText: m.alt }),\n ...(m.title === undefined ? {} : { title: { text: m.title } }),\n })),\n };\n}\n\n/** What the human approves about a file: its identity, not its bytes. */\nexport interface ApprovedMedia {\n filename: string;\n kind: MediaKind;\n contentType: string;\n size: number;\n sha256: string;\n /** Alt text for screen readers; images only. */\n alt?: string;\n /** A document's title, which LinkedIn requires; documents only. */\n title?: string;\n}\n\nexport function mediaDigest(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('hex');\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<{\n text: string;\n visibility: 'PUBLIC' | 'CONNECTIONS';\n media?: ApprovedMedia[];\n /** Epoch ms; makes this a scheduled post. */\n scheduledAt?: number;\n poll?: PollSpec;\n /** The link card the owner was shown; the article urn is what is sent. */\n card?: LinkCard;\n }>,\n client: Client,\n bytes?: Uint8Array[],\n): Promise<WriteResult> {\n const approved = confirmed.payload.media ?? [];\n const files = bytes ?? [];\n\n // The approval names each file by digest and the bytes travel separately —\n // so ALL of them are checked before anything leaves the machine. Checking\n // one at a time would upload the first before discovering the second changed.\n for (const [i, a] of approved.entries()) {\n const b = files[i];\n if (b === undefined || mediaDigest(b) !== a.sha256) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `${a.filename} changed after it was approved; nothing was sent`,\n };\n }\n }\n\n const media: { category: ShareMediaCategory; urn: string; alt?: string; title?: string }[] = [];\n const { card } = confirmed.payload;\n if (card !== undefined) media.push({ category: 'ARTICLE', urn: card.urn });\n\n // A poll is created first, as its own object, then referenced like media.\n const { poll } = confirmed.payload;\n if (poll !== undefined) {\n const created = await createPoll(poll, client);\n if (!created.ok) return created;\n media.push({ category: 'POLL', urn: created.urn });\n }\n for (const [i, a] of approved.entries()) {\n const uploaded = await uploadMedia(\n {\n bytes: files[i] as Uint8Array,\n filename: a.filename,\n kind: a.kind,\n contentType: a.contentType,\n },\n client,\n );\n if (!uploaded.ok) return uploaded;\n media.push({\n category: a.kind,\n urn: uploaded.urn,\n ...(a.alt === undefined ? {} : { alt: a.alt }),\n ...(a.title === undefined ? {} : { title: a.title }),\n });\n }\n\n const body = sharePayload(\n confirmed.payload.text,\n confirmed.payload.visibility,\n media,\n confirmed.payload.scheduledAt,\n );\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\n// ─── Editing a post ───────────────────────────────────────────────────────────\n//\n// VERIFIED LIVE 2026-10-13: a Rest.li partial update on normShares/<urn>\n// replaced a post's text, and the response returned the post as LinkedIn then\n// held it, media untouched. The same resource `delete` uses, so no rotating\n// queryId is involved. It replaces the WHOLE text: an @mention in the old text\n// is not carried over, because `attributes` is sent empty.\n\nexport function editPostBody(text: string) {\n return { patch: { $set: { commentaryV2: { text, attributes: [] } } } };\n}\n\nexport async function editPost(\n confirmed: ConfirmedWrite<{ urn: string; text: string }>,\n client: Client,\n): Promise<WriteResult> {\n const { urn, text } = confirmed.payload;\n const result = await client.request({\n url: deleteUrl(urn),\n method: 'POST',\n body: editPostBody(text),\n spendClass: 'write',\n operation: 'edit-post',\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 const held = (result.json as { data?: { commentary?: { text?: unknown } } } | null)?.data\n ?.commentary?.text;\n if (held !== text) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'LinkedIn answered, but the post does not hold the text that was sent',\n hint: `Look at the post before trying again: \\`lnrelay post\\` or the browser. ${urn}`,\n };\n }\n return { ok: true, id: urn };\n}\n\n// ─── Polls ────────────────────────────────────────────────────────────────────\n//\n// VERIFIED LIVE 2026-10-13: the PollsPollSummary mutation returned a\n// pollSummary urn, and normShares with media { category: URN_REFERENCE } posted\n// it — LinkedIn's own scheduled list showed it as a poll. Creating the poll\n// publishes nothing; it is an orphan until a post references it.\n\nexport type PollDuration = 'ONE_DAY' | 'THREE_DAYS' | 'ONE_WEEK' | 'TWO_WEEKS';\n\nexport interface PollSpec {\n question: string;\n options: string[];\n duration: PollDuration;\n}\n\nconst DURATIONS: Record<string, PollDuration> = {\n '1d': 'ONE_DAY',\n '3d': 'THREE_DAYS',\n '1w': 'ONE_WEEK',\n '2w': 'TWO_WEEKS',\n};\n\n/** The `--duration` shorthand as LinkedIn's enum, or null. */\nexport function pollDuration(shorthand: string): PollDuration | null {\n return DURATIONS[shorthand] ?? null;\n}\n\n/** The first GraphQL error message, wherever this envelope put it. */\nfunction gqlError(json: unknown): string | null {\n const j = json as { errors?: { message?: string }[]; data?: { errors?: { message?: string }[] } };\n const errors = j?.errors ?? j?.data?.errors;\n return errors !== undefined && errors.length > 0 ? (errors[0]?.message ?? 'GraphQL error') : null;\n}\n\n/** The created poll's urn, or null — including when the 200 carries errors. */\nexport function pollUrnOf(json: unknown): string | null {\n if (gqlError(json) !== null) return null;\n return JSON.stringify(json ?? null).match(/urn:li:fsd_pollSummary:\\d+/)?.[0] ?? null;\n}\n\nasync function createPoll(\n poll: PollSpec,\n client: Client,\n): Promise<\n { ok: true; urn: string } | { ok: false; code: string; message: string; hint?: string }\n> {\n const contract = contractFor('createPoll');\n if (contract?.queryId === undefined) {\n return { ok: false, code: 'NOT_IMPLEMENTED', message: 'no verified poll contract' };\n }\n const result = await client.request({\n url: `${contract.path}?action=execute&queryId=${contract.queryId}`,\n method: 'POST',\n body: { variables: { poll }, queryId: contract.queryId, includeWebMetadata: true },\n spendClass: 'write',\n operation: 'create-poll',\n });\n if (!result.ok)\n return { ok: false, code: result.code, message: `${result.message}; nothing was posted` };\n\n // GraphQL answers a validation failure with HTTP 200 — read the body, or a\n // refused poll would be reported as created.\n const error = gqlError(result.json);\n if (error !== null) {\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `LinkedIn refused the poll: ${error}; nothing was posted`,\n };\n }\n const urn = pollUrnOf(result.json);\n if (urn === null) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the poll mutation answered without a poll urn; nothing was posted',\n hint: 'The queryId may have rotated — recapture it (docs/ENGINE-RESEARCH.md).',\n };\n }\n return { ok: true, urn };\n}\n\n// ─── Link cards ───────────────────────────────────────────────────────────────\n//\n// A URL in the text is only text: a post sent without media renders it as a\n// bare link (verified 2026-10-13 on a scheduled probe — no card). The composer\n// makes the card by asking LinkedIn to resolve the URL into an article\n// (`urn:li:article:<id>`), and the post carries that urn as ARTICLE media.\n\nexport interface LinkCard {\n urn: string;\n title: string;\n /** The site, as LinkedIn names it under the title. */\n source: string;\n}\n\n/** The first link in the text — the one the web composer previews. */\nexport function firstUrl(text: string): string | null {\n const found = text.match(/https?:\\/\\/[^\\s<>\"]+/)?.[0];\n if (found === undefined) return null;\n // Closing punctuation belongs to the sentence, unless the link opened it.\n let url = found.replace(/[.,;:!?'\"]+$/, '');\n if (url.endsWith(')') && !url.includes('(')) url = url.slice(0, -1);\n return url;\n}\n\nexport function urlPreviewUrl(url: string): string {\n const contract = contractFor('urlPreview');\n return (\n `${contract?.path}?includeWebMetadata=true` +\n `&variables=(url:${encodeURIComponent(url)})&queryId=${contract?.queryId}`\n );\n}\n\ntype CardResult =\n | { ok: true; card: LinkCard | null }\n | { ok: false; code: string; message: string; hint?: string };\n\nexport function parseUrlPreview(json: unknown): CardResult {\n const error = gqlError(json);\n if (error !== null) {\n return { ok: false, code: 'SCHEMA_DRIFT', message: `the link preview failed: ${error}` };\n }\n const j = json as {\n data?: { data?: { contentcreationDashUpdateUrlPreviewByUrl?: { elements?: unknown[] } } };\n included?: {\n content?: {\n articleComponent?: {\n articleUrn?: string;\n title?: { text?: string };\n subtitle?: { text?: string };\n };\n };\n }[];\n };\n const elements = j?.data?.data?.contentcreationDashUpdateUrlPreviewByUrl?.elements;\n if (!Array.isArray(elements)) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the link preview response had no preview collection',\n hint: 'Re-capture the urlPreview contract: paste a link into the web composer.',\n };\n }\n if (elements.length === 0) return { ok: true, card: null };\n\n const article = (j.included ?? []).find((e) => e.content?.articleComponent?.articleUrn)?.content\n ?.articleComponent;\n if (article?.articleUrn === undefined) {\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'LinkedIn previewed the link but no article came with it',\n };\n }\n return {\n ok: true,\n card: {\n urn: article.articleUrn,\n title: article.title?.text ?? '',\n source: article.subtitle?.text ?? '',\n },\n };\n}\n\n/** Ask LinkedIn what card it would show for a link. A read. */\nexport async function fetchLinkCard(url: string, client: Client): Promise<CardResult> {\n const result = await client.request({\n url: urlPreviewUrl(url),\n spendClass: 'page',\n operation: 'link-preview',\n });\n if (!result.ok) {\n const out: CardResult = { ok: false, code: result.code, message: result.message };\n if (result.hint !== undefined) out.hint = result.hint;\n return out;\n }\n return parseUrlPreview(result.json);\n}\n","// ─── `lnrelay edit photo|banner <file>` ───────────────────────────────────────\n//\n// Replace the owner's profile photo or cover image with a file, as the\n// browser does (engine/sdui-profile-image.ts): register, upload, save. The\n// file is checked before anything is sent, the owner approves it by its\n// digest, and the profile is read back afterwards: the new image must be the\n// one showing, or the command fails.\n\nimport { readFileSync, statSync } from 'node:fs';\nimport { basename, resolve } from 'node:path';\nimport type { Session } from '../engine/auth.ts';\nimport { fullProfileUrl } from '../engine/full-profile.ts';\nimport { createEngine, createLiveClient } from '../engine/index.ts';\nimport type { Failure } from '../engine/sdui-form.ts';\nimport { sendAction } from '../engine/sdui-profile.ts';\nimport {\n IMAGE_KINDS,\n type ImageKeys,\n type ImageKind,\n type ImageRequest,\n imageSizeOf,\n newKeys,\n parseRegister,\n picturesOf,\n REGISTER_REQUEST,\n registerBody,\n saveBody,\n type Upload,\n} from '../engine/sdui-profile-image.ts';\nimport { mediaDigest } 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 { refuseUnapprovable, terminalDeps } from './gate.ts';\nimport { authorLine, gate, prepare } from './write.ts';\n\n/** What an image change needs from LinkedIn. Injectable so tests send nothing. */\nexport interface ImageSurface {\n vanity(): Promise<{ ok: true; vanity: string } | Failure>;\n pictures(\n vanity: string,\n ): Promise<{ ok: true; profileId: string; photo?: string; banner?: string } | Failure>;\n register(body: unknown): Promise<{ ok: true; raw: string } | Failure>;\n put(upload: Upload, bytes: Uint8Array, mimeType: string): Promise<{ ok: true } | Failure>;\n save(kind: ImageKind, body: unknown): Promise<{ ok: true } | Failure>;\n}\n\nfunction liveImages(session: Session): ImageSurface {\n const client = createLiveClient(session);\n return {\n vanity: async () => {\n const me = await createEngine(session).whoami();\n if (!me.ok) return me;\n const id = me.value?.publicIdentifier;\n return typeof id === 'string' && id !== ''\n ? { ok: true, vanity: id }\n : { ok: false, code: 'SCHEMA_DRIFT', message: 'whoami returned no public profile id' };\n },\n pictures: async (vanity) => {\n const r = await client.request({\n url: fullProfileUrl(vanity),\n spendClass: 'profile',\n operation: 'profile-pictures',\n });\n return r.ok ? picturesOf(r.json) : r;\n },\n register: async (body) => {\n const raw = await sendAction(REGISTER_REQUEST, body, client, 'image-register');\n return typeof raw === 'string' ? { ok: true, raw } : raw;\n },\n put: async (upload, bytes, mimeType) => {\n const r = await client.request({\n url: upload.url,\n method: 'PUT',\n bytes,\n headers: { 'content-type': mimeType, ...upload.headers },\n spendClass: 'write',\n operation: 'image-upload',\n });\n return r.ok ? { ok: true } : r;\n },\n save: async (kind, body) => {\n const raw = await sendAction(kind.save, body, client, `${kind.name}-save`);\n return typeof raw === 'string' ? { ok: true } : raw;\n },\n };\n}\n\n/** LinkedIn's own limit on either image. */\nconst MAX_BYTES = 8 * 1024 * 1024;\n\ntype Picked = { bytes: Uint8Array; width: number; height: number; mimeType: string };\n\n/** Read the file and check it is a PNG or JPEG of the shape `kind` takes. */\nfunction pick(kind: ImageKind, path: string): Picked | Envelope {\n let bytes: Uint8Array;\n try {\n if (!statSync(path).isFile()) throw new Error('not a file');\n bytes = new Uint8Array(readFileSync(path));\n } catch {\n return err('edit', 'INVALID_INPUT', `cannot read ${path}`);\n }\n if (bytes.byteLength > MAX_BYTES)\n return err('edit', 'INVALID_INPUT', `${basename(path)} is over LinkedIn's 8 MB limit`);\n const size = imageSizeOf(bytes);\n if (size === null)\n return err('edit', 'INVALID_INPUT', `${basename(path)} is not a PNG or JPEG image`);\n const ratio = size.width / size.height;\n if (Math.abs(ratio / kind.aspect - 1) > 0.02) {\n const want = kind.name === 'photo' ? 'square' : '4:1 (1584 × 396)';\n return err(\n 'edit',\n 'INVALID_INPUT',\n `${basename(path)} is ${size.width} × ${size.height}; a ${kind.label} must be ${want}`,\n 'It is uploaded as it is, uncropped: crop it to that shape first.',\n );\n }\n return { bytes, ...size };\n}\n\ntype Approved = { image: string; file: string; sha256: string; was: string | null };\n\nfunction planOf(\n kind: ImageKind,\n file: string,\n picked: Picked,\n was: string | undefined,\n author: string,\n): WritePlan<Approved> {\n const sha256 = mediaDigest(picked.bytes);\n return {\n action: `replace your ${kind.label}`,\n payload: { image: kind.name, file, sha256, was: was ?? null },\n summary: [\n author,\n `image ${kind.label}`,\n `file ${file}`,\n ` ${picked.width} × ${picked.height}, ${picked.bytes.byteLength} bytes, sha256 ${sha256.slice(0, 16)}…`,\n `now ${was === undefined ? 'none' : `asset ${was}`}`,\n ],\n reversibility:\n 'replaceable again with any file, but the current image is not kept here: have the ' +\n 'original file before replacing it. Everyone who can see your profile sees the change.',\n transport: 'voyager',\n };\n}\n\n/** Register, upload both copies, save. The display asset id, or why not. */\nasync function send(\n li: ImageSurface,\n kind: ImageKind,\n req: Omit<ImageRequest, 'displayName'> & { displayName: string },\n picked: Picked,\n): Promise<{ ok: true; displayId: string } | Envelope> {\n const nothing = (f: Failure, step: string) =>\n err('edit', f.code, `${step} failed (${f.message}); nothing changed on your profile`, f.hint);\n const registered = await li.register(registerBody(kind, req));\n if (!registered.ok) return nothing(registered, 'registering the image');\n const ticket = parseRegister(registered.raw, req.keys);\n if (!ticket.ok) return nothing(ticket, 'registering the image');\n for (const upload of [ticket.uploads.original, ticket.uploads.display]) {\n const put = await li.put(upload, picked.bytes, picked.mimeType);\n if (!put.ok) return nothing(put, 'uploading the image');\n }\n const saved = await li.save(kind, saveBody(kind, { ...req, ...ticket }));\n if (!saved.ok)\n return err('edit', saved.code, `saving the ${kind.label} failed: ${saved.message}`);\n return { ok: true, displayId: ticket.displayId };\n}\n\nexport async function runEditImage(\n name: string,\n path: string | undefined,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n surface?: ImageSurface,\n keys?: ImageKeys,\n): Promise<Envelope> {\n const kind = (IMAGE_KINDS as Record<string, ImageKind>)[name];\n if (kind === undefined)\n return err('edit', 'INVALID_INPUT', `'${name}' is not an image this edits`, 'photo, banner');\n if (path === undefined || path.trim() === '')\n return err('edit', 'INVALID_INPUT', 'an image file is required', `lnrelay edit ${name} <file>`);\n const file = resolve(path);\n const picked = pick(kind, file);\n if ('ok' in picked) return picked;\n\n const unapprovable = refuseUnapprovable('edit', 'editing', deps);\n if (unapprovable !== null) return unapprovable;\n // register, two uploads, save\n const ctx = prepare('edit', now, 'voyager', 4);\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager')\n return err('edit', 'NOT_IMPLEMENTED', 'profile edits go over the browser session only');\n const li = surface ?? liveImages(ctx.transport.session);\n\n const me = await li.vanity();\n if (!me.ok) return err('edit', me.code, me.message, me.hint);\n const before = await li.pictures(me.vanity);\n if (!before.ok) return err('edit', before.code, before.message, before.hint);\n\n const plan = planOf(kind, file, picked, before[kind.name], authorLine(ctx.transport));\n const gated = await gate('edit', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const ext = picked.mimeType === 'image/png' ? 'png' : 'jpg';\n const sent = await send(\n li,\n kind,\n {\n profileId: before.profileId,\n vanity: me.vanity,\n file: { name: basename(file), mimeType: picked.mimeType, size: picked.bytes.byteLength },\n keys: keys ?? newKeys(kind),\n displayName: `edited-image-${new Date(now).toISOString().replace(/[:.]/g, '-')}.${ext}`,\n },\n picked,\n );\n if (!('displayId' in sent)) return sent;\n\n // Never an empty success: the new image must be the one showing.\n const after = await li.pictures(me.vanity);\n if (!after.ok || after[kind.name] !== sent.displayId) {\n return err(\n 'edit',\n 'SCHEMA_DRIFT',\n `LinkedIn accepted the save, but your ${kind.label} does not read back as the new image`,\n after.ok\n ? `It shows asset ${after[kind.name] ?? 'none'}; the upload was ${sent.displayId}.`\n : `The read-back failed: ${after.message}`,\n );\n }\n return ok('edit', { image: kind.name, verified: true, asset: sent.displayId });\n}\n","// ─── The profile photo and the cover image ────────────────────────────────────\n//\n// Captured 2026-10-19 by changing each in the browser. Both are three steps,\n// over the same SDUI register request:\n//\n// 1. server-request profileImageRegister: the file described (name, type,\n// size) as an ORIGINAL and a DISPLAY image, each with an empty\n// asset-urn state. The answer sets those states to two digitalmedia\n// asset ids and carries an upload instruction for each: a /dms-uploads/\n// URL and its headers (`mediaTypeFamily: STILLIMAGE`).\n// 2. PUT each file to its URL.\n// 3. server-request saveProfilePicture / saveProfileBackgroundImage, naming\n// the display image and both asset ids. This is the step that changes\n// the profile; 1 and 2 leave orphan assets nobody sees.\n//\n// The browser uploads its editor's render (cropped, scaled) as the display\n// image and the picked file as the original. Here the file is both, with the\n// crop set to the whole image, so the file must already be the right shape:\n// square for the photo, 4:1 for the cover (LinkedIn's 1584 × 396).\n//\n// The keys (`auto-binding-…`) and file pointers are the client's own choice;\n// LinkedIn echoes them back, which is how the answer is read.\n\nimport { randomUUID } from 'node:crypto';\nimport { type Failure, responseErrors } from './sdui-form.ts';\n\nexport interface ImageKind {\n name: 'photo' | 'banner';\n /** What the owner calls it. */\n label: string;\n screen: string;\n originalType: string;\n displayType: string;\n save: string;\n /** Width over height the file must have, ±2%. */\n aspect: number;\n}\n\nexport const IMAGE_KINDS = {\n photo: {\n name: 'photo',\n label: 'profile photo',\n screen: 'com.linkedin.sdui.flagshipnav.profile.ProfileAddPicture',\n originalType: 'ProfileOriginalPhoto',\n displayType: 'ProfileDisplayPhoto',\n save: 'com.linkedin.sdui.requests.profile.saveProfilePicture',\n aspect: 1,\n },\n banner: {\n name: 'banner',\n label: 'cover image',\n screen: 'com.linkedin.sdui.flagshipnav.profile.ProfileAddBackgroundImage',\n originalType: 'ProfileOriginalBackground',\n displayType: 'ProfileDisplayBackground',\n save: 'com.linkedin.sdui.requests.profile.saveProfileBackgroundImage',\n aspect: 4,\n },\n} as const satisfies Record<string, ImageKind>;\n\nconst REGISTER = 'com.linkedin.sdui.requests.profile.profileImageRegister';\nexport const REGISTER_REQUEST = REGISTER;\nconst NS = 'MemoryNamespace';\n/** The photo editor's saving flag has a fixed name; the cover's is generated. */\nconst PHOTO_SAVING = 'ADD_PHOTOPROFILE_PHOTO_UPLOAD_IS_SAVING';\n\nexport interface ImageKeys {\n originalMedia: string;\n originalAssetUrns: string;\n displayMedia: string;\n displayAssetUrns: string;\n saving: string;\n originalPointer: string;\n displayPointer: string;\n}\n\nconst binding = () => `auto-binding-${randomUUID()}`;\nconst pointer = () => Math.random().toString(36).slice(2, 13).padEnd(11, '0');\n\nexport function newKeys(kind: ImageKind): ImageKeys {\n return {\n originalMedia: binding(),\n originalAssetUrns: binding(),\n displayMedia: binding(),\n displayAssetUrns: binding(),\n saving: kind.name === 'photo' ? PHOTO_SAVING : binding(),\n originalPointer: pointer(),\n displayPointer: pointer(),\n };\n}\n\nexport interface ImageFile {\n name: string;\n mimeType: string;\n size: number;\n}\n\nexport interface ImageRequest {\n profileId: string;\n vanity: string;\n file: ImageFile;\n keys: ImageKeys;\n /** What the display copy is called; the browser names its render this way. */\n displayName?: string;\n}\n\nconst focusKey = (vanity: string) =>\n `ProfileComponentStateLastPerformedActionRef${vanity}ProfileComponentState`;\nconst bind = (key: string) => ({ key, namespace: NS });\nconst stateKey = (id: string) => ({ key: { value: { $case: 'id', id } } });\nconst META = { $type: 'proto.sdui.common.RequestMetadata' } as const;\n\n/** The whole image, unscaled and unfiltered: the file is already the shape it should be. */\nconst WHOLE_IMAGE = {\n $type: 'proto.sdui.media.MediaEditData',\n croppedRegion: {\n $type: 'proto.sdui.common.Rect',\n topLeft: { $type: 'proto.sdui.common.Coordinate2D', x: 0, y: 0 },\n topRight: { $type: 'proto.sdui.common.Coordinate2D', x: 1, y: 0 },\n bottomLeft: { $type: 'proto.sdui.common.Coordinate2D', x: 0, y: 1 },\n bottomRight: { $type: 'proto.sdui.common.Coordinate2D', x: 1, y: 1 },\n },\n scaleRatio: 1,\n brightness: 0,\n contrast: 0,\n saturation: 0,\n vignette: 0,\n imageFilter: 'ImageFilter_None',\n};\n\nfunction mediaList(file: ImageFile, name: string, ptr: string, edited: boolean) {\n const size = String(file.size);\n return {\n $type: 'proto.sdui.media.MediaList',\n mediaFiles: [\n {\n mediaAttributions: [],\n analysisData: {},\n fileName: name,\n source: {\n $case: 'localFile',\n localFile: {\n fileName: name,\n mimeType: file.mimeType,\n filePointer: ptr,\n size,\n shouldIncludeFileContents: false,\n },\n },\n size,\n mimeType: file.mimeType,\n filePointer: ptr,\n mediaFileId: ptr,\n ...(edited ? { editData: WHOLE_IMAGE } : {}),\n captions: [],\n thumbnails: [],\n },\n ],\n };\n}\n\ntype Value = Record<string, unknown> | string[] | string | boolean;\nconst CASES: Record<string, string> = {\n object: 'mediaListValue',\n array: 'stringListValue',\n string: 'stringValue',\n boolean: 'booleanValue',\n};\n\nfunction state(key: string, value: Value) {\n const kind = Array.isArray(value) ? 'array' : typeof value;\n return {\n key,\n namespace: NS,\n value,\n originalProtoCase: CASES[kind] as string,\n protoKey: { $type: 'proto.sdui.Key', value: { $case: 'id', id: key } },\n };\n}\n\nfunction serverRequest(\n requestId: string,\n payload: Record<string, unknown>,\n states: ReturnType<typeof state>[],\n screenId: string,\n) {\n const requestedStateKeys = states.map((s) => stateKey(s.key));\n const requestedArguments = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys,\n payload,\n requestMetadata: META,\n };\n return {\n requestId,\n serverRequest: {\n requestId,\n requestedArguments,\n isApfcEnabled: false,\n isStreaming: false,\n rumPageKey: '',\n },\n states,\n requestedArguments: { ...requestedArguments, states, screenId, knownTemplateIds: [] },\n };\n}\n\nconst displayNameOf = (req: ImageRequest) =>\n req.displayName ??\n `edited-image-${new Date().toISOString().replace(/[:.]/g, '-')}.${req.file.name.split('.').pop()}`;\n\n/** The save's payload, and which states it reads, in the browser's order. */\nfunction savePlan(kind: ImageKind, req: ImageRequest) {\n const k = req.keys;\n const focus = focusKey(req.vanity);\n if (kind.name === 'photo') {\n return {\n payload: {\n profileId: req.profileId,\n vanityName: req.vanity,\n newMedia: bind(k.displayMedia),\n originalAssetUrns: bind(k.originalAssetUrns),\n displayAssetUrns: bind(k.displayAssetUrns),\n isSavingProfilePhoto: bind(k.saving),\n focusableComponentRefKey: bind(focus),\n },\n keys: [k.displayMedia, k.originalAssetUrns, k.displayAssetUrns, k.saving, focus],\n focusValue: 'topcard-logo-image-referencekey',\n };\n }\n return {\n payload: {\n vanityName: req.vanity,\n profileId: req.profileId,\n editedMedia: bind(k.displayMedia),\n displayAssetUrns: bind(k.displayAssetUrns),\n originalAssetUrns: bind(k.originalAssetUrns),\n focusableComponentRefKey: bind(focus),\n isSaving: bind(k.saving),\n omitDefaultPhotoFilterEditInfo: true,\n },\n keys: [k.displayMedia, k.displayAssetUrns, k.originalAssetUrns, focus],\n focusValue: `${req.vanity}_cover_edit_button`,\n };\n}\n\n/** Step 1: describe the file and ask where to upload it. Changes nothing visible. */\nexport function registerBody(kind: ImageKind, req: ImageRequest) {\n const k = req.keys;\n const save = savePlan(kind, req);\n const payload = {\n profileId: req.profileId,\n originalMedia: bind(k.originalMedia),\n originalAssetUrns: bind(k.originalAssetUrns),\n originalMediaType: kind.originalType,\n displayMedia: bind(k.displayMedia),\n displayMediaType: kind.displayType,\n displayAssetUrns: bind(k.displayAssetUrns),\n uploadOriginal: true,\n followUpRequest: { key: kind.save, data: save.payload, stateKeys: save.keys.map(bind) },\n skipEdit: false,\n isSaving: bind(k.saving),\n };\n return serverRequest(\n REGISTER,\n payload,\n [\n state(k.originalMedia, mediaList(req.file, req.file.name, k.originalPointer, false)),\n state(k.originalAssetUrns, []),\n state(k.displayMedia, mediaList(req.file, displayNameOf(req), k.displayPointer, true)),\n state(k.displayAssetUrns, []),\n state(k.saving, true),\n ],\n kind.screen,\n );\n}\n\n/** Step 3: put the uploaded image on the profile. */\nexport function saveBody(\n kind: ImageKind,\n req: ImageRequest & { originalId: string; displayId: string },\n) {\n const k = req.keys;\n const save = savePlan(kind, req);\n const values: Record<string, Value> = {\n [k.displayMedia]: mediaList(req.file, displayNameOf(req), k.displayPointer, true),\n [k.originalAssetUrns]: [req.originalId],\n [k.displayAssetUrns]: [req.displayId],\n [k.saving]: true,\n [focusKey(req.vanity)]: save.focusValue,\n };\n return serverRequest(\n kind.save,\n save.payload,\n save.keys.map((key) => state(key, values[key] as Value)),\n kind.screen,\n );\n}\n\n// ─── The register answer ──────────────────────────────────────────────────────\n\nexport interface Upload {\n url: string;\n headers: Record<string, string>;\n}\n\nexport type Registered =\n | {\n ok: true;\n originalId: string;\n displayId: string;\n uploads: { original: Upload; display: Upload };\n }\n | Failure;\n\ntype Node = Record<string, unknown>;\n\nfunction* walk(v: unknown): Generator<Node> {\n if (Array.isArray(v)) for (const x of v) yield* walk(x);\n else if (v !== null && typeof v === 'object') {\n yield v as Node;\n for (const x of Object.values(v)) yield* walk(x);\n }\n}\n\n/** `mediaTypeFamily` as the HTTP header the upload takes, `media-type-family`. */\nconst headerName = (key: string) => key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);\n\n/** The asset id a SetState puts in each key, keyed by that key. */\nfunction assetIdOf(n: Node): [string, string] | undefined {\n if (n.$type !== 'proto.sdui.actions.core.SetState') return undefined;\n const s = (n.value as Node | undefined)?.state as Node | undefined;\n const id = ((s?.key as Node | undefined)?.key as Node | undefined)?.value as Node | undefined;\n const list = ((s?.value as Node | undefined)?.stringListValue as Node | undefined)\n ?.stringValues as unknown[] | undefined;\n return typeof id?.id === 'string' && typeof list?.[0] === 'string' ? [id.id, list[0]] : undefined;\n}\n\n/** An upload instruction's file pointer, and its URL and headers ('multipart' if not one PUT). */\nfunction uploadOf(n: Node): [string, Upload | 'multipart'] | undefined {\n if (typeof n.fileReference !== 'string') return undefined;\n const instruction = (n.uploadInstruction as Node | undefined)?.instruction as Node | undefined;\n const single = instruction?.singleRequestUploadInstruction as Node | undefined;\n if (typeof single?.uploadUrl !== 'string') return [n.fileReference, 'multipart'];\n const headers: Record<string, string> = {};\n for (const h of (single.uploadHeaders as Node[] | undefined) ?? [])\n if (typeof h.key === 'string' && typeof h.value === 'string')\n headers[headerName(h.key)] = h.value;\n return [n.fileReference, { url: single.uploadUrl, headers }];\n}\n\nfunction rowZero(raw: string): unknown {\n const row = raw.match(/(?:^|\\n)0:(\\{.*)/)?.[1];\n try {\n return row === undefined ? undefined : JSON.parse(row);\n } catch {\n return undefined;\n }\n}\n\nexport function parseRegister(raw: string, keys: ImageKeys): Registered {\n const refused = responseErrors(raw);\n if (refused !== null)\n return { ok: false, code: 'INVALID_INPUT', message: `LinkedIn refused the image: ${refused}` };\n const ids = new Map<string, string>();\n const uploads = new Map<string, Upload | 'multipart'>();\n for (const n of walk(rowZero(raw))) {\n const id = assetIdOf(n);\n if (id !== undefined) ids.set(...id);\n const up = uploadOf(n);\n if (up !== undefined) uploads.set(...up);\n }\n const originalId = ids.get(keys.originalAssetUrns);\n const displayId = ids.get(keys.displayAssetUrns);\n const original = uploads.get(keys.originalPointer);\n const display = uploads.get(keys.displayPointer);\n if (original === 'multipart' || display === 'multipart')\n return {\n ok: false,\n code: 'NOT_IMPLEMENTED',\n message:\n 'LinkedIn asked for a multi-part upload, which has not been observed here. Nothing was ' +\n 'uploaded. Try a smaller file.',\n };\n if (originalId === undefined || displayId === undefined || !original || !display)\n return {\n ok: false,\n code: 'SCHEMA_DRIFT',\n message: 'the image registration carried no asset ids or upload urls; nothing was uploaded',\n };\n return { ok: true, originalId, displayId, uploads: { original, display } };\n}\n\n// ─── The file ─────────────────────────────────────────────────────────────────\n\n/** A PNG's or JPEG's dimensions from its header, or null for anything else. */\nexport function imageSizeOf(\n bytes: Uint8Array,\n): { width: number; height: number; mimeType: string } | null {\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const png = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\n if (bytes.length >= 24 && png.every((b, i) => bytes[i] === b))\n return { width: view.getUint32(16), height: view.getUint32(20), mimeType: 'image/png' };\n if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return null;\n let at = 2;\n while (at + 9 <= bytes.length) {\n if (bytes[at] !== 0xff) return null;\n const marker = bytes[at + 1] as number;\n // SOF0–SOF15, except DHT (C4), JPG (C8) and DAC (CC).\n if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker))\n return {\n height: view.getUint16(at + 5),\n width: view.getUint16(at + 7),\n mimeType: 'image/jpeg',\n };\n at += 2 + view.getUint16(at + 2);\n }\n return null;\n}\n\n// ─── Reading it back ──────────────────────────────────────────────────────────\n\n/**\n * The owner's profile id and the asset id of each picture showing now, from\n * the full profile (engine/full-profile.ts). A picture not set is left out.\n */\nexport function picturesOf(\n json: unknown,\n): { ok: true; profileId: string; photo?: string; banner?: string } | Failure {\n const root = json as { data?: Node; included?: Node[] } | null;\n const urn = (root?.data?.['*elements'] as unknown[] | undefined)?.[0];\n const p = (root?.included ?? []).find((n) => n.entityUrn === urn);\n const profileId = typeof urn === 'string' ? urn.split(':').pop() : undefined;\n if (p === undefined || profileId === undefined)\n return { ok: false, code: 'SCHEMA_DRIFT', message: 'the profile answer carried no profile' };\n const asset = (pic: unknown) =>\n String((pic as Node | null)?.displayImageUrn ?? '').match(/digitalmediaAsset:(.+)$/)?.[1];\n const photo = asset(p.profilePicture);\n const banner = asset(p.backgroundPicture);\n return {\n ok: true,\n profileId,\n ...(photo !== undefined ? { photo } : {}),\n ...(banner !== undefined ? { banner } : {}),\n };\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","// ─── 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","// ─── 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","// ─── `lnrelay role add|edit|remove`, and `lnrelay experience` ─────────────────\n//\n// Roles on the owner's Experience section. Every change is planned from the\n// form LinkedIn holds now and read back afterwards; see engine/sdui-position.ts\n// for how a save is put together and why the headline is never touched.\n\nimport type { Session } from '../engine/auth.ts';\nimport { createEngine, createLiveClient } from '../engine/index.ts';\nimport type { Failure, Model } from '../engine/sdui-form.ts';\nimport {\n applyChanges,\n fetchPositions,\n openPositionForm,\n type Position,\n type PositionChanges,\n type PositionForm,\n roleSummary,\n sendPositionDelete,\n sendPositionSave,\n type YearMonth,\n} from '../engine/sdui-position.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { ConfirmDeps, WritePlan } from './confirm.ts';\nimport { refuseUnapprovable, terminalDeps } from './gate.ts';\nimport { authorLine, gate, prepare } from './write.ts';\n\n/** What a role change needs from LinkedIn. Injectable so tests send nothing. */\nexport interface RoleSurface {\n vanity(): Promise<{ ok: true; vanity: string } | Failure>;\n list(vanity: string): Promise<{ ok: true; positions: Position[] } | Failure>;\n open(payload: Record<string, unknown>, edit: boolean): Promise<PositionForm | Failure>;\n save(form: PositionForm, model: Model): Promise<{ ok: true } | Failure>;\n remove(form: PositionForm): Promise<{ ok: true } | Failure>;\n}\n\nfunction liveRoles(session: Session, quiet = false): RoleSurface {\n const client = createLiveClient(session, undefined, quiet);\n return {\n vanity: async () => {\n const me = await createEngine(session, undefined, quiet).whoami();\n if (!me.ok) return me;\n const id = me.value?.publicIdentifier;\n return typeof id === 'string' && id !== ''\n ? { ok: true, vanity: id }\n : { ok: false, code: 'SCHEMA_DRIFT', message: 'whoami returned no public profile id' };\n },\n list: (vanity) => fetchPositions(vanity, client),\n open: (payload, edit) => openPositionForm(payload, client, edit),\n save: (form, model) => sendPositionSave(form, model, client),\n remove: (form) => sendPositionDelete(form, client),\n };\n}\n\n/** What the CLI asked for, before validation. Dates are YYYY-MM. */\nexport interface RoleRequest {\n title?: string;\n company?: string;\n start?: string;\n end?: string;\n current?: boolean;\n description?: string;\n location?: string;\n notify?: boolean;\n}\n\nconst SUBCOMMANDS = 'add, edit <position-id>, remove <position-id>';\n\nfunction yearMonth(flag: string, v: string): YearMonth | Envelope {\n const m = /^(\\d{4})-(\\d{2})$/.exec(v);\n const month = Number(m?.[2]);\n if (m === null || month < 1 || month > 12) {\n return err(\n 'role',\n 'INVALID_INPUT',\n `--${flag} '${v}' is not a month`,\n 'use YYYY-MM, e.g. 2021-06',\n );\n }\n return { year: Number(m[1]), month };\n}\n\nfunction changesFrom(req: RoleRequest): PositionChanges | Envelope {\n const c: PositionChanges = {};\n if (req.title !== undefined) c.title = req.title;\n if (req.company !== undefined) c.company = req.company;\n if (req.description !== undefined) c.description = req.description;\n if (req.location !== undefined) c.location = req.location;\n if (req.notify === true) c.notify = true;\n if (req.start !== undefined) {\n const d = yearMonth('start', req.start);\n if ('ok' in d) return d;\n c.start = d;\n }\n if (req.current === true && req.end !== undefined) {\n return err('role', 'INVALID_INPUT', '--current and --end contradict each other');\n }\n if (req.current === true) c.end = 'present';\n else if (req.end !== undefined) {\n const d = yearMonth('end', req.end);\n if ('ok' in d) return d;\n c.end = d;\n }\n return c;\n}\n\nconst span = (s: ReturnType<typeof roleSummary>) =>\n `${s.start ?? '?'} – ${s.current ? 'present' : (s.end ?? '?')}`;\nconst q = (v: string) => `\"${v.length > 160 ? `${v.slice(0, 160)}…` : v.replace(/\\n/g, ' ')}\"`;\n\nfunction roleLines(s: ReturnType<typeof roleSummary>): string[] {\n return [\n `title ${q(s.title)}`,\n `company ${q(s.company)}`,\n `dates ${span(s)}`,\n ...(s.location === '' ? [] : [`location ${q(s.location)}`]),\n ...(s.description === '' ? [] : [`about ${q(s.description)}`]),\n ];\n}\n\n/** Only what differs, from → to. */\nfunction diffLines(a: ReturnType<typeof roleSummary>, b: ReturnType<typeof roleSummary>): string[] {\n const out: string[] = [];\n const row = (label: string, x: string, y: string) => {\n if (x !== y) out.push(`${label.padEnd(8)} ${q(x)} → ${q(y)}`);\n };\n row('title', a.title, b.title);\n row('company', a.company, b.company);\n row('dates', span(a), span(b));\n row('location', a.location, b.location);\n row('about', a.description, b.description);\n return out;\n}\n\nconst SAFETY = (notify: boolean) => [\n 'headline unchanged (LinkedIn would otherwise rewrite it from this role)',\n `notify ${notify ? 'ON — your network may be told' : 'off'}`,\n];\n\nexport async function runRole(\n sub: string | undefined,\n target: string | undefined,\n req: RoleRequest,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n surface?: RoleSurface,\n): Promise<Envelope> {\n if (sub !== 'add' && sub !== 'edit' && sub !== 'remove') {\n return err(\n 'role',\n 'INVALID_INPUT',\n `unknown role subcommand '${sub ?? ''}'`,\n `lnrelay role ${SUBCOMMANDS}`,\n );\n }\n if (sub === 'add') {\n const missing = (['title', 'company', 'start'] as const).filter(\n (f) => req[f] === undefined || req[f] === '',\n );\n if (missing.length > 0) {\n return err(\n 'role',\n 'INVALID_INPUT',\n `a new role needs ${missing.map((f) => `--${f}`).join(', ')}`,\n );\n }\n } else if (target === undefined || !/^\\d+$/.test(target)) {\n return err(\n 'role',\n 'INVALID_INPUT',\n `role ${sub} needs a position id`,\n 'list them with `lnrelay experience`',\n );\n }\n const changes = changesFrom(req);\n if ('ok' in changes) return changes;\n if (sub === 'edit' && Object.keys(changes).filter((k) => k !== 'notify').length === 0) {\n return err(\n 'role',\n 'INVALID_INPUT',\n 'nothing to change',\n 'pass --title, --company, --start, --end, --current, --location or --description',\n );\n }\n\n const unapprovable = refuseUnapprovable('role', 'changing a role', deps);\n if (unapprovable !== null) return unapprovable;\n const ctx = prepare('role', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager') {\n return err('role', 'NOT_IMPLEMENTED', 'role changes go over the browser session only');\n }\n const roles = surface ?? liveRoles(ctx.transport.session);\n const me = await roles.vanity();\n if (!me.ok) return err('role', me.code, me.message, me.hint);\n const listed = await roles.list(me.vanity);\n if (!listed.ok) return err('role', listed.code, listed.message, listed.hint);\n\n if (sub === 'add') return addRole(changes, me.vanity, listed.positions, roles, ctx, deps);\n const position = listed.positions.find((p) => p.positionId === target);\n if (position === undefined) {\n return err(\n 'role',\n 'NOT_FOUND',\n `no role ${target} on your profile`,\n `your roles: ${listed.positions.map((p) => `${p.positionId} (${p.title})`).join(', ') || 'none'}`,\n );\n }\n const form = await roles.open({ ...position.payload, vanityName: me.vanity }, true);\n if (!form.ok) return err('role', form.code, form.message, form.hint);\n return sub === 'edit'\n ? editRole(position, form, changes, me.vanity, roles, ctx, deps)\n : removeRole(position, form, me.vanity, roles, ctx, deps);\n}\n\ntype Ctx = Exclude<ReturnType<typeof prepare>, Envelope>;\n\nasync function addRole(\n changes: PositionChanges,\n vanity: string,\n before: Position[],\n roles: RoleSurface,\n ctx: Ctx,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n const form = await roles.open({ vanityName: vanity }, false);\n if (!form.ok) return err('role', form.code, form.message, form.hint);\n const applied = applyChanges(form, changes);\n if (!applied.ok) return err('role', applied.code, applied.message, applied.hint);\n const role = roleSummary(applied.model);\n\n const plan: WritePlan<{ changes: PositionChanges }> = {\n action: 'add a role to your profile',\n payload: { changes },\n summary: [authorLine(ctx.transport), ...roleLines(role), ...SAFETY(changes.notify === true)],\n reversibility: 'removable with `lnrelay role remove <position-id>`',\n transport: 'voyager',\n };\n const gated = await gate('role', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const saved = await roles.save(form, applied.model);\n if (!saved.ok) return err('role', saved.code, saved.message, saved.hint);\n const after = await roles.list(vanity);\n const known = new Set(before.map((p) => p.positionId));\n const added = after.ok\n ? after.positions.find((p) => !known.has(p.positionId) && p.title === role.title)\n : undefined;\n if (added === undefined) {\n return err(\n 'role',\n 'SCHEMA_DRIFT',\n 'LinkedIn accepted the role, but it does not appear on your profile',\n );\n }\n return ok('role', { added: added.positionId, verified: true });\n}\n\nasync function editRole(\n position: Position,\n form: PositionForm,\n changes: PositionChanges,\n vanity: string,\n roles: RoleSurface,\n ctx: Ctx,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n const applied = applyChanges(form, changes);\n if (!applied.ok) return err('role', applied.code, applied.message, applied.hint);\n const was = roleSummary(form.model);\n const will = roleSummary(applied.model);\n const diff = diffLines(was, will);\n if (diff.length === 0)\n return err('role', 'INVALID_INPUT', 'the role already reads exactly that; nothing to save');\n\n // `was` is bound: a role that changed after the preview is a different edit.\n const plan: WritePlan<{ positionId: string; was: typeof was; changes: PositionChanges }> = {\n action: 'edit a role on your profile',\n payload: { positionId: position.positionId, was, changes },\n summary: [\n authorLine(ctx.transport),\n `role ${position.positionId}`,\n ...diff,\n ...SAFETY(changes.notify === true),\n ],\n reversibility: 'editable again; the old values are kept only in this preview and the audit log',\n transport: 'voyager',\n };\n const gated = await gate('role', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const saved = await roles.save(form, applied.model);\n if (!saved.ok) return err('role', saved.code, saved.message, saved.hint);\n const reread = await roles.open({ ...position.payload, vanityName: vanity }, true);\n const now = reread.ok ? roleSummary(reread.model) : null;\n if (now === null || diffLines(will, now).length > 0) {\n return err(\n 'role',\n 'SCHEMA_DRIFT',\n 'LinkedIn accepted the edit, but the role does not read back as edited',\n );\n }\n return ok('role', { edited: position.positionId, verified: true });\n}\n\nasync function removeRole(\n position: Position,\n form: PositionForm,\n vanity: string,\n roles: RoleSurface,\n ctx: Ctx,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n const role = roleSummary(form.model);\n const plan: WritePlan<{ positionId: string; role: typeof role }> = {\n action: 'remove a role from your profile',\n payload: { positionId: position.positionId, role },\n summary: [authorLine(ctx.transport), `role ${position.positionId}`, ...roleLines(role)],\n reversibility: 'NONE. LinkedIn deletes it; re-adding makes a new role.',\n transport: 'voyager',\n };\n const gated = await gate('role', plan, ctx, deps);\n if ('ok' in gated) return gated;\n\n const removed = await roles.remove(form);\n if (!removed.ok) return err('role', removed.code, removed.message, removed.hint);\n const after = await roles.list(vanity);\n if (!after.ok || after.positions.some((p) => p.positionId === position.positionId)) {\n return err(\n 'role',\n 'SCHEMA_DRIFT',\n 'LinkedIn accepted the removal, but the role is still listed',\n );\n }\n return ok('role', { removed: position.positionId, verified: true });\n}\n\n/** `lnrelay experience`: the roles on the owner's profile, with their ids. */\nexport async function runExperience(quiet = false): Promise<Envelope> {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('experience', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const roles = liveRoles(session.session, quiet);\n const me = await roles.vanity();\n if (!me.ok) return err('experience', me.code, me.message, me.hint);\n const listed = await roles.list(me.vanity);\n if (!listed.ok) return err('experience', listed.code, listed.message, listed.hint);\n return ok('experience', {\n items: listed.positions.map((p) => ({ positionId: p.positionId, title: p.title })),\n meta: { state: 'complete', returnedCount: listed.positions.length },\n });\n}\n","// ─── `lnrelay search <kind>` and `lnrelay search-filters <kind>` ──────────────\n//\n// For companies, groups, events, courses, products, services and schools; see\n// engine/search.ts. People and jobs have their own commands, which `search\n// people` and `search jobs` hand over to. Each call returns up to 50 results\n// and spends the search budget, as does a place looked up by name.\n\nimport { parsePeopleFilters } from '../engine/people.ts';\nimport {\n type Found,\n parseResults,\n SEARCH_PAGE,\n type SearchKindName,\n searchUrl,\n} from '../engine/search.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport {\n keywordSets,\n line,\n type Matched,\n metaOf,\n type PageFetch,\n type Paging,\n searchAll,\n} from './paged.ts';\nimport { type Lookup, liveFetch, type PeopleFetch, resolvePlace, shape } from './people.ts';\n\nexport interface FindRequest {\n keywords?: string | string[];\n limit: number;\n start?: number;\n /** A place by name, looked up, for the kinds that filter by place. */\n location?: string;\n industry?: string[];\n /** 1st, 2nd, 3rd+. */\n network?: string[];\n /** `key=v1,v2`, by LinkedIn's own names, from `search-filters <kind>`. */\n raw?: string[];\n}\n\n/** LinkedIn pages no further than 1000 into any one query. */\nconst PAGING: Paging = { pageSize: SEARCH_PAGE, max: 1000 };\n\n/** The friendly flags, and the parameter each kind knows them by. */\nconst FLAGS: Record<\n 'location' | 'industry' | 'network',\n Partial<Record<SearchKindName, string>>\n> = {\n location: { companies: 'companyHqGeo', services: 'geoUrn' },\n industry: { companies: 'industryCompanyVertical' },\n network: { companies: 'network', services: 'network' },\n};\n\nconst NETWORK: Record<string, string> = {\n '1st': 'F',\n '2nd': 'S',\n '3rd+': 'O',\n F: 'F',\n S: 'S',\n O: 'O',\n};\n\ntype Refusal = { ok: false; code: string; message: string; hint?: string };\n\nfunction paramFor(flag: keyof typeof FLAGS, kind: SearchKindName): string | Refusal {\n const param = FLAGS[flag][kind];\n if (param !== undefined) return param;\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `${kind} cannot be filtered by --${flag}`,\n hint: `--${flag} works for: ${Object.keys(FLAGS[flag]).join(', ')}; other filters are in \\`search-filters ${kind}\\``,\n };\n}\n\n/** The request's filters as LinkedIn's parameters; a place is looked up. */\nasync function paramsOf(\n kind: SearchKindName,\n req: Omit<FindRequest, 'limit'>,\n get: PeopleFetch,\n): Promise<{ params: Record<string, string[]>; resolved: Record<string, Lookup> } | Refusal> {\n const params: Record<string, string[]> = {};\n const resolved: Record<string, Lookup> = {};\n if (req.industry !== undefined && req.industry.length > 0) {\n const p = paramFor('industry', kind);\n if (typeof p !== 'string') return p;\n params[p] = req.industry;\n }\n if (req.network !== undefined && req.network.length > 0) {\n const p = paramFor('network', kind);\n if (typeof p !== 'string') return p;\n const codes = req.network.map((n) => NETWORK[n]);\n if (codes.some((c) => c === undefined))\n return { ok: false, code: 'INVALID_INPUT', message: '--network takes 1st, 2nd, 3rd+' };\n params[p] = codes as string[];\n }\n for (const r of req.raw ?? []) {\n const m = r.match(/^([A-Za-z_]+)=(.+)$/);\n if (m?.[1] === undefined || m[2] === undefined)\n return {\n ok: false,\n code: 'INVALID_INPUT',\n message: `--filter '${r}' is not key=value[,value]`,\n };\n params[m[1]] = m[2]\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v !== '');\n }\n if (req.location !== undefined && req.location.trim() !== '') {\n const p = paramFor('location', kind);\n if (typeof p !== 'string') return p;\n const place = await resolvePlace(get, req.location.trim());\n if ('ok' in place) return place;\n params[p] = [...(params[p] ?? []), place.id];\n resolved.location = place;\n }\n return { params, resolved };\n}\n\nfunction compactFound(f: Matched<Found>): string {\n return line([\n f.id,\n f.name,\n f.subtitle,\n f.detail,\n f.verified ? 'verified' : undefined,\n f.summary !== undefined && f.summary.length > 120 ? `${f.summary.slice(0, 117)}…` : f.summary,\n f.url,\n f.matched !== undefined ? `matched: ${f.matched.join(' + ')}` : undefined,\n ]);\n}\n\nexport async function runFind(\n kind: SearchKindName,\n req: FindRequest,\n opts: OutputOpts = {},\n fetch?: PeopleFetch,\n): Promise<Envelope> {\n const command = `search ${kind}`;\n const sets = keywordSets(req.keywords);\n const anyFilter =\n (req.location ?? '').trim() !== '' ||\n (req.industry?.length ?? 0) > 0 ||\n (req.network?.length ?? 0) > 0 ||\n (req.raw?.length ?? 0) > 0;\n if (sets.length === 0 && !anyFilter) {\n return err(\n command,\n 'INVALID_INPUT',\n 'give keywords, a filter, or both',\n `lnrelay search ${kind} \"<keywords>\"`,\n );\n }\n const get = fetch ?? liveFetch(command, opts.quiet === true);\n if (typeof get !== 'function') return get;\n const p = await paramsOf(kind, req, get);\n if ('ok' in p) return err(command, p.code, p.message, p.hint);\n\n const first = Math.max(0, req.start ?? 0);\n const want = Math.max(1, Math.min(req.limit, PAGING.max - first));\n const fetchPage: PageFetch<Found> = async (keywords, start) => {\n const res = await get(\n searchUrl({ kind, ...(keywords ? { keywords } : {}), params: p.params, start }),\n 'search',\n );\n const page = res.ok ? parseResults(res.json) : res;\n if (!page.ok) return page;\n return {\n ok: true,\n items: page.items,\n ...(page.total !== undefined ? { total: page.total } : {}),\n ...(page.claimed !== undefined ? { claimed: page.claimed } : {}),\n unknownTypes: page.unknownTypes,\n };\n };\n const merged = await searchAll(\n fetchPage,\n sets.length > 0 ? sets : [undefined],\n first,\n want,\n PAGING,\n );\n if (merged.rows.length === 0 && merged.failure !== undefined) {\n const f = merged.failure;\n return err(command, f.code, f.message, f.hint);\n }\n const single = sets.length <= 1;\n return ok('search', {\n kind,\n query: { ...(sets.length > 0 ? { keywords: single ? sets[0] : sets } : {}), params: p.params },\n ...(Object.keys(p.resolved).length > 0 ? { resolved: p.resolved } : {}),\n items: shape(merged.rows, opts, compactFound),\n meta: metaOf(command, merged, single, first),\n });\n}\n\nexport async function runFindFilters(\n kind: SearchKindName,\n req: Omit<FindRequest, 'limit'>,\n opts: OutputOpts = {},\n fetch?: PeopleFetch,\n): Promise<Envelope> {\n const command = `search-filters ${kind}`;\n const sets = keywordSets(req.keywords);\n if (sets.length > 1)\n return err(\n command,\n 'INVALID_INPUT',\n 'search-filters takes one keyword set: its counts belong to that one query',\n );\n const get = fetch ?? liveFetch(command, opts.quiet === true);\n if (typeof get !== 'function') return get;\n const p = await paramsOf(kind, req, get);\n if ('ok' in p) return err(command, p.code, p.message, p.hint);\n const res = await get(\n searchUrl({\n kind,\n ...(sets[0] !== undefined ? { keywords: sets[0] } : {}),\n params: p.params,\n start: 0,\n withFilters: true,\n }),\n 'search',\n );\n const parsed = res.ok ? parsePeopleFilters(res.json) : res;\n if (!parsed.ok) return err(command, parsed.code, parsed.message, parsed.hint);\n return ok('search-filters', {\n kind,\n ...(Object.keys(p.resolved).length > 0 ? { resolved: p.resolved } : {}),\n items: shape(parsed.filters, opts, (f) => {\n const how = f.input === 'text' ? 'free text' : 'ids';\n const options = f.options\n .map((o) => `${o.value}=${o.label}${o.count !== undefined ? ` (${o.count})` : ''}`)\n .join(', ');\n return `${f.key} [${how}]${options !== '' ? `: ${options}` : ''}`;\n }),\n meta: { state: 'complete', operation: command, returnedCount: parsed.filters.length },\n });\n}\n","// ─── `lnrelay skill add|remove`, and `lnrelay skills` ─────────────────────────\n//\n// See engine/sdui-skill.ts. Every change is planned from what the profile\n// holds now and read back afterwards.\n\nimport type { Session } from '../engine/auth.ts';\nimport { createEngine, createLiveClient } from '../engine/index.ts';\nimport type { Failure } from '../engine/sdui-form.ts';\nimport {\n addSkillBody,\n fetchSkills,\n openSkillForm,\n removeSkillBody,\n SKILL,\n type Skill,\n type SkillForm,\n sendSkill,\n skillNameOf,\n} from '../engine/sdui-skill.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope } from '../types.ts';\nimport type { ConfirmDeps, WritePlan } from './confirm.ts';\nimport { refuseUnapprovable, terminalDeps } from './gate.ts';\nimport { authorLine, gate, prepare } from './write.ts';\n\n/** What a skill change needs from LinkedIn. Injectable so tests send nothing. */\nexport interface SkillSurface {\n vanity(): Promise<{ ok: true; vanity: string } | Failure>;\n list(vanity: string): Promise<{ ok: true; skills: Skill[] } | Failure>;\n open(payload: Record<string, unknown>, edit: boolean): Promise<SkillForm | Failure>;\n send(body: unknown, requestId: string): Promise<{ ok: true } | Failure>;\n}\n\nfunction liveSkills(session: Session, quiet = false): SkillSurface {\n const client = createLiveClient(session, undefined, quiet);\n return {\n vanity: async () => {\n const me = await createEngine(session, undefined, quiet).whoami();\n if (!me.ok) return me;\n const id = me.value?.publicIdentifier;\n return typeof id === 'string' && id !== ''\n ? { ok: true, vanity: id }\n : { ok: false, code: 'SCHEMA_DRIFT', message: 'whoami returned no public profile id' };\n },\n list: (vanity) => fetchSkills(vanity, client),\n open: (payload, edit) => openSkillForm(payload, client, edit),\n send: (body, requestId) => sendSkill(body, requestId, client),\n };\n}\n\nconst listed = (skills: Skill[]) =>\n skills.map((s) => `${s.skillId} (${s.name ?? '?'})`).join(', ') || 'none';\n\nexport async function runSkill(\n sub: string | undefined,\n arg: string | undefined,\n now = Date.now(),\n deps: ConfirmDeps = terminalDeps(),\n surface?: SkillSurface,\n): Promise<Envelope> {\n if (sub !== 'add' && sub !== 'remove') {\n return err(\n 'skill',\n 'INVALID_INPUT',\n `unknown skill subcommand '${sub ?? ''}'`,\n 'lnrelay skill add \"<name>\" | lnrelay skill remove <skill-id>',\n );\n }\n if (arg === undefined || arg.trim() === '') {\n return err(\n 'skill',\n 'INVALID_INPUT',\n sub === 'add' ? 'the skill name is required' : 'the skill id is required',\n 'ids come from `lnrelay skills`',\n );\n }\n const unapprovable = refuseUnapprovable('skill', 'changing your skills', deps);\n if (unapprovable !== null) return unapprovable;\n const ctx = prepare('skill', now, 'voyager');\n if ('ok' in ctx) return ctx;\n if (ctx.transport.kind !== 'voyager')\n return err('skill', 'NOT_IMPLEMENTED', 'skill changes go over the browser session only');\n\n const skills = surface ?? liveSkills(ctx.transport.session);\n const me = await skills.vanity();\n if (!me.ok) return err('skill', me.code, me.message, me.hint);\n const before = await skills.list(me.vanity);\n if (!before.ok) return err('skill', before.code, before.message, before.hint);\n\n return sub === 'add'\n ? addSkill(arg.trim(), before.skills, me.vanity, skills, ctx, deps)\n : removeSkill(arg, before.skills, me.vanity, skills, ctx, deps);\n}\n\ntype Ctx = Exclude<ReturnType<typeof prepare>, Envelope>;\n\nasync function addSkill(\n name: string,\n current: Skill[],\n vanity: string,\n skills: SkillSurface,\n ctx: Ctx,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n const dup = current.find((s) => s.name?.toLowerCase() === name.toLowerCase());\n if (dup !== undefined)\n return err(\n 'skill',\n 'INVALID_INPUT',\n `\"${dup.name}\" is already on your profile (${dup.skillId})`,\n );\n const form = await skills.open({ vanityName: vanity }, false);\n if (!form.ok) return err('skill', form.code, form.message, form.hint);\n const body = addSkillBody(form, name);\n if (!body.ok) return err('skill', body.code, body.message, body.hint);\n\n const plan: WritePlan<{ name: string }> = {\n action: 'add a skill to your profile',\n payload: { name },\n summary: [\n authorLine(ctx.transport),\n `skill \"${name}\"`,\n 'linked to nothing (no roles, schools or projects)',\n ],\n reversibility: 'removable with `lnrelay skill remove <skill-id>`',\n transport: 'voyager',\n };\n const gated = await gate('skill', plan, ctx, deps);\n if ('ok' in gated) return gated;\n const sent = await skills.send(body.body, SKILL.save);\n if (!sent.ok) return err('skill', sent.code, sent.message, sent.hint);\n const after = await skills.list(vanity);\n const known = new Set(current.map((s) => s.skillId));\n const added = after.ok ? after.skills.find((s) => !known.has(s.skillId)) : undefined;\n if (added === undefined)\n return err(\n 'skill',\n 'SCHEMA_DRIFT',\n 'LinkedIn accepted the skill, but it does not appear on your profile',\n );\n return ok('skill', { added: added.skillId, name: added.name, verified: true });\n}\n\nasync function removeSkill(\n arg: string,\n current: Skill[],\n vanity: string,\n skills: SkillSurface,\n ctx: Ctx,\n deps: ConfirmDeps,\n): Promise<Envelope> {\n const target = current.find((s) => s.skillId === arg);\n if (target === undefined)\n return err(\n 'skill',\n 'NOT_FOUND',\n `no skill ${arg} on your profile`,\n `your skills: ${listed(current)}`,\n );\n const form = await skills.open({ ...target.payload, vanityName: vanity }, true);\n if (!form.ok) return err('skill', form.code, form.message, form.hint);\n const body = removeSkillBody(form);\n if (!body.ok) return err('skill', body.code, body.message, body.hint);\n const name = skillNameOf(form) ?? target.name ?? '?';\n\n const plan: WritePlan<{ skillId: string; name: string }> = {\n action: 'remove a skill from your profile',\n payload: { skillId: target.skillId, name },\n summary: [authorLine(ctx.transport), `skill \"${name}\" (${target.skillId})`],\n reversibility:\n 'NONE for its endorsements, which go with it; the skill itself can be added again',\n transport: 'voyager',\n };\n const gated = await gate('skill', plan, ctx, deps);\n if ('ok' in gated) return gated;\n const sent = await skills.send(body.body, SKILL.delete);\n if (!sent.ok) return err('skill', sent.code, sent.message, sent.hint);\n const after = await skills.list(vanity);\n if (!after.ok || after.skills.some((s) => s.skillId === target.skillId)) {\n return err(\n 'skill',\n 'SCHEMA_DRIFT',\n 'LinkedIn accepted the removal, but the skill is still listed',\n );\n }\n return ok('skill', { removed: target.skillId, verified: true });\n}\n\n/** `lnrelay skills`: the skills on the owner's profile, with their ids. */\nexport async function runSkills(quiet = false): Promise<Envelope> {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('skills', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const skills = liveSkills(session.session, quiet);\n const me = await skills.vanity();\n if (!me.ok) return err('skills', me.code, me.message, me.hint);\n const listedSkills = await skills.list(me.vanity);\n if (!listedSkills.ok)\n return err('skills', listedSkills.code, listedSkills.message, listedSkills.hint);\n return ok('skills', {\n items: listedSkills.skills.map((s) => ({ skillId: s.skillId, name: s.name })),\n meta: { state: 'complete', returnedCount: listedSkills.skills.length },\n });\n}\n","// ─── Who viewed the owner's profile ───────────────────────────────────────────\n//\n// Captured 2026-10-16. /me/profile-views/ (now /analytics/profile-views/) is\n// drawn by two SDUI server requests: WvmpAnalytics, the total over the page's\n// default range (past 90 days), and WvmpEntityList, the viewers newest first.\n// Both answer in the session's language, so nothing here reads LinkedIn's\n// words for meaning beyond the \"•\" before a degree.\n//\n// The list: each viewer is its own RSC row, tracked `viewer-list-item`. A\n// named viewer links to their /in/ profile; an anonymous one (\"Founder in the\n// Software industry from Budapest\") links to a people search instead. The\n// viewer's profile id is not in their row: it is in the Connect or Message\n// action, the rows the list references right after the viewer's. Private-mode\n// viewers are only a count (\"4 LinkedIn members\"), outside every row.\n//\n// A free account shows up to 3 viewers; the list has a next-page marker\n// (`wvmp-entity-list-next-page-loaded`) that was not exercised.\n//\n// Premium (captured 2026-11-22) names every viewer in the range, in one\n// answer, and takes a date range: 7, 14, 28, 90 or 365 days, the value of the\n// range state (`WvmpSearchFilterTimeRange_LAST_365_DAYS`). Its totals add\n// highlights (top location, industry, company: value then label, between the\n// `highlights` and `details` markers) and the companies viewers work at, each\n// a name and \"(25%)\". Since then both requests answer 500 without a referer.\n\nimport { Rows } from './posts.ts';\nimport type { Failure } from './sdui-form.ts';\n\nconst SERVER_REQUEST = 'https://www.linkedin.com/flagship-web/rsc-action/actions/server-request';\nexport const VIEWERS_URL = `${SERVER_REQUEST}?sduiid=WvmpEntityList`;\nexport const VIEW_TOTALS_URL = `${SERVER_REQUEST}?sduiid=WvmpAnalytics`;\n\n/** Both requests answer 500 without a referer (since 2026-11); any LinkedIn page will do. */\nexport const VIEWERS_REFERER = 'https://www.linkedin.com/analytics/profile-views/';\n\n/** The ranges the page offers, in days. */\nexport const VIEW_RANGES = [7, 14, 28, 90, 365] as const;\nexport type ViewRange = (typeof VIEW_RANGES)[number];\n\nconst RANGE = 'WvmpSearchFilterType_DATE_RANGE';\nconst META = { $type: 'proto.sdui.common.RequestMetadata' } as const;\n\n/** The page's own request: its id, payload, and the date-range state it is keyed by. */\nfunction serverRequest(\n requestId: string,\n stateKey: string,\n payload: Record<string, unknown>,\n days: ViewRange | undefined,\n) {\n const state = {\n key: stateKey,\n namespace: 'MemoryNamespace',\n value: days === undefined ? [] : [`WvmpSearchFilterTimeRange_LAST_${days}_DAYS`],\n originalProtoCase: 'stringListValue',\n protoKey: { $type: 'proto.sdui.Key', value: { $case: 'id', id: stateKey } },\n };\n const requestedArguments = {\n $type: 'proto.sdui.actions.requests.RequestedArguments',\n requestedStateKeys: [{ key: { value: { $case: 'id', id: stateKey } } }],\n payload: {\n ...payload,\n filterTypeList: [RANGE],\n dateRangeSelectionFilters: { key: stateKey, namespace: 'MemoryNamespace' },\n },\n requestMetadata: META,\n };\n return {\n requestId,\n serverRequest: {\n requestId,\n requestedArguments,\n isApfcEnabled: false,\n isStreaming: false,\n rumPageKey: '',\n },\n states: [state],\n requestedArguments: {\n ...requestedArguments,\n states: [state],\n screenId: 'com.linkedin.sdui.flagshipnav.home.Home',\n knownTemplateIds: [],\n },\n };\n}\n\nexport function viewersBody(days?: ViewRange) {\n return serverRequest(\n 'WvmpEntityList',\n `entityListQueryFilterPrefix${RANGE}`,\n { sortType: 'ProfileViewSortType_TIME_DESCENDING' },\n days,\n );\n}\n\nexport function viewTotalsBody(days?: ViewRange) {\n return serverRequest(\n 'WvmpAnalytics',\n `analyticsFieldsFilterPrefix${RANGE}`,\n {\n highlightCardDimensions: [\n 'DimensionType_LOCATION',\n 'DimensionType_INDUSTRY',\n 'DimensionType_ORGANIZATION',\n ],\n detailsCardDimensions: ['DimensionType_ORGANIZATION'],\n highlightCardResultCount: 4,\n detailsCardResultCount: 23,\n },\n days,\n );\n}\n\nexport type Viewer =\n | {\n name: string;\n /** Their profile id: what `profile`, `messages` and `people --connection-of` take. */\n id?: string;\n url: string;\n /** Connection degree, as LinkedIn words it in the session's language. */\n degree?: string;\n headline?: string;\n /** When, as LinkedIn words it (\"2d ago\"). */\n viewed?: string;\n }\n | {\n anonymous: true;\n /** What LinkedIn says of them instead (\"Founder in the Software industry from …\"). */\n description: string;\n viewed?: string;\n /** The people search LinkedIn links them to. */\n searchUrl?: string;\n };\n\nconst drift = (message: string): Failure => ({ ok: false, code: 'SCHEMA_DRIFT', message });\nconst unquote = (s: string) => JSON.parse(`\"${s}\"`) as string;\nconst STR = '((?:[^\"\\\\\\\\]|\\\\\\\\.)+)';\n\nconst ITEM =\n /\"viewName\":\"viewer-list-item\"(?:,\"impressionThresholds\":\\[[^\\]]*\\])?[^{}]*\"semanticPosition\"/;\n/** Size and weight, whatever style props sit between them and the text (Premium adds two). */\nconst TEXT_PROPS =\n /\"textProps\":\\{\"fontFamily\":\"[^\"]*\",\"fontSize\":\"(\\w+)\",\"fontStyle\":\"[^\"]*\",\"fontWeight\":\"(\\w+)\"(?:,\"\\w+\":\"[^\"]*\")*?,\"children\":/g;\nconst OWN_TEXT = new RegExp(`^\\\\[\"${STR}\"\\\\]`);\nconst NESTED_TEXT = new RegExp(`\\\\[null,\"${STR}\"`);\nconst LINK = new RegExp(`\"urlValue\":\\\\{\"\\\\$case\":\"url\",\"url\":\"${STR}\"`);\nconst PROFILE_ID = /ACoA[A-Za-z0-9_-]{10,}/;\nconst PLAIN_TEXT = new RegExp(`\"children\":\\\\[\"${STR}\"\\\\]`, 'g');\n\n/** Each text in a viewer's row: its size and weight, then what it says. */\nfunction textsOf(row: string): { size: string; weight: string; text: string }[] {\n return [...row.matchAll(TEXT_PROPS)].flatMap((m) => {\n const after = row.slice((m.index ?? 0) + m[0].length, (m.index ?? 0) + m[0].length + 600);\n const raw = after.match(OWN_TEXT)?.[1] ?? after.match(NESTED_TEXT)?.[1];\n if (raw === undefined) return [];\n const text = unquote(raw).trim();\n return text === '' ? [] : [{ size: m[1] as string, weight: m[2] as string, text }];\n });\n}\n\nfunction viewerOf(row: string, id: string | undefined): Viewer | undefined {\n // In order: the name (or the anonymous description), the degree, the\n // headline, and last when they looked.\n const texts = textsOf(row);\n const at = texts.findIndex((t) => t.size === 'medium' && t.weight === 'bold');\n const first = texts[at]?.text;\n if (first === undefined) return undefined;\n const rest = texts.slice(at + 1).map((t) => t.text);\n const degreeText = rest.find((t) => t.startsWith('•'));\n const lines = rest.filter((t) => t !== degreeText);\n const viewed = lines.at(-1);\n const link = row.match(LINK)?.[1];\n const url = link === undefined ? undefined : unquote(link);\n if (url === undefined || !/linkedin\\.com\\/in\\//.test(url)) {\n const v: Viewer = { anonymous: true, description: first };\n if (viewed !== undefined) v.viewed = viewed;\n if (url !== undefined) v.searchUrl = url;\n return v;\n }\n const degree = degreeText?.replace(/^•\\s*/, '');\n const headline = lines.length > 1 ? lines[0] : undefined;\n return {\n name: first,\n ...(id !== undefined ? { id } : {}),\n url,\n ...(degree !== undefined ? { degree } : {}),\n ...(headline !== undefined ? { headline } : {}),\n ...(viewed !== undefined ? { viewed } : {}),\n };\n}\n\n/**\n * Whole-row references only: `$L` (lazy), `$Q` (a map) or bare. A `$b:4:props…`\n * path points back INTO a row, here into the list itself, and is not followed.\n */\nconst REF = /\"\\$[LQ]?([0-9a-f]+)\"/g;\n\n/** The first profile id in `ref` or the rows it references, never via a viewer's row. */\nfunction idUnder(rows: Rows, ref: string, items: Set<string>): string | undefined {\n const seen = new Set([ref]);\n const queue = [ref];\n while (queue.length > 0 && seen.size < 200) {\n const row = rows.byId.get(queue.shift() as string) ?? '';\n const id = row.match(PROFILE_ID)?.[0];\n if (id !== undefined) return id;\n for (const m of row.matchAll(REF)) {\n const next = m[1] as string;\n if (!seen.has(next) && !items.has(next) && rows.byId.has(next)) {\n seen.add(next);\n queue.push(next);\n }\n }\n }\n return undefined;\n}\n\n/**\n * Each viewer's profile id, from the action that follows their row: written\n * inline after the reference to it (Premium), or in a row referenced there.\n */\nfunction idsByViewer(rows: Rows, items: Set<string>): Map<string, string> {\n const ids = new Map<string, string>();\n for (const row of rows.byId.values()) {\n let current: string | undefined;\n let from = 0;\n // The first id found after a viewer's reference, inline or referenced, is theirs.\n const settle = (id: string | undefined) => {\n if (current !== undefined && id !== undefined && !ids.has(current)) ids.set(current, id);\n };\n for (const m of row.matchAll(REF)) {\n const ref = m[1] as string;\n const at = m.index ?? 0;\n settle(row.slice(from, at).match(PROFILE_ID)?.[0]);\n from = at + m[0].length;\n if (items.has(ref)) current = ref;\n else if (current !== undefined && !ids.has(current)) settle(idUnder(rows, ref, items));\n }\n settle(row.slice(from).match(PROFILE_ID)?.[0]);\n }\n return ids;\n}\n\nexport function parseViewers(\n stream: string,\n): { ok: true; viewers: Viewer[]; privateViewers?: number } | Failure {\n if (!stream.includes('\"viewName\":\"viewer-list\"'))\n return drift('the profile viewers answer was not the viewer list');\n const rows = new Rows(stream);\n const items = new Set([...rows.byId].filter(([, row]) => ITEM.test(row)).map(([id]) => id));\n const ids = idsByViewer(rows, items);\n const viewers = [...items].flatMap((id) => viewerOf(rows.byId.get(id) ?? '', ids.get(id)) ?? []);\n const shown = Math.max(items.size, (stream.match(new RegExp(ITEM, 'g')) ?? []).length);\n if (shown > 0 && viewers.length === 0)\n return drift(`${shown} profile viewers were shown but none could be read`);\n\n // \"4 LinkedIn members\": the one number outside every viewer's row.\n let privateViewers: number | undefined;\n for (const [id, row] of rows.byId) {\n if (items.has(id) || privateViewers !== undefined) continue;\n for (const m of row.matchAll(PLAIN_TEXT)) {\n const n = unquote(m[1] as string).match(/^(\\d[\\d.,\\s]*)\\s+\\D/)?.[1];\n if (n !== undefined) {\n privateViewers = Number(n.replace(/\\D/g, ''));\n break;\n }\n }\n }\n return privateViewers === undefined\n ? { ok: true, viewers }\n : { ok: true, viewers, privateViewers };\n}\n\nexport interface ViewTotals {\n ok: true;\n total: number;\n /** The total's own label, when it names the period (\"… in the past 90 days\"). */\n period?: string;\n /** Premium: top location, industry and company, labelled as LinkedIn words it. */\n highlights?: { label: string; value: string }[];\n /** Premium: the companies viewers work at, with their share in percent. */\n companies?: { name: string; share: number }[];\n}\n\nconst textsIn = (s: string) =>\n [...s.matchAll(PLAIN_TEXT)].map((m) => unquote(m[1] as string).trim());\n\n/** Value, label, value, label…, after the section's heading. */\nfunction highlightsOf(stream: string): { label: string; value: string }[] {\n const from = stream.indexOf('\"viewName\":\"highlights\"');\n if (from === -1) return [];\n const to = stream.indexOf('\"viewName\":\"details\"', from);\n const texts = textsIn(stream.slice(from, to === -1 ? undefined : to)).slice(1);\n const out: { label: string; value: string }[] = [];\n for (let i = 0; i + 1 < texts.length; i += 2)\n out.push({ value: texts[i] as string, label: texts[i + 1] as string });\n return out;\n}\n\n/** Each name followed by \"(N%)\", once. */\nfunction companiesOf(texts: string[]): { name: string; share: number }[] {\n const seen = new Map<string, number>();\n texts.forEach((t, i) => {\n const share = t.match(/^\\((\\d+)\\s*%\\)$/)?.[1];\n const name = texts[i - 1];\n if (share !== undefined && name !== undefined && !seen.has(name)) seen.set(name, Number(share));\n });\n return [...seen].map(([name, share]) => ({ name, share }));\n}\n\nexport function parseViewTotals(stream: string): ViewTotals | Failure {\n const texts = textsIn(stream);\n const at = texts.findIndex((t) => /^\\d[\\d.,\\s]*$/.test(t));\n if (at === -1) return drift('the profile view totals carried no number');\n const total = Number((texts[at] as string).replace(/\\D/g, ''));\n // The free page labels its total with the period; Premium only \"profile viewers\".\n const label = texts[at + 1];\n const highlights = highlightsOf(stream);\n const companies = companiesOf(texts);\n return {\n ok: true,\n total,\n ...(label !== undefined && /\\d/.test(label) ? { period: label } : {}),\n ...(highlights.length > 0 ? { highlights } : {}),\n ...(companies.length > 0 ? { companies } : {}),\n };\n}\n","// ─── `lnrelay viewers` ────────────────────────────────────────────────────────\n//\n// Who viewed the owner's profile, as their profile-views page shows it; see\n// engine/profile-views.ts. Two page calls: the total, then the viewers. A free\n// account is shown up to 3 viewers of the total, Premium every one; the result\n// is `partial` whenever LinkedIn counts more than it names and counts as\n// private. Premium also takes a range (--days) and adds highlights and the\n// companies viewers work at.\n\nimport { createLiveClient } from '../engine/index.ts';\nimport {\n parseViewers,\n parseViewTotals,\n VIEW_TOTALS_URL,\n VIEWERS_REFERER,\n VIEWERS_URL,\n type Viewer,\n type ViewRange,\n viewersBody,\n viewTotalsBody,\n} from '../engine/profile-views.ts';\nimport { loadSession } from '../engine/session.ts';\nimport { err, ok } from '../output.ts';\nimport type { Envelope, FetchState } from '../types.ts';\nimport type { OutputOpts } from './live.ts';\nimport { line } from './paged.ts';\nimport { shape } from './people.ts';\n\ntype Fetched =\n | { ok: true; raw: string }\n | { ok: false; code: string; message: string; hint?: string };\n\n/** One accounted POST. Injectable so tests send nothing. */\nexport type ViewersFetch = (url: string, body: unknown, spendClass: 'page') => Promise<Fetched>;\n\nfunction liveFetch(quiet: boolean): ViewersFetch | Envelope {\n const session = loadSession();\n if (session.state !== 'ok')\n return err('viewers', 'AUTH_FAILED', 'no LinkedIn session — run `lnrelay login`');\n const client = createLiveClient(session.session, undefined, quiet);\n return async (url, body, spendClass) => {\n const r = await client.request({\n url,\n method: 'POST',\n body,\n headers: { referer: VIEWERS_REFERER },\n spendClass,\n operation: 'viewers',\n });\n if (!r.ok) return r;\n return { ok: true, raw: (r.classification as { raw?: string }).raw ?? '' };\n };\n}\n\nconst compactViewer = (v: Viewer) =>\n 'anonymous' in v\n ? line(['anonymous', v.description, v.viewed])\n : line([v.name, v.degree, v.headline, v.viewed, v.url]);\n\nexport async function runViewers(\n opts: OutputOpts & { days?: ViewRange } = {},\n fetch?: ViewersFetch,\n): Promise<Envelope> {\n const get = fetch ?? liveFetch(opts.quiet === true);\n if (typeof get !== 'function') return get;\n\n const totalsRes = await get(VIEW_TOTALS_URL, viewTotalsBody(opts.days), 'page');\n const totals = totalsRes.ok ? parseViewTotals(totalsRes.raw) : totalsRes;\n const listRes = await get(VIEWERS_URL, viewersBody(opts.days), 'page');\n const list = listRes.ok ? parseViewers(listRes.raw) : listRes;\n if (!list.ok) return err('viewers', list.code, list.message, list.hint);\n\n const shown = list.viewers.length;\n // Complete when the named and the private add up to the total exactly. A\n // free account's counts do not (3 named and 4 private of 5): it holds back.\n const accounted =\n totals.ok && (totals.total <= shown || shown + (list.privateViewers ?? 0) === totals.total);\n const state: FetchState = !totals.ok ? 'unknown' : accounted ? 'complete' : 'partial';\n const { ok: _ok, ...summary } = totals.ok ? totals : { ok: false };\n return ok('viewers', {\n ...(opts.days !== undefined ? { days: opts.days } : {}),\n ...(totals.ok ? summary : { totalError: `${totals.code}: ${totals.message}` }),\n ...(list.privateViewers !== undefined ? { privateViewers: list.privateViewers } : {}),\n items: shape(list.viewers, opts, compactViewer),\n meta: { state, operation: 'viewers', returnedCount: shown },\n });\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"],"mappings":";;;AAkBA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,SAAS;;;ACHlB,SAAS,gBAAgB;AACzB,SAAS,aAAAA,YAAW,cAAAC,mBAAkB;;;ACAtC,SAAS,YAAY,WAAW,cAAc,YAAY,qBAAqB;AAC/E,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAEvB,SAAS,WAAmB;AACjC,SAAO,QAAQ,IAAI,qBAAqB,KAAK,QAAQ,GAAG,UAAU;AACpE;AAEO,SAAS,aAAa,OAAyB;AACpD,SAAO,KAAK,SAAS,GAAG,GAAG,KAAK;AAClC;AAaO,SAAS,SAAY,MAA6B;AACvD,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO,EAAE,OAAO,UAAU;AAEjD,MAAI;AACJ,MAAI;AACF,UAAM,aAAa,MAAM,OAAO;AAAA,EAClC,SAAS,GAAG;AACV,WAAO,WAAW,MAAM,eAAgB,EAAY,OAAO,EAAE;AAAA,EAC/D;AAEA,MAAI;AACF,WAAO,EAAE,OAAO,MAAM,OAAO,KAAK,MAAM,GAAG,EAAO;AAAA,EACpD,SAAS,GAAG;AACV,WAAO,WAAW,MAAM,qBAAsB,EAAY,OAAO,EAAE;AAAA,EACrE;AACF;AAEA,SAAS,WAAW,MAAc,QAAmC;AACnE,QAAM,SAAQ,oBAAI,KAAK,GAAE,YAAY,EAAE,QAAQ,SAAS,GAAG;AAC3D,QAAMC,UAAS,UAAU,cAAc,OAAO,KAAK,MAAM,GAAG,EAAE,IAAI,KAAK,MAAM;AAC7E,MAAI;AACF,cAAU,QAAQA,OAAM,GAAG,EAAE,WAAW,KAAK,CAAC;AAC9C,eAAW,MAAMA,OAAM;AAAA,EACz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AC/B;AAEA,SAAO;AAAA,IACL;AAAA,IACA,8aAIkE,QAAQ;AAAA,IAC1E,CAAC;AAAA,IACD,YAAY,MAAM,MAAM,aAAa,CAAC;AAAA,EACxC;AAEA,aAAW,UAAU,CAAC,eAAe,UAAU,GAAY;AACzD,WAAO;AAAA,MACL,OAAO,QAAQ,KAAK,GAAG;AAAA,MACvB,kBAAkB,WAAW,gBAAgB,gBAAgB,gBAAgB,+LAEK,MAAM;AAAA,MAExF;AAAA,QACE,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,0CAA0C;AAAA,QAChF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAI,EAAE,SAAS,EAAE,SAAS,6BAA6B;AAAA,MAC5F;AAAA,MACA,OAAO,EAAE,OAAO,MAAM,MAAM,MAAM,cAAc,QAAQ,OAAO,SAAS,EAAE,CAAC;AAAA,IAC7E;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IAGA,CAAC;AAAA,IACD,YAAY,MAAM,eAAe,CAAC;AAAA,EACpC;AAEA,SAAO;AACT;AAEA,IAAMC,SAAQ,iBAAiB,QAAQ,KAAK,CAAC,GAAG,YAAY,KAAK,YAAY,MAAM;AAAA,EACjF;AAAA,EACA;AACF,CAAC;AAED,IAAIA,OAAM,KAAK;AACb,QAAM,SAAS,YAAY;AAC3B,QAAM,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AACjD;","names":["mkdirSync","renameSync","target","mkdirSync","quarantine","target","renameSync","inner","counts","defined","line","range","byUrn","typeOf","nodes","count","contract","postUrn","text","entry","str","resolve","part","named","text","text","defined","line","card","insight","drift","byUrn","role","text","defined","drift","classify","byUrn","Refused","selection","texts","fetch","named","selection","liveFetch","PAGING","counts","text","fetch","fail","liveFetch","fetch","companies","texts","count","byUrn","range","address","liveFetch","fetch","count","drift","text","defined","collection","urns","str","card","part","mailbox","liveFetch","PAGING","shape","line","fetch","selection","collection","count","COUNT","drift","texts","PAGE_SIZE","postUrn","existsSync","existsSync","readFileSync","contract","mailbox","DEGREE","txt","defined","byUrn","render","drift","fetch","text","text","defined","liveFetch","collect","fetch","text","idOf","inner","cleanUrl","drift","r","count","byUrn","invitations","liveFetch","PAGING","compactRow","res","fetch","count","drift","text","byUrn","liveFetch","fetch","SCREEN","drift","unquote","TEXT","text","contract","drift","str","idOf","defined","nodes","SECTIONS","counts","count","bool","SCREEN","profileId","drift","unquote","TEXT","texts","text","drift","TEXT","drift","text","PAGER_URL","MAX_PAGES","drift","count","liveFetch","counts","fail","count","PAGER_URL","compact","LISTS","fetch","EDIT_NAV","drift","text","count","reply","drift","mkdirSync","dirname","readFileSync","statSync","basename","createHash","VOYAGER","readFileSync","randomUUID","existsSync","PAGING","NETWORK","fetch","drift","unquote","STR","LINK","PROFILE_ID","text","texts","REF","share","companies","liveFetch","fetch","basename","compact","text","entry"]}