@lobu/runtime-device 22.0.0 → 23.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 (77) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +3 -3
  3. package/npm-shrinkwrap.json +15 -15
  4. package/package.json +1 -1
  5. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +1 -1
  6. package/vendor/cli/dist/connectors/README.md +14 -1
  7. package/vendor/cli/dist/connectors/google_gmail.ts +1 -0
  8. package/vendor/cli/dist/connectors/jira-helpers.ts +313 -0
  9. package/vendor/cli/dist/connectors/jira.ts +29 -221
  10. package/vendor/cli/dist/connectors/linkedin-browser-script.ts +13 -0
  11. package/vendor/cli/dist/connectors/linkedin-draft-page.js +104 -0
  12. package/vendor/cli/dist/connectors/linkedin-drafts.ts +73 -0
  13. package/vendor/cli/dist/connectors/linkedin-identity.ts +32 -0
  14. package/vendor/cli/dist/connectors/linkedin-inbox-adapter.js +1185 -0
  15. package/vendor/cli/dist/connectors/linkedin-inbox.ts +156 -0
  16. package/vendor/cli/dist/connectors/linkedin-like.ts +114 -0
  17. package/vendor/cli/dist/connectors/linkedin-takeout.ts +577 -0
  18. package/vendor/cli/dist/connectors/linkedin.ts +3998 -0
  19. package/vendor/cli/dist/connectors/takeout-utils.ts +240 -0
  20. package/vendor/cli/dist/connectors/tiktok-inbox-page.js +9 -9
  21. package/vendor/cli/dist/connectors/tiktok-web-page.js +21 -15
  22. package/vendor/cli/dist/connectors/tiktok_web.ts +63 -30
  23. package/vendor/cli/dist/connectors/whatsapp-web-adapter.js +64 -564
  24. package/vendor/cli/dist/connectors/whatsapp-web-helpers.ts +30 -444
  25. package/vendor/cli/dist/connectors/whatsapp-web-identity.ts +20 -6
  26. package/vendor/cli/dist/connectors/whatsapp_web.ts +45 -645
  27. package/vendor/cli/dist/connectors/x-dm-adapter.js +556 -0
  28. package/vendor/cli/dist/connectors/x-identity.ts +31 -2
  29. package/vendor/cli/dist/connectors/x.ts +266 -120
  30. package/vendor/cli/dist/runtime-components.json +4 -4
  31. package/vendor/cli/dist/templates/AGENTS.md.tmpl +2 -2
  32. package/vendor/cli/package.json +1 -1
  33. package/vendor/connector-sdk/dist/browser-handoff-banner.d.ts +39 -0
  34. package/vendor/connector-sdk/dist/browser-handoff-banner.js +175 -0
  35. package/vendor/connector-sdk/dist/browser-source-read.d.ts +52 -0
  36. package/vendor/connector-sdk/dist/browser-source-read.js +107 -0
  37. package/vendor/connector-sdk/dist/connector-types.d.ts +10 -0
  38. package/vendor/connector-sdk/dist/index.d.ts +3 -0
  39. package/vendor/connector-sdk/dist/index.js +2 -0
  40. package/vendor/connector-sdk/package.json +9 -1
  41. package/vendor/connector-worker/dist/agent-turn/guest-entry.js +15 -6
  42. package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +288 -148
  43. package/vendor/connector-worker/dist/daemon/automation.d.ts +4 -11
  44. package/vendor/connector-worker/dist/daemon/automation.js +6 -6
  45. package/vendor/connector-worker/dist/daemon/client.d.ts +2 -4
  46. package/vendor/connector-worker/dist/daemon/client.js +0 -3
  47. package/vendor/connector-worker/dist/daemon/executor.js +0 -3
  48. package/vendor/connector-worker/dist/daemon/mac-device-daemon.d.ts +4 -3
  49. package/vendor/connector-worker/dist/daemon/mac-device-daemon.js +4 -10
  50. package/vendor/connector-worker/dist/daemon/native-bridge/executor.js +27 -25
  51. package/vendor/connector-worker/dist/daemon/start.js +3 -15
  52. package/vendor/connector-worker/dist/daemon/terminal-failure.js +0 -11
  53. package/vendor/connector-worker/dist/daemon/worker-id.d.ts +17 -0
  54. package/vendor/connector-worker/dist/daemon/worker-id.js +22 -0
  55. package/vendor/connector-worker/dist/mac-device-daemon.js +14 -26
  56. package/vendor/connector-worker/package.json +1 -1
  57. package/vendor/core/dist/capabilities.d.ts +1 -1
  58. package/vendor/core/dist/capabilities.js +0 -1
  59. package/vendor/core/dist/connector-query-errors.d.ts +32 -0
  60. package/vendor/core/dist/connector-query-errors.js +41 -1
  61. package/vendor/core/dist/contracts/tools/manage-conversations.js +2 -2
  62. package/vendor/core/dist/contracts/tools/manage-feeds.d.ts +14 -0
  63. package/vendor/core/dist/contracts/tools/manage-feeds.js +17 -0
  64. package/vendor/core/dist/contracts/worker/protocol.d.ts +8 -131
  65. package/vendor/core/dist/contracts/worker/protocol.js +9 -61
  66. package/vendor/core/dist/device-pin-tombstones.d.ts +44 -0
  67. package/vendor/core/dist/device-pin-tombstones.js +57 -0
  68. package/vendor/core/dist/index.d.ts +2 -1
  69. package/vendor/core/dist/index.js +1 -0
  70. package/vendor/core/dist/logger.js +10 -25
  71. package/vendor/core/dist/utils/diagnostic-scrubber.js +258 -21
  72. package/vendor/core/dist/worker/wire.d.ts +0 -10
  73. package/vendor/core/package.json +6 -6
  74. package/vendor/connector-worker/dist/daemon/device-chat.d.ts +0 -9
  75. package/vendor/connector-worker/dist/daemon/device-chat.js +0 -61
  76. package/vendor/core/dist/contracts/worker/device-chat.d.ts +0 -4
  77. package/vendor/core/dist/contracts/worker/device-chat.js +0 -26
