@lobu/runtime-server 22.0.0 → 24.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (303) hide show
  1. package/dist/catalogs/connectors.json +1448 -212
  2. package/dist/catalogs/skills.json +1 -1
  3. package/dist/component.json +1 -1
  4. package/dist/connectors/README.md +15 -2
  5. package/dist/connectors/google_gmail.ts +1 -0
  6. package/dist/connectors/jira-helpers.ts +313 -0
  7. package/dist/connectors/jira.ts +29 -221
  8. package/dist/connectors/linkedin-browser-script.ts +13 -0
  9. package/dist/connectors/linkedin-draft-page.js +104 -0
  10. package/dist/connectors/linkedin-drafts.ts +73 -0
  11. package/dist/connectors/linkedin-identity.ts +32 -0
  12. package/dist/connectors/linkedin-inbox-adapter.js +1182 -0
  13. package/dist/connectors/linkedin-inbox.ts +156 -0
  14. package/dist/connectors/linkedin-like.ts +114 -0
  15. package/dist/connectors/linkedin-takeout.ts +577 -0
  16. package/dist/connectors/linkedin.ts +4017 -0
  17. package/dist/connectors/reddit.ts +92 -20
  18. package/dist/connectors/slack.ts +1 -0
  19. package/dist/connectors/takeout-utils.ts +240 -0
  20. package/dist/connectors/tiktok-inbox-page.js +9 -9
  21. package/dist/connectors/tiktok-web-page.js +21 -15
  22. package/dist/connectors/tiktok_web.ts +63 -30
  23. package/dist/connectors/whatsapp-web-adapter.js +104 -574
  24. package/dist/connectors/whatsapp-web-helpers.ts +30 -444
  25. package/dist/connectors/whatsapp-web-identity.ts +20 -6
  26. package/dist/connectors/whatsapp_web.ts +46 -646
  27. package/dist/connectors/x-dm-adapter.js +556 -0
  28. package/dist/connectors/x-identity.ts +33 -2
  29. package/dist/connectors/x.ts +266 -120
  30. package/dist/db/migrations/20261017120000_drop_feeds_kind_virtual.sql +26 -0
  31. package/dist/db/migrations/20261017130000_drop_retired_dead_code_columns.sql +46 -0
  32. package/dist/db/migrations/20261019120000_retire_identities_of_deleted_entities.sql +21 -0
  33. package/dist/db/migrations/20261020120000_entities_live_metadata_domain.sql +66 -0
  34. package/dist/db/migrations/20261020130000_agents_starters.sql +14 -0
  35. package/dist/db/migrations/20261020140000_view_attachments_by_page.sql +71 -0
  36. package/dist/dependencies.bun.lock +78 -75
  37. package/dist/guest.bundle.js +650 -448
  38. package/dist/owletto/dist/assets/_-CC8cTmRg.js +3 -0
  39. package/dist/owletto/dist/assets/_-ksFp4zVf.js +2 -0
  40. package/dist/owletto/dist/assets/_agentId-DWUFSrVp.js +2 -0
  41. package/dist/owletto/dist/assets/_agentId-MENLoohA.js +2 -0
  42. package/dist/owletto/dist/assets/_automationId-BnHqdXOC.js +2 -0
  43. package/dist/owletto/dist/assets/_connectorKey._connectionId-CefXIqy2.js +2 -0
  44. package/dist/owletto/dist/assets/_connectorKey.index-C1QPGf9E.js +2 -0
  45. package/dist/owletto/dist/assets/_conversationId-DinuPCUp.js +2 -0
  46. package/dist/owletto/dist/assets/{_deploymentId-BQfYN1U2.js → _deploymentId-BeyzVjRm.js} +2 -2
  47. package/dist/owletto/dist/assets/_eventId-3L_qeL_l.js +2 -0
  48. package/dist/owletto/dist/assets/_name-Dgedji78.js +2 -0
  49. package/dist/owletto/dist/assets/_owner-DbrKma4e.js +3 -0
  50. package/dist/owletto/dist/assets/_shape-DtVfRFz_.js +2 -0
  51. package/dist/owletto/dist/assets/_skillKey-CqLHzm7L.js +2 -0
  52. package/dist/owletto/dist/assets/_slug-ndDr_CUg.js +2 -0
  53. package/dist/owletto/dist/assets/_viewKey-3CH5w8mr.js +2 -0
  54. package/dist/owletto/dist/assets/_viewKey-DHQY9A8u.js +2 -0
  55. package/dist/owletto/dist/assets/{accept-invitation-D3OgJG4i.js → accept-invitation-CRKbM2Xy.js} +2 -2
  56. package/dist/owletto/dist/assets/activity-route-view-CFLNukhD.js +2 -0
  57. package/dist/owletto/dist/assets/{agent-card-controls-DzRs4Ix9.js → agent-card-controls-Be1Okb2C.js} +2 -2
  58. package/dist/owletto/dist/assets/{agent-client-setup-list-B2SvH7xD.js → agent-client-setup-list-BA8dU_C6.js} +2 -2
  59. package/dist/owletto/dist/assets/agent-connect-pages-CAV-yXus.js +2 -0
  60. package/dist/owletto/dist/assets/agent-editor-form-Bi6WvYX-.js +2 -0
  61. package/dist/owletto/dist/assets/{agent-guardrails-route-BaV1VpDh.js → agent-guardrails-route-DMOjG1D4.js} +2 -2
  62. package/dist/owletto/dist/assets/{agent-loading-shells-CtZJM2Gc.js → agent-loading-shells-De_2d8Lr.js} +2 -2
  63. package/dist/owletto/dist/assets/{agent-permissions-matrix-Ds48KFK9.js → agent-permissions-matrix-gZWl6mAe.js} +2 -2
  64. package/dist/owletto/dist/assets/{agent-skill-context-DPk5r08w.js → agent-skill-context-JLaTamGR.js} +2 -2
  65. package/dist/owletto/dist/assets/{agent-skills-route-DYpB5H1J.js → agent-skills-route-DcK41PWj.js} +2 -2
  66. package/dist/owletto/dist/assets/agent-subpage-shell-BBJoyTuC.js +2 -0
  67. package/dist/owletto/dist/assets/agent-thread-Buz3naVF.js +6 -0
  68. package/dist/owletto/dist/assets/agents-C-ReckCa.js +2 -0
  69. package/dist/owletto/dist/assets/agents-workbench-CqaKGggb.js +2 -0
  70. package/dist/owletto/dist/assets/app._appId-Cl1fTuIt.js +2 -0
  71. package/dist/owletto/dist/assets/automation-detail-content-BMLL4lxO.js +2 -0
  72. package/dist/owletto/dist/assets/automations-C-ReckCa.js +2 -0
  73. package/dist/owletto/dist/assets/callback-DTKKsfkz.js +2 -0
  74. package/dist/owletto/dist/assets/{card-DIF8SF9b.js → card-yU0TmNRH.js} +2 -2
  75. package/dist/owletto/dist/assets/{claim-DELEa-gH.js → claim-DJfTvlT2.js} +2 -2
  76. package/dist/owletto/dist/assets/client-rows--FrZfJol.js +2 -0
  77. package/dist/owletto/dist/assets/{clients-CpG676mg.js → clients-L4K1UT8c.js} +2 -2
  78. package/dist/owletto/dist/assets/{code-editor-V27Z4o3P.js → code-editor-U54Gwjit.js} +2 -2
  79. package/dist/owletto/dist/assets/connect-4zqtnDHb.js +2 -0
  80. package/dist/owletto/dist/assets/connect._clientId-Dj0SqgbE.js +2 -0
  81. package/dist/owletto/dist/assets/connected._clientId-sgtocSvf.js +2 -0
  82. package/dist/owletto/dist/assets/connected._clientId.activity-DTpSW1Xy.js +2 -0
  83. package/dist/owletto/dist/assets/connected._clientId.index-h9X5H1x8.js +2 -0
  84. package/dist/owletto/dist/assets/{connection-DySpRE9x.js → connection-ByvKkyFm.js} +2 -2
  85. package/dist/owletto/dist/assets/{connection-feed-detail-C_D68j6d.js → connection-feed-detail-DWM9lTao.js} +2 -2
  86. package/dist/owletto/dist/assets/connections-browser-CEwYrYqt.js +2 -0
  87. package/dist/owletto/dist/assets/{connector-provenance-CNXtzYg5.js → connector-provenance-BocTm__v.js} +2 -2
  88. package/dist/owletto/dist/assets/connector-scope-lists-OYDOydtz.js +2 -0
  89. package/dist/owletto/dist/assets/connectors-CyZpcE5f.js +2 -0
  90. package/dist/owletto/dist/assets/{consent-BVzxrAO9.js → consent-DdfINrVp.js} +2 -2
  91. package/dist/owletto/dist/assets/{conversations-table-DfZGICl7.js → conversations-table-BSznfdYt.js} +2 -2
  92. package/dist/owletto/dist/assets/{core.esm-DiTpULFl.js → core.esm-Dr7tcIB-.js} +2 -2
  93. package/dist/owletto/dist/assets/create-CBGwASon.js +2 -0
  94. package/dist/owletto/dist/assets/create-Cf5hp6Z8.js +2 -0
  95. package/dist/owletto/dist/assets/create-CwThQtd3.js +2 -0
  96. package/dist/owletto/dist/assets/create-automation-form-9T5WnoUs.js +3 -0
  97. package/dist/owletto/dist/assets/create._connectorKey-sNHQHNpg.js +2 -0
  98. package/dist/owletto/dist/assets/{cronstrue-DPXl0qA2.js → cronstrue-BWFEyy_P.js} +2 -2
  99. package/dist/owletto/dist/assets/deployments-DHh9dyzv.js +2 -0
  100. package/dist/owletto/dist/assets/{deployments-body-D6TAWs_6.js → deployments-body-2xKS8gRo.js} +2 -2
  101. package/dist/owletto/dist/assets/{deployments-DCQdFdwG.js → deployments-wG_8QzOF.js} +2 -2
  102. package/dist/owletto/dist/assets/{device-CntqYW65.js → device-6z-xgsoW.js} +2 -2
  103. package/dist/owletto/dist/assets/device-pin-tombstone-Cwq88RMU.js +2 -0
  104. package/dist/owletto/dist/assets/device._deviceId-BDerBfD9.js +2 -0
  105. package/dist/owletto/dist/assets/entity-avatar-Cc1CuI-0.js +2 -0
  106. package/dist/owletto/dist/assets/entity-options-DHdMC1Lx.js +2 -0
  107. package/dist/owletto/dist/assets/entity-page--OkXmlNP.js +2 -0
  108. package/dist/owletto/dist/assets/entity-type-page-89RoK_-P.js +2 -0
  109. package/dist/owletto/dist/assets/event-detail-D4YZRtrA.js +2 -0
  110. package/dist/owletto/dist/assets/events-feed-DsrkV2ix.js +2 -0
  111. package/dist/owletto/dist/assets/filter-editors-B1_QUpg_.js +2 -0
  112. package/dist/owletto/dist/assets/{full-page-spinner-KpV2FS2u.js → full-page-spinner-Cqih-8IW.js} +2 -2
  113. package/dist/owletto/dist/assets/guardrails-B8Rs1be3.js +2 -0
  114. package/dist/owletto/dist/assets/identity-B0nH4yiC.js +2 -0
  115. package/dist/owletto/dist/assets/index-4TSkcsth.js +2 -0
  116. package/dist/owletto/dist/assets/index-BSH07yVD.css +1 -0
  117. package/dist/owletto/dist/assets/index-BgkhXElB.js +2 -0
  118. package/dist/owletto/dist/assets/index-CoW4Bz3w.js +2 -0
  119. package/dist/owletto/dist/assets/index-Codw-Qqi.js +2 -0
  120. package/dist/owletto/dist/assets/{index-BNh2cidi.js → index-DAOyXG1X.js} +2 -2
  121. package/dist/owletto/dist/assets/{index-BEvyBdOU.js → index-DKPwCasf.js} +2 -2
  122. package/dist/owletto/dist/assets/index-DMyXd3bJ.js +2 -0
  123. package/dist/owletto/dist/assets/index-DYCqXaMf.js +7950 -0
  124. package/dist/owletto/dist/assets/index-DYYZLcJ0.js +2 -0
  125. package/dist/owletto/dist/assets/index-DYzWV5_z.js +2 -0
  126. package/dist/owletto/dist/assets/index-Da6CrGEu.js +2 -0
  127. package/dist/owletto/dist/assets/{index-DCdkwg9H.js → index-DfyDUpuI.js} +2 -2
  128. package/dist/owletto/dist/assets/index-DneshLbf.js +2 -0
  129. package/dist/owletto/dist/assets/index-TgRS2v_F.js +2 -0
  130. package/dist/owletto/dist/assets/{index-BJXkc60S.js → index-ZNlrDc_f.js} +2 -2
  131. package/dist/owletto/dist/assets/{json-diff-D_Ym3Uku.js → json-diff-DFvYINBT.js} +3 -3
  132. package/dist/owletto/dist/assets/{list-skeleton-Bl0OS39L.js → list-skeleton-DFsEqLU1.js} +2 -2
  133. package/dist/owletto/dist/assets/login-DO0j-AYr.js +2 -0
  134. package/dist/owletto/dist/assets/{logout-DUccApuZ.js → logout-BmNwoAf7.js} +2 -2
  135. package/dist/owletto/dist/assets/member-scope-gate-B2LrMWBU.js +2 -0
  136. package/dist/owletto/dist/assets/memory-browse-page-Cjpl8EbB.js +103 -0
  137. package/dist/owletto/dist/assets/{model-selector-CB1BDvlW.js → model-selector-TQcA93xm.js} +2 -2
  138. package/dist/owletto/dist/assets/models-D7aED5Sa.js +2 -0
  139. package/dist/owletto/dist/assets/new-BMrFy5Qa.js +2 -0
  140. package/dist/owletto/dist/assets/{new-B5UsLiy6.js → new-ByBhteWA.js} +2 -2
  141. package/dist/owletto/dist/assets/new-DWp3deoW.js +2 -0
  142. package/dist/owletto/dist/assets/{oauth-workspace-access-PGyTnW2K.js → oauth-workspace-access-D_5uESuz.js} +2 -2
  143. package/dist/owletto/dist/assets/{organization-BH8PYlVu.js → organization-DTFoYP4V.js} +2 -2
  144. package/dist/owletto/dist/assets/peek-pane-content-DF5iGC3c.js +2 -0
  145. package/dist/owletto/dist/assets/{permissions-CwN_YP3u.js → permissions-C_auqxfP.js} +2 -2
  146. package/dist/owletto/dist/assets/proposal-review-shell-DsNiavG_.js +2 -0
  147. package/dist/owletto/dist/assets/public-shell-ready-B2NUI89V.js +2 -0
  148. package/dist/owletto/dist/assets/{recent-DqdZE_TI.js → recent-3d99S2IE.js} +2 -2
  149. package/dist/owletto/dist/assets/record-activity-C9KfBkXb.js +2 -0
  150. package/dist/owletto/dist/assets/record-field-peek-BBZcRuGT.js +2 -0
  151. package/dist/owletto/dist/assets/record-session-BizRugWs.js +2 -0
  152. package/dist/owletto/dist/assets/{reset-password-DAvBYkiI.js → reset-password-DqfcSn8M.js} +2 -2
  153. package/dist/owletto/dist/assets/runs-panel-T1ZxTVz6.js +2 -0
  154. package/dist/owletto/dist/assets/runs-table-D_8QlCCN.js +2 -0
  155. package/dist/owletto/dist/assets/schema-value-normalization-CylKX3PK.js +97 -0
  156. package/dist/owletto/dist/assets/settings-B_ClYztB.js +2 -0
  157. package/dist/owletto/dist/assets/settings-DgX1-xo7.js +2 -0
  158. package/dist/owletto/dist/assets/skills-Drw5tcZw.js +2 -0
  159. package/dist/owletto/dist/assets/{source-record-panels-CRIPMWfN.js → source-record-panels-Cg249m1S.js} +2 -2
  160. package/dist/owletto/dist/assets/{use-mention-search-DqEykWl_.js → use-mention-search-BYbFvHbJ.js} +2 -2
  161. package/dist/owletto/dist/assets/view-param-filters-DMSqkN2J.js +2 -0
  162. package/dist/owletto/dist/index.html +2 -2
  163. package/dist/server-main.bundle.mjs +14031 -12680
  164. package/npm-shrinkwrap.json +329 -313
  165. package/package.json +6 -5
  166. package/vendor/connector-sdk/dist/browser-handoff-banner.d.ts +39 -0
  167. package/vendor/connector-sdk/dist/browser-handoff-banner.js +175 -0
  168. package/vendor/connector-sdk/dist/browser-source-read.d.ts +52 -0
  169. package/vendor/connector-sdk/dist/browser-source-read.js +107 -0
  170. package/vendor/connector-sdk/dist/connector-types.d.ts +10 -0
  171. package/vendor/connector-sdk/dist/index.d.ts +3 -0
  172. package/vendor/connector-sdk/dist/index.js +2 -0
  173. package/vendor/connector-sdk/package.json +9 -1
  174. package/vendor/core/dist/agent-policy.js +0 -3
  175. package/vendor/core/dist/agent-tooling.d.ts +1 -1
  176. package/vendor/core/dist/agent-tooling.js +3 -1
  177. package/vendor/core/dist/capabilities.d.ts +1 -1
  178. package/vendor/core/dist/capabilities.js +0 -1
  179. package/vendor/core/dist/connector-query-errors.d.ts +32 -0
  180. package/vendor/core/dist/connector-query-errors.js +41 -1
  181. package/vendor/core/dist/contracts/agent-settings.d.ts +6 -2
  182. package/vendor/core/dist/contracts/agent-settings.js +12 -1
  183. package/vendor/core/dist/contracts/tools/manage-conversations.js +2 -2
  184. package/vendor/core/dist/contracts/tools/manage-feeds.d.ts +14 -0
  185. package/vendor/core/dist/contracts/tools/manage-feeds.js +17 -0
  186. package/vendor/core/dist/contracts/tools/manage-views.d.ts +53 -234
  187. package/vendor/core/dist/contracts/tools/manage-views.js +50 -76
  188. package/vendor/core/dist/contracts/tools/view-attach.d.ts +5 -8
  189. package/vendor/core/dist/contracts/tools/view-attach.js +14 -31
  190. package/vendor/core/dist/contracts/tools/view-definition.d.ts +21 -0
  191. package/vendor/core/dist/contracts/tools/view-definition.js +165 -0
  192. package/vendor/core/dist/contracts/worker/protocol.d.ts +47 -133
  193. package/vendor/core/dist/contracts/worker/protocol.js +33 -62
  194. package/vendor/core/dist/device-pin-tombstones.d.ts +44 -0
  195. package/vendor/core/dist/device-pin-tombstones.js +57 -0
  196. package/vendor/core/dist/index.d.ts +3 -2
  197. package/vendor/core/dist/index.js +3 -1
  198. package/vendor/core/dist/logger.js +10 -25
  199. package/vendor/core/dist/suggestions.d.ts +15 -2
  200. package/vendor/core/dist/suggestions.js +48 -3
  201. package/vendor/core/dist/types.d.ts +26 -0
  202. package/vendor/core/dist/types.js +5 -0
  203. package/vendor/core/dist/utils/diagnostic-scrubber.js +258 -21
  204. package/vendor/core/dist/worker/wire.d.ts +0 -10
  205. package/vendor/core/package.json +16 -10
  206. package/vendor/postgres/cf/src/connection.js +18 -0
  207. package/vendor/postgres/cjs/src/connection.js +18 -0
  208. package/vendor/postgres/src/connection.js +18 -0
  209. package/vendor/views/dist/api.d.ts +71 -17
  210. package/vendor/views/dist/api.js +200 -35
  211. package/vendor/views/dist/bridge.d.ts +3 -0
  212. package/vendor/views/dist/bridge.js +9 -1
  213. package/vendor/views/dist/components.d.ts +170 -0
  214. package/vendor/views/dist/components.js +361 -0
  215. package/vendor/views/dist/index.d.ts +1 -1
  216. package/vendor/views/package.json +11 -1
  217. package/dist/owletto/dist/assets/_-CEPl6gU4.js +0 -3
  218. package/dist/owletto/dist/assets/_-C_zNZben.js +0 -2
  219. package/dist/owletto/dist/assets/_agentId-CBC_SadO.js +0 -2
  220. package/dist/owletto/dist/assets/_agentId-QQW91cHX.js +0 -2
  221. package/dist/owletto/dist/assets/_automationId-YTTNksw6.js +0 -2
  222. package/dist/owletto/dist/assets/_connectorKey._connectionId-fK0h7RAp.js +0 -2
  223. package/dist/owletto/dist/assets/_connectorKey.index-C7TPS598.js +0 -2
  224. package/dist/owletto/dist/assets/_conversationId-CEhxlTIo.js +0 -2
  225. package/dist/owletto/dist/assets/_eventId-Cl8GSdjg.js +0 -2
  226. package/dist/owletto/dist/assets/_name-t3oBJ6Zf.js +0 -2
  227. package/dist/owletto/dist/assets/_owner-cUtGHqSw.js +0 -3
  228. package/dist/owletto/dist/assets/_shape-bo2lMVCu.js +0 -2
  229. package/dist/owletto/dist/assets/_skillKey-Dwm4Q4wI.js +0 -2
  230. package/dist/owletto/dist/assets/_slug-CU1PuHB9.js +0 -2
  231. package/dist/owletto/dist/assets/_viewKey-Bh6E_NxA.js +0 -2
  232. package/dist/owletto/dist/assets/_viewKey-D4jKl-Zf.js +0 -2
  233. package/dist/owletto/dist/assets/activity-route-view-DQglkhXU.js +0 -2
  234. package/dist/owletto/dist/assets/agent-connect-pages-B6uKvT_X.js +0 -2
  235. package/dist/owletto/dist/assets/agent-editor-form-oUnIYHd7.js +0 -2
  236. package/dist/owletto/dist/assets/agent-subpage-shell-B3K_jPYR.js +0 -2
  237. package/dist/owletto/dist/assets/agent-thread-C8UaUTWc.js +0 -6
  238. package/dist/owletto/dist/assets/agents-F4mGI2oF.js +0 -2
  239. package/dist/owletto/dist/assets/agents-workbench-CMyk4PI7.js +0 -2
  240. package/dist/owletto/dist/assets/app._appId-DH1Qutz6.js +0 -2
  241. package/dist/owletto/dist/assets/automation-detail-content-CEDNboId.js +0 -2
  242. package/dist/owletto/dist/assets/automations-F4mGI2oF.js +0 -2
  243. package/dist/owletto/dist/assets/callback-CU-hb8JB.js +0 -2
  244. package/dist/owletto/dist/assets/client-rows-EJSKR6z1.js +0 -2
  245. package/dist/owletto/dist/assets/connect-B2YL6qIK.js +0 -2
  246. package/dist/owletto/dist/assets/connect._clientId-B6LDmDRV.js +0 -2
  247. package/dist/owletto/dist/assets/connected._clientId-D_HaKoI1.js +0 -2
  248. package/dist/owletto/dist/assets/connected._clientId.activity-DQWcUqKM.js +0 -2
  249. package/dist/owletto/dist/assets/connected._clientId.index-BC3R303A.js +0 -2
  250. package/dist/owletto/dist/assets/connections-browser-Cnv2iBbZ.js +0 -2
  251. package/dist/owletto/dist/assets/connector-scope-lists-BKDetNDc.js +0 -2
  252. package/dist/owletto/dist/assets/connectors-BJnk1z_2.js +0 -2
  253. package/dist/owletto/dist/assets/create-CUqO6Kfk.js +0 -2
  254. package/dist/owletto/dist/assets/create-JRFM8mMf.js +0 -2
  255. package/dist/owletto/dist/assets/create-automation-form-_4vUkrls.js +0 -3
  256. package/dist/owletto/dist/assets/create-iHcxV0xd.js +0 -2
  257. package/dist/owletto/dist/assets/create._connectorKey-CCYLEicg.js +0 -2
  258. package/dist/owletto/dist/assets/deployments-ihkhK1zV.js +0 -2
  259. package/dist/owletto/dist/assets/device-pin-tombstone-Bz4JHHMK.js +0 -2
  260. package/dist/owletto/dist/assets/device._deviceId-D4plO3GM.js +0 -2
  261. package/dist/owletto/dist/assets/entity-options-UJs64GdQ.js +0 -2
  262. package/dist/owletto/dist/assets/entity-page-Djz6T50J.js +0 -2
  263. package/dist/owletto/dist/assets/entity-type-page-OznRag6A.js +0 -2
  264. package/dist/owletto/dist/assets/event-detail-04qOUGIP.js +0 -2
  265. package/dist/owletto/dist/assets/events-feed-fucGZSJR.js +0 -2
  266. package/dist/owletto/dist/assets/filter-editors-DCQgGLyR.js +0 -2
  267. package/dist/owletto/dist/assets/guardrails-molekzAF.js +0 -2
  268. package/dist/owletto/dist/assets/identity-BJcaG66g.js +0 -2
  269. package/dist/owletto/dist/assets/index-B04ON9Jv.js +0 -2
  270. package/dist/owletto/dist/assets/index-BLEcy9-T.css +0 -1
  271. package/dist/owletto/dist/assets/index-BOsK-K-2.js +0 -2
  272. package/dist/owletto/dist/assets/index-BOzuAbvi.js +0 -2
  273. package/dist/owletto/dist/assets/index-Bk1x7A67.js +0 -2
  274. package/dist/owletto/dist/assets/index-CFnx5huL.js +0 -2
  275. package/dist/owletto/dist/assets/index-D3s8rhG9.js +0 -2
  276. package/dist/owletto/dist/assets/index-Dbd1jusf.js +0 -2
  277. package/dist/owletto/dist/assets/index-DqZuqC08.js +0 -2
  278. package/dist/owletto/dist/assets/index-Dr-Xg_xO.js +0 -2
  279. package/dist/owletto/dist/assets/index-KPOvMVa-.js +0 -2
  280. package/dist/owletto/dist/assets/index-_oPeVpL_.js +0 -7950
  281. package/dist/owletto/dist/assets/login-QHdxqX-4.js +0 -2
  282. package/dist/owletto/dist/assets/member-scope-gate-CFbrq1by.js +0 -2
  283. package/dist/owletto/dist/assets/memory-browse-page-IrIXuZTF.js +0 -103
  284. package/dist/owletto/dist/assets/models-DnMb3n-Z.js +0 -2
  285. package/dist/owletto/dist/assets/new-BWo8_Pms.js +0 -2
  286. package/dist/owletto/dist/assets/new-DpmDXmFI.js +0 -2
  287. package/dist/owletto/dist/assets/peek-pane-content-B2AFNTzP.js +0 -2
  288. package/dist/owletto/dist/assets/proposal-review-shell-DKKGu4Ww.js +0 -2
  289. package/dist/owletto/dist/assets/public-shell-ready-7KYnww6e.js +0 -2
  290. package/dist/owletto/dist/assets/record-activity-CvgZyCmw.js +0 -2
  291. package/dist/owletto/dist/assets/renderer-BL6VcwQH.js +0 -97
  292. package/dist/owletto/dist/assets/runs-BWtc5rmc.js +0 -2
  293. package/dist/owletto/dist/assets/runs-panel-BO3h5RkS.js +0 -2
  294. package/dist/owletto/dist/assets/runs-table-DxIiqrSk.js +0 -2
  295. package/dist/owletto/dist/assets/settings-4Ev-0iNL.js +0 -2
  296. package/dist/owletto/dist/assets/settings-Crxlwps-.js +0 -2
  297. package/dist/owletto/dist/assets/skills-D0X430X8.js +0 -2
  298. package/dist/owletto/dist/assets/status-dot-C5KDvvm9.js +0 -2
  299. package/dist/owletto/dist/assets/tabs-B4Er9hJj.js +0 -2
  300. package/dist/owletto/dist/assets/view-param-filters-Cylutoy1.js +0 -2
  301. package/vendor/core/dist/contracts/worker/device-chat.d.ts +0 -4
  302. package/vendor/core/dist/contracts/worker/device-chat.js +0 -26
  303. /package/vendor/postgres/{.bun-tag-f39dafdb2305d504 → .bun-tag-2f292c6554a8475e} +0 -0
