1
+import { spawn } from 'node:child_process';
2
+import { z } from 'zod/v3';
3
+import { runLocalCommand } from '../runtime';
4
+import type {
5
+ LocalCommandExecution,
6
+ LocalExecutionContext,
7
+ LocalExecutionResult,
8
+ LocalToolkitDeclaration,
9
+ LocalToolDeclaration,
10
+} from '../types';
11
+
12
+const IMESSAGE_CLI_BINARY_ID = 'beeper-imessage-cli';
13
+const IMESSAGE_CLI_VERSION = '0.21.0';
14
+const COMMAND_TIMEOUT_MS = 120_000;
15
+const SEND_VERIFY_TIMEOUT_MS = 8_000;
16
+const SEND_VERIFY_INTERVAL_MS = 500;
17
+const THREAD_SCAN_DEFAULT_MAX_PAGES = 10;
18
+const THREAD_SCAN_MAX_PAGES = 50;
19
+const CONTACT_LOOKUP_TIMEOUT_MS = 5_000;
20
+const REACTION_PREPARE_TIMEOUT_MS = 5_000;
21
+const REACTION_TIMEOUT_MS = 20_000;
22
+
23
+const baseInput = z.object({
24
+ dataDir: z
25
+ .string()
26
+ .min(1)
27
+ .optional()
28
+ .describe('Optional directory for imessage-cli state. Defaults to a temporary directory.'),
29
+ useSecondaryInstance: z
30
+ .boolean()
31
+ .default(true)
32
+ .describe(
33
+ 'Use a secondary Messages.app instance. This is usually fine for read/send/list tools. UI-dependent tools such as reactions default to the primary Messages.app instance because they need the transcript view to be visible.'
34
+ ),
35
+ verbose: z.boolean().default(false).describe('Enable verbose imessage-cli logging.'),
36
+});
37
+
38
+const primaryInstanceInput = baseInput.extend({
39
+ useSecondaryInstance: z
40
+ .boolean()
41
+ .default(false)
42
+ .describe(
43
+ 'Use a secondary Messages.app instance. Defaults to false for reactions because the upstream UI automation needs the primary transcript view to be visible.'
44
+ ),
45
+});
46
+
47
+const cursorInput = z.object({
48
+ before: z
49
+ .string()
50
+ .min(1)
51
+ .optional()
52
+ .describe(
53
+ 'Fetch items older than this cursor. For LIST_THREADS, use result.pageInfo.nextBefore.'
54
+ ),
55
+ after: z.string().min(1).optional().describe('Fetch items newer than this cursor.'),
56
+});
57
+
58
+const cliOutput = z.object({
59
+ ok: z.boolean(),
60
+ commandName: z.string(),
61
+ callId: z.string().optional(),
62
+ durationMs: z.number().optional(),
63
+ result: z.unknown().optional(),
64
+ resultText: z.string().optional(),
65
+ stdout: z.string(),
66
+ stderr: z.string(),
67
+});
68
+
69
+const stringArray = (value: unknown): string[] =>
70
+ Array.isArray(value) ? value.map(item => String(item)) : [];
71
+
72
+const stringValue = (value: unknown): string => String(value ?? '');
73
+
74
+const optionalString = (value: unknown): string | undefined => {
75
+ const text = typeof value === 'string' ? value.trim() : '';
76
+ return text.length > 0 ? text : undefined;
77
+};
78
+
79
+const absolutePath = (value: unknown): string => stringValue(value);
80
+
81
+const isRecord = (value: unknown): value is Record<string, unknown> =>
82
+ typeof value === 'object' && value !== null && !Array.isArray(value);
83
+
84
+const toRecordArray = (value: unknown): Record<string, unknown>[] => {
85
+ if (Array.isArray(value)) return value.filter(isRecord);
86
+ if (isRecord(value) && Array.isArray(value.items)) return value.items.filter(isRecord);
87
+ return [];
88
+};
89
+
90
+const normalizePhone = (value: string): string => value.replace(/[^0-9]/g, '');
91
+
92
+const normalizeIdentifier = (value: unknown): string => {
93
+ const text = String(value ?? '')
94
+ .trim()
95
+ .toLowerCase();
96
+ if (!text) return '';
97
+ if (text.includes('@')) return text;
98
+ const digits = normalizePhone(text);
99
+ return digits || text;
100
+};
101
+
102
+const unique = <T>(values: ReadonlyArray<T>): T[] => [...new Set(values)];
103
+
104
+const compactRecord = (record: Record<string, unknown>, keys: ReadonlyArray<string>) =>
105
+ Object.fromEntries(keys.filter(key => record[key] !== undefined).map(key => [key, record[key]]));
106
+
107
+const messageIdOf = (message: unknown): string | undefined =>
108
+ isRecord(message) ? optionalString(message.id) : undefined;
109
+
110
+const messageTextOf = (message: unknown): string =>
111
+ isRecord(message) ? stringValue(message.text ?? '') : '';
112
+
113
+const messageIsSender = (message: unknown): boolean =>
114
+ isRecord(message) && message.isSender === true;
115
+
116
+const messageMatchesSentText = (message: unknown, text: string): boolean =>
117
+ messageIsSender(message) && messageTextOf(message) === text;
118
+
119
+const extractPageItems = (result: unknown): Record<string, unknown>[] =>
120
+ isRecord(result) ? toRecordArray(result.items) : [];
121
+
122
+const extractThreadId = (value: unknown): string | undefined => {
123
+ if (!isRecord(value)) return undefined;
124
+ return optionalString(value.id ?? value.threadId ?? value.threadID ?? value.chatId);
125
+};
126
+
127
+const participantIdentifiers = (thread: Record<string, unknown>): string[] => {
128
+ const participants = toRecordArray(thread.participants);
129
+ return unique(
130
+ participants.flatMap(participant =>
131
+ [participant.email, participant.phoneNumber, participant.handle, participant.id]
132
+ .map(optionalString)
133
+ .filter((value): value is string => Boolean(value))
134
+ )
135
+ );
136
+};
137
+
138
+const latestMessage = (thread: Record<string, unknown>): Record<string, unknown> | undefined => {
139
+ const messages = toRecordArray(thread.messages);
140
+ return messages[0];
141
+};
142
+
143
+const buildGlobalArgs = (input: Record<string, unknown>): string[] => {
144
+ const args: string[] = [];
145
+ const dataDir = optionalString(input.dataDir);
146
+ if (dataDir) args.push('--data-dir', dataDir);
147
+ if (input.useSecondaryInstance === false) args.push('--no-use-secondary-instance');
148
+ // Local tools are one-shot calls. Avoid keeping DB event watchers open unless a
149
+ // future streaming tool explicitly opts in.
150
+ args.push('--no-events');
151
+ if (input.verbose === true) args.push('--verbose');
152
+ return args;
153
+};
154
+
155
+const withCursorArgs = (input: Record<string, unknown>, args: string[]): string[] => {
156
+ const before = optionalString(input.before);
157
+ const after = optionalString(input.after);
158
+ if (before && after) throw new Error('Use only one of before or after.');
159
+ if (before) args.push('--before', before);
160
+ if (after) args.push('--after', after);
161
+ return args;
162
+};
163
+
164
+const stripAnsi = (text: string): string => text.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, '');
165
+
166
+const parseImessageCliOutput = (
167
+ commandName: string,
168
+ stdout: string,
169
+ stderr: string
170
+): LocalExecutionResult => {
171
+ const cleanStdout = stripAnsi(stdout);
172
+ const lines = cleanStdout.split(/\r?\n/);
173
+ const okIndex = lines.findIndex(line => /^\[\d+\] ok /.test(line));
174
+ const okLine = okIndex >= 0 ? lines[okIndex] : undefined;
175
+ const match = okLine?.match(/^\[(\d+)\] ok \S+ \((\d+(?:\.\d+)?)ms\)$/);
176
+
177
+ const resultLines = okIndex >= 0 ? lines.slice(okIndex + 1) : lines;
178
+ const resultText = resultLines
179
+ .filter(line => line.trim() !== 'Exiting...')
180
+ .join('\n')
181
+ .trim();
182
+
183
+ let parsed: unknown;
184
+ if (resultText) {
185
+ try {
186
+ parsed = JSON.parse(resultText) as unknown;
187
+ } catch {
188
+ parsed = undefined;
189
+ }
190
+ }
191
+
192
+ return {
193
+ ok: true,
194
+ commandName,
195
+ ...(match?.[1] ? { callId: match[1] } : {}),
196
+ ...(match?.[2] ? { durationMs: Number(match[2]) } : {}),
197
+ ...(parsed !== undefined ? { result: parsed } : {}),
198
+ ...(resultText ? { resultText } : {}),
199
+ stdout,
200
+ stderr,
201
+ };
202
+};
203
+
204
+const runImessageCli = async (
205
+ commandName: string,
206
+ commandArgs: ReadonlyArray<string>,
207
+ input: Record<string, unknown>,
208
+ context: LocalExecutionContext,
209
+ options: { readonly timeoutMs?: number } = {}
210
+): Promise<LocalExecutionResult> => {
211
+ const execution: LocalCommandExecution = {
212
+ kind: 'command',
213
+ command: {
214
+ bundledBinary: IMESSAGE_CLI_BINARY_ID,
215
+ fallbackCommand: 'imessage-cli',
216
+ },
217
+ args: [...buildGlobalArgs(input), commandName, ...commandArgs],
218
+ timeoutMs: options.timeoutMs ?? COMMAND_TIMEOUT_MS,
219
+ };
220
+ const result = await runLocalCommand(execution, input, context);
221
+ return parseImessageCliOutput(
222
+ commandName,
223
+ String(result.stdout ?? ''),
224
+ String(result.stderr ?? '')
225
+ );
226
+};
227
+
228
+const runProcess = async (
229
+ command: string,
230
+ args: ReadonlyArray<string>,
231
+ timeoutMs: number
232
+): Promise<{ readonly stdout: string; readonly stderr: string }> => {
233
+ const child = spawn(command, [...args], {
234
+ env: process.env,
235
+ stdio: ['ignore', 'pipe', 'pipe'],
236
+ });
237
+
238
+ let stdout = '';
239
+ let stderr = '';
240
+ child.stdout.setEncoding('utf8');
241
+ child.stderr.setEncoding('utf8');
242
+ child.stdout.on('data', chunk => {
243
+ stdout += chunk;
244
+ });
245
+ child.stderr.on('data', chunk => {
246
+ stderr += chunk;
247
+ });
248
+
249
+ const exitPromise = new Promise<{
250
+ readonly exitCode: number | null;
251
+ readonly signal: string | null;
252
+ }>((resolve, reject) => {
253
+ child.once('error', reject);
254
+ child.once('exit', (exitCode, signal) => resolve({ exitCode, signal }));
255
+ });
256
+ const timeout = setTimeout(() => child.kill('SIGTERM'), timeoutMs);
257
+ const { exitCode, signal } = await exitPromise.finally(() => clearTimeout(timeout));
258
+ if (exitCode !== 0) {
259
+ throw new Error(
260
+ `${command} failed with exitCode=${exitCode ?? 'null'} signal=${signal ?? 'null'}${
261
+ stderr.trim() ? `: ${stderr.trim()}` : ''
262
+ }`
263
+ );
264
+ }
265
+ return { stdout, stderr };
266
+};
267
+
268
+const contactLookupScript = `
269
+function normalizePhone(value) {
270
+ return String(value || '').replace(/[^0-9]/g, '');
271
+}
272
+function normalizeIdentifier(value) {
273
+ const text = String(value || '').trim().toLowerCase();
274
+ if (!text) return '';
275
+ if (text.indexOf('@') >= 0) return text;
276
+ return normalizePhone(text) || text;
277
+}
278
+function valuesOf(collection) {
279
+ try { return collection().map(item => String(item.value())); } catch (_) { return []; }
280
+}
281
+function personName(person) {
282
+ try { return String(person.name() || '').trim(); } catch (_) { return ''; }
283
+}
284
+function run(argv) {
285
+ const mode = argv[0] || 'query';
286
+ const payload = JSON.parse(argv[1] || '{}');
287
+ const query = String(payload.query || '').toLowerCase();
288
+ const requestedIdentifiers = (payload.identifiers || []).map(normalizeIdentifier).filter(Boolean);
289
+ const requestedSet = new Set(requestedIdentifiers);
290
+ const Contacts = Application('Contacts');
291
+ const people = Contacts.people();
292
+ const matches = [];
293
+ const labels = {};
294
+ for (const person of people) {
295
+ const name = personName(person);
296
+ const emails = valuesOf(person.emails);
297
+ const phones = valuesOf(person.phones);
298
+ const identifiers = emails.concat(phones);
299
+ const normalized = identifiers.map(normalizeIdentifier).filter(Boolean);
300
+ const haystack = [name].concat(identifiers).join(' ').toLowerCase();
301
+ if (mode === 'query' && query && haystack.indexOf(query) >= 0) {
302
+ matches.push({ name, emails, phones, identifiers });
303
+ }
304
+ if (mode === 'labels') {
305
+ for (let index = 0; index < normalized.length; index += 1) {
306
+ const value = normalized[index];
307
+ if (requestedSet.has(value)) labels[value] = name || identifiers[index] || value;
308
+ }
309
+ }
310
+ }
311
+ return JSON.stringify({ matches: matches.slice(0, 25), labels });
312
+}
313
+`;
314
+
315
+interface ContactLookupResult {
316
+ readonly matches: ReadonlyArray<{
317
+ readonly name?: string;
318
+ readonly emails?: ReadonlyArray<string>;
319
+ readonly phones?: ReadonlyArray<string>;
320
+ readonly identifiers?: ReadonlyArray<string>;
321
+ }>;
322
+ readonly labels: Record<string, string>;
323
+ readonly error?: string;
324
+}
325
+
326
+const emptyContactLookup = (error?: string): ContactLookupResult => ({
327
+ matches: [],
328
+ labels: {},
329
+ ...(error ? { error } : {}),
330
+});
331
+
332
+const lookupContacts = async (
333
+ mode: 'query' | 'labels',
334
+ payload: Record<string, unknown>
335
+): Promise<ContactLookupResult> => {
336
+ if (process.platform !== 'darwin') return emptyContactLookup('Contacts lookup requires macOS.');
337
+ try {
338
+ const result = await runProcess(
339
+ 'osascript',
340
+ ['-l', 'JavaScript', '-e', contactLookupScript, mode, JSON.stringify(payload)],
341
+ CONTACT_LOOKUP_TIMEOUT_MS
342
+ );
343
+ const parsed = JSON.parse(result.stdout.trim()) as unknown;
344
+ if (!isRecord(parsed))
345
+ return emptyContactLookup('Contacts lookup returned a non-object result.');
346
+ return {
347
+ matches: Array.isArray(parsed.matches) ? parsed.matches.filter(isRecord) : [],
348
+ labels: isRecord(parsed.labels)
349
+ ? Object.fromEntries(
350
+ Object.entries(parsed.labels).map(([key, value]) => [key, String(value)])
351
+ )
352
+ : {},
353
+ };
354
+ } catch (error) {
355
+ return emptyContactLookup(error instanceof Error ? error.message : String(error));
356
+ }
357
+};
358
+
359
+const contactIdentifiersFromMatches = (lookup: ContactLookupResult): string[] =>
360
+ unique(
361
+ lookup.matches.flatMap(match =>
362
+ [...(match.identifiers ?? []), ...(match.emails ?? []), ...(match.phones ?? [])]
363
+ .map(normalizeIdentifier)
364
+ .filter(Boolean)
365
+ )
366
+ );
367
+
368
+const labelsForThreads = async (
369
+ threads: ReadonlyArray<Record<string, unknown>>,
370
+ enabled: boolean
371
+): Promise<Record<string, string>> => {
372
+ if (!enabled || threads.length === 0) return {};
373
+ const identifiers = unique(threads.flatMap(thread => participantIdentifiers(thread))).map(
374
+ normalizeIdentifier
375
+ );
376
+ if (identifiers.length === 0) return {};
377
+ return (await lookupContacts('labels', { identifiers })).labels;
378
+};
379
+
380
+const compactParticipant = (
381
+ participant: Record<string, unknown>,
382
+ labels: Record<string, string>
383
+): Record<string, unknown> => {
384
+ const identifier = optionalString(
385
+ participant.email ?? participant.phoneNumber ?? participant.handle
386
+ );
387
+ const normalized = normalizeIdentifier(identifier);
388
+ return {
389
+ ...compactRecord(participant, ['isSelf', 'email', 'phoneNumber', 'handle']),
390
+ ...(identifier && labels[normalized] ? { label: labels[normalized] } : {}),
391
+ };
392
+};
393
+
394
+const compactMessage = (message: unknown): Record<string, unknown> | undefined => {
395
+ if (!isRecord(message)) return undefined;
396
+ return compactRecord(message, [
397
+ 'id',
398
+ 'text',
399
+ 'isSender',
400
+ 'timestamp',
401
+ 'isDelivered',
402
+ 'isErrored',
403
+ 'seen',
404
+ ]);
405
+};
406
+
407
+const compactThread = (thread: Record<string, unknown>, labels: Record<string, string>) => {
408
+ const participants = toRecordArray(thread.participants).map(participant =>
409
+ compactParticipant(participant, labels)
410
+ );
411
+ const lastMessage = compactMessage(latestMessage(thread));
412
+ const participantLabels = unique(
413
+ participants
414
+ .map(participant =>
415
+ optionalString(participant.label ?? participant.email ?? participant.phoneNumber)
416
+ )
417
+ .filter((value): value is string => Boolean(value))
418
+ );
419
+ return {
420
+ ...compactRecord(thread, [
421
+ 'id',
422
+ 'title',
423
+ 'type',
424
+ 'timestamp',
425
+ 'folderName',
426
+ 'unreadCount',
427
+ 'isUnread',
428
+ 'isReadOnly',
429
+ 'isPinned',
430
+ 'isMarkedUnread',
431
+ 'isLowPriority',
432
+ 'lastReadMessageSortKey',
433
+ ]),
434
+ participantLabels,
435
+ participants,
436
+ ...(lastMessage ? { lastMessage } : {}),
437
+ };
438
+};
439
+
440
+const pageInfoFor = (result: unknown) => {
441
+ const record = isRecord(result) ? result : {};
442
+ const oldestCursor = optionalString(record.oldestCursor);
443
+ return {
444
+ hasMore: record.hasMore === true,
445
+ oldestCursor,
446
+ nextBefore: oldestCursor,
447
+ nextSteps: oldestCursor
448
+ ? `Fetch older threads with { "before": "${oldestCursor}" }.`
449
+ : 'No older cursor was returned.',
450
+ };
451
+};
452
+
453
+const compactThreadsResult = async (
454
+ rawResult: LocalExecutionResult,
455
+ options: {
456
+ readonly compact: boolean;
457
+ readonly includeRaw: boolean;
458
+ readonly resolveContactNames: boolean;
459
+ }
460
+): Promise<LocalExecutionResult> => {
461
+ if (!options.compact || !isRecord(rawResult.result)) return rawResult;
462
+ const threads = extractPageItems(rawResult.result);
463
+ const labels = await labelsForThreads(threads, options.resolveContactNames);
464
+ const compactResult = {
465
+ items: threads.map(thread => compactThread(thread, labels)),
466
+ pageInfo: pageInfoFor(rawResult.result),
467
+ contactResolution: {
468
+ enabled: options.resolveContactNames,
469
+ resolvedLabels: Object.keys(labels).length,
470
+ },
471
+ ...(options.includeRaw ? { raw: rawResult.result } : {}),
472
+ };
473
+ return {
474
+ ...rawResult,
475
+ result: compactResult,
476
+ resultText: undefined,
477
+ stdout: options.includeRaw ? rawResult.stdout : '',
478
+ };
479
+};
480
+
481
+const delay = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms));
482
+
483
+const fetchMessages = async (
484
+ threadId: string,
485
+ input: Record<string, unknown>,
486
+ context: LocalExecutionContext
487
+): Promise<LocalExecutionResult> => runImessageCli('messages', [threadId], input, context);
488
+
489
+const pollForSentMessage = async (params: {
490
+ readonly threadId: string;
491
+ readonly text: string;
492
+ readonly input: Record<string, unknown>;
493
+ readonly context: LocalExecutionContext;
494
+ readonly timeoutMs: number;
495
+ readonly excludeMessageIds?: ReadonlySet<string>;
496
+}): Promise<{
497
+ readonly message?: Record<string, unknown>;
498
+ readonly messagesResult?: LocalExecutionResult;
499
+ readonly attempts: number;
500
+}> => {
501
+ const deadline = Date.now() + params.timeoutMs;
502
+ let attempts = 0;
503
+ let lastResult: LocalExecutionResult | undefined;
504
+
505
+ do {
506
+ attempts += 1;
507
+ lastResult = await fetchMessages(params.threadId, params.input, params.context);
508
+ const messages = extractPageItems(lastResult.result);
509
+ const message = messages.find(candidate => {
510
+ const candidateId = messageIdOf(candidate);
511
+ return (
512
+ messageMatchesSentText(candidate, params.text) &&
513
+ (!candidateId || !params.excludeMessageIds?.has(candidateId))
514
+ );
515
+ });
516
+ if (message) return { message, messagesResult: lastResult, attempts };
517
+ if (Date.now() < deadline) await delay(SEND_VERIFY_INTERVAL_MS);
518
+ } while (Date.now() < deadline);
519
+
520
+ return { messagesResult: lastResult, attempts };
521
+};
522
+
523
+const enhanceSendResult = (params: {
524
+ readonly commandResult: LocalExecutionResult;
525
+ readonly threadId?: string;
526
+ readonly sentText: string;
527
+ readonly sentMessage?: Record<string, unknown>;
528
+ readonly messagesResult?: LocalExecutionResult;
529
+ readonly attempts: number;
530
+ readonly verify: boolean;
531
+}): LocalExecutionResult => {
532
+ const sentMessageId = messageIdOf(params.sentMessage);
533
+ const sendVerification = {
534
+ commandSucceeded: params.commandResult.ok === true,
535
+ verified: Boolean(params.sentMessage),
536
+ status: params.sentMessage
537
+ ? 'observed_sent_message'
538
+ : params.verify
539
+ ? 'command_succeeded_but_sent_message_not_observed_yet'
540
+ : 'not_requested',
541
+ attempts: params.attempts,
542
+ threadId: params.threadId,
543
+ sentMessageId,
544
+ };
545
+
546
+ let enhancedResult = params.commandResult.result;
547
+ if (isRecord(enhancedResult) && params.sentMessage) {
548
+ const messagesPage = isRecord(params.messagesResult?.result)
549
+ ? params.messagesResult?.result
550
+ : { items: [params.sentMessage], hasMore: false };
551
+ enhancedResult = {
552
+ ...enhancedResult,
553
+ messages: messagesPage,
554
+ sentMessage: params.sentMessage,
555
+ sentMessageId,
556
+ sendVerification,
557
+ };
558
+ } else if (isRecord(enhancedResult)) {
559
+ enhancedResult = {
560
+ ...enhancedResult,
561
+ sentMessage: params.sentMessage ?? null,
562
+ sentMessageId,
563
+ sendVerification,
564
+ };
565
+ } else {
566
+ enhancedResult = {
567
+ originalResult: enhancedResult,
568
+ sentMessage: params.sentMessage ?? null,
569
+ sentMessageId,
570
+ sendVerification,
571
+ };
572
+ }
573
+
574
+ return {
575
+ ...params.commandResult,
576
+ result: enhancedResult,
577
+ sentMessage: params.sentMessage ?? null,
578
+ sentMessageId,
579
+ sendVerification,
580
+ resultText: JSON.stringify(enhancedResult, null, 2),
581
+ };
582
+};
583
+
584
+const threadMatches = (params: {
585
+ readonly thread: Record<string, unknown>;
586
+ readonly query?: string;
587
+ readonly recipientIdentifiers: ReadonlySet<string>;
588
+ readonly contactIdentifiers: ReadonlySet<string>;
589
+ readonly labels: Record<string, string>;
590
+}): boolean => {
591
+ const identifiers = participantIdentifiers(params.thread);
592
+ const normalizedIdentifiers = identifiers.map(normalizeIdentifier).filter(Boolean);
593
+ const labels = normalizedIdentifiers.map(identifier => params.labels[identifier]).filter(Boolean);
594
+ const query = params.query?.trim().toLowerCase();
595
+
596
+ if (params.recipientIdentifiers.size > 0) {
597
+ const normalizedSet = new Set(normalizedIdentifiers);
598
+ const hasAllRecipients = [...params.recipientIdentifiers].every(identifier =>
599
+ normalizedSet.has(identifier)
600
+ );
601
+ if (hasAllRecipients) return true;
602
+ }
603
+
604
+ if (params.contactIdentifiers.size > 0) {
605
+ const normalizedSet = new Set(normalizedIdentifiers);
606
+ if ([...params.contactIdentifiers].some(identifier => normalizedSet.has(identifier)))
607
+ return true;
608
+ }
609
+
610
+ if (!query) return false;
611
+ const searchable = [
612
+ optionalString(params.thread.title),
613
+ optionalString(params.thread.id),
614
+ ...identifiers,
615
+ ...labels,
616
+ ]
617
+ .filter((value): value is string => Boolean(value))
618
+ .join(' ')
619
+ .toLowerCase();
620
+ return searchable.includes(query);
621
+};
622
+
623
+const scanThreads = async (params: {
624
+ readonly input: Record<string, unknown>;
625
+ readonly context: LocalExecutionContext;
626
+ readonly query?: string;
627
+ readonly recipients?: ReadonlyArray<string>;
628
+ readonly maxPages?: number;
629
+ readonly resolveContactNames?: boolean;
630
+}): Promise<{
631
+ readonly matches: ReadonlyArray<Record<string, unknown>>;
632
+ readonly pagesScanned: number;
633
+ readonly nextBefore?: string;
634
+ readonly hasMore: boolean;
635
+ readonly contactLookup?: ContactLookupResult;
636
+ readonly labels: Record<string, string>;
637
+}> => {
638
+ const maxPages = Math.min(
639
+ Math.max(1, Number(params.maxPages ?? THREAD_SCAN_DEFAULT_MAX_PAGES)),
640
+ THREAD_SCAN_MAX_PAGES
641
+ );
642
+ const recipients = params.recipients ?? [];
643
+ const recipientIdentifiers = new Set(recipients.map(normalizeIdentifier).filter(Boolean));
644
+ const contactLookup =
645
+ params.resolveContactNames && params.query
646
+ ? await lookupContacts('query', { query: params.query })
647
+ : undefined;
648
+ const contactIdentifiers = new Set(
649
+ contactLookup ? contactIdentifiersFromMatches(contactLookup) : []
650
+ );
651
+
652
+ let before: string | undefined = optionalString(params.input.before);
653
+ let hasMore = true;
654
+ let pagesScanned = 0;
655
+ let nextBefore: string | undefined;
656
+ const matches: Record<string, unknown>[] = [];
657
+ const labelTargets: Record<string, unknown>[] = [];
658
+
659
+ while (pagesScanned < maxPages && hasMore) {
660
+ pagesScanned += 1;
661
+ const pageInput = { ...params.input, ...(before ? { before } : {}) };
662
+ const page = await runImessageCli(
663
+ 'threads',
664
+ withCursorArgs(pageInput, []),
665
+ pageInput,
666
+ params.context
667
+ );
668
+ const result = isRecord(page.result) ? page.result : {};
669
+ const threads = extractPageItems(result);
670
+ labelTargets.push(...threads);
671
+ const labels = await labelsForThreads(threads, params.resolveContactNames ?? true);
672
+ matches.push(
673
+ ...threads.filter(thread =>
674
+ threadMatches({
675
+ thread,
676
+ query: params.query,
677
+ recipientIdentifiers,
678
+ contactIdentifiers,
679
+ labels,
680
+ })
681
+ )
682
+ );
683
+ hasMore = result.hasMore === true;
684
+ nextBefore = optionalString(result.oldestCursor);
685
+ before = nextBefore;
686
+ if (!before) break;
687
+ }
688
+
689
+ const labels = await labelsForThreads(labelTargets, params.resolveContactNames ?? true);
690
+ return { matches, pagesScanned, nextBefore, hasMore, contactLookup, labels };
691
+};
692
+
693
+const commandTool = <TInput extends z.ZodTypeAny>(definition: {
694
+ readonly slug: string;
695
+ readonly name: string;
696
+ readonly description: string;
697
+ readonly inputParams: TInput;
698
+ readonly command: string;
699
+ readonly args: (input: z.infer<TInput>) => ReadonlyArray<string>;
700
+}): LocalToolDeclaration<TInput> => ({
701
+ slug: definition.slug,
702
+ name: definition.name,
703
+ description: definition.description,
704
+ platforms: ['darwin-arm64', 'darwin-x64'],
705
+ inputParams: definition.inputParams,
706
+ outputParams: cliOutput,
707
+ execution: {
708
+ kind: 'native',
709
+ execute: (input, context) =>
710
+ runImessageCli(definition.command, definition.args(input as z.infer<TInput>), input, context),
711
+ },
712
+});
713
+
714
+const nativeTool = <TInput extends z.ZodTypeAny>(definition: {
715
+ readonly slug: string;
716
+ readonly name: string;
717
+ readonly description: string;
718
+ readonly inputParams: TInput;
719
+ readonly execute: (
720
+ input: z.infer<TInput>,
721
+ context: LocalExecutionContext
722
+ ) => Promise<LocalExecutionResult>;
723
+}): LocalToolDeclaration<TInput> => ({
724
+ slug: definition.slug,
725
+ name: definition.name,
726
+ description: definition.description,
727
+ platforms: ['darwin-arm64', 'darwin-x64'],
728
+ inputParams: definition.inputParams,
729
+ outputParams: cliOutput,
730
+ execution: {
731
+ kind: 'native',
732
+ execute: (input, context) => definition.execute(input as z.infer<TInput>, context),
733
+ },
734
+});
735
+
736
+const threadId = z
737
+ .string()
738
+ .min(1)
739
+ .describe('platform-imessage chat/thread ID, e.g. any;-;user@example.com.');
740
+const messageId = z.string().min(1).describe('platform-imessage message ID.');
741
+const text = z.string().min(1).describe('Message text.');
742
+const filePath = z.string().min(1).describe('Local file path to attach.');
743
+
744
+const listThreadsInput = baseInput.merge(cursorInput).extend({
745
+ compact: z
746
+ .boolean()
747
+ .default(true)
748
+ .describe(
749
+ 'Return a compact thread shape with id/title/type/participant labels/lastMessage/pageInfo. Set false to return the raw upstream CLI response.'
750
+ ),
751
+ includeRaw: z
752
+ .boolean()
753
+ .default(false)
754
+ .describe('When compact=true, include the raw upstream thread page under result.raw.'),
755
+ resolveContactNames: z
756
+ .boolean()
757
+ .default(true)
758
+ .describe('Best-effort macOS Contacts lookup for participant labels in compact output.'),
759
+});
760
+
761
+const findThreadInput = baseInput.extend({
762
+ query: z
763
+ .string()
764
+ .min(1)
765
+ .optional()
766
+ .describe('Contact name, phone/email, thread title, or participant identifier to search for.'),
767
+ recipients: z
768
+ .array(z.string().min(1))
769
+ .optional()
770
+ .describe('Phone numbers or emails that must be present in the thread participants.'),
771
+ maxPages: z
772
+ .number()
773
+ .int()
774
+ .positive()
775
+ .max(THREAD_SCAN_MAX_PAGES)
776
+ .default(THREAD_SCAN_DEFAULT_MAX_PAGES)
777
+ .describe('Maximum 25-thread pages to scan.'),
778
+ compact: z.boolean().default(true).describe('Return compact thread matches.'),
779
+ resolveContactNames: z
780
+ .boolean()
781
+ .default(true)
782
+ .describe(
783
+ 'Best-effort macOS Contacts lookup so names like “Mustafa” can resolve to phone/email participants.'
784
+ ),
785
+});
786
+
787
+const sendVerificationInput = {
788
+ verifySent: z
789
+ .boolean()
790
+ .default(true)
791
+ .describe(
792
+ 'After the send command succeeds, poll the local Messages DB for the newly sent message.'
793
+ ),
794
+ verificationTimeoutMs: z
795
+ .number()
796
+ .int()
797
+ .min(0)
798
+ .max(30_000)
799
+ .default(SEND_VERIFY_TIMEOUT_MS)
800
+ .describe(
801
+ 'How long to poll for the sent message before returning command_succeeded_but_not_observed.'
802
+ ),
803
+};
804
+
805
+const reactionInput = primaryInstanceInput.extend({
806
+ threadId,
807
+ messageId,
808
+ reaction: z
809
+ .string()
810
+ .min(1)
811
+ .describe(
812
+ 'Reaction key or emoji. Standard keys: heart, like, dislike, laugh, emphasize, question.'
813
+ ),
814
+ prepareTranscript: z
815
+ .boolean()
816
+ .default(true)
817
+ .describe('Run select-thread before reacting so the transcript is visible for UI automation.'),
818
+ prepareTimeoutMs: z
819
+ .number()
820
+ .int()
821
+ .positive()
822
+ .max(30_000)
823
+ .default(REACTION_PREPARE_TIMEOUT_MS)
824
+ .describe('Timeout for select-thread transcript preparation.'),
825
+ reactionTimeoutMs: z
826
+ .number()
827
+ .int()
828
+ .positive()
829
+ .max(60_000)
830
+ .default(REACTION_TIMEOUT_MS)
831
+ .describe('Timeout for the reaction command itself.'),
832
+});
833
+
834
+const sendMessageInput = baseInput.extend({ threadId, text, ...sendVerificationInput });
835
+
836
+const createThreadAndSendInput = baseInput.extend({
837
+ recipients: z.array(z.string().min(1)).min(1).describe('Recipient phone numbers or emails.'),
838
+ message: text,
839
+ ...sendVerificationInput,
840
+});
841
+
842
+export const beeperImessageToolkit: LocalToolkitDeclaration = {
843
+ slug: 'BEEPER_IMESSAGE',
844
+ name: 'Beeper iMessage (local)',
845
+ description:
846
+ 'Local macOS iMessage tools backed by Beeper platform-imessage imessage-cli. Reads ~/Library/Messages and automates Messages.app for send/reaction/chat mutations.',
847
+ platforms: ['darwin-arm64', 'darwin-x64'],
848
+ source: {
849
+ type: 'cli',
850
+ repository: 'https://github.com/ComposioHQ/platform-imessage',
851
+ command: 'imessage-cli',
852
+ },
853
+ bundledBinaries: [
854
+ {
855
+ id: IMESSAGE_CLI_BINARY_ID,
856
+ description: `Beeper platform-imessage imessage-cli ${IMESSAGE_CLI_VERSION}.`,
857
+ targets: [
858
+ {
859
+ platforms: ['darwin-arm64'],
860
+ path: 'beeper-imessage/darwin-arm64/imessage-cli',
861
+ },
862
+ {
863
+ platforms: ['darwin-x64'],
864
+ path: 'beeper-imessage/darwin-x64/imessage-cli',
865
+ },
866
+ ],
867
+ },
868
+ ],
869
+ setup: {
870
+ install:
871
+ 'The CLI ships a bundled imessage-cli binary built from the ts/packages/cli-local-tools/vendor/platform-imessage submodule. Alternatively install/build imessage-cli and set a command override in ~/composio/local_tools.json.',
872
+ commandOverrides: [
873
+ 'composio local-tools configure BEEPER_IMESSAGE --command /path/to/imessage-cli',
874
+ ],
875
+ notes: [
876
+ 'Requires macOS with Messages.app configured for iMessage.',
877
+ 'Read-only tools require Messages Data access. Mutating tools require Messages Data and Accessibility; some setup flows may also request Contacts or Automation.',
878
+ 'Run LOCAL_BEEPER_IMESSAGE_AUTHORIZE (or imessage-cli authorize) to inspect/request permissions. A future local-tool auth abstraction should route this through composio link BEEPER_IMESSAGE.',
879
+ 'Most read/send tools work with the secondary Messages instance. Reaction tools default to the primary instance and prepare the transcript because upstream UI automation requires a visible reply transcript.',
880
+ ],
881
+ },
882
+ tools: [
883
+ commandTool({
884
+ slug: 'VERSION',
885
+ name: 'Get imessage-cli version',
886
+ description:
887
+ 'Print the bundled Beeper platform-imessage CLI version without touching Messages.app.',
888
+ inputParams: baseInput,
889
+ command: 'version',
890
+ args: () => [],
891
+ }),
892
+ commandTool({
893
+ slug: 'AUTHORIZE',
894
+ name: 'Inspect or request iMessage local permissions',
895
+ description:
896
+ 'Run imessage-cli authorize for Accessibility, Contacts, Messages Data, and Automation permissions. This may open macOS prompts or System Settings. This is the local equivalent of linking/authorizing the iMessage toolkit.',
897
+ inputParams: baseInput.extend({
898
+ target: z
899
+ .enum(['all', 'accessibility', 'contacts', 'messages-data', 'automation'])
900
+ .default('all')
901
+ .describe('Permission target to inspect/request.'),
902
+ }),
903
+ command: 'authorize',
904
+ args: input => [input.target],
905
+ }),
906
+ commandTool({
907
+ slug: 'CURRENT_USER',
908
+ name: 'Get current iMessage user',
909
+ description:
910
+ 'Return the iMessage identity known to the local platform-imessage backend. Requires Messages Data access.',
911
+ inputParams: baseInput,
912
+ command: 'current-user',
913
+ args: () => [],
914
+ }),
915
+ nativeTool({
916
+ slug: 'LIST_THREADS',
917
+ name: 'List iMessage threads',
918
+ description:
919
+ 'List normal-inbox iMessage chats from the local Messages database. Defaults to compact output with pageInfo.nextBefore for pagination; set compact=false for raw upstream output.',
920
+ inputParams: listThreadsInput,
921
+ execute: async (input, context) => {
922
+ const raw = await runImessageCli('threads', withCursorArgs(input, []), input, context);
923
+ return compactThreadsResult(raw, {
924
+ compact: input.compact,
925
+ includeRaw: input.includeRaw,
926
+ resolveContactNames: input.resolveContactNames,
927
+ });
928
+ },
929
+ }),
930
+ nativeTool({
931
+ slug: 'FIND_THREAD',
932
+ name: 'Find iMessage thread',
933
+ description:
934
+ 'Find threads by contact name, phone/email, thread title, or participants without doing a manual LIST_THREADS pagination/filter dance.',
935
+ inputParams: findThreadInput,
936
+ execute: async (input, context) => {
937
+ if (!input.query && (!input.recipients || input.recipients.length === 0)) {
938
+ throw new Error('Provide query or recipients to find an iMessage thread.');
939
+ }
940
+ const scan = await scanThreads({
941
+ input,
942
+ context,
943
+ query: input.query,
944
+ recipients: input.recipients,
945
+ maxPages: input.maxPages,
946
+ resolveContactNames: input.resolveContactNames,
947
+ });
948
+ const result = {
949
+ items: input.compact
950
+ ? scan.matches.map(thread => compactThread(thread, scan.labels))
951
+ : scan.matches,
952
+ pageInfo: {
953
+ pagesScanned: scan.pagesScanned,
954
+ hasMore: scan.hasMore,
955
+ nextBefore: scan.nextBefore,
956
+ },
957
+ contactResolution: {
958
+ enabled: input.resolveContactNames,
959
+ matchedContacts: scan.contactLookup?.matches.length ?? 0,
960
+ error: scan.contactLookup?.error,
961
+ },
962
+ };
963
+ return {
964
+ ok: true,
965
+ commandName: 'find-thread',
966
+ result,
967
+ resultText: JSON.stringify(result, null, 2),
968
+ stdout: '',
969
+ stderr: '',
970
+ };
971
+ },
972
+ }),
973
+ commandTool({
974
+ slug: 'GET_THREAD',
975
+ name: 'Get iMessage thread',
976
+ description: 'Fetch a single iMessage chat/thread by platform-imessage thread ID.',
977
+ inputParams: baseInput.extend({ threadId }),
978
+ command: 'thread',
979
+ args: input => [input.threadId],
980
+ }),
981
+ commandTool({
982
+ slug: 'LIST_MESSAGES',
983
+ name: 'List iMessage messages',
984
+ description:
985
+ 'List messages in a chat from the local Messages database, optionally using cursors.',
986
+ inputParams: baseInput.merge(cursorInput).extend({ threadId }),
987
+ command: 'messages',
988
+ args: input => withCursorArgs(input, [input.threadId]),
989
+ }),
990
+ commandTool({
991
+ slug: 'GET_MESSAGE',
992
+ name: 'Get iMessage message',
993
+ description: 'Fetch a single message by chat/thread ID and message ID.',
994
+ inputParams: baseInput.extend({ threadId, messageId }),
995
+ command: 'message',
996
+ args: input => [input.threadId, input.messageId],
997
+ }),
998
+ nativeTool({
999
+ slug: 'SEARCH_MESSAGES',
1000
+ name: 'Search local iMessage messages',
1001
+ description:
1002
+ 'Search local iMessage messages by text and, by default, also search thread participants/contact names so queries like “Nikos” can find matching chats.',
1003
+ inputParams: baseInput.extend({
1004
+ query: z
1005
+ .string()
1006
+ .min(1)
1007
+ .describe('Text, participant name, phone/email, or thread title to search for.'),
1008
+ includeThreadMatches: z
1009
+ .boolean()
1010
+ .default(true)
1011
+ .describe(
1012
+ 'Also scan threads/participants/contact names in addition to upstream message text search.'
1013
+ ),
1014
+ maxThreadPages: z
1015
+ .number()
1016
+ .int()
1017
+ .positive()
1018
+ .max(THREAD_SCAN_MAX_PAGES)
1019
+ .default(THREAD_SCAN_DEFAULT_MAX_PAGES)
1020
+ .describe('Maximum 25-thread pages to scan when includeThreadMatches=true.'),
1021
+ compactThreads: z
1022
+ .boolean()
1023
+ .default(true)
1024
+ .describe('Return compact matching thread records.'),
1025
+ resolveContactNames: z
1026
+ .boolean()
1027
+ .default(true)
1028
+ .describe('Best-effort macOS Contacts lookup for participant/name matching.'),
1029
+ }),
1030
+ execute: async (input, context) => {
1031
+ const searchResult = await runImessageCli('search', [input.query], input, context);
1032
+ const threadScan = input.includeThreadMatches
1033
+ ? await scanThreads({
1034
+ input,
1035
+ context,
1036
+ query: input.query,
1037
+ maxPages: input.maxThreadPages,
1038
+ resolveContactNames: input.resolveContactNames,
1039
+ })
1040
+ : undefined;
1041
+ const result = {
1042
+ messageSearch: searchResult.result,
1043
+ matchingThreads: threadScan
1044
+ ? input.compactThreads
1045
+ ? threadScan.matches.map(thread => compactThread(thread, threadScan.labels))
1046
+ : threadScan.matches
1047
+ : [],
1048
+ threadSearch: threadScan
1049
+ ? {
1050
+ pagesScanned: threadScan.pagesScanned,
1051
+ hasMore: threadScan.hasMore,
1052
+ nextBefore: threadScan.nextBefore,
1053
+ contactResolution: {
1054
+ enabled: input.resolveContactNames,
1055
+ matchedContacts: threadScan.contactLookup?.matches.length ?? 0,
1056
+ error: threadScan.contactLookup?.error,
1057
+ },
1058
+ }
1059
+ : { enabled: false },
1060
+ };
1061
+ return {
1062
+ ...searchResult,
1063
+ result,
1064
+ resultText: JSON.stringify(result, null, 2),
1065
+ };
1066
+ },
1067
+ }),
1068
+ nativeTool({
1069
+ slug: 'CREATE_THREAD_AND_SEND',
1070
+ name: 'Create iMessage thread and send message',
1071
+ description:
1072
+ 'Create or resolve a chat for one or more recipients and send the initial message. After the send command succeeds, this verifies the newly sent message and returns sentMessage/sentMessageId to avoid stale existing-thread ambiguity.',
1073
+ inputParams: createThreadAndSendInput,
1074
+ execute: async (input, context) => {
1075
+ const createResult = await runImessageCli(
1076
+ 'create-thread',
1077
+ [...stringArray(input.recipients), '--message', input.message],
1078
+ input,
1079
+ context
1080
+ );
1081
+ const threadId = extractThreadId(createResult.result);
1082
+ const verification =
1083
+ input.verifySent && threadId
1084
+ ? await pollForSentMessage({
1085
+ threadId,
1086
+ text: input.message,
1087
+ input,
1088
+ context,
1089
+ timeoutMs: input.verificationTimeoutMs,
1090
+ })
1091
+ : { attempts: 0 };
1092
+ return enhanceSendResult({
1093
+ commandResult: createResult,
1094
+ threadId,
1095
+ sentText: input.message,
1096
+ sentMessage: verification.message,
1097
+ messagesResult: verification.messagesResult,
1098
+ attempts: verification.attempts,
1099
+ verify: input.verifySent,
1100
+ });
1101
+ },
1102
+ }),
1103
+ nativeTool({
1104
+ slug: 'SEND_MESSAGE',
1105
+ name: 'Send iMessage text',
1106
+ description:
1107
+ 'Send a text message to an existing chat/thread. Returns sendVerification plus sentMessage/sentMessageId when the local DB observes the new message, so callers should not retry solely because a thread preview is stale.',
1108
+ inputParams: sendMessageInput,
1109
+ execute: async (input, context) => {
1110
+ const beforeMessages = input.verifySent
1111
+ ? await fetchMessages(input.threadId, input, context)
1112
+ : undefined;
1113
+ const excludeMessageIds = new Set(
1114
+ extractPageItems(beforeMessages?.result)
1115
+ .map(messageIdOf)
1116
+ .filter((value): value is string => Boolean(value))
1117
+ );
1118
+ const sendResult = await runImessageCli(
1119
+ 'send',
1120
+ [input.threadId, input.text],
1121
+ input,
1122
+ context
1123
+ );
1124
+ const verification = input.verifySent
1125
+ ? await pollForSentMessage({
1126
+ threadId: input.threadId,
1127
+ text: input.text,
1128
+ input,
1129
+ context,
1130
+ timeoutMs: input.verificationTimeoutMs,
1131
+ excludeMessageIds,
1132
+ })
1133
+ : { attempts: 0 };
1134
+ return enhanceSendResult({
1135
+ commandResult: sendResult,
1136
+ threadId: input.threadId,
1137
+ sentText: input.text,
1138
+ sentMessage: verification.message,
1139
+ messagesResult: verification.messagesResult,
1140
+ attempts: verification.attempts,
1141
+ verify: input.verifySent,
1142
+ });
1143
+ },
1144
+ }),
1145
+ commandTool({
1146
+ slug: 'REPLY_TO_MESSAGE',
1147
+ name: 'Reply to iMessage message',
1148
+ description: 'Reply to a specific iMessage with text. Mutates real Messages state.',
1149
+ inputParams: baseInput.extend({ threadId, messageId, text }),
1150
+ command: 'reply',
1151
+ args: input => [input.threadId, input.messageId, input.text],
1152
+ }),
1153
+ commandTool({
1154
+ slug: 'SEND_FILE',
1155
+ name: 'Send iMessage file attachment',
1156
+ description:
1157
+ 'Send a local file attachment to an existing chat/thread. Mutates real Messages state.',
1158
+ inputParams: baseInput.extend({ threadId, filePath }),
1159
+ command: 'send-file',
1160
+ args: input => [input.threadId, absolutePath(input.filePath)],
1161
+ }),
1162
+ commandTool({
1163
+ slug: 'REPLY_WITH_FILE',
1164
+ name: 'Reply to iMessage with file attachment',
1165
+ description:
1166
+ 'Reply to a specific message with a local file attachment. Mutates real Messages state.',
1167
+ inputParams: baseInput.extend({ threadId, messageId, filePath }),
1168
+ command: 'reply-file',
1169
+ args: input => [input.threadId, input.messageId, absolutePath(input.filePath)],
1170
+ }),
1171
+ commandTool({
1172
+ slug: 'EDIT_MESSAGE',
1173
+ name: 'Edit sent iMessage',
1174
+ description:
1175
+ 'Edit a previously sent iMessage. Supported by upstream on macOS Ventura or later.',
1176
+ inputParams: baseInput.extend({ threadId, messageId, text }),
1177
+ command: 'edit',
1178
+ args: input => [input.threadId, input.messageId, input.text],
1179
+ }),
1180
+ commandTool({
1181
+ slug: 'UNDO_SEND',
1182
+ name: 'Undo sent iMessage',
1183
+ description:
1184
+ 'Undo send for a previously sent iMessage. Upstream supports this on macOS Ventura or later within the Messages time limit.',
1185
+ inputParams: baseInput.extend({ threadId, messageId }),
1186
+ command: 'undo-send',
1187
+ args: input => [input.threadId, input.messageId],
1188
+ }),
1189
+ nativeTool({
1190
+ slug: 'REACT_TO_MESSAGE',
1191
+ name: 'React to iMessage',
1192
+ description:
1193
+ 'Add a standard reaction to a message using a supported key or emoji. Defaults to the primary Messages.app instance and runs select-thread first because upstream reaction automation needs a visible transcript.',
1194
+ inputParams: reactionInput,
1195
+ execute: async (input, context) => {
1196
+ const effectiveInput = { ...input, useSecondaryInstance: input.useSecondaryInstance };
1197
+ if (input.prepareTranscript) {
1198
+ await runImessageCli('select-thread', [input.threadId], effectiveInput, context, {
1199
+ timeoutMs: input.prepareTimeoutMs,
1200
+ });
1201
+ }
1202
+ return runImessageCli(
1203
+ 'react',
1204
+ [input.threadId, input.messageId, input.reaction],
1205
+ effectiveInput,
1206
+ context,
1207
+ { timeoutMs: input.reactionTimeoutMs }
1208
+ );
1209
+ },
1210
+ }),
1211
+ nativeTool({
1212
+ slug: 'UNREACT_FROM_MESSAGE',
1213
+ name: 'Remove iMessage reaction',
1214
+ description:
1215
+ 'Remove a standard reaction from a message. Defaults to the primary Messages.app instance and runs select-thread first because upstream reaction automation needs a visible transcript.',
1216
+ inputParams: reactionInput,
1217
+ execute: async (input, context) => {
1218
+ const effectiveInput = { ...input, useSecondaryInstance: input.useSecondaryInstance };
1219
+ if (input.prepareTranscript) {
1220
+ await runImessageCli('select-thread', [input.threadId], effectiveInput, context, {
1221
+ timeoutMs: input.prepareTimeoutMs,
1222
+ });
1223
+ }
1224
+ return runImessageCli(
1225
+ 'unreact',
1226
+ [input.threadId, input.messageId, input.reaction],
1227
+ effectiveInput,
1228
+ context,
1229
+ { timeoutMs: input.reactionTimeoutMs }
1230
+ );
1231
+ },
1232
+ }),
1233
+ commandTool({
1234
+ slug: 'MARK_READ',
1235
+ name: 'Mark iMessage thread read',
1236
+ description:
1237
+ 'Mark a chat/thread as read by sending a read receipt. Mutates real Messages state.',
1238
+ inputParams: baseInput.extend({ threadId }),
1239
+ command: 'mark-read',
1240
+ args: input => [input.threadId],
1241
+ }),
1242
+ commandTool({
1243
+ slug: 'MARK_UNREAD',
1244
+ name: 'Mark iMessage thread unread',
1245
+ description: 'Mark a chat/thread as unread. Mutates real Messages state.',
1246
+ inputParams: baseInput.extend({ threadId }),
1247
+ command: 'mark-unread',
1248
+ args: input => [input.threadId],
1249
+ }),
1250
+ commandTool({
1251
+ slug: 'MUTE_THREAD',
1252
+ name: 'Mute iMessage thread',
1253
+ description: 'Mute a chat/thread indefinitely. Mutates real Messages state.',
1254
+ inputParams: baseInput.extend({ threadId }),
1255
+ command: 'mute',
1256
+ args: input => [input.threadId],
1257
+ }),
1258
+ commandTool({
1259
+ slug: 'UNMUTE_THREAD',
1260
+ name: 'Unmute iMessage thread',
1261
+ description: 'Unmute a chat/thread. Mutates real Messages state.',
1262
+ inputParams: baseInput.extend({ threadId }),
1263
+ command: 'unmute',
1264
+ args: input => [input.threadId],
1265
+ }),
1266
+ commandTool({
1267
+ slug: 'SEND_TYPING_STATUS',
1268
+ name: 'Send iMessage typing status',
1269
+ description: 'Send typing on/off status for a chat/thread. Mutates real Messages state.',
1270
+ inputParams: baseInput.extend({
1271
+ threadId,
1272
+ status: z.enum(['on', 'off']).describe('Typing status to send.'),
1273
+ }),
1274
+ command: 'typing',
1275
+ args: input => [input.threadId, input.status],
1276
+ }),
1277
+ commandTool({
1278
+ slug: 'NOTIFY_ANYWAY',
1279
+ name: 'Notify anyway for iMessage thread',
1280
+ description:
1281
+ 'Trigger the Messages "notify anyway" action for a chat/thread. Mutates real Messages state.',
1282
+ inputParams: baseInput.extend({ threadId }),
1283
+ command: 'notify-anyway',
1284
+ args: input => [input.threadId],
1285
+ }),
1286
+ commandTool({
1287
+ slug: 'DELETE_THREAD',
1288
+ name: 'Delete iMessage thread',
1289
+ description:
1290
+ 'Delete a chat/thread from Messages. Requires confirm=true because this mutates real Messages state.',
1291
+ inputParams: baseInput.extend({
1292
+ threadId,
1293
+ confirm: z.literal(true).describe('Must be true to delete the thread.'),
1294
+ }),
1295
+ command: 'delete-thread',
1296
+ args: input => [input.threadId],
1297
+ }),
1298
+ ],
1299
+};