@@ -21,6 +21,15 @@ import {
21
21
  type WebhookRegistration,
22
22
  type WebhookRegistrationContext,
23
23
  } from '@lobu/connector-sdk';
24
+ import {
25
+ adfToText,
26
+ buildJiraJql,
27
+ JIRA_ISSUE_COLUMNS,
28
+ JIRA_ISSUE_FIELDS,
29
+ jiraActorName,
30
+ jiraAsString,
31
+ mapJiraIssueToRow,
32
+ } from './jira-helpers.js';
24
33
 
25
34
  // ---------------------------------------------------------------------------
26
35
  // Types
@@ -108,193 +117,6 @@ interface JiraSearchResponse {
108
117
  isLast?: boolean;
109
118
  }
110
119
 
111
- /** Stable column set returned by direct source reads. */
112
- const JIRA_ISSUE_COLUMNS = [
113
- { name: 'id', type: 'string' },
114
- { name: 'key', type: 'string' },
115
- { name: 'summary', type: 'string' },
116
- { name: 'status', type: 'string' },
117
- { name: 'assignee', type: 'string' },
118
- { name: 'reporter', type: 'string' },
119
- { name: 'priority', type: 'string' },
120
- { name: 'project_key', type: 'string' },
121
- { name: 'project_name', type: 'string' },
122
- { name: 'labels', type: 'string' },
123
- { name: 'created_at', type: 'string' },
124
- { name: 'updated_at', type: 'string' },
125
- { name: 'description', type: 'string' },
126
- { name: 'url', type: 'string' },
127
- ] as const;
128
-
129
- const ISSUE_FIELDS =
130
- 'summary,description,status,assignee,reporter,priority,project,labels,created,updated';
131
-
132
- /** Sort columns the live path can honor by rewriting ORDER BY. */
133
- const SORT_COLUMNS: Record<string, string> = {
134
- updated: 'updated',
135
- updated_at: 'updated',
136
- created: 'created',
137
- created_at: 'created',
138
- key: 'key',
139
- priority: 'priority',
140
- status: 'status',
141
- };
142
-
143
- const ADF_BLOCK_TYPES = new Set([
144
- 'blockquote',
145
- 'bulletList',
146
- 'codeBlock',
147
- 'heading',
148
- 'listItem',
149
- 'orderedList',
150
- 'paragraph',
151
- 'rule',
152
- 'table',
153
- 'tableCell',
154
- 'tableHeader',
155
- 'tableRow',
156
- ]);
157
-
158
- function asString(value: unknown): string | undefined {
159
- return typeof value === 'string' && value.trim().length > 0 ? value : undefined;
160
- }
161
-
162
- function actorName(user: JiraUser | null | undefined): string | undefined {
163
- return user?.displayName ?? user?.emailAddress ?? undefined;
164
- }
165
-
166
- /**
167
- * Jira v3 descriptions/comment bodies use the Atlassian Document Format (ADF) —
168
- * a nested JSON node tree. Flatten its text nodes to plain text. Strings (older
169
- * payloads) pass through unchanged.
170
- */
171
- function adfToText(value: unknown): string {
172
- if (typeof value === 'string') return value;
173
- if (!value || typeof value !== 'object') return '';
174
- const node = value as { type?: string; text?: string; content?: unknown[] };
175
- // Soft line break inside a paragraph (not a block boundary).
176
- if (node.type === 'hardBreak') return '\n';
177
- if (typeof node.text === 'string') return node.text;
178
- if (Array.isArray(node.content)) {
179
- let out = '';
180
- for (const child of node.content) {
181
- const text = adfToText(child);
182
- if (!text) continue;
183
- const childType =
184
- child && typeof child === 'object' ? (child as { type?: string }).type : undefined;
185
- // hardBreak already contributes '\n' as its text; don't insert a second.
186
- if (out && childType && ADF_BLOCK_TYPES.has(childType)) out += '\n';
187
- out += text;
188
- }
189
- return out.trim();
190
- }
191
- return '';
192
- }
193
-
194
- /**
195
- * Peel a trailing `ORDER BY …` so caller JQL can be AND-composed without
196
- * wrapping the sort clause.
197
- */
198
- function splitTrailingOrderBy(jql: string): { body: string; orderBy: string | null } {
199
- let quote: '"' | "'" | null = null;
200
- let escaped = false;
201
- let depth = 0;
202
- for (let i = 0; i < jql.length; i += 1) {
203
- const char = jql[i];
204
- if (quote) {
205
- if (escaped) {
206
- escaped = false;
207
- } else if (char === '\\') {
208
- escaped = true;
209
- } else if (char === quote) {
210
- quote = null;
211
- }
212
- continue;
213
- }
214
- if (char === '"' || char === "'") {
215
- quote = char;
216
- continue;
217
- }
218
- if (char === '(') {
219
- depth += 1;
220
- continue;
221
- }
222
- if (char === ')') {
223
- depth = Math.max(0, depth - 1);
224
- continue;
225
- }
226
- if (
227
- depth === 0 &&
228
- (i === 0 || /\s/.test(jql[i - 1])) &&
229
- /^order\s+by\b/i.test(jql.slice(i))
230
- ) {
231
- return { body: jql.slice(0, i).trim(), orderBy: jql.slice(i).trim() };
232
- }
233
- }
234
- return { body: jql.trim(), orderBy: null };
235
- }
236
-
237
- function buildJiraJql(args: {
238
- baseQuery: string;
239
- query?: string;
240
- sort?: { column: string; order: 'asc' | 'desc' };
241
- defaultWhenEmpty?: string;
242
- window?: { start: string; end: string };
243
- }): string {
244
- const trimmed = args.baseQuery.trim();
245
- // Keep an omitted scope bounded instead of scanning the whole site.
246
- const jql = trimmed.length > 0 ? trimmed : (args.defaultWhenEmpty ?? 'updated >= -90d');
247
-
248
- // If the base is only ORDER BY, treat the restriction as empty and keep sort.
249
- let { body, orderBy } = splitTrailingOrderBy(jql);
250
- if (!body && orderBy) {
251
- body = args.defaultWhenEmpty ?? 'updated >= -90d';
252
- }
253
-
254
- const callerQuery = args.query?.trim() ?? '';
255
- if (callerQuery) {
256
- const caller = splitTrailingOrderBy(callerQuery);
257
- if (caller.body) {
258
- body = body.length > 0 ? `(${body}) AND (${caller.body})` : caller.body;
259
- }
260
- if (caller.orderBy) {
261
- throw new Error(
262
- 'Jira source read query cannot contain ORDER BY; use the separate sort field',
263
- );
264
- }
265
- }
266
-
267
- if (args.window) {
268
- const bounds = `updated >= ${Date.parse(args.window.start)} AND updated < ${Date.parse(args.window.end)}`;
269
- body = body ? `(${body}) AND (${bounds})` : bounds;
270
- }
271
-
272
- // `body` is non-empty from here on: an empty base fell back to
273
- // `defaultWhenEmpty`, and the caller query can further restrict it.
274
- if (orderBy) {
275
- if (args.sort) {
276
- throw new Error(
277
- 'Jira source read: cannot apply sort when the base JQL already contains ORDER BY',
278
- );
279
- }
280
- return `${body} ${orderBy}`;
281
- }
282
-
283
- if (args.sort) {
284
- const field = SORT_COLUMNS[args.sort.column];
285
- if (!field) {
286
- throw new Error(
287
- `Jira source read sort column '${args.sort.column}' is unsupported; ` +
288
- `use one of: ${Object.keys(SORT_COLUMNS).join(', ')}`,
289
- );
290
- }
291
- const dir = args.sort.order === 'asc' ? 'ASC' : 'DESC';
292
- return `${body} ORDER BY ${field} ${dir}`;
293
- }
294
-
295
- return `${body} ORDER BY updated DESC`;
296
- }
297
-
298
120
  // ---------------------------------------------------------------------------
