linkedin-relay-mcp 3.6.1 → 3.8.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
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env bun
2
+ // src/cli.ts
3
+ import { readFileSync as readFileSync3 } from "fs";
4
+
2
5
  // src/args.ts
3
6
  function parseArgs(argv) {
4
7
  const [command, ...rest] = argv;
@@ -1998,9 +2001,9 @@ function textStates(payload, text2) {
1998
2001
  }
1999
2002
  return null;
2000
2003
  };
2001
- const plain = keyOf("commentary", "commentFieldBinding");
2004
+ const plain2 = keyOf("commentary", "commentFieldBinding");
2002
2005
  const rich = keyOf("richTextCommentary", "richCommentFieldBinding");
2003
- if (plain === null || rich === null) return [];
2006
+ if (plain2 === null || rich === null) return [];
2004
2007
  const entry2 = (key, value, protoCase) => ({
2005
2008
  key,
2006
2009
  namespace: "MemoryNamespace",
@@ -2009,7 +2012,7 @@ function textStates(payload, text2) {
2009
2012
  protoKey: { $type: "proto.sdui.Key", value: { $case: "id", id: key } }
2010
2013
  });
2011
2014
  return [
2012
- entry2(plain, text2, "stringValue"),
2015
+ entry2(plain2, text2, "stringValue"),
2013
2016
  entry2(rich, { text: text2, attribute: [], $type: "TextModel", source: "local" }, "textModelForWrite")
2014
2017
  ];
2015
2018
  }
@@ -2068,12 +2071,12 @@ function parseCommentUrn(urn) {
2068
2071
  activityId: fsd[3]
2069
2072
  };
2070
2073
  }