@@ -0,0 +1,4017 @@
1
+ /**
2
+ * LinkedIn Connector
3
+ *
4
+ * Built-in connector spanning live browser feeds and local export readers:
5
+ *
6
+ * • LIVE feeds (home_feed, company_updates, jobs) — scraped via the paired
7
+ * Owletto Chrome extension's network-intercept / content-script primitives.
8
+ * The extension runs inside the user's real Chrome session — no Playwright,
9
+ * no cookie cache, no `--remote-debugging-port` plumbing. We attach the CDP
10
+ * Network domain in the user's signed-in tab, drive scroll pagination, and
11
+ * parse the Voyager API responses the page emits. Auth is implicit: the user
12
+ * is already signed into linkedin.com in the paired Chrome. If no online
13
+ * Owletto extension is reachable in the connection's org, these syncs fail
14
+ * fast with a clear "no paired Owletto extension" error.
15
+ *
16
+ * • TAKEOUT feeds (connections, messages, invitations, applied_jobs, profile,
17
+ * companies, learning, events, endorsements, media) — read from the user's
18
+ * local LinkedIn Data Export CSV files through an injected reader. The
19
+ * platform does not currently supply that reader; those feeds fail with
20
+ * a missing-capability error until a filesystem-capable caller supplies it.
21
+ *
22
+ * Folding both into ONE connector (key "linkedin") means a single connection
23
+ * dedups all people on the shared `linkedin_slug`/`email` identity: a person met
24
+ * live and a person in the CSV export collapse to the same entity.
25
+ *
26
+ * Write handoff: `prepare_comment` waits for the user to open the exact post,
27
+ * fills that page's comment composer, and stops. The human clicks Post
28
+ * themselves — Lobu never submits the comment.
29
+ *
30
+ * Closed-loop (optional): `verify_staged_comment` re-opens the post and scrapes
31
+ * comments to check whether the human actually posted the draft.
32
+ * Staging ≠ verified posted.
33
+ */
34
+
35
+ import {
36
+ buildInjectHandoffBannerExpression as buildSharedHandoffBannerExpression,
37
+ requireBrowser,
38
+ truncateHandoffReason as truncateSharedHandoffReason,
39
+ type ActionContext,
40
+ type ActionResult,
41
+ type ChromeActionDispatcher,
42
+ type RuntimeConnectorDefinition,
43
+ ConnectorRuntime,
44
+ calculateEngagementScore,
45
+ type EventAttributionRule,
46
+ type EventEnvelope,
47
+ extensionDomScrape,
48
+ extensionNetworkSync,
49
+ IDENTITY,
50
+ type SyncContext,
51
+ type SyncResult,
52
+ } from "@lobu/connector-sdk";
53
+ import {
54
+ LINKEDIN_IDENTITY,
55
+ normalizeLinkedInMemberId,
56
+ normalizeLinkedInSlug,
57
+ } from "./linkedin-identity.js";
58
+ import { setLinkedInLike } from "./linkedin-like.js";
59
+ import {
60
+ readCompanyFollows,
61
+ readConnections,
62
+ readEndorsements,
63
+ readEvents,
64
+ readInvitations,
65
+ readJobs,
66
+ readLearning,
67
+ readMessages,
68
+ readProfile,
69
+ readRichMedia,
70
+ type TakeoutCsvReader,
71
+ } from "./linkedin-takeout.js";
72
+ import {
73
+ batchSize,
74
+ type LocalTakeoutConfig,
75
+ maxEventCursor,
76
+ takeBatch,
77
+ } from "./takeout-utils.js";
78
+ import {
79
+ observeLinkedInInbox,
80
+ readLinkedInInbox,
81
+ sendLinkedInMessage,
82
+ type LinkedInInboxCheckpoint,
83
+ } from "./linkedin-inbox.js";
84
+ import { prepareLinkedInDraft } from "./linkedin-drafts.js";
85
+ import { LINKEDIN_HOME_URL } from "./linkedin-browser-script.js";
86
+
87
+ // ── Types ──────────────────────────────────────────────────────
88
+
89
+ /**
90
+ * Merged checkpoint. Carries the live cursor fields (last_post_id / last_job_id
91
+ * / last_timestamp) AND every takeout feed's `last_*_timestamp` cursor. The
92
+ * takeout `jobs` feed was renamed to `applied_jobs`, so its cursor is
93
+ * `last_applied_jobs_timestamp` (no ambiguity with the live `jobs` feed, which
94
+ * checkpoints on last_job_id/last_timestamp). No production checkpoint exists,
95
+ * so the rename is safe.
96
+ */
97
+ interface LinkedInCheckpoint extends LinkedInInboxCheckpoint {
98
+ // Live feed cursors.
99
+ last_post_id?: string;
100
+ last_job_id?: string;
101
+ last_timestamp?: string;
102
+ // Takeout feed cursors.
103
+ last_messages_timestamp?: string;
104
+ last_connections_timestamp?: string;
105
+ last_invitations_timestamp?: string;
106
+ last_applied_jobs_timestamp?: string;
107
+ last_profile_timestamp?: string;
108
+ last_companies_timestamp?: string;
109
+ last_learning_timestamp?: string;
110
+ last_events_timestamp?: string;
111
+ last_endorsements_timestamp?: string;
112
+ last_media_timestamp?: string;
113
+ }
114
+
115
+ /**
116
+ * Merged config. Permissive superset of the live config (company_url,
117
+ * max_scrolls) and the takeout config (takeout_dir, batch_size). A given feed
118
+ * only reads the keys relevant to its source.
119
+ */
120
+ interface LinkedInConfig extends LocalTakeoutConfig {
121
+ company_url?: string;
122
+ max_scrolls?: number;
123
+ min_scrolls?: number;
124
+ }
125
+
126
+ interface LinkedInPost {
127
+ id: string;
128
+ text: string;
129
+ author: string;
130
+ authorHeadline?: string;
131
+ /** Immutable `urn:li:fsd_profile:<id>` tail — primary identity when present. */
132
+ authorMemberId?: string;
133
+ /** Canonical `/in/<slug>` vanity id — soft identity, bridges to takeout. */
134
+ authorSlug?: string;
135
+ likes: number;
136
+ comments: number;
137
+ shares: number;
138
+ publishedAt: Date;
139
+ }
140
+
141
+ interface LinkedInJob {
142
+ id: string;
143
+ title: string;
144
+ location: string;
145
+ postedAt: Date;
146
+ url: string;
147
+ description?: string;
148
+ }
149
+
150
+ function normalizeCheckpointPostId(postId?: string): string | undefined {
151
+ if (!postId) return undefined;
152
+ return postId.startsWith("li_post_")
153
+ ? postId.slice("li_post_".length)
154
+ : postId;
155
+ }
156
+
157
+ // ── Identity attributions ──────────────────────────────────────
158
+
159
+ /**
160
+ * Link a `connection` event to the connected person via their canonical
161
+ * `linkedin_slug` (extracted from the profile URL) plus their `email`. Neither
162
+ * is `primary` — they match equal-weight cross-channel until a stable primary
163
+ * id arrives from the live connector. The full URL is kept as a display trait,
164
+ * not an identity (case/URL noise would fork the entity). Connections ARE the
165
+ * user's network, so we mint (`autoCreate`) a person per row.
166
+ */
167
+ const LINKEDIN_CONNECTION_ATTRIBUTIONS: EventAttributionRule[] = [
168
+ {
169
+ role: "about",
170
+ autoCreate: true,
171
+ target: {
172
+ entityType: "person",
173
+ titlePath: "author_name",
174
+ identities: [
175
+ {
176
+ namespace: LINKEDIN_IDENTITY.SLUG,
177
+ eventPath: "metadata.linkedin_slug",
178
+ },
179
+ { namespace: IDENTITY.EMAIL, eventPath: "metadata.email" },
180
+ ],
181
+ },
182
+ traits: {
183
+ linkedin_url: {
184
+ eventPath: "metadata.linkedin_url",
185
+ mergeStrategy: "prefer_non_empty",
186
+ },
187
+ company: {
188
+ eventPath: "metadata.company",
189
+ mergeStrategy: "prefer_non_empty",
190
+ },
191
+ position: {
192
+ eventPath: "metadata.position",
193
+ mergeStrategy: "prefer_non_empty",
194
+ },
195
+ },
196
+ },
197
+ ];
198
+
199
+ /**
200
+ * Link a `message` event to its sender (the counterparty) via the
201
+ * `linkedin_slug` extracted from their profile URL, plus display name. Real
202
+ * counterparties, so mint on no match.
203
+ */
204
+ const LINKEDIN_MESSAGE_ATTRIBUTIONS: EventAttributionRule[] = [
205
+ {
206
+ role: "authored_by",
207
+ autoCreate: true,
208
+ target: {
209
+ entityType: "person",
210
+ titlePath: "metadata.from",
211
+ identities: [
212
+ {
213
+ namespace: LINKEDIN_IDENTITY.SLUG,
214
+ eventPath: "metadata.sender_linkedin_slug",
215
+ },
216
+ ],
217
+ },
218
+ traits: {
219
+ linkedin_url: {
220
+ eventPath: "metadata.sender_profile_url",
221
+ mergeStrategy: "prefer_non_empty",
222
+ },
223
+ last_linkedin_message_at: {
224
+ eventPath: "occurred_at",
225
+ mergeStrategy: "overwrite",
226
+ },
227
+ },
228
+ },
229
+ ];
230
+
231
+ /**
232
+ * Link a live `post` to its author. The Voyager feed (company_updates) exposes
233
+ * the actor's immutable `urn:li:fsd_profile:<id>` as `author_member_id` plus the
234
+ * `/in/<slug>`. Both are identities; NEITHER is `primary` — they match
235
+ * EQUAL-WEIGHT (same as the connections/messages attributions).
236
+ *
237
+ * Why not primary member_id: takeout-ingested people already exist keyed on
238
+ * `linkedin_slug` (no member id — the export has none). A `primary` member_id
239
+ * would be authoritative: on a live post it would find no member-id match, mint
240
+ * a NEW person, and fork the existing slug-person (the resolver does not fall
241
+ * back to a secondary slug hit when a primary is present). Equal-weight instead
242
+ * UNIONS the hits: the live post matches the existing person by slug AND
243
+ * accretes the member_id onto them. Durability still holds — once the member_id
244
+ * is on the person, a later vanity-URL change still resolves via that member_id
245
+ * in the equal-weight union. Real authors, so mint on no match.
246
+ */
247
+ const LINKEDIN_POST_AUTHOR_ATTRIBUTIONS: EventAttributionRule[] = [
248
+ {
249
+ role: "authored_by",
250
+ autoCreate: true,
251
+ target: {
252
+ entityType: "person",
253
+ titlePath: "author_name",
254
+ identities: [
255
+ {
256
+ namespace: LINKEDIN_IDENTITY.MEMBER_ID,
257
+ eventPath: "metadata.author_member_id",
258
+ },
259
+ {
260
+ namespace: LINKEDIN_IDENTITY.SLUG,
261
+ eventPath: "metadata.author_linkedin_slug",
262
+ },
263
+ ],
264
+ },
265
+ traits: {
266
+ linkedin_headline: {
267
+ eventPath: "metadata.author_headline",
268
+ mergeStrategy: "prefer_non_empty",
269
+ },
270
+ last_linkedin_post_at: {
271
+ eventPath: "occurred_at",
272
+ mergeStrategy: "overwrite",
273
+ },
274
+ },
275
+ },
276
+ ];
277
+
278
+ /**
279
+ * Attribute only people whose `linkedin_slug` was resolved from the row's
280
+ * profile links. The engine skips rules with no resolved identity, so a card
281
+ * that exposes no link for a member cannot create a name-only entity for them.
282
+ * When an engagement card exposes links for both members, it carries both
283
+ * slugs so the author can be minted instead of being dropped.
284
+ */
285
+ const LINKEDIN_HOME_FEED_ATTRIBUTIONS: EventAttributionRule[] = [
286
+ {
287
+ name: "author",
288
+ role: "authored_by",
289
+ autoCreate: true,
290
+ target: {
291
+ entityType: "person",
292
+ titlePath: "author_name",
293
+ identities: [
294
+ {
295
+ namespace: LINKEDIN_IDENTITY.SLUG,
296
+ eventPath: "metadata.author_linkedin_slug",
297
+ },
298
+ ],
299
+ },
300
+ traits: {
301
+ linkedin_url: {
302
+ eventPath: "metadata.author_profile_url",
303
+ mergeStrategy: "prefer_non_empty",
304
+ },
305
+ },
306
+ },
307
+ {
308
+ name: "engager",
309
+ role: "performed_by",
310
+ autoCreate: true,
311
+ target: {
312
+ entityType: "person",
313
+ titlePath: "metadata.social_actor",
314
+ identities: [
315
+ {
316
+ namespace: LINKEDIN_IDENTITY.SLUG,
317
+ eventPath: "metadata.social_actor_slug",
318
+ },
319
+ ],
320
+ },
321
+ traits: {
322
+ linkedin_url: {
323
+ eventPath: "metadata.social_actor_profile_url",
324
+ mergeStrategy: "prefer_non_empty",
325
+ },
326
+ },
327
+ },
328
+ ];
329
+
330
+ /** A visible comment links its author to the author of the parent post. */
331
+ const LINKEDIN_HOME_COMMENT_ATTRIBUTIONS: EventAttributionRule[] = [
332
+ {
333
+ name: "commenter",
334
+ role: "authored_by",
335
+ autoCreate: true,
336
+ target: {
337
+ entityType: "person",
338
+ titlePath: "author_name",
339
+ identities: [
340
+ {
341
+ namespace: LINKEDIN_IDENTITY.SLUG,
342
+ eventPath: "metadata.author_linkedin_slug",
343
+ },
344
+ ],
345
+ },
346
+ traits: {
347
+ linkedin_url: {
348
+ eventPath: "metadata.author_profile_url",
349
+ mergeStrategy: "prefer_non_empty",
350
+ },
351
+ },
352
+ },
353
+ {
354
+ name: "post_author",
355
+ role: "about",
356
+ autoCreate: true,
357
+ target: {
358
+ entityType: "person",
359
+ titlePath: "metadata.parent_author",
360
+ identities: [
361
+ {
362
+ namespace: LINKEDIN_IDENTITY.SLUG,
363
+ eventPath: "metadata.parent_author_linkedin_slug",
364
+ },
365
+ ],
366
+ },
367
+ traits: {
368
+ linkedin_url: {
369
+ eventPath: "metadata.parent_author_profile_url",
370
+ mergeStrategy: "prefer_non_empty",
371
+ },
372
+ },
373
+ },
374
+ {
375
+ name: "parent_comment_author",
376
+ role: "mentions",
377
+ autoCreate: true,
378
+ target: {
379
+ entityType: "person",
380
+ titlePath: "metadata.parent_comment_author",
381
+ identities: [
382
+ {
383
+ namespace: LINKEDIN_IDENTITY.SLUG,
384
+ eventPath: "metadata.parent_comment_author_linkedin_slug",
385
+ },
386
+ ],
387
+ },
388
+ traits: {
389
+ linkedin_url: {
390
+ eventPath: "metadata.parent_comment_author_profile_url",
391
+ mergeStrategy: "prefer_non_empty",
392
+ },
393
+ },
394
+ },
395
+ ];
396
+
397
+ // ── Home-feed content-script scrape contract ────────────────────
398
+ //
399
+ // The personalized home feed (linkedin.com/feed/) is the ONE feed that can't
400
+ // be read via network capture: attaching the CDP debugger stops the feed from
401
+ // rendering, so the Voyager responses never arrive. Instead we drive the
402
+ // extension's `cs_scrape` op (a content script, no debugger) with a declarative
403
+ // selector config defined here. The extension runs a site-agnostic scrape
404
+ // engine — the LinkedIn selectors live in this connector, not the extension.
405
+
406
+ /** One profile/company anchor scraped from a home-feed card. */
407
+ interface HomeFeedLink {
408
+ /** The `/in/<slug>` or `/company/<slug>` href. */
409
+ href?: string;
410
+ /**
411
+ * The anchor's accessible name — LinkedIn renders these as `View <Name>'s
412
+ * profile` (person) or `View company: <Name>` (company). Used to match an
413
+ * anchor to the actor/author named elsewhere in the card, so identity never
414
+ * depends on link order.
415
+ */
416
+ name?: string;
417
+ }
418
+
419
+ /** One media URL scraped from a feed card. */
420
+ interface HomeFeedMedia {
421
+ url?: string;
422
+ alt_text?: string;
423
+ }
424
+
425
+ /** A row produced by the extension's cs_scrape from HOME_FEED_SCRAPE_CONFIG. */
426
+ interface HomeFeedRow {
427
+ /** The componentkey token (base64url-ish, NOT a numeric activity id). */
428
+ id?: string;
429
+ body?: string;
430
+ author?: string;
431
+ /**
432
+ * The post-author's name, read from the card's control-menu button
433
+ * (`aria-label="Open control menu for post by <Author>"`). LinkedIn names the
434
+ * author here on the observed plain, engagement, promoted, and company card
435
+ * shapes, regardless of link order. This is preferred over the body-text
436
+ * heuristic when present.
437
+ */
438
+ author_control_label?: string;
439
+ /**
440
+ * Post permalink, when a row carries one. The scrape spec that fed this is
441
+ * inert on current cards (see `post_url` in HOME_FEED_SCRAPE_CONFIG), so
442
+ * treat it as best-effort and prefer `post_identity` for durable identity.
443
+ */
444
+ post_url?: string;
445
+ /**
446
+ * Rendered identifier carrying the stable post id: a readable shareId /
447
+ * ugcPostId / activity URN, or the encoded comment-tools id that
448
+ * `decodeHomeFeedPostIdentity` turns into a URN before ingestion.
449
+ */
450
+ post_identity?: string;
451
+ /** Every profile/company anchor in the card, each with its accessible name. */
452
+ links?: HomeFeedLink[];
453
+ /** Media that belongs to a top-level post (nested comment media excluded). */
454
+ post_media?: HomeFeedMedia[];
455
+ /** Media that belongs to a visible comment row. */
456
+ comment_media?: HomeFeedMedia[];
457
+ /** Dedicated engagement-summary values, never inferred from post prose. */
458
+ reaction_count_text?: string;
459
+ reaction_count_label?: string;
460
+ comment_count_text?: string;
461
+ comment_count_label?: string;
462
+ repost_count_text?: string;
463
+ repost_count_label?: string;
464
+ /** Explicit browser-runtime proof that the post's thread was fully expanded. */
465
+ comment_coverage?: HomeFeedCommentCoverage;
466
+ /** Durable identity of an enclosing comment when this row is a nested reply. */
467
+ parent_comment_identity?: string;
468
+ }
469
+
470
+ interface HomeFeedCommentCoverage {
471
+ expected: number;
472
+ collected: number;
473
+ complete: boolean;
474
+ timedOut?: boolean;
475
+ }
476
+
477
+ /** LinkedIn origins the cs_scrape window is allowed to touch. */
478
+ const LINKEDIN_ALLOWED_ORIGINS = ["linkedin.com", "*.linkedin.com"];
479
+
480
+ const HOME_FEED_COMMENT_COUNT_TEXT_SELECTOR =
481
+ ':scope:not([id^="replaceableComment_"]) div:has(+ hr + div button[aria-label="Open reactions menu"]):not([id^="replaceableComment_"] *) > div:last-child > div:first-child, .social-details-social-counts__comments, .social-details-social-counts__comments-count';
482
+ const HOME_FEED_COMMENT_COUNT_LABEL_SELECTOR =
483
+ '.social-details-social-counts [aria-label*="comment" i], [aria-label$=" comment" i]:not([id^="replaceableComment_"] *), [aria-label$=" comments" i]:not([id^="replaceableComment_"] *)';
484
+ const HOME_FEED_POST_CONTROL_SELECTOR =
485
+ '[role="button"]:not([id^="replaceableComment_"] *):not([componentkey^="commentsSectionContainer"] *), button:not([id^="replaceableComment_"] *):not([componentkey^="commentsSectionContainer"] *), a:not([id^="replaceableComment_"] *):not([componentkey^="commentsSectionContainer"] *)';
486
+ const HOME_FEED_POST_IDENTITY_SELECTOR =
487
+ ':is([id*="shareId="], [id*="ugcPostId="], [id*="urn:li:activity:"], [id*="-replaceableCommentTools"]):not([id^="replaceableComment_"]):not([id^="replaceableComment_"] *)';
488
+
489
+ /** Current comment-tool ids encode a typed post URN, followed by the recycled
490
+ * card key. Decode only the typed prefix: field 1 is activity, field 2 ugcPost,
491
+ * and field 3 groupPost. Each contains field 1 as a protobuf sint64 (ZigZag);
492
+ * groupPost contains the group id in field 1 and the post id in field 2.
493
+ * Native comment URNs and live post URLs confirm those namespaces. */
494
+ function decodeHomeFeedPostIdentity(
495
+ raw: string | undefined
496
+ ): string | undefined {
497
+ const marker = "-replaceableCommentTools";
498
+ if (!raw?.includes(marker)) return raw;
499
+ const invalid = () =>
500
+ new Error(
501
+ "LinkedIn returned an invalid encoded post identity. No home-feed events were persisted."
502
+ );
503
+ let bytes: string;
504
+ try {
505
+ bytes = atob(
506
+ raw.slice(0, raw.indexOf(marker)).replace(/-/g, "+").replace(/_/g, "/")
507
+ );
508
+ } catch {
509
+ throw invalid();
510
+ }
511
+ const tag = bytes.charCodeAt(0);
512
+ if (
513
+ (tag !== 10 && tag !== 18 && tag !== 26) ||
514
+ bytes.length < 4 ||
515
+ bytes.length > (tag === 26 ? 24 : 13) ||
516
+ bytes.charCodeAt(1) !== bytes.length - 2 ||
517
+ bytes.charCodeAt(2) !== 8
518
+ ) {
519
+ throw invalid();
520
+ }
521
+ let offset = 3;
522
+ const readId = (minimum: bigint) => {
523
+ let encoded = 0n;
524
+ for (let shift = 0; shift < 70 && offset < bytes.length; shift += 7) {
525
+ const byte = bytes.charCodeAt(offset++);
526
+ encoded |= BigInt(byte & 127) << BigInt(shift);
527
+ if (byte & 128) continue;
528
+ if ((encoded & 1n) !== 0n || encoded >= 1n << 64n || encoded < minimum) {
529
+ throw invalid();
530
+ }
531
+ return encoded >> 1n;
532
+ }
533
+ throw invalid();
534
+ };
535
+ // Group ids can be smaller than post ids, but must still be positive.
536
+ const firstId = readId(tag === 26 ? 2n : 200_000n);
537
+ if (tag === 26) {
538
+ if (bytes.charCodeAt(offset++) !== 16) throw invalid();
539
+ const postId = readId(200_000n);
540
+ if (offset !== bytes.length) throw invalid();
541
+ return `urn:li:groupPost:${firstId}-${postId}`;
542
+ }
543
+ if (offset !== bytes.length) throw invalid();
544
+ return `urn:li:${tag === 10 ? "activity" : "ugcPost"}:${firstId}`;
545
+ }
546
+
547
+ // A fenced dispatch discards every row it collected, so an oversized scrape
548
+ // repeats forever (prod hit `run timed out after 90000ms` on this feed).
549
+ // Target a 60s dispatch within Owletto's 90s run fence: reserve 23s for
550
+ // navigation (20s load wait + up to 3s settle in tools.js) and 12s for
551
+ // deadline overrun and harvesting. This is a cooperative expansion deadline,
552
+ // not a hard scrape timeout: the engine stops scrolling after observing it,
553
+ // then finishes harvesting. DOM work and anchor-lock waits can still overrun.
554
+ const HOME_FEED_SCRAPE_DEADLINE_MS = 25_000;
555
+
556
+ /**
557
+ * Selectors for the virtualized linkedin.com/feed/ DOM. Home-feed posts are
558
+ * componentkey divs with no activity urn, so the row id is the componentkey
559
+ * token (NOT numeric). These selectors live here, not in the extension.
560
+ */
561
+ const HOME_FEED_SCRAPE_CONFIG = {
562
+ // Current LinkedIn pages scroll inside <main>, not document/window.
563
+ scroll: { max: 8, stall: 3, waitMs: 1500, deep: true },
564
+ loggedOutWhen: {
565
+ pathRegex: "/(login|authwall|uas/login|checkpoint|signup)\\b",
566
+ },
567
+ rowSelector:
568
+ 'div[componentkey^="expanded"][componentkey*="FeedType_MAIN_FEED_RELEVANCE"], [id^="replaceableComment_urn:li:comment:"]',
569
+ expandRows: {
570
+ // Only actual post containers start with `expanded`; helper/component rows
571
+ // share the FeedType suffix but must never drive another post's controls.
572
+ rowSelector:
573
+ 'div[componentkey^="expanded"][componentkey*="FeedType_MAIN_FEED_RELEVANCE"]',
574
+ // LinkedIn swaps the whole card for a fresh element mid-expansion (sorting
575
+ // by "Most recent" is enough to trigger it). Without a row-local durable
576
+ // id the extension cannot tell a replacement from a recycled slot, so it
577
+ // abandons the thread. Same selector as post_identity below: the two must
578
+ // resolve to the same post or expansion proof binds to the wrong row.
579
+ identity: {
580
+ selector: HOME_FEED_POST_IDENTITY_SELECTOR,
581
+ take: "attr",
582
+ attr: "id",
583
+ // Exclude the recycled card-key suffix from expansion ownership.
584
+ regex: "^(.*?)(?:-replaceableCommentTools|$)",
585
+ group: 1,
586
+ },
587
+ expected: {
588
+ // Keep this aligned with the post-level comment count fields below. The
589
+ // count is not always interactive: LinkedIn also renders it as a plain
590
+ // counter wrapper or an aria-labelled span.
591
+ selector: `${HOME_FEED_COMMENT_COUNT_TEXT_SELECTOR}, ${HOME_FEED_COMMENT_COUNT_LABEL_SELECTOR}, ${HOME_FEED_POST_CONTROL_SELECTOR}`,
592
+ textRegex: "^\\d[\\d,.]*(?:\\s*[kmb])?\\s+comments?",
593
+ textRegexFlags: "i",
594
+ regex: "(\\d[\\d,.]*(?:\\s*[kmb])?)\\s+comments?",
595
+ regexFlags: "i",
596
+ },
597
+ items: {
598
+ selector: '[id^="replaceableComment_urn:li:comment:"]',
599
+ idAttr: "id",
600
+ },
601
+ open: {
602
+ selector: '[role="button"], button, a',
603
+ textRegex: "^\\d[\\d,.]*(?:\\s*[kmb])?\\s+comments?",
604
+ textRegexFlags: "i",
605
+ },
606
+ sort: {
607
+ triggerSelector: '[role="button"], button',
608
+ triggerTextRegex: "^Most relevant$|^Most recent$",
609
+ triggerTextRegexFlags: "i",
610
+ selectedTextRegex: "^Most recent$",
611
+ selectedTextRegexFlags: "i",
612
+ optionSelector: '[role="menuitem"]',
613
+ optionTextRegex: "^Most recent\\b",
614
+ optionTextRegexFlags: "i",
615
+ maxWaitMs: 1500,
616
+ },
617
+ more: {
618
+ selector: '[role="button"], button, a',
619
+ textRegex:
620
+ "^(?:(?:See|Load|View)\\s+\\d[\\d,.]*\\s+(?:more\\s+)?comments?|(?:See|Load|View)\\s+(?:more|previous)\\s+(?:comments?|replies)|\\d[\\d,.]*\\s+replies)\\b",
621
+ textRegexFlags: "i",
622
+ },
623
+ maxPasses: 40,
624
+ maxDurationMs: HOME_FEED_SCRAPE_DEADLINE_MS,
625
+ // LinkedIn removes its controls before the requested comments finish
626
+ // rendering. Allow a short control-free settling window; the shared
627
+ // maxDurationMs budget still caps the whole expansion pass.
628
+ stall: 12,
629
+ waitMs: 350,
630
+ outputField: "comment_coverage",
631
+ },
632
+ id: {
633
+ source: "attr",
634
+ // Posts identify themselves with componentkey; native comments use their
635
+ // replaceableComment id. Selecting comments individually keeps two visible
636
+ // comments (and their media) from collapsing into one container row.
637
+ name: ["componentkey", "id"],
638
+ // Post rows keep only the token before FeedType_. Comment ids have no
639
+ // FeedType_ suffix, so the end-of-string alternative preserves the full
640
+ // native comment identity.
641
+ regex: "^(?:expanded)?(.+?)(?=FeedType_|$)",
642
+ group: 1,
643
+ },
644
+ requireFields: ["body"],
645
+ fields: {
646
+ body: { take: "text" },
647
+ author: {
648
+ // LinkedIn obfuscates the actor classes, so the old
649
+ // .update-components-actor__* selectors no longer match. Best-effort:
650
+ // grab the visible name span inside the actor's profile/company link
651
+ // when present. When this misses, buildHomeFeedEvents falls back to
652
+ // parsing the author out of the row body text.
653
+ selector:
654
+ 'a[href*="/in/"] span[aria-hidden="true"], a[href*="/company/"] span[aria-hidden="true"]',
655
+ take: "text",
656
+ firstLine: true,
657
+ },
658
+ author_control_label: {
659
+ // The post's own control-menu button supplies the preferred author signal
660
+ // independently of profile-link order — see HomeFeedRow.
661
+ selector: 'button[aria-label*="control menu for post by"]',
662
+ take: "attr",
663
+ attr: "aria-label",
664
+ },
665
+ post_url: {
666
+ // Current cards expose neither a permalink anchor nor a post URN. Their
667
+ // control menu still has LinkedIn's own "Copy link to post" action, but
668
+ // the extension does not click clipboard-writing actions. `post_url` is
669
+ // therefore best-effort/empty; `post_identity` below is the durable key.
670
+ take: "clipboardAction",
671
+ triggerSelector: 'button[aria-label*="control menu for post by"]',
672
+ actionSelector: '[role="menuitem"]',
673
+ actionTextRegex: "^Copy link(?: to post)?$",
674
+ actionTextRegexFlags: "i",
675
+ maxWaitMs: 1500,
676
+ },
677
+ post_identity: {
678
+ // Readable commentary URNs and encoded comment-tool ids both carry the
679
+ // durable post identity. parseRows decodes the latter before ingestion.
680
+ selector: HOME_FEED_POST_IDENTITY_SELECTOR,
681
+ take: "attr",
682
+ attr: "id",
683
+ },
684
+ links: {
685
+ // Every profile/company anchor with its accessible name, so
686
+ // buildHomeFeedEvents can match the author/engager by NAME rather than by
687
+ // fragile DOM position. `aria` reads the anchor's own or descendant
688
+ // aria-label ("View <Name>'s profile"); `alt` covers the avatar img on
689
+ // company links ("View company: <Name>").
690
+ selector: 'a[href*="/in/"], a[href*="/company/"]',
691
+ take: "objectAll",
692
+ parts: {
693
+ href: { take: "attr", attr: "href" },
694
+ name: { take: "aria" },
695
+ nameAlt: { take: "alt" },
696
+ },
697
+ },
698
+ post_media: {
699
+ // Profile photos and company logos are identities, not post attachments.
700
+ // The final :not keeps media inside a nested visible comment off the post.
701
+ selector:
702
+ ':scope:not([id^="replaceableComment_"]) img[src*="media.licdn.com/dms/image/"]:not([src*="profile-displayphoto"]):not([src*="company-logo"]):not([id^="replaceableComment_"] img)',
703
+ take: "objectAll",
704
+ parts: {
705
+ url: { take: "attr", attr: "src" },
706
+ alt_text: { take: "attr", attr: "alt" },
707
+ },
708
+ },
709
+ comment_media: {
710
+ selector:
711
+ ':scope[id^="replaceableComment_"] img[src*="media.licdn.com/dms/image/"]:not([src*="profile-displayphoto"]):not([src*="company-logo"])',
712
+ take: "objectAll",
713
+ parts: {
714
+ url: { take: "attr", attr: "src" },
715
+ alt_text: { take: "attr", attr: "alt" },
716
+ },
717
+ },
718
+ parent_comment_identity: {
719
+ // Replies are nested beneath their parent comment on the current feed.
720
+ // Starting the closest lookup at parentElement keeps top-level comments
721
+ // empty while recording the enclosing durable comment id for replies.
722
+ closestSelector: '[id^="replaceableComment_urn:li:comment:"]',
723
+ take: "attr",
724
+ attr: "id",
725
+ },
726
+ // Engagement comes only from LinkedIn's dedicated social-count controls.
727
+ // Keep both visible text and accessible-label variants because the current
728
+ // feed uses both shapes across post types and experiments.
729
+ //
730
+ // Row scoping matters here: a post row CONTAINS its visible comment rows,
731
+ // and `querySelector` returns the first match in DOCUMENT order across the
732
+ // whole comma list, not the first branch that matches. So every branch that
733
+ // is not already anchored to `.social-details-social-counts` (the post's own
734
+ // block) carries `:not([id^="replaceableComment_"] *)`, which excludes
735
+ // elements inside a nested comment. The reaction fields then add a leading
736
+ // `:scope[id^="replaceableComment_"]` branch so a comment row reads its OWN
737
+ // reactions: the current feed puts the count beside an "Open reactions
738
+ // menu" button using obfuscated classes, while permalink pages still use a
739
+ // comment social-bar class with an experiment suffix (`--cr`). The semantic
740
+ // sibling branch covers the feed and the prefix class match covers the
741
+ // permalink shape. Current post cards put their count block immediately
742
+ // before the divider and action bar; those semantic siblings avoid the
743
+ // obfuscated classes. Comment and repost counts stay post-only — a
744
+ // comment's reply count is a different quantity.
745
+ reaction_count_text: {
746
+ selector:
747
+ ':scope:not([id^="replaceableComment_"]) div:has(+ hr + div button[aria-label="Open reactions menu"]):not([id^="replaceableComment_"] *) > a:first-child, :scope[id^="replaceableComment_"] div:has(> button[aria-label="Open reactions menu"]) > :first-child, :scope[id^="replaceableComment_"] [class*="comments-comment-social-bar__reactions-count"], .social-details-social-counts__reactions-count, .social-details-social-counts__reactions',
748
+ take: "text",
749
+ },
750
+ reaction_count_label: {
751
+ selector:
752
+ ':scope[id^="replaceableComment_"] [aria-label*=" reaction on " i], :scope[id^="replaceableComment_"] [aria-label*=" reactions on " i], .social-details-social-counts [aria-label*="reaction" i], [aria-label$=" reaction" i]:not([aria-label^="Reaction button state:" i]):not([id^="replaceableComment_"] *), [aria-label$=" reactions" i]:not([aria-label^="Reaction button state:" i]):not([id^="replaceableComment_"] *)',
753
+ take: "attr",
754
+ attr: "aria-label",
755
+ },
756
+ comment_count_text: {
757
+ selector: HOME_FEED_COMMENT_COUNT_TEXT_SELECTOR,
758
+ take: "text",
759
+ },
760
+ comment_count_label: {
761
+ selector: HOME_FEED_COMMENT_COUNT_LABEL_SELECTOR,
762
+ take: "attr",
763
+ attr: "aria-label",
764
+ },
765
+ repost_count_text: {
766
+ selector:
767
+ ':scope:not([id^="replaceableComment_"]) div:has(+ hr + div button[aria-label="Open reactions menu"]):not([id^="replaceableComment_"] *) > div:last-child > a:last-child, .social-details-social-counts__reposts, .social-details-social-counts__reposts-count',
768
+ take: "text",
769
+ },
770
+ repost_count_label: {
771
+ selector:
772
+ '.social-details-social-counts [aria-label*="repost" i], [aria-label$=" repost" i]:not([id^="replaceableComment_"] *), [aria-label$=" reposts" i]:not([id^="replaceableComment_"] *)',
773
+ take: "attr",
774
+ attr: "aria-label",
775
+ },
776
+ },
777
+ } as const;
778
+
779
+ /**
780
+ * Profile activity lists render the same cards as the home feed under their own
781
+ * FeedType, so they share its fields and identity parsing. Read only comments
782
+ * already rendered on those pages, without expanding threads.
783
+ */
784
+ const MY_ACTIVITY_LISTS = {
785
+ posts: { path: "all", feedType: "FeedType_CREATOR_PROFILE_ALL_CONTENT_VIEW" },
786
+ comments: { path: "comments", feedType: "FeedType_PROFILE_COMMENTS" },
787
+ } as const;
788
+
789
+ function myActivityScrapeConfig(feedType: string, maxScrolls: number) {
790
+ const { expandRows: _expandRows, ...cardConfig } = HOME_FEED_SCRAPE_CONFIG;
791
+ // post_url opens every card's control menu and waits for a copy-link item it
792
+ // never uses; activity cards carry post_identity, so skip that per-row wait.
793
+ const { post_url: _postUrl, ...fields } = cardConfig.fields;
794
+ return {
795
+ ...cardConfig,
796
+ fields,
797
+ rowSelector: `div[componentkey^="expanded"][componentkey*="${feedType}"], [id^="replaceableComment_urn:li:comment:"]`,
798
+ scroll: { ...cardConfig.scroll, max: maxScrolls },
799
+ };
800
+ }
801
+
802
+ /** UI prefixes on post cards, stripped before resolving the author's name. */
803
+ const MY_ACTIVITY_CHROME_PREFIXES = [
804
+ /^Feed post(?:\s+|$)/i,
805
+ /^Promote this post to reach people who matter to you\.\s*Boost\s*/i,
806
+ /^This post type can['’]t be boosted\.\s*/i,
807
+ ];
808
+
809
+ function stripMyActivityChrome(text: string): string {
810
+ let out = text.trim();
811
+ for (const prefix of MY_ACTIVITY_CHROME_PREFIXES) {
812
+ out = out.replace(prefix, "");
813
+ }
814
+ return out;
815
+ }
816
+
817
+ function linkedInProfileSlugFromUrl(
818
+ url: string | undefined
819
+ ): string | undefined {
820
+ const match = url?.match(/linkedin\.com\/in\/([^/?#]+)/i);
821
+ const slug = match?.[1] ? decodeURIComponent(match[1]) : undefined;
822
+ return slug && slug.toLowerCase() !== "me" ? slug : undefined;
823
+ }
824
+
825
+ async function readMyLinkedInActivity(
826
+ ctx: ActionContext
827
+ ): Promise<ActionResult> {
828
+ const requested = Array.isArray(ctx.input.kinds)
829
+ ? ctx.input.kinds.filter(
830
+ (kind): kind is keyof typeof MY_ACTIVITY_LISTS =>
831
+ kind === "posts" || kind === "comments"
832
+ )
833
+ : [];
834
+ const kinds =
835
+ requested.length > 0 ? requested : (["posts", "comments"] as const);
836
+ const rawScrolls = Number(ctx.input.max_scrolls ?? 3);
837
+ const maxScrolls = Number.isFinite(rawScrolls)
838
+ ? Math.min(10, Math.max(1, Math.trunc(rawScrolls)))
839
+ : 3;
840
+ const dispatcher = requireBrowser(ctx);
841
+
842
+ // Resolve the /in/me/ redirect before constructing canonical activity URLs.
843
+ const profile = await extensionDomScrape<Record<string, unknown>>({
844
+ dispatcher,
845
+ url: "https://www.linkedin.com/in/me/",
846
+ config: {
847
+ rowSelector: "main",
848
+ requireFields: [],
849
+ fields: {},
850
+ loggedOutWhen: HOME_FEED_SCRAPE_CONFIG.loggedOutWhen,
851
+ },
852
+ parseRows: (rows) => rows,
853
+ allowedOrigins: LINKEDIN_ALLOWED_ORIGINS,
854
+ // One action run reads several pages; a run-scoped scratch tab is released
855
+ // after each scrape, so reuse LinkedIn's anchor tab across these reads.
856
+ persistent: true,
857
+ });
858
+ if (!profile.loggedIn) {
859
+ return {
860
+ success: false,
861
+ error:
862
+ "Not logged into LinkedIn. Sign in to linkedin.com in the paired Chrome profile, then retry.",
863
+ };
864
+ }
865
+ const slug = linkedInProfileSlugFromUrl(profile.landedUrl);
866
+ // Author slugs are stored in normalizeLinkedInSlug's canonical form (still
867
+ // percent-encoded), so ownership compares against that form, not `slug`.
868
+ const memberSlug = normalizeLinkedInSlug(profile.landedUrl);
869
+ if (!slug || !memberSlug) {
870
+ return {
871
+ success: false,
872
+ error: `Could not resolve the signed-in LinkedIn profile from ${JSON.stringify(profile.landedUrl ?? null)}.`,
873
+ };
874
+ }
875
+
876
+ const items: Array<Record<string, unknown>> = [];
877
+ for (const kind of kinds) {
878
+ const list = MY_ACTIVITY_LISTS[kind];
879
+ const { items: rows, loggedIn } = await extensionDomScrape<HomeFeedRow>({
880
+ dispatcher,
881
+ url: `https://www.linkedin.com/in/${encodeURIComponent(slug)}/recent-activity/${list.path}/`,
882
+ config: myActivityScrapeConfig(list.feedType, maxScrolls),
883
+ parseRows: (raw) =>
884
+ (raw as HomeFeedRow[]).map((row) => ({
885
+ ...row,
886
+ body: parseHomeFeedCommentIdentity(row.id)
887
+ ? row.body
888
+ : stripMyActivityChrome(row.body ?? ""),
889
+ post_identity: decodeHomeFeedPostIdentity(row.post_identity),
890
+ })),
891
+ allowedOrigins: LINKEDIN_ALLOWED_ORIGINS,
892
+ persistent: true,
893
+ });
894
+ if (!loggedIn) {
895
+ return {
896
+ success: false,
897
+ error:
898
+ "Not logged into LinkedIn. Sign in to linkedin.com in the paired Chrome profile, then retry.",
899
+ };
900
+ }
901
+ for (const event of buildHomeFeedEvents(rows, new Date())) {
902
+ const metadata = (event.metadata ?? {}) as Record<string, unknown>;
903
+ const authorSlug = metadata.author_linkedin_slug;
904
+ items.push({
905
+ list: kind,
906
+ type: event.origin_type,
907
+ id: event.origin_id,
908
+ ...(event.origin_parent_id
909
+ ? { parent_id: event.origin_parent_id }
910
+ : {}),
911
+ is_mine: authorSlug === memberSlug,
912
+ author: event.author_name ?? null,
913
+ text: event.payload_text ?? "",
914
+ url: event.source_url ?? null,
915
+ ...(typeof metadata.parent_author === "string"
916
+ ? { parent_author: metadata.parent_author }
917
+ : {}),
918
+ });
919
+ }
920
+ }
921
+
922
+ return {
923
+ success: true,
924
+ output: { profile_slug: slug, count: items.length, items },
925
+ };
926
+ }
927
+
928
+ /**
929
+ * Live home-feed read for virtual timelines: scrapes the same cards the
930
+ * home_feed sync persists, but returns them without storing any events.
931
+ * Skips short-URL resolution and reports unaddressable posts as skipped:
932
+ * the flagger can only stage drafts for posts with a durable URL.
933
+ */
934
+ async function readHomeFeed(ctx: ActionContext): Promise<ActionResult> {
935
+ const rawScrolls = Number(ctx.input.max_scrolls ?? 6);
936
+ const maxScrolls = Number.isFinite(rawScrolls)
937
+ ? Math.min(10, Math.max(1, Math.trunc(rawScrolls)))
938
+ : 6;
939
+ const dispatcher = requireBrowser(ctx);
940
+ // Timeline reads prioritize more posts. Expanding a busy comment thread
941
+ // spends the shared expansion deadline before the scraper can paginate.
942
+ // Already-rendered comments remain readable through the same row selector.
943
+ const { expandRows: _expandRows, ...timelineConfig } =
944
+ HOME_FEED_SCRAPE_CONFIG;
945
+ const { items: rows, loggedIn } = await extensionDomScrape<HomeFeedRow>({
946
+ dispatcher,
947
+ url: LINKEDIN_HOME_URL,
948
+ config: {
949
+ ...timelineConfig,
950
+ scroll: { ...timelineConfig.scroll, max: maxScrolls },
951
+ },
952
+ parseRows: (raw) =>
953
+ (raw as HomeFeedRow[]).map((row) => ({
954
+ ...row,
955
+ post_identity: decodeHomeFeedPostIdentity(row.post_identity),
956
+ })),
957
+ allowedOrigins: LINKEDIN_ALLOWED_ORIGINS,
958
+ // A hidden warm tab can retain only the initial batch. The default scrape
959
+ // window gives LinkedIn a fresh rendering surface and closes after reading.
960
+ persistent: false,
961
+ });
962
+ if (!loggedIn) {
963
+ return {
964
+ success: false,
965
+ error:
966
+ "Not logged into LinkedIn. Sign in to linkedin.com in the paired Chrome profile, then retry.",
967
+ };
968
+ }
969
+ const items: Array<Record<string, unknown>> = [];
970
+ // Count only emitted events without a URL: unresolved scrape rows may
971
+ // never become events (dropped as noise), so counting rows would inflate
972
+ // the number. The flagger can only stage drafts for addressable posts.
973
+ let skipped = 0;
974
+ for (const event of buildHomeFeedEvents(rows, new Date())) {
975
+ if (!event.source_url) {
976
+ skipped += 1;
977
+ continue;
978
+ }
979
+ items.push({
980
+ type: event.origin_type,
981
+ id: event.origin_id,
982
+ ...(event.origin_parent_id ? { parent_id: event.origin_parent_id } : {}),
983
+ author: event.author_name ?? null,
984
+ text: event.payload_text ?? "",
985
+ url: event.source_url,
986
+ });
987
+ }
988
+ return {
989
+ success: true,
990
+ output: { count: items.length, skipped, items },
991
+ };
992
+ }
993
+
994
+ /**
995
+ * Best-effort author extraction from a home-feed row's body text. Social
996
+ * context appears before the post author in two shapes: actor banners name an
997
+ * engaging member ("X likes this", "X commented", "X reposted this") and
998
+ * actor-less banners are platform labels with no member ("Recommended for
999
+ * you", "Voices worth following"). Stacked context can contain more than one
1000
+ * actor banner; the author follows the last one.
1001
+ */
1002
+ const HOME_FEED_ACTOR_BANNER_RE =
1003
+ /\b(?:(?:likes?|loves?|celebrates?|supports?) this|finds? this (?:insightful|funny)|commented(?: on this)?|reposted this)\s*/gi;
1004
+ const HOME_FEED_ACTORLESS_BANNER_RE =
1005
+ /^(?:recommended for you|voices worth following)\s+/i;
1006
+
1007
+ /** Normalize a matched actor-banner to a stable engagement verb. */
1008
+ function normalizeSocialAction(banner: string): string {
1009
+ const b = banner.toLowerCase();
1010
+ if (b.includes("comment")) return "comment";
1011
+ if (b.includes("repost")) return "repost";
1012
+ if (b.includes("insightful")) return "insightful";
1013
+ if (b.includes("funny")) return "funny";
1014
+ if (b.includes("love")) return "love";
1015
+ if (b.includes("celebrate")) return "celebrate";
1016
+ if (b.includes("support")) return "support";
1017
+ return "like";
1018
+ }
1019
+
1020
+ type HomeFeedBanner =
1021
+ | { kind: "actor"; actor: string; action: string }
1022
+ | { kind: "actorless" };
1023
+
1024
+ /** Strip relative-time tokens, fused CTAs, and leading emoji from a name. */
1025
+ function cleanHomeFeedDisplayName(raw: string): string {
1026
+ let name = raw.trim();
1027
+ // A repost segment puts a relative-time token (e.g. "17h") right after the
1028
+ // original poster's name and before the marker — strip it so we keep just
1029
+ // the name.
1030
+ name = name.replace(/\s+\d+\s*[smhdwy]o?$/i, "").trim();
1031
+ // Feed cards sometimes fuse UI chrome into the name after a repost /
1032
+ // company author: "Sim Visit website", "Acme View job".
1033
+ name = name
1034
+ .replace(
1035
+ /\s+(?:Visit website|View (?:job|page|profile)|Apply now|Register now|Sign up)$/i,
1036
+ ""
1037
+ )
1038
+ .trim();
1039
+ // Leading emoji / symbol decorations on display names (e.g. "🦔 james").
1040
+ name = name.replace(/^[^\p{L}\p{N}]+/u, "").trim();
1041
+ return name.slice(0, 60);
1042
+ }
1043
+
1044
+ function parseHomeFeedAuthorDetails(body: string): {
1045
+ author: string;
1046
+ banner: HomeFeedBanner | null;
1047
+ } {
1048
+ if (!body) return { author: "", banner: null };
1049
+ const text = body.replace(/^feed post\s+/i, "").trim();
1050
+
1051
+ // Limit banner matching to the row header so post content cannot be mistaken
1052
+ // for social context.
1053
+ const sepIdx = text.indexOf(" • ");
1054
+ if (sepIdx === -1) {
1055
+ // Expanded-post cards can use "<Name> Author <headline>" without a degree
1056
+ // marker. Resolve that bounded prefix before scanning for banner phrases
1057
+ // so words in the post content cannot affect attribution.
1058
+ const badge = text.match(/^(.{1,60}?)\s+Author\b/);
1059
+ return {
1060
+ author: badge ? cleanHomeFeedDisplayName(badge[1]) : "",
1061
+ banner: null,
1062
+ };
1063
+ }
1064
+ let header = text.slice(0, sepIdx).trim();
1065
+
1066
+ let banner: HomeFeedBanner | null = null;
1067
+ const actorless = header.match(HOME_FEED_ACTORLESS_BANNER_RE);
1068
+ if (actorless) {
1069
+ header = header.slice(actorless[0].length).trim();
1070
+ banner = { kind: "actorless" };
1071
+ }
1072
+
1073
+ const matches = [...header.matchAll(HOME_FEED_ACTOR_BANNER_RE)];
1074
+ if (matches.length > 0) {
1075
+ const first = matches[0];
1076
+ const last = matches[matches.length - 1];
1077
+ const actorGroup = header.slice(0, first.index).trim();
1078
+ const pluralActors = actorGroup.match(/^(.*?)\s+and\s+\d+\s+others?$/i);
1079
+ // "A and 3 others" / "A, B and 22 others" use A's profile link. Preserve
1080
+ // commas in a single member's display name (for example, "A, MBA").
1081
+ const actor = cleanHomeFeedDisplayName(
1082
+ pluralActors ? pluralActors[1].split(",")[0] : actorGroup
1083
+ );
1084
+ banner = {
1085
+ kind: "actor",
1086
+ actor: actor.slice(0, 60),
1087
+ action: normalizeSocialAction(first[0]),
1088
+ };
1089
+ header = header.slice(last.index + last[0].length).trim();
1090
+ }
1091
+
1092
+ let name = header;
1093
+ // A "<Name> Premium Profile <degree> <Name>" badge row repeats the name —
1094
+ // keep only the leading one.
1095
+ const premiumIdx = name.indexOf(" Premium Profile");
1096
+ if (premiumIdx !== -1) name = name.slice(0, premiumIdx);
1097
+ return { author: cleanHomeFeedDisplayName(name), banner };
1098
+ }
1099
+
1100
+ export function parseHomeFeedAuthor(body: string): string {
1101
+ return parseHomeFeedAuthorDetails(body).author;
1102
+ }
1103
+
1104
+ /**
1105
+ * Pull the post author's name out of the control-menu aria-label
1106
+ * ("Open control menu for post by <Author>"). Returns "" when the field is
1107
+ * missing (older cards / extensions) so callers fall back to the body parse.
1108
+ */
1109
+ function parseAuthorControlLabel(label?: string): string {
1110
+ if (!label) return "";
1111
+ const m = label.match(/control menu for post by\s+(.+)$/i);
1112
+ return m ? cleanHomeFeedDisplayName(m[1]) : "";
1113
+ }
1114
+
1115
+ /** A comparison key that ignores case, accents, and punctuation. */
1116
+ function nameKey(name: string): string {
1117
+ return cleanHomeFeedDisplayName(name)
1118
+ .toLowerCase()
1119
+ .normalize("NFD")
1120
+ .replace(/[\u0300-\u036f]/g, "")
1121
+ .replace(/[^\p{L}\p{N} ]/gu, "")
1122
+ .replace(/\s+/g, " ")
1123
+ .trim();
1124
+ }
1125
+
1126
+ /** The accessible name LinkedIn renders on a profile/company anchor. */
1127
+ function linkDisplayName(link: HomeFeedLink): string {
1128
+ const raw = link.name || "";
1129
+ // "View <Name>'s profile" / "View <Name>'s graphic" (person avatars) and
1130
+ // "View company: <Name>" (company avatars).
1131
+ const person = raw.match(/^View\s+(.+?)['’]s\s+(?:profile|graphic)/i);
1132
+ if (person) return cleanHomeFeedDisplayName(person[1]);
1133
+ const company = raw.match(/^View company:\s+(.+)$/i);
1134
+ if (company) return cleanHomeFeedDisplayName(company[1]);
1135
+ return cleanHomeFeedDisplayName(raw);
1136
+ }
1137
+
1138
+ /**
1139
+ * Coerce the extension's `links` field into HomeFeedLink[]. The objectAll scrape
1140
+ * emits `{href, name, nameAlt}` per anchor (name = aria-label, nameAlt = img
1141
+ * alt); coalesce them into one accessible name. Guards a non-array value so a
1142
+ * malformed/absent field yields no links rather than a crash.
1143
+ */
1144
+ function normalizeHomeFeedLinks(raw: unknown): HomeFeedLink[] {
1145
+ if (!Array.isArray(raw)) return [];
1146
+ return raw.map((l) => {
1147
+ const link = (l ?? {}) as {
1148
+ href?: string;
1149
+ name?: string;
1150
+ nameAlt?: string;
1151
+ };
1152
+ return { href: link.href, name: link.name || link.nameAlt || "" };
1153
+ });
1154
+ }
1155
+
1156
+ /**
1157
+ * Whether the paired extension understood the `objectAll` scrape take. A build
1158
+ * that predates it ignores the take and returns the field as plain text, so
1159
+ * `row.links` arrives as a string rather than an array. Attribution still
1160
+ * degrades gracefully (events emit with author names, just no slugs), but the
1161
+ * caller surfaces this so a stale extension is observable rather than silent.
1162
+ * A card with genuinely no profile links yields `[]`, which is indistinguishable
1163
+ * from support — so support is inferred from ANY row producing an array.
1164
+ */
1165
+ export function homeFeedObjectAllSupported(rows: HomeFeedRow[]): boolean {
1166
+ const withLinks = rows.filter((r) => r?.links !== undefined);
1167
+ if (withLinks.length === 0) return true; // no evidence either way — assume ok
1168
+ return withLinks.some((r) => Array.isArray(r.links));
1169
+ }
1170
+
1171
+ /** Whether an href points at a `/company/` page rather than a member. */
1172
+ function isCompanyHref(href?: string): boolean {
1173
+ return /\/company\//i.test(href ?? "");
1174
+ }
1175
+
1176
+ /**
1177
+ * Resolve a member's `/in/<slug>` from the card's anchors by matching a target
1178
+ * display name to the anchor's accessible name. Matching by NAME (not DOM
1179
+ * position) makes attribution robust to link count and order.
1180
+ *
1181
+ * Attribution requires the name to resolve UNAMBIGUOUSLY to one member. It
1182
+ * returns undefined when:
1183
+ * - a company anchor shares the name (the target is that company, e.g. a
1184
+ * company author whose name also appears on a person mention), or
1185
+ * - more than one distinct member slug matches the name.
1186
+ * This prevents a same-named person mention from being promoted to author when
1187
+ * the real author is a company or a different same-named person.
1188
+ */
1189
+ function resolveMemberSlug(
1190
+ links: HomeFeedLink[],
1191
+ targetName: string
1192
+ ): string | undefined {
1193
+ const target = nameKey(targetName);
1194
+ if (!target) return undefined;
1195
+ const memberSlugs = new Set<string>();
1196
+ let companyMatch = false;
1197
+ for (const link of links) {
1198
+ if (nameKey(linkDisplayName(link)) !== target) continue;
1199
+ const slug = normalizeLinkedInSlug(link.href);
1200
+ if (slug) memberSlugs.add(slug);
1201
+ else if (isCompanyHref(link.href)) companyMatch = true;
1202
+ }
1203
+ if (companyMatch || memberSlugs.size !== 1) return undefined;
1204
+ return [...memberSlugs][0];
1205
+ }
1206
+
1207
+ /**
1208
+ * The home feed mixes in ads, suggestions, and non-post noise. These never
1209
+ * become useful events, so drop them before emitting. Heuristic by necessity —
1210
+ * the home feed has no structured "is this an ad" field over the content-script
1211
+ * scrape.
1212
+ */
1213
+ export function isHomeFeedNoise(
1214
+ body: string,
1215
+ signals: {
1216
+ authorControlLabel?: string;
1217
+ hasDurableIdentity?: boolean;
1218
+ } = {}
1219
+ ): boolean {
1220
+ if (!body || body.trim().length < 30) return true;
1221
+ if (/\bPromoted\b/i.test(body.slice(0, 130))) return true;
1222
+ if (/\bSuggested\b/i.test(body.slice(0, 30))) return true;
1223
+ // Current feed modules use the same outer componentkey shape and "Feed post"
1224
+ // prefix as posts, but have neither a post control nor an author/time header.
1225
+ // Real member/company cards expose at least one of those signals. Keeping the
1226
+ // header fallback makes a broken control-menu selector fail the durable-id
1227
+ // health check instead of silently dropping genuine posts.
1228
+ const text = body.replace(/^feed post\s+/i, "").trim();
1229
+ const hasMemberHeader = text.includes(" • ") || /^\S.+\s+Author\b/.test(text);
1230
+ const hasPostControl = Boolean(
1231
+ parseAuthorControlLabel(signals.authorControlLabel)
1232
+ );
1233
+ return !hasMemberHeader && !hasPostControl && !signals.hasDurableIdentity;
1234
+ }
1235
+
1236
+ interface HomeFeedEngagement {
1237
+ reactions?: number;
1238
+ comments?: number;
1239
+ reposts?: number;
1240
+ }
1241
+
1242
+ interface HomeFeedCommentIdentity {
1243
+ urn: string;
1244
+ parentNamespace: ReturnType<typeof linkedInUrnNamespace>;
1245
+ parentId: string;
1246
+ commentId: string;
1247
+ }
1248
+
1249
+ interface HomeFeedRowContext {
1250
+ author: string;
1251
+ authorSlug?: string;
1252
+ postUrl?: string;
1253
+ metadata: Record<string, unknown>;
1254
+ }
1255
+
1256
+ function homeFeedPostIdentityKey(
1257
+ row: HomeFeedRow,
1258
+ context: HomeFeedRowContext
1259
+ ): string | undefined {
1260
+ for (const raw of [context.postUrl, row.post_identity]) {
1261
+ if (!raw) continue;
1262
+ const match = raw.match(
1263
+ /(?:(shareId|ugcPostId)=|urn:li:(activity|share|ugcPost):)(\d{6,})|urn:li:(groupPost):(\d+-\d{6,})/i
1264
+ );
1265
+ if (!match) continue;
1266
+ return `${linkedInUrnNamespace(match[1] ?? match[2] ?? match[4] ?? "")}:${match[3] ?? match[5]}`;
1267
+ }
1268
+ return undefined;
1269
+ }
1270
+
1271
+ function homeFeedPostOriginId(identityKey: string): string {
1272
+ return `li_home_${identityKey.replace(":", "_")}`;
1273
+ }
1274
+
1275
+ function parseHomeFeedCommentIdentity(
1276
+ raw: string | undefined
1277
+ ): HomeFeedCommentIdentity | undefined {
1278
+ if (!raw) return undefined;
1279
+ // Normalize both parent forms so the same comment has one canonical URN.
1280
+ const match = raw.match(
1281
+ /urn:li:comment:\((?:urn:li:)?(activity|share|ugcPost):(\d+),(\d+)\)/i
1282
+ );
1283
+ if (!match) return undefined;
1284
+ const parentNamespace = linkedInUrnNamespace(match[1]);
1285
+ return {
1286
+ urn: `urn:li:comment:(urn:li:${parentNamespace}:${match[2]},${match[3]})`,
1287
+ parentNamespace,
1288
+ parentId: match[2],
1289
+ commentId: match[3],
1290
+ };
1291
+ }
1292
+
1293
+ function parseLinkedInCompactCount(raw: string): number {
1294
+ const match = raw.trim().match(/^(\d[\d,.]*)(?:\s*([kmb]))?$/i);
1295
+ if (!match) return 0;
1296
+ const base = Number(match[1].replace(/,/g, ""));
1297
+ if (!Number.isFinite(base)) return 0;
1298
+ const multiplier =
1299
+ match[2]?.toLowerCase() === "b"
1300
+ ? 1_000_000_000
1301
+ : match[2]?.toLowerCase() === "m"
1302
+ ? 1_000_000
1303
+ : match[2]?.toLowerCase() === "k"
1304
+ ? 1_000
1305
+ : 1;
1306
+ return Math.round(base * multiplier);
1307
+ }
1308
+
1309
+ function maxHomeFeedCounter(
1310
+ ...values: Array<string | undefined>
1311
+ ): number | undefined {
1312
+ let max = 0;
1313
+ for (const value of values) {
1314
+ if (!value) continue;
1315
+ for (const match of value.matchAll(/\b(\d[\d,.]*(?:\s*[kmb])?)\b/gi)) {
1316
+ max = Math.max(max, parseLinkedInCompactCount(match[1]));
1317
+ }
1318
+ }
1319
+ return max > 0 ? max : undefined;
1320
+ }
1321
+
1322
+ function homeFeedReactionCount(row: HomeFeedRow): number | undefined {
1323
+ for (const value of [row.reaction_count_text, row.reaction_count_label]) {
1324
+ const others = value?.match(
1325
+ /\band\s+(\d[\d,.]*(?:\s*[kmb])?)\s+others?\s+reacted\b/i
1326
+ );
1327
+ if (others) return parseLinkedInCompactCount(others[1]) + 1;
1328
+ }
1329
+
1330
+ const explicitTotal = maxHomeFeedCounter(row.reaction_count_text);
1331
+ if (explicitTotal !== undefined) return explicitTotal;
1332
+
1333
+ const label = row.reaction_count_label;
1334
+ if (!label) return undefined;
1335
+ return maxHomeFeedCounter(label);
1336
+ }
1337
+
1338
+ export function parseHomeFeedEngagement(row: HomeFeedRow): HomeFeedEngagement {
1339
+ return {
1340
+ reactions: homeFeedReactionCount(row),
1341
+ comments: maxHomeFeedCounter(
1342
+ row.comment_count_text,
1343
+ row.comment_count_label
1344
+ ),
1345
+ reposts: maxHomeFeedCounter(row.repost_count_text, row.repost_count_label),
1346
+ };
1347
+ }
1348
+
1349
+ interface HomeFeedCommentCoverageSummary {
1350
+ threads: number;
1351
+ expected: number;
1352
+ collected: number;
1353
+ incomplete: number;
1354
+ unsupported: number;
1355
+ timedOut: number;
1356
+ details: string[];
1357
+ }
1358
+
1359
+ /**
1360
+ * Prove completeness from the browser runtime's per-post expansion result.
1361
+ * The independently parsed LinkedIn counter is authoritative: a stale runtime
1362
+ * that omits coverage, or an expansion selector that reads a different count,
1363
+ * fails closed instead of silently persisting a visible-only comment subset.
1364
+ */
1365
+ function summarizeHomeFeedCommentCoverage(
1366
+ rows: HomeFeedRow[]
1367
+ ): HomeFeedCommentCoverageSummary {
1368
+ const byPost = new Map<
1369
+ string,
1370
+ { advertised: number; coverage?: HomeFeedCommentCoverage }
1371
+ >();
1372
+ for (const row of rows) {
1373
+ if (!row?.id || parseHomeFeedCommentIdentity(row.id)) continue;
1374
+ const advertised = parseHomeFeedEngagement(row).comments ?? 0;
1375
+ const expected = Math.max(advertised, row.comment_coverage?.expected ?? 0);
1376
+ if (expected <= 0) continue;
1377
+ const context = buildHomeFeedRowContext(row);
1378
+ if (isHomeFeedRowNoise(row, context)) continue;
1379
+ const identityKey = homeFeedPostIdentityKey(row, context);
1380
+ if (!identityKey) continue;
1381
+ const existing = byPost.get(identityKey);
1382
+ if (!existing || (!existing.coverage && row.comment_coverage)) {
1383
+ byPost.set(identityKey, {
1384
+ advertised: expected,
1385
+ ...(row.comment_coverage ? { coverage: row.comment_coverage } : {}),
1386
+ });
1387
+ }
1388
+ }
1389
+
1390
+ let expected = 0;
1391
+ let collected = 0;
1392
+ let incomplete = 0;
1393
+ let unsupported = 0;
1394
+ let timedOut = 0;
1395
+ const details: string[] = [];
1396
+ for (const thread of byPost.values()) {
1397
+ expected += thread.advertised;
1398
+ if (!thread.coverage) {
1399
+ unsupported++;
1400
+ incomplete++;
1401
+ details.push(`${thread.advertised}/unknown/unknown`);
1402
+ continue;
1403
+ }
1404
+ collected += Math.min(thread.coverage.collected, thread.advertised);
1405
+ if (
1406
+ !thread.coverage.complete ||
1407
+ thread.coverage.expected !== thread.advertised ||
1408
+ thread.coverage.collected < thread.advertised
1409
+ ) {
1410
+ incomplete++;
1411
+ if (thread.coverage.timedOut) timedOut++;
1412
+ details.push(
1413
+ `${thread.advertised}/${thread.coverage.expected}/${thread.coverage.collected}`
1414
+ );
1415
+ }
1416
+ }
1417
+ return {
1418
+ threads: byPost.size,
1419
+ expected,
1420
+ collected,
1421
+ incomplete,
1422
+ unsupported,
1423
+ timedOut,
1424
+ details,
1425
+ };
1426
+ }
1427
+
1428
+ function homeFeedEngagementMetadata(
1429
+ counts: HomeFeedEngagement
1430
+ ): Record<string, number> {
1431
+ return {
1432
+ ...(counts.reactions ? { reactions: counts.reactions } : {}),
1433
+ ...(counts.comments ? { comments: counts.comments } : {}),
1434
+ ...(counts.reposts ? { reposts: counts.reposts } : {}),
1435
+ };
1436
+ }
1437
+
1438
+ function homeFeedEngagementScore(counts: HomeFeedEngagement): number {
1439
+ return Math.min(
1440
+ (counts.reactions ?? 0) +
1441
+ (counts.comments ?? 0) * 2 +
1442
+ (counts.reposts ?? 0) * 3,
1443
+ 100
1444
+ );
1445
+ }
1446
+
1447
+ function normalizeHomeFeedMedia(raw: unknown): Array<Record<string, unknown>> {
1448
+ if (!Array.isArray(raw)) return [];
1449
+ const seen = new Set<string>();
1450
+ const attachments: Array<Record<string, unknown>> = [];
1451
+ for (const item of raw) {
1452
+ if (!item || typeof item !== "object") continue;
1453
+ const candidate = item as HomeFeedMedia;
1454
+ if (!candidate.url) continue;
1455
+ let url: URL;
1456
+ try {
1457
+ url = new URL(candidate.url, "https://www.linkedin.com");
1458
+ } catch {
1459
+ continue;
1460
+ }
1461
+ if (
1462
+ url.protocol !== "https:" ||
1463
+ !(
1464
+ url.hostname === "media.licdn.com" ||
1465
+ url.hostname.endsWith(".licdn.com")
1466
+ ) ||
1467
+ /(?:profile-displayphoto|company-logo)/i.test(url.pathname) ||
1468
+ seen.has(url.href)
1469
+ ) {
1470
+ continue;
1471
+ }
1472
+ seen.add(url.href);
1473
+ const altText = candidate.alt_text?.trim();
1474
+ attachments.push({
1475
+ kind: "image",
1476
+ url: url.href,
1477
+ ...(altText ? { alt_text: altText } : {}),
1478
+ });
1479
+ }
1480
+ return attachments;
1481
+ }
1482
+
1483
+ function buildHomeFeedRowContext(row: HomeFeedRow): HomeFeedRowContext {
1484
+ const parsedAuthor = parseHomeFeedAuthorDetails(row.body ?? "");
1485
+ const domAuthor = cleanHomeFeedDisplayName(
1486
+ (row.author ?? "").trim().split(" • ")[0] ?? ""
1487
+ );
1488
+ const actorBanner =
1489
+ parsedAuthor.banner?.kind === "actor" ? parsedAuthor.banner : null;
1490
+ const controlAuthor = parseAuthorControlLabel(row.author_control_label);
1491
+ let banner = parsedAuthor.banner;
1492
+ if (actorBanner && controlAuthor) {
1493
+ if (nameKey(parsedAuthor.author) !== nameKey(controlAuthor)) banner = null;
1494
+ } else if (
1495
+ actorBanner &&
1496
+ domAuthor &&
1497
+ actorBanner.actor.localeCompare(domAuthor, undefined, {
1498
+ sensitivity: "accent",
1499
+ }) !== 0
1500
+ ) {
1501
+ banner = null;
1502
+ }
1503
+ const author =
1504
+ controlAuthor ||
1505
+ (banner ? parsedAuthor.author : "") ||
1506
+ domAuthor ||
1507
+ parsedAuthor.author;
1508
+ const links = normalizeHomeFeedLinks(row.links);
1509
+ const engagement = banner?.kind === "actor" ? banner : null;
1510
+ const authorSlug = resolveMemberSlug(links, author);
1511
+ const engagerSlug = engagement
1512
+ ? resolveMemberSlug(links, engagement.actor)
1513
+ : undefined;
1514
+ const profileUrlFor = (slug: string) => `https://www.linkedin.com/in/${slug}`;
1515
+ const counts = parseHomeFeedEngagement(row);
1516
+ const metadata: Record<string, unknown> = {
1517
+ author,
1518
+ ...homeFeedEngagementMetadata(counts),
1519
+ };
1520
+ if (engagement) {
1521
+ metadata.social_actor = engagement.actor;
1522
+ metadata.social_action = engagement.action;
1523
+ if (engagerSlug) {
1524
+ metadata.social_actor_slug = engagerSlug;
1525
+ metadata.social_actor_profile_url = profileUrlFor(engagerSlug);
1526
+ }
1527
+ }
1528
+ if (authorSlug) {
1529
+ metadata.author_linkedin_slug = authorSlug;
1530
+ metadata.author_profile_url = profileUrlFor(authorSlug);
1531
+ }
1532
+
1533
+ const embeddedUrn = row.post_identity?.match(
1534
+ /(?:(shareId|ugcPostId)=|urn:li:(activity|share|ugcPost):)(\d{6,})|urn:li:(groupPost):(\d+-\d{6,})/i
1535
+ );
1536
+ const embeddedId = embeddedUrn?.[3] ?? embeddedUrn?.[5];
1537
+ const embeddedNamespace = linkedInUrnNamespace(
1538
+ embeddedUrn?.[1] ?? embeddedUrn?.[2] ?? embeddedUrn?.[4] ?? ""
1539
+ );
1540
+ const postUrl = normalizeLinkedInPostUrl(
1541
+ row.post_url ??
1542
+ (embeddedId ? `urn:li:${embeddedNamespace}:${embeddedId}` : "")
1543
+ );
1544
+ return {
1545
+ author,
1546
+ authorSlug,
1547
+ postUrl: postUrl || undefined,
1548
+ metadata,
1549
+ };
1550
+ }
1551
+
1552
+ function isHomeFeedRowNoise(
1553
+ row: HomeFeedRow,
1554
+ context: HomeFeedRowContext
1555
+ ): boolean {
1556
+ return isHomeFeedNoise(row.body ?? "", {
1557
+ authorControlLabel: row.author_control_label,
1558
+ hasDurableIdentity: Boolean(homeFeedPostIdentityKey(row, context)),
1559
+ });
1560
+ }
1561
+
1562
+ /**
1563
+ * Map cs_scrape home-feed rows to event envelopes. A scraped permalink still
1564
+ * wins when a row carries one, but current cards expose none, so the canonical
1565
+ * post identity is normally the activity/share/ugcPost/groupPost id embedded in
1566
+ * `post_identity`. The scrape-only componentkey never becomes an event origin,
1567
+ * and a post without either durable identity is not emitted. Native comments
1568
+ * carry their own durable id and point at the stable parent-post origin.
1569
+ * Home-feed posts expose no reliable timestamp, so the caller stamps
1570
+ * occurred_at with the sync time.
1571
+ */
1572
+ export function buildHomeFeedEvents(
1573
+ rows: HomeFeedRow[],
1574
+ occurredAt: Date
1575
+ ): EventEnvelope[] {
1576
+ const seenOrigins = new Set<string>();
1577
+ const events: EventEnvelope[] = [];
1578
+ // Each row carries its own context: LinkedIn recycles the componentkey, so
1579
+ // keying per-row state on row.id would let one card's author and permalink
1580
+ // stand in for a different post that reused the key.
1581
+ const prepared: Array<{
1582
+ row: HomeFeedRow;
1583
+ body: string;
1584
+ context: HomeFeedRowContext;
1585
+ nativeIdentity?: HomeFeedCommentIdentity;
1586
+ parentCommentIdentity?: HomeFeedCommentIdentity;
1587
+ }> = [];
1588
+ const postContextsByIdentity = new Map<string, HomeFeedRowContext>();
1589
+ const commentContextsById = new Map<string, HomeFeedRowContext>();
1590
+ for (const row of rows) {
1591
+ if (!row?.id || !row.body) continue;
1592
+ const nativeIdentity = parseHomeFeedCommentIdentity(row.id);
1593
+ const enclosingCommentIdentity = parseHomeFeedCommentIdentity(
1594
+ row.parent_comment_identity
1595
+ );
1596
+ const parentCommentIdentity =
1597
+ enclosingCommentIdentity?.commentId !== nativeIdentity?.commentId
1598
+ ? enclosingCommentIdentity
1599
+ : undefined;
1600
+ const context = buildHomeFeedRowContext(row);
1601
+ if (!nativeIdentity && isHomeFeedRowNoise(row, context)) {
1602
+ continue;
1603
+ }
1604
+ prepared.push({
1605
+ row,
1606
+ body: row.body,
1607
+ context,
1608
+ ...(nativeIdentity ? { nativeIdentity } : {}),
1609
+ ...(parentCommentIdentity ? { parentCommentIdentity } : {}),
1610
+ });
1611
+ if (nativeIdentity) {
1612
+ commentContextsById.set(nativeIdentity.commentId, context);
1613
+ } else {
1614
+ const identityKey = homeFeedPostIdentityKey(row, context);
1615
+ if (identityKey && !postContextsByIdentity.has(identityKey)) {
1616
+ postContextsByIdentity.set(identityKey, context);
1617
+ }
1618
+ }
1619
+ }
1620
+ for (const {
1621
+ row,
1622
+ body,
1623
+ context,
1624
+ nativeIdentity,
1625
+ parentCommentIdentity,
1626
+ } of prepared) {
1627
+ if (nativeIdentity) {
1628
+ const originId = `li_comment_${nativeIdentity.commentId}`;
1629
+ if (seenOrigins.has(originId)) continue;
1630
+ seenOrigins.add(originId);
1631
+ const parentIdentityKey = `${nativeIdentity.parentNamespace}:${nativeIdentity.parentId}`;
1632
+ const parentOriginId = homeFeedPostOriginId(parentIdentityKey);
1633
+ const immediateParentOriginId = parentCommentIdentity
1634
+ ? `li_comment_${parentCommentIdentity.commentId}`
1635
+ : parentOriginId;
1636
+ const parent = postContextsByIdentity.get(parentIdentityKey);
1637
+ const parentComment = parentCommentIdentity
1638
+ ? commentContextsById.get(parentCommentIdentity.commentId)
1639
+ : undefined;
1640
+ const sourceUrl =
1641
+ parent?.postUrl ??
1642
+ normalizeLinkedInPostUrl(
1643
+ `urn:li:${nativeIdentity.parentNamespace}:${nativeIdentity.parentId}`
1644
+ );
1645
+ const counts = parseHomeFeedEngagement(row);
1646
+ const commentMetadata: Record<string, unknown> = {
1647
+ ...context.metadata,
1648
+ ...homeFeedEngagementMetadata(counts),
1649
+ parent_post_origin_id: parentOriginId,
1650
+ comment_urn: nativeIdentity.urn,
1651
+ comment_id: nativeIdentity.commentId,
1652
+ parent_activity_id: nativeIdentity.parentId,
1653
+ parent_activity_namespace: nativeIdentity.parentNamespace,
1654
+ };
1655
+ if (parentCommentIdentity) {
1656
+ commentMetadata.parent_comment_origin_id = immediateParentOriginId;
1657
+ commentMetadata.parent_comment_id = parentCommentIdentity.commentId;
1658
+ commentMetadata.is_reply = true;
1659
+ if (parentComment) {
1660
+ commentMetadata.parent_comment_author = parentComment.author;
1661
+ if (parentComment.authorSlug) {
1662
+ commentMetadata.parent_comment_author_linkedin_slug =
1663
+ parentComment.authorSlug;
1664
+ commentMetadata.parent_comment_author_profile_url = `https://www.linkedin.com/in/${parentComment.authorSlug}`;
1665
+ }
1666
+ }
1667
+ }
1668
+ if (parent) {
1669
+ commentMetadata.parent_author = parent.author;
1670
+ if (parent.authorSlug) {
1671
+ commentMetadata.parent_author_linkedin_slug = parent.authorSlug;
1672
+ commentMetadata.parent_author_profile_url = `https://www.linkedin.com/in/${parent.authorSlug}`;
1673
+ }
1674
+ }
1675
+ events.push({
1676
+ origin_id: originId,
1677
+ origin_parent_id: immediateParentOriginId,
1678
+ payload_text: body,
1679
+ attachments: normalizeHomeFeedMedia(row.comment_media),
1680
+ author_name: context.author,
1681
+ occurred_at: occurredAt,
1682
+ origin_type: "comment",
1683
+ ...(sourceUrl ? { source_url: sourceUrl } : {}),
1684
+ score: homeFeedEngagementScore(counts),
1685
+ metadata: commentMetadata,
1686
+ });
1687
+ continue;
1688
+ }
1689
+
1690
+ const identityKey = homeFeedPostIdentityKey(row, context);
1691
+ if (!identityKey) continue;
1692
+ const originId = homeFeedPostOriginId(identityKey);
1693
+ if (seenOrigins.has(originId)) continue;
1694
+ seenOrigins.add(originId);
1695
+ const counts = parseHomeFeedEngagement(row);
1696
+ // The identity key already proved a durable post id, so a canonical URL is
1697
+ // always derivable. Deriving it from the key is the normal path now that
1698
+ // post_url comes back empty; it also covers a scraped permalink that did
1699
+ // not normalize (post_url holding the bare /feed/ surface).
1700
+ const sourceUrl =
1701
+ context.postUrl ?? normalizeLinkedInPostUrl(`urn:li:${identityKey}`);
1702
+
1703
+ events.push({
1704
+ origin_id: originId,
1705
+ payload_text: body,
1706
+ attachments: normalizeHomeFeedMedia(row.post_media),
1707
+ author_name: context.author,
1708
+ // Feed posts expose no reliable timestamp; use the sync time.
1709
+ occurred_at: occurredAt,
1710
+ origin_type: "post",
1711
+ score: homeFeedEngagementScore(counts),
1712
+ // source_url is the durable post handle action callers (prepare_comment)
1713
+ // resolve directly.
1714
+ ...(sourceUrl ? { source_url: sourceUrl } : {}),
1715
+ metadata: context.metadata,
1716
+ });
1717
+ }
1718
+ return events;
1719
+ }
1720
+
1721
+ // ── prepare_comment handoff (browser stage, human submits) ───────────
1722
+
1723
+ type PrepareCommentResult = {
1724
+ prepared: boolean;
1725
+ tab_id: number;
1726
+ post_url: string;
1727
+ body: string;
1728
+ method: "evaluate";
1729
+ /** Whether the in-page handoff banner was injected. */
1730
+ banner_shown?: boolean;
1731
+ /** Truncated reason shown on the banner (if any). */
1732
+ reason_preview?: string;
1733
+ message: string;
1734
+ };
1735
+
1736
+ /**
1737
+ * Canonical casing for the LinkedIn URN namespace an id came from. share and
1738
+ * ugcPost and groupPost ids live in different id spaces than activity ids, so
1739
+ * the namespace has to survive normalization; /feed/update/ resolves them all.
1740
+ */
1741
+ function linkedInUrnNamespace(
1742
+ token: string
1743
+ ): "activity" | "share" | "ugcPost" | "groupPost" {
1744
+ const normalized = token.toLowerCase();
1745
+ if (normalized === "shareid" || normalized === "share") return "share";
1746
+ if (normalized === "ugcpostid" || normalized === "ugcpost") return "ugcPost";
1747
+ if (normalized === "grouppost") return "groupPost";
1748
+ return "activity";
1749
+ }
1750
+
1751
+ /**
1752
+ * Normalize a post URL or activity id into a linkedin.com update URL.
1753
+ * Accepts full URLs, `urn:li:activity:…` / `urn:li:share:…` /
1754
+ * `urn:li:ugcPost:…` / `urn:li:groupPost:<group>-<post>`, bare activity digits,
1755
+ * or `/feed/update/…` paths.
1756
+ */
1757
+ export function normalizeLinkedInPostUrl(input: string): string | null {
1758
+ const raw = input.trim();
1759
+ if (!raw) return null;
1760
+
1761
+ // Bare activity id (digits only, possibly with li_post_ prefix from events).
1762
+ const bareId = raw.replace(/^li_post_/, "");
1763
+ if (/^\d{6,}$/.test(bareId)) {
1764
+ return `https://www.linkedin.com/feed/update/urn:li:activity:${bareId}`;
1765
+ }
1766
+
1767
+ // Post URNs or shorthand, with a compound id only for groupPost.
1768
+ const urnMatch = raw.match(
1769
+ /(?:urn:li:)?(?:(activity|share|ugcPost):(\d{6,})|(groupPost):(\d+-\d{6,}))/i
1770
+ );
1771
+ if (urnMatch && !raw.includes("://") && !raw.startsWith("/")) {
1772
+ const ns = linkedInUrnNamespace(urnMatch[1] ?? urnMatch[3] ?? "");
1773
+ return `https://www.linkedin.com/feed/update/urn:li:${ns}:${urnMatch[2] ?? urnMatch[4] ?? ""}`;
1774
+ }
1775
+
1776
+ try {
1777
+ const withScheme = raw.startsWith("//")
1778
+ ? `https:${raw}`
1779
+ : raw.startsWith("/")
1780
+ ? `https://www.linkedin.com${raw}`
1781
+ : raw.includes("://")
1782
+ ? raw
1783
+ : `https://${raw}`;
1784
+ const u = new URL(withScheme);
1785
+ if (u.protocol !== "https:" && u.protocol !== "http:") return null;
1786
+ u.protocol = "https:";
1787
+ const host = u.hostname.toLowerCase().replace(/^www\./, "");
1788
+ if (host !== "linkedin.com" && !host.endsWith(".linkedin.com")) {
1789
+ return null;
1790
+ }
1791
+ // Prefer canonical feed/update URLs when we can extract a post id, keeping
1792
+ // whichever URN namespace the source URL used.
1793
+ const urnInUrl = `${u.pathname}${u.search}`.match(
1794
+ /(?:urn(?::|%3A)li(?::|%3A))?(?:(activity|share|ugcPost)(?::|%3A|-)(\d{6,})|(groupPost)(?::|%3A|-)(\d+-\d{6,}))/i
1795
+ );
1796
+ if (urnInUrl) {
1797
+ const ns = linkedInUrnNamespace(urnInUrl[1] ?? urnInUrl[3] ?? "");
1798
+ return `https://www.linkedin.com/feed/update/urn:li:${ns}:${urnInUrl[2] ?? urnInUrl[4] ?? ""}`;
1799
+ }
1800
+ return null;
1801
+ } catch {
1802
+ return null;
1803
+ }
1804
+ }
1805
+
1806
+ function isLinkedInShortPostUrl(input: string | undefined): boolean {
1807
+ if (!input) return false;
1808
+ try {
1809
+ const url = new URL(input);
1810
+ return (
1811
+ url.protocol === "https:" &&
1812
+ url.hostname === "lnkd.in" &&
1813
+ url.pathname.startsWith("/p/")
1814
+ );
1815
+ } catch {
1816
+ return false;
1817
+ }
1818
+ }
1819
+
1820
+ /** Resolve LinkedIn's Copy-link short URL to its durable post URN URL. */
1821
+ export async function resolveLinkedInShortPostUrl(
1822
+ input: string,
1823
+ fetchImpl: typeof fetch = fetch
1824
+ ): Promise<string | null> {
1825
+ let shortUrl: URL;
1826
+ try {
1827
+ shortUrl = new URL(input);
1828
+ } catch {
1829
+ return null;
1830
+ }
1831
+ if (!isLinkedInShortPostUrl(shortUrl.href)) return null;
1832
+
1833
+ try {
1834
+ const response = await fetchImpl(shortUrl, {
1835
+ method: "HEAD",
1836
+ redirect: "manual",
1837
+ signal: AbortSignal.timeout(5_000),
1838
+ });
1839
+ const location = response.headers.get("location");
1840
+ if (!location) return normalizeLinkedInPostUrl(response.url);
1841
+ return normalizeLinkedInPostUrl(new URL(location, shortUrl).href);
1842
+ } catch {
1843
+ return null;
1844
+ }
1845
+ }
1846
+
1847
+ export async function resolveHomeFeedPostUrls(
1848
+ rows: HomeFeedRow[],
1849
+ fetchImpl: typeof fetch = fetch
1850
+ ): Promise<HomeFeedRow[]> {
1851
+ return Promise.all(
1852
+ rows.map(async (row) => {
1853
+ const postUrl = row.post_url?.trim();
1854
+ if (!postUrl || normalizeLinkedInPostUrl(postUrl)) return row;
1855
+ const resolved = await resolveLinkedInShortPostUrl(postUrl, fetchImpl);
1856
+ return resolved ? { ...row, post_url: resolved } : row;
1857
+ })
1858
+ );
1859
+ }
1860
+
1861
+ function unresolvedHomeFeedPostRows(rows: HomeFeedRow[]): HomeFeedRow[] {
1862
+ return rows.filter((row) => {
1863
+ if (!row?.id || !row.body) return false;
1864
+ const context = buildHomeFeedRowContext(row);
1865
+ if (
1866
+ parseHomeFeedCommentIdentity(row.id) ||
1867
+ isHomeFeedRowNoise(row, context)
1868
+ ) {
1869
+ return false;
1870
+ }
1871
+ return !homeFeedPostIdentityKey(row, context);
1872
+ });
1873
+ }
1874
+
1875
+ function unresolvedHomeFeedShortUrlCount(rows: HomeFeedRow[]): number {
1876
+ return rows.filter((row) => {
1877
+ if (!row?.id || !row.body || parseHomeFeedCommentIdentity(row.id)) {
1878
+ return false;
1879
+ }
1880
+ const context = buildHomeFeedRowContext(row);
1881
+ return (
1882
+ !isHomeFeedRowNoise(row, context) && isLinkedInShortPostUrl(row.post_url)
1883
+ );
1884
+ }).length;
1885
+ }
1886
+
1887
+ /** True when navigate landed on login / authwall rather than the post. */
1888
+ export function isLinkedInAuthWall(url: string | null | undefined): boolean {
1889
+ if (!url) return false;
1890
+ const lower = url.toLowerCase();
1891
+ return (
1892
+ lower.includes("/login") ||
1893
+ lower.includes("/authwall") ||
1894
+ lower.includes("/checkpoint") ||
1895
+ lower.includes("uas/login")
1896
+ );
1897
+ }
1898
+
1899
+ function chromeOriginsInput(): { allowed_origins: string[] } {
1900
+ return { allowed_origins: LINKEDIN_ALLOWED_ORIGINS };
1901
+ }
1902
+
1903
+ /** Cap the explanation shown in the in-page banner. */
1904
+ export const truncateHandoffReason = truncateSharedHandoffReason;
1905
+
1906
+ const LINKEDIN_HANDOFF_INSTRUCTION =
1907
+ "Review the draft and click Post yourself \u2014 Lobu did not submit.";
1908
+ const LINKEDIN_HANDOFF_FOOTER =
1909
+ "After posting or editing, record the outcome in Lobu Activity. You can also reject it with a reason.";
1910
+ const LINKEDIN_HANDOFF_COMPOSER_SELECTORS = [
1911
+ ".comments-comment-box-comment__text-editor .ql-editor",
1912
+ ".comments-comment-box__form .ql-editor",
1913
+ 'div.ql-editor[contenteditable="true"]',
1914
+ 'div[role="textbox"][contenteditable="true"]',
1915
+ ];
1916
+ const LINKEDIN_HANDOFF_HOST_SELECTORS = [".comments-comment-box", "form"];
1917
+
1918
+ /**
1919
+ * JS expression: inject a small Lobu handoff banner on the page.
1920
+ * The banner points the user to the side panel for the run details.
1921
+ * Best-effort; LinkedIn re-renders may remove it.
1922
+ */
1923
+ export function buildInjectHandoffBannerExpression(opts: {
1924
+ reason?: string;
1925
+ title?: string;
1926
+ }): string {
1927
+ return buildSharedHandoffBannerExpression({
1928
+ reason: opts.reason,
1929
+ title: opts.title ?? "Lobu staged this comment",
1930
+ instruction: LINKEDIN_HANDOFF_INSTRUCTION,
1931
+ footer: LINKEDIN_HANDOFF_FOOTER,
1932
+ composerSelectors: LINKEDIN_HANDOFF_COMPOSER_SELECTORS,
1933
+ hostSelectors: LINKEDIN_HANDOFF_HOST_SELECTORS,
1934
+ });
1935
+ }
1936
+
1937
+ /** JS expression: open the comment composer if collapsed, then fill it. */
1938
+ export function buildFillCommentExpression(body: string): string {
1939
+ // JSON.stringify for safe embedding of the draft text.
1940
+ const textLit = JSON.stringify(body);
1941
+ return `(async()=>{
1942
+ const text = ${textLit};
1943
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1944
+
1945
+ function visible(el) {
1946
+ if (!el) return false;
1947
+ const s = window.getComputedStyle(el);
1948
+ if (s.display === 'none' || s.visibility === 'hidden' || s.opacity === '0') return false;
1949
+ const r = el.getBoundingClientRect();
1950
+ return r.width > 0 && r.height > 0;
1951
+ }
1952
+
1953
+ function findComposer() {
1954
+ const selectors = [
1955
+ '.comments-comment-box-comment__text-editor .ql-editor',
1956
+ '.comments-comment-box__form .ql-editor',
1957
+ 'form.comments-comment-box__form div.ql-editor',
1958
+ 'div.comments-comment-texteditor .ql-editor',
1959
+ 'div.ql-editor[contenteditable="true"]',
1960
+ 'div[role="textbox"][contenteditable="true"]',
1961
+ 'div[contenteditable="true"][aria-label*="comment" i]',
1962
+ 'div[contenteditable="true"][data-placeholder*="comment" i]',
1963
+ ];
1964
+ for (const sel of selectors) {
1965
+ try {
1966
+ const el = document.querySelector(sel);
1967
+ if (el && visible(el)) return el;
1968
+ } catch (_) {}
1969
+ }
1970
+ // Broader: any visible contenteditable textbox in a comments region.
1971
+ const regions = document.querySelectorAll(
1972
+ '.comments-comment-box, .feed-shared-update-v2__comments-container, [class*="comments-comment"]'
1973
+ );
1974
+ for (const region of regions) {
1975
+ const el = region.querySelector('[contenteditable="true"]');
1976
+ if (el && visible(el)) return el;
1977
+ }
1978
+ return null;
1979
+ }
1980
+
1981
+ // SAFETY: never click submit controls. Only the human posts.
1982
+ function isSubmitLabel(label) {
1983
+ const n = String(label || '').replace(/\\s+/g, ' ').trim();
1984
+ if (/^(post|submit|send|publish|share)$/i.test(n)) return true;
1985
+ if (/^(post|submit|send)\\s+(comment|reply)$/i.test(n)) return true;
1986
+ return false;
1987
+ }
1988
+ function isOpenLabel(label) {
1989
+ if (isSubmitLabel(label)) return false;
1990
+ const n = String(label || '').replace(/\\s+/g, ' ').trim();
1991
+ return (
1992
+ /^comment$/i.test(n) ||
1993
+ /^comments$/i.test(n) ||
1994
+ /^comment on /i.test(n) ||
1995
+ /^leave a comment/i.test(n) ||
1996
+ /^post a comment/i.test(n)
1997
+ );
1998
+ }
1999
+
2000
+ function openComposer() {
2001
+ if (findComposer()) return true;
2002
+ const nodes = Array.from(
2003
+ document.querySelectorAll('button, [role="button"]')
2004
+ );
2005
+ for (const el of nodes) {
2006
+ if (!visible(el)) continue;
2007
+ const label = (
2008
+ el.getAttribute('aria-label') ||
2009
+ el.innerText ||
2010
+ el.textContent ||
2011
+ ''
2012
+ )
2013
+ .replace(/\\s+/g, ' ')
2014
+ .trim();
2015
+ if (isSubmitLabel(label)) continue;
2016
+ if (isOpenLabel(label)) {
2017
+ el.click();
2018
+ return true;
2019
+ }
2020
+ }
2021
+ return false;
2022
+ }
2023
+
2024
+ openComposer();
2025
+ await sleep(600);
2026
+ let composer = findComposer();
2027
+ if (!composer) {
2028
+ openComposer();
2029
+ await sleep(800);
2030
+ composer = findComposer();
2031
+ }
2032
+ if (!composer) {
2033
+ return { ok: false, reason: 'composer_not_found' };
2034
+ }
2035
+
2036
+ const existing = (composer.innerText || composer.textContent || '').trim();
2037
+ if (existing && existing !== text.trim()) {
2038
+ return { ok: false, reason: 'existing_draft', submitted: false };
2039
+ }
2040
+ if (existing === text.trim()) {
2041
+ return { ok: true, reason: 'already_prepared', preview: existing.slice(0, 120), submitted: false };
2042
+ }
2043
+ composer.focus();
2044
+ try {
2045
+ document.execCommand('selectAll', false, undefined);
2046
+ document.execCommand('delete', false, undefined);
2047
+ } catch (_) {
2048
+ composer.textContent = '';
2049
+ }
2050
+ // insertText only — never Enter / Cmd+Enter (those can submit on LinkedIn).
2051
+ const inserted = document.execCommand('insertText', false, text);
2052
+ if (!inserted) {
2053
+ composer.textContent = text;
2054
+ composer.dispatchEvent(new InputEvent('input', { bubbles: true, data: text, inputType: 'insertText' }));
2055
+ }
2056
+ await sleep(100);
2057
+ const got = (composer.innerText || composer.textContent || '').trim();
2058
+ // Scroll composer into view so the human sees the draft. Do NOT click Post.
2059
+ try { composer.scrollIntoView({ block: 'center', behavior: 'smooth' }); } catch (_) {}
2060
+ return {
2061
+ ok: got.length > 0,
2062
+ reason: got.length > 0 ? 'typed' : 'empty_after_type',
2063
+ preview: got.slice(0, 120),
2064
+ used_insert_text: !!inserted,
2065
+ submitted: false,
2066
+ };
2067
+ })()`;
2068
+ }
2069
+
2070
+ /**
2071
+ * Stage a LinkedIn comment in the exact user-opened page: activate → fill
2072
+ * composer. The ordinary Lobu notification is created by the calling Automation.
2073
+ *
2074
+ * HARD RULE — never auto-post:
2075
+ * - never click Post / Submit / Send
2076
+ * - never press Enter / Cmd+Enter after typing
2077
+ * - only open the composer (Comment) + type draft text
2078
+ * The human must click Post themselves.
2079
+ */
2080
+ export async function prepareLinkedInComment(
2081
+ dispatcher: ChromeActionDispatcher,
2082
+ opts: {
2083
+ postUrl: string;
2084
+ body: string;
2085
+ /** Short explanation for the in-page banner. */
2086
+ reason?: string;
2087
+ /** Inject in-page handoff banner (default true). */
2088
+ banner?: boolean;
2089
+ }
2090
+ ): Promise<PrepareCommentResult> {
2091
+ const body = opts.body.trim();
2092
+ if (!body) {
2093
+ throw new Error("prepare_comment: body must be non-empty");
2094
+ }
2095
+ const postUrl = normalizeLinkedInPostUrl(opts.postUrl);
2096
+ if (!postUrl) {
2097
+ throw new Error(
2098
+ `prepare_comment: invalid post_url / activity_id: ${JSON.stringify(opts.postUrl)}`
2099
+ );
2100
+ }
2101
+ const banner = opts.banner !== false;
2102
+ const reasonPreview = truncateHandoffReason(opts.reason);
2103
+
2104
+ const nav = await dispatcher.dispatch<{
2105
+ tab_id?: number;
2106
+ current_url?: string;
2107
+ title?: string;
2108
+ }>("navigate", {
2109
+ // LinkedIn rewrites /feed/update/<urn> to its trailing-slash form after
2110
+ // load, and an activated tab is only drivable on its exact URL, so the
2111
+ // caller's activation target is this same trailing-slash page URL.
2112
+ url: `${postUrl}/`,
2113
+ require_page_activation: true,
2114
+ ...chromeOriginsInput(),
2115
+ });
2116
+ const tabId = nav.tab_id;
2117
+ if (typeof tabId !== "number") {
2118
+ throw new Error("prepare_comment: navigate did not return tab_id");
2119
+ }
2120
+ if (isLinkedInAuthWall(nav.current_url)) {
2121
+ throw new Error(
2122
+ `Not logged into LinkedIn (landed on ${nav.current_url}). Sign in in the paired Chrome profile, then retry.`
2123
+ );
2124
+ }
2125
+
2126
+ // Give the post chrome a beat to hydrate the social-action bar.
2127
+ try {
2128
+ await dispatcher.dispatch("wait_for_selector", {
2129
+ tab_id: tabId,
2130
+ selector:
2131
+ 'button, [role="button"], .feed-shared-social-action-bar, .comments-comment-box',
2132
+ timeout_ms: 8000,
2133
+ ...chromeOriginsInput(),
2134
+ });
2135
+ } catch {
2136
+ // Non-fatal — the DOM fill below still checks the composer.
2137
+ }
2138
+
2139
+ // Fill only through the DOM, which can read the composer before writing. An
2140
+ // accessibility textbox does not expose an existing draft, so there is no
2141
+ // type_ref fallback.
2142
+ let evalOut:
2143
+ | {
2144
+ value?: {
2145
+ ok?: boolean;
2146
+ reason?: string;
2147
+ preview?: string;
2148
+ submitted?: boolean;
2149
+ };
2150
+ exception?: string;
2151
+ }
2152
+ | undefined;
2153
+ try {
2154
+ evalOut = await dispatcher.dispatch<NonNullable<typeof evalOut>>(
2155
+ "evaluate",
2156
+ {
2157
+ tab_id: tabId,
2158
+ expression: buildFillCommentExpression(body),
2159
+ await_promise: true,
2160
+ ...chromeOriginsInput(),
2161
+ }
2162
+ );
2163
+ } catch {
2164
+ // Failure is reported below; never fill an editor whose contents cannot be checked.
2165
+ }
2166
+ const value = evalOut?.value;
2167
+ if (value?.reason === "existing_draft") {
2168
+ throw new Error(
2169
+ "prepare_comment: preserving your existing draft; clear it before preparing another comment"
2170
+ );
2171
+ }
2172
+ if (value?.submitted === true) {
2173
+ throw new Error(
2174
+ "prepare_comment: fill expression reported submitted=true — aborting (must never auto-post)"
2175
+ );
2176
+ }
2177
+ if (evalOut?.exception || !value?.ok) {
2178
+ throw new Error(
2179
+ "prepare_comment: could not fill comment composer (the DOM draft could not be verified). Is the post still available and commentable?"
2180
+ );
2181
+ }
2182
+
2183
+ let bannerShown = false;
2184
+ if (banner) {
2185
+ try {
2186
+ const bannerOut = await dispatcher.dispatch<{
2187
+ value?: { ok?: boolean; anchored?: boolean };
2188
+ exception?: string;
2189
+ }>("evaluate", {
2190
+ tab_id: tabId,
2191
+ expression: buildInjectHandoffBannerExpression({
2192
+ reason: reasonPreview,
2193
+ }),
2194
+ await_promise: true,
2195
+ ...chromeOriginsInput(),
2196
+ });
2197
+ bannerShown = bannerOut.value?.ok === true && !bannerOut.exception;
2198
+ } catch {
2199
+ // Banner is best-effort; draft is already staged.
2200
+ }
2201
+ }
2202
+
2203
+ return {
2204
+ prepared: true,
2205
+ tab_id: tabId,
2206
+ post_url: postUrl,
2207
+ body,
2208
+ method: "evaluate",
2209
+ banner_shown: bannerShown,
2210
+ reason_preview: reasonPreview,
2211
+ message:
2212
+ "Comment staged in your browser. Review the draft and click Post yourself — Lobu did not submit.",
2213
+ };
2214
+ }
2215
+
2216
+ // ── verify_staged_comment (read: did the human Post?) ────────────────
2217
+
2218
+ export type ScrapedComment = {
2219
+ author?: string;
2220
+ text: string;
2221
+ };
2222
+
2223
+ export type VerifyStagedCommentResult = {
2224
+ /** True when a visible comment matches the expected body. */
2225
+ verified: boolean;
2226
+ post_url: string;
2227
+ body: string;
2228
+ tab_id?: number;
2229
+ comments_scanned: number;
2230
+ match?: {
2231
+ author?: string;
2232
+ text_preview: string;
2233
+ match_kind: "exact" | "prefix" | "contains";
2234
+ };
2235
+ /** Why verification failed or was inconclusive. */
2236
+ reason?: string;
2237
+ message: string;
2238
+ };
2239
+
2240
+ /** Collapse whitespace / case for comment body comparison. */
2241
+ export function normalizeCommentMatchText(text: string): string {
2242
+ return text
2243
+ .normalize("NFKC")
2244
+ .replace(/\u00a0/g, " ")
2245
+ .replace(/\s+/g, " ")
2246
+ .trim()
2247
+ .toLowerCase();
2248
+ }
2249
+
2250
+ /**
2251
+ * Match staged draft text against a scraped comment body.
2252
+ * Allows LinkedIn "…more" truncation and longer surrounding blocks.
2253
+ */
2254
+ export function commentBodiesMatch(
2255
+ expected: string,
2256
+ actual: string
2257
+ ): { ok: true; kind: "exact" | "prefix" | "contains" } | { ok: false } {
2258
+ const e = normalizeCommentMatchText(expected);
2259
+ const a = normalizeCommentMatchText(actual);
2260
+ if (!e || !a) return { ok: false };
2261
+ if (a === e) return { ok: true, kind: "exact" };
2262
+ // Partial matches must be distinctive enough not to verify common phrases.
2263
+ if (Math.min(e.length, a.length) < 24) return { ok: false };
2264
+ // LinkedIn may truncate the visible comment before its "See more" control.
2265
+ if (e.startsWith(a)) return { ok: true, kind: "prefix" };
2266
+ // Some DOM variants wrap the comment body in a longer text block.
2267
+ if (a.includes(e)) return { ok: true, kind: "contains" };
2268
+ return { ok: false };
2269
+ }
2270
+
2271
+ /**
2272
+ * JS expression: scrape visible comments on a LinkedIn post/permalink page.
2273
+ * Best-effort DOM selectors — LinkedIn class names churn.
2274
+ */
2275
+ export function buildScrapeCommentsExpression(): string {
2276
+ return `(() => {
2277
+ const roots = [
2278
+ ...document.querySelectorAll('article.comments-comment-item'),
2279
+ ...document.querySelectorAll('.comments-comment-item'),
2280
+ ...document.querySelectorAll('.comments-comment-entity'),
2281
+ ...document.querySelectorAll('[class*="comments-comment-item"]'),
2282
+ ];
2283
+ const seen = new Set();
2284
+ const out = [];
2285
+ for (const root of roots) {
2286
+ if (!(root instanceof HTMLElement)) continue;
2287
+ if (seen.has(root)) continue;
2288
+ seen.add(root);
2289
+ const textEl =
2290
+ root.querySelector('.update-components-text') ||
2291
+ root.querySelector('.comments-comment-item__main-content') ||
2292
+ root.querySelector('[class*="comment-item__main"]') ||
2293
+ root.querySelector('.feed-shared-inline-show-more-text') ||
2294
+ root.querySelector('[data-test-id="main-feed-activity-card"] span[dir="ltr"]') ||
2295
+ root.querySelector('span[dir="ltr"]');
2296
+ let text = (textEl?.innerText || textEl?.textContent || '').replace(/\\s+/g, ' ').trim();
2297
+ // Drop "See more" / "…more" chrome.
2298
+ text = text.replace(/\\s*…?\\s*see more\\s*$/i, '').replace(/\\s*…more\\s*$/i, '').trim();
2299
+ if (!text || text.length < 2) continue;
2300
+ const authorEl =
2301
+ root.querySelector('.comments-post-meta__name-text') ||
2302
+ root.querySelector('.comments-comment-meta__description-title') ||
2303
+ root.querySelector('a[href*="/in/"] span[aria-hidden="true"]') ||
2304
+ root.querySelector('a[href*="/in/"]');
2305
+ const author = (authorEl?.textContent || '').replace(/\\s+/g, ' ').trim() || undefined;
2306
+ out.push({ author, text: text.slice(0, 2000) });
2307
+ if (out.length >= 80) break;
2308
+ }
2309
+ return { ok: true, comments: out, count: out.length, url: location.href };
2310
+ })()`;
2311
+ }
2312
+
2313
+ /**
2314
+ * Re-open a LinkedIn post and check whether a comment matching `body` is visible.
2315
+ * Read-only — never types or submits. Matching is best-effort DOM scrape.
2316
+ */
2317
+ export async function verifyLinkedInStagedComment(
2318
+ dispatcher: ChromeActionDispatcher,
2319
+ opts: {
2320
+ postUrl: string;
2321
+ body: string;
2322
+ /** Require the author's display name to include this (case-insensitive). */
2323
+ author_hint?: string;
2324
+ focus?: boolean;
2325
+ }
2326
+ ): Promise<VerifyStagedCommentResult> {
2327
+ const body = opts.body.trim();
2328
+ if (!body) {
2329
+ throw new Error("verify_staged_comment: body must be non-empty");
2330
+ }
2331
+ const postUrl = normalizeLinkedInPostUrl(opts.postUrl);
2332
+ if (!postUrl) {
2333
+ throw new Error(
2334
+ `verify_staged_comment: invalid post_url / activity_id: ${JSON.stringify(opts.postUrl)}`
2335
+ );
2336
+ }
2337
+ const authorHint = opts.author_hint?.trim().toLowerCase() || undefined;
2338
+ const focus = opts.focus !== false;
2339
+
2340
+ const nav = await dispatcher.dispatch<{
2341
+ tab_id?: number;
2342
+ current_url?: string;
2343
+ }>("navigate", {
2344
+ url: postUrl,
2345
+ new_tab: true,
2346
+ wait_for_load: true,
2347
+ ...chromeOriginsInput(),
2348
+ });
2349
+ const tabId = nav.tab_id;
2350
+ if (typeof tabId !== "number") {
2351
+ throw new Error("verify_staged_comment: navigate did not return tab_id");
2352
+ }
2353
+ if (isLinkedInAuthWall(nav.current_url)) {
2354
+ throw new Error(
2355
+ `Not logged into LinkedIn (landed on ${nav.current_url}). Sign in in the paired Chrome profile, then retry.`
2356
+ );
2357
+ }
2358
+
2359
+ try {
2360
+ await dispatcher.dispatch("wait_for_selector", {
2361
+ tab_id: tabId,
2362
+ selector:
2363
+ ".comments-comment-item, .comments-comment-entity, .feed-shared-update-v2, article",
2364
+ timeout_ms: 8000,
2365
+ ...chromeOriginsInput(),
2366
+ });
2367
+ } catch {
2368
+ // Non-fatal — page may still expose comments.
2369
+ }
2370
+
2371
+ // Best-effort: expand the comments section / load more (never Post).
2372
+ try {
2373
+ await dispatcher.dispatch("evaluate", {
2374
+ tab_id: tabId,
2375
+ expression: `(() => {
2376
+ const labels = [/^(load|show|view) more comments/i, /^\\d+\\s+comments?$/i, /^comments$/i];
2377
+ const clickables = [
2378
+ ...document.querySelectorAll('button, [role="button"], a'),
2379
+ ];
2380
+ const control = clickables.find((el) => {
2381
+ const n = (el.textContent || '').replace(/\\s+/g, ' ').trim();
2382
+ return n && labels.some((re) => re.test(n));
2383
+ });
2384
+ if (control) {
2385
+ try { control.click(); } catch (_) {}
2386
+ }
2387
+ return !!control;
2388
+ })()`,
2389
+ await_promise: false,
2390
+ ...chromeOriginsInput(),
2391
+ });
2392
+ } catch {
2393
+ // Expand is optional.
2394
+ }
2395
+
2396
+ try {
2397
+ await dispatcher.dispatch("wait_for_selector", {
2398
+ tab_id: tabId,
2399
+ selector: ".comments-comment-item, .comments-comment-entity",
2400
+ timeout_ms: 3000,
2401
+ ...chromeOriginsInput(),
2402
+ });
2403
+ } catch {
2404
+ // A post can legitimately have no comments.
2405
+ }
2406
+
2407
+ if (focus) {
2408
+ try {
2409
+ await dispatcher.dispatch("focus_tab", {
2410
+ tab_id: tabId,
2411
+ draw_attention: true,
2412
+ ...chromeOriginsInput(),
2413
+ });
2414
+ } catch {
2415
+ // Focus is best-effort.
2416
+ }
2417
+ }
2418
+
2419
+ let comments: ScrapedComment[] = [];
2420
+ try {
2421
+ const scrape = await dispatcher.dispatch<{
2422
+ value?: { comments?: unknown; count?: number };
2423
+ exception?: string;
2424
+ }>("evaluate", {
2425
+ tab_id: tabId,
2426
+ expression: buildScrapeCommentsExpression(),
2427
+ await_promise: true,
2428
+ ...chromeOriginsInput(),
2429
+ });
2430
+ if (scrape.exception) {
2431
+ return {
2432
+ verified: false,
2433
+ post_url: postUrl,
2434
+ body,
2435
+ tab_id: tabId,
2436
+ comments_scanned: 0,
2437
+ reason: `scrape_exception: ${scrape.exception}`,
2438
+ message:
2439
+ "Could not scrape comments on the page. Open the post in Chrome and confirm the comment is visible.",
2440
+ };
2441
+ }
2442
+ const raw = scrape.value?.comments;
2443
+ if (Array.isArray(raw)) {
2444
+ comments = raw.filter(
2445
+ (c): c is ScrapedComment =>
2446
+ !!c &&
2447
+ typeof c === "object" &&
2448
+ typeof c.text === "string" &&
2449
+ c.text.trim().length > 0 &&
2450
+ (c.author === undefined || typeof c.author === "string")
2451
+ );
2452
+ }
2453
+ } catch (err) {
2454
+ return {
2455
+ verified: false,
2456
+ post_url: postUrl,
2457
+ body,
2458
+ tab_id: tabId,
2459
+ comments_scanned: 0,
2460
+ reason: err instanceof Error ? err.message : String(err),
2461
+ message: "Comment scrape failed (extension evaluate error).",
2462
+ };
2463
+ }
2464
+
2465
+ const candidates = authorHint
2466
+ ? comments.filter((c) =>
2467
+ (c.author ?? "").toLowerCase().includes(authorHint)
2468
+ )
2469
+ : comments;
2470
+
2471
+ for (const c of candidates) {
2472
+ const m = commentBodiesMatch(body, c.text);
2473
+ if (!m.ok) continue;
2474
+ return {
2475
+ verified: true,
2476
+ post_url: postUrl,
2477
+ body,
2478
+ tab_id: tabId,
2479
+ comments_scanned: comments.length,
2480
+ match: {
2481
+ author: c.author,
2482
+ text_preview: c.text.slice(0, 160),
2483
+ match_kind: m.kind,
2484
+ },
2485
+ message: `Verified: a visible comment matches the staged draft${
2486
+ c.author ? ` (author: ${c.author})` : ""
2487
+ }.`,
2488
+ };
2489
+ }
2490
+
2491
+ return {
2492
+ verified: false,
2493
+ post_url: postUrl,
2494
+ body,
2495
+ tab_id: tabId,
2496
+ comments_scanned: comments.length,
2497
+ reason:
2498
+ comments.length === 0
2499
+ ? "no_comments_visible"
2500
+ : authorHint
2501
+ ? "no_matching_comment_for_author"
2502
+ : "no_matching_comment",
2503
+ message:
2504
+ comments.length === 0
2505
+ ? "No comments visible on the post yet. The human may not have posted, comments may be collapsed, or the DOM selectors missed them."
2506
+ : "Comments are visible but none matched the staged draft body. The human may have edited the text before posting.",
2507
+ };
2508
+ }
2509
+
2510
+ export function filterPostsSinceCheckpoint(
2511
+ posts: LinkedInPost[],
2512
+ checkpoint: LinkedInCheckpoint
2513
+ ): LinkedInPost[] {
2514
+ const seenIds = new Set<string>();
2515
+ const checkpointPostId = normalizeCheckpointPostId(checkpoint.last_post_id);
2516
+ const checkpointTimestamp = checkpoint.last_timestamp
2517
+ ? new Date(checkpoint.last_timestamp).getTime()
2518
+ : null;
2519
+
2520
+ const filtered: LinkedInPost[] = [];
2521
+ for (const post of posts) {
2522
+ if (!post.id || !post.text || seenIds.has(post.id)) continue;
2523
+ seenIds.add(post.id);
2524
+
2525
+ if (checkpointPostId && post.id === checkpointPostId) break;
2526
+ if (
2527
+ checkpointTimestamp !== null &&
2528
+ post.publishedAt.getTime() <= checkpointTimestamp
2529
+ ) {
2530
+ continue;
2531
+ }
2532
+
2533
+ filtered.push(post);
2534
+ }
2535
+
2536
+ return filtered;
2537
+ }
2538
+
2539
+ // ── Voyager API Response Parsers ──────────────────────────────
2540
+
2541
+ export function parseCompanyUpdates(
2542
+ _url: string,
2543
+ json: unknown
2544
+ ): LinkedInPost[] {
2545
+ const posts: LinkedInPost[] = [];
2546
+ const data = json as any;
2547
+
2548
+ // Build URN lookup from `included` array (LinkedIn GraphQL uses references)
2549
+ const included: any[] = data?.included ?? [];
2550
+ const byUrn: Record<string, any> = {};
2551
+ for (const item of included) {
2552
+ const urn = item.entityUrn || item.$id;
2553
+ if (urn) byUrn[urn] = item;
2554
+ }
2555
+
2556
+ // Find feed elements - LinkedIn nests under data.data with a long key
2557
+ const feedRoot = data?.data?.data ?? data?.data ?? data;
2558
+ let elements: any[] = [];
2559
+ for (const key of Object.keys(feedRoot)) {
2560
+ const val = feedRoot[key];
2561
+ if (val?.["*elements"] && Array.isArray(val["*elements"])) {
2562
+ elements = val["*elements"];
2563
+ break;
2564
+ }
2565
+ if (val?.elements && Array.isArray(val.elements)) {
2566
+ elements = val.elements;
2567
+ break;
2568
+ }
2569
+ }
2570
+
2571
+ const resolve = (ref: any) =>
2572
+ (typeof ref === "string" ? byUrn[ref] : ref) ?? {};
2573
+
2574
+ for (const ref of elements) {
2575
+ const el = resolve(ref);
2576
+
2577
+ // Get commentary text (may be a reference)
2578
+ const commentaryObj = resolve(el["*commentary"] ?? el.commentary);
2579
+ const textObj = commentaryObj?.text ?? commentaryObj;
2580
+ const text = textObj?.text ?? textObj?.attributedText?.text ?? "";
2581
+ if (!text) continue;
2582
+
2583
+ // Get actor
2584
+ const actorObj = resolve(el["*actor"] ?? el.actor);
2585
+ const authorName = actorObj?.name?.text ?? actorObj?.name ?? "Unknown";
2586
+ const authorDesc =
2587
+ actorObj?.description?.text ?? actorObj?.description ?? undefined;
2588
+
2589
+ // Actor identity: the member's immutable `urn:li:fsd_profile:<id>` and the
2590
+ // vanity `/in/<slug>`. Voyager threads the profile urn through several
2591
+ // shapes — the actor may be a ref into `included`, and the urn hides under
2592
+ // `*miniProfile` (a bare urn string OR a ref to resolve), `miniProfile` (a
2593
+ // bare urn string OR an object with `entityUrn`), `urn`, or `entityUrn`.
2594
+ // normalizeLinkedInMemberId returns null for a non-person urn (e.g. a
2595
+ // company actor's `urn:li:fsd_company:…`), so a company-authored post yields
2596
+ // no member id and its attribution match-only-gates off (createWhen).
2597
+ const authorUrn: string =
2598
+ (typeof actorObj?.["*miniProfile"] === "string"
2599
+ ? actorObj["*miniProfile"]
2600
+ : resolve(actorObj?.["*miniProfile"])?.entityUrn) ??
2601
+ (typeof actorObj?.miniProfile === "string"
2602
+ ? actorObj.miniProfile
2603
+ : actorObj?.miniProfile?.entityUrn) ??
2604
+ actorObj?.urn ??
2605
+ actorObj?.entityUrn ??
2606
+ "";
2607
+ const authorMemberId = normalizeLinkedInMemberId(authorUrn) ?? undefined;
2608
+ const authorProfileUrl: string =
2609
+ actorObj?.navigationContext?.actionTarget ??
2610
+ actorObj?.navigationUrl ??
2611
+ resolve(actorObj?.["*miniProfile"])?.publicIdentifier ??
2612
+ "";
2613
+ // normalizeLinkedInSlug pulls the `/in/<slug>` segment from a full URL (and
2614
+ // returns null for a company `/company/…` URL or anything slug-invalid).
2615
+ const authorSlug = normalizeLinkedInSlug(authorProfileUrl);
2616
+
2617
+ // Get social counts
2618
+ const socialRef = el["*socialDetail"] ?? el.socialDetail;
2619
+ const social = resolve(socialRef);
2620
+ const counts =
2621
+ social?.totalSocialActivityCounts ??
2622
+ social?.socialActivityCountsInsight?.totalSocialActivityCounts ??
2623
+ {};
2624
+
2625
+ // Get URN for ID
2626
+ const urn = el.entityUrn ?? el["*backendUrn"] ?? "";
2627
+ const urnParts = urn.split(":");
2628
+ const id =
2629
+ urnParts[urnParts.length - 1] ||
2630
+ `li_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
2631
+
2632
+ // Get timestamp
2633
+ const metadata = resolve(el["*metadata"] ?? el.metadata);
2634
+ const publishedAt = metadata?.publishedAt ?? el.createdAt ?? Date.now();
2635
+
2636
+ posts.push({
2637
+ id,
2638
+ text,
2639
+ author: authorName,
2640
+ authorHeadline: typeof authorDesc === "string" ? authorDesc : undefined,
2641
+ authorMemberId: authorMemberId || undefined,
2642
+ authorSlug: authorSlug ?? undefined,
2643
+ likes: counts.numLikes ?? 0,
2644
+ comments: counts.numComments ?? 0,
2645
+ shares: counts.numShares ?? 0,
2646
+ publishedAt: new Date(publishedAt),
2647
+ });
2648
+ }
2649
+
2650
+ return posts;
2651
+ }
2652
+
2653
+ function parseJobListings(_url: string, json: unknown): LinkedInJob[] {
2654
+ const jobs: LinkedInJob[] = [];
2655
+ const data = json as any;
2656
+
2657
+ const elements = data?.elements ?? data?.data?.elements ?? [];
2658
+
2659
+ for (const element of elements) {
2660
+ const jobPosting = element?.jobPosting ?? element;
2661
+ const title = jobPosting?.title ?? element?.title ?? "";
2662
+ if (!title) continue;
2663
+
2664
+ const urnParts = (
2665
+ jobPosting?.entityUrn ??
2666
+ element?.dashEntityUrn ??
2667
+ ""
2668
+ ).split(":");
2669
+ const id =
2670
+ urnParts[urnParts.length - 1] ||
2671
+ `job_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
2672
+
2673
+ jobs.push({
2674
+ id,
2675
+ title,
2676
+ location: jobPosting?.formattedLocation ?? jobPosting?.location ?? "",
2677
+ postedAt: new Date(
2678
+ jobPosting?.listedAt ?? element?.createdAt ?? Date.now()
2679
+ ),
2680
+ url: `https://www.linkedin.com/jobs/view/${id}`,
2681
+ description: jobPosting?.description?.text ?? undefined,
2682
+ });
2683
+ }
2684
+
2685
+ return jobs;
2686
+ }
2687
+
2688
+ // ── Config Schemas ────────────────────────────────────────────
2689
+
2690
+ const companyUpdatesConfigSchema = {
2691
+ type: "object",
2692
+ required: ["company_url"],
2693
+ properties: {
2694
+ company_url: {
2695
+ type: "string",
2696
+ description:
2697
+ 'LinkedIn company page URL (e.g., "https://www.linkedin.com/company/openai")',
2698
+ },
2699
+ max_scrolls: {
2700
+ type: "integer",
2701
+ minimum: 1,
2702
+ maximum: 20,
2703
+ default: 5,
2704
+ description: "Maximum scroll iterations for pagination (default: 5)",
2705
+ },
2706
+ },
2707
+ };
2708
+
2709
+ const liveMessagesConfigSchema = {
2710
+ type: "object",
2711
+ properties: {
2712
+ inbox: {
2713
+ type: "string",
2714
+ pattern: "^(?:me|urn:li:fsd_pageMailbox:[0-9]+)$",
2715
+ default: "me",
2716
+ description:
2717
+ 'Whose inbox to read: "me" (default) for the signed-in member, or a company page\'s mailbox URN (urn:li:fsd_pageMailbox:<number>, the mailboxUrn the page\'s admin inbox at /company/<id>/admin/inbox/ requests; it differs from the company id). The signed-in member must administer the page. Changing it restarts the feed\'s subscription from a fresh baseline.',
2718
+ },
2719
+ },
2720
+ };
2721
+
2722
+ const homeFeedConfigSchema = {
2723
+ type: "object",
2724
+ properties: {
2725
+ max_scrolls: {
2726
+ type: "integer",
2727
+ minimum: 1,
2728
+ maximum: 30,
2729
+ default: 8,
2730
+ description:
2731
+ "Maximum scroll iterations for the home feed (default: 8). Upper end of the range when min_scrolls is set.",
2732
+ },
2733
+ min_scrolls: {
2734
+ type: "integer",
2735
+ minimum: 1,
2736
+ maximum: 30,
2737
+ description:
2738
+ "Optional lower bound. When set below max_scrolls, each sync picks a uniform random scroll count in [min_scrolls, max_scrolls].",
2739
+ },
2740
+ },
2741
+ };
2742
+
2743
+ /** Per-run scroll budget: fixed max_scrolls, or uniform [min_scrolls, max_scrolls]. */
2744
+ function readHomeScrollBudget(config: {
2745
+ max_scrolls?: number;
2746
+ min_scrolls?: number;
2747
+ }): number {
2748
+ const max = Math.max(1, Math.min(30, Number(config.max_scrolls ?? 8) || 8));
2749
+ if (config.min_scrolls === undefined || config.min_scrolls === null) {
2750
+ return max;
2751
+ }
2752
+ const min = Math.max(1, Math.min(max, Number(config.min_scrolls) || 1));
2753
+ if (min >= max) return max;
2754
+ return min + Math.floor(Math.random() * (max - min + 1));
2755
+ }
2756
+
2757
+ const jobsConfigSchema = {
2758
+ type: "object",
2759
+ required: ["company_url"],
2760
+ properties: {
2761
+ company_url: {
2762
+ type: "string",
2763
+ description:
2764
+ 'LinkedIn company page URL (e.g., "https://www.linkedin.com/company/openai")',
2765
+ },
2766
+ max_scrolls: {
2767
+ type: "integer",
2768
+ minimum: 1,
2769
+ maximum: 10,
2770
+ default: 3,
2771
+ description: "Maximum scroll iterations for job listings (default: 3)",
2772
+ },
2773
+ },
2774
+ };
2775
+
2776
+ function localTakeoutSchema(description: string): Record<string, unknown> {
2777
+ return {
2778
+ type: "object",
2779
+ properties: {
2780
+ takeout_dir: { type: "string", description },
2781
+ batch_size: {
2782
+ type: "integer",
2783
+ minimum: 1,
2784
+ maximum: 5000,
2785
+ default: 1000,
2786
+ description: "Maximum events to emit per sync run.",
2787
+ },
2788
+ },
2789
+ };
2790
+ }
2791
+
2792
+ // ── Connector ─────────────────────────────────────────────────
2793
+
2794
+ /**
2795
+ * True when a raw post reference is a LinkedIn HOME-FEED surface with no
2796
+ * specific post identity (e.g. `https://www.linkedin.com/feed/`, the feed
2797
+ * root, `/feed/hashtag/…`, or a bare `/feed/update` with no id). Such a URL
2798
+ * addresses the whole feed, not a post — prepare_comment must never treat it
2799
+ * as a durable post id (it would enqueue a doomed navigate and fail). Only
2800
+ * consulted after normalizeLinkedInPostUrl returned null, so any input that
2801
+ * resolves to a durable post URL is already handled.
2802
+ */
2803
+ export function isGenericLinkedInFeedUrl(raw: string): boolean {
2804
+ try {
2805
+ const withScheme = raw.startsWith("//")
2806
+ ? `https:${raw}`
2807
+ : raw.startsWith("/")
2808
+ ? `https://www.linkedin.com${raw}`
2809
+ : raw.includes("://")
2810
+ ? raw
2811
+ : `https://${raw}`;
2812
+ const u = new URL(withScheme);
2813
+ const host = u.hostname.toLowerCase().replace(/^www\./, "");
2814
+ if (host !== "linkedin.com" && !host.endsWith(".linkedin.com")) {
2815
+ return false;
2816
+ }
2817
+ const path = u.pathname.replace(/\/+$/, "");
2818
+ // A URL that carries a durable post identity (urn:li:…) is not the bare
2819
+ // feed surface, even though it lives under /feed/ — it resolves to a real
2820
+ // post. Only paths with NO embedded identity are "generic feed".
2821
+ if (/urn(?::|%3A)li(?::|%3A)(?:activity|share|ugcPost)/i.test(path)) {
2822
+ return false;
2823
+ }
2824
+ // Any other /feed/ path is a feed surface once no durable post id
2825
+ // resolved — the feed root, /feed/hashtag/<tag>, /feed/trending, and a
2826
+ // bare /feed/update (no urn). Nothing that normalizes to a real post URL
2827
+ // reaches here, so a prefix match is safe and complete.
2828
+ return path === "/feed" || path.startsWith("/feed/");
2829
+ } catch {
2830
+ return false;
2831
+ }
2832
+ }
2833
+
2834
+ /**
2835
+ * Non-failing result for a post reference that is not a supported durable
2836
+ * identifier. `success: true` so the action completes WITHOUT a failed
2837
+ * operational run — a not_actionable input is not a Lobu infrastructure
2838
+ * incident. `output.status` lets callers distinguish this from a real stage.
2839
+ */
2840
+ function notActionableMissingPostId(postUrlRaw: string): ActionResult {
2841
+ return {
2842
+ success: true,
2843
+ output: {
2844
+ status: "not_actionable",
2845
+ reason: "missing_durable_post_id",
2846
+ post_url: postUrlRaw,
2847
+ message:
2848
+ "A durable LinkedIn post identifier is required (e.g. urn:li:activity:…, a /feed/update/urn:li:… URL, or the canonical post URL from a synced post event). The provided reference addresses the LinkedIn home feed, not a specific post.",
2849
+ },
2850
+ };
2851
+ }
2852
+
2853
+ /**
2854
+ * The ten LinkedIn Data Export feeds: checkpoint cursor and pure reader per
2855
+ * feed key. This table replaces a chain of ten near-identical `if (feedKey ===
2856
+ * …)` blocks; the mapping it encodes is unchanged.
2857
+ *
2858
+ * Feed keys and cursor names are the persisted contract — a feed row keys on
2859
+ * the feed key and a checkpoint on the cursor name — so both are copied over
2860
+ * verbatim rather than tidied (see {@link LinkedInCheckpoint} on why the
2861
+ * takeout `jobs` cursor is `last_applied_jobs_timestamp`).
2862
+ */
2863
+ const LINKEDIN_TAKEOUT_FEEDS: Record<
2864
+ string,
2865
+ {
2866
+ cursor: Exclude<keyof LinkedInCheckpoint, "linkedin_inbox">;
2867
+ read: (readCsv: TakeoutCsvReader) => EventEnvelope[];
2868
+ }
2869
+ > = {
2870
+ messages: { cursor: "last_messages_timestamp", read: readMessages },
2871
+ connections: { cursor: "last_connections_timestamp", read: readConnections },
2872
+ invitations: { cursor: "last_invitations_timestamp", read: readInvitations },
2873
+ applied_jobs: { cursor: "last_applied_jobs_timestamp", read: readJobs },
2874
+ profile: { cursor: "last_profile_timestamp", read: readProfile },
2875
+ companies: { cursor: "last_companies_timestamp", read: readCompanyFollows },
2876
+ learning: { cursor: "last_learning_timestamp", read: readLearning },
2877
+ events: { cursor: "last_events_timestamp", read: readEvents },
2878
+ endorsements: {
2879
+ cursor: "last_endorsements_timestamp",
2880
+ read: readEndorsements,
2881
+ },
2882
+ media: { cursor: "last_media_timestamp", read: readRichMedia },
2883
+ };
2884
+
2885
+ /**
2886
+ * The configured export directory, or a thrown error naming what is missing.
2887
+ *
2888
+ * Only checks that the value is SET; it cannot stat the path, because this runs
2889
+ * inside the isolate, which has no filesystem. An injected host reader must
2890
+ * validate its directory before reading; the platform does not provide one.
2891
+ */
2892
+ function assertTakeoutDir(config: LinkedInConfig): string {
2893
+ const dir = config.takeout_dir;
2894
+ if (!dir) throw new Error("Missing takeout_dir for LinkedIn.");
2895
+ return dir;
2896
+ }
2897
+
2898
+ /** One sync pass's output; `syncFeed` commits it as a single page. */
2899
+ interface LinkedInSyncPage {
2900
+ events: EventEnvelope[];
2901
+ checkpoint: LinkedInCheckpoint;
2902
+ metadata?: Record<string, unknown>;
2903
+ }
2904
+
2905
+ export default class LinkedInConnector extends ConnectorRuntime<
2906
+ LinkedInCheckpoint,
2907
+ LinkedInConfig
2908
+ > {
2909
+ private readonly fetchImpl: typeof fetch;
2910
+ /**
2911
+ * Builds a CSV reader rooted at the export directory, or `undefined` when the
2912
+ * host has no filesystem — which is the case in the isolate every platform
2913
+ * run uses. Supplying it is how a Node-hosted caller (or a future worker that
2914
+ * advertises a local-file capability) turns the takeout feeds on, WITHOUT
2915
+ * putting `node:fs` into the bundle the live browser feeds must load.
2916
+ */
2917
+ private readonly csvReader?: (takeoutDir: string) => TakeoutCsvReader;
2918
+
2919
+ constructor(
2920
+ fetchImpl: typeof fetch = fetch,
2921
+ csvReader?: (takeoutDir: string) => TakeoutCsvReader
2922
+ ) {
2923
+ super();
2924
+ this.fetchImpl = fetchImpl;
2925
+ this.csvReader = csvReader;
2926
+ }
2927
+
2928
+ readonly definition: RuntimeConnectorDefinition<
2929
+ LinkedInCheckpoint,
2930
+ LinkedInConfig
2931
+ > = {
2932
+ key: "linkedin",
2933
+ name: "LinkedIn",
2934
+ description:
2935
+ "Read LinkedIn feeds, notifications, and recent inbox messages through paired Chrome. Subscribe to source changes, answer direct messages, and prepare message, post, or comment drafts for human submission. Also supports local LinkedIn Data Export CSV files.",
2936
+ version: "3.20.1",
2937
+ faviconDomain: "linkedin.com",
2938
+ // Live feeds bind a signed-in Chrome account. Local takeout imports need no browser.
2939
+ browser: {
2940
+ authMethods: ["browser"],
2941
+ origins: ["https://www.linkedin.com"],
2942
+ accountProbe: {
2943
+ url: LINKEDIN_HOME_URL,
2944
+ // Only the self-profile endpoint; vanity profile URLs can be renamed.
2945
+ expression: `(async () => {
2946
+ const raw = document.cookie.split('; ').find(cookie => cookie.startsWith('JSESSIONID='));
2947
+ if (!raw) return null;
2948
+ const csrf = decodeURIComponent(raw.slice(11)).replace(/^"|"$/g, '');
2949
+ const response = await fetch('/voyager/api/me', {
2950
+ credentials: 'include',
2951
+ headers: { 'csrf-token': csrf, 'x-restli-protocol-version': '2.0.0' },
2952
+ });
2953
+ if (response.status === 401 || response.status === 403) return null;
2954
+ if (!response.ok) throw new Error('LinkedIn account check failed (HTTP ' + response.status + ')');
2955
+ const self = await response.json();
2956
+ const accountId = self.miniProfile?.entityUrn;
2957
+ return typeof accountId === 'string' && accountId ? { accountId } : null;
2958
+ })()`,
2959
+ },
2960
+ },
2961
+ authSchema: {
2962
+ methods: [
2963
+ {
2964
+ type: "browser",
2965
+ mode: "live",
2966
+ },
2967
+ { type: "none", label: "Local data export" },
2968
+ // Keep browser first: connection setup uses the first authenticated
2969
+ // method, while sign-in independently discovers OAuth loginScopes.
2970
+ {
2971
+ type: "oauth",
2972
+ provider: "linkedin",
2973
+ requiredScopes: [],
2974
+ loginScopes: ["openid", "profile", "email"],
2975
+ loginProvisioning: { autoCreateConnection: false },
2976
+ authorizationUrl: "https://www.linkedin.com/oauth/v2/authorization",
2977
+ tokenUrl: "https://www.linkedin.com/oauth/v2/accessToken",
2978
+ userinfoUrl: "https://api.linkedin.com/v2/userinfo",
2979
+ tokenEndpointAuthMethod: "client_secret_post",
2980
+ clientIdKey: "LINKEDIN_CLIENT_ID",
2981
+ clientSecretKey: "LINKEDIN_CLIENT_SECRET",
2982
+ description:
2983
+ "Identity-only LinkedIn sign-in. Feeds use the browser or local exports.",
2984
+ setupInstructions:
2985
+ "Enable Sign In with LinkedIn using OpenID Connect in your LinkedIn app. Register /api/auth/oauth2/callback/linkedin on your Lobu origin for sign-in, then enter the client ID and client secret.",
2986
+ },
2987
+ ],
2988
+ },
2989
+ // Source subscriptions deliver only declared keys. Declaring any replaces the
2990
+ // eventKinds-derived catalog, so every feed kind is listed here.
2991
+ automationEvents: [
2992
+ {
2993
+ key: "notification.changed",
2994
+ label: "Notification Changed",
2995
+ resourceType: "notification",
2996
+ description:
2997
+ "A new or changed notification reference. Read its content from the notifications feed.",
2998
+ },
2999
+ {
3000
+ key: "message.created",
3001
+ label: "Message Created",
3002
+ resourceType: "message",
3003
+ description:
3004
+ "A new inbox message reference. Read its content from the live messages feed by id:<message URN>. A reply Automation can answer a direct message in its conversation.",
3005
+ capabilities: { replyToSource: true },
3006
+ },
3007
+ {
3008
+ key: "source.gap",
3009
+ label: "Source Gap",
3010
+ description:
3011
+ "Catch-up reached the end of what LinkedIn exposes, so earlier changes at this conversation or notification position may be missing.",
3012
+ },
3013
+ { key: "post", label: "Post" },
3014
+ { key: "comment", label: "Comment" },
3015
+ { key: "job_posting", label: "Job Posting" },
3016
+ { key: "message", label: "Message" },
3017
+ { key: "connection", label: "Connection" },
3018
+ ],
3019
+ feeds: {
3020
+ // ── Live (Chrome-extension) feeds ──────────────────────────
3021
+ notifications: {
3022
+ key: "notifications",
3023
+ name: "Notifications",
3024
+ description:
3025
+ "Read notification content and links without marking them seen. Subscriptions check once per minute while the paired browser is online; grouped notification content changes activate Automations, and catch-up beyond the scan budget reports a source gap. Exact source timestamps are unavailable.",
3026
+ read: (ctx) => readLinkedInInbox(ctx),
3027
+ observe: (ctx) => observeLinkedInInbox(ctx),
3028
+ webhook: {
3029
+ mode: "trigger",
3030
+ events: ["notification.changed", "source.gap"],
3031
+ },
3032
+ eventKinds: {
3033
+ "notification.changed": {
3034
+ description: "A new or meaningfully changed LinkedIn notification",
3035
+ },
3036
+ "source.gap": {
3037
+ description:
3038
+ "Catch-up scanned its page budget without reaching a known notification",
3039
+ },
3040
+ },
3041
+ },
3042
+ live_messages: {
3043
+ key: "live_messages",
3044
+ name: "Live Messages",
3045
+ description:
3046
+ "Read recent messages from inbox conversations without marking them seen. The cursor pages conversations and their recent message pages, not a full history export; `id:<message URN>` reads one recent message back. Rows carry the conversation's thread_id and full conversation_id, whether it is a group, the sender's member id, slug and name, and the message's content_kind; a company page inbox's rows also carry the visitor's topic when LinkedIn shows one. The `inbox` setting reads a company page's inbox the signed-in member administers instead of the member's own. Subscriptions check once per minute while the browser is online and report catch-up gaps.",
3047
+ configSchema: liveMessagesConfigSchema,
3048
+ read: (ctx) => readLinkedInInbox(ctx),
3049
+ observe: (ctx) => observeLinkedInInbox(ctx),
3050
+ webhook: { mode: "trigger", events: ["message.created", "source.gap"] },
3051
+ eventKinds: {
3052
+ "message.created": { description: "A new LinkedIn inbox message" },
3053
+ "source.gap": {
3054
+ description:
3055
+ "A conversation's recent message page may hide older catch-up messages",
3056
+ },
3057
+ },
3058
+ },
3059
+ home_feed: {
3060
+ sync: (ctx) => this.syncFeed(ctx),
3061
+ key: "home_feed",
3062
+ name: "Home Feed",
3063
+ description: "Your personalized LinkedIn home feed.",
3064
+ configSchema: homeFeedConfigSchema,
3065
+ eventKinds: {
3066
+ post: {
3067
+ description: "A post from your personalized LinkedIn home feed",
3068
+ attributions: LINKEDIN_HOME_FEED_ATTRIBUTIONS,
3069
+ metadataSchema: {
3070
+ type: "object",
3071
+ properties: {
3072
+ author: { type: "string" },
3073
+ author_linkedin_slug: { type: "string" },
3074
+ author_profile_url: { type: "string" },
3075
+ social_actor: {
3076
+ type: "string",
3077
+ description:
3078
+ "Member whose engagement surfaced this post (likes/commented/reposted banners).",
3079
+ },
3080
+ social_action: {
3081
+ type: "string",
3082
+ description:
3083
+ "Engagement verb: like, love, celebrate, support, insightful, funny, comment, repost.",
3084
+ },
3085
+ social_actor_slug: { type: "string" },
3086
+ social_actor_profile_url: { type: "string" },
3087
+ reactions: { type: "number" },
3088
+ comments: { type: "number" },
3089
+ reposts: { type: "number" },
3090
+ },
3091
+ },
3092
+ },
3093
+ comment: {
3094
+ description:
3095
+ "A complete comment or reply on a personalized feed post",
3096
+ attributions: LINKEDIN_HOME_COMMENT_ATTRIBUTIONS,
3097
+ metadataSchema: {
3098
+ type: "object",
3099
+ properties: {
3100
+ author: { type: "string" },
3101
+ author_linkedin_slug: { type: "string" },
3102
+ author_profile_url: { type: "string" },
3103
+ parent_post_origin_id: { type: "string" },
3104
+ parent_author: { type: "string" },
3105
+ parent_author_linkedin_slug: { type: "string" },
3106
+ parent_author_profile_url: { type: "string" },
3107
+ comment_urn: { type: "string" },
3108
+ comment_id: { type: "string" },
3109
+ parent_activity_id: { type: "string" },
3110
+ parent_activity_namespace: { type: "string" },
3111
+ parent_comment_origin_id: { type: "string" },
3112
+ parent_comment_id: { type: "string" },
3113
+ parent_comment_author: { type: "string" },
3114
+ parent_comment_author_linkedin_slug: { type: "string" },
3115
+ parent_comment_author_profile_url: { type: "string" },
3116
+ is_reply: { type: "boolean" },
3117
+ reactions: { type: "number" },
3118
+ comments: { type: "number" },
3119
+ reposts: { type: "number" },
3120
+ },
3121
+ },
3122
+ },
3123
+ },
3124
+ },
3125
+ company_updates: {
3126
+ sync: (ctx) => this.syncFeed(ctx),
3127
+ key: "company_updates",
3128
+ name: "Company Updates",
3129
+ description: "Posts and updates from the company LinkedIn page.",
3130
+ configSchema: companyUpdatesConfigSchema,
3131
+ eventKinds: {
3132
+ post: {
3133
+ description: "A company LinkedIn post",
3134
+ attributions: LINKEDIN_POST_AUTHOR_ATTRIBUTIONS,
3135
+ metadataSchema: {
3136
+ type: "object",
3137
+ properties: {
3138
+ author_headline: { type: "string" },
3139
+ author_member_id: { type: "string" },
3140
+ author_linkedin_slug: { type: "string" },
3141
+ likes: { type: "number" },
3142
+ comments: { type: "number" },
3143
+ shares: { type: "number" },
3144
+ },
3145
+ },
3146
+ },
3147
+ },
3148
+ },
3149
+ jobs: {
3150
+ sync: (ctx) => this.syncFeed(ctx),
3151
+ key: "jobs",
3152
+ name: "Job Listings",
3153
+ description: "Open job positions (hiring velocity signal).",
3154
+ configSchema: jobsConfigSchema,
3155
+ eventKinds: {
3156
+ job_posting: {
3157
+ description: "An open job listing",
3158
+ metadataSchema: {
3159
+ type: "object",
3160
+ properties: {
3161
+ location: { type: "string" },
3162
+ },
3163
+ },
3164
+ },
3165
+ },
3166
+ },
3167
+ // ── Takeout (local CSV) feeds ──────────────────────────────
3168
+ messages: {
3169
+ sync: (ctx) => this.syncFeed(ctx),
3170
+ key: "messages",
3171
+ name: "Messages",
3172
+ configSchema: localTakeoutSchema(
3173
+ "Path to the LinkedIn Data Export folder."
3174
+ ),
3175
+ eventKinds: {
3176
+ message: {
3177
+ description: "A LinkedIn direct message",
3178
+ attributions: LINKEDIN_MESSAGE_ATTRIBUTIONS,
3179
+ },
3180
+ },
3181
+ },
3182
+ connections: {
3183
+ sync: (ctx) => this.syncFeed(ctx),
3184
+ key: "connections",
3185
+ name: "Connections",
3186
+ configSchema: localTakeoutSchema(
3187
+ "Path to the LinkedIn Data Export folder."
3188
+ ),
3189
+ eventKinds: {
3190
+ connection: {
3191
+ description: "A first-degree LinkedIn connection",
3192
+ attributions: LINKEDIN_CONNECTION_ATTRIBUTIONS,
3193
+ },
3194
+ },
3195
+ },
3196
+ invitations: {
3197
+ sync: (ctx) => this.syncFeed(ctx),
3198
+ key: "invitations",
3199
+ name: "Invitations",
3200
+ configSchema: localTakeoutSchema(
3201
+ "Path to the LinkedIn Data Export folder."
3202
+ ),
3203
+ },
3204
+ applied_jobs: {
3205
+ sync: (ctx) => this.syncFeed(ctx),
3206
+ key: "applied_jobs",
3207
+ name: "Applied Jobs",
3208
+ description:
3209
+ "Your own applied/saved job postings from the LinkedIn Data Export.",
3210
+ configSchema: localTakeoutSchema(
3211
+ "Path to the LinkedIn Data Export folder."
3212
+ ),
3213
+ },
3214
+ profile: {
3215
+ sync: (ctx) => this.syncFeed(ctx),
3216
+ key: "profile",
3217
+ name: "Profile",
3218
+ configSchema: localTakeoutSchema(
3219
+ "Path to the LinkedIn Data Export folder."
3220
+ ),
3221
+ },
3222
+ companies: {
3223
+ sync: (ctx) => this.syncFeed(ctx),
3224
+ key: "companies",
3225
+ name: "Company Follows",
3226
+ configSchema: localTakeoutSchema(
3227
+ "Path to the LinkedIn Data Export folder."
3228
+ ),
3229
+ },
3230
+ learning: {
3231
+ sync: (ctx) => this.syncFeed(ctx),
3232
+ key: "learning",
3233
+ name: "Learning",
3234
+ configSchema: localTakeoutSchema(
3235
+ "Path to the LinkedIn Data Export folder."
3236
+ ),
3237
+ },
3238
+ events: {
3239
+ sync: (ctx) => this.syncFeed(ctx),
3240
+ key: "events",
3241
+ name: "Events",
3242
+ configSchema: localTakeoutSchema(
3243
+ "Path to the LinkedIn Data Export folder."
3244
+ ),
3245
+ },
3246
+ endorsements: {
3247
+ sync: (ctx) => this.syncFeed(ctx),
3248
+ key: "endorsements",
3249
+ name: "Endorsements and Recommendations",
3250
+ configSchema: localTakeoutSchema(
3251
+ "Path to the LinkedIn Data Export folder."
3252
+ ),
3253
+ },
3254
+ media: {
3255
+ sync: (ctx) => this.syncFeed(ctx),
3256
+ key: "media",
3257
+ name: "Rich Media",
3258
+ configSchema: localTakeoutSchema(
3259
+ "Path to the LinkedIn Data Export folder."
3260
+ ),
3261
+ },
3262
+ },
3263
+ actions: {
3264
+ set_like: {
3265
+ key: "set_like",
3266
+ name: "Set like",
3267
+ kind: "write",
3268
+ description:
3269
+ "Set the Like reaction on one exact LinkedIn post and verify it after reload. Already-matching posts are unchanged. Preserves other reaction types. Never comments or posts; selection and budgets belong to the Automation.",
3270
+ annotations: {
3271
+ openWorldHint: true,
3272
+ destructiveHint: false,
3273
+ idempotentHint: true,
3274
+ },
3275
+ inputSchema: {
3276
+ type: "object",
3277
+ required: ["post_url", "liked"],
3278
+ properties: {
3279
+ post_url: { type: "string", format: "uri" },
3280
+ liked: { type: "boolean" },
3281
+ },
3282
+ additionalProperties: false,
3283
+ },
3284
+ },
3285
+ send_message: {
3286
+ key: "send_message",
3287
+ name: "Send direct message reply",
3288
+ kind: "write",
3289
+ description:
3290
+ "Send a text reply into an exact existing LinkedIn direct-message conversation and confirm it appears there. Pass a member-inbox row's thread_id, or a row's full conversation_id to reply from the inbox the message came from (a company page the signed-in member administers). This direct send is approved only for answering direct messages on accounts the owner operates; group conversations are refused, and posts, comments and other messages stay draft-only through prepare_message, prepare_post and prepare_comment. A retry with the same idempotency_key returns the earlier message instead of sending again.",
3291
+ annotations: {
3292
+ openWorldHint: true,
3293
+ destructiveHint: false,
3294
+ idempotentHint: true,
3295
+ },
3296
+ inputSchema: {
3297
+ type: "object",
3298
+ required: ["conversation_id", "text", "idempotency_key"],
3299
+ additionalProperties: false,
3300
+ properties: {
3301
+ conversation_id: {
3302
+ type: "string",
3303
+ pattern:
3304
+ "^(?:[A-Za-z0-9_-]+=*|urn:li:msg_conversation:\\((?:urn:li:fsd_profile:[A-Za-z0-9_-]+|urn:li:fsd_pageMailbox:[0-9]+),[A-Za-z0-9_-]+=*\\))$",
3305
+ maxLength: 500,
3306
+ description:
3307
+ "The row's thread_id (the member's own inbox) or its full conversation_id (the inbox it names).",
3308
+ },
3309
+ text: { type: "string", minLength: 1, maxLength: 3000 },
3310
+ idempotency_key: {
3311
+ type: "string",
3312
+ minLength: 1,
3313
+ maxLength: 300,
3314
+ description: "One reply per key: a retry returns the first send.",
3315
+ },
3316
+ },
3317
+ },
3318
+ },
3319
+ prepare_message: {
3320
+ key: "prepare_message",
3321
+ name: "Prepare message",
3322
+ kind: "write",
3323
+ description:
3324
+ "Prepare a text reply in an exact existing conversation. Execute with activation: { kind: 'page_visit', urls: [conversation_url] }. When the user visits that URL, fill its empty composer. The user clicks Send. Never sends or overwrites a draft.",
3325
+ annotations: {
3326
+ openWorldHint: true,
3327
+ destructiveHint: false,
3328
+ idempotentHint: false,
3329
+ },
3330
+ inputSchema: {
3331
+ type: "object",
3332
+ required: ["conversation_url", "body"],
3333
+ additionalProperties: false,
3334
+ properties: {
3335
+ conversation_url: { type: "string", format: "uri" },
3336
+ body: { type: "string", minLength: 1, maxLength: 3000 },
3337
+ },
3338
+ },
3339
+ },
3340
+ prepare_post: {
3341
+ key: "prepare_post",
3342
+ name: "Prepare personal post",
3343
+ kind: "write",
3344
+ description: `Prepare a text post for the signed-in member. Execute with activation: { kind: 'page_visit', urls: ['${LINKEDIN_HOME_URL}'] }. When the user visits that page, open its personal post composer and fill an empty draft. The user clicks Post. Never publishes or overwrites a draft.`,
3345
+ annotations: {
3346
+ openWorldHint: true,
3347
+ destructiveHint: false,
3348
+ idempotentHint: false,
3349
+ },
3350
+ inputSchema: {
3351
+ type: "object",
3352
+ required: ["body"],
3353
+ additionalProperties: false,
3354
+ properties: {
3355
+ body: { type: "string", minLength: 1, maxLength: 3000 },
3356
+ },
3357
+ },
3358
+ },
3359
+ prepare_comment: {
3360
+ key: "prepare_comment",
3361
+ name: "Prepare comment",
3362
+ description:
3363
+ "Stage a comment draft after the user opens the exact LinkedIn post (fill composer, banner). The page-activation target is the post page URL with a trailing slash (https://www.linkedin.com/feed/update/urn:li:activity:<id>/), the form LinkedIn settles on. NEVER opens a tab or submits — the human must click Post.",
3364
+ // Page activation is separate from org policy approval. This action only
3365
+ // fills the composer; the human performs the irreversible Post click.
3366
+ // The fill expression skips submit-labelled controls and never presses Enter.
3367
+ kind: "write",
3368
+ annotations: {
3369
+ openWorldHint: true,
3370
+ destructiveHint: false,
3371
+ idempotentHint: false,
3372
+ },
3373
+ inputSchema: {
3374
+ type: "object",
3375
+ required: ["body"],
3376
+ anyOf: [{ required: ["post_url"] }, { required: ["activity_id"] }],
3377
+ properties: {
3378
+ post_url: {
3379
+ type: "string",
3380
+ description:
3381
+ 'LinkedIn post URL, or activity id / URN (e.g. "https://www.linkedin.com/feed/update/urn:li:activity:7312345678901234567", "urn:li:activity:7312345678901234567", or "7312345678901234567").',
3382
+ },
3383
+ activity_id: {
3384
+ type: "string",
3385
+ description:
3386
+ "Activity id when post_url is omitted (digits or urn:li:activity:…).",
3387
+ },
3388
+ body: {
3389
+ type: "string",
3390
+ description:
3391
+ "Draft comment text. Left in the composer for the user to edit/send.",
3392
+ minLength: 1,
3393
+ maxLength: 3000,
3394
+ },
3395
+ reason: {
3396
+ type: "string",
3397
+ description:
3398
+ "Optional short explanation for the in-page banner (truncated).",
3399
+ maxLength: 500,
3400
+ },
3401
+ banner: {
3402
+ type: "boolean",
3403
+ description:
3404
+ "Inject a small in-page Lobu handoff banner (default true).",
3405
+ },
3406
+ },
3407
+ },
3408
+ outputSchema: {
3409
+ type: "object",
3410
+ properties: {
3411
+ prepared: { type: "boolean" },
3412
+ status: {
3413
+ type: "string",
3414
+ enum: ["not_actionable", "prepared"],
3415
+ description:
3416
+ "prepared after the draft is staged; not_actionable when the input did not carry a durable post id (no browser action was taken).",
3417
+ },
3418
+ reason: {
3419
+ type: "string",
3420
+ description:
3421
+ "Present with status=not_actionable: why the input was not actionable (e.g. missing_durable_post_id).",
3422
+ },
3423
+ tab_id: { type: "integer" },
3424
+ post_url: { type: "string" },
3425
+ body: { type: "string" },
3426
+ method: { type: "string" },
3427
+ banner_shown: { type: "boolean" },
3428
+ reason_preview: { type: "string" },
3429
+ message: { type: "string" },
3430
+ },
3431
+ },
3432
+ },
3433
+ verify_staged_comment: {
3434
+ key: "verify_staged_comment",
3435
+ name: "Verify staged comment",
3436
+ description:
3437
+ "Re-open a LinkedIn post in the paired Chrome browser and check whether a comment matching the draft body is visible. Read-only — never posts. Best-effort DOM scrape (not a guarantee of publication).",
3438
+ kind: "read",
3439
+ annotations: {
3440
+ openWorldHint: true,
3441
+ destructiveHint: false,
3442
+ idempotentHint: true,
3443
+ },
3444
+ inputSchema: {
3445
+ type: "object",
3446
+ required: ["body"],
3447
+ anyOf: [{ required: ["post_url"] }, { required: ["activity_id"] }],
3448
+ properties: {
3449
+ post_url: {
3450
+ type: "string",
3451
+ description:
3452
+ "LinkedIn post URL, activity id, or URN (same shapes as prepare_comment).",
3453
+ },
3454
+ activity_id: {
3455
+ type: "string",
3456
+ description:
3457
+ "Activity id when post_url is omitted (digits or urn:li:activity:…).",
3458
+ },
3459
+ body: {
3460
+ type: "string",
3461
+ description: "Expected comment text (the staged draft).",
3462
+ minLength: 1,
3463
+ maxLength: 3000,
3464
+ },
3465
+ author_hint: {
3466
+ type: "string",
3467
+ description:
3468
+ "Optional author display-name substring to require when matching.",
3469
+ maxLength: 200,
3470
+ },
3471
+ focus: {
3472
+ type: "boolean",
3473
+ description:
3474
+ "Bring the post tab to the foreground (default true).",
3475
+ },
3476
+ },
3477
+ },
3478
+ outputSchema: {
3479
+ type: "object",
3480
+ properties: {
3481
+ verified: { type: "boolean" },
3482
+ status: {
3483
+ type: "string",
3484
+ enum: ["not_actionable", "verified"],
3485
+ description:
3486
+ "verified after a matching comment is found; not_actionable when the input did not carry a durable post id (no browser action was taken).",
3487
+ },
3488
+ reason: {
3489
+ type: "string",
3490
+ description:
3491
+ "Present whenever verification did not succeed: why (e.g. missing_durable_post_id, no_matching_comment, no_comments_visible, scrape_exception).",
3492
+ },
3493
+ post_url: { type: "string" },
3494
+ body: { type: "string" },
3495
+ tab_id: { type: "integer" },
3496
+ comments_scanned: { type: "integer" },
3497
+ match: {
3498
+ type: "object",
3499
+ properties: {
3500
+ author: { type: "string" },
3501
+ text_preview: { type: "string" },
3502
+ match_kind: {
3503
+ type: "string",
3504
+ enum: ["exact", "prefix", "contains"],
3505
+ },
3506
+ },
3507
+ },
3508
+ message: { type: "string" },
3509
+ },
3510
+ },
3511
+ },
3512
+ read_my_activity: {
3513
+ key: "read_my_activity",
3514
+ name: "Read my activity",
3515
+ description:
3516
+ "Read the signed-in member's own recent LinkedIn posts and comments from their profile activity pages in the paired Chrome browser, and return them without storing any events. Read-only.",
3517
+ kind: "read",
3518
+ annotations: {
3519
+ openWorldHint: true,
3520
+ destructiveHint: false,
3521
+ idempotentHint: true,
3522
+ },
3523
+ inputSchema: {
3524
+ type: "object",
3525
+ properties: {
3526
+ kinds: {
3527
+ type: "array",
3528
+ items: { type: "string", enum: ["posts", "comments"] },
3529
+ description:
3530
+ 'Which activity lists to read. Default ["posts", "comments"].',
3531
+ },
3532
+ max_scrolls: {
3533
+ type: "integer",
3534
+ minimum: 1,
3535
+ maximum: 10,
3536
+ description: "Scroll passes per list (default 3).",
3537
+ },
3538
+ },
3539
+ },
3540
+ },
3541
+ read_home_feed: {
3542
+ key: "read_home_feed",
3543
+ name: "Read home feed",
3544
+ description:
3545
+ "Read the signed-in member's current LinkedIn home feed in the paired Chrome browser, and return the visible posts and comments without storing any events. Read-only.",
3546
+ kind: "read",
3547
+ annotations: {
3548
+ openWorldHint: true,
3549
+ destructiveHint: false,
3550
+ idempotentHint: true,
3551
+ },
3552
+ inputSchema: {
3553
+ type: "object",
3554
+ properties: {
3555
+ max_scrolls: {
3556
+ type: "integer",
3557
+ minimum: 1,
3558
+ maximum: 10,
3559
+ description: "Scroll passes over the feed (default 6).",
3560
+ },
3561
+ },
3562
+ },
3563
+ },
3564
+ },
3565
+ };
3566
+
3567
+ async execute(ctx: ActionContext): Promise<ActionResult> {
3568
+ try {
3569
+ if (ctx.actionKey === "set_like") {
3570
+ if (typeof ctx.input.liked !== "boolean") {
3571
+ return { success: false, error: "liked must be a boolean" };
3572
+ }
3573
+ const url =
3574
+ typeof ctx.input.post_url === "string"
3575
+ ? normalizeLinkedInPostUrl(ctx.input.post_url)
3576
+ : null;
3577
+ if (!url)
3578
+ return {
3579
+ success: false,
3580
+ error: "post_url must identify an exact LinkedIn post",
3581
+ };
3582
+ return {
3583
+ success: true,
3584
+ output: await setLinkedInLike(
3585
+ requireBrowser(ctx),
3586
+ `${url}/`,
3587
+ ctx.input.liked
3588
+ ),
3589
+ };
3590
+ }
3591
+ if (ctx.actionKey === "send_message") {
3592
+ return await sendLinkedInMessage(ctx);
3593
+ }
3594
+ if (
3595
+ ctx.actionKey === "prepare_message" ||
3596
+ ctx.actionKey === "prepare_post"
3597
+ ) {
3598
+ return await prepareLinkedInDraft(ctx);
3599
+ }
3600
+ if (ctx.actionKey === "read_my_activity") {
3601
+ return await readMyLinkedInActivity(ctx);
3602
+ }
3603
+ if (ctx.actionKey === "read_home_feed") {
3604
+ return await readHomeFeed(ctx);
3605
+ }
3606
+ if (
3607
+ ctx.actionKey !== "prepare_comment" &&
3608
+ ctx.actionKey !== "verify_staged_comment"
3609
+ ) {
3610
+ return { success: false, error: `Unknown action: ${ctx.actionKey}` };
3611
+ }
3612
+ const body =
3613
+ typeof ctx.input.body === "string" ? ctx.input.body.trim() : "";
3614
+ if (!body) {
3615
+ return { success: false, error: "body is required" };
3616
+ }
3617
+ const postUrlRaw =
3618
+ (typeof ctx.input.post_url === "string" && ctx.input.post_url.trim()) ||
3619
+ (typeof ctx.input.activity_id === "string" &&
3620
+ ctx.input.activity_id.trim()) ||
3621
+ "";
3622
+ if (!postUrlRaw) {
3623
+ return {
3624
+ success: false,
3625
+ error: "post_url or activity_id is required",
3626
+ };
3627
+ }
3628
+
3629
+ // Require a supported DURABLE post identifier BEFORE any browser
3630
+ // dispatch. A generic home-feed URL must not enqueue a doomed navigate:
3631
+ // return a non-failing not_actionable result instead (no failed run, no
3632
+ // computer-use action, not an infrastructure incident).
3633
+ const normalizedPostUrl = normalizeLinkedInPostUrl(postUrlRaw);
3634
+ if (!normalizedPostUrl) {
3635
+ if (isGenericLinkedInFeedUrl(postUrlRaw)) {
3636
+ return notActionableMissingPostId(postUrlRaw);
3637
+ }
3638
+ return {
3639
+ success: false,
3640
+ error: `post_url or activity_id must reference a specific LinkedIn post (got ${JSON.stringify(postUrlRaw)})`,
3641
+ };
3642
+ }
3643
+
3644
+ const dispatcher = requireBrowser(ctx);
3645
+
3646
+ if (ctx.actionKey === "verify_staged_comment") {
3647
+ const authorHint =
3648
+ typeof ctx.input.author_hint === "string"
3649
+ ? ctx.input.author_hint.trim()
3650
+ : "";
3651
+ const output = await verifyLinkedInStagedComment(dispatcher, {
3652
+ postUrl: normalizedPostUrl,
3653
+ body,
3654
+ author_hint: authorHint || undefined,
3655
+ focus: ctx.input.focus !== false,
3656
+ });
3657
+ return {
3658
+ success: true,
3659
+ output: {
3660
+ ...output,
3661
+ ...(output.verified ? { status: "verified" } : {}),
3662
+ },
3663
+ };
3664
+ }
3665
+
3666
+ const reason =
3667
+ typeof ctx.input.reason === "string" ? ctx.input.reason.trim() : "";
3668
+ const output = await prepareLinkedInComment(dispatcher, {
3669
+ postUrl: normalizedPostUrl,
3670
+ body,
3671
+ reason: reason || undefined,
3672
+ banner: ctx.input.banner !== false,
3673
+ });
3674
+ return { success: true, output: { ...output, status: "prepared" } };
3675
+ } catch (error) {
3676
+ return {
3677
+ success: false,
3678
+ error: error instanceof Error ? error.message : String(error),
3679
+ };
3680
+ }
3681
+ }
3682
+
3683
+ private async syncFeed(
3684
+ ctx: SyncContext<LinkedInCheckpoint, LinkedInConfig>
3685
+ ): Promise<SyncResult> {
3686
+ const page = await this.collectFeed(ctx);
3687
+ await ctx.commit(page.events, page.checkpoint);
3688
+ return { status: "complete", metadata: page.metadata };
3689
+ }
3690
+
3691
+ private async collectFeed(
3692
+ ctx: SyncContext<LinkedInCheckpoint, LinkedInConfig>
3693
+ ): Promise<LinkedInSyncPage> {
3694
+ const feedKey = ctx.feedKey;
3695
+
3696
+ // ── Live (Chrome-extension) feeds ────────────────────────────
3697
+ if (
3698
+ feedKey === "home_feed" ||
3699
+ feedKey === "company_updates" ||
3700
+ feedKey === "jobs"
3701
+ ) {
3702
+ return this.syncLive(ctx);
3703
+ }
3704
+
3705
+ // ── Takeout (local CSV) feeds ────────────────────────────────
3706
+ // Parsing lives in `linkedin-takeout.ts` and is filesystem-free; the
3707
+ // capability to actually READ the export is supplied here. Injecting it
3708
+ // (rather than importing `node:fs` alongside the live feeds) is what keeps
3709
+ // the whole bundle isolate-eligible — see this class's header.
3710
+ const takeout = Object.hasOwn(LINKEDIN_TAKEOUT_FEEDS, feedKey)
3711
+ ? LINKEDIN_TAKEOUT_FEEDS[feedKey]
3712
+ : undefined;
3713
+ if (takeout) {
3714
+ const readCsv = this.csvReader;
3715
+ if (!readCsv) {
3716
+ throw new Error(
3717
+ "LinkedIn feed '" +
3718
+ feedKey +
3719
+ "' reads the local LinkedIn Data Export, " +
3720
+ "and this runtime provides no filesystem access. This invocation has no CSV reader; " +
3721
+ "browser-backed live feeds do not require one. For a local import, construct " +
3722
+ "the connector with an explicit reader in a filesystem-capable host."
3723
+ );
3724
+ }
3725
+ return this.result(
3726
+ ctx,
3727
+ takeout.cursor,
3728
+ takeout.read(readCsv(assertTakeoutDir(ctx.config))),
3729
+ batchSize(ctx.config)
3730
+ );
3731
+ }
3732
+
3733
+ throw new Error(`Unknown LinkedIn feed: ${feedKey}`);
3734
+ }
3735
+
3736
+ // ── Live scrape dispatch ─────────────────────────────────────
3737
+
3738
+ private async syncLive(
3739
+ ctx: SyncContext<LinkedInCheckpoint, LinkedInConfig>
3740
+ ): Promise<LinkedInSyncPage> {
3741
+ const config = ctx.config;
3742
+ const checkpoint = (ctx.checkpoint ?? {}) as LinkedInCheckpoint;
3743
+ const feedKey = ctx.feedKey;
3744
+
3745
+ // home_feed is the one feed that needs a content-script scrape (the CDP
3746
+ // debugger stops the personalized feed from rendering) and takes no
3747
+ // company_url — it always reads LINKEDIN_HOME_URL.
3748
+ if (feedKey === "home_feed") {
3749
+ const homeScrolls = readHomeScrollBudget(config);
3750
+ return this.syncHomeFeed(homeScrolls, checkpoint, requireBrowser(ctx));
3751
+ }
3752
+
3753
+ if (!config.company_url) {
3754
+ throw new Error("company_url is required");
3755
+ }
3756
+
3757
+ // Canonicalize the public alias before applying the exact browser grant.
3758
+ const companyUrl = new URL(config.company_url);
3759
+ if (companyUrl.hostname === "linkedin.com") {
3760
+ companyUrl.hostname = "www.linkedin.com";
3761
+ }
3762
+ const baseUrl = companyUrl.href.replace(/\/$/, "");
3763
+ const maxScrolls = config.max_scrolls ?? (feedKey === "jobs" ? 3 : 5);
3764
+
3765
+ const dispatcher = requireBrowser(ctx);
3766
+ if (feedKey === "jobs") {
3767
+ return this.syncJobs(baseUrl, maxScrolls, checkpoint, dispatcher);
3768
+ }
3769
+ return this.syncUpdates(baseUrl, maxScrolls, checkpoint, dispatcher);
3770
+ }
3771
+
3772
+ /**
3773
+ * Personalized home feed via the extension's content-script scrape. Network
3774
+ * capture can't read it (the CDP debugger stops the feed rendering), so we
3775
+ * dispatch a `cs_scrape` against LINKEDIN_HOME_URL with the home-feed
3776
+ * selectors. Use the same fresh scrape window as timeline reads: a hidden
3777
+ * persistent tab can leave LinkedIn's lazy-loaded feed on its initial batch.
3778
+ */
3779
+ private async syncHomeFeed(
3780
+ maxScrolls: number,
3781
+ checkpoint: LinkedInCheckpoint,
3782
+ dispatcher: ChromeActionDispatcher
3783
+ ): Promise<LinkedInSyncPage> {
3784
+ const { items: rows, loggedIn } = await extensionDomScrape<HomeFeedRow>({
3785
+ dispatcher,
3786
+ url: LINKEDIN_HOME_URL,
3787
+ config: {
3788
+ ...HOME_FEED_SCRAPE_CONFIG,
3789
+ scroll: { ...HOME_FEED_SCRAPE_CONFIG.scroll, max: maxScrolls },
3790
+ },
3791
+ parseRows: (raw) =>
3792
+ (raw as HomeFeedRow[]).map((row) => ({
3793
+ ...row,
3794
+ post_identity: decodeHomeFeedPostIdentity(row.post_identity),
3795
+ })),
3796
+ allowedOrigins: LINKEDIN_ALLOWED_ORIGINS,
3797
+ persistent: false,
3798
+ });
3799
+
3800
+ if (!loggedIn) {
3801
+ throw new Error(
3802
+ "Not logged into LinkedIn. Sign in to linkedin.com in the paired Chrome profile, then re-run the sync."
3803
+ );
3804
+ }
3805
+ if (rows.length === 0) {
3806
+ throw new Error(
3807
+ "LinkedIn is logged in, but the home feed produced no post rows. Confirm that the paired browser is signed into LinkedIn and retry."
3808
+ );
3809
+ }
3810
+
3811
+ const resolvedRows = await resolveHomeFeedPostUrls(rows, this.fetchImpl);
3812
+ const unresolvedShortUrlCount =
3813
+ unresolvedHomeFeedShortUrlCount(resolvedRows);
3814
+ if (unresolvedShortUrlCount > 0) {
3815
+ throw new Error(
3816
+ `LinkedIn could not resolve ${unresolvedShortUrlCount} copied post short URL${unresolvedShortUrlCount === 1 ? "" : "s"} to a durable identity. No home-feed events were persisted.`
3817
+ );
3818
+ }
3819
+ const unresolvedPosts = unresolvedHomeFeedPostRows(resolvedRows);
3820
+ if (unresolvedPosts.length > 0) {
3821
+ const count = unresolvedPosts.length;
3822
+ // The row id alone (no post text) is enough to spot a LinkedIn markup change.
3823
+ throw new Error(
3824
+ `LinkedIn scraped ${count} post row${count === 1 ? "" : "s"} without a durable activity/share/ugcPost identity (first row id: ${String(unresolvedPosts[0].id).slice(0, 120)}). No partial home-feed batch was persisted.`
3825
+ );
3826
+ }
3827
+
3828
+ const commentCoverage = summarizeHomeFeedCommentCoverage(resolvedRows);
3829
+
3830
+ const events = buildHomeFeedEvents(resolvedRows, new Date());
3831
+ if (events.length === 0) {
3832
+ throw new Error(
3833
+ "LinkedIn is logged in and returned feed rows, but no row combined usable content with a durable identity. Confirm that the paired browser is signed into LinkedIn and retry."
3834
+ );
3835
+ }
3836
+
3837
+ // Capability gate: author/engager slugs need the `objectAll` scrape take. An
3838
+ // older extension can't produce it, so identity degrades to name-only.
3839
+ // Surface it in metadata (rather than failing) so a stale extension is
3840
+ // observable — events still flow, just without slugs.
3841
+ const objectAllSupported = homeFeedObjectAllSupported(resolvedRows);
3842
+
3843
+ return {
3844
+ events,
3845
+ // The home feed exposes no stable per-post cursor (opaque token ids, no
3846
+ // timestamps), so there is nothing new to checkpoint — pass it through.
3847
+ checkpoint,
3848
+ metadata: {
3849
+ items_found: events.length,
3850
+ items_scraped: rows.length,
3851
+ scrolls_this_run: maxScrolls,
3852
+ backend: "extension-cs-scrape",
3853
+ object_all_supported: objectAllSupported,
3854
+ comment_threads_complete: commentCoverage.incomplete === 0,
3855
+ comment_threads_checked: commentCoverage.threads,
3856
+ comment_threads_incomplete: commentCoverage.incomplete,
3857
+ comment_threads_unsupported: commentCoverage.unsupported,
3858
+ comment_threads_timed_out: commentCoverage.timedOut,
3859
+ comment_coverage_details: commentCoverage.details,
3860
+ comments_expected: commentCoverage.expected,
3861
+ comments_collected: commentCoverage.collected,
3862
+ },
3863
+ };
3864
+ }
3865
+
3866
+ private async syncUpdates(
3867
+ baseUrl: string,
3868
+ maxScrolls: number,
3869
+ checkpoint: LinkedInCheckpoint,
3870
+ dispatcher: ChromeActionDispatcher
3871
+ ): Promise<LinkedInSyncPage> {
3872
+ const postsUrl = `${baseUrl}/posts/`;
3873
+ const result = await extensionNetworkSync<LinkedInPost>({
3874
+ dispatcher,
3875
+ url: postsUrl,
3876
+ config: {
3877
+ interceptPatterns: [
3878
+ {
3879
+ regex: "voyager/api/graphql\\?variables=.*ORGANIZATION_MEMBER_FEED",
3880
+ },
3881
+ { regex: "voyager/api/graphql\\?variables=.*organizationalPageUrn" },
3882
+ ],
3883
+ allowedOrigins: ["linkedin.com", "*.linkedin.com"],
3884
+ maxScrolls,
3885
+ scrollDelayMs: 3000,
3886
+ responseTimeoutMs: 8000,
3887
+ },
3888
+ parseResponse: parseCompanyUpdates,
3889
+ checkAuth: (currentUrl) =>
3890
+ !currentUrl.includes("/login") && !currentUrl.includes("/authwall"),
3891
+ });
3892
+
3893
+ const posts = filterPostsSinceCheckpoint(result.items, checkpoint);
3894
+ const events: EventEnvelope[] = posts.map((post) => ({
3895
+ origin_id: `li_post_${post.id}`,
3896
+ payload_text: post.text,
3897
+ author_name: post.author,
3898
+ occurred_at: post.publishedAt,
3899
+ origin_type: "post",
3900
+ source_url: `https://www.linkedin.com/feed/update/urn:li:activity:${post.id}`,
3901
+ score: calculateEngagementScore("linkedin", {
3902
+ upvotes: post.likes,
3903
+ reply_count: post.comments,
3904
+ }),
3905
+ metadata: {
3906
+ author_headline: post.authorHeadline,
3907
+ // Author identity for the `post` attribution. member_id (primary) when
3908
+ // Voyager exposed the actor's fsd_profile urn; slug bridges to takeout.
3909
+ author_member_id: post.authorMemberId,
3910
+ author_linkedin_slug: post.authorSlug,
3911
+ likes: post.likes,
3912
+ comments: post.comments,
3913
+ shares: post.shares,
3914
+ },
3915
+ }));
3916
+ events.sort(
3917
+ (a, b) =>
3918
+ new Date(b.occurred_at).getTime() - new Date(a.occurred_at).getTime()
3919
+ );
3920
+
3921
+ return {
3922
+ events,
3923
+ checkpoint: {
3924
+ ...checkpoint,
3925
+ last_post_id: posts[0]?.id ?? checkpoint.last_post_id,
3926
+ last_timestamp:
3927
+ events[0]?.occurred_at?.toISOString?.() ?? checkpoint.last_timestamp,
3928
+ },
3929
+ // No cookie persistence — auth lives in the user's signed-in Chrome,
3930
+ // not in our cookie cache.
3931
+ metadata: {
3932
+ items_found: events.length,
3933
+ items_skipped: result.items.length - posts.length,
3934
+ api_calls: result.apiCallCount,
3935
+ backend: "extension",
3936
+ },
3937
+ };
3938
+ }
3939
+
3940
+ private async syncJobs(
3941
+ baseUrl: string,
3942
+ maxScrolls: number,
3943
+ checkpoint: LinkedInCheckpoint,
3944
+ dispatcher: ChromeActionDispatcher
3945
+ ): Promise<LinkedInSyncPage> {
3946
+ const jobsUrl = `${baseUrl}/jobs/`;
3947
+ const result = await extensionNetworkSync<LinkedInJob>({
3948
+ dispatcher,
3949
+ url: jobsUrl,
3950
+ config: {
3951
+ interceptPatterns: [
3952
+ { regex: "voyager/api/graphql.*jobPosting", flags: "i" },
3953
+ { regex: "voyager/api/search/dash/.*jobs", flags: "i" },
3954
+ { regex: "voyager/api/organization/.*jobs", flags: "i" },
3955
+ ],
3956
+ allowedOrigins: ["linkedin.com", "*.linkedin.com"],
3957
+ maxScrolls,
3958
+ scrollDelayMs: 3000,
3959
+ responseTimeoutMs: 8000,
3960
+ },
3961
+ parseResponse: parseJobListings,
3962
+ checkAuth: (currentUrl) =>
3963
+ !currentUrl.includes("/login") && !currentUrl.includes("/authwall"),
3964
+ });
3965
+
3966
+ const seenIds = new Set<string>();
3967
+ const jobs = result.items.filter((j) => {
3968
+ if (!j.id || seenIds.has(j.id)) return false;
3969
+ seenIds.add(j.id);
3970
+ return true;
3971
+ });
3972
+ jobs.sort((a, b) => b.postedAt.getTime() - a.postedAt.getTime());
3973
+
3974
+ const events: EventEnvelope[] = jobs.map((job) => ({
3975
+ origin_id: `li_job_${job.id}`,
3976
+ payload_text: job.description ?? job.title,
3977
+ title: job.title,
3978
+ occurred_at: job.postedAt,
3979
+ origin_type: "job_posting",
3980
+ source_url: job.url,
3981
+ metadata: { location: job.location },
3982
+ }));
3983
+
3984
+ return {
3985
+ events,
3986
+ checkpoint: {
3987
+ ...checkpoint,
3988
+ last_job_id: jobs[0]?.id ?? checkpoint.last_job_id,
3989
+ last_timestamp:
3990
+ jobs[0]?.postedAt?.toISOString?.() ?? checkpoint.last_timestamp,
3991
+ },
3992
+ metadata: {
3993
+ items_found: events.length,
3994
+ api_calls: result.apiCallCount,
3995
+ backend: "extension",
3996
+ },
3997
+ };
3998
+ }
3999
+
4000
+ // ── Takeout (local CSV) readers ──────────────────────────────
4001
+
4002
+ private result(
4003
+ ctx: SyncContext<LinkedInCheckpoint, LinkedInConfig>,
4004
+ key: Exclude<keyof LinkedInCheckpoint, "linkedin_inbox">,
4005
+ allEvents: EventEnvelope[],
4006
+ max: number
4007
+ ): LinkedInSyncPage {
4008
+ const events = takeBatch(allEvents, ctx.checkpoint?.[key], max);
4009
+ return {
4010
+ events,
4011
+ checkpoint: {
4012
+ ...ctx.checkpoint,
4013
+ [key]: maxEventCursor(events, ctx.checkpoint?.[key]),
4014
+ },
4015
+ };
4016
+ }
4017
+ }