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'],
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'],
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'],
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
- },
864
- ],
865
- setup: {
866
- install:
867
- '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.',
868
- commandOverrides: [
869
- 'composio local-tools configure BEEPER_IMESSAGE --command /path/to/imessage-cli',
870
- ],
871
- notes: [
872
- 'Requires macOS with Messages.app configured for iMessage.',
873
- 'Read-only tools require Messages Data access. Mutating tools require Messages Data and Accessibility; some setup flows may also request Contacts or Automation.',
874
- '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.',
875
- '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.',
876
- ],
877
- },
878
- tools: [
879
- commandTool({
880
- slug: 'VERSION',
881
- name: 'Get imessage-cli version',
882
- description:
883
- 'Print the bundled Beeper platform-imessage CLI version without touching Messages.app.',
884
- inputParams: baseInput,
885
- command: 'version',
886
- args: () => [],
887
- }),
888
- commandTool({
889
- slug: 'AUTHORIZE',
890
- name: 'Inspect or request iMessage local permissions',
891
- description:
892
- '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.',
893
- inputParams: baseInput.extend({
894
- target: z
895
- .enum(['all', 'accessibility', 'contacts', 'messages-data', 'automation'])
896
- .default('all')
897
- .describe('Permission target to inspect/request.'),
898
- }),
899
- command: 'authorize',
900
- args: input => [input.target],
901
- }),
902
- commandTool({
903
- slug: 'CURRENT_USER',
904
- name: 'Get current iMessage user',
905
- description:
906
- 'Return the iMessage identity known to the local platform-imessage backend. Requires Messages Data access.',
907
- inputParams: baseInput,
908
- command: 'current-user',
909
- args: () => [],
910
- }),
911
- nativeTool({
912
- slug: 'LIST_THREADS',
913
- name: 'List iMessage threads',
914
- description:
915
- '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.',
916
- inputParams: listThreadsInput,
917
- execute: async (input, context) => {
918
- const raw = await runImessageCli('threads', withCursorArgs(input, []), input, context);
919
- return compactThreadsResult(raw, {
920
- compact: input.compact,
921
- includeRaw: input.includeRaw,
922
- resolveContactNames: input.resolveContactNames,
923
- });
924
- },
925
- }),
926
- nativeTool({
927
- slug: 'FIND_THREAD',
928
- name: 'Find iMessage thread',
929
- description:
930
- 'Find threads by contact name, phone/email, thread title, or participants without doing a manual LIST_THREADS pagination/filter dance.',
931
- inputParams: findThreadInput,
932
- execute: async (input, context) => {
933
- if (!input.query && (!input.recipients || input.recipients.length === 0)) {
934
- throw new Error('Provide query or recipients to find an iMessage thread.');
935
- }
936
- const scan = await scanThreads({
937
- input,
938
- context,
939
- query: input.query,
940
- recipients: input.recipients,
941
- maxPages: input.maxPages,
942
- resolveContactNames: input.resolveContactNames,
943
- });
944
- const result = {
945
- items: input.compact
946
- ? scan.matches.map(thread => compactThread(thread, scan.labels))
947
- : scan.matches,
948
- pageInfo: {
949
- pagesScanned: scan.pagesScanned,
950
- hasMore: scan.hasMore,
951
- nextBefore: scan.nextBefore,
952
- },
953
- contactResolution: {
954
- enabled: input.resolveContactNames,
955
- matchedContacts: scan.contactLookup?.matches.length ?? 0,
956
- error: scan.contactLookup?.error,
957
- },
958
- };
959
- return {
960
- ok: true,
961
- commandName: 'find-thread',
962
- result,
963
- resultText: JSON.stringify(result, null, 2),
964
- stdout: '',
965
- stderr: '',
966
- };
967
- },
968
- }),
969
- commandTool({
970
- slug: 'GET_THREAD',
971
- name: 'Get iMessage thread',
972
- description: 'Fetch a single iMessage chat/thread by platform-imessage thread ID.',
973
- inputParams: baseInput.extend({ threadId }),
974
- command: 'thread',
975
- args: input => [input.threadId],
976
- }),
977
- commandTool({
978
- slug: 'LIST_MESSAGES',
979
- name: 'List iMessage messages',
980
- description:
981
- 'List messages in a chat from the local Messages database, optionally using cursors.',
982
- inputParams: baseInput.merge(cursorInput).extend({ threadId }),
983
- command: 'messages',
984
- args: input => withCursorArgs(input, [input.threadId]),
985
- }),
986
- commandTool({
987
- slug: 'GET_MESSAGE',
988
- name: 'Get iMessage message',
989
- description: 'Fetch a single message by chat/thread ID and message ID.',
990
- inputParams: baseInput.extend({ threadId, messageId }),
991
- command: 'message',
992
- args: input => [input.threadId, input.messageId],
993
- }),
994
- nativeTool({
995
- slug: 'SEARCH_MESSAGES',
996
- name: 'Search local iMessage messages',
997
- description:
998
- 'Search local iMessage messages by text and, by default, also search thread participants/contact names so queries like “Nikos” can find matching chats.',
999
- inputParams: baseInput.extend({
1000
- query: z
1001
- .string()
1002
- .min(1)
1003
- .describe('Text, participant name, phone/email, or thread title to search for.'),
1004
- includeThreadMatches: z
1005
- .boolean()
1006
- .default(true)
1007
- .describe(
1008
- 'Also scan threads/participants/contact names in addition to upstream message text search.'
1009
- ),
1010
- maxThreadPages: z
1011
- .number()
1012
- .int()
1013
- .positive()
1014
- .max(THREAD_SCAN_MAX_PAGES)
1015
- .default(THREAD_SCAN_DEFAULT_MAX_PAGES)
1016
- .describe('Maximum 25-thread pages to scan when includeThreadMatches=true.'),
1017
- compactThreads: z
1018
- .boolean()
1019
- .default(true)
1020
- .describe('Return compact matching thread records.'),
1021
- resolveContactNames: z
1022
- .boolean()
1023
- .default(true)
1024
- .describe('Best-effort macOS Contacts lookup for participant/name matching.'),
1025
- }),
1026
- execute: async (input, context) => {
1027
- const searchResult = await runImessageCli('search', [input.query], input, context);
1028
- const threadScan = input.includeThreadMatches
1029
- ? await scanThreads({
1030
- input,
1031
- context,
1032
- query: input.query,
1033
- maxPages: input.maxThreadPages,
1034
- resolveContactNames: input.resolveContactNames,
1035
- })
1036
- : undefined;
1037
- const result = {
1038
- messageSearch: searchResult.result,
1039
- matchingThreads: threadScan
1040
- ? input.compactThreads
1041
- ? threadScan.matches.map(thread => compactThread(thread, threadScan.labels))
1042
- : threadScan.matches
1043
- : [],
1044
- threadSearch: threadScan
1045
- ? {
1046
- pagesScanned: threadScan.pagesScanned,
1047
- hasMore: threadScan.hasMore,
1048
- nextBefore: threadScan.nextBefore,
1049
- contactResolution: {
1050
- enabled: input.resolveContactNames,
1051
- matchedContacts: threadScan.contactLookup?.matches.length ?? 0,
1052
- error: threadScan.contactLookup?.error,
1053
- },
1054
- }
1055
- : { enabled: false },
1056
- };
1057
- return {
1058
- ...searchResult,
1059
- result,
1060
- resultText: JSON.stringify(result, null, 2),
1061
- };
1062
- },
1063
- }),
1064
- nativeTool({
1065
- slug: 'CREATE_THREAD_AND_SEND',
1066
- name: 'Create iMessage thread and send message',
1067
- description:
1068
- '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.',
1069
- inputParams: createThreadAndSendInput,
1070
- execute: async (input, context) => {
1071
- const createResult = await runImessageCli(
1072
- 'create-thread',
1073
- [...stringArray(input.recipients), '--message', input.message],
1074
- input,
1075
- context
1076
- );
1077
- const threadId = extractThreadId(createResult.result);
1078
- const verification =
1079
- input.verifySent && threadId
1080
- ? await pollForSentMessage({
1081
- threadId,
1082
- text: input.message,
1083
- input,
1084
- context,
1085
- timeoutMs: input.verificationTimeoutMs,
1086
- })
1087
- : { attempts: 0 };
1088
- return enhanceSendResult({
1089
- commandResult: createResult,
1090
- threadId,
1091
- sentText: input.message,
1092
- sentMessage: verification.message,
1093
- messagesResult: verification.messagesResult,
1094
- attempts: verification.attempts,
1095
- verify: input.verifySent,
1096
- });
1097
- },
1098
- }),
1099
- nativeTool({
1100
- slug: 'SEND_MESSAGE',
1101
- name: 'Send iMessage text',
1102
- description:
1103
- '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.',
1104
- inputParams: sendMessageInput,
1105
- execute: async (input, context) => {
1106
- const beforeMessages = input.verifySent
1107
- ? await fetchMessages(input.threadId, input, context)
1108
- : undefined;
1109
- const excludeMessageIds = new Set(
1110
- extractPageItems(beforeMessages?.result)
1111
- .map(messageIdOf)
1112
- .filter((value): value is string => Boolean(value))
1113
- );
1114
- const sendResult = await runImessageCli(
1115
- 'send',
1116
- [input.threadId, input.text],
1117
- input,
1118
- context
1119
- );
1120
- const verification = input.verifySent
1121
- ? await pollForSentMessage({
1122
- threadId: input.threadId,
1123
- text: input.text,
1124
- input,
1125
- context,
1126
- timeoutMs: input.verificationTimeoutMs,
1127
- excludeMessageIds,
1128
- })
1129
- : { attempts: 0 };
1130
- return enhanceSendResult({
1131
- commandResult: sendResult,
1132
- threadId: input.threadId,
1133
- sentText: input.text,
1134
- sentMessage: verification.message,
1135
- messagesResult: verification.messagesResult,
1136
- attempts: verification.attempts,
1137
- verify: input.verifySent,
1138
- });
1139
- },
1140
- }),
1141
- commandTool({
1142
- slug: 'REPLY_TO_MESSAGE',
1143
- name: 'Reply to iMessage message',
1144
- description: 'Reply to a specific iMessage with text. Mutates real Messages state.',
1145
- inputParams: baseInput.extend({ threadId, messageId, text }),
1146
- command: 'reply',
1147
- args: input => [input.threadId, input.messageId, input.text],
1148
- }),
1149
- commandTool({
1150
- slug: 'SEND_FILE',
1151
- name: 'Send iMessage file attachment',
1152
- description:
1153
- 'Send a local file attachment to an existing chat/thread. Mutates real Messages state.',
1154
- inputParams: baseInput.extend({ threadId, filePath }),
1155
- command: 'send-file',
1156
- args: input => [input.threadId, absolutePath(input.filePath)],
1157
- }),
1158
- commandTool({
1159
- slug: 'REPLY_WITH_FILE',
1160
- name: 'Reply to iMessage with file attachment',
1161
- description:
1162
- 'Reply to a specific message with a local file attachment. Mutates real Messages state.',
1163
- inputParams: baseInput.extend({ threadId, messageId, filePath }),
1164
- command: 'reply-file',
1165
- args: input => [input.threadId, input.messageId, absolutePath(input.filePath)],
1166
- }),
1167
- commandTool({
1168
- slug: 'EDIT_MESSAGE',
1169
- name: 'Edit sent iMessage',
1170
- description:
1171
- 'Edit a previously sent iMessage. Supported by upstream on macOS Ventura or later.',
1172
- inputParams: baseInput.extend({ threadId, messageId, text }),
1173
- command: 'edit',
1174
- args: input => [input.threadId, input.messageId, input.text],
1175
- }),
1176
- commandTool({
1177
- slug: 'UNDO_SEND',
1178
- name: 'Undo sent iMessage',
1179
- description:
1180
- 'Undo send for a previously sent iMessage. Upstream supports this on macOS Ventura or later within the Messages time limit.',
1181
- inputParams: baseInput.extend({ threadId, messageId }),
1182
- command: 'undo-send',
1183
- args: input => [input.threadId, input.messageId],
1184
- }),
1185
- nativeTool({
1186
- slug: 'REACT_TO_MESSAGE',
1187
- name: 'React to iMessage',
1188
- description:
1189
- '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.',
1190
- inputParams: reactionInput,
1191
- execute: async (input, context) => {
1192
- const effectiveInput = { ...input, useSecondaryInstance: input.useSecondaryInstance };
1193
- if (input.prepareTranscript) {
1194
- await runImessageCli('select-thread', [input.threadId], effectiveInput, context, {
1195
- timeoutMs: input.prepareTimeoutMs,
1196
- });
1197
- }
1198
- return runImessageCli(
1199
- 'react',
1200
- [input.threadId, input.messageId, input.reaction],
1201
- effectiveInput,
1202
- context,
1203
- { timeoutMs: input.reactionTimeoutMs }
1204
- );
1205
- },
1206
- }),
1207
- nativeTool({
1208
- slug: 'UNREACT_FROM_MESSAGE',
1209
- name: 'Remove iMessage reaction',
1210
- description:
1211
- '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.',
1212
- inputParams: reactionInput,
1213
- execute: async (input, context) => {
1214
- const effectiveInput = { ...input, useSecondaryInstance: input.useSecondaryInstance };
1215
- if (input.prepareTranscript) {
1216
- await runImessageCli('select-thread', [input.threadId], effectiveInput, context, {
1217
- timeoutMs: input.prepareTimeoutMs,
1218
- });
1219
- }
1220
- return runImessageCli(
1221
- 'unreact',
1222
- [input.threadId, input.messageId, input.reaction],
1223
- effectiveInput,
1224
- context,
1225
- { timeoutMs: input.reactionTimeoutMs }
1226
- );
1227
- },
1228
- }),
1229
- commandTool({
1230
- slug: 'MARK_READ',
1231
- name: 'Mark iMessage thread read',
1232
- description:
1233
- 'Mark a chat/thread as read by sending a read receipt. Mutates real Messages state.',
1234
- inputParams: baseInput.extend({ threadId }),
1235
- command: 'mark-read',
1236
- args: input => [input.threadId],
1237
- }),
1238
- commandTool({
1239
- slug: 'MARK_UNREAD',
1240
- name: 'Mark iMessage thread unread',
1241
- description: 'Mark a chat/thread as unread. Mutates real Messages state.',
1242
- inputParams: baseInput.extend({ threadId }),
1243
- command: 'mark-unread',
1244
- args: input => [input.threadId],
1245
- }),
1246
- commandTool({
1247
- slug: 'MUTE_THREAD',
1248
- name: 'Mute iMessage thread',
1249
- description: 'Mute a chat/thread indefinitely. Mutates real Messages state.',
1250
- inputParams: baseInput.extend({ threadId }),
1251
- command: 'mute',
1252
- args: input => [input.threadId],
1253
- }),
1254
- commandTool({
1255
- slug: 'UNMUTE_THREAD',
1256
- name: 'Unmute iMessage thread',
1257
- description: 'Unmute a chat/thread. Mutates real Messages state.',
1258
- inputParams: baseInput.extend({ threadId }),
1259
- command: 'unmute',
1260
- args: input => [input.threadId],
1261
- }),
1262
- commandTool({
1263
- slug: 'SEND_TYPING_STATUS',
1264
- name: 'Send iMessage typing status',
1265
- description: 'Send typing on/off status for a chat/thread. Mutates real Messages state.',
1266
- inputParams: baseInput.extend({
1267
- threadId,
1268
- status: z.enum(['on', 'off']).describe('Typing status to send.'),
1269
- }),
1270
- command: 'typing',
1271
- args: input => [input.threadId, input.status],
1272
- }),
1273
- commandTool({
1274
- slug: 'NOTIFY_ANYWAY',
1275
- name: 'Notify anyway for iMessage thread',
1276
- description:
1277
- 'Trigger the Messages "notify anyway" action for a chat/thread. Mutates real Messages state.',
1278
- inputParams: baseInput.extend({ threadId }),
1279
- command: 'notify-anyway',
1280
- args: input => [input.threadId],
1281
- }),
1282
- commandTool({
1283
- slug: 'DELETE_THREAD',
1284
- name: 'Delete iMessage thread',
1285
- description:
1286
- 'Delete a chat/thread from Messages. Requires confirm=true because this mutates real Messages state.',
1287
- inputParams: baseInput.extend({
1288
- threadId,
1289
- confirm: z.literal(true).describe('Must be true to delete the thread.'),
1290
- }),
1291
- command: 'delete-thread',
1292
- args: input => [input.threadId],
1293
- }),
1294
- ],
1295
-};