299
121
  // Connector
300
122
  // ---------------------------------------------------------------------------
@@ -463,11 +285,11 @@ export default class JiraConnector extends ConnectorRuntime<JiraCheckpoint, Jira
463
285
  throw new Error('Jira source reads require Atlassian OAuth credentials.');
464
286
  }
465
287
 
466
- const baseQuery = asString(ctx.config.query) ?? asString(ctx.config.jql) ?? '';
288
+ const baseQuery = jiraAsString(ctx.config.query) ?? jiraAsString(ctx.config.jql) ?? '';
467
289
 
468
290
  const jql = buildJiraJql({
469
291
  baseQuery,
470
- query: asString(ctx.query),
292
+ query: jiraAsString(ctx.query),
471
293
  window: ctx.window,
472
294
  ...(ctx.window ? { defaultWhenEmpty: '' } : {}),
473
295
  sort: ctx.sort,
@@ -492,7 +314,7 @@ export default class JiraConnector extends ConnectorRuntime<JiraCheckpoint, Jira
492
314
  const params = new URLSearchParams({
493
315
  jql,
494
316
  maxResults: String(Math.min(this.PAGE_SIZE, limit)),
495
- fields: ISSUE_FIELDS,
317
+ fields: JIRA_ISSUE_FIELDS,
496
318
  });
497
319
  if (ctx.cursor) params.set('nextPageToken', ctx.cursor);
498
320
  const data = await http.json<JiraSearchResponse>(
@@ -540,7 +362,7 @@ export default class JiraConnector extends ConnectorRuntime<JiraCheckpoint, Jira
540
362
  end: new Date().toISOString(),
541
363
  };
542
364
  const jql = buildJiraJql({
543
- baseQuery: asString(ctx.config.query) ?? asString(ctx.config.jql) ?? '',
365
+ baseQuery: jiraAsString(ctx.config.query) ?? jiraAsString(ctx.config.jql) ?? '',
544
366
  defaultWhenEmpty: `updated >= -${lookbackDays}d`,
545
367
  window,
546
368
  });
@@ -559,7 +381,7 @@ export default class JiraConnector extends ConnectorRuntime<JiraCheckpoint, Jira
559
381
  const params = new URLSearchParams({
560
382
  jql,
561
383
  maxResults: String(this.PAGE_SIZE),
562
- fields: ISSUE_FIELDS,
384
+ fields: JIRA_ISSUE_FIELDS,
563
385
  });
564
386
  if (pageToken) {
565
387
  seenTokens.add(pageToken);
@@ -675,24 +497,10 @@ export default class JiraConnector extends ConnectorRuntime<JiraCheckpoint, Jira
675
497
  config: JiraConfig,
676
498
  ): Record<string, unknown> | null {
677
499
  if (!issue?.id) return null;
678
- const fields = issue.fields ?? {};
679
- const labels = Array.isArray(fields.labels) ? fields.labels.join(', ') : null;
680
- return {
681
- id: issue.id,
682
- key: issue.key ?? null,
683
- summary: fields.summary ?? null,
684
- status: fields.status?.name ?? null,
685
- assignee: actorName(fields.assignee) ?? null,
686
- reporter: actorName(fields.reporter) ?? null,
687
- priority: fields.priority?.name ?? null,
688
- project_key: fields.project?.key ?? null,
689
- project_name: fields.project?.name ?? null,
690
- labels,
691
- created_at: fields.created ?? null,
692
- updated_at: fields.updated ?? null,
693
- description: adfToText(fields.description) || null,
694
- url: this.issueUrl(issue, config) ?? null,
695
- };
500
+ return mapJiraIssueToRow(
501
+ issue,
502
+ config as unknown as Record<string, unknown>,
503
+ );
696
504
  }
697
505
 
698
506
  private issueEvent(issue: JiraIssue | undefined, config: JiraConfig): EventEnvelope | null {
@@ -705,25 +513,25 @@ export default class JiraConnector extends ConnectorRuntime<JiraCheckpoint, Jira
705
513
  origin_id: `jira_issue_${issue.id}`,
706
514
  title: fields.summary ?? issue.key ?? undefined,
707
515
  payload_text: adfToText(fields.description),
708
- author_name: actorName(fields.reporter ?? fields.assignee),
516
+ author_name: jiraActorName(fields.reporter ?? fields.assignee),
709
517
  source_url: this.issueUrl(issue, config),
710
518
  occurred_at: createdAt,
711
519
  origin_type: 'issue',
712
520
  metadata: {
713
521
  key: issue.key ?? null,
714
522
  status: fields.status?.name ?? null,
715
- assignee: actorName(fields.assignee) ?? null,
716
- reporter: actorName(fields.reporter) ?? null,
523
+ assignee: jiraActorName(fields.assignee) ?? null,
524
+ reporter: jiraActorName(fields.reporter) ?? null,
717
525
  updated_at: fields.updated ?? null,
718
526
  },
719
527
  };
720
528
  }
721
529
 
722
530
  private issueUrl(issue: JiraIssue | undefined, config?: JiraConfig): string | undefined {
723
- const siteUrl = asString(config?.site_url);
724
- const key = asString(issue?.key);
725
- const cloudId = asString(config?.cloud_id);
726
- const siteCloudId = asString(config?.site_cloud_id);
531
+ const siteUrl = jiraAsString(config?.site_url);
532
+ const key = jiraAsString(issue?.key);
533
+ const cloudId = jiraAsString(config?.cloud_id);
534
+ const siteCloudId = jiraAsString(config?.site_cloud_id);
727
535
  // Only rewrite to /browse when site_url was discovered for THIS cloud_id.
728
536
  // A feed-level cloud_id override must not inherit another site's host.
729
537
  if (siteUrl && key && cloudId && siteCloudId && cloudId === siteCloudId) {
@@ -756,7 +564,7 @@ export default class JiraConnector extends ConnectorRuntime<JiraCheckpoint, Jira
756
564
  sessionState: Record<string, unknown> | null | undefined,
757
565
  credentials: SyncCredentials | null | undefined,
758
566
  ): Promise<string> {
759
- const fromConfig = asString(config.cloud_id) ?? asString(sessionState?.cloud_id);
567
+ const fromConfig = jiraAsString(config.cloud_id) ?? jiraAsString(sessionState?.cloud_id);
760
568
  if (fromConfig) return fromConfig;
761
569
 
762
570
  if (!credentials?.accessToken) {
@@ -804,7 +612,7 @@ export default class JiraConnector extends ConnectorRuntime<JiraCheckpoint, Jira
804
612
  ? distinctUsable[0]
805
613
  : null;
806
614
 
807
- const id = asString(site?.id);
615
+ const id = jiraAsString(site?.id);
808
616
  if (!id) {
809
617
  if (jiraScoped.length > 1 || distinctUsable.length > 1) {
810
618
  throw new Error(
@@ -819,8 +627,8 @@ export default class JiraConnector extends ConnectorRuntime<JiraCheckpoint, Jira
819
627
  // Cache on this job's config so subsequent calls in the same run skip the hop.
820
628
  config.cloud_id = id;
821
629
  config.site_cloud_id = id;
822
- const siteUrl = asString(site?.url);
823
- const siteName = asString(site?.name);
630
+ const siteUrl = jiraAsString(site?.url);
631
+ const siteName = jiraAsString(site?.name);
824
632
  if (siteUrl) config.site_url = siteUrl;
825
633
  else delete config.site_url;
826
634
  if (siteName) config.site_name = siteName;
@@ -0,0 +1,13 @@
1
+ export const LINKEDIN_HOME_URL = "https://www.linkedin.com/feed/foryou/";
2
+
3
+ /** Keep data inert in generated browser code, including an HTML script context. */
4
+ export function linkedInScriptArgument(value: unknown): string {
5
+ const json = JSON.stringify(value);
6
+ if (json === undefined) throw new Error("LinkedIn browser input is required");
7
+ const literal = JSON.stringify(json).replace(
8
+ /[<>\u2028\u2029]/g,
9
+ (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`
10
+ );
11
+ // Parsing also preserves JSON object keys such as __proto__ as plain data.
12
+ return `JSON.parse(${literal})`;
13
+ }
@@ -0,0 +1,104 @@
1
+ // Serialized into the activated LinkedIn page with Function.prototype.toString(),
2
+ // so it stays plain JS: no syntax a transform would rewrite, no outer bindings.
3
+ /** Serialized as one closed function; never clicks Send/Post or presses Enter. */
4
+ export async function fillLinkedInDraft(input) {
5
+ function fail(message) {
6
+ throw new Error(`LinkedIn draft: ${message}`);
7
+ }
8
+ if (location.href !== input.url)
9
+ fail("The activated page is not the requested draft target");
10
+ const visible = (element) =>
11
+ element.getClientRects().length > 0 &&
12
+ getComputedStyle(element).visibility !== "hidden";
13
+ let editor;
14
+ if (input.kind === "prepare_message") {
15
+ const selected = [
16
+ ...document.querySelectorAll(
17
+ '.msg-conversation-listitem--active a[href*="/messaging/thread/"], a[aria-current="page"][href*="/messaging/thread/"]'
18
+ ),
19
+ ].filter(
20
+ (link) =>
21
+ visible(link) &&
22
+ new URL(link.href).pathname === new URL(input.url).pathname
23
+ );
24
+ if (selected.length !== 1)
25
+ fail("The selected conversation does not match the requested recipient");
26
+ const threads = [...document.querySelectorAll(".msg-thread")].filter(
27
+ visible
28
+ );
29
+ if (threads.length !== 1) fail("Exactly one conversation must be open");
30
+ const editors = [
31
+ ...threads[0].querySelectorAll(
32
+ '.msg-form [contenteditable="true"][role="textbox"]'
33
+ ),
34
+ ].filter(visible);
35
+ if (editors.length !== 1)
36
+ fail("The conversation message composer is unavailable");
37
+ editor = editors[0];
38
+ if (
39
+ threads[0].querySelector(
40
+ '.msg-form__attachment, .msg-form__attachments [data-attachment-id], input[type="file"]:disabled'
41
+ )
42
+ ) {
43
+ fail("The conversation already has an attachment draft");
44
+ }
45
+ } else if (input.kind === "prepare_post") {
46
+ if (document.querySelector('[role="dialog"] [contenteditable="true"]'))
47
+ fail("A composer is already open; finish or close it first");
48
+ const buttons = [
49
+ ...document.querySelectorAll(
50
+ 'button, a[href="https://www.linkedin.com/preload/sharebox/?"]'
51
+ ),
52
+ ].filter(
53
+ (button) =>
54
+ visible(button) && button.textContent?.trim() === "Start a post"
55
+ );
56
+ if (buttons.length !== 1)
57
+ fail("The personal post composer entry point is unavailable");
58
+ buttons[0].click();
59
+ for (let attempt = 0; attempt < 40; attempt++) {
60
+ const editors = [
61
+ ...document.querySelectorAll(
62
+ '[role="dialog"] [contenteditable="true"][role="textbox"], [role="dialog"] .ql-editor[contenteditable="true"]'
63
+ ),
64
+ ].filter(visible);
65
+ if (editors.length === 1) {
66
+ editor = editors[0];
67
+ break;
68
+ }
69
+ await new Promise((resolve) => setTimeout(resolve, 100));
70
+ }
71
+ if (!editor) fail("The personal post composer did not open");
72
+ const dialog = editor.closest('[role="dialog"]');
73
+ if (
74
+ !dialog ||
75
+ dialog.querySelector('input[type="file"]:disabled, [data-attachment-id]')
76
+ )
77
+ fail("The post composer is not an empty text draft");
78
+ } else fail("Unsupported draft action");
79
+ if (!editor || location.href !== input.url)
80
+ fail("The activated target changed");
81
+ if (
82
+ (editor.textContent ?? "").trim() ||
83
+ editor.querySelector("img,video,audio,[contenteditable=false]")
84
+ )
85
+ fail("The composer already contains a draft");
86
+ editor.focus();
87
+ if (!document.execCommand("insertText", false, input.body))
88
+ fail("The browser could not fill the draft");
89
+ const normalized = (value) => value.replace(/\r\n/g, "\n").trim();
90
+ if (
91
+ normalized(editor.innerText ?? editor.textContent ?? "") !==
92
+ normalized(input.body)
93
+ )
94
+ fail("The draft text could not be verified; review the composer");
95
+ return {
96
+ prepared: true,
97
+ submitted: false,
98
+ url: input.url,
99
+ message:
100
+ input.kind === "prepare_message"
101
+ ? "Draft ready. Review it and click Send in LinkedIn."
102
+ : "Draft ready. Review it and click Post in LinkedIn.",
103
+ };
104
+ }
@@ -0,0 +1,73 @@
1
+ import {
2
+ requireBrowser,
3
+ type ActionContext,
4
+ type ActionResult,
5
+ } from "@lobu/connector-sdk";
6
+ import {
7
+ LINKEDIN_HOME_URL,
8
+ linkedInScriptArgument,
9
+ } from "./linkedin-browser-script.js";
10
+ import { fillLinkedInDraft } from "./linkedin-draft-page.js";
11
+
12
+ export function linkedInDraftUrl(
13
+ kind: string,
14
+ input: Record<string, unknown>
15
+ ): string {
16
+ if (kind === "prepare_post") return LINKEDIN_HOME_URL;
17
+ const url = new URL(String(input.conversation_url ?? ""));
18
+ if (
19
+ url.origin !== "https://www.linkedin.com" ||
20
+ url.username ||
21
+ url.password ||
22
+ url.search ||
23
+ url.hash ||
24
+ !/^\/messaging\/thread\/[A-Za-z0-9_=%-]+\/$/.test(url.pathname)
25
+ ) {
26
+ throw new Error(
27
+ "conversation_url must be the exact LinkedIn conversation URL ending in a slash"
28
+ );
29
+ }
30
+ return url.href;
31
+ }
32
+
33
+ export async function prepareLinkedInDraft(
34
+ ctx: ActionContext
35
+ ): Promise<ActionResult> {
36
+ try {
37
+ const body =
38
+ typeof ctx.input.body === "string" ? ctx.input.body.trim() : "";
39
+ if (!body || body.length > 3000)
40
+ throw new Error("body must contain 1–3000 characters");
41
+ const url = linkedInDraftUrl(ctx.actionKey, ctx.input);
42
+ const browser = requireBrowser(ctx);
43
+ const nav = await browser.dispatch<{ tab_id?: number }>("navigate", {
44
+ url,
45
+ require_page_activation: true,
46
+ });
47
+ if (typeof nav.tab_id !== "number")
48
+ throw new Error("The activated LinkedIn page is unavailable");
49
+ const result = await browser.dispatch<{
50
+ value?: Record<string, unknown>;
51
+ exception?: unknown;
52
+ }>("evaluate", {
53
+ tab_id: nav.tab_id,
54
+ await_promise: true,
55
+ expression: `(${fillLinkedInDraft.toString()})(${linkedInScriptArgument({ kind: ctx.actionKey, url, body })})`,
56
+ });
57
+ if (
58
+ result.exception ||
59
+ result.value?.prepared !== true ||
60
+ result.value?.submitted !== false
61
+ ) {
62
+ throw new Error(
63
+ `Draft could not be verified: ${JSON.stringify(result.exception ?? result.value)}`
64
+ );
65
+ }
66
+ return { success: true, output: { ...result.value, tab_id: nav.tab_id } };
67
+ } catch (error) {
68
+ return {
69
+ success: false,
70
+ error: error instanceof Error ? error.message : String(error),
71
+ };
72
+ }
73
+ }
@@ -7,6 +7,7 @@
7
7
  * connector that extracted them.
8
8
  */
9
9
 
10
+ import type { ChatUserIdentity } from "./chat-user-identity.js";
10
11
  import type { ConnectorIdentityModule } from "./connector-identity-module.js";
11
12
 
12
13
  /** Connector-owned identity namespaces (not SDK-global). */
@@ -19,6 +20,13 @@ export const LINKEDIN_IDENTITY = {
19
20
  SLUG: "linkedin_slug",
20
21
  /** Immutable member id from `urn:li:fsd_profile:<id>`. */
21
22
  MEMBER_ID: "linkedin_member_id",
23
+ /**
24
+ * A direct-message sender's member id, linking the sender to a Lobu member.
25
+ * Distinct from `linkedin_member_id`, the person-entity attribution key, so
26
+ * a chat link on a `$member` never collides with the contact entity the same
27
+ * sender's messages auto-create.
28
+ */
29
+ USER_MEMBER_ID: "linkedin_user_member_id",
22
30
  } as const;
23
31
 
24
32
  export type LinkedInIdentityNamespace =
@@ -66,6 +74,7 @@ export function normalizeLinkedInIdentityValue(
66
74
  case LINKEDIN_IDENTITY.SLUG:
67
75
  return normalizeLinkedInSlug(raw);
68
76
  case LINKEDIN_IDENTITY.MEMBER_ID:
77
+ case LINKEDIN_IDENTITY.USER_MEMBER_ID:
69
78
  return normalizeLinkedInMemberId(raw);
70
79
  default:
71
80
  return undefined;
@@ -78,3 +87,26 @@ export const linkedInIdentityModule: ConnectorIdentityModule = {
78
87
  recallNamespaces: [LINKEDIN_IDENTITY.SLUG, LINKEDIN_IDENTITY.MEMBER_ID],
79
88
  normalize: normalizeLinkedInIdentityValue,
80
89
  };
90
+
91
+ /**
92
+ * LinkedIn's direct-message sender model. Member ids are unique across
93
+ * LinkedIn, so there is no tenant axis: `teamId` is ignored and the scope is
94
+ * global.
95
+ *
96
+ * LinkedIn's OpenID sign-in returns an opaque `sub`, not the messaging member
97
+ * id, so no sign-in extractor writes this namespace; a link comes only from the
98
+ * explicit, sender-proven chat link offered in the direct message.
99
+ */
100
+ export const linkedInChatUserIdentity: ChatUserIdentity = {
101
+ platform: "linkedin",
102
+ providerId: "linkedin",
103
+ namespace: LINKEDIN_IDENTITY.USER_MEMBER_ID,
104
+ buildUserKey(_teamId, platformUserId) {
105
+ return normalizeLinkedInMemberId(platformUserId);
106
+ },
107
+ userKeyScope: () => ({ kind: "global" }),
108
+ // The stored key is the member id the adapter puts on a message author.
109
+ platformUserIdFromKey(key) {
110
+ return normalizeLinkedInMemberId(key);
111
+ },
112
+ };