2071
- const plain = /^urn:li:comment:\((?:urn:li:)?(activity|ugcPost):(\d+),(\d+)\)$/.exec(urn);
2072
- if (plain !== null) {
2074
+ const plain2 = /^urn:li:comment:\((?:urn:li:)?(activity|ugcPost):(\d+),(\d+)\)$/.exec(urn);
2075
+ if (plain2 !== null) {
2073
2076
  return {
2074
- threadType: plain[1],
2075
- activityId: plain[2],
2076
- commentId: plain[3]
2077
+ threadType: plain2[1],
2078
+ activityId: plain2[2],
2079
+ commentId: plain2[3]
2077
2080
  };
2078
2081
  }
2079
2082
  return null;
@@ -3606,6 +3609,15 @@ var COMMANDS = [
3606
3609
  risk: "read",
3607
3610
  implemented: true
3608
3611
  },
3612
+ {
3613
+ name: "experience",
3614
+ cost: "2 calls",
3615
+ summary: "The roles on your own profile, with the position id `role edit|remove` takes.",
3616
+ usage: "lnrelay experience",
3617
+ audience: ["cli", "mcp"],
3618
+ risk: "read",
3619
+ implemented: true
3620
+ },
3609
3621
  {
3610
3622
  name: "local",
3611
3623
  cost: "free \u2014 local cache",
@@ -3691,8 +3703,17 @@ var COMMANDS = [
3691
3703
  {
3692
3704
  name: "edit",
3693
3705
  cost: "1 read + 1 write",
3694
- summary: "Change the text of a comment or post you wrote. Its own verb, so a comment urn can never be mistaken for something to comment ON.",
3695
- usage: 'lnrelay edit <comment-urn | share-urn | ugcPost-urn> "<text>"\n A post is edited by the urn it was created as (`share` prints it; `my-posts` lists\n it as shareUrn), not its activity urn. The whole text is replaced.',
3706
+ summary: "Change the text of a comment or post you wrote, or your profile headline or About. Its own verb, so a comment urn can never be mistaken for something to comment ON.",
3707
+ usage: 'lnrelay edit <comment-urn | share-urn | ugcPost-urn> "<text>"\n lnrelay edit headline|about ("<text>" | --file <path>)\n A post is edited by the urn it was created as (`share` prints it; `my-posts` lists\n it as shareUrn), not its activity urn. The whole text is replaced. A profile edit\n shows the current text beside the new one, sends every other profile field back as\n LinkedIn holds it, and reads the profile back to confirm. Headline max 220 characters.',
3708
+ audience: ["cli"],
3709
+ risk: "write",
3710
+ implemented: true
3711
+ },
3712
+ {
3713
+ name: "role",
3714
+ cost: "3-4 reads + 1 write",
3715
+ summary: "Add, edit or remove a role in your Experience. Never rewrites your headline; notify network is off unless --notify.",
3716
+ usage: 'lnrelay role add --title "<t>" --company "<c>" --start YYYY-MM [--end YYYY-MM | --current]\n [--location "<l>"] [--description "<d>" | --description-file <path>] [--notify]\n lnrelay role edit <position-id> [any of the flags above]\n lnrelay role remove <position-id>\n Position ids come from `lnrelay experience`. The preview shows the role as it is and\n as it will be; the result is read back from the profile. A role with media attached\n is refused. The company is free text (not linked to a company page).',
3696
3717
  audience: ["cli"],
3697
3718
  risk: "write",
3698
3719
  implemented: true
@@ -3723,120 +3744,496 @@ function helpText() {
3723
3744
  return lines.join("\n");
3724
3745
  }
3725
3746
 
3726
- // src/commands/sync.ts
3727
- var CONNECTIONS_MIN_INTERVAL_MS = 7 * 864e5;
3728
- function searchText(item) {
3729
- return [item.name, item.headline, item.location, item.text, item.author, item.company, item.title].filter((v) => typeof v === "string").join(" ");
3747
+ // src/engine/sdui-form.ts
3748
+ function balanced(s, start) {
3749
+ const open = s[start];
3750
+ const close = open === "[" ? "]" : "}";
3751
+ let depth = 0;
3752
+ let inString = false;
3753
+ let escaped = false;
3754
+ for (let i = start; i < s.length; i++) {
3755
+ const ch = s[i];
3756
+ if (escaped) escaped = false;
3757
+ else if (ch === "\\") escaped = true;
3758
+ else if (ch === '"') inString = !inString;
3759
+ else if (!inString && ch === open) depth++;
3760
+ else if (!inString && ch === close) {
3761
+ depth--;
3762
+ if (depth === 0) return s.slice(start, i + 1);
3763
+ }
3764
+ }
3765
+ return null;
3730
3766
  }
3731
- function rowsFrom(items) {
3732
- return items.filter((i) => typeof i.urn === "string" && i.urn !== "").map((i) => ({ urn: i.urn, body: i, text: searchText(i) }));
3767
+ function parseAt(s, start) {
3768
+ const text2 = start < 0 ? null : balanced(s, start);
3769
+ if (text2 === null) return null;
3770
+ try {
3771
+ return JSON.parse(text2);
3772
+ } catch {
3773
+ return null;
3774
+ }
3733
3775
  }
3734
- function diffSnapshot(before, seen, claimed) {
3735
- const complete = claimed === void 0 || seen.size >= claimed;
3736
- if (!complete) return { removed: [], complete: false };
3737
- return { removed: [...before].filter((urn) => !seen.has(urn)), complete: true };
3776
+ function plain(v) {
3777
+ const protoCase = String(v.$case);
3778
+ const raw = v[protoCase];
3779
+ if (protoCase === "stringListValue") {
3780
+ return { protoCase, value: raw?.stringValues ?? [] };
3781
+ }
3782
+ if (protoCase === "signedLongValue" && typeof raw === "string" && raw.startsWith("$n")) {
3783
+ return { protoCase, value: { type: "bigint", value: raw.slice(2) } };
3784
+ }
3785
+ return { protoCase, value: raw };
3738
3786
  }
3739
- async function syncMyPosts(engine, db, limit, now) {
3740
- const me = await engine.whoami();
3741
- if (!me.ok) return err("sync", me.code, me.message, me.hint);
3742
- const profileUrn = typeof me.value?.entityUrn === "string" ? me.value.entityUrn : void 0;
3743
- if (profileUrn === void 0) {
3744
- return err("sync", "SCHEMA_DRIFT", "could not determine the owner profile urn");
3787
+ function readModel(stream) {
3788
+ const at = stream.indexOf('"modelStates":[');
3789
+ const entries = parseAt(stream, at === -1 ? -1 : stream.indexOf("[", at));
3790
+ if (entries === null) return null;
3791
+ const model = /* @__PURE__ */ new Map();
3792
+ for (const entry2 of entries) {
3793
+ const id = entry2.key?.key?.value?.id;
3794
+ if (id !== void 0 && entry2.value !== void 0 && !model.has(id)) {
3795
+ model.set(id, plain(entry2.value));
3796
+ }
3745
3797
  }
3746
- const result = await engine.myPosts(profileUrn, limit);
3747
- if (!result.ok) return err("sync", result.code, result.message, result.hint);
3748
- const rows = rowsFrom(shapeAll(result.value.parsed.items, result.value.index));
3749
- const stored = upsert(db, "my-posts", rows, now);
3750
- setCheckpoint(db, {
3751
- source: "my-posts",
3752
- lastSuccessfulAt: now,
3753
- newestCreatedAt: null,
3754
- headIds: rows.slice(0, 5).map((r) => r.urn),
3755
- state: "ok"
3756
- });
3757
- return ok("sync", {
3758
- source: "my-posts",
3759
- ...stored,
3760
- meta: result.value.parsed.meta,
3761
- note: rows.length === 0 ? "LinkedIn returned no posts for this account. That is a genuine empty, not a failed fetch \u2014 meta.state says which." : void 0
3762
- });
3798
+ return model;
3763
3799
  }
3764
- function tooSoon(db, now) {
3765
- const cp = getCheckpoint(db, "connections");
3766
- const age = cp === void 0 ? Number.POSITIVE_INFINITY : now - cp.lastSuccessfulAt;
3767
- if (age >= CONNECTIONS_MIN_INTERVAL_MS) return void 0;
3768
- const days = Math.ceil((CONNECTIONS_MIN_INTERVAL_MS - age) / 864e5);
3769
- return err(
3770
- "sync",
3771
- "BUDGET_EXHAUSTED",
3772
- `connections were synced ${Math.floor(age / 864e5)} days ago`,
3773
- `This is the most expensive read in the tool and connections change slowly. Wait ${days} more day(s), or pass --force.`
3800
+ function findRequest(stream, requestId) {
3801
+ const at = stream.indexOf(`"requestId":"${requestId}","requestedArguments":`);
3802
+ if (at === -1) return null;
3803
+ const args = parseAt(
3804
+ stream,
3805
+ stream.indexOf("{", stream.indexOf('"requestedArguments":', at))
3774
3806
  );
3807
+ return args !== null && Array.isArray(args.requestedStateKeys) && args.payload !== void 0 ? args : null;
3808
+ }
3809
+ var unknownExpression = (what) => ({
3810
+ ok: false,
3811
+ code: "SCHEMA_DRIFT",
3812
+ message: `the form computes a value with an expression this tool does not evaluate (${what})`,
3813
+ hint: "Nothing was sent. Re-capture the form to see what it has become."
3814
+ });
3815
+ function boundId(body) {
3816
+ return body?.key?.key?.value?.id;
3817
+ }
3818
+ function str2(node, model) {
3819
+ const e = node.expression;
3820
+ if (e?.$case === "stringValue") return String(e.stringValue);
3821
+ if (e?.$case === "bindableString") {
3822
+ const v = model.get(boundId(e.bindableString) ?? "")?.value;
3823
+ return typeof v === "string" ? v : "";
3824
+ }
3825
+ return null;
3775
3826
  }
3776
- async function syncConnections(engine, db, limit, force, now) {
3777
- const before = urnsFor(db, "connections");
3778
- if (!force && before.size > 0) {
3779
- const blocked = tooSoon(db, now);
3780
- if (blocked !== void 0) return blocked;
3827
+ function bool2(node, model) {
3828
+ const e = node.expression;
3829
+ const body = e?.[e?.$case ?? ""];
3830
+ switch (e?.$case) {
3831
+ case "booleanExpression":
3832
+ return bool2(body, model);
3833
+ case "booleanValue":
3834
+ return e.booleanValue === true;
3835
+ case "bindableBoolean":
3836
+ return model.get(boundId(e.bindableBoolean) ?? "")?.value === true;
3837
+ case "notExpression": {
3838
+ const a = bool2(body?.a ?? {}, model);
3839
+ return a === null ? null : !a;
3840
+ }
3841
+ case "orExpression":
3842
+ case "andExpression": {
3843
+ const a = bool2(body?.a ?? {}, model);
3844
+ const b = bool2(body?.b ?? {}, model);
3845
+ if (a === null || b === null) return null;
3846
+ return e.$case === "orExpression" ? a || b : a && b;
3847
+ }
3848
+ case "stringEqualsExpression": {
3849
+ const a = str2(body?.a ?? {}, model);
3850
+ const b = str2(body?.b ?? {}, model);
3851
+ if (a === null || b === null) return null;
3852
+ return body.ignoreCase === true ? a.toLowerCase() === b.toLowerCase() : a === b;
3853
+ }
3854
+ default:
3855
+ return null;
3781
3856
  }
3782
- const result = await engine.connections(limit);
3783
- if (!result.ok) return err("sync", result.code, result.message, result.hint);
3784
- const rows = rowsFrom(shapeAll(result.value.parsed.items, result.value.index));
3785
- const stored = upsert(db, "connections", rows, now);
3786
- const claimed = result.value.parsed.meta.claimedCount;
3787
- const seen = new Set(rows.map((r) => r.urn));
3788
- const { removed, complete } = diffSnapshot(before, seen, claimed);
3789
- if (removed.length > 0) removeUrns(db, "connections", removed);
3790
- setCheckpoint(db, {
3791
- source: "connections",
3792
- lastSuccessfulAt: now,
3793
- newestCreatedAt: null,
3794
- headIds: [],
3795
- // Honest: a snapshot, never a watermark.
3796
- state: complete ? "ok" : "snapshot-partial"
3797
- });
3798
- return ok("sync", {
3799
- source: "connections",
3800
- added: stored.added,
3801
- updated: stored.updated,
3802
- removed: removed.length,
3803
- claimed,
3804
- complete,
3805
- meta: result.value.parsed.meta,
3806
- note: complete ? void 0 : `Only ${rows.length} of ${claimed} connections were retrieved, so removals could not be determined and none were applied. Raise --limit to complete the snapshot.`
3857
+ }
3858
+ function evaluate(expression, model) {
3859
+ const value = bool2(expression, model);
3860
+ return value === null ? unknownExpression(JSON.stringify(expression).slice(0, 80)) : { ok: true, value };
3861
+ }
3862
+ function wireStates(keys, model, resolve) {
3863
+ const out = [];
3864
+ for (const id of keys) {
3865
+ const state = model.get(id);
3866
+ if (state === void 0) continue;
3867
+ let value = state.value;
3868
+ if (state.protoCase === "expression") {
3869
+ const r = resolve(id, state) ?? evaluate(state.value, model);
3870
+ if (!r.ok) return r;
3871
+ value = r.value;
3872
+ }
3873
+ out.push({
3874
+ key: id,
3875
+ namespace: "MemoryNamespace",
3876
+ value,
3877
+ originalProtoCase: state.protoCase,
3878
+ protoKey: { $type: "proto.sdui.Key", value: { $case: "id", id } }
3879
+ });
3880
+ }
3881
+ return out;
3882
+ }
3883
+ var keysOf = (args) => args.requestedStateKeys.map((k) => k.key.value.id);
3884
+ function requestBody(requestId, args, states2, screen) {
3885
+ const requestedArguments = {
3886
+ $type: "proto.sdui.actions.requests.RequestedArguments",
3887
+ requestedStateKeys: args.requestedStateKeys,
3888
+ payload: args.payload,
3889
+ requestMetadata: { $type: "proto.sdui.common.RequestMetadata" }
3890
+ };
3891
+ return {
3892
+ requestId,
3893
+ serverRequest: {
3894
+ requestId,
3895
+ requestedArguments,
3896
+ isApfcEnabled: false,
3897
+ isStreaming: false,
3898
+ rumPageKey: ""
3899
+ },
3900
+ states: states2,
3901
+ requestedArguments: { ...requestedArguments, states: states2, screenId: screen, knownTemplateIds: [] }
3902
+ };
3903
+ }
3904
+ function navBody(screen, payload) {
3905
+ return {
3906
+ clientArguments: {
3907
+ $type: "proto.sdui.actions.requests.RequestedArguments",
3908
+ requestedStateKeys: [],
3909
+ payload,
3910
+ requestMetadata: { $type: "proto.sdui.common.RequestMetadata" },
3911
+ states: [],
3912
+ screenId: screen,
3913
+ knownTemplateIds: []
3914
+ },
3915
+ isModal: true
3916
+ };
3917
+ }
3918
+ function responseErrors(raw) {
3919
+ return raw.match(/"errors":\[([^\]]+)\]/)?.[1]?.slice(0, 300) ?? null;
3920
+ }
3921
+
3922
+ // src/engine/sdui-profile.ts
3923
+ var NAV_URL = "https://www.linkedin.com/flagship-web/rsc-action/actions/navigation";
3924
+ var ACTION_URL = "https://www.linkedin.com/flagship-web/rsc-action/actions/server-request";
3925
+ var PROFILE_FIELDS = {
3926
+ headline: {
3927
+ name: "headline",
3928
+ screen: "com.linkedin.sdui.flagshipnav.profile.ProfileEditIntroForm",
3929
+ save: "com.linkedin.sdui.requests.profile.saveProfileIntroForm",
3930
+ binding: "headline",
3931
+ // The web form refuses more ("Exceeded maximum length of 220 characters").
3932
+ maxLength: 220
3933
+ },
3934
+ about: {
3935
+ name: "about",
3936
+ screen: "com.linkedin.sdui.flagshipnav.profile.ProfileAboutForm",
3937
+ save: "com.linkedin.sdui.requests.profile.saveProfileAboutForm",
3938
+ binding: "about",
3939
+ maxLength: 2600
3940
+ }
3941
+ };
3942
+ var drift2 = (message) => ({
3943
+ ok: false,
3944
+ code: "SCHEMA_DRIFT",
3945
+ message,
3946
+ hint: "Re-capture the profile form with scripts/observe-write.ts (edit one character, then revert)."
3947
+ });
3948
+ function readForm(stream, field) {
3949
+ const states2 = readModel(stream);
3950
+ if (states2 === null) return drift2("the profile form carried no initial values");
3951
+ const args = findRequest(stream, field.save);
3952
+ if (args === null)
3953
+ return drift2(`the profile form carried no ${field.save.split(".").pop()} action`);
3954
+ return { ok: true, args, states: states2, screen: field.screen, save: field.save };
3955
+ }
3956
+ function boundKey(form, property) {
3957
+ const ref = form.args.payload[property];
3958
+ return ref?.key;
3959
+ }
3960
+ function currentValue(form, field) {
3961
+ const key = boundKey(form, field.binding);
3962
+ const v = key === void 0 ? void 0 : form.states.get(key)?.value;
3963
+ return typeof v === "string" ? v : void 0;
3964
+ }
3965
+ function topSkills(form) {
3966
+ return (key) => {
3967
+ if (!key.endsWith("ReorderableSkillsFormBindingsskillIdsBinding")) return void 0;
3968
+ const initial = [...form.states.entries()].find(([k]) => k.startsWith("initialSkills"))?.[1];
3969
+ if (initial === void 0) return drift2("the About form carried no initial top skills");
3970
+ if (!Array.isArray(initial.value) || initial.value.length > 0) {
3971
+ return {
3972
+ ok: false,
3973
+ code: "NOT_IMPLEMENTED",
3974
+ message: "your About section has top skills, and saving it with them has not been verified",
3975
+ hint: "Edit About in the browser for now; nothing was changed."
3976
+ };
3977
+ }
3978
+ return { ok: true, value: [] };
3979
+ };
3980
+ }
3981
+ function saveBody(form, field, value) {
3982
+ if (value.length > field.maxLength) {
3983
+ return {
3984
+ ok: false,
3985
+ code: "INVALID_INPUT",
3986
+ message: `the ${field.name} is ${value.length} characters; LinkedIn allows ${field.maxLength}`
3987
+ };
3988
+ }
3989
+ const target = boundKey(form, field.binding);
3990
+ const current = target === void 0 ? void 0 : form.states.get(target);
3991
+ if (target === void 0 || current === void 0) {
3992
+ return drift2(`the profile form has no ${field.name} field`);
3993
+ }
3994
+ const model = new Map(form.states);
3995
+ model.set(target, { ...current, value });
3996
+ const states2 = wireStates(keysOf(form.args), model, topSkills(form));
3997
+ if (!Array.isArray(states2)) return states2;
3998
+ return { ok: true, body: requestBody(form.save, form.args, states2, form.screen) };
3999
+ }
4000
+ async function fetchProfileForm(field, vanityName, client) {
4001
+ const stream = await openForm(
4002
+ field.screen,
4003
+ { vanityName, isVanityNameResolved: true },
4004
+ client,
4005
+ `profile-${field.name}-form`
4006
+ );
4007
+ return typeof stream === "string" ? readForm(stream, field) : stream;
4008
+ }
4009
+ async function openForm(screen, payload, client, operation) {
4010
+ const result = await client.request({
4011
+ url: `${NAV_URL}?screenId=${screen}&sduiid=${screen}`,
4012
+ method: "POST",
4013
+ body: navBody(screen, payload),
4014
+ spendClass: "page",
4015
+ operation
3807
4016
  });
4017
+ if (!result.ok) {
4018
+ const out = { ok: false, code: result.code, message: result.message };
4019
+ if (result.hint !== void 0) out.hint = result.hint;
4020
+ return out;
4021
+ }
4022
+ return result.classification.raw ?? "";
3808
4023
  }
3809
- async function runSync(source, limit, force, now = Date.now()) {
3810
- if (source !== "my-posts" && source !== "connections") {
3811
- return err(
3812
- "sync",
3813
- "INVALID_INPUT",
3814
- `unknown sync source '${source ?? ""}'`,
3815
- "lnrelay sync my-posts | lnrelay sync connections"
3816
- );
4024
+ async function sendAction(requestId, body, client, operation, spendClass = "write") {
4025
+ const result = await client.request({
4026
+ url: `${ACTION_URL}?sduiid=${requestId}`,
4027
+ method: "POST",
4028
+ body,
4029
+ spendClass,
4030
+ operation
4031
+ });
4032
+ if (!result.ok) {
4033
+ const out = { ok: false, code: result.code, message: result.message };
4034
+ if (result.hint !== void 0) out.hint = result.hint;
4035
+ return out;
3817
4036
  }
3818
- const session = loadSession();
3819
- if (session.state === "corrupt") {
3820
- return err("sync", "CACHE_CORRUPT", "the stored session was unreadable", LAUNCH_HINT);
4037
+ const raw = result.classification.raw ?? "";
4038
+ const errors = responseErrors(raw);
4039
+ if (errors !== null) {
4040
+ return { ok: false, code: "INVALID_INPUT", message: `LinkedIn refused it: ${errors}` };
3821
4041
  }
3822
- if (session.state === "missing") {
3823
- return err("sync", "AUTH_FAILED", "no session \u2014 run `lnrelay login` first", LAUNCH_HINT);
4042
+ return raw;
4043
+ }
4044
+ async function sendProfileSave(form, body, client) {
4045
+ const r = await sendAction(form.save, body, client, "profile-save");
4046
+ return typeof r === "string" ? { ok: true } : r;
4047
+ }
4048
+
4049
+ // src/engine/sdui-position.ts
4050
+ var POSITION = {
4051
+ addScreen: "com.linkedin.sdui.flagshipnav.profile.ProfilePositionAddForm",
4052
+ editScreen: "com.linkedin.sdui.flagshipnav.profile.ProfilePositionDetailsEditForm",
4053
+ listScreen: "com.linkedin.sdui.flagshipnav.profile.ProfileExperienceDetails",
4054
+ media: "com.linkedin.sdui.impl.profile.components.forms.uploadPositionMedia",
4055
+ save: "com.linkedin.sdui.requests.profile.saveProfilePositionForm",
4056
+ delete: "com.linkedin.sdui.requests.profile.deleteProfilePositionForm"
4057
+ };
4058
+ var EDIT_NAV = `{"$type":"proto.sdui.actions.core.NavigateToScreen","screenId":"${POSITION.editScreen}"`;
4059
+ function listPositions(stream) {
4060
+ if (readModel(stream) === null && !stream.includes(EDIT_NAV) && !stream.includes('"rows"')) {
4061
+ return drift2("the Experience screen could not be read");
3824
4062
  }
3825
- const engine = createEngine(session.session);
3826
- try {
3827
- const db = openDb(now);
3828
- return source === "my-posts" ? await syncMyPosts(engine, db, limit, now) : await syncConnections(engine, db, limit, force, now);
3829
- } catch (e) {
3830
- if (e instanceof CacheCorrupt) {
3831
- return err(
3832
- "sync",
3833
- "CACHE_CORRUPT",
3834
- e.message,
3835
- `Moved to ${e.quarantinedTo}. A corrupt cache is NOT treated as empty \u2014 that would make this sync re-enumerate everything. Inspect it, then re-run.`
3836
- );
3837
- }
3838
- throw e;
4063
+ const positions = [];
4064
+ const seen = /* @__PURE__ */ new Set();
4065
+ let i = 0;
4066
+ for (; ; ) {
4067
+ i = stream.indexOf(EDIT_NAV, i);
4068
+ if (i === -1) break;
4069
+ const text2 = balanced(stream, i);
4070
+ i += EDIT_NAV.length;
4071
+ if (text2 === null) continue;
4072
+ const payload = JSON.parse(text2).requestedArguments?.payload;
4073
+ const id = payload?.positionId;
4074
+ if (typeof id !== "string" || seen.has(id) || payload === void 0) continue;
4075
+ seen.add(id);
4076
+ positions.push({ positionId: id, title: String(payload.title ?? ""), payload });
4077
+ }
4078
+ if (positions.length === 0 && !stream.includes('"rows"') && !stream.includes("Experience")) {
4079
+ return drift2("the Experience screen listed no roles and did not look like one");
4080
+ }
4081
+ return { ok: true, positions };
4082
+ }
4083
+ function readPositionForm(stream) {
4084
+ const model = readModel(stream);
4085
+ if (model === null) return drift2("the position form carried no initial values");
4086
+ const media = findRequest(stream, POSITION.media);
4087
+ const prefix = media?.payload.formIdPrefix;
4088
+ if (media === null || typeof prefix !== "string") {
4089
+ return drift2("the position form carried no save step (uploadPositionMedia)");
4090
+ }
4091
+ const del = findRequest(stream, POSITION.delete);
4092
+ return {
4093
+ ok: true,
4094
+ model,
4095
+ prefix,
4096
+ media,
4097
+ del,
4098
+ screen: del === null ? POSITION.addScreen : POSITION.editScreen
4099
+ };
4100
+ }
4101
+ var date = (d) => ({
4102
+ $type: "proto.sdui.common.Date",
4103
+ day: 0,
4104
+ month: d.month,
4105
+ year: d.year
4106
+ });
4107
+ var ym = (v) => {
4108
+ const d = v;
4109
+ return d?.year ? `${d.year}-${String(d.month ?? 0).padStart(2, "0")}` : null;
4110
+ };
4111
+ function applyChanges(form, changes) {
4112
+ const model = new Map(form.model);
4113
+ const set = (field, value) => {
4114
+ const key = `${form.prefix}${field}`;
4115
+ const current = model.get(key);
4116
+ if (current === void 0) return false;
4117
+ model.set(key, { ...current, value });
4118
+ return true;
4119
+ };
4120
+ const missing = [];
4121
+ const need = (field, value) => {
4122
+ if (!set(field, value)) missing.push(field);
4123
+ };
4124
+ if (changes.title !== void 0) need("title", changes.title);
4125
+ if (changes.description !== void 0) need("description", changes.description);
4126
+ if (changes.location !== void 0) need("location", changes.location);
4127
+ if (changes.company !== void 0) {
4128
+ need("companyName", changes.company);
4129
+ need("organizationId", -1);
4130
+ need("organizationEntityId", { type: "bigint", value: "-1" });
4131
+ }
4132
+ if (changes.start !== void 0) need("startDate", date(changes.start));
4133
+ if (changes.end === "present") need("isCurrentPosition", true);
4134
+ else if (changes.end !== void 0) {
4135
+ need("isCurrentPosition", false);
4136
+ need("endDate", date(changes.end));
4137
+ }
4138
+ need("dynamicallyCreateHeadline", false);
4139
+ need("allowProfileEditBroadcasts", changes.notify === true);
4140
+ if (missing.length > 0) return drift2(`the position form has no ${missing.join(", ")} field`);
4141
+ const s = roleSummary(model);
4142
+ if (!s.current && s.start !== null && s.end !== null && s.end < s.start) {
4143
+ return {
4144
+ ok: false,
4145
+ code: "INVALID_INPUT",
4146
+ message: `the role ends (${s.end}) before it starts (${s.start})`
4147
+ };
3839
4148
  }
4149
+ return { ok: true, model };
4150
+ }
4151
+ function roleSummary(model) {
4152
+ const get = (field) => [...model.entries()].find(([k]) => k.endsWith(`ProfilePositionForm${field}`))?.[1].value;
4153
+ const current = get("isCurrentPosition") === true;
4154
+ return {
4155
+ title: String(get("title") ?? ""),
4156
+ company: String(get("companyName") ?? ""),
4157
+ start: ym(get("startDate")),
4158
+ end: current ? null : ym(get("endDate")),
4159
+ current,
4160
+ location: String(get("location") ?? ""),
4161
+ description: String(get("description") ?? "")
4162
+ };
4163
+ }
4164
+ function noMedia(model) {
4165
+ const count2 = [...model.entries()].find(
4166
+ ([k]) => k.endsWith("position-mediaUiCollection-mediaCount")
4167
+ )?.[1].value;
4168
+ return typeof count2 === "number" && count2 > 0 ? {
4169
+ ok: false,
4170
+ code: "NOT_IMPLEMENTED",
4171
+ message: "this role has media attached, and saving one with media has not been verified",
4172
+ hint: "Edit it in the browser for now; nothing was changed."
4173
+ } : null;
4174
+ }
4175
+ var resolver = (key) => key.endsWith("position-mediaIds") ? { ok: true, value: [] } : void 0;
4176
+ function mediaBody(form, model) {
4177
+ const refused = noMedia(model);
4178
+ if (refused !== null) return refused;
4179
+ const states2 = wireStates(keysOf(form.media), model, resolver);
4180
+ if (!Array.isArray(states2)) return states2;
4181
+ return { ok: true, body: requestBody(POSITION.media, form.media, states2, form.screen) };
4182
+ }
4183
+ function saveFromReply(reply) {
4184
+ const args = findRequest(reply, POSITION.save);
4185
+ return args === null ? drift2("the media step did not hand back the save action") : { ok: true, args };
4186
+ }
4187
+ function positionSaveBody(save, model, screen) {
4188
+ const sending = new Map(model);
4189
+ for (const [k, v] of sending)
4190
+ if (k.endsWith("isActiveProfileFormLoading")) sending.set(k, { ...v, value: true });
4191
+ const states2 = wireStates(keysOf(save), sending, resolver);
4192
+ if (!Array.isArray(states2)) return states2;
4193
+ return { ok: true, body: requestBody(POSITION.save, save, states2, screen) };
4194
+ }
4195
+ function deleteBody(form) {
4196
+ if (form.del === null)
4197
+ return drift2("this form has no delete action (it is not an existing role)");
4198
+ const states2 = wireStates(keysOf(form.del), form.model, resolver);
4199
+ if (!Array.isArray(states2)) return states2;
4200
+ return { ok: true, body: requestBody(POSITION.delete, form.del, states2, form.screen) };
4201
+ }
4202
+ async function fetchPositions(vanityName, client) {
4203
+ const stream = await openForm(
4204
+ POSITION.listScreen,
4205
+ { vanityName, isVanityNameResolved: true },
4206
+ client,
4207
+ "experience-list"
4208
+ );
4209
+ return typeof stream === "string" ? listPositions(stream) : stream;
4210
+ }
4211
+ async function openPositionForm(payload, client, edit2) {
4212
+ const stream = await openForm(
4213
+ edit2 ? POSITION.editScreen : POSITION.addScreen,
4214
+ { ...payload, isVanityNameResolved: true },
4215
+ client,
4216
+ edit2 ? "position-edit-form" : "position-add-form"
4217
+ );
4218
+ return typeof stream === "string" ? readPositionForm(stream) : stream;
4219
+ }
4220
+ async function sendPositionSave(form, model, client) {
4221
+ const media = mediaBody(form, model);
4222
+ if (!media.ok) return media;
4223
+ const reply = await sendAction(POSITION.media, media.body, client, "position-media-step", "page");
4224
+ if (typeof reply !== "string") return reply;
4225
+ const save = saveFromReply(reply);
4226
+ if (!save.ok) return save;
4227
+ const body = positionSaveBody(save.args, model, form.screen);
4228
+ if (!body.ok) return body;
4229
+ const sent = await sendAction(POSITION.save, body.body, client, "position-save");
4230
+ return typeof sent === "string" ? { ok: true } : sent;
4231
+ }
4232
+ async function sendPositionDelete(form, client) {
4233
+ const body = deleteBody(form);
4234
+ if (!body.ok) return body;
4235
+ const sent = await sendAction(POSITION.delete, body.body, client, "position-delete");
4236
+ return typeof sent === "string" ? { ok: true } : sent;
3840
4237
  }
3841
4238
 
3842
4239
  // src/commands/write.ts
@@ -4410,9 +4807,9 @@ function parseScheduleTime(input) {
4410
4807
  const local = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})$/.exec(input);
4411
4808
  if (local === null) return null;
4412
4809
  const [y, mo, d, h, mi] = local.slice(1).map(Number);
4413
- const date = new Date(y, mo - 1, d, h, mi);
4414
- const same = date.getFullYear() === y && date.getMonth() === mo - 1 && date.getDate() === d && date.getHours() === h && date.getMinutes() === mi;
4415
- return same ? date.getTime() : null;
4810
+ const date2 = new Date(y, mo - 1, d, h, mi);
4811
+ const same = date2.getFullYear() === y && date2.getMonth() === mo - 1 && date2.getDate() === d && date2.getHours() === h && date2.getMinutes() === mi;
4812
+ return same ? date2.getTime() : null;
4416
4813
  }
4417
4814
  var MIN_LEAD_MS = 10 * 6e4;
4418
4815
  function mediaFrom(media, via2) {
@@ -4634,6 +5031,91 @@ async function runEditPost(urn, text2, now, deps) {
4634
5031
  const result = await editPost(gated.confirmed, createLiveClient(ctx.transport.session));
4635
5032
  return result.ok ? ok("edit", { edited: urn }) : err("edit", result.code, result.message, result.hint);
4636
5033
  }
5034
+ function liveProfile(session) {
5035
+ const client = createLiveClient(session);
5036
+ return {
5037
+ vanity: async () => {
5038
+ const me = await createEngine(session).whoami();
5039
+ if (!me.ok) return me;
5040
+ const id = me.value?.publicIdentifier ?? null;
5041
+ return typeof id === "string" && id !== "" ? { ok: true, vanity: id } : { ok: false, code: "SCHEMA_DRIFT", message: "whoami returned no public profile id" };
5042
+ },
5043
+ open: (field, vanity) => fetchProfileForm(field, vanity, client),
5044
+ send: (form, body) => sendProfileSave(form, body, client)
5045
+ };
5046
+ }
5047
+ var PROFILE_HINT = `profile fields: ${Object.keys(PROFILE_FIELDS).join(", ")}`;
5048
+ async function runEditProfile(name, text2, now = Date.now(), deps = terminalDeps(), surface) {
5049
+ const field = PROFILE_FIELDS[name];
5050
+ if (field === void 0) {
5051
+ return err(
5052
+ "edit",
5053
+ "INVALID_INPUT",
5054
+ `'${name}' is not a profile field this edits`,
5055
+ PROFILE_HINT
5056
+ );
5057
+ }
5058
+ if (text2 === void 0 || text2.trim() === "") {
5059
+ return err(
5060
+ "edit",
5061
+ "INVALID_INPUT",
5062
+ `the new ${name} is required`,
5063
+ `lnrelay edit ${name} "<text>"`
5064
+ );
5065
+ }
5066
+ if (text2.length > field.maxLength) {
5067
+ return err(
5068
+ "edit",
5069
+ "INVALID_INPUT",
5070
+ `the ${name} is ${text2.length} characters; LinkedIn allows ${field.maxLength}`
5071
+ );
5072
+ }
5073
+ const unapprovable = refuseUnapprovable("edit", "editing", deps);
5074
+ if (unapprovable !== null) return unapprovable;
5075
+ const ctx = prepare("edit", now, "voyager");
5076
+ if ("ok" in ctx) return ctx;
5077
+ if (ctx.transport.kind !== "voyager") {
5078
+ return err("edit", "NOT_IMPLEMENTED", "profile edits go over the browser session only");
5079
+ }
5080
+ const profile = surface ?? liveProfile(ctx.transport.session);
5081
+ const me = await profile.vanity();
5082
+ if (!me.ok) return err("edit", me.code, me.message, me.hint);
5083
+ const form = await profile.open(field, me.vanity);
5084
+ if (!form.ok) return err("edit", form.code, form.message, form.hint);
5085
+ const was = currentValue(form, field) ?? "";
5086
+ if (was === text2) {
5087
+ return err("edit", "INVALID_INPUT", `your ${name} already reads exactly that; nothing to save`);
5088
+ }
5089
+ const built = saveBody(form, field, text2);
5090
+ if (!built.ok) return err("edit", built.code, built.message, built.hint);
5091
+ const plan = {
5092
+ action: `change your ${name}`,
5093
+ payload: { field: name, was, text: text2 },
5094
+ summary: [
5095
+ authorLine(ctx.transport),
5096
+ `field ${name}`,
5097
+ `was "${was}"`,
5098
+ `new "${text2}"`
5099
+ ],
5100
+ reversibility: "editable again, but the old text is kept only in this preview and the audit log (~/.lnrelay/writes.jsonl). Every other profile field is sent back as LinkedIn holds it.",
5101
+ transport: "voyager"
5102
+ };
5103
+ const gated = await gate("edit", plan, ctx, deps);
5104
+ if ("ok" in gated) return gated;
5105
+ const sent = await profile.send(form, built.body);
5106
+ if (!sent.ok) return err("edit", sent.code, sent.message, sent.hint);
5107
+ const after = await profile.open(field, me.vanity);
5108
+ const reads = after.ok ? currentValue(after, field) : void 0;
5109
+ if (reads !== text2) {
5110
+ return err(
5111
+ "edit",
5112
+ "SCHEMA_DRIFT",
5113
+ `LinkedIn accepted the save, but your ${name} does not read back as the new text`,
5114
+ after.ok ? `It reads: "${reads ?? ""}"` : `The read-back failed: ${after.message}`
5115
+ );
5116
+ }
5117
+ return ok("edit", { field: name, verified: true });
5118
+ }
4637
5119
  function activityIdOf(urn) {
4638
5120
  return /^urn:li:(?:activity|ugcPost|share):(\d+)$/.exec(urn)?.[1] ?? null;
4639
5121
  }
@@ -4727,6 +5209,9 @@ async function runEdit(commentUrn, text2, now = Date.now(), deps = terminalDeps(
4727
5209
  );
4728
5210
  }
4729
5211
  const ref = parseCommentUrn(commentUrn);
5212
+ if (ref === null && !commentUrn.startsWith("urn:")) {
5213
+ return runEditProfile(commentUrn, text2, now, deps);
5214
+ }
4730
5215
  if (ref === null) {
4731
5216
  if (/^urn:li:(share|ugcPost):\d+$/.test(commentUrn)) {
4732
5217
  return runEditPost(commentUrn, text2, now, deps);
@@ -4846,6 +5331,368 @@ async function runReply(commentUrn, text2, now = Date.now(), deps = terminalDeps
4846
5331
  return result.ok ? ok("reply", { repliedTo: commentUrn }) : err("reply", result.code, result.message, result.hint);
4847
5332
  }
4848
5333
 
5334
+ // src/commands/role.ts
5335
+ function liveRoles(session, quiet = false) {
5336
+ const client = createLiveClient(session, void 0, quiet);
5337
+ return {
5338
+ vanity: async () => {
5339
+ const me = await createEngine(session, void 0, quiet).whoami();
5340
+ if (!me.ok) return me;
5341
+ const id = me.value?.publicIdentifier;
5342
+ return typeof id === "string" && id !== "" ? { ok: true, vanity: id } : { ok: false, code: "SCHEMA_DRIFT", message: "whoami returned no public profile id" };
5343
+ },
5344
+ list: (vanity) => fetchPositions(vanity, client),
5345
+ open: (payload, edit2) => openPositionForm(payload, client, edit2),
5346
+ save: (form, model) => sendPositionSave(form, model, client),
5347
+ remove: (form) => sendPositionDelete(form, client)
5348
+ };
5349
+ }
5350
+ var SUBCOMMANDS = "add, edit <position-id>, remove <position-id>";
5351
+ function yearMonth(flag, v) {
5352
+ const m = /^(\d{4})-(\d{2})$/.exec(v);
5353
+ const month = Number(m?.[2]);
5354
+ if (m === null || month < 1 || month > 12) {
5355
+ return err(
5356
+ "role",
5357
+ "INVALID_INPUT",
5358
+ `--${flag} '${v}' is not a month`,
5359
+ "use YYYY-MM, e.g. 2021-06"
5360
+ );
5361
+ }
5362
+ return { year: Number(m[1]), month };
5363
+ }
5364
+ function changesFrom(req) {
5365
+ const c = {};
5366
+ if (req.title !== void 0) c.title = req.title;
5367
+ if (req.company !== void 0) c.company = req.company;
5368
+ if (req.description !== void 0) c.description = req.description;
5369
+ if (req.location !== void 0) c.location = req.location;
5370
+ if (req.notify === true) c.notify = true;
5371
+ if (req.start !== void 0) {
5372
+ const d = yearMonth("start", req.start);
5373
+ if ("ok" in d) return d;
5374
+ c.start = d;
5375
+ }
5376
+ if (req.current === true && req.end !== void 0) {
5377
+ return err("role", "INVALID_INPUT", "--current and --end contradict each other");
5378
+ }
5379
+ if (req.current === true) c.end = "present";
5380
+ else if (req.end !== void 0) {
5381
+ const d = yearMonth("end", req.end);
5382
+ if ("ok" in d) return d;
5383
+ c.end = d;
5384
+ }
5385
+ return c;
5386
+ }
5387
+ var span = (s) => `${s.start ?? "?"} \u2013 ${s.current ? "present" : s.end ?? "?"}`;
5388
+ var q = (v) => `"${v.length > 160 ? `${v.slice(0, 160)}\u2026` : v.replace(/\n/g, " ")}"`;
5389
+ function roleLines(s) {
5390
+ return [
5391
+ `title ${q(s.title)}`,
5392
+ `company ${q(s.company)}`,
5393
+ `dates ${span(s)}`,
5394
+ ...s.location === "" ? [] : [`location ${q(s.location)}`],
5395
+ ...s.description === "" ? [] : [`about ${q(s.description)}`]
5396
+ ];
5397
+ }
5398
+ function diffLines(a, b) {
5399
+ const out = [];
5400
+ const row = (label, x, y) => {
5401
+ if (x !== y) out.push(`${label.padEnd(8)} ${q(x)} \u2192 ${q(y)}`);
5402
+ };
5403
+ row("title", a.title, b.title);
5404
+ row("company", a.company, b.company);
5405
+ row("dates", span(a), span(b));
5406
+ row("location", a.location, b.location);
5407
+ row("about", a.description, b.description);
5408
+ return out;
5409
+ }
5410
+ var SAFETY = (notify) => [
5411
+ "headline unchanged (LinkedIn would otherwise rewrite it from this role)",
5412
+ `notify ${notify ? "ON \u2014 your network may be told" : "off"}`
5413
+ ];
5414
+ async function runRole(sub, target, req, now = Date.now(), deps = terminalDeps(), surface) {
5415
+ if (sub !== "add" && sub !== "edit" && sub !== "remove") {
5416
+ return err(
5417
+ "role",
5418
+ "INVALID_INPUT",
5419
+ `unknown role subcommand '${sub ?? ""}'`,
5420
+ `lnrelay role ${SUBCOMMANDS}`
5421
+ );
5422
+ }
5423
+ if (sub === "add") {
5424
+ const missing = ["title", "company", "start"].filter(
5425
+ (f) => req[f] === void 0 || req[f] === ""
5426
+ );
5427
+ if (missing.length > 0) {
5428
+ return err(
5429
+ "role",
5430
+ "INVALID_INPUT",
5431
+ `a new role needs ${missing.map((f) => `--${f}`).join(", ")}`
5432
+ );
5433
+ }
5434
+ } else if (target === void 0 || !/^\d+$/.test(target)) {
5435
+ return err(
5436
+ "role",
5437
+ "INVALID_INPUT",
5438
+ `role ${sub} needs a position id`,
5439
+ "list them with `lnrelay experience`"
5440
+ );
5441
+ }
5442
+ const changes = changesFrom(req);
5443
+ if ("ok" in changes) return changes;
5444
+ if (sub === "edit" && Object.keys(changes).filter((k) => k !== "notify").length === 0) {
5445
+ return err(
5446
+ "role",
5447
+ "INVALID_INPUT",
5448
+ "nothing to change",
5449
+ "pass --title, --company, --start, --end, --current, --location or --description"
5450
+ );
5451
+ }
5452
+ const unapprovable = refuseUnapprovable("role", "changing a role", deps);
5453
+ if (unapprovable !== null) return unapprovable;
5454
+ const ctx = prepare("role", now, "voyager");
5455
+ if ("ok" in ctx) return ctx;
5456
+ if (ctx.transport.kind !== "voyager") {
5457
+ return err("role", "NOT_IMPLEMENTED", "role changes go over the browser session only");
5458
+ }
5459
+ const roles = surface ?? liveRoles(ctx.transport.session);
5460
+ const me = await roles.vanity();
5461
+ if (!me.ok) return err("role", me.code, me.message, me.hint);
5462
+ const listed = await roles.list(me.vanity);
5463
+ if (!listed.ok) return err("role", listed.code, listed.message, listed.hint);
5464
+ if (sub === "add") return addRole(changes, me.vanity, listed.positions, roles, ctx, deps);
5465
+ const position = listed.positions.find((p) => p.positionId === target);
5466
+ if (position === void 0) {
5467
+ return err(
5468
+ "role",
5469
+ "NOT_FOUND",
5470
+ `no role ${target} on your profile`,
5471
+ `your roles: ${listed.positions.map((p) => `${p.positionId} (${p.title})`).join(", ") || "none"}`
5472
+ );
5473
+ }
5474
+ const form = await roles.open({ ...position.payload, vanityName: me.vanity }, true);
5475
+ if (!form.ok) return err("role", form.code, form.message, form.hint);
5476
+ return sub === "edit" ? editRole(position, form, changes, me.vanity, roles, ctx, deps) : removeRole(position, form, me.vanity, roles, ctx, deps);
5477
+ }
5478
+ async function addRole(changes, vanity, before, roles, ctx, deps) {
5479
+ const form = await roles.open({ vanityName: vanity }, false);
5480
+ if (!form.ok) return err("role", form.code, form.message, form.hint);
5481
+ const applied = applyChanges(form, changes);
5482
+ if (!applied.ok) return err("role", applied.code, applied.message, applied.hint);
5483
+ const role2 = roleSummary(applied.model);
5484
+ const plan = {
5485
+ action: "add a role to your profile",
5486
+ payload: { changes },
5487
+ summary: [authorLine(ctx.transport), ...roleLines(role2), ...SAFETY(changes.notify === true)],
5488
+ reversibility: "removable with `lnrelay role remove <position-id>`",
5489
+ transport: "voyager"
5490
+ };
5491
+ const gated = await gate("role", plan, ctx, deps);
5492
+ if ("ok" in gated) return gated;
5493
+ const saved = await roles.save(form, applied.model);
5494
+ if (!saved.ok) return err("role", saved.code, saved.message, saved.hint);
5495
+ const after = await roles.list(vanity);
5496
+ const known = new Set(before.map((p) => p.positionId));
5497
+ const added = after.ok ? after.positions.find((p) => !known.has(p.positionId) && p.title === role2.title) : void 0;
5498
+ if (added === void 0) {
5499
+ return err(
5500
+ "role",
5501
+ "SCHEMA_DRIFT",
5502
+ "LinkedIn accepted the role, but it does not appear on your profile"
5503
+ );
5504
+ }
5505
+ return ok("role", { added: added.positionId, verified: true });
5506
+ }
5507
+ async function editRole(position, form, changes, vanity, roles, ctx, deps) {
5508
+ const applied = applyChanges(form, changes);
5509
+ if (!applied.ok) return err("role", applied.code, applied.message, applied.hint);
5510
+ const was = roleSummary(form.model);
5511
+ const will = roleSummary(applied.model);
5512
+ const diff = diffLines(was, will);
5513
+ if (diff.length === 0)
5514
+ return err("role", "INVALID_INPUT", "the role already reads exactly that; nothing to save");
5515
+ const plan = {
5516
+ action: "edit a role on your profile",
5517
+ payload: { positionId: position.positionId, was, changes },
5518
+ summary: [
5519
+ authorLine(ctx.transport),
5520
+ `role ${position.positionId}`,
5521
+ ...diff,
5522
+ ...SAFETY(changes.notify === true)
5523
+ ],
5524
+ reversibility: "editable again; the old values are kept only in this preview and the audit log",
5525
+ transport: "voyager"
5526
+ };
5527
+ const gated = await gate("role", plan, ctx, deps);
5528
+ if ("ok" in gated) return gated;
5529
+ const saved = await roles.save(form, applied.model);
5530
+ if (!saved.ok) return err("role", saved.code, saved.message, saved.hint);
5531
+ const reread = await roles.open({ ...position.payload, vanityName: vanity }, true);
5532
+ const now = reread.ok ? roleSummary(reread.model) : null;
5533
+ if (now === null || diffLines(will, now).length > 0) {
5534
+ return err(
5535
+ "role",
5536
+ "SCHEMA_DRIFT",
5537
+ "LinkedIn accepted the edit, but the role does not read back as edited"
5538
+ );
5539
+ }
5540
+ return ok("role", { edited: position.positionId, verified: true });
5541
+ }
5542
+ async function removeRole(position, form, vanity, roles, ctx, deps) {
5543
+ const role2 = roleSummary(form.model);
5544
+ const plan = {
5545
+ action: "remove a role from your profile",
5546
+ payload: { positionId: position.positionId, role: role2 },
5547
+ summary: [authorLine(ctx.transport), `role ${position.positionId}`, ...roleLines(role2)],
5548
+ reversibility: "NONE. LinkedIn deletes it; re-adding makes a new role.",
5549
+ transport: "voyager"
5550
+ };
5551
+ const gated = await gate("role", plan, ctx, deps);
5552
+ if ("ok" in gated) return gated;
5553
+ const removed = await roles.remove(form);
5554
+ if (!removed.ok) return err("role", removed.code, removed.message, removed.hint);
5555
+ const after = await roles.list(vanity);
5556
+ if (!after.ok || after.positions.some((p) => p.positionId === position.positionId)) {
5557
+ return err(
5558
+ "role",
5559
+ "SCHEMA_DRIFT",
5560
+ "LinkedIn accepted the removal, but the role is still listed"
5561
+ );
5562
+ }
5563
+ return ok("role", { removed: position.positionId, verified: true });
5564
+ }
5565
+ async function runExperience(quiet = false) {
5566
+ const session = loadSession();
5567
+ if (session.state !== "ok")
5568
+ return err("experience", "AUTH_FAILED", "no LinkedIn session \u2014 run `lnrelay login`");
5569
+ const roles = liveRoles(session.session, quiet);
5570
+ const me = await roles.vanity();
5571
+ if (!me.ok) return err("experience", me.code, me.message, me.hint);
5572
+ const listed = await roles.list(me.vanity);
5573
+ if (!listed.ok) return err("experience", listed.code, listed.message, listed.hint);
5574
+ return ok("experience", {
5575
+ items: listed.positions.map((p) => ({ positionId: p.positionId, title: p.title })),
5576
+ meta: { state: "complete", returnedCount: listed.positions.length }
5577
+ });
5578
+ }
5579
+
5580
+ // src/commands/sync.ts
5581
+ var CONNECTIONS_MIN_INTERVAL_MS = 7 * 864e5;
5582
+ function searchText(item) {
5583
+ return [item.name, item.headline, item.location, item.text, item.author, item.company, item.title].filter((v) => typeof v === "string").join(" ");
5584
+ }
5585
+ function rowsFrom(items) {
5586
+ return items.filter((i) => typeof i.urn === "string" && i.urn !== "").map((i) => ({ urn: i.urn, body: i, text: searchText(i) }));
5587
+ }
5588
+ function diffSnapshot(before, seen, claimed) {
5589
+ const complete = claimed === void 0 || seen.size >= claimed;
5590
+ if (!complete) return { removed: [], complete: false };
5591
+ return { removed: [...before].filter((urn) => !seen.has(urn)), complete: true };
5592
+ }
5593
+ async function syncMyPosts(engine, db, limit, now) {
5594
+ const me = await engine.whoami();
5595
+ if (!me.ok) return err("sync", me.code, me.message, me.hint);
5596
+ const profileUrn = typeof me.value?.entityUrn === "string" ? me.value.entityUrn : void 0;
5597
+ if (profileUrn === void 0) {
5598
+ return err("sync", "SCHEMA_DRIFT", "could not determine the owner profile urn");
5599
+ }
5600
+ const result = await engine.myPosts(profileUrn, limit);
5601
+ if (!result.ok) return err("sync", result.code, result.message, result.hint);
5602
+ const rows = rowsFrom(shapeAll(result.value.parsed.items, result.value.index));
5603
+ const stored = upsert(db, "my-posts", rows, now);
5604
+ setCheckpoint(db, {
5605
+ source: "my-posts",
5606
+ lastSuccessfulAt: now,
5607
+ newestCreatedAt: null,
5608
+ headIds: rows.slice(0, 5).map((r) => r.urn),
5609
+ state: "ok"
5610
+ });
5611
+ return ok("sync", {
5612
+ source: "my-posts",
5613
+ ...stored,
5614
+ meta: result.value.parsed.meta,
5615
+ note: rows.length === 0 ? "LinkedIn returned no posts for this account. That is a genuine empty, not a failed fetch \u2014 meta.state says which." : void 0
5616
+ });
5617
+ }
5618
+ function tooSoon(db, now) {
5619
+ const cp = getCheckpoint(db, "connections");
5620
+ const age = cp === void 0 ? Number.POSITIVE_INFINITY : now - cp.lastSuccessfulAt;
5621
+ if (age >= CONNECTIONS_MIN_INTERVAL_MS) return void 0;
5622
+ const days = Math.ceil((CONNECTIONS_MIN_INTERVAL_MS - age) / 864e5);
5623
+ return err(
5624
+ "sync",
5625
+ "BUDGET_EXHAUSTED",
5626
+ `connections were synced ${Math.floor(age / 864e5)} days ago`,
5627
+ `This is the most expensive read in the tool and connections change slowly. Wait ${days} more day(s), or pass --force.`
5628
+ );
5629
+ }
5630
+ async function syncConnections(engine, db, limit, force, now) {
5631
+ const before = urnsFor(db, "connections");
5632
+ if (!force && before.size > 0) {
5633
+ const blocked = tooSoon(db, now);
5634
+ if (blocked !== void 0) return blocked;
5635
+ }
5636
+ const result = await engine.connections(limit);
5637
+ if (!result.ok) return err("sync", result.code, result.message, result.hint);
5638
+ const rows = rowsFrom(shapeAll(result.value.parsed.items, result.value.index));
5639
+ const stored = upsert(db, "connections", rows, now);
5640
+ const claimed = result.value.parsed.meta.claimedCount;
5641
+ const seen = new Set(rows.map((r) => r.urn));
5642
+ const { removed, complete } = diffSnapshot(before, seen, claimed);
5643
+ if (removed.length > 0) removeUrns(db, "connections", removed);
5644
+ setCheckpoint(db, {
5645
+ source: "connections",
5646
+ lastSuccessfulAt: now,
5647
+ newestCreatedAt: null,
5648
+ headIds: [],
5649
+ // Honest: a snapshot, never a watermark.
5650
+ state: complete ? "ok" : "snapshot-partial"
5651
+ });
5652
+ return ok("sync", {
5653
+ source: "connections",
5654
+ added: stored.added,
5655
+ updated: stored.updated,
5656
+ removed: removed.length,
5657
+ claimed,
5658
+ complete,
5659
+ meta: result.value.parsed.meta,
5660
+ note: complete ? void 0 : `Only ${rows.length} of ${claimed} connections were retrieved, so removals could not be determined and none were applied. Raise --limit to complete the snapshot.`
5661
+ });
5662
+ }
5663
+ async function runSync(source, limit, force, now = Date.now()) {
5664
+ if (source !== "my-posts" && source !== "connections") {
5665
+ return err(
5666
+ "sync",
5667
+ "INVALID_INPUT",
5668
+ `unknown sync source '${source ?? ""}'`,
5669
+ "lnrelay sync my-posts | lnrelay sync connections"
5670
+ );
5671
+ }
5672
+ const session = loadSession();
5673
+ if (session.state === "corrupt") {
5674
+ return err("sync", "CACHE_CORRUPT", "the stored session was unreadable", LAUNCH_HINT);
5675
+ }
5676
+ if (session.state === "missing") {
5677
+ return err("sync", "AUTH_FAILED", "no session \u2014 run `lnrelay login` first", LAUNCH_HINT);
5678
+ }
5679
+ const engine = createEngine(session.session);
5680
+ try {
5681
+ const db = openDb(now);
5682
+ return source === "my-posts" ? await syncMyPosts(engine, db, limit, now) : await syncConnections(engine, db, limit, force, now);
5683
+ } catch (e) {
5684
+ if (e instanceof CacheCorrupt) {
5685
+ return err(
5686
+ "sync",
5687
+ "CACHE_CORRUPT",
5688
+ e.message,
5689
+ `Moved to ${e.quarantinedTo}. A corrupt cache is NOT treated as empty \u2014 that would make this sync re-enumerate everything. Inspect it, then re-run.`
5690
+ );
5691
+ }
5692
+ throw e;
5693
+ }
5694
+ }
5695
+
4849
5696
  // src/entry.ts
4850
5697
  import { realpathSync } from "fs";
4851
5698
  import { basename as basename2 } from "path";
@@ -4977,6 +5824,8 @@ async function dispatch(argv, now) {
4977
5824
  num(args, "limit") ?? 25,
4978
5825
  output(args)
4979
5826
  );
5827
+ case "experience":
5828
+ return runExperience(bool(args, "quiet"));
4980
5829
  case "scheduled":
4981
5830
  return runScheduled(bool(args, "quiet"));
4982
5831
  case "sync":
@@ -5044,6 +5893,56 @@ async function write(command, args, now) {
5044
5893
  if (wasApproved()) auditOutcome(command, mode.mode, envelope);
5045
5894
  return envelope;
5046
5895
  }
5896
+ function edit(args, now, deps) {
5897
+ const [target, inline] = args.positionals;
5898
+ if (args.flags.file === true) return err("edit", "INVALID_INPUT", "--file needs a path");
5899
+ const file = str(args, "file");
5900
+ if (file === void 0) return runEdit(target, inline, now, deps);
5901
+ if (inline !== void 0) {
5902
+ return err("edit", "INVALID_INPUT", "pass the new text inline or with --file, not both");
5903
+ }
5904
+ let text2;
5905
+ try {
5906
+ text2 = readFileSync3(file, "utf-8").replace(/\n$/, "");
5907
+ } catch {
5908
+ return err("edit", "INVALID_INPUT", `cannot read ${file}`);
5909
+ }
5910
+ return runEdit(target, text2, now, deps);
5911
+ }
5912
+ function role(args, now, deps) {
5913
+ const [sub, target] = args.positionals;
5914
+ const valued = [
5915
+ "title",
5916
+ "company",
5917
+ "start",
5918
+ "end",
5919
+ "location",
5920
+ "description",
5921
+ "description-file"
5922
+ ];
5923
+ for (const flag of valued) {
5924
+ if (args.flags[flag] === true) return err("role", "INVALID_INPUT", `--${flag} needs a value`);
5925
+ }
5926
+ const req = {};
5927
+ for (const flag of ["title", "company", "start", "end", "location", "description"]) {
5928
+ const v = str(args, flag);
5929
+ if (v !== void 0) req[flag] = v;
5930
+ }
5931
+ const file = str(args, "description-file");
5932
+ if (file !== void 0) {
5933
+ if (req.description !== void 0) {
5934
+ return err("role", "INVALID_INPUT", "pass --description or --description-file, not both");
5935
+ }
5936
+ try {
5937
+ req.description = readFileSync3(file, "utf-8").replace(/\n$/, "");
5938
+ } catch {
5939
+ return err("role", "INVALID_INPUT", `cannot read ${file}`);
5940
+ }
5941
+ }
5942
+ if (bool(args, "current")) req.current = true;
5943
+ if (bool(args, "notify")) req.notify = true;
5944
+ return runRole(sub, target, req, now, deps);
5945
+ }
5047
5946
  function runWrite(command, args, now, deps) {
5048
5947
  const [first, second] = args.positionals;
5049
5948
  switch (command) {
@@ -5052,13 +5951,15 @@ function runWrite(command, args, now, deps) {
5052
5951
  case "comment":
5053
5952
  return runComment(first, second, now, deps);
5054
5953
  case "edit":
5055
- return runEdit(first, second, now, deps);
5954
+ return edit(args, now, deps);
5056
5955
  case "reply":
5057
5956
  return runReply(first, second, now, deps);
5058
5957
  case "react":
5059
5958
  return runReact(first, str(args, "type") ?? "LIKE", now, deps, bool(args, "remove"));
5060
5959
  case "delete":
5061
5960
  return runDelete(first, now, deps, bool(args, "quiet"));
5961
+ case "role":
5962
+ return role(args, now, deps);
5062
5963
  default:
5063
5964
  return err(command, "NOT_IMPLEMENTED", `'${command}' has no write runner`);
5064
5965
  }