@openclaw/imessage 2026.8.1-beta.3 → 2026.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/dist/{accounts-D00Njxg2.js → accounts-CCirBEIm.js} +4 -5
  2. package/dist/{actions.runtime-B_xJiBXF.js → actions.runtime-UDLBuS_8.js} +5 -5
  3. package/dist/api.js +6 -5
  4. package/dist/{approval-handler.runtime-BKku8aUf.js → approval-handler.runtime-ZaQQ2c4l.js} +9 -8
  5. package/dist/{approval-reactions-BME5eA6T.js → approval-reactions-B2-_97DN.js} +7 -11
  6. package/dist/{channel-BFQTpvrG.js → channel-B0wzN0uJ.js} +18 -16
  7. package/dist/channel-config-api.js +1 -1
  8. package/dist/channel-plugin-api.js +1 -1
  9. package/dist/{channel.runtime-BjkXwX9_.js → channel.runtime-lJfW7FBd.js} +60 -13
  10. package/dist/{config-schema-DV0KP5nC.js → config-schema-DuGbA8Kp.js} +8 -7
  11. package/dist/contract-api.js +1 -1
  12. package/dist/doctor-contract-api.js +8 -281
  13. package/dist/{group-policy-Ca3c5KES.js → group-policy-fYokgrgz.js} +25 -23
  14. package/dist/media-contract-api.js +1 -1
  15. package/dist/{media-contract-BEgdvYhW.js → media-contract-pns3TSS5.js} +3 -2
  16. package/dist/{message-tool-api-TZiNYA17.js → message-tool-api-CLWaomvw.js} +9 -7
  17. package/dist/message-tool-api.js +1 -1
  18. package/dist/{monitor-Uv5RaRTk.js → monitor-CSTZ-GFU.js} +304 -40
  19. package/dist/{question-reactions-to0i8vxE.js → question-reactions-viP7ZcyG.js} +1 -1
  20. package/dist/{reaction-context-DaNrZqYo.js → reaction-context-BAYI7pz0.js} +2 -2
  21. package/dist/{remote-file-CDuk0joc.js → remote-file-CmdycSRk.js} +9 -8
  22. package/dist/runtime-Cza4CY5T.js +8 -0
  23. package/dist/runtime-api.js +10 -9
  24. package/dist/{sanitize-outbound-DaLmdkbf.js → sanitize-outbound-DKRlFQoD.js} +371 -80
  25. package/dist/{send-Dake4Awx.js → send-DxhFcMfW.js} +146 -24
  26. package/dist/state-contract-DvahEY4X.js +56 -0
  27. package/dist/state-migrations-BhY4RwjU.js +277 -0
  28. package/node_modules/typebox/build/format/date.d.mts +1 -1
  29. package/node_modules/typebox/build/format/date.mjs +1 -1
  30. package/node_modules/typebox/build/format/date_time.d.mts +2 -2
  31. package/node_modules/typebox/build/format/date_time.mjs +3 -3
  32. package/node_modules/typebox/build/format/email.d.mts +1 -1
  33. package/node_modules/typebox/build/format/email.mjs +2 -2
  34. package/node_modules/typebox/build/format/hostname.mjs +2 -10
  35. package/node_modules/typebox/build/format/idn_email.d.mts +1 -1
  36. package/node_modules/typebox/build/format/idn_email.mjs +3 -3
  37. package/node_modules/typebox/build/format/idn_hostname.d.mts +1 -0
  38. package/node_modules/typebox/build/format/idn_hostname.mjs +3 -11
  39. package/node_modules/typebox/build/format/idna/format/bidi.d.mts +3 -0
  40. package/node_modules/typebox/build/format/idna/format/bidi.mjs +98 -0
  41. package/node_modules/typebox/build/format/idna/format/puny.d.mts +3 -0
  42. package/node_modules/typebox/build/format/idna/format/puny.mjs +144 -0
  43. package/node_modules/typebox/build/format/idna/hostname.d.mts +1 -0
  44. package/node_modules/typebox/build/format/idna/hostname.mjs +16 -0
  45. package/node_modules/typebox/build/format/idna/idn-hostname.d.mts +1 -0
  46. package/node_modules/typebox/build/format/idna/idn-hostname.mjs +41 -0
  47. package/node_modules/typebox/build/format/idna/index.d.mts +2 -0
  48. package/node_modules/typebox/build/format/idna/index.mjs +2 -0
  49. package/node_modules/typebox/build/format/idna/label/ascii.d.mts +1 -0
  50. package/node_modules/typebox/build/format/idna/label/ascii.mjs +9 -0
  51. package/node_modules/typebox/build/format/idna/label/puny.d.mts +1 -0
  52. package/node_modules/typebox/build/format/idna/label/puny.mjs +28 -0
  53. package/node_modules/typebox/build/format/idna/label/unicode.d.mts +1 -0
  54. package/node_modules/typebox/build/format/idna/label/unicode.mjs +106 -0
  55. package/node_modules/typebox/build/format/idna/pattern/pattern.d.mts +30 -0
  56. package/node_modules/typebox/build/format/idna/pattern/pattern.mjs +70 -0
  57. package/node_modules/typebox/build/format/ipv4.d.mts +0 -1
  58. package/node_modules/typebox/build/format/ipv4.mjs +2 -32
  59. package/node_modules/typebox/build/format/ipv6.mjs +2 -61
  60. package/node_modules/typebox/build/format/iri.d.mts +2 -2
  61. package/node_modules/typebox/build/format/iri.mjs +26 -8
  62. package/node_modules/typebox/build/format/iri_reference.d.mts +2 -2
  63. package/node_modules/typebox/build/format/iri_reference.mjs +9 -55
  64. package/node_modules/typebox/build/format/regex.d.mts +1 -2
  65. package/node_modules/typebox/build/format/regex.mjs +2 -6
  66. package/node_modules/typebox/build/format/time.d.mts +2 -2
  67. package/node_modules/typebox/build/format/time.mjs +19 -14
  68. package/node_modules/typebox/build/format/uri.d.mts +1 -1
  69. package/node_modules/typebox/build/format/uri.mjs +3 -130
  70. package/node_modules/typebox/build/format/uri_reference.d.mts +1 -1
  71. package/node_modules/typebox/build/format/uri_reference.mjs +2 -3
  72. package/node_modules/typebox/build/format/uri_template.d.mts +2 -3
  73. package/node_modules/typebox/build/format/uri_template.mjs +4 -5
  74. package/node_modules/typebox/build/format/url.d.mts +3 -3
  75. package/node_modules/typebox/build/format/url.mjs +4 -5
  76. package/node_modules/typebox/build/guard/emit.d.mts +3 -1
  77. package/node_modules/typebox/build/guard/emit.mjs +12 -5
  78. package/node_modules/typebox/build/guard/guard.d.mts +8 -2
  79. package/node_modules/typebox/build/guard/guard.mjs +25 -4
  80. package/node_modules/typebox/build/guard/string.d.mts +2 -2
  81. package/node_modules/typebox/build/guard/string.mjs +7 -7
  82. package/node_modules/typebox/build/schema/engine/_context.mjs +3 -3
  83. package/node_modules/typebox/build/schema/engine/_functions.mjs +1 -2
  84. package/node_modules/typebox/build/schema/engine/_regexp.d.mts +2 -0
  85. package/node_modules/typebox/build/schema/engine/_regexp.mjs +4 -0
  86. package/node_modules/typebox/build/schema/engine/_stack.mjs +12 -13
  87. package/node_modules/typebox/build/schema/engine/additionalItems.mjs +17 -7
  88. package/node_modules/typebox/build/schema/engine/additionalProperties.mjs +4 -3
  89. package/node_modules/typebox/build/schema/engine/contains.mjs +18 -6
  90. package/node_modules/typebox/build/schema/engine/enum.mjs +1 -1
  91. package/node_modules/typebox/build/schema/engine/items.mjs +26 -6
  92. package/node_modules/typebox/build/schema/engine/maxContains.mjs +3 -3
  93. package/node_modules/typebox/build/schema/engine/minContains.mjs +14 -4
  94. package/node_modules/typebox/build/schema/engine/not.mjs +4 -2
  95. package/node_modules/typebox/build/schema/engine/oneOf.mjs +7 -6
  96. package/node_modules/typebox/build/schema/engine/pattern.mjs +3 -2
  97. package/node_modules/typebox/build/schema/engine/patternProperties.mjs +4 -3
  98. package/node_modules/typebox/build/schema/engine/ref.mjs +1 -7
  99. package/node_modules/typebox/build/schema/engine/schema.mjs +13 -4
  100. package/node_modules/typebox/build/schema/engine/type.mjs +1 -1
  101. package/node_modules/typebox/build/schema/resolve/resolve.d.mts +4 -1
  102. package/node_modules/typebox/build/schema/resolve/resolve.mjs +202 -1
  103. package/node_modules/typebox/build/schema/static/propertyNames.d.mts +5 -0
  104. package/node_modules/typebox/build/schema/static/propertyNames.mjs +3 -0
  105. package/node_modules/typebox/build/schema/static/schema.d.mts +3 -0
  106. package/node_modules/typebox/build/schema/types/index.d.mts +0 -2
  107. package/node_modules/typebox/build/schema/types/index.mjs +0 -2
  108. package/node_modules/typebox/build/system/memory/clone.mjs +14 -11
  109. package/node_modules/typebox/build/system/memory/discard.mjs +6 -5
  110. package/node_modules/typebox/build/system/settings/settings.d.mts +9 -0
  111. package/node_modules/typebox/build/system/settings/settings.mjs +2 -0
  112. package/node_modules/typebox/build/type/engine/call/distribute_arguments.d.mts +6 -1
  113. package/node_modules/typebox/build/type/engine/call/distribute_arguments.mjs +16 -3
  114. package/node_modules/typebox/build/type/engine/call/instantiate.mjs +34 -4
  115. package/node_modules/typebox/build/type/engine/evaluate/broaden.d.mts +5 -5
  116. package/node_modules/typebox/build/type/engine/evaluate/broaden.mjs +20 -26
  117. package/node_modules/typebox/build/type/engine/evaluate/compare.d.mts +6 -10
  118. package/node_modules/typebox/build/type/engine/evaluate/compare.mjs +9 -13
  119. package/node_modules/typebox/build/type/engine/evaluate/composite.d.mts +7 -4
  120. package/node_modules/typebox/build/type/engine/evaluate/composite.mjs +12 -19
  121. package/node_modules/typebox/build/type/engine/evaluate/distribute.d.mts +4 -20
  122. package/node_modules/typebox/build/type/engine/evaluate/distribute.mjs +8 -20
  123. package/node_modules/typebox/build/type/engine/evaluate/evaluate.d.mts +4 -4
  124. package/node_modules/typebox/build/type/engine/evaluate/evaluate.mjs +11 -8
  125. package/node_modules/typebox/build/type/engine/evaluate/flatten.d.mts +1 -1
  126. package/node_modules/typebox/build/type/engine/evaluate/flatten.mjs +3 -4
  127. package/node_modules/typebox/build/type/engine/evaluate/narrow.d.mts +17 -2
  128. package/node_modules/typebox/build/type/engine/evaluate/narrow.mjs +26 -6
  129. package/node_modules/typebox/build/type/engine/exclude/operation.mjs +3 -4
  130. package/node_modules/typebox/build/type/engine/extract/operation.d.mts +1 -1
  131. package/node_modules/typebox/build/type/engine/extract/operation.mjs +3 -4
  132. package/node_modules/typebox/build/type/engine/priority/priority.d.mts +2 -2
  133. package/node_modules/typebox/build/type/engine/priority/priority.mjs +3 -4
  134. package/node_modules/typebox/build/type/script/mapping.d.mts +32 -29
  135. package/node_modules/typebox/build/type/script/mapping.mjs +18 -25
  136. package/node_modules/typebox/build/type/script/parser.d.mts +19 -25
  137. package/node_modules/typebox/build/type/script/parser.mjs +27 -23
  138. package/node_modules/typebox/build/value/errors/errors.d.mts +2 -2
  139. package/node_modules/typebox/build/value/errors/errors.mjs +1 -1
  140. package/node_modules/typebox/package.json +27 -27
  141. package/node_modules/typebox/readme.md +79 -82
  142. package/openclaw.plugin.json +0 -6
  143. package/package.json +5 -5
  144. package/dist/catchup-Dh-Rv4Ur.js +0 -294
  145. package/dist/monitor-reply-cache-BdeUQaHO.js +0 -353
  146. package/dist/persisted-echo-cache-DGxy-J4t.js +0 -143
  147. package/node_modules/typebox/build/format/_idna.d.mts +0 -2
  148. package/node_modules/typebox/build/format/_idna.mjs +0 -246
  149. package/node_modules/typebox/build/format/_puny.d.mts +0 -1
  150. package/node_modules/typebox/build/format/_puny.mjs +0 -77
  151. package/node_modules/typebox/build/schema/resolve/ref.d.mts +0 -3
  152. package/node_modules/typebox/build/schema/resolve/ref.mjs +0 -146
  153. package/node_modules/typebox/build/schema/types/contentEncoding.d.mts +0 -9
  154. package/node_modules/typebox/build/schema/types/contentEncoding.mjs +0 -13
  155. package/node_modules/typebox/build/schema/types/contentMediaType.d.mts +0 -9
  156. package/node_modules/typebox/build/schema/types/contentMediaType.mjs +0 -13
