@lobu/runtime-device 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 (115) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +33 -30
  3. package/npm-shrinkwrap.json +140 -124
  4. package/package.json +2 -1
  5. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +74 -1
  6. package/vendor/cli/dist/commands/_lib/apply/apply-cmd.js +9 -11
  7. package/vendor/cli/dist/commands/_lib/apply/client.d.ts +3 -11
  8. package/vendor/cli/dist/commands/_lib/apply/client.js +3 -3
  9. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +0 -6
  10. package/vendor/cli/dist/commands/_lib/apply/desired-state.js +6 -15
  11. package/vendor/cli/dist/commands/_lib/apply/diff.js +1 -0
  12. package/vendor/cli/dist/commands/_lib/apply/map-config.js +8 -0
  13. package/vendor/cli/dist/commands/_lib/view-bundler.d.ts +2 -9
  14. package/vendor/cli/dist/commands/_lib/view-bundler.js +25 -97
  15. package/vendor/cli/dist/config/define.d.ts +8 -0
  16. package/vendor/cli/dist/connectors/README.md +15 -2
  17. package/vendor/cli/dist/connectors/google_gmail.ts +1 -0
  18. package/vendor/cli/dist/connectors/jira-helpers.ts +313 -0
  19. package/vendor/cli/dist/connectors/jira.ts +29 -221
  20. package/vendor/cli/dist/connectors/linkedin-browser-script.ts +13 -0
  21. package/vendor/cli/dist/connectors/linkedin-draft-page.js +104 -0
  22. package/vendor/cli/dist/connectors/linkedin-drafts.ts +73 -0
  23. package/vendor/cli/dist/connectors/linkedin-identity.ts +32 -0
  24. package/vendor/cli/dist/connectors/linkedin-inbox-adapter.js +1182 -0
  25. package/vendor/cli/dist/connectors/linkedin-inbox.ts +156 -0
  26. package/vendor/cli/dist/connectors/linkedin-like.ts +114 -0
  27. package/vendor/cli/dist/connectors/linkedin-takeout.ts +577 -0
  28. package/vendor/cli/dist/connectors/linkedin.ts +4017 -0
  29. package/vendor/cli/dist/connectors/reddit.ts +92 -20
  30. package/vendor/cli/dist/connectors/slack.ts +1 -0
  31. package/vendor/cli/dist/connectors/takeout-utils.ts +240 -0
  32. package/vendor/cli/dist/connectors/tiktok-inbox-page.js +9 -9
  33. package/vendor/cli/dist/connectors/tiktok-web-page.js +21 -15
  34. package/vendor/cli/dist/connectors/tiktok_web.ts +63 -30
  35. package/vendor/cli/dist/connectors/whatsapp-web-adapter.js +104 -574
  36. package/vendor/cli/dist/connectors/whatsapp-web-helpers.ts +30 -444
  37. package/vendor/cli/dist/connectors/whatsapp-web-identity.ts +20 -6
  38. package/vendor/cli/dist/connectors/whatsapp_web.ts +46 -646
  39. package/vendor/cli/dist/connectors/x-dm-adapter.js +556 -0
  40. package/vendor/cli/dist/connectors/x-identity.ts +33 -2
  41. package/vendor/cli/dist/connectors/x.ts +266 -120
  42. package/vendor/cli/dist/runtime-components.json +4 -4
  43. package/vendor/cli/dist/templates/AGENTS.md.tmpl +12 -5
  44. package/vendor/cli/package.json +1 -1
  45. package/vendor/connector-sdk/dist/browser-handoff-banner.d.ts +39 -0
  46. package/vendor/connector-sdk/dist/browser-handoff-banner.js +175 -0
  47. package/vendor/connector-sdk/dist/browser-source-read.d.ts +52 -0
  48. package/vendor/connector-sdk/dist/browser-source-read.js +107 -0
  49. package/vendor/connector-sdk/dist/connector-types.d.ts +10 -0
  50. package/vendor/connector-sdk/dist/index.d.ts +3 -0
  51. package/vendor/connector-sdk/dist/index.js +2 -0
  52. package/vendor/connector-sdk/package.json +9 -1
  53. package/vendor/connector-worker/dist/agent-turn/gateway-tools.d.ts +2 -2
  54. package/vendor/connector-worker/dist/agent-turn/gateway-tools.js +2 -2
  55. package/vendor/connector-worker/dist/agent-turn/guest-entry.js +49 -8
  56. package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +650 -448
  57. package/vendor/connector-worker/dist/agent-turn/native-session.d.ts +12 -0
  58. package/vendor/connector-worker/dist/agent-turn/native-session.js +32 -6
  59. package/vendor/connector-worker/dist/agent-turn/types.d.ts +24 -3
  60. package/vendor/connector-worker/dist/daemon/agent-turn.js +5 -1
  61. package/vendor/connector-worker/dist/daemon/automation.d.ts +4 -11
  62. package/vendor/connector-worker/dist/daemon/automation.js +26 -21
  63. package/vendor/connector-worker/dist/daemon/client.d.ts +2 -4
  64. package/vendor/connector-worker/dist/daemon/client.js +0 -3
  65. package/vendor/connector-worker/dist/daemon/executor.js +0 -3
  66. package/vendor/connector-worker/dist/daemon/mac-device-daemon.d.ts +4 -3
  67. package/vendor/connector-worker/dist/daemon/mac-device-daemon.js +4 -10
  68. package/vendor/connector-worker/dist/daemon/native-bridge/executor.js +27 -25
  69. package/vendor/connector-worker/dist/daemon/start.js +3 -15
  70. package/vendor/connector-worker/dist/daemon/terminal-failure.js +0 -11
  71. package/vendor/connector-worker/dist/daemon/worker-id.d.ts +17 -0
  72. package/vendor/connector-worker/dist/daemon/worker-id.js +22 -0
  73. package/vendor/connector-worker/dist/isolate/prelude.js +93 -44
  74. package/vendor/connector-worker/dist/mac-device-daemon.js +14 -26
  75. package/vendor/connector-worker/package.json +1 -1
  76. package/vendor/core/dist/agent-policy.js +0 -3
  77. package/vendor/core/dist/agent-tooling.d.ts +1 -1
  78. package/vendor/core/dist/agent-tooling.js +3 -1
  79. package/vendor/core/dist/capabilities.d.ts +1 -1
  80. package/vendor/core/dist/capabilities.js +0 -1
  81. package/vendor/core/dist/connector-query-errors.d.ts +32 -0
  82. package/vendor/core/dist/connector-query-errors.js +41 -1
  83. package/vendor/core/dist/contracts/agent-settings.d.ts +6 -2
  84. package/vendor/core/dist/contracts/agent-settings.js +12 -1
  85. package/vendor/core/dist/contracts/tools/manage-conversations.js +2 -2
  86. package/vendor/core/dist/contracts/tools/manage-feeds.d.ts +14 -0
  87. package/vendor/core/dist/contracts/tools/manage-feeds.js +17 -0
  88. package/vendor/core/dist/contracts/tools/manage-views.d.ts +53 -234
  89. package/vendor/core/dist/contracts/tools/manage-views.js +50 -76
  90. package/vendor/core/dist/contracts/tools/view-attach.d.ts +5 -8
  91. package/vendor/core/dist/contracts/tools/view-attach.js +14 -31
  92. package/vendor/core/dist/contracts/tools/view-definition.d.ts +21 -0
  93. package/vendor/core/dist/contracts/tools/view-definition.js +165 -0
  94. package/vendor/core/dist/contracts/worker/protocol.d.ts +47 -133
  95. package/vendor/core/dist/contracts/worker/protocol.js +33 -62
  96. package/vendor/core/dist/device-pin-tombstones.d.ts +44 -0
  97. package/vendor/core/dist/device-pin-tombstones.js +57 -0
  98. package/vendor/core/dist/index.d.ts +3 -2
  99. package/vendor/core/dist/index.js +3 -1
  100. package/vendor/core/dist/logger.js +10 -25
  101. package/vendor/core/dist/suggestions.d.ts +15 -2
  102. package/vendor/core/dist/suggestions.js +48 -3
  103. package/vendor/core/dist/types.d.ts +26 -0
  104. package/vendor/core/dist/types.js +5 -0
  105. package/vendor/core/dist/utils/diagnostic-scrubber.js +258 -21
  106. package/vendor/core/dist/worker/wire.d.ts +0 -10
  107. package/vendor/core/package.json +16 -10
  108. package/vendor/postgres/cf/src/connection.js +18 -0
  109. package/vendor/postgres/cjs/src/connection.js +18 -0
  110. package/vendor/postgres/src/connection.js +18 -0
  111. package/vendor/connector-worker/dist/daemon/device-chat.d.ts +0 -9
  112. package/vendor/connector-worker/dist/daemon/device-chat.js +0 -61
  113. package/vendor/core/dist/contracts/worker/device-chat.d.ts +0 -4
  114. package/vendor/core/dist/contracts/worker/device-chat.js +0 -26
  115. /package/vendor/postgres/{.bun-tag-f39dafdb2305d504 → .bun-tag-2f292c6554a8475e} +0 -0
