@lobu/runtime-device 24.7.0 → 24.9.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 (88) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +35 -51
  3. package/npm-shrinkwrap.json +214 -334
  4. package/package.json +4 -2
  5. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +14 -3
  6. package/vendor/cli/dist/chrome-extension/manifest.json +5 -4
  7. package/vendor/cli/dist/chrome-extension/tools.js +2 -3
  8. package/vendor/cli/dist/commands/_lib/apply/apply-cmd.js +27 -0
  9. package/vendor/cli/dist/commands/_lib/apply/client.d.ts +16 -5
  10. package/vendor/cli/dist/commands/_lib/apply/client.js +31 -9
  11. package/vendor/cli/dist/commands/_lib/apply/deployment.d.ts +8 -12
  12. package/vendor/cli/dist/commands/_lib/apply/deployment.js +14 -1
  13. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +8 -4
  14. package/vendor/cli/dist/commands/_lib/apply/desired-state.js +2 -1
  15. package/vendor/cli/dist/commands/_lib/apply/diff.d.ts +26 -7
  16. package/vendor/cli/dist/commands/_lib/apply/diff.js +101 -30
  17. package/vendor/cli/dist/commands/_lib/apply/map-config.js +29 -2
  18. package/vendor/cli/dist/commands/_lib/apply/render.js +2 -0
  19. package/vendor/cli/dist/commands/_lib/apply/shared.d.ts +20 -0
  20. package/vendor/cli/dist/commands/_lib/apply/shared.js +22 -0
  21. package/vendor/cli/dist/commands/_lib/init-from-org/bootstrap.js +14 -0
  22. package/vendor/cli/dist/commands/dev.js +28 -4
  23. package/vendor/cli/dist/commands/memory/_lib/seed-cmd.js +6 -2
  24. package/vendor/cli/dist/config/define.d.ts +21 -3
  25. package/vendor/cli/dist/connectors/README.md +6 -2
  26. package/vendor/cli/dist/connectors/github.ts +16 -3
  27. package/vendor/cli/dist/connectors/imessage.ts +953 -0
  28. package/vendor/cli/dist/connectors/linkedin.ts +20 -377
  29. package/vendor/cli/dist/connectors/market_quotes.ts +388 -91
  30. package/vendor/cli/dist/connectors/postgres.ts +21 -14
  31. package/vendor/cli/dist/connectors/x-dm-adapter.js +55 -21
  32. package/vendor/cli/dist/connectors/x.ts +1 -1
  33. package/vendor/cli/dist/runtime-components.json +4 -4
  34. package/vendor/cli/dist/templates/AGENTS.md.tmpl +1 -1
  35. package/vendor/cli/package.json +1 -1
  36. package/vendor/connector-sdk/dist/connector-types.d.ts +23 -2
  37. package/vendor/connector-sdk/package.json +1 -1
  38. package/vendor/connector-worker/dist/daemon/automation.js +7 -4
  39. package/vendor/connector-worker/dist/env.d.ts +15 -0
  40. package/vendor/connector-worker/dist/env.js +17 -0
  41. package/vendor/connector-worker/dist/executor/isolate.d.ts +3 -1
  42. package/vendor/connector-worker/dist/executor/isolate.js +32 -8
  43. package/vendor/connector-worker/package.json +1 -1
  44. package/vendor/core/dist/classify-error.d.ts +3 -4
  45. package/vendor/core/dist/classify-error.js +8 -8
  46. package/vendor/core/dist/connector-query-errors.d.ts +6 -0
  47. package/vendor/core/dist/connector-query-errors.js +4 -0
  48. package/vendor/core/dist/contracts/tools/collection-presentation.d.ts +17 -1
  49. package/vendor/core/dist/contracts/tools/collection-presentation.js +27 -3
  50. package/vendor/core/dist/contracts/tools/manage-automations.d.ts +39 -0
  51. package/vendor/core/dist/contracts/tools/manage-automations.js +11 -1
  52. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +1 -1
  53. package/vendor/core/dist/contracts/tools/manage-entity.d.ts +2 -0
  54. package/vendor/core/dist/contracts/tools/manage-entity.js +7 -0
  55. package/vendor/core/dist/contracts/tools/manage-feeds.d.ts +2 -0
  56. package/vendor/core/dist/contracts/tools/manage-feeds.js +3 -0
  57. package/vendor/core/dist/contracts/tools/manage-views.d.ts +249 -7
  58. package/vendor/core/dist/contracts/tools/manage-views.js +83 -21
  59. package/vendor/core/dist/contracts/tools/navigation.d.ts +248 -0
  60. package/vendor/core/dist/contracts/tools/navigation.js +284 -0
  61. package/vendor/core/dist/contracts/tools/view-attach.d.ts +7 -0
  62. package/vendor/core/dist/contracts/tools/view-attach.js +15 -0
  63. package/vendor/core/dist/contracts/tools/view-content-hash.d.ts +4 -1
  64. package/vendor/core/dist/contracts/tools/view-content-hash.js +4 -2
  65. package/vendor/core/dist/contracts/tools/view-definition.d.ts +2 -0
  66. package/vendor/core/dist/contracts/tools/view-definition.js +52 -0
  67. package/vendor/core/dist/contracts/tools/view-host.d.ts +68 -0
  68. package/vendor/core/dist/contracts/tools/view-host.js +30 -1
  69. package/vendor/core/dist/contracts/tools/view-scope.d.ts +31 -0
  70. package/vendor/core/dist/contracts/tools/view-scope.js +45 -0
  71. package/vendor/core/dist/error-report.js +1 -0
  72. package/vendor/core/dist/errors.d.ts +17 -24
  73. package/vendor/core/dist/errors.js +17 -24
  74. package/vendor/core/dist/types.d.ts +0 -6
  75. package/vendor/core/package.json +11 -1
  76. package/vendor/views/dist/api.d.ts +30 -5
  77. package/vendor/views/dist/api.js +22 -8
  78. package/vendor/views/dist/bridge.d.ts +17 -0
  79. package/vendor/views/dist/bridge.js +49 -1
  80. package/vendor/views/dist/components.d.ts +27 -5
  81. package/vendor/views/dist/components.js +57 -7
  82. package/vendor/views/dist/embed.d.ts +98 -0
  83. package/vendor/views/dist/embed.js +418 -0
  84. package/vendor/views/dist/index.d.ts +3 -1
  85. package/vendor/views/dist/index.js +1 -0
  86. package/vendor/views/package.json +1 -1
  87. package/vendor/cli/dist/connectors/linkedin-takeout.ts +0 -577
  88. package/vendor/cli/dist/connectors/takeout-utils.ts +0 -240