@@ -1,15 +1,352 @@
1
- import { u as expandIMessageUserPath } from "./accounts-D00Njxg2.js";
2
- import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
1
+ import { u as expandIMessageUserPath } from "./accounts-CCirBEIm.js";
2
+ import { t as getIMessageRuntime } from "./runtime-Cza4CY5T.js";
3
+ import { a as IMESSAGE_REPLY_CACHE_NAMESPACE, f as resolveIMessageReplyCacheEntryKey, i as IMESSAGE_REPLY_CACHE_MAX_ENTRIES, n as IMESSAGE_REPLY_CACHE_COUNTER_KEY, o as IMESSAGE_REPLY_CACHE_TTL_MS, r as IMESSAGE_REPLY_CACHE_COUNTER_NAMESPACE } from "./state-contract-DvahEY4X.js";
4
+ import { normalizeE164 } from "openclaw/plugin-sdk/account-resolution";
5
+ import { normalizeLowercaseStringOrEmpty, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
6
+ import { logVerbose } from "openclaw/plugin-sdk/runtime-env";
3
7
  import { resolveUserPath } from "openclaw/plugin-sdk/text-utility-runtime";
4
8
  import { spawn } from "node:child_process";
5
9
  import { StringDecoder } from "node:string_decoder";
6
10
  import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
7
11
  import { FormatCapabilityProfile, findCodeRegions, isInsideCode, markdownToIR, renderMarkdownWithAttributedRanges, sanitizeAssistantVisibleText, stripMarkdown, tokenizeHtmlTags } from "openclaw/plugin-sdk/text-chunking";
12
+ //#region extensions/imessage/src/chat-context.ts
13
+ const EMAIL_HANDLE_PATTERN = /^[^\s@]+@[^\s@]+$/u;
14
+ function parseDirectChatIdentity(raw) {
15
+ const trimmed = raw.trim();
16
+ const parts = trimmed.split(";");
17
+ if (parts.length === 3 && parts[1] === "-" && parts[2]) {
18
+ const service = parts[0]?.toLowerCase();
19
+ if (service === "imessage" || service === "sms" || service === "any") {
20
+ const identifier = parts[2];
21
+ return {
22
+ service,
23
+ identifier: EMAIL_HANDLE_PATTERN.test(identifier) ? identifier.toLowerCase() : identifier
24
+ };
25
+ }
26
+ }
27
+ if (parts.length !== 1) return;
28
+ if (trimmed.startsWith("+") || EMAIL_HANDLE_PATTERN.test(trimmed)) return { identifier: trimmed.toLowerCase() };
29
+ }
30
+ function resolveIMessageDirectChatService(configuredService, chatGuid) {
31
+ if (configuredService === "imessage" || configuredService === "sms") return configuredService;
32
+ const observedService = chatGuid ? parseDirectChatIdentity(chatGuid)?.service : void 0;
33
+ return observedService === "imessage" || observedService === "sms" ? observedService : void 0;
34
+ }
35
+ function isIMessageEmailChatIdentifier(raw) {
36
+ const identity = parseDirectChatIdentity(raw);
37
+ return Boolean(identity && EMAIL_HANDLE_PATTERN.test(identity.identifier));
38
+ }
39
+ /**
40
+ * Strip the `iMessage;-;` / `SMS;-;` / `any;-;` service prefix that Messages
41
+ * uses for direct chats. Different layers report direct DMs in different
42
+ * forms, so raw comparison would falsely treat one DM as different chats.
43
+ */
44
+ function normalizeDirectChatIdentifier(raw) {
45
+ const trimmed = raw.trim();
46
+ return parseDirectChatIdentity(trimmed)?.identifier ?? trimmed;
47
+ }
48
+ function chatContextFromIMessageTarget(target, effectiveService) {
49
+ if (target.kind === "chat_id") return { chatId: target.chatId };
50
+ if (target.kind === "chat_guid") return { chatGuid: target.chatGuid };
51
+ if (target.kind === "chat_identifier") return { chatIdentifier: target.chatIdentifier };
52
+ const trimmedHandle = target.to.trim();
53
+ const canonicalHandle = trimmedHandle.startsWith("+") ? normalizeE164(trimmedHandle) : /^[^\s@]+@[^\s@]+$/u.test(trimmedHandle) ? trimmedHandle.toLowerCase() : void 0;
54
+ if (!canonicalHandle) return {};
55
+ const service = target.service === "auto" ? effectiveService : target.service;
56
+ if (service !== "imessage" && service !== "sms") return {};
57
+ return { chatIdentifier: `${service === "sms" ? "SMS" : "iMessage"};-;${canonicalHandle}` };
58
+ }
59
+ function compareOptional(left, right) {
60
+ return left === void 0 || right === void 0 ? void 0 : left === right;
61
+ }
62
+ function compareChatSelector(cachedRaw, currentRaw, crossKind = false) {
63
+ const cached = normalizeOptionalString(cachedRaw);
64
+ const current = normalizeOptionalString(currentRaw);
65
+ if (!cached || !current) return;
66
+ if (cached === current) return true;
67
+ const cachedDirect = parseDirectChatIdentity(cached);
68
+ const currentDirect = parseDirectChatIdentity(current);
69
+ if (!cachedDirect || !currentDirect) return crossKind ? void 0 : false;
70
+ if (cachedDirect.identifier !== currentDirect.identifier) return false;
71
+ if (cachedDirect.service === "any") return true;
72
+ if (!cachedDirect.service || !currentDirect.service) return;
73
+ return cachedDirect.service === currentDirect.service;
74
+ }
75
+ function resolveIMessageChatMatch(cached, current) {
76
+ const cachedChatGuid = normalizeOptionalString(cached.chatGuid);
77
+ const currentChatGuid = normalizeOptionalString(current.chatGuid);
78
+ const cachedChatIdentifier = normalizeOptionalString(cached.chatIdentifier);
79
+ const currentChatIdentifier = normalizeOptionalString(current.chatIdentifier);
80
+ const comparisons = [
81
+ compareChatSelector(cachedChatGuid, currentChatGuid),
82
+ compareChatSelector(cachedChatIdentifier, currentChatIdentifier),
83
+ compareOptional(cached.chatId, current.chatId),
84
+ compareChatSelector(cachedChatGuid, currentChatIdentifier, true),
85
+ compareChatSelector(cachedChatIdentifier, currentChatGuid, true)
86
+ ].filter((comparison) => comparison !== void 0);
87
+ if (comparisons.length === 0) return "unknown";
88
+ return comparisons.every(Boolean) ? "match" : "mismatch";
89
+ }
90
+ function isPositiveIMessageChatMatch(cached, current) {
91
+ return resolveIMessageChatMatch(cached, current) === "match";
92
+ }
93
+ //#endregion
8
94
  //#region extensions/imessage/src/constants.ts
9
95
  /** Default timeout for iMessage probe/RPC operations (10 seconds). */
10
96
  const DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS = 1e4;
11
97
  const DEFAULT_IMESSAGE_SEND_TIMEOUT_MS = 18e4;
12
98
  //#endregion
99
+ //#region extensions/imessage/src/monitor-reply-cache.ts
100
+ /** Recency window for the "react to the latest message" fallback. */
101
+ const LATEST_FALLBACK_MS = 6e5;
102
+ let persistenceFailureLogged = false;
103
+ function reportPersistenceFailure(scope, err) {
104
+ if (persistenceFailureLogged) return;
105
+ persistenceFailureLogged = true;
106
+ logVerbose(`imessage reply-cache: ${scope} disabled after first failure: ${String(err)}`);
107
+ }
108
+ const imessageReplyCacheByMessageId = /* @__PURE__ */ new Map();
109
+ const imessageShortIdToUuid = /* @__PURE__ */ new Map();
110
+ const imessageUuidToShortId = /* @__PURE__ */ new Map();
111
+ let imessageShortIdCounter = 0;
112
+ function openReplyCacheStore() {
113
+ return getIMessageRuntime().state.openSyncKeyedStore({
114
+ namespace: IMESSAGE_REPLY_CACHE_NAMESPACE,
115
+ maxEntries: IMESSAGE_REPLY_CACHE_MAX_ENTRIES
116
+ });
117
+ }
118
+ function openReplyCacheCounterStore() {
119
+ return getIMessageRuntime().state.openSyncKeyedStore({
120
+ namespace: IMESSAGE_REPLY_CACHE_COUNTER_NAMESPACE,
121
+ maxEntries: 1
122
+ });
123
+ }
124
+ function remainingTtlMs(timestamp) {
125
+ const remaining = IMESSAGE_REPLY_CACHE_TTL_MS - Math.max(0, Date.now() - timestamp);
126
+ return remaining > 0 ? remaining : void 0;
127
+ }
128
+ let hydrated = false;
129
+ function hydrateFromStoreOnce() {
130
+ if (hydrated) return;
131
+ hydrated = true;
132
+ const cutoff = Date.now() - IMESSAGE_REPLY_CACHE_TTL_MS;
133
+ let entries;
134
+ try {
135
+ const counter = openReplyCacheCounterStore().lookup(IMESSAGE_REPLY_CACHE_COUNTER_KEY);
136
+ if (counter && Number.isSafeInteger(counter.counter) && counter.counter > 0) imessageShortIdCounter = Math.max(imessageShortIdCounter, counter.counter);
137
+ entries = openReplyCacheStore().entries().map(({ value }) => value).filter((entry) => entry.timestamp >= cutoff).toSorted((a, b) => a.timestamp - b.timestamp).slice(-IMESSAGE_REPLY_CACHE_MAX_ENTRIES);
138
+ for (const entry of entries) {
139
+ const numeric = Number.parseInt(entry.shortId, 10);
140
+ if (Number.isFinite(numeric) && numeric > imessageShortIdCounter) imessageShortIdCounter = numeric;
141
+ }
142
+ } catch (err) {
143
+ reportPersistenceFailure("read", err);
144
+ return;
145
+ }
146
+ if (entries.length === 0) return;
147
+ for (const entry of entries) {
148
+ imessageReplyCacheByMessageId.set(entry.messageId, entry);
149
+ imessageShortIdToUuid.set(entry.shortId, entry.messageId);
150
+ imessageUuidToShortId.set(entry.messageId, entry.shortId);
151
+ }
152
+ }
153
+ function persistReplyCacheEntry(entry) {
154
+ const ttlMs = remainingTtlMs(entry.timestamp);
155
+ if (!ttlMs) return;
156
+ try {
157
+ openReplyCacheStore().register(resolveIMessageReplyCacheEntryKey(entry.messageId), entry, { ttlMs });
158
+ } catch (err) {
159
+ reportPersistenceFailure("write", err);
160
+ }
161
+ }
162
+ function deleteReplyCacheEntry(messageId) {
163
+ try {
164
+ openReplyCacheStore().delete(resolveIMessageReplyCacheEntryKey(messageId));
165
+ } catch (err) {
166
+ reportPersistenceFailure("delete", err);
167
+ }
168
+ }
169
+ function persistReplyCacheCounter() {
170
+ try {
171
+ openReplyCacheCounterStore().register(IMESSAGE_REPLY_CACHE_COUNTER_KEY, { counter: imessageShortIdCounter });
172
+ } catch (err) {
173
+ reportPersistenceFailure("counter", err);
174
+ }
175
+ }
176
+ function buildReplyCacheEntry(entry, messageId, shortId) {
177
+ return {
178
+ accountId: entry.accountId,
179
+ messageId,
180
+ shortId,
181
+ timestamp: entry.timestamp,
182
+ ...typeof entry.chatGuid === "string" ? { chatGuid: entry.chatGuid } : {},
183
+ ...typeof entry.chatIdentifier === "string" ? { chatIdentifier: entry.chatIdentifier } : {},
184
+ ...typeof entry.chatId === "number" ? { chatId: entry.chatId } : {},
185
+ ...typeof entry.isFromMe === "boolean" ? { isFromMe: entry.isFromMe } : {}
186
+ };
187
+ }
188
+ function generateShortId() {
189
+ imessageShortIdCounter += 1;
190
+ persistReplyCacheCounter();
191
+ return String(imessageShortIdCounter);
192
+ }
193
+ function rememberIMessageReplyCache(entry) {
194
+ hydrateFromStoreOnce();
195
+ const messageId = entry.messageId.trim();
196
+ if (!messageId) return {
197
+ ...entry,
198
+ shortId: ""
199
+ };
200
+ let shortId = imessageUuidToShortId.get(messageId);
201
+ if (!shortId) {
202
+ shortId = generateShortId();
203
+ imessageShortIdToUuid.set(shortId, messageId);
204
+ imessageUuidToShortId.set(messageId, shortId);
205
+ }
206
+ const fullEntry = buildReplyCacheEntry(entry, messageId, shortId);
207
+ imessageReplyCacheByMessageId.delete(messageId);
208
+ imessageReplyCacheByMessageId.set(messageId, fullEntry);
209
+ const cutoff = Date.now() - IMESSAGE_REPLY_CACHE_TTL_MS;
210
+ let evicted = false;
211
+ const deletedMessageIds = [];
212
+ for (const [key, value] of imessageReplyCacheByMessageId) {
213
+ if (value.timestamp >= cutoff) break;
214
+ imessageReplyCacheByMessageId.delete(key);
215
+ deletedMessageIds.push(key);
216
+ if (value.shortId) {
217
+ imessageShortIdToUuid.delete(value.shortId);
218
+ imessageUuidToShortId.delete(key);
219
+ }
220
+ evicted = true;
221
+ }
222
+ while (imessageReplyCacheByMessageId.size > IMESSAGE_REPLY_CACHE_MAX_ENTRIES) {
223
+ const oldest = imessageReplyCacheByMessageId.keys().next().value;
224
+ if (!oldest) break;
225
+ const oldEntry = imessageReplyCacheByMessageId.get(oldest);
226
+ imessageReplyCacheByMessageId.delete(oldest);
227
+ deletedMessageIds.push(oldest);
228
+ if (oldEntry?.shortId) {
229
+ imessageShortIdToUuid.delete(oldEntry.shortId);
230
+ imessageUuidToShortId.delete(oldest);
231
+ }
232
+ evicted = true;
233
+ }
234
+ if (evicted) for (const messageIdToDelete of deletedMessageIds) deleteReplyCacheEntry(messageIdToDelete);
235
+ persistReplyCacheEntry(fullEntry);
236
+ return fullEntry;
237
+ }
238
+ function hasChatScope(ctx) {
239
+ if (!ctx) return false;
240
+ return Boolean(normalizeOptionalString(ctx.chatGuid) || normalizeOptionalString(ctx.chatIdentifier) || typeof ctx.chatId === "number");
241
+ }
242
+ function isCrossChatMismatch(cached, ctx) {
243
+ return resolveIMessageChatMatch(cached, ctx) === "mismatch";
244
+ }
245
+ function describeChatForError(values) {
246
+ const parts = [];
247
+ if (normalizeOptionalString(values.chatGuid)) parts.push("chatGuid=<redacted>");
248
+ if (normalizeOptionalString(values.chatIdentifier)) parts.push("chatIdentifier=<redacted>");
249
+ if (typeof values.chatId === "number") parts.push("chatId=<redacted>");
250
+ return parts.length === 0 ? "<unknown chat>" : parts.join(", ");
251
+ }
252
+ function describeMessageIdForError(inputId, inputKind) {
253
+ if (inputKind === "short") return `<short:${inputId.length}-digit>`;
254
+ return `<uuid:${inputId.slice(0, 8)}...>`;
255
+ }
256
+ function buildCrossChatError(inputId, inputKind, cached, ctx) {
257
+ const remediation = inputKind === "short" ? "Use a message ID from the current chat target; MessageSidFull from another chat is rejected." : "Retry with the correct chat target.";
258
+ return /* @__PURE__ */ new Error(`iMessage message id ${describeMessageIdForError(inputId, inputKind)} belongs to a different chat (${describeChatForError(cached)}) than the current call target (${describeChatForError(ctx)}). ${remediation}`);
259
+ }
260
+ function resolveIMessageMessageId(shortOrUuid, opts) {
261
+ const trimmed = shortOrUuid.trim();
262
+ if (!trimmed) return trimmed;
263
+ hydrateFromStoreOnce();
264
+ if (/^\d+$/.test(trimmed)) {
265
+ const uuid = imessageShortIdToUuid.get(trimmed);
266
+ if (uuid) {
267
+ const cached = imessageReplyCacheByMessageId.get(uuid);
268
+ if (opts?.chatContext && hasChatScope(opts.chatContext)) {
269
+ if (cached && isCrossChatMismatch(cached, opts.chatContext)) throw buildCrossChatError(trimmed, "short", cached, opts.chatContext);
270
+ }
271
+ if (opts?.requireFromMe && cached?.isFromMe !== true) throw buildFromMeError(trimmed, "short");
272
+ return uuid;
273
+ }
274
+ if (opts?.requireKnownShortId && !hasChatScope(opts.chatContext)) throw new Error(`iMessage short message id ${describeMessageIdForError(trimmed, "short")} requires a chat scope (chatGuid / chatIdentifier / chatId or a target).`);
275
+ if (opts?.requireKnownShortId) throw new Error(`iMessage short message id ${describeMessageIdForError(trimmed, "short")} is no longer available. Use MessageSidFull.`);
276
+ return trimmed;
277
+ }
278
+ const cached = imessageReplyCacheByMessageId.get(trimmed);
279
+ if (opts?.chatContext) {
280
+ if (cached && isCrossChatMismatch(cached, opts.chatContext)) throw buildCrossChatError(trimmed, "uuid", cached, opts.chatContext);
281
+ }
282
+ if (opts?.requireFromMe && cached?.isFromMe !== true) throw buildFromMeError(trimmed, "uuid");
283
+ return trimmed;
284
+ }
285
+ function isKnownFromMeIMessageMessageId(messageId, ctx) {
286
+ const trimmed = normalizeOptionalString(messageId);
287
+ if (!trimmed || !ctx.accountId || !hasChatScope(ctx)) return false;
288
+ hydrateFromStoreOnce();
289
+ const cached = imessageReplyCacheByMessageId.get(trimmed);
290
+ if (!cached || cached.isFromMe !== true || cached.accountId !== ctx.accountId) return false;
291
+ return isPositiveIMessageChatMatch(cached, ctx);
292
+ }
293
+ function buildFromMeError(inputId, inputKind) {
294
+ return /* @__PURE__ */ new Error(`iMessage message id ${describeMessageIdForError(inputId, inputKind)} is not one this agent sent. edit and unsend can only target messages the gateway delivered itself; messages received from other participants cannot be modified.`);
295
+ }
296
+ /**
297
+ * Return the most recent cached entry whose chat scope matches the supplied
298
+ * context. Used as a fallback when an agent calls a per-message action (e.g.
299
+ * `react`) without specifying a `messageId` — the natural intent is "react
300
+ * to the message I just received in this chat."
301
+ *
302
+ * Strict semantics for safety:
303
+ * - Caller must supply a chat scope. We refuse to "guess" the active chat.
304
+ * - Cached entry must positively match on at least one identifier kind
305
+ * (chatGuid, chatIdentifier, chatId, or normalized direct-DM fingerprint).
306
+ * We do NOT fall through on "no overlapping identifier" — that's how a
307
+ * cached entry from a foreign chat could be returned when the caller's
308
+ * context didn't share any identifier kind with the cache.
309
+ * - Caller must supply an accountId; we never cross account boundaries.
310
+ * - We only consider entries newer than `LATEST_FALLBACK_MS`. The intent
311
+ * of "react to the latest" is "the message I just received," not
312
+ * "anything in this chat from any time."
313
+ */
314
+ function findLatestIMessageEntryForChat(ctx) {
315
+ if (!hasChatScope(ctx)) return;
316
+ if (!ctx.accountId) return;
317
+ const cutoff = Date.now() - LATEST_FALLBACK_MS;
318
+ let best;
319
+ for (const entry of imessageReplyCacheByMessageId.values()) {
320
+ if (entry.accountId !== ctx.accountId) continue;
321
+ if (entry.timestamp < cutoff) continue;
322
+ if (!isPositiveIMessageChatMatch(entry, ctx)) continue;
323
+ if (!best || entry.timestamp > best.timestamp) best = entry;
324
+ }
325
+ return best;
326
+ }
327
+ function resolveIMessageCachedResourceBinding(messageId, ctx) {
328
+ hydrateFromStoreOnce();
329
+ const entry = imessageReplyCacheByMessageId.get(messageId.trim());
330
+ if (!entry) return "unknown";
331
+ if (Date.now() - entry.timestamp > 216e5) return "unknown";
332
+ if (entry.accountId !== ctx.accountId) return "mismatch";
333
+ const chatMatch = resolveIMessageChatMatch(entry, ctx);
334
+ if (chatMatch !== "match") return chatMatch;
335
+ return "match";
336
+ }
337
+ function isIMessageCurrentMessageInChat(params) {
338
+ if (!params.accountId || !hasChatScope(params.chatContext)) return false;
339
+ const currentMessageId = normalizeOptionalString(String(params.currentMessageId));
340
+ if (!currentMessageId) return false;
341
+ hydrateFromStoreOnce();
342
+ const fullMessageId = /^\d+$/.test(currentMessageId) ? imessageShortIdToUuid.get(currentMessageId) : currentMessageId;
343
+ if (!fullMessageId) return false;
344
+ return resolveIMessageCachedResourceBinding(fullMessageId, {
345
+ ...params.chatContext,
346
+ accountId: params.accountId
347
+ }) === "match";
348
+ }
349
+ //#endregion
13
350
  //#region extensions/imessage/src/client.ts
14
351
  var IMessageRpcRequestError = class extends Error {
15
352
  constructor(message, code, data) {
@@ -329,107 +666,61 @@ function codeDelimiter(content) {
329
666
  const longestRun = Math.max(0, ...[...content.matchAll(/`+/gu)].map((match) => match[0].length));
330
667
  return "`".repeat(longestRun + 1);
331
668
  }
332
- function protectDunderIdentifiers(input) {
333
- const protections = [];
334
- let markdown = "";
335
- let cursor = 0;
336
- for (const match of input.matchAll(/__[\p{L}_][\p{L}\p{N}_]*__/gu)) {
337
- const identifier = match[0];
338
- const start = match.index ?? 0;
339
- const end = start + identifier.length;
340
- const before = input[start - 1];
341
- const beforeBefore = input[start - 2];
342
- const after = input[end];
343
- const member = before === ".";
344
- const call = after === "(";
345
- const functionArgument = before === "(" && /[\p{L}\p{N}_]/u.test(beforeBefore ?? "");
346
- if (!member && !call && !functionArgument && !(after === "[")) continue;
347
- let token = `OCdunder${protections.length}token`;
348
- while (input.includes(token)) token += "x";
349
- markdown += input.slice(cursor, start) + token;
350
- protections.push({
351
- token,
352
- identifier
353
- });
354
- cursor = end;
355
- }
356
- return {
357
- markdown: markdown + input.slice(cursor),
358
- protections
359
- };
360
- }
361
- function applyTextEdits(text, edits) {
362
- const ordered = edits.toSorted((left, right) => left.start - right.start);
669
+ function restoreCodeMarkers(text, ranges, codeRanges) {
363
670
  let rendered = "";
364
671
  let cursor = 0;
365
- for (const edit of ordered) {
366
- rendered += text.slice(cursor, edit.start) + edit.text;
367
- cursor = edit.end;
368
- }
369
- rendered += text.slice(cursor);
370
- return {
371
- text: rendered,
372
- mapOffset: (offset) => offset + ordered.reduce((delta, edit) => delta + (edit.end <= offset ? edit.text.length - edit.end + edit.start : 0), 0)
373
- };
374
- }
375
- function restoreDunderIdentifiers(text, ranges, codeRanges, protections) {
376
- const edited = applyTextEdits(text, protections.flatMap((protection) => {
377
- const start = text.indexOf(protection.token);
378
- return start === -1 ? [] : [{
379
- start,
380
- end: start + protection.token.length,
381
- text: protection.identifier
382
- }];
383
- }));
384
- const mapRange = (range) => ({
385
- ...range,
386
- start: edited.mapOffset(range.start),
387
- length: edited.mapOffset(range.start + range.length) - edited.mapOffset(range.start)
388
- });
389
- return {
390
- text: edited.text,
391
- ranges: ranges.map(mapRange),
392
- codeRanges: codeRanges.map(mapRange)
393
- };
394
- }
395
- function restoreCodeMarkers(text, ranges, codeRanges) {
396
- const edited = applyTextEdits(text, codeRanges.map((range) => {
672
+ const edits = codeRanges.map((range) => {
397
673
  const end = range.start + range.length;
398
674
  const content = text.slice(range.start, end);
399
675
  const marker = codeDelimiter(content);
400
676
  const padding = content.startsWith("`") || content.endsWith("`") ? " " : "";
677
+ rendered += text.slice(cursor, range.start) + `${marker}${padding}${content}${padding}${marker}`;
678
+ cursor = end;
401
679
  return {
402
- start: range.start,
403
680
  end,
404
- text: `${marker}${padding}${content}${padding}${marker}`
681
+ shift: rendered.length - end
405
682
  };
406
- }));
683
+ });
684
+ rendered += text.slice(cursor);
685
+ const mapOffset = (offset) => {
686
+ let low = 0;
687
+ let high = edits.length;
688
+ while (low < high) {
689
+ const middle = low + Math.floor((high - low) / 2);
690
+ const edit = edits[middle];
691
+ if (edit && edit.end <= offset) low = middle + 1;
692
+ else high = middle;
693
+ }
694
+ return offset + (edits[low - 1]?.shift ?? 0);
695
+ };
407
696
  return {
408
- text: edited.text,
409
- ranges: ranges.map((range) => ({
410
- ...range,
411
- start: edited.mapOffset(range.start),
412
- length: edited.mapOffset(range.start + range.length) - edited.mapOffset(range.start)
413
- }))
697
+ text: rendered,
698
+ ranges: ranges.map((range) => {
699
+ const start = mapOffset(range.start);
700
+ return {
701
+ ...range,
702
+ start,
703
+ length: mapOffset(range.start + range.length) - start
704
+ };
705
+ })
414
706
  };
415
707
  }
416
708
  function extractMarkdownFormatRuns(input) {
417
- const protectedDunders = protectDunderIdentifiers(input);
418
- const ir = markdownToIR(protectedDunders.markdown, {
709
+ const ir = markdownToIR(input, {
419
710
  autolink: false,
420
711
  enableHtmlUnderline: true,
421
712
  headingStyle: "rich",
422
713
  linkify: false,
714
+ preserveDunderIdentifiers: true,
423
715
  preserveSourceBlockSpacing: true
424
716
  });
425
717
  const rendered = renderMarkdownWithAttributedRanges(ir, { styleMap: IMESSAGE_STYLE_MAP }, IMESSAGE_FORMAT_PROFILE);
426
718
  const code = renderMarkdownWithAttributedRanges(ir, { styleMap: { code: "code" } }, IMESSAGE_CODE_PROFILE);
427
- const dunders = restoreDunderIdentifiers(rendered.text, rendered.ranges.map(({ start, length, style }) => ({
719
+ return restoreCodeMarkers(rendered.text, rendered.ranges.map(({ start, length, style }) => ({
428
720
  start,
429
721
  length,
430
722
  styles: [style]
431
- })), code.ranges, protectedDunders.protections);
432
- return restoreCodeMarkers(dunders.text, dunders.ranges, dunders.codeRanges);
723
+ })), code.ranges);
433
724
  }
434
725
  //#endregion
435
726
  //#region extensions/imessage/src/monitor/sanitize-outbound.ts
@@ -893,4 +1184,4 @@ function sanitizeOutboundText(text) {
893
1184
  return cleaned;
894
1185
  }
895
1186
  //#endregion
896
- export { IMessageRpcRequestError as a, DEFAULT_IMESSAGE_SEND_TIMEOUT_MS as c, extractMarkdownFormatRuns as i, sanitizeIMessageFinalOutboundText as n, createIMessageRpcClient as o, sanitizeOutboundText as r, DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS as s, protectIMessageFencedRoleMarkers as t };
1187
+ export { normalizeDirectChatIdentifier as _, IMessageRpcRequestError as a, isIMessageCurrentMessageInChat as c, resolveIMessageCachedResourceBinding as d, resolveIMessageMessageId as f, isIMessageEmailChatIdentifier as g, chatContextFromIMessageTarget as h, extractMarkdownFormatRuns as i, isKnownFromMeIMessageMessageId as l, DEFAULT_IMESSAGE_SEND_TIMEOUT_MS as m, sanitizeIMessageFinalOutboundText as n, createIMessageRpcClient as o, DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS as p, sanitizeOutboundText as r, findLatestIMessageEntryForChat as s, protectIMessageFencedRoleMarkers as t, rememberIMessageReplyCache as u, resolveIMessageDirectChatService as v };