linkedin-relay-mcp 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -4,6 +4,13 @@ function parseArgs(argv) {
4
4
  const [command, ...rest] = argv;
5
5
  const positionals = [];
6
6
  const flags = {};
7
+ const repeated = {};
8
+ const keep = (key, value) => {
9
+ flags[key] = value;
10
+ const seen = repeated[key] ?? [];
11
+ seen.push(value);
12
+ repeated[key] = seen;
13
+ };
7
14
  for (let i = 0; i < rest.length; i++) {
8
15
  const token = rest[i];
9
16
  if (token === void 0) continue;
@@ -11,7 +18,7 @@ function parseArgs(argv) {
11
18
  const key = token.slice(2);
12
19
  const next = rest[i + 1];
13
20
  if (next !== void 0 && !next.startsWith("--")) {
14
- flags[key] = next;
21
+ keep(key, next);
15
22
  i++;
16
23
  } else {
17
24
  flags[key] = true;
@@ -20,7 +27,7 @@ function parseArgs(argv) {
20
27
  const key = token.slice(1);
21
28
  const next = rest[i + 1];
22
29
  if (next !== void 0 && !next.startsWith("-")) {
23
- flags[key] = next;
30
+ keep(key, next);
24
31
  i++;
25
32
  } else {
26
33
  flags[key] = true;
@@ -29,7 +36,7 @@ function parseArgs(argv) {
29
36
  positionals.push(token);
30
37
  }
31
38
  }
32
- return { command, positionals, flags };
39
+ return { command, positionals, flags, repeated };
33
40
  }
34
41
  function bool(args, name) {
35
42
  return args.flags[name] === true || args.flags[name] === "true";
@@ -44,10 +51,13 @@ function num(args, name) {
44
51
  const n = Number(v);
45
52
  return Number.isFinite(n) ? n : void 0;
46
53
  }
54
+ function list(args, name) {
55
+ return args.repeated[name] ?? [];
56
+ }
47
57
 
48
- // src/cache/db.ts
49
- import { Database } from "bun:sqlite";
50
- import { mkdirSync as mkdirSync2, renameSync as renameSync2 } from "fs";
58
+ // src/commands/approval.ts
59
+ import { appendFileSync, mkdirSync as mkdirSync2 } from "fs";
60
+ import { dirname as dirname2 } from "path";
51
61
 
52
62
  // src/cache/store.ts
53
63
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
@@ -90,7 +100,224 @@ function saveJson(path, value) {
90
100
  renameSync(tmp, path);
91
101
  }
92
102
 
103
+ // src/output.ts
104
+ function ok(command, data) {
105
+ return { ok: true, command, data };
106
+ }
107
+ function err(command, code, message, hint, status, retryAfterMs) {
108
+ const error = { code, message };
109
+ if (hint !== void 0) error.hint = hint;
110
+ if (status !== void 0) error.status = status;
111
+ if (retryAfterMs !== void 0) error.retryAfterMs = retryAfterMs;
112
+ return { ok: false, command, error };
113
+ }
114
+ function toJson(envelope) {
115
+ return JSON.stringify(envelope, null, 2);
116
+ }
117
+ function exitCodeFor(envelope) {
118
+ if (envelope.ok) return 0;
119
+ return envelope.error.code === "UNKNOWN_COMMAND" ? 2 : 1;
120
+ }
121
+
122
+ // src/commands/confirm.ts
123
+ import { createHash } from "crypto";
124
+ var APPROVAL_MODES = ["interactive", "agent", "unattended"];
125
+ function confirmToken(action, payload) {
126
+ return createHash("sha256").update(`${action}:${JSON.stringify(payload)}`).digest("hex").slice(0, 4);
127
+ }
128
+ function riskLines(transport) {
129
+ return transport === "oauth" ? [
130
+ " This write itself is sanctioned \u2014 it uses LinkedIn's own",
131
+ " w_member_social scope. The reads this tool performs are not."
132
+ ] : [
133
+ " This goes over the PRIVATE API, not a sanctioned one. It breaches",
134
+ " LinkedIn User Agreement \xA78.2 and can permanently restrict this account."
135
+ ];
136
+ }
137
+ function planToken(plan) {
138
+ return confirmToken(plan.action, plan.tokenBasis ?? plan.payload);
139
+ }
140
+ function previewLines(plan, budgetLine2) {
141
+ return [
142
+ `ABOUT TO ${plan.action.toUpperCase()} ON LINKEDIN`,
143
+ ...plan.summary,
144
+ `via ${plan.transport === "oauth" ? "official OAuth (w_member_social)" : "Voyager (private API)"}`,
145
+ `undo ${plan.reversibility}`,
146
+ ...riskLines(plan.transport).map((l) => l.trim()),
147
+ budgetLine2
148
+ ];
149
+ }
150
+ function renderPlan(plan, budgetLine2) {
151
+ const token = planToken(plan);
152
+ const lines = [
153
+ "",
154
+ ` ABOUT TO ${plan.action.toUpperCase()} ON LINKEDIN`,
155
+ ` ${"\u2500".repeat(58)}`,
156
+ ...plan.summary.map((l) => ` ${l}`),
157
+ ` via ${plan.transport === "oauth" ? "official OAuth (w_member_social)" : "Voyager (private API)"}`,
158
+ ` undo ${plan.reversibility}`,
159
+ "",
160
+ ...riskLines(plan.transport),
161
+ ` ${budgetLine2}`,
162
+ "",
163
+ ` Type ${token} to confirm, anything else to abort: `
164
+ ];
165
+ return lines.join("\n");
166
+ }
167
+ function canApprove(deps) {
168
+ const a = deps.approval ?? { mode: "interactive" };
169
+ if (a.planOnly === true || a.mode === "unattended") return true;
170
+ if (a.mode === "agent" && a.token !== void 0) return true;
171
+ return deps.isTty;
172
+ }
173
+ var refuse = (message, hint) => ({ ok: false, code: "CONFIRMATION_REQUIRED", message, hint });
174
+ async function confirmWrite(plan, budgetLine2, deps) {
175
+ const a = deps.approval ?? { mode: "interactive" };
176
+ const token = planToken(plan);
177
+ const mint = () => ({
178
+ ok: true,
179
+ confirmed: { action: plan.action, payload: plan.payload, token }
180
+ });
181
+ if (a.planOnly === true) {
182
+ return { ok: false, code: "PLANNED", token, preview: previewLines(plan, budgetLine2) };
183
+ }
184
+ if (a.token !== void 0) {
185
+ if (a.mode === "interactive") {
186
+ return refuse(
187
+ `--confirm is not accepted in interactive approval mode; nothing was sent`,
188
+ "In this mode only a human at a terminal approves a write. The owner can allow agents to confirm on their word with `lnrelay approval set agent`, run at a terminal."
189
+ );
190
+ }
191
+ if (a.token !== token) {
192
+ return refuse(
193
+ "the content changed since it was previewed \u2014 the token no longer matches; nothing was sent",
194
+ "Run again with --plan, show the new preview, and confirm with the new token."
195
+ );
196
+ }
197
+ return mint();
198
+ }
199
+ if (a.mode === "unattended") return mint();
200
+ if (!deps.isTty) {
201
+ return a.mode === "agent" ? refuse(
202
+ `'${plan.action}' needs the owner's approval of this exact content`,
203
+ "Nothing was sent. Run the same command with --plan, show the preview to the owner, and when they approve re-run it with --confirm <token>."
204
+ ) : refuse(
205
+ `'${plan.action}' needs a human to confirm it at an interactive terminal`,
206
+ "No terminal is attached, so nothing was sent and no network call was made. Run this command yourself in a shell. There is no --yes flag; only the owner can change how writes are approved, with `lnrelay approval set`, at a terminal."
207
+ );
208
+ }
209
+ const answer = (await deps.prompt(renderPlan(plan, budgetLine2))).trim();
210
+ if (answer !== token) {
211
+ return refuse(
212
+ "aborted \u2014 the confirmation token did not match",
213
+ "Nothing was sent. Re-run and type the token shown in the prompt."
214
+ );
215
+ }
216
+ return mint();
217
+ }
218
+
219
+ // src/commands/approval.ts
220
+ var MEANING = {
221
+ interactive: "every write waits for a human to type a token at a terminal",
222
+ agent: "an agent may write after the owner approves the exact content: --plan to preview, --confirm <token> once they say so",
223
+ unattended: "agents may write without asking; budget caps, cooldowns and the audit log still apply"
224
+ };
225
+ var isMode = (v) => typeof v === "string" && APPROVAL_MODES.includes(v);
226
+ function loadApprovalMode() {
227
+ const loaded = loadJson(cachePath("config.json"));
228
+ if (loaded.state === "missing") return { ok: true, mode: "interactive" };
229
+ if (loaded.state === "corrupt") {
230
+ return {
231
+ ok: false,
232
+ message: "the approval setting was unreadable and has been quarantined",
233
+ hint: `Moved to ${loaded.quarantinedTo}. Writes fall back to interactive from the next run; set another mode with \`lnrelay approval set\`.`
234
+ };
235
+ }
236
+ const mode = loaded.value.approval ?? "interactive";
237
+ if (!isMode(mode)) {
238
+ return {
239
+ ok: false,
240
+ message: `unknown approval mode '${String(mode)}' in config.json`,
241
+ hint: `one of: ${APPROVAL_MODES.join(", ")}. Set it with \`lnrelay approval set <mode>\`.`
242
+ };
243
+ }
244
+ return { ok: true, mode };
245
+ }
246
+ function setToken(mode) {
247
+ return confirmToken("set approval mode", mode);
248
+ }
249
+ function append(entry2) {
250
+ const path = cachePath("writes.jsonl");
251
+ mkdirSync2(dirname2(path), { recursive: true });
252
+ appendFileSync(path, `${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry2 })}
253
+ `, {
254
+ mode: 384
255
+ });
256
+ }
257
+ var approvedInThisRun = false;
258
+ function wasApproved() {
259
+ return approvedInThisRun;
260
+ }
261
+ function auditApproval(command, mode, summary, token) {
262
+ approvedInThisRun = true;
263
+ append({ event: "approved", command, mode, summary, token });
264
+ }
265
+ function auditOutcome(command, mode, envelope) {
266
+ append(
267
+ envelope.ok ? { event: "outcome", command, mode, ok: true, data: envelope.data } : { event: "outcome", command, mode, ok: false, error: envelope.error }
268
+ );
269
+ }
270
+ function runApprovalShow() {
271
+ const loaded = loadApprovalMode();
272
+ if (!loaded.ok) return err("approval", "CACHE_CORRUPT", loaded.message, loaded.hint);
273
+ return ok("approval", {
274
+ mode: loaded.mode,
275
+ meaning: MEANING[loaded.mode],
276
+ audit: cachePath("writes.jsonl")
277
+ });
278
+ }
279
+ async function runApprovalSet(mode, deps) {
280
+ if (!isMode(mode)) {
281
+ return err(
282
+ "approval",
283
+ "INVALID_INPUT",
284
+ `unknown approval mode '${mode ?? ""}'`,
285
+ `one of: ${APPROVAL_MODES.map((m) => `${m} (${MEANING[m]})`).join("; ")}`
286
+ );
287
+ }
288
+ if (!deps.isTty) {
289
+ return err(
290
+ "approval",
291
+ "CONFIRMATION_REQUIRED",
292
+ "the approval mode can only be changed by a human at an interactive terminal",
293
+ "Nothing was changed. An agent cannot choose how its own writes are approved."
294
+ );
295
+ }
296
+ const token = setToken(mode);
297
+ const answer = (await deps.prompt(
298
+ [
299
+ "",
300
+ ` SET LINKEDIN WRITE APPROVAL TO: ${mode.toUpperCase()}`,
301
+ ` ${MEANING[mode]}`,
302
+ "",
303
+ ` Type ${token} to confirm, anything else to abort: `
304
+ ].join("\n")
305
+ )).trim();
306
+ if (answer !== token) {
307
+ return err("approval", "CONFIRMATION_REQUIRED", "aborted \u2014 nothing was changed");
308
+ }
309
+ const current = loadJson(cachePath("config.json"));
310
+ saveJson(cachePath("config.json"), {
311
+ ...current.state === "ok" ? current.value : {},
312
+ approval: mode
313
+ });
314
+ append({ event: "mode", mode });
315
+ return ok("approval", { mode, meaning: MEANING[mode] });
316
+ }
317
+
93
318
  // src/cache/db.ts
319
+ import { Database } from "bun:sqlite";
320
+ import { mkdirSync as mkdirSync3, renameSync as renameSync2 } from "fs";
94
321
  var DB_FILE = "cache.db";
95
322
  var THIRD_PARTY_TTL_MS = 30 * 864e5;
96
323
  function fold(value) {
@@ -130,7 +357,7 @@ var CacheCorrupt = class extends Error {
130
357
  quarantinedTo;
131
358
  };
132
359
  function openDb(now = Date.now()) {
133
- mkdirSync2(cacheDir(), { recursive: true });
360
+ mkdirSync3(cacheDir(), { recursive: true });
134
361
  const path = cachePath(DB_FILE);
135
362
  let db;
136
363
  try {
@@ -166,7 +393,7 @@ function quarantine2(path, reason, now) {
166
393
  const stamp = new Date(now).toISOString().replace(/[:.]/g, "-");
167
394
  const target = cachePath("quarantine", stamp, DB_FILE);
168
395
  try {
169
- mkdirSync2(cachePath("quarantine", stamp), { recursive: true });
396
+ mkdirSync3(cachePath("quarantine", stamp), { recursive: true });
170
397
  renameSync2(path, target);
171
398
  } catch {
172
399
  }
@@ -187,7 +414,7 @@ function upsert(db, source, rows, now = Date.now()) {
187
414
  let added = 0;
188
415
  let updated = 0;
189
416
  const exists = db.query("SELECT 1 FROM records WHERE urn = ? AND source = ?");
190
- const write = db.query(
417
+ const write2 = db.query(
191
418
  `INSERT INTO records (urn, source, body, text, textFold, firstSeenAt, updatedAt, expiresAt)
192
419
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
193
420
  ON CONFLICT(urn, source) DO UPDATE SET
@@ -198,7 +425,7 @@ function upsert(db, source, rows, now = Date.now()) {
198
425
  for (const row of rows) {
199
426
  if (exists.get(row.urn, source) === null) added++;
200
427
  else updated++;
201
- write.run(
428
+ write2.run(
202
429
  row.urn,
203
430
  source,
204
431
  JSON.stringify(row.body),
@@ -556,25 +783,6 @@ function compactRows(rows) {
556
783
  });
557
784
  }
558
785
 
559
- // src/output.ts
560
- function ok(command, data) {
561
- return { ok: true, command, data };
562
- }
563
- function err(command, code, message, hint, status, retryAfterMs) {
564
- const error = { code, message };
565
- if (hint !== void 0) error.hint = hint;
566
- if (status !== void 0) error.status = status;
567
- if (retryAfterMs !== void 0) error.retryAfterMs = retryAfterMs;
568
- return { ok: false, command, error };
569
- }
570
- function toJson(envelope) {
571
- return JSON.stringify(envelope, null, 2);
572
- }
573
- function exitCodeFor(envelope) {
574
- if (envelope.ok) return 0;
575
- return envelope.error.code === "UNKNOWN_COMMAND" ? 2 : 1;
576
- }
577
-
578
786
  // src/commands/cache.ts
579
787
  var SOURCES = ["connections", "my-posts", "third-party"];
580
788
  function corruptEnvelope(command, e) {
@@ -715,11 +923,11 @@ function buildHeaders(session) {
715
923
  }
716
924
 
717
925
  // src/progress.ts
718
- function progressReporter(quiet, write = (s) => {
926
+ function progressReporter(quiet, write2 = (s) => {
719
927
  process.stderr.write(s);
720
928
  }) {
721
929
  return (msg) => {
722
- if (!quiet) write(`${msg}
930
+ if (!quiet) write2(`${msg}
723
931
  `);
724
932
  };
725
933
  }
@@ -1935,7 +2143,7 @@ function getAllCookies(wsUrl) {
1935
2143
  }
1936
2144
 
1937
2145
  // src/engine/voyager-write.ts
1938
- import { createHash } from "crypto";
2146
+ import { createHash as createHash2 } from "crypto";
1939
2147
 
1940
2148
  // src/engine/voyager-media.ts
1941
2149
  var MEDIA_UPLOAD_URL = "https://www.linkedin.com/voyager/api/voyagerVideoDashMediaUploadMetadata?action=upload";
@@ -2031,11 +2239,17 @@ function sharePayload(text2, visibility, media = []) {
2031
2239
  origin: "FEED",
2032
2240
  allowedCommentersScope: "ALL",
2033
2241
  postState: "PUBLISHED",
2034
- media: media.map((m) => ({ category: m.category, mediaUrn: m.urn, tapTargets: [] }))
2242
+ // altText only when given, so a post without it keeps the body verified in 2026-08.
2243
+ media: media.map((m) => ({
2244
+ category: m.category,
2245
+ mediaUrn: m.urn,
2246
+ tapTargets: [],
2247
+ ...m.alt === void 0 ? {} : { altText: m.alt }
2248
+ }))
2035
2249
  };
2036
2250
  }
2037
2251
  function mediaDigest(bytes) {
2038
- return createHash("sha256").update(bytes).digest("hex");
2252
+ return createHash2("sha256").update(bytes).digest("hex");
2039
2253
  }
2040
2254
  var POST_URN = /urn:li:(share|activity|ugcPost):\d+/;
2041
2255
  function isDeletableUrn(urn) {
@@ -2070,27 +2284,35 @@ function extractShareUrn(json) {
2070
2284
  return JSON.stringify(json ?? null).match(POST_URN)?.[0] ?? null;
2071
2285
  }
2072
2286
  async function share(confirmed, client, bytes) {
2073
- const { media: approved } = confirmed.payload;
2074
- const media = [];
2075
- if (approved !== void 0) {
2076
- if (bytes === void 0 || mediaDigest(bytes) !== approved.sha256) {
2287
+ const approved = confirmed.payload.media ?? [];
2288
+ const files = bytes ?? [];
2289
+ for (const [i, a] of approved.entries()) {
2290
+ const b = files[i];
2291
+ if (b === void 0 || mediaDigest(b) !== a.sha256) {
2077
2292
  return {
2078
2293
  ok: false,
2079
2294
  code: "INVALID_INPUT",
2080
- message: `${approved.filename} changed after it was approved; nothing was sent`
2295
+ message: `${a.filename} changed after it was approved; nothing was sent`
2081
2296
  };
2082
2297
  }
2298
+ }
2299
+ const media = [];
2300
+ for (const [i, a] of approved.entries()) {
2083
2301
  const uploaded = await uploadMedia(
2084
2302
  {
2085
- bytes,
2086
- filename: approved.filename,
2087
- kind: approved.kind,
2088
- contentType: approved.contentType
2303
+ bytes: files[i],
2304
+ filename: a.filename,
2305
+ kind: a.kind,
2306
+ contentType: a.contentType
2089
2307
  },
2090
2308
  client
2091
2309
  );
2092
2310
  if (!uploaded.ok) return uploaded;
2093
- media.push({ category: approved.kind, urn: uploaded.urn });
2311
+ media.push({
2312
+ category: a.kind,
2313
+ urn: uploaded.urn,
2314
+ ...a.alt === void 0 ? {} : { alt: a.alt }
2315
+ });
2094
2316
  }
2095
2317
  const body = sharePayload(confirmed.payload.text, confirmed.payload.visibility, media);
2096
2318
  const result = await client.request({
@@ -2115,64 +2337,6 @@ async function share(confirmed, client, bytes) {
2115
2337
 
2116
2338
  // src/commands/gate.ts
2117
2339
  import { createInterface } from "readline/promises";
2118
-
2119
- // src/commands/confirm.ts
2120
- import { createHash as createHash2 } from "crypto";
2121
- function confirmToken(action, payload) {
2122
- return createHash2("sha256").update(`${action}:${JSON.stringify(payload)}`).digest("hex").slice(0, 4);
2123
- }
2124
- function riskLines(transport) {
2125
- return transport === "oauth" ? [
2126
- " This write itself is sanctioned \u2014 it uses LinkedIn's own",
2127
- " w_member_social scope. The reads this tool performs are not."
2128
- ] : [
2129
- " This goes over the PRIVATE API, not a sanctioned one. It breaches",
2130
- " LinkedIn User Agreement \xA78.2 and can permanently restrict this account."
2131
- ];
2132
- }
2133
- function renderPlan(plan, budgetLine2) {
2134
- const token = confirmToken(plan.action, plan.payload);
2135
- const lines = [
2136
- "",
2137
- ` ABOUT TO ${plan.action.toUpperCase()} ON LINKEDIN`,
2138
- ` ${"\u2500".repeat(58)}`,
2139
- ...plan.summary.map((l) => ` ${l}`),
2140
- ` via ${plan.transport === "oauth" ? "official OAuth (w_member_social)" : "Voyager (private API)"}`,
2141
- ` undo ${plan.reversibility}`,
2142
- "",
2143
- ...riskLines(plan.transport),
2144
- ` ${budgetLine2}`,
2145
- "",
2146
- ` Type ${token} to confirm, anything else to abort: `
2147
- ];
2148
- return lines.join("\n");
2149
- }
2150
- async function confirmWrite(plan, budgetLine2, deps) {
2151
- if (!deps.isTty) {
2152
- return {
2153
- ok: false,
2154
- code: "CONFIRMATION_REQUIRED",
2155
- message: `'${plan.action}' needs a human to confirm it at an interactive terminal`,
2156
- hint: "No terminal is attached, so nothing was sent and no network call was made. Run this command yourself in a shell. There is deliberately no --yes flag: an agent that could set one would not be confirming anything."
2157
- };
2158
- }
2159
- const token = confirmToken(plan.action, plan.payload);
2160
- const answer = (await deps.prompt(renderPlan(plan, budgetLine2))).trim();
2161
- if (answer !== token) {
2162
- return {
2163
- ok: false,
2164
- code: "CONFIRMATION_REQUIRED",
2165
- message: "aborted \u2014 the confirmation token did not match",
2166
- hint: "Nothing was sent. Re-run and type the token shown in the prompt."
2167
- };
2168
- }
2169
- return {
2170
- ok: true,
2171
- confirmed: { action: plan.action, payload: plan.payload, token }
2172
- };
2173
- }
2174
-
2175
- // src/commands/gate.ts
2176
2340
  function ledger() {
2177
2341
  const result = loadJson(cachePath("budget.json"));
2178
2342
  return result.state === "ok" ? result.value : emptyLedger();
@@ -2181,6 +2345,20 @@ function budgetLine(now) {
2181
2345
  const s = summarise(ledger(), "write", now);
2182
2346
  return `${s.remaining} of ${s.cap} writes left today.`;
2183
2347
  }
2348
+ function refuseUnapprovable(command, action, deps) {
2349
+ if (canApprove(deps)) return null;
2350
+ return deps.approval?.mode === "agent" ? err(
2351
+ command,
2352
+ "CONFIRMATION_REQUIRED",
2353
+ `${action} needs the owner's approval of this exact content`,
2354
+ "Nothing was sent and no network call was made. Run the same command with --plan, show the preview to the owner, and when they approve re-run it with --confirm <token>."
2355
+ ) : err(
2356
+ command,
2357
+ "CONFIRMATION_REQUIRED",
2358
+ `${action} needs a human to confirm it at an interactive terminal`,
2359
+ "No terminal is attached, so nothing was sent and no network call was made."
2360
+ );
2361
+ }
2184
2362
  function terminalDeps() {
2185
2363
  return {
2186
2364
  isTty: process.stdin.isTTY === true && process.stdout.isTTY === true,
@@ -2210,7 +2388,21 @@ function reserve(command, now, calls = 1) {
2210
2388
  }
2211
2389
  async function gateWrite(command, plan, now, deps, opts = {}) {
2212
2390
  const outcome = await confirmWrite(plan, budgetLine(now), deps);
2391
+ if (!outcome.ok && outcome.code === "PLANNED") {
2392
+ return ok(command, {
2393
+ planned: true,
2394
+ token: outcome.token,
2395
+ preview: outcome.preview,
2396
+ next: `show this to the owner; on their approval re-run the same command with --confirm ${outcome.token}`
2397
+ });
2398
+ }
2213
2399
  if (!outcome.ok) return err(command, outcome.code, outcome.message, outcome.hint);
2400
+ auditApproval(
2401
+ command,
2402
+ deps.approval?.mode ?? "interactive",
2403
+ plan.summary,
2404
+ outcome.confirmed.token
2405
+ );
2214
2406
  if (opts.commitSpend !== false) {
2215
2407
  const attempt = spend(ledger(), "write", now);
2216
2408
  if ("permit" in attempt) saveJson(cachePath("budget.json"), attempt.ledger);
@@ -2231,7 +2423,7 @@ function findOwnPost(posts, urn) {
2231
2423
  (p) => typeof p.urn === "string" && postId(p.urn) === id || p.shareUrn === urn
2232
2424
  );
2233
2425
  }
2234
- function previewLines(post) {
2426
+ function previewLines2(post) {
2235
2427
  if (post === void 0) {
2236
2428
  return [
2237
2429
  "content COULD NOT READ THIS POST.",
@@ -2270,14 +2462,8 @@ function evict(urn, now) {
2270
2462
  }
2271
2463
  }
2272
2464
  async function deleteComment(ref, urn, now, deps) {
2273
- if (!deps.isTty) {
2274
- return err(
2275
- "delete",
2276
- "CONFIRMATION_REQUIRED",
2277
- "deleting needs a human to confirm it at an interactive terminal",
2278
- "No terminal is attached, so nothing was sent and no network call was made."
2279
- );
2280
- }
2465
+ const unapprovable = refuseUnapprovable("delete", "deleting", deps);
2466
+ if (unapprovable !== null) return unapprovable;
2281
2467
  const session = loadSession();
2282
2468
  if (session.state !== "ok") {
2283
2469
  return err("delete", "AUTH_FAILED", "no LinkedIn session", LAUNCH_HINT);
@@ -2359,11 +2545,13 @@ async function runDelete(urn, now = Date.now(), deps, quiet = false) {
2359
2545
  }
2360
2546
  const refused = reserve("delete", now);
2361
2547
  if (refused !== null) return refused;
2548
+ const unapprovable = refuseUnapprovable("delete", "deleting", deps ?? terminalDeps());
2549
+ if (unapprovable !== null) return unapprovable;
2362
2550
  const post = await lookup(urn, quiet);
2363
2551
  const plan = {
2364
2552
  action: "delete a post",
2365
2553
  payload: { urn },
2366
- summary: [`post ${urn}`, ...previewLines(post)],
2554
+ summary: [`post ${urn}`, ...previewLines2(post)],
2367
2555
  reversibility: "NONE. A deleted post is gone, with its comments and reactions.",
2368
2556
  transport: "voyager"
2369
2557
  };
@@ -3124,11 +3312,20 @@ var COMMANDS = [
3124
3312
  risk: "local",
3125
3313
  implemented: true
3126
3314
  },
3315
+ {
3316
+ name: "approval",
3317
+ cost: "free \u2014 local",
3318
+ summary: "Show or set how writes are approved: interactive (a human at a terminal), agent (the owner approves a --plan preview in chat), or unattended. Only a terminal can change it.",
3319
+ usage: "lnrelay approval [show]\n lnrelay approval set <interactive|agent|unattended>\n Setting needs an interactive terminal and a typed token. Every approval and outcome\n is appended to ~/.lnrelay/writes.jsonl.",
3320
+ audience: ["cli"],
3321
+ risk: "local",
3322
+ implemented: true
3323
+ },
3127
3324
  {
3128
3325
  name: "share",
3129
3326
  cost: "1 call \u2014 write",
3130
3327
  summary: "Post to your own feed. Prefers LinkedIn's official OAuth scope, falls back to the private API when no token exists \u2014 the prompt always names which.",
3131
- usage: 'lnrelay share "<text>" [--image <path> | --video <path>] [--visibility public|connections]\n [--via oauth|voyager]\n Stops and asks at an interactive terminal. No TTY = no write, and no network call.\n --image (png/jpg/gif/webp) or --video (mp4/mov) uploads the file first, over the\n private API only; the prompt shows its size and sha256.',
3328
+ usage: 'lnrelay share "<text>" [--image <path> ... | --video <path>] [--alt "<text>" ...]\n [--visibility public|connections] [--via oauth|voyager] [--plan | --confirm <token>]\n Approval follows `lnrelay approval`: --plan previews and returns a token without\n sending; --confirm <token> sends it in agent mode. In interactive mode it asks at a\n terminal. --image (png/jpg/gif/webp, repeat for up to 20) or one --video (mp4/mov)\n uploads first, over the private API only; the preview shows each size and sha256.\n --alt pairs with --image by position; --alt "" skips one.',
3132
3329
  audience: ["cli"],
3133
3330
  risk: "write",
3134
3331
  implemented: true
@@ -3759,6 +3956,43 @@ async function gate(command, plan, ctx, deps) {
3759
3956
  if ("ok" in gated) return gated;
3760
3957
  return { confirmed: gated.confirmed };
3761
3958
  }
3959
+ function mediaLines(media) {
3960
+ return media.flatMap(({ filename, kind, size, sha256, alt }) => [
3961
+ `${kind === "IMAGE" ? "image" : "video"} ${filename} (${Math.ceil(size / 1024)} KB, sha256 ${sha256.slice(0, 12)})`,
3962
+ ...alt === void 0 ? [] : [` alt "${alt}"`]
3963
+ ]);
3964
+ }
3965
+ var MAX_IMAGES = 20;
3966
+ function loadAllMedia(media) {
3967
+ const alts = media.alts ?? [];
3968
+ if (media.flag === "video" && media.paths.length > 1) {
3969
+ return err("share", "INVALID_INPUT", "a post carries one video", "pass a single --video");
3970
+ }
3971
+ if (media.flag === "video" && alts.length > 0) {
3972
+ return err("share", "INVALID_INPUT", "--alt applies to images, not video");
3973
+ }
3974
+ if (media.paths.length > MAX_IMAGES) {
3975
+ return err("share", "INVALID_INPUT", `a post carries at most ${MAX_IMAGES} images`);
3976
+ }
3977
+ if (alts.length > 0 && alts.length !== media.paths.length) {
3978
+ return err(
3979
+ "share",
3980
+ "INVALID_INPUT",
3981
+ `${alts.length} --alt for ${media.paths.length} images; they pair up by position`,
3982
+ 'give one --alt per --image, in the same order; pass --alt "" for an image without one'
3983
+ );
3984
+ }
3985
+ const approved = [];
3986
+ const bytes = [];
3987
+ for (const [i, path] of media.paths.entries()) {
3988
+ const one = loadMedia({ flag: media.flag, path });
3989
+ if ("ok" in one) return one;
3990
+ const alt = alts[i];
3991
+ approved.push(alt === void 0 || alt === "" ? one.approved : { ...one.approved, alt });
3992
+ bytes.push(one.bytes);
3993
+ }
3994
+ return { approved, bytes };
3995
+ }
3762
3996
  function loadMedia(media) {
3763
3997
  const kind = mediaKindOf(media.path);
3764
3998
  if (kind === null) {
@@ -3802,7 +4036,7 @@ async function runShare(text2, visibility, now = Date.now(), deps = terminalDeps
3802
4036
  return err("share", "INVALID_INPUT", "text is required", 'lnrelay share "<text>"');
3803
4037
  }
3804
4038
  const vis = visibility === "connections" ? "CONNECTIONS" : "PUBLIC";
3805
- const loaded = media === void 0 ? void 0 : loadMedia(media);
4039
+ const loaded = media === void 0 || media.paths.length === 0 ? void 0 : loadAllMedia(media);
3806
4040
  if (loaded !== void 0 && "ok" in loaded) return loaded;
3807
4041
  if (loaded !== void 0 && via2 === "oauth") {
3808
4042
  return err(
@@ -3812,7 +4046,7 @@ async function runShare(text2, visibility, now = Date.now(), deps = terminalDeps
3812
4046
  "drop --via oauth, or pass --via voyager"
3813
4047
  );
3814
4048
  }
3815
- const ctx = loaded === void 0 ? prepare("share", now, via2) : prepare("share", now, "voyager", 3);
4049
+ const ctx = loaded === void 0 ? prepare("share", now, via2) : prepare("share", now, "voyager", 2 * loaded.approved.length + 1);
3816
4050
  if ("ok" in ctx) return ctx;
3817
4051
  const payload = {
3818
4052
  text: text2,
@@ -3821,10 +4055,7 @@ async function runShare(text2, visibility, now = Date.now(), deps = terminalDeps
3821
4055
  const summary = [authorLine(ctx.transport), `content "${text2}"`, `audience ${vis}`];
3822
4056
  if (loaded !== void 0) {
3823
4057
  payload.media = loaded.approved;
3824
- const { filename, kind, size, sha256 } = loaded.approved;
3825
- summary.push(
3826
- `${kind === "IMAGE" ? "image" : "video"} ${filename} (${Math.ceil(size / 1024)} KB, sha256 ${sha256.slice(0, 12)})`
3827
- );
4058
+ summary.push(...mediaLines(loaded.approved));
3828
4059
  }
3829
4060
  const plan = {
3830
4061
  action: "post to your feed",
@@ -3902,14 +4133,8 @@ async function runComment(postUrn2, text2, now = Date.now(), deps = terminalDeps
3902
4133
  "Pass urn:li:activity:<id>."
3903
4134
  );
3904
4135
  }
3905
- if (!deps.isTty) {
3906
- return err(
3907
- "comment",
3908
- "CONFIRMATION_REQUIRED",
3909
- "commenting needs a human to confirm it at an interactive terminal",
3910
- "No terminal is attached, so nothing was sent and no network call was made."
3911
- );
3912
- }
4136
+ const unapprovable = refuseUnapprovable("comment", "commenting", deps);
4137
+ if (unapprovable !== null) return unapprovable;
3913
4138
  const ctx = prepare("comment", now, "voyager");
3914
4139
  if ("ok" in ctx) return ctx;
3915
4140
  if (ctx.transport.kind !== "voyager") {
@@ -3921,6 +4146,9 @@ async function runComment(postUrn2, text2, now = Date.now(), deps = terminalDeps
3921
4146
  const plan = {
3922
4147
  action: "comment on a post",
3923
4148
  payload: { activityId, text: text2, tokens: harvested.tokens },
4149
+ // The harvested trackingId changes on every render, so --plan and --confirm
4150
+ // would never agree on a token derived from it. The intent is what's approved.
4151
+ tokenBasis: { activityId, text: text2 },
3924
4152
  summary: [authorLine(ctx.transport), `on ${postUrn2}`, `content "${text2}"`],
3925
4153
  reversibility: "deletable with `lnrelay delete <comment-urn>`; the author is notified immediately",
3926
4154
  transport: "voyager"
@@ -3951,14 +4179,8 @@ async function runEdit(commentUrn, text2, now = Date.now(), deps = terminalDeps(
3951
4179
  "Only comments can be edited here \u2014 a published post cannot. Get the urn from `lnrelay post <activity-urn>`."
3952
4180
  );
3953
4181
  }
3954
- if (!deps.isTty) {
3955
- return err(
3956
- "edit",
3957
- "CONFIRMATION_REQUIRED",
3958
- "editing needs a human to confirm it at an interactive terminal",
3959
- "No terminal is attached, so nothing was sent and no network call was made."
3960
- );
3961
- }
4182
+ const unapprovable = refuseUnapprovable("edit", "editing", deps);
4183
+ if (unapprovable !== null) return unapprovable;
3962
4184
  const ctx = prepare("edit", now, "voyager");
3963
4185
  if ("ok" in ctx) return ctx;
3964
4186
  if (ctx.transport.kind !== "voyager") {
@@ -4042,14 +4264,8 @@ async function runReply(commentUrn, text2, now = Date.now(), deps = terminalDeps
4042
4264
  "To comment on a POST, use `lnrelay comment <activity-urn>`. Comment urns come from `lnrelay post <activity-urn>`."
4043
4265
  );
4044
4266
  }
4045
- if (!deps.isTty) {
4046
- return err(
4047
- "reply",
4048
- "CONFIRMATION_REQUIRED",
4049
- "replying needs a human to confirm it at an interactive terminal",
4050
- "No terminal is attached, so nothing was sent and no network call was made."
4051
- );
4052
- }
4267
+ const unapprovable = refuseUnapprovable("reply", "replying", deps);
4268
+ if (unapprovable !== null) return unapprovable;
4053
4269
  const ctx = prepare("reply", now, "voyager");
4054
4270
  if ("ok" in ctx) return ctx;
4055
4271
  if (ctx.transport.kind !== "voyager") {
@@ -4163,7 +4379,10 @@ async function dispatch(argv, now) {
4163
4379
  `Usage when it lands: ${def.usage.split("\n")[0]}. See docs/PLAN.md for the phase it belongs to.`
4164
4380
  );
4165
4381
  }
4382
+ if (def.risk === "write") return write(command, args, now);
4166
4383
  switch (command) {
4384
+ case "approval":
4385
+ return args.positionals[0] === "set" ? runApprovalSet(args.positionals[1], terminalDeps()) : runApprovalShow();
4167
4386
  case "doctor":
4168
4387
  return runDoctor(now, bool(args, "offline"));
4169
4388
  case "budget":
@@ -4205,24 +4424,6 @@ async function dispatch(argv, now) {
4205
4424
  return runLogin();
4206
4425
  case "oauth":
4207
4426
  return oauth(args);
4208
- case "share":
4209
- return share3(args, now);
4210
- case "comment":
4211
- return runComment(args.positionals[0], args.positionals[1], now);
4212
- case "edit":
4213
- return runEdit(args.positionals[0], args.positionals[1], now);
4214
- case "reply":
4215
- return runReply(args.positionals[0], args.positionals[1], now);
4216
- case "react":
4217
- return runReact(
4218
- args.positionals[0],
4219
- str(args, "type") ?? "LIKE",
4220
- now,
4221
- void 0,
4222
- bool(args, "remove")
4223
- );
4224
- case "delete":
4225
- return runDelete(args.positionals[0], now, void 0, bool(args, "quiet"));
4226
4427
  case "whoami":
4227
4428
  return runWhoami(bool(args, "raw"));
4228
4429
  case "profile":
@@ -4263,7 +4464,45 @@ if (entry.run) {
4263
4464
  `);
4264
4465
  process.exit(exitCodeFor(envelope));
4265
4466
  }
4266
- function share3(args, now) {
4467
+ async function write(command, args, now) {
4468
+ if (args.flags.confirm === true) {
4469
+ return err(
4470
+ command,
4471
+ "INVALID_INPUT",
4472
+ "--confirm needs the token that --plan returned",
4473
+ `lnrelay ${command} \u2026 --plan, then the same command with --confirm <token>`
4474
+ );
4475
+ }
4476
+ const mode = loadApprovalMode();
4477
+ if (!mode.ok) return err(command, "CACHE_CORRUPT", mode.message, mode.hint);
4478
+ const deps = {
4479
+ ...terminalDeps(),
4480
+ approval: { mode: mode.mode, token: str(args, "confirm"), planOnly: bool(args, "plan") }
4481
+ };
4482
+ const envelope = await runWrite(command, args, now, deps);
4483
+ if (wasApproved()) auditOutcome(command, mode.mode, envelope);
4484
+ return envelope;
4485
+ }
4486
+ function runWrite(command, args, now, deps) {
4487
+ const [first, second] = args.positionals;
4488
+ switch (command) {
4489
+ case "share":
4490
+ return share3(args, now, deps);
4491
+ case "comment":
4492
+ return runComment(first, second, now, deps);
4493
+ case "edit":
4494
+ return runEdit(first, second, now, deps);
4495
+ case "reply":
4496
+ return runReply(first, second, now, deps);
4497
+ case "react":
4498
+ return runReact(first, str(args, "type") ?? "LIKE", now, deps, bool(args, "remove"));
4499
+ case "delete":
4500
+ return runDelete(first, now, deps, bool(args, "quiet"));
4501
+ default:
4502
+ return err(command, "NOT_IMPLEMENTED", `'${command}' has no write runner`);
4503
+ }
4504
+ }
4505
+ function share3(args, now, deps) {
4267
4506
  const surface = via(args);
4268
4507
  if (surface === "invalid") {
4269
4508
  return err(
@@ -4273,29 +4512,33 @@ function share3(args, now) {
4273
4512
  "one of: oauth, voyager. Omit it to prefer OAuth and fall back to Voyager."
4274
4513
  );
4275
4514
  }
4276
- for (const flag of ["image", "video"]) {
4515
+ for (const flag of ["image", "video", "alt"]) {
4277
4516
  if (args.flags[flag] === true) {
4278
4517
  return err("share", "INVALID_INPUT", `--${flag} needs a file path`);
4279
4518
  }
4280
4519
  }
4281
- const image = str(args, "image");
4282
- const video = str(args, "video");
4283
- if (image !== void 0 && video !== void 0) {
4520
+ const images = list(args, "image");
4521
+ const videos = list(args, "video");
4522
+ if (images.length > 0 && videos.length > 0) {
4284
4523
  return err(
4285
4524
  "share",
4286
4525
  "INVALID_INPUT",
4287
- "a post carries an image or a video, not both",
4288
- "pass one of --image <path> or --video <path>"
4526
+ "a post carries images or a video, not both",
4527
+ "pass --image <path> (repeatable) or a single --video <path>"
4289
4528
  );
4290
4529
  }
4530
+ const alts = list(args, "alt");
4291
4531
  let media;
4292
- if (image !== void 0) media = { flag: "image", path: image };
4293
- else if (video !== void 0) media = { flag: "video", path: video };
4532
+ if (images.length > 0) media = { flag: "image", paths: images, alts };
4533
+ else if (videos.length > 0) media = { flag: "video", paths: videos, alts };
4534
+ else if (alts.length > 0) {
4535
+ return err("share", "INVALID_INPUT", "--alt describes an --image, and none was given");
4536
+ }
4294
4537
  return runShare(
4295
4538
  args.positionals[0],
4296
4539
  str(args, "visibility") ?? "public",
4297
4540
  now,
4298
- void 0,
4541
+ deps,
4299
4542
  surface,
4300
4543
  media
4301
4544
  );