@@ -0,0 +1,953 @@
1
+ import {
2
+ ConnectorRuntime,
3
+ type ActionContext,
4
+ type ActionDefinition,
5
+ type ActionResult,
6
+ type RuntimeConnectorDefinition,
7
+ } from '@lobu/connector-sdk';
8
+
9
+ /**
10
+ * iMessage/SMS over an existing os.shell connection.
11
+ *
12
+ * `run` is the only os.shell operation this connector uses: every command is
13
+ * a fixed argv with user input quoted as one argument, and every SQL statement
14
+ * carrying a value arrives on stdin (only the constant pre-send sentinel query
15
+ * rides in argv). SQLite and osascript are macOS system binaries, so no
16
+ * project install step is involved.
17
+ */
18
+ const APPLE_EPOCH_OFFSET_SECONDS = 978307200;
19
+ const SQLITE_BINARY = '/usr/bin/sqlite3';
20
+ const OSASCRIPT_BINARY = '/usr/bin/osascript';
21
+ // Double quotes keep paths with spaces working; $HOME is expanded by the
22
+ // device shell (zsh -l on a Mac), not by this connector.
23
+ const CHAT_DB_PATH = '"$HOME/Library/Messages/chat.db"';
24
+ const READ_TIMEOUT_MS = 15000;
25
+ const WRITE_TIMEOUT_MS = 30000;
26
+ const MAX_SEARCH_LENGTH = 500;
27
+ const MAX_SEND_LENGTH = 4000;
28
+ // os.shell caps stdout at 1 MiB. Keep each text/blob column small and page
29
+ // sizes bounded so a full page stays below that cap. Plain `text` over this
30
+ // size is dropped; `attributedBody` is cut to its first bytes, which hold the
31
+ // string ahead of the attribute data, so only text that itself overflows is
32
+ // lost.
33
+ const MAX_STORED_TEXT_BYTES = 2048;
34
+ const MAX_SHELL_STDOUT_CHARS = 1_048_576;
35
+
36
+ const SEND_SCRIPT = `on run argv
37
+ set targetKind to item 1 of argv
38
+ set targetValue to item 2 of argv
39
+ set body to item 3 of argv
40
+ tell application "Messages"
41
+ if targetKind is "chat" then
42
+ set targetChat to chat id targetValue
43
+ send body to targetChat
44
+ else
45
+ set targetService to first service whose service type is iMessage
46
+ set targetBuddy to participant targetValue of targetService
47
+ send body to targetBuddy
48
+ end if
49
+ end tell
50
+ return "sent"
51
+ end run
52
+ `;
53
+
54
+ /** Shell only transports argv; quoting is the injection boundary. */
55
+ export function quoteShellArg(value: string): string {
56
+ if (value.includes('\0')) throw new Error('Expected a string without NUL bytes');
57
+ return "'" + value.replaceAll("'", "'\\''") + "'";
58
+ }
59
+
60
+ /** A SQLite string literal. Values always travel on stdin, never in argv. */
61
+ export function sqlStringLiteral(value: string): string {
62
+ if (value.includes('\0')) throw new Error('Expected a string without NUL bytes');
63
+ return "'" + value.replaceAll("'", "''") + "'";
64
+ }
65
+
66
+ export function isoFromAppleDate(value: unknown): string | null {
67
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return null;
68
+ const milliseconds = value / 1e6 + APPLE_EPOCH_OFFSET_SECONDS * 1000;
69
+ const date = new Date(milliseconds);
70
+ if (Number.isNaN(date.getTime())) return null;
71
+ return date.toISOString();
72
+ }
73
+
74
+ /** Exact nanosecond lower bound for `message.date`; seconds stay integral. */
75
+ export function appleNsSince(iso: string): string {
76
+ const milliseconds = Date.parse(iso);
77
+ if (!Number.isFinite(milliseconds)) throw new Error('since must be an ISO timestamp');
78
+ const seconds = Math.floor(milliseconds / 1000) - APPLE_EPOCH_OFFSET_SECONDS;
79
+ return `${seconds}000000000`;
80
+ }
81
+
82
+ function hexNibble(code: number): number {
83
+ if (code >= 48 && code <= 57) return code - 48;
84
+ if (code >= 65 && code <= 70) return code - 55;
85
+ if (code >= 97 && code <= 102) return code - 87;
86
+ return -1;
87
+ }
88
+
89
+ function asciiAt(bytes: Uint8Array, start: number, text: string): boolean {
90
+ if (start + text.length > bytes.length) return false;
91
+ for (let i = 0; i < text.length; i++) {
92
+ if (bytes[start + i] !== text.charCodeAt(i)) return false;
93
+ }
94
+ return true;
95
+ }
96
+
97
+ function decodeStringAt(
98
+ bytes: Uint8Array,
99
+ index: number,
100
+ littleEndian: boolean,
101
+ ): string | null {
102
+ const head = bytes[index];
103
+ if (head === undefined) return null;
104
+ let length: number;
105
+ let start = index + 1;
106
+ if (head === 0x81 || head === 0x82) {
107
+ const width = head === 0x81 ? 2 : 4;
108
+ if (start + width > bytes.length) return null;
109
+ length = 0;
110
+ for (let offset = 0; offset < width; offset++) {
111
+ const byte = bytes[start + offset] as number;
112
+ const shift = (littleEndian ? offset : width - 1 - offset) * 8;
113
+ length += byte * 2 ** shift;
114
+ }
115
+ start += width;
116
+ } else if (head <= 0x7f) {
117
+ length = head;
118
+ } else {
119
+ return null;
120
+ }
121
+ if (start + length > bytes.length) return null;
122
+ try {
123
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(start, start + length));
124
+ } catch {
125
+ return null;
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Apple archived attributed strings are typedstream object graphs. The plain
131
+ * message body is the first NSString's bytes; there is no need to model the
132
+ * attribute dictionaries that follow it. Public format description:
133
+ * 0x04 0x0b "streamtyped", then object/type tags, then the string tag 0x01 0x2b,
134
+ * a length (0x81 + u16 or 0x82 + u32 for longer bodies), and UTF-8 bytes.
135
+ */
136
+ export function decodeTypedStream(bytes: Uint8Array): string | null {
137
+ if (bytes.length < 14 || bytes[0] !== 0x04 || bytes[1] !== 0x0b) return null;
138
+ let littleEndian: boolean;
139
+ if (asciiAt(bytes, 2, 'streamtyped')) littleEndian = true;
140
+ else if (asciiAt(bytes, 2, 'typedstream')) littleEndian = false;
141
+ else return null;
142
+ for (let index = 13; index + 1 < bytes.length; index++) {
143
+ if (bytes[index] !== 0x01 || bytes[index + 1] !== 0x2b) continue;
144
+ return decodeStringAt(bytes, index + 2, littleEndian);
145
+ }
146
+ return null;
147
+ }
148
+
149
+ /** Decode `hex(attributedBody)`; malformed blobs are data, not page failures. */
150
+ export function decodeAttributedBody(hex: unknown): string | null {
151
+ if (typeof hex !== 'string' || hex.length === 0 || hex.length % 2 !== 0) return null;
152
+ const bytes = new Uint8Array(hex.length / 2);
153
+ for (let index = 0; index < bytes.length; index++) {
154
+ const high = hexNibble(hex.charCodeAt(index * 2));
155
+ const low = hexNibble(hex.charCodeAt(index * 2 + 1));
156
+ if (high < 0 || low < 0) return null;
157
+ bytes[index] = high * 16 + low;
158
+ }
159
+ return decodeTypedStream(bytes);
160
+ }
161
+
162
+ export interface MessageRowOutput {
163
+ rowid: number;
164
+ guid: string | null;
165
+ chat_id: number | null;
166
+ sender: string | null;
167
+ is_from_me: boolean;
168
+ service: string | null;
169
+ text: string | null;
170
+ text_source: 'text' | 'attributedBody' | null;
171
+ text_truncated: boolean;
172
+ has_attachments: boolean;
173
+ sent_at: string | null;
174
+ is_delivered: boolean;
175
+ is_sent: boolean;
176
+ error: number;
177
+ }
178
+
179
+ export interface ChatRowOutput {
180
+ chat_id: number;
181
+ guid: string | null;
182
+ display_name: string | null;
183
+ chat_identifier: string | null;
184
+ participants: string[];
185
+ service: string | null;
186
+ last_message_at: string | null;
187
+ }
188
+
189
+ function numberOrNull(value: unknown): number | null {
190
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
191
+ }
192
+
193
+ function stringOrNull(value: unknown): string | null {
194
+ return typeof value === 'string' ? value : null;
195
+ }
196
+
197
+ function flag(value: unknown): boolean {
198
+ return value === 1 || value === true;
199
+ }
200
+
201
+ export function mapMessageRow(row: Record<string, unknown>): MessageRowOutput {
202
+ const fromMe = flag(row.is_from_me);
203
+ const rawText = stringOrNull(row.text);
204
+ let text = rawText !== null && rawText.length > 0 ? rawText : null;
205
+ let textSource: 'text' | 'attributedBody' | null = text === null ? null : 'text';
206
+ if (text === null) {
207
+ const decoded = decodeAttributedBody(row.attributed_body_hex);
208
+ if (decoded !== null) {
209
+ text = decoded;
210
+ textSource = 'attributedBody';
211
+ }
212
+ }
213
+ return {
214
+ rowid: numberOrNull(row.rowid) ?? 0,
215
+ guid: stringOrNull(row.guid),
216
+ chat_id: numberOrNull(row.chat_id),
217
+ sender: fromMe ? 'me' : stringOrNull(row.sender),
218
+ is_from_me: fromMe,
219
+ service: stringOrNull(row.service),
220
+ text,
221
+ text_source: textSource,
222
+ text_truncated:
223
+ text === null && (flag(row.text_truncated) || flag(row.body_truncated)),
224
+ has_attachments: flag(row.has_attachments),
225
+ sent_at: isoFromAppleDate(row.date),
226
+ is_delivered: flag(row.is_delivered),
227
+ is_sent: flag(row.is_sent),
228
+ error: numberOrNull(row.error) ?? 0,
229
+ };
230
+ }
231
+
232
+ export function listChatsSql(limit: number): string {
233
+ return `SELECT c.ROWID AS chat_id, c.guid AS guid, c.display_name AS display_name,
234
+ c.chat_identifier AS chat_identifier, c.service_name AS service,
235
+ MAX(m.date) AS last_message_date,
236
+ (SELECT json_group_array(h.id)
237
+ FROM chat_handle_join chj
238
+ JOIN handle h ON h.ROWID = chj.handle_id
239
+ WHERE chj.chat_id = c.ROWID) AS participants_json
240
+ FROM chat c
241
+ JOIN chat_message_join cmj ON cmj.chat_id = c.ROWID
242
+ JOIN message m ON m.ROWID = cmj.message_id
243
+ GROUP BY c.ROWID
244
+ ORDER BY last_message_date DESC, c.ROWID DESC
245
+ LIMIT ${limit};`;
246
+ }
247
+
248
+ export function participantsFromJson(value: unknown): string[] {
249
+ if (typeof value !== 'string' || value.length === 0) return [];
250
+ let parsed: unknown;
251
+ try {
252
+ parsed = JSON.parse(value);
253
+ } catch {
254
+ return [];
255
+ }
256
+ if (!Array.isArray(parsed)) return [];
257
+ const handles = parsed.filter(
258
+ (item): item is string => typeof item === 'string' && item.length > 0,
259
+ );
260
+ return [...new Set(handles)].sort();
261
+ }
262
+
263
+ function messageColumns(chatId: string): string {
264
+ return `m.ROWID AS rowid, m.guid AS guid, ${chatId} AS chat_id,
265
+ h.id AS sender, m.is_from_me AS is_from_me, m.service AS service,
266
+ CASE WHEN length(CAST(m.text AS BLOB)) <= ${MAX_STORED_TEXT_BYTES}
267
+ THEN m.text ELSE NULL END AS text,
268
+ CASE WHEN length(CAST(m.text AS BLOB)) > ${MAX_STORED_TEXT_BYTES}
269
+ THEN 1 ELSE 0 END AS text_truncated,
270
+ hex(substr(m.attributedBody, 1, ${MAX_STORED_TEXT_BYTES})) AS attributed_body_hex,
271
+ CASE WHEN length(m.attributedBody) > ${MAX_STORED_TEXT_BYTES}
272
+ THEN 1 ELSE 0 END AS body_truncated,
273
+ m.cache_has_attachments AS has_attachments, m.date AS date,
274
+ m.is_delivered AS is_delivered, m.is_sent AS is_sent, m.error AS error`;
275
+ }
276
+
277
+ export function readChatSql(
278
+ chatId: number,
279
+ beforeRowid: number | null,
280
+ limit: number,
281
+ ): string {
282
+ return `SELECT ${messageColumns('cmj.chat_id')}
283
+ FROM message m
284
+ JOIN chat_message_join cmj ON cmj.message_id = m.ROWID
285
+ LEFT JOIN handle h ON h.ROWID = m.handle_id
286
+ WHERE cmj.chat_id = ${chatId}${beforeRowid === null ? '' : ` AND m.ROWID < ${beforeRowid}`}
287
+ ORDER BY m.ROWID DESC
288
+ LIMIT ${limit};`;
289
+ }
290
+
291
+ export function searchMessagesSql(
292
+ query: string,
293
+ chatId: number | null,
294
+ since: string | null,
295
+ beforeRowid: number | null,
296
+ limit: number,
297
+ ): string {
298
+ const literal = sqlStringLiteral(query);
299
+ // Byte-exact prefilter: most modern rows have text = NULL, and the body's
300
+ // UTF-8 bytes are stored verbatim inside the attributedBody blob. This is
301
+ // intentionally a superset: the blob also holds attribute key names, so the
302
+ // caller post-filters on the decoded body text.
303
+ const clauses = [
304
+ `(instr(m.text, ${literal}) > 0 OR instr(m.attributedBody, CAST(${literal} AS BLOB)) > 0)`,
305
+ ];
306
+ if (chatId !== null) {
307
+ clauses.push(
308
+ `EXISTS (SELECT 1 FROM chat_message_join cmj WHERE cmj.message_id = m.ROWID AND cmj.chat_id = ${chatId})`,
309
+ );
310
+ }
311
+ if (since !== null) clauses.push(`m.date >= ${since}`);
312
+ if (beforeRowid !== null) clauses.push(`m.ROWID < ${beforeRowid}`);
313
+ // A message can join multiple chats; report its canonical (lowest) chat id
314
+ // once instead of duplicating the row per join.
315
+ return `SELECT ${messageColumns('(SELECT MIN(cmj.chat_id) FROM chat_message_join cmj WHERE cmj.message_id = m.ROWID)')}
316
+ FROM message m
317
+ LEFT JOIN handle h ON h.ROWID = m.handle_id
318
+ WHERE ${clauses.join(' AND ')}
319
+ ORDER BY m.ROWID DESC
320
+ LIMIT ${limit};`;
321
+ }
322
+
323
+ export function outgoingSentinelSql(): string {
324
+ return 'SELECT IFNULL(MAX(ROWID), 0) AS rowid FROM message WHERE is_from_me = 1;';
325
+ }
326
+
327
+ export function chatByGuidSql(guid: string): string {
328
+ return `SELECT ROWID AS chat_id, guid AS guid
329
+ FROM chat
330
+ WHERE guid = ${sqlStringLiteral(guid)}
331
+ ORDER BY ROWID DESC
332
+ LIMIT 1;`;
333
+ }
334
+
335
+ export function chatByRecipientSql(recipient: string): string {
336
+ const directGuid = `iMessage;-;${recipient}`;
337
+ return `SELECT ROWID AS chat_id, guid AS guid
338
+ FROM chat
339
+ WHERE chat_identifier = ${sqlStringLiteral(recipient)}
340
+ OR guid = ${sqlStringLiteral(directGuid)}
341
+ ORDER BY ROWID DESC
342
+ LIMIT 1;`;
343
+ }
344
+
345
+ export function confirmSentSql(
346
+ target: { chatGuid: string } | { recipient: string },
347
+ sentinel: number,
348
+ ): string {
349
+ const match =
350
+ 'chatGuid' in target
351
+ ? `c.guid = ${sqlStringLiteral(target.chatGuid)}`
352
+ : `(h.id = ${sqlStringLiteral(target.recipient)}
353
+ OR c.chat_identifier = ${sqlStringLiteral(target.recipient)}
354
+ OR c.guid = ${sqlStringLiteral(`iMessage;-;${target.recipient}`)})`;
355
+ return `SELECT ${messageColumns('cmj.chat_id')}
356
+ FROM message m
357
+ LEFT JOIN chat_message_join cmj ON cmj.message_id = m.ROWID
358
+ LEFT JOIN chat c ON c.ROWID = cmj.chat_id
359
+ LEFT JOIN handle h ON h.ROWID = m.handle_id
360
+ WHERE m.is_from_me = 1 AND m.ROWID > ${sentinel} AND (${match})
361
+ ORDER BY m.ROWID DESC
362
+ LIMIT 1;`;
363
+ }
364
+
365
+ type SendTarget = { kind: 'chat'; chatGuid: string } | { kind: 'recipient'; recipient: string };
366
+
367
+ function action(
368
+ key: string,
369
+ name: string,
370
+ description: string,
371
+ kind: 'read' | 'write',
372
+ properties: Record<string, unknown> = {},
373
+ required: string[] = [],
374
+ schemaExtras: Record<string, unknown> = {},
375
+ ): ActionDefinition {
376
+ return {
377
+ key,
378
+ name,
379
+ description,
380
+ kind,
381
+ inputSchema: {
382
+ type: 'object',
383
+ properties,
384
+ required,
385
+ additionalProperties: false,
386
+ ...schemaExtras,
387
+ },
388
+ annotations: {
389
+ destructiveHint: kind === 'write',
390
+ openWorldHint: kind === 'write',
391
+ idempotentHint: kind === 'read',
392
+ },
393
+ };
394
+ }
395
+
396
+ function requiredString(
397
+ input: Record<string, unknown>,
398
+ key: string,
399
+ maximum: number,
400
+ ): string {
401
+ const value = input[key];
402
+ if (typeof value !== 'string' || value.length === 0 || value.length > maximum || value.includes('\0'))
403
+ throw new Error(`${key} is required and must be at most ${maximum} characters`);
404
+ return value;
405
+ }
406
+
407
+ function boundedInteger(
408
+ value: unknown,
409
+ fallback: number,
410
+ maximum: number,
411
+ minimum = 1,
412
+ ): number {
413
+ if (value === undefined) return fallback;
414
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum || value > maximum)
415
+ throw new Error(`Invalid numeric value; expected ${minimum}..${maximum}`);
416
+ return value;
417
+ }
418
+
419
+ function hasControlCharacters(value: string): boolean {
420
+ for (let index = 0; index < value.length; index++) {
421
+ if (value.charCodeAt(index) < 0x20) return true;
422
+ }
423
+ return false;
424
+ }
425
+
426
+ function chatGuid(input: Record<string, unknown>): string {
427
+ const value = requiredString(input, 'chat_guid', 255);
428
+ if (hasControlCharacters(value)) throw new Error('chat_guid contains control characters');
429
+ const parts = value.split(';');
430
+ if (
431
+ parts.length < 3 ||
432
+ (parts[0] !== 'iMessage' && parts[0] !== 'SMS' && parts[0] !== 'any') ||
433
+ (parts[1] !== '-' && parts[1] !== '+') ||
434
+ parts.slice(2).join(';').length === 0
435
+ )
436
+ throw new Error('chat_guid must be a Messages chat GUID such as iMessage;-;+15550001001');
437
+ return value;
438
+ }
439
+
440
+ function recipient(input: Record<string, unknown>): string {
441
+ const value = requiredString(input, 'recipient', 255).trim();
442
+ if (value.length === 0 || hasControlCharacters(value))
443
+ throw new Error('recipient must be a phone number or email without control characters');
444
+ return value;
445
+ }
446
+
447
+ function sendTarget(input: Record<string, unknown>): SendTarget {
448
+ const hasGuid = input.chat_guid !== undefined;
449
+ const hasRecipient = input.recipient !== undefined;
450
+ if (hasGuid === hasRecipient)
451
+ throw new Error('Provide exactly one of chat_guid or recipient');
452
+ return hasGuid
453
+ ? { kind: 'chat', chatGuid: chatGuid(input) }
454
+ : { kind: 'recipient', recipient: recipient(input) };
455
+ }
456
+
457
+ function optionalChatId(input: Record<string, unknown>): number | null {
458
+ if (input.chat_id === undefined) return null;
459
+ return boundedInteger(input.chat_id, 0, Number.MAX_SAFE_INTEGER);
460
+ }
461
+
462
+ function assertChatId(input: Record<string, unknown>): number {
463
+ const value = input.chat_id;
464
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1)
465
+ throw new Error('chat_id is required');
466
+ return value;
467
+ }
468
+
469
+ function listLimit(input: Record<string, unknown>): number {
470
+ return boundedInteger(input.limit, 20, 100);
471
+ }
472
+
473
+ function readLimit(input: Record<string, unknown>): number {
474
+ return boundedInteger(input.limit, 50, 100);
475
+ }
476
+
477
+ function searchLimit(input: Record<string, unknown>): number {
478
+ return boundedInteger(input.limit, 50, 50);
479
+ }
480
+
481
+ function beforeRowid(input: Record<string, unknown>): number | null {
482
+ if (input.before_rowid === undefined) return null;
483
+ return boundedInteger(input.before_rowid, 0, Number.MAX_SAFE_INTEGER);
484
+ }
485
+
486
+ type ShellOutput = {
487
+ exit_code?: number;
488
+ timed_out?: boolean;
489
+ stdout?: string;
490
+ stderr?: string;
491
+ };
492
+
493
+ type ShellResult =
494
+ | { kind: 'receipt'; receipt: Record<string, unknown> }
495
+ | { kind: 'completed'; runId: number | undefined; shell: ShellOutput }
496
+ | { kind: 'error'; error: string };
497
+
498
+ type SqlResult =
499
+ | { rows: Array<Record<string, unknown>> }
500
+ | { receipt: Record<string, unknown> }
501
+ | { error: string };
502
+
503
+ async function runShell(
504
+ ctx: ActionContext,
505
+ connectionId: number,
506
+ command: string,
507
+ stdin: string,
508
+ timeoutMs: number,
509
+ idempotencyKey: string,
510
+ ): Promise<ShellResult> {
511
+ const operations = ctx.operations;
512
+ if (!operations)
513
+ return { kind: 'error', error: 'Connector operation delegation is unavailable.' };
514
+ const receipt = (await operations.execute({
515
+ connection_id: connectionId,
516
+ operation_key: 'run',
517
+ idempotency_key: idempotencyKey,
518
+ input: { command, stdin, timeout_ms: timeoutMs },
519
+ })) as Record<string, unknown>;
520
+ if (typeof receipt.error === 'string') return { kind: 'error', error: receipt.error };
521
+ const status = receipt.status;
522
+ if (status === 'pending_approval' || status === 'in_progress')
523
+ return { kind: 'receipt', receipt };
524
+ if (status !== 'completed') return { kind: 'error', error: JSON.stringify(receipt) };
525
+ const shell = receipt.output as ShellOutput | undefined;
526
+ if (!shell || shell.exit_code !== 0 || shell.timed_out)
527
+ return {
528
+ kind: 'error',
529
+ error: JSON.stringify({
530
+ run_id: receipt.run_id,
531
+ exit_code: shell?.exit_code,
532
+ timed_out: shell?.timed_out,
533
+ stderr: shell?.stderr?.slice(-2000),
534
+ stdout: shell?.stdout?.slice(-1000),
535
+ stdout_head: shell?.stdout?.slice(0, 1000),
536
+ }),
537
+ };
538
+ return { kind: 'completed', runId: numberOrNull(receipt.run_id) ?? undefined, shell };
539
+ }
540
+
541
+ async function runSql(
542
+ ctx: ActionContext,
543
+ connectionId: number,
544
+ sql: string,
545
+ idempotencyKey: string,
546
+ ): Promise<SqlResult> {
547
+ const result = await runShell(
548
+ ctx,
549
+ connectionId,
550
+ `${quoteShellArg(SQLITE_BINARY)} -readonly -json ${CHAT_DB_PATH}`,
551
+ sql,
552
+ READ_TIMEOUT_MS,
553
+ idempotencyKey,
554
+ );
555
+ if (result.kind === 'receipt') return { receipt: result.receipt };
556
+ if (result.kind === 'error') return { error: result.error };
557
+ const stdout = result.shell.stdout ?? '';
558
+ if (stdout.length >= MAX_SHELL_STDOUT_CHARS)
559
+ return {
560
+ error: `sqlite3 output reached the shell's 1 MiB stdout cap; lower \`limit\` and retry (shell run ${result.runId}).`,
561
+ };
562
+ if (stdout.trim() === '') return { rows: [] };
563
+ let parsed: unknown;
564
+ try {
565
+ parsed = JSON.parse(stdout);
566
+ } catch {
567
+ return {
568
+ error: `sqlite3 output could not be parsed, possibly because it was truncated by the shell's 1 MiB stdout cap; lower \`limit\` and retry (shell run ${result.runId}).`,
569
+ };
570
+ }
571
+ if (!Array.isArray(parsed) || parsed.some((row) => typeof row !== 'object' || row === null))
572
+ return {
573
+ error: `sqlite3 returned an unexpected JSON shape; lower \`limit\` and retry (shell run ${result.runId}).`,
574
+ };
575
+ return { rows: parsed as Array<Record<string, unknown>> };
576
+ }
577
+
578
+ function resultFromSqlFailure(result: { receipt: Record<string, unknown> } | { error: string }): ActionResult {
579
+ return 'receipt' in result
580
+ ? { success: true, output: { ...result.receipt } }
581
+ : { success: false, error: result.error };
582
+ }
583
+
584
+ /**
585
+ * The sentinel query's one-row JSON line in the send `run`'s stdout. A Mac
586
+ * endpoint runs commands under a login shell, so profile output may precede
587
+ * it; every line is checked, not just the first.
588
+ */
589
+ function parseSentinel(stdout: string): number | null {
590
+ for (const line of stdout.split('\n')) {
591
+ try {
592
+ const rows = JSON.parse(line) as unknown;
593
+ const row = Array.isArray(rows) ? rows[0] : undefined;
594
+ const rowid =
595
+ row && typeof row === 'object' ? numberOrNull((row as Record<string, unknown>).rowid) : null;
596
+ if (rowid !== null) return rowid;
597
+ } catch {
598
+ // Not the sentinel line.
599
+ }
600
+ }
601
+ return null;
602
+ }
603
+
604
+ type ShellErrorDetails = { stdout?: string; stdout_head?: string };
605
+
606
+ /** The shell's nonzero-exit error JSON, or null for a pre-run failure. */
607
+ function parseShellError(error: string): ShellErrorDetails | null {
608
+ try {
609
+ const parsed = JSON.parse(error) as unknown;
610
+ if (!parsed || typeof parsed !== 'object') return null;
611
+ const details = parsed as ShellErrorDetails;
612
+ return typeof details.stdout === 'string' || typeof details.stdout_head === 'string'
613
+ ? details
614
+ : null;
615
+ } catch {
616
+ return null;
617
+ }
618
+ }
619
+
620
+ function chatRow(row: Record<string, unknown>): ChatRowOutput {
621
+ return {
622
+ chat_id: numberOrNull(row.chat_id) ?? 0,
623
+ guid: stringOrNull(row.guid),
624
+ display_name: stringOrNull(row.display_name),
625
+ chat_identifier: stringOrNull(row.chat_identifier),
626
+ participants: participantsFromJson(row.participants_json),
627
+ service: stringOrNull(row.service),
628
+ last_message_at: isoFromAppleDate(row.last_message_date),
629
+ };
630
+ }
631
+
632
+ export default class IMessageConnector extends ConnectorRuntime {
633
+ readonly definition: RuntimeConnectorDefinition = {
634
+ key: 'imessage',
635
+ name: 'iMessage',
636
+ version: '1.0.0',
637
+ faviconDomain: 'apple.com',
638
+ description:
639
+ 'Read and send iMessage and SMS on a Mac by delegating every command to an existing os.shell connection. Reads ~/Library/Messages/chat.db and sends through Messages.app automation. Needs an os.shell connection on a Mac where Lobu has Full Disk Access (reads) and Automation -> Messages permission (send).',
640
+ authSchema: { methods: [{ type: 'none' }] },
641
+ feeds: {},
642
+ optionsSchema: {
643
+ type: 'object',
644
+ required: ['shell_connection_id'],
645
+ properties: {
646
+ shell_connection_id: {
647
+ type: 'integer',
648
+ minimum: 1,
649
+ title: 'Shell connection ID',
650
+ description:
651
+ 'Discover the existing os.shell connection with operations.listAvailable. Its device and policies govern all commands.',
652
+ },
653
+ },
654
+ additionalProperties: false,
655
+ },
656
+ actions: {
657
+ list_chats: action(
658
+ 'list_chats',
659
+ 'List chats',
660
+ 'Recent chats ordered by last message time, with participants and service.',
661
+ 'read',
662
+ { limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 } },
663
+ ),
664
+ read_chat: action(
665
+ 'read_chat',
666
+ 'Read chat',
667
+ "Read one chat's messages newest first. Pass next_cursor as before_rowid for the next page. A message whose text does not fit in 2 KiB returns text: null with text_truncated: true.",
668
+ 'read',
669
+ {
670
+ chat_id: { type: 'integer', minimum: 1 },
671
+ before_rowid: {
672
+ type: 'integer',
673
+ minimum: 1,
674
+ description: 'Row cursor returned as next_cursor by a previous page.',
675
+ },
676
+ limit: { type: 'integer', minimum: 1, maximum: 100, default: 50 },
677
+ },
678
+ ['chat_id'],
679
+ ),
680
+ search_messages: action(
681
+ 'search_messages',
682
+ 'Search messages',
683
+ 'Case-sensitive literal substring search over message text, including bodies stored only in attributedBody. Blob attribute names are ignored. Messages whose text does not fit in 2 KiB are not matched. Pass next_cursor as before_rowid for the next page.',
684
+ 'read',
685
+ {
686
+ query: { type: 'string', minLength: 1, maxLength: MAX_SEARCH_LENGTH },
687
+ chat_id: {
688
+ type: 'integer',
689
+ minimum: 1,
690
+ description: 'Optional chat scope; search every chat when omitted.',
691
+ },
692
+ since: {
693
+ type: 'string',
694
+ format: 'date-time',
695
+ description: 'Optional ISO timestamp lower bound.',
696
+ },
697
+ before_rowid: {
698
+ type: 'integer',
699
+ minimum: 1,
700
+ description: 'Row cursor returned as next_cursor by a previous page.',
701
+ },
702
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 50 },
703
+ },
704
+ ['query'],
705
+ ),
706
+ send_message: action(
707
+ 'send_message',
708
+ 'Send message',
709
+ 'Send a text message through Messages.app automation, then confirm the outgoing row in chat.db. Returns delivered, sent_unconfirmed or failed.',
710
+ 'write',
711
+ {
712
+ chat_guid: {
713
+ type: 'string',
714
+ minLength: 1,
715
+ maxLength: 255,
716
+ description: 'Existing Messages chat GUID, for example iMessage;-;+15550001001.',
717
+ },
718
+ recipient: {
719
+ type: 'string',
720
+ minLength: 1,
721
+ maxLength: 255,
722
+ description: 'Phone number or email for a direct iMessage participant.',
723
+ },
724
+ text: {
725
+ type: 'string',
726
+ minLength: 1,
727
+ maxLength: MAX_SEND_LENGTH,
728
+ description: 'Message body to send.',
729
+ },
730
+ },
731
+ ['text'],
732
+ { oneOf: [{ required: ['chat_guid'] }, { required: ['recipient'] }] },
733
+ ),
734
+ },
735
+ };
736
+
737
+ async execute(ctx: ActionContext): Promise<ActionResult> {
738
+ if (!ctx.operations)
739
+ return {
740
+ success: false,
741
+ error:
742
+ 'This Lobu host does not support connector operation delegation. Update the Lobu server.',
743
+ };
744
+ const connectionId = ctx.config.shell_connection_id;
745
+ if (typeof connectionId !== 'number' || !Number.isSafeInteger(connectionId) || connectionId < 1)
746
+ return {
747
+ success: false,
748
+ error: 'Configure shell_connection_id with an existing os.shell connection.',
749
+ };
750
+ switch (ctx.actionKey) {
751
+ case 'list_chats':
752
+ return this.listChats(ctx, connectionId);
753
+ case 'read_chat':
754
+ return this.readChat(ctx, connectionId);
755
+ case 'search_messages':
756
+ return this.searchMessages(ctx, connectionId);
757
+ case 'send_message':
758
+ return this.sendMessage(ctx, connectionId);
759
+ default:
760
+ throw new Error(`Unknown iMessage action: ${ctx.actionKey}`);
761
+ }
762
+ }
763
+
764
+ private async listChats(ctx: ActionContext, connectionId: number): Promise<ActionResult> {
765
+ const limit = listLimit(ctx.input);
766
+ const result = await runSql(ctx, connectionId, listChatsSql(limit), 'imessage-list-chats');
767
+ if (!('rows' in result)) return resultFromSqlFailure(result);
768
+ return {
769
+ success: true,
770
+ output: { chats: result.rows.map(chatRow) },
771
+ };
772
+ }
773
+
774
+ private async readChat(ctx: ActionContext, connectionId: number): Promise<ActionResult> {
775
+ const chatId = assertChatId(ctx.input);
776
+ const limit = readLimit(ctx.input);
777
+ const before = beforeRowid(ctx.input);
778
+ const result = await runSql(
779
+ ctx,
780
+ connectionId,
781
+ readChatSql(chatId, before, limit),
782
+ 'imessage-read-chat',
783
+ );
784
+ if (!('rows' in result)) return resultFromSqlFailure(result);
785
+ const messages = result.rows.map(mapMessageRow);
786
+ const last = messages.at(-1);
787
+ return {
788
+ success: true,
789
+ output: {
790
+ chat_id: chatId,
791
+ messages,
792
+ next_cursor: messages.length === limit && last ? last.rowid : null,
793
+ },
794
+ };
795
+ }
796
+
797
+ private async searchMessages(
798
+ ctx: ActionContext,
799
+ connectionId: number,
800
+ ): Promise<ActionResult> {
801
+ const query = requiredString(ctx.input, 'query', MAX_SEARCH_LENGTH);
802
+ const limit = searchLimit(ctx.input);
803
+ const before = beforeRowid(ctx.input);
804
+ const chatId = optionalChatId(ctx.input);
805
+ const sinceInput = ctx.input.since;
806
+ let since: string | null = null;
807
+ if (sinceInput !== undefined) {
808
+ if (typeof sinceInput !== 'string') throw new Error('since must be an ISO timestamp');
809
+ since = appleNsSince(sinceInput);
810
+ }
811
+ const overFetch = Math.min(limit * 2, 100);
812
+ const result = await runSql(
813
+ ctx,
814
+ connectionId,
815
+ searchMessagesSql(query, chatId, since, before, overFetch),
816
+ 'imessage-search-messages',
817
+ );
818
+ if (!('rows' in result)) return resultFromSqlFailure(result);
819
+ const matched = result.rows
820
+ .map(mapMessageRow)
821
+ .filter((message) => message.text !== null && message.text.includes(query));
822
+ const messages = matched.slice(0, limit);
823
+ // A short SQL batch can still hold more decoded matches than the page
824
+ // size; only the absence of further scanned rows *and* matches ends paging.
825
+ const exhausted = result.rows.length < overFetch;
826
+ const nextCursor =
827
+ exhausted && matched.length <= limit
828
+ ? null
829
+ : (messages.at(-1)?.rowid ?? numberOrNull(result.rows.at(-1)?.rowid) ?? null);
830
+ return { success: true, output: { messages, next_cursor: nextCursor } };
831
+ }
832
+
833
+ private async sendMessage(ctx: ActionContext, connectionId: number): Promise<ActionResult> {
834
+ const target = sendTarget(ctx.input);
835
+ const text = requiredString(ctx.input, 'text', MAX_SEND_LENGTH);
836
+
837
+ // The send is the first and only effectful child: the sentinel read rides
838
+ // in the same `run`, so an approval card shows (and approving executes)
839
+ // the actual send. sqlite3 takes its constant SQL as an argument and never
840
+ // reads stdin, which leaves the AppleScript on stdin for osascript.
841
+ const command = [
842
+ `${quoteShellArg(SQLITE_BINARY)} -readonly -json ${CHAT_DB_PATH} ${quoteShellArg(outgoingSentinelSql())}`,
843
+ [
844
+ OSASCRIPT_BINARY,
845
+ '-',
846
+ target.kind === 'chat' ? 'chat' : 'recipient',
847
+ target.kind === 'chat' ? target.chatGuid : target.recipient,
848
+ text,
849
+ ]
850
+ .map(quoteShellArg)
851
+ .join(' '),
852
+ ].join(' && ');
853
+ const send = await runShell(
854
+ ctx,
855
+ connectionId,
856
+ command,
857
+ SEND_SCRIPT,
858
+ WRITE_TIMEOUT_MS,
859
+ 'imessage-send',
860
+ );
861
+ if (send.kind === 'receipt') return { success: true, output: { ...send.receipt } };
862
+ if (send.kind === 'error') {
863
+ // The sentinel query always prints one row, so empty stdout proves
864
+ // sqlite3 failed and `&&` never reached osascript. Any other stdout
865
+ // (login-profile noise included) cannot rule out a send.
866
+ const details = parseShellError(send.error);
867
+ const notSent =
868
+ details !== null &&
869
+ (details.stdout_head ?? '').trim() === '' &&
870
+ (details.stdout ?? '').trim() === '';
871
+ return {
872
+ success: false,
873
+ error: `${send.error} ${
874
+ notSent
875
+ ? 'The message was not sent: the pre-send database read failed before osascript ran.'
876
+ : 'The message may already have been sent; inspect this run before retrying.'
877
+ }`,
878
+ };
879
+ }
880
+ const sentinel = parseSentinel(send.shell.stdout ?? '');
881
+
882
+ const chatResult = await runSql(
883
+ ctx,
884
+ connectionId,
885
+ target.kind === 'chat'
886
+ ? chatByGuidSql(target.chatGuid)
887
+ : chatByRecipientSql(target.recipient),
888
+ 'imessage-send-chat',
889
+ );
890
+ const resolvedChat = 'rows' in chatResult ? chatResult.rows[0] : undefined;
891
+ const chatId = numberOrNull(resolvedChat?.chat_id);
892
+ const chatGuid =
893
+ target.kind === 'chat' ? target.chatGuid : stringOrNull(resolvedChat?.guid);
894
+ const base = {
895
+ run_id: send.runId,
896
+ chat_id: chatId,
897
+ chat_guid: chatGuid,
898
+ recipient: target.kind === 'recipient' ? target.recipient : null,
899
+ };
900
+ if (sentinel === null) {
901
+ return {
902
+ success: true,
903
+ output: {
904
+ ...base,
905
+ status: 'sent_unconfirmed',
906
+ message: null,
907
+ note: 'The pre-send outgoing row id was unreadable, so the sent row cannot be confirmed.',
908
+ },
909
+ };
910
+ }
911
+
912
+ const confirm = await runSql(
913
+ ctx,
914
+ connectionId,
915
+ confirmSentSql(target, sentinel),
916
+ 'imessage-send-confirm',
917
+ );
918
+ if (!('rows' in confirm)) {
919
+ return {
920
+ success: true,
921
+ output: {
922
+ ...base,
923
+ status: 'sent_unconfirmed',
924
+ message: null,
925
+ ...('receipt' in confirm
926
+ ? { confirmation_receipt: confirm.receipt }
927
+ : { confirmation_error: confirm.error }),
928
+ },
929
+ };
930
+ }
931
+ const message = confirm.rows[0] ? mapMessageRow(confirm.rows[0]) : null;
932
+ if (!message) {
933
+ return {
934
+ success: true,
935
+ output: {
936
+ ...base,
937
+ status: 'sent_unconfirmed',
938
+ message: null,
939
+ note: 'Messages has not written an outgoing row for this chat yet.',
940
+ },
941
+ };
942
+ }
943
+ const output = {
944
+ ...base,
945
+ chat_id: message.chat_id ?? base.chat_id,
946
+ status: message.error !== 0 ? 'failed' : message.is_delivered ? 'delivered' : 'sent_unconfirmed',
947
+ message,
948
+ };
949
+ return output.status === 'failed'
950
+ ? { success: false, error: JSON.stringify(output), output }
951
+ : { success: true, output };
952
+ }
953
+ }