@@ -0,0 +1,556 @@
1
+ /**
2
+ * Serialized into the signed-in x.com page. All bindings must remain inside
3
+ * this function: the connector ships it with Function.prototype.toString().
4
+ *
5
+ * It reads and sends direct messages through the same-origin DM endpoints
6
+ * the x.com web client calls, with the page's own session cookies. It never
7
+ * opens /messages, which marks conversations read.
8
+ */
9
+ export function xDirectMessagesProgram() {
10
+ const key = "__lobuXDirectMessagesV1";
11
+ // An identical program keeps a warm tab's listeners; any code change
12
+ // reinstalls and asks the replaced program's listeners to reattach.
13
+ const version = xDirectMessagesProgram.toString();
14
+ if (globalThis[key]?.version === version) return;
15
+ globalThis[key]?.detach();
16
+ const listeners = new Map();
17
+ // X's public web-client bearer: the same constant every x.com visitor's
18
+ // browser sends with these requests. It names the web app, not a user; the
19
+ // account's authority comes only from the page's session cookies.
20
+ const WEB_CLIENT_BEARER =
21
+ "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA";
22
+ const DM_API = "/i/api/1.1/dm";
23
+ const DM_PARAMS =
24
+ "dm_users=true&include_groups=true&include_conversation_info=true&supports_reactions=true";
25
+ const CONVERSATION_ID = /^[0-9]{1,20}(?:-[0-9]{1,20})?$/;
26
+ const MESSAGE_REFERENCE = /^id:([0-9]{1,20}(?:-[0-9]{1,20})?):([0-9]{1,20})$/;
27
+ // A message being answered is recent; an id lookup reads at most this many
28
+ // conversation pages back.
29
+ const LOOKUP_PAGES = 5;
30
+ // One observation pass is bounded source work; `more` continues the round.
31
+ const UPDATE_PAGES_PER_PASS = 10;
32
+ // Matching recent text without a request id is ambiguous, not delivery proof.
33
+ const RESEND_WINDOW_MS = 10 * 60 * 1000;
34
+ const BATCH_EVENTS = 500;
35
+ const BATCH_BYTES = 128 * 1024;
36
+ function fail(message) {
37
+ throw new Error(`X direct messages: ${message}`);
38
+ }
39
+ function cookie(name) {
40
+ const raw = document.cookie
41
+ .split("; ")
42
+ .find((value) => value.startsWith(`${name}=`));
43
+ return raw ? decodeURIComponent(raw.slice(name.length + 1)) : "";
44
+ }
45
+ // `twid` carries the signed-in numeric user id; it is not a credential.
46
+ function account() {
47
+ const match = /^u=([0-9]+)$/.exec(cookie("twid"));
48
+ if (!match) fail("Sign in to X in the paired browser");
49
+ return match[1];
50
+ }
51
+ async function request(path, init = {}) {
52
+ const self = account();
53
+ const csrf = cookie("ct0");
54
+ if (!csrf) fail("Sign in to X in the paired browser");
55
+ const response = await fetch(path, {
56
+ credentials: "include",
57
+ signal: AbortSignal.timeout(20000),
58
+ ...init,
59
+ headers: {
60
+ authorization: WEB_CLIENT_BEARER,
61
+ "x-csrf-token": csrf,
62
+ "x-twitter-auth-type": "OAuth2Session",
63
+ "x-twitter-active-user": "yes",
64
+ ...init.headers,
65
+ },
66
+ });
67
+ if (!response.ok) {
68
+ let code = null;
69
+ try {
70
+ code = (await response.json())?.errors?.[0]?.code ?? null;
71
+ } catch {
72
+ code = null;
73
+ }
74
+ fail(
75
+ `request failed (HTTP ${response.status}${code === null ? "" : `, X error ${code}`})`,
76
+ );
77
+ }
78
+ const body = await response.json();
79
+ if (account() !== self) fail("X account changed during the request");
80
+ return body;
81
+ }
82
+ async function inbox() {
83
+ const body = await request(
84
+ `${DM_API}/inbox_initial_state.json?${DM_PARAMS}`,
85
+ );
86
+ return body?.inbox_initial_state ?? fail("Inbox state is unavailable");
87
+ }
88
+ async function conversation(conversationId, maxId) {
89
+ const page = maxId ? `&max_id=${encodeURIComponent(maxId)}` : "";
90
+ const body = await request(
91
+ `${DM_API}/conversation/${conversationId}.json?context=FETCH_DM_CONVERSATION&${DM_PARAMS}${page}`,
92
+ );
93
+ return body?.conversation_timeline ?? fail("Conversation is unavailable");
94
+ }
95
+ async function updates(cursor) {
96
+ const body = await request(
97
+ `${DM_API}/user_updates.json?cursor=${encodeURIComponent(cursor)}&${DM_PARAMS}`,
98
+ );
99
+ const events = body?.user_events ?? fail("Inbox updates are unavailable");
100
+ // A quiet inbox answers with only its cursor and last-seen ids: no
101
+ // `entries` key means nothing arrived. Inbox and conversation reads
102
+ // still require their entries.
103
+ return "entries" in events ? events : { ...events, entries: [] };
104
+ }
105
+ function timeOf(value) {
106
+ if (value === null || value === undefined || value === "")
107
+ return Number.NaN;
108
+ const millis = Number(value);
109
+ return Number.isFinite(millis) ? millis : Date.parse(String(value ?? ""));
110
+ }
111
+ // Message text with t.co links expanded and the attachment's own link removed.
112
+ function textOf(data) {
113
+ let value = String(data.text ?? "");
114
+ const mediaLinks = new Set(
115
+ Object.values(data.attachment ?? {}).flatMap((media) => [
116
+ media?.url,
117
+ media?.expanded_url,
118
+ ]),
119
+ );
120
+ for (const url of data.entities?.urls ?? []) {
121
+ if (typeof url?.url === "string" && typeof url.expanded_url === "string")
122
+ value = value
123
+ .split(url.url)
124
+ .join(
125
+ mediaLinks.has(url.url) || mediaLinks.has(url.expanded_url)
126
+ ? ""
127
+ : url.expanded_url,
128
+ );
129
+ }
130
+ for (const link of mediaLinks) {
131
+ if (typeof link === "string" && link) value = value.split(link).join("");
132
+ }
133
+ return value.trim();
134
+ }
135
+ function messagesOf(payload) {
136
+ if (!Array.isArray(payload?.entries))
137
+ fail("Response entries are unavailable");
138
+ const messages = [];
139
+ for (const entry of payload.entries) {
140
+ const message = entry?.message;
141
+ if (message) {
142
+ if (!message.message_data) fail("Message data is unavailable");
143
+ messages.push(message);
144
+ }
145
+ }
146
+ return messages;
147
+ }
148
+ // The one place a source row and its reference id are derived.
149
+ function rowsOf(payload, self) {
150
+ const users = payload?.users ?? {};
151
+ const conversations = payload?.conversations ?? {};
152
+ const rows = [];
153
+ for (const message of messagesOf(payload)) {
154
+ const data = message.message_data;
155
+ const messageId = String(message.id ?? data.id ?? "");
156
+ const conversationId = String(message.conversation_id ?? "");
157
+ const senderId = String(data.sender_id ?? "");
158
+ const time = timeOf(message.time ?? data.time);
159
+ if (
160
+ !/^[0-9]+$/.test(messageId) ||
161
+ !CONVERSATION_ID.test(conversationId) ||
162
+ !senderId ||
163
+ !Number.isFinite(time) ||
164
+ !Number.isFinite(new Date(time).getTime())
165
+ )
166
+ fail("Message identity or timestamp is invalid");
167
+ const info = conversations[conversationId];
168
+ const sender = users[senderId];
169
+ const text = textOf(data);
170
+ const isGroup =
171
+ typeof info?.type === "string"
172
+ ? info.type === "GROUP_DM"
173
+ : !conversationId.includes("-");
174
+ rows.push({
175
+ id: `${conversationId}:${messageId}`,
176
+ message_id: messageId,
177
+ conversation_id: conversationId,
178
+ conversation_name:
179
+ isGroup && typeof info?.name === "string" ? info.name : null,
180
+ sender_id: senderId,
181
+ sender_handle:
182
+ typeof sender?.screen_name === "string" ? sender.screen_name : null,
183
+ sender_name: typeof sender?.name === "string" ? sender.name : null,
184
+ from_me: senderId === self,
185
+ is_group: isGroup,
186
+ // A message request: the conversation sits in the untrusted inbox
187
+ // until the account accepts it.
188
+ is_request: info?.trusted === false,
189
+ text,
190
+ content_kind: text ? "text" : data.attachment ? "media" : "empty",
191
+ occurred_at: new Date(time).toISOString(),
192
+ });
193
+ }
194
+ return rows.sort(
195
+ (a, b) =>
196
+ b.occurred_at.localeCompare(a.occurred_at) || b.id.localeCompare(a.id),
197
+ );
198
+ }
199
+ async function readMessage(self, conversationId, messageId) {
200
+ let maxId;
201
+ for (let page = 0; page < LOOKUP_PAGES; page++) {
202
+ const timeline = await conversation(conversationId, maxId);
203
+ const row = rowsOf(timeline, self).find(
204
+ (candidate) => candidate.message_id === messageId,
205
+ );
206
+ if (row) return row;
207
+ if (timeline.status !== "HAS_MORE") return null;
208
+ if (!timeline.min_entry_id)
209
+ fail(
210
+ "Message lookup is incomplete: conversation cursor is unavailable",
211
+ );
212
+ maxId = String(timeline.min_entry_id);
213
+ }
214
+ fail("Message lookup is incomplete: conversation page limit reached");
215
+ }
216
+ async function read(input) {
217
+ const self = account();
218
+ const limit = Math.max(1, Math.min(100, Number(input.limit) || 20));
219
+ const query = typeof input.query === "string" ? input.query.trim() : "";
220
+ if (query) {
221
+ const match = MESSAGE_REFERENCE.exec(query);
222
+ if (!match) fail("Only id:<message id> queries are supported");
223
+ const row = await readMessage(self, match[1], match[2]);
224
+ return { rows: row ? [row] : [], hasMore: false };
225
+ }
226
+ // The inbox's recent state across conversations, not a history export.
227
+ const all = rowsOf(await inbox(), self);
228
+ let start = 0;
229
+ if (input.cursor) {
230
+ if (typeof input.cursor !== "string" || input.cursor.length > 1000)
231
+ fail("Invalid cursor");
232
+ const cursor = JSON.parse(input.cursor);
233
+ if (cursor?.v !== 1 || cursor.account !== self)
234
+ fail("Cursor belongs to a different account");
235
+ start = all.findIndex((row) => row.id === cursor.after) + 1;
236
+ if (!start) fail("Cursor expired; restart the read");
237
+ }
238
+ const rows = all.slice(start, start + limit);
239
+ const more = start + limit < all.length;
240
+ if (account() !== self) fail("X account changed during the read");
241
+ return {
242
+ rows,
243
+ hasMore: more,
244
+ ...(more
245
+ ? {
246
+ nextCursor: JSON.stringify({
247
+ v: 1,
248
+ account: self,
249
+ after: rows.at(-1).id,
250
+ }),
251
+ }
252
+ : {}),
253
+ };
254
+ }
255
+ async function digest(value) {
256
+ const bytes = await crypto.subtle.digest(
257
+ "SHA-256",
258
+ new TextEncoder().encode(value),
259
+ );
260
+ return [...new Uint8Array(bytes)]
261
+ .map((byte) => byte.toString(16).padStart(2, "0"))
262
+ .join("");
263
+ }
264
+ // X's client request id, derived from the caller's idempotency key so a
265
+ // retried send carries the same id and can recognise its earlier attempt.
266
+ async function requestIdOf(self, conversationId, idempotencyKey) {
267
+ const hex = await digest(
268
+ JSON.stringify([self, conversationId, idempotencyKey]),
269
+ );
270
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-${((Number.parseInt(hex[16], 16) & 3) | 8).toString(16)}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
271
+ }
272
+ // An outgoing message on the latest page that is this send's earlier attempt.
273
+ // A matching body cannot identify a send: independent replies can share text.
274
+ function earlierAttempt(timeline, self, requestId, text) {
275
+ const requestIds = new Map(
276
+ messagesOf(timeline).map((message) => [
277
+ String(message.id),
278
+ typeof message.request_id === "string" ? message.request_id : null,
279
+ ]),
280
+ );
281
+ const since = Date.now() - RESEND_WINDOW_MS;
282
+ return (
283
+ rowsOf(timeline, self).find((row) => {
284
+ if (!row.from_me) return false;
285
+ const sent = requestIds.get(row.message_id);
286
+ if (sent) return sent === requestId;
287
+ if (row.text === text.trim() && Date.parse(row.occurred_at) >= since)
288
+ fail(
289
+ "Matching recent text has no request id; cannot identify the earlier send. Inspect the conversation before sending again",
290
+ );
291
+ return false;
292
+ }) ?? null
293
+ );
294
+ }
295
+ async function send(input) {
296
+ const self = account();
297
+ const conversationId = String(input.conversation_id ?? "");
298
+ if (!CONVERSATION_ID.test(conversationId))
299
+ fail("conversation_id must be an exact X DM conversation id");
300
+ if (
301
+ conversationId.includes("-") &&
302
+ !conversationId.split("-").includes(self)
303
+ )
304
+ fail("The conversation does not belong to the signed-in account");
305
+ const text = typeof input.text === "string" ? input.text : "";
306
+ if (!text.trim()) fail("text is required");
307
+ const idempotencyKey =
308
+ typeof input.idempotency_key === "string" ? input.idempotency_key : "";
309
+ if (!idempotencyKey) fail("idempotency_key is required");
310
+ const requestId = await requestIdOf(self, conversationId, idempotencyKey);
311
+ // Only an existing conversation the account can read is a send target.
312
+ const before = await conversation(conversationId);
313
+ const prior = earlierAttempt(before, self, requestId, text);
314
+ if (prior) {
315
+ return {
316
+ sent: true,
317
+ deduplicated: true,
318
+ id: prior.id,
319
+ message_id: prior.message_id,
320
+ conversation_id: conversationId,
321
+ occurred_at: prior.occurred_at,
322
+ };
323
+ }
324
+ if (account() !== self) fail("X account changed before the send");
325
+ const response = await request(`${DM_API}/new2.json`, {
326
+ method: "POST",
327
+ headers: { "content-type": "application/json" },
328
+ body: JSON.stringify({
329
+ conversation_id: conversationId,
330
+ recipient_ids: false,
331
+ request_id: requestId,
332
+ text,
333
+ cards_platform: "Web-12",
334
+ include_cards: 1,
335
+ include_quote_count: true,
336
+ dm_users: false,
337
+ }),
338
+ });
339
+ const created = messagesOf(response).find(
340
+ (message) => String(message.conversation_id) === conversationId,
341
+ );
342
+ const messageId = created ? String(created.id ?? "") : "";
343
+ if (!/^[0-9]+$/.test(messageId))
344
+ fail("X accepted the send but returned no message id");
345
+ const after = await conversation(conversationId);
346
+ const landed = rowsOf(after, self).find(
347
+ (row) => row.message_id === messageId && row.from_me,
348
+ );
349
+ if (!landed)
350
+ fail(
351
+ `sent message ${messageId} is not visible in the conversation; delivery is uncertain. Inspect the conversation before sending again`,
352
+ );
353
+ return {
354
+ sent: true,
355
+ deduplicated: false,
356
+ id: landed.id,
357
+ message_id: messageId,
358
+ conversation_id: conversationId,
359
+ occurred_at: landed.occurred_at,
360
+ };
361
+ }
362
+ // The update cursor is the whole position: a first pass records where the
363
+ // inbox stands now, and each later pass reports what arrived after it.
364
+ async function snapshot(previous, self) {
365
+ if (!previous) {
366
+ const state = await inbox();
367
+ messagesOf(state);
368
+ if (typeof state.cursor !== "string" || !state.cursor)
369
+ fail("Inbox cursor is unavailable");
370
+ return {
371
+ checkpoint: {
372
+ account: self,
373
+ cursor: state.cursor,
374
+ started_at: Date.now(),
375
+ },
376
+ events: [],
377
+ more: false,
378
+ };
379
+ }
380
+ const events = [];
381
+ const observed = new Set();
382
+ let cursor = previous.cursor;
383
+ let more = false;
384
+ for (let page = 1; ; page++) {
385
+ const batch = await updates(cursor);
386
+ for (const row of rowsOf(batch, self).reverse()) {
387
+ if (observed.has(row.id)) continue;
388
+ observed.add(row.id);
389
+ events.push({
390
+ id: row.id,
391
+ event_type: "message.created",
392
+ resource_type: "message",
393
+ resource_ref: row.id,
394
+ occurred_at: row.occurred_at,
395
+ });
396
+ }
397
+ if (typeof batch.cursor !== "string" || !batch.cursor)
398
+ fail("Inbox update cursor is unavailable");
399
+ const next = batch.cursor;
400
+ const progressed = next !== cursor && (batch.entries?.length ?? 0) > 0;
401
+ cursor = next;
402
+ if (!progressed) break;
403
+ if (page === UPDATE_PAGES_PER_PASS) {
404
+ more = true;
405
+ break;
406
+ }
407
+ }
408
+ if (account() !== self) fail("X account changed during observation");
409
+ return {
410
+ checkpoint: { account: self, cursor, started_at: previous.started_at },
411
+ events,
412
+ more,
413
+ };
414
+ }
415
+ // Ordered batches of at most 500 references and 128 KiB. Only the final
416
+ // batch carries the checkpoint, so an interruption cannot skip references.
417
+ async function batchesOf(previous, result) {
418
+ const next = { x_dm: result.checkpoint };
419
+ const { events } = result;
420
+ const base = `x_dm:${await digest(JSON.stringify([previous, next, events]))}`;
421
+ const size = (batch) =>
422
+ new TextEncoder().encode(JSON.stringify(batch)).length;
423
+ const batches = [];
424
+ for (let offset = 0; ; ) {
425
+ const through = (end) => ({
426
+ id: `${base}:${offset}`,
427
+ events: events.slice(offset, end),
428
+ ...(end === events.length
429
+ ? { checkpoint: { previous, next }, more: result.more }
430
+ : {}),
431
+ });
432
+ let end = Math.min(offset + BATCH_EVENTS, events.length);
433
+ let batch = through(end);
434
+ while (size(batch) > BATCH_BYTES && end - offset > 1) {
435
+ end = offset + Math.floor((end - offset) / 2);
436
+ batch = through(end);
437
+ }
438
+ if (size(batch) > BATCH_BYTES)
439
+ fail("Source reference batch exceeds the browser record limit");
440
+ batches.push(batch);
441
+ if (end === events.length) return batches;
442
+ offset = end;
443
+ }
444
+ }
445
+ const active = (listener) => listeners.get(listener.id) === listener;
446
+ function post(listener, record) {
447
+ window.postMessage(
448
+ {
449
+ type: "lobu-feed-record",
450
+ token: listener.token,
451
+ sequence: ++listener.sequence,
452
+ record,
453
+ },
454
+ location.origin,
455
+ );
456
+ }
457
+ // The one way a listener ends. A reason asks the bridge to reattach from the
458
+ // durable checkpoint; only an explicit stop or a same-binding relisten is silent.
459
+ function stop(listener, reason) {
460
+ if (!active(listener)) return;
461
+ clearTimeout(listener.timer);
462
+ window.removeEventListener("message", listener.onReply);
463
+ listeners.delete(listener.id);
464
+ if (reason)
465
+ post(listener, {
466
+ id: "x:live_messages:source-observation-error",
467
+ source_error: reason,
468
+ });
469
+ }
470
+ // Called by a replacing program version: its listeners cannot inherit this
471
+ // one's undelivered batches, so each reattaches instead of going silent.
472
+ function detach() {
473
+ for (const listener of [...listeners.values()])
474
+ stop(
475
+ listener,
476
+ "X source program was replaced; reattach from the durable checkpoint",
477
+ );
478
+ }
479
+ // Unacknowledged batches are reposted unchanged on the next tick.
480
+ async function poll(listener) {
481
+ if (!active(listener)) return;
482
+ try {
483
+ if (!listener.batches.length) {
484
+ if (account() !== listener.account)
485
+ fail("X account changed; reconnect this source");
486
+ const { checkpoint } = listener;
487
+ const result = await snapshot(checkpoint?.x_dm, listener.account);
488
+ listener.batches = await batchesOf(checkpoint, result);
489
+ }
490
+ if (active(listener)) post(listener, listener.batches[0]);
491
+ } catch {
492
+ stop(
493
+ listener,
494
+ "X source observation failed; reconnect to recover without skipping messages",
495
+ );
496
+ }
497
+ if (active(listener))
498
+ listener.timer = setTimeout(() => poll(listener), 60000);
499
+ }
500
+ function receive(listener, event) {
501
+ if (
502
+ event.source !== window ||
503
+ event.origin !== location.origin ||
504
+ event.data?.token !== listener.token
505
+ )
506
+ return;
507
+ if (event.data.type === "lobu-feed-record:stop") return stop(listener);
508
+ if (
509
+ event.data.type !== "lobu-feed-record:ack" ||
510
+ event.data.sequence !== listener.sequence
511
+ )
512
+ return;
513
+ if (event.data.ok === false)
514
+ return stop(
515
+ listener,
516
+ "X source delivery was rejected; reattach from the durable checkpoint",
517
+ );
518
+ if (event.data.ok && listener.batches.length) {
519
+ // Receipt means the browser durably buffered the batch. Only the server
520
+ // commits the final batch's checkpoint; a reattach starts from that value.
521
+ const done = listener.batches.shift();
522
+ if (done.checkpoint) listener.checkpoint = done.checkpoint.next;
523
+ else post(listener, listener.batches[0]);
524
+ }
525
+ }
526
+ async function listen(input) {
527
+ if (!input.bridge_id || !input.token)
528
+ fail("Source subscription binding is required");
529
+ const self = account();
530
+ const previous = input.checkpoint?.x_dm;
531
+ if (previous && previous.account !== self)
532
+ fail("Source checkpoint belongs to another account");
533
+ const prior = listeners.get(input.bridge_id);
534
+ if (prior) stop(prior);
535
+ const listener = {
536
+ id: input.bridge_id,
537
+ token: input.token,
538
+ account: self,
539
+ // The last posted record; only its receipt may advance delivery.
540
+ sequence: 0,
541
+ // The checkpoint the next snapshot starts from, set by the final batch's receipt.
542
+ checkpoint: input.checkpoint ?? null,
543
+ // Undelivered batches of the current snapshot, in order.
544
+ batches: [],
545
+ timer: null,
546
+ };
547
+ listener.onReply = (event) => receive(listener, event);
548
+ listeners.set(listener.id, listener);
549
+ window.addEventListener("message", listener.onReply);
550
+ await poll(listener);
551
+ if (!listeners.has(listener.id))
552
+ fail("Unable to attach source subscription");
553
+ return { listening: true };
554
+ }
555
+ globalThis[key] = { version, read, listen, send, detach };
556
+ }
@@ -1,12 +1,13 @@
1
1
  /**
2
2
  * X (Twitter) connector identity namespaces and normalization.
3
3
  *
4
- * Single source of truth for x_user_id / x_handle rules. The connector and
5
- * server entity-link ingestion import from here — not from connector-sdk.
4
+ * Single source of truth for X account, handle and chat identity rules. The
5
+ * connector and server entity-link ingestion import from here, not connector-sdk.
6
6
  * Connector-specific identity knowledge stays in the connector package so
7
7
  * core code never names X.
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). */
@@ -15,6 +16,13 @@ export const X_IDENTITY = {
15
16
  USER_ID: 'x_user_id',
16
17
  /** Mutable/reusable @handle — secondary claim, not recall-indexed. */
17
18
  HANDLE: 'x_handle',
19
+ /**
20
+ * A direct-message sender's numeric user id, linking the sender to a Lobu
21
+ * member. Distinct from `x_user_id`, the person-entity attribution key, so a
22
+ * chat link on a `$member` never collides with the contact entity the same
23
+ * account's posts and messages auto-create.
24
+ */
25
+ CHAT_USER_ID: 'x_chat_user_id',
18
26
  } as const;
19
27
 
20
28
  export type XIdentityNamespace = (typeof X_IDENTITY)[keyof typeof X_IDENTITY];
@@ -45,6 +53,7 @@ export function normalizeXIdentityValue(
45
53
  ): string | null | undefined {
46
54
  switch (namespace) {
47
55
  case X_IDENTITY.USER_ID:
56
+ case X_IDENTITY.CHAT_USER_ID:
48
57
  return normalizeXUserId(raw);
49
58
  case X_IDENTITY.HANDLE:
50
59
  return normalizeXHandle(raw);
@@ -61,3 +70,25 @@ export const xIdentityModule: ConnectorIdentityModule = {
61
70
  recallNamespaces: [X_IDENTITY.USER_ID],
62
71
  normalize: normalizeXIdentityValue,
63
72
  };
73
+
74
+ /**
75
+ * X's direct-message sender model. Numeric user ids are unique across X, so
76
+ * there is no tenant axis: `teamId` is ignored and the scope is global.
77
+ *
78
+ * Signing in with X proves it: Better Auth's X provider is `twitter`, and the
79
+ * account id it stores is the same numeric user id a direct message carries.
80
+ * The chat link offered in a direct message proves it too, within the
81
+ * workspace that issued it.
82
+ */
83
+ export const xChatUserIdentity: ChatUserIdentity = {
84
+ platform: 'x',
85
+ providerId: 'twitter',
86
+ namespace: X_IDENTITY.CHAT_USER_ID,
87
+ buildUserKey(_teamId, platformUserId) {
88
+ return normalizeXUserId(platformUserId);
89
+ },
90
+ userKeyScope: () => ({ kind: 'global' }),
91
+ platformUserIdFromKey(key) {
92
+ return normalizeXUserId(key);
93
+ },
94
+ };