@stage-labs/metro 0.1.0-beta.2 → 0.1.0-beta.21

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 (225) hide show
  1. package/dist/api.js +103 -0
  2. package/dist/cli.js +134 -565
  3. package/dist/control.js +102 -0
  4. package/dist/prompt.js +10 -0
  5. package/dist/runtime.js +94 -0
  6. package/dist/store.js +70 -0
  7. package/dist/update.js +33 -0
  8. package/dist/version.js +97 -0
  9. package/package.json +34 -22
  10. package/runtime/node_modules/@metro-labs/discord/package.json +28 -0
  11. package/runtime/node_modules/@metro-labs/discord/src/accounts.ts +119 -0
  12. package/runtime/node_modules/@metro-labs/discord/src/actions.ts +388 -0
  13. package/runtime/node_modules/@metro-labs/discord/src/api-base.ts +1 -0
  14. package/runtime/node_modules/@metro-labs/discord/src/attachments.ts +29 -0
  15. package/runtime/node_modules/@metro-labs/discord/src/format.ts +210 -0
  16. package/runtime/node_modules/@metro-labs/discord/src/group-actions.ts +50 -0
  17. package/runtime/node_modules/@metro-labs/discord/src/group.ts +115 -0
  18. package/runtime/node_modules/@metro-labs/discord/src/index.ts +127 -0
  19. package/runtime/node_modules/@metro-labs/discord/src/members.ts +215 -0
  20. package/runtime/node_modules/@metro-labs/discord/src/send-files.ts +43 -0
  21. package/runtime/node_modules/@metro-labs/discord/src/station.ts +19 -0
  22. package/runtime/node_modules/@metro-labs/discord/src/verify.ts +82 -0
  23. package/runtime/node_modules/@metro-labs/discord/src/voice-speak.ts +195 -0
  24. package/runtime/node_modules/@metro-labs/discord/src/voice-transcribe.ts +292 -0
  25. package/runtime/node_modules/@metro-labs/discord/src/voice.ts +197 -0
  26. package/runtime/node_modules/@metro-labs/discord/src/wire.ts +5 -0
  27. package/runtime/node_modules/@metro-labs/mcp/package.json +66 -0
  28. package/runtime/node_modules/@metro-labs/mcp/src/channels/dedupe.ts +24 -0
  29. package/runtime/node_modules/@metro-labs/mcp/src/channels/inbound.ts +367 -0
  30. package/runtime/node_modules/@metro-labs/mcp/src/channels/media-note.ts +85 -0
  31. package/runtime/node_modules/@metro-labs/mcp/src/channels/pending.ts +75 -0
  32. package/runtime/node_modules/@metro-labs/mcp/src/channels/relay.ts +129 -0
  33. package/runtime/node_modules/@metro-labs/mcp/src/channels/webhook-note.ts +51 -0
  34. package/runtime/node_modules/@metro-labs/mcp/src/daemon/account-api.ts +311 -0
  35. package/runtime/node_modules/@metro-labs/mcp/src/daemon/agent-api.ts +335 -0
  36. package/runtime/node_modules/@metro-labs/mcp/src/daemon/api-error.ts +8 -0
  37. package/runtime/node_modules/@metro-labs/mcp/src/daemon/api-http.ts +129 -0
  38. package/runtime/node_modules/@metro-labs/mcp/src/daemon/attach-grant.ts +99 -0
  39. package/runtime/node_modules/@metro-labs/mcp/src/daemon/attach-owner.ts +32 -0
  40. package/runtime/node_modules/@metro-labs/mcp/src/daemon/attach-serve.ts +124 -0
  41. package/runtime/node_modules/@metro-labs/mcp/src/daemon/attach-session.ts +278 -0
  42. package/runtime/node_modules/@metro-labs/mcp/src/daemon/boot.ts +322 -0
  43. package/runtime/node_modules/@metro-labs/mcp/src/daemon/cli-pair-api.ts +111 -0
  44. package/runtime/node_modules/@metro-labs/mcp/src/daemon/cli-pair.ts +20 -0
  45. package/runtime/node_modules/@metro-labs/mcp/src/daemon/collection-api.ts +202 -0
  46. package/runtime/node_modules/@metro-labs/mcp/src/daemon/connector-api.ts +338 -0
  47. package/runtime/node_modules/@metro-labs/mcp/src/daemon/connector-json.ts +31 -0
  48. package/runtime/node_modules/@metro-labs/mcp/src/daemon/connector-oauth-routes.ts +157 -0
  49. package/runtime/node_modules/@metro-labs/mcp/src/daemon/connector-oauth.ts +127 -0
  50. package/runtime/node_modules/@metro-labs/mcp/src/daemon/connector-tools.ts +100 -0
  51. package/runtime/node_modules/@metro-labs/mcp/src/daemon/connector-url.ts +57 -0
  52. package/runtime/node_modules/@metro-labs/mcp/src/daemon/connector-verify.ts +333 -0
  53. package/runtime/node_modules/@metro-labs/mcp/src/daemon/cors.ts +29 -0
  54. package/runtime/node_modules/@metro-labs/mcp/src/daemon/crash-guard.ts +49 -0
  55. package/runtime/node_modules/@metro-labs/mcp/src/daemon/events.ts +117 -0
  56. package/runtime/node_modules/@metro-labs/mcp/src/daemon/google-auth.ts +164 -0
  57. package/runtime/node_modules/@metro-labs/mcp/src/daemon/google-oauth.ts +208 -0
  58. package/runtime/node_modules/@metro-labs/mcp/src/daemon/http.ts +357 -0
  59. package/runtime/node_modules/@metro-labs/mcp/src/daemon/identity.ts +79 -0
  60. package/runtime/node_modules/@metro-labs/mcp/src/daemon/log.ts +42 -0
  61. package/runtime/node_modules/@metro-labs/mcp/src/daemon/oauth-client.ts +162 -0
  62. package/runtime/node_modules/@metro-labs/mcp/src/daemon/oauth-discovery.ts +120 -0
  63. package/runtime/node_modules/@metro-labs/mcp/src/daemon/oauth-pending.ts +65 -0
  64. package/runtime/node_modules/@metro-labs/mcp/src/daemon/pair-codes.ts +58 -0
  65. package/runtime/node_modules/@metro-labs/mcp/src/daemon/paths.ts +134 -0
  66. package/runtime/node_modules/@metro-labs/mcp/src/daemon/project-api.ts +214 -0
  67. package/runtime/node_modules/@metro-labs/mcp/src/daemon/protocol.ts +224 -0
  68. package/runtime/node_modules/@metro-labs/mcp/src/daemon/run-api.ts +125 -0
  69. package/runtime/node_modules/@metro-labs/mcp/src/daemon/run-pair.ts +18 -0
  70. package/runtime/node_modules/@metro-labs/mcp/src/daemon/runtime-source.ts +105 -0
  71. package/runtime/node_modules/@metro-labs/mcp/src/daemon/secure-fs.ts +57 -0
  72. package/runtime/node_modules/@metro-labs/mcp/src/daemon/session-api.ts +27 -0
  73. package/runtime/node_modules/@metro-labs/mcp/src/daemon/session-apis.ts +41 -0
  74. package/runtime/node_modules/@metro-labs/mcp/src/daemon/session.ts +218 -0
  75. package/runtime/node_modules/@metro-labs/mcp/src/daemon/supervisor-io.ts +97 -0
  76. package/runtime/node_modules/@metro-labs/mcp/src/daemon/supervisor.ts +323 -0
  77. package/runtime/node_modules/@metro-labs/mcp/src/daemon/train-call.ts +22 -0
  78. package/runtime/node_modules/@metro-labs/mcp/src/daemon/train-error.ts +53 -0
  79. package/runtime/node_modules/@metro-labs/mcp/src/daemon/tunnel.ts +169 -0
  80. package/runtime/node_modules/@metro-labs/mcp/src/daemon/upload-api.ts +295 -0
  81. package/runtime/node_modules/@metro-labs/mcp/src/daemon/upload-store.ts +181 -0
  82. package/runtime/node_modules/@metro-labs/mcp/src/db/account-attach.ts +91 -0
  83. package/runtime/node_modules/@metro-labs/mcp/src/db/agent-admin.ts +215 -0
  84. package/runtime/node_modules/@metro-labs/mcp/src/db/agent-map.ts +71 -0
  85. package/runtime/node_modules/@metro-labs/mcp/src/db/agent-scope.ts +64 -0
  86. package/runtime/node_modules/@metro-labs/mcp/src/db/client.ts +37 -0
  87. package/runtime/node_modules/@metro-labs/mcp/src/db/connector-collections.ts +218 -0
  88. package/runtime/node_modules/@metro-labs/mcp/src/db/connector-config.ts +147 -0
  89. package/runtime/node_modules/@metro-labs/mcp/src/db/connectors.ts +329 -0
  90. package/runtime/node_modules/@metro-labs/mcp/src/db/ids.ts +19 -0
  91. package/runtime/node_modules/@metro-labs/mcp/src/db/key-map.ts +45 -0
  92. package/runtime/node_modules/@metro-labs/mcp/src/db/materialize.ts +364 -0
  93. package/runtime/node_modules/@metro-labs/mcp/src/db/projects.ts +300 -0
  94. package/runtime/node_modules/@metro-labs/mcp/src/db/runtime-admin.ts +31 -0
  95. package/runtime/node_modules/@metro-labs/mcp/src/db/runtimes.ts +105 -0
  96. package/runtime/node_modules/@metro-labs/mcp/src/db/schema.ts +131 -0
  97. package/runtime/node_modules/@metro-labs/mcp/src/db/token-carry.ts +45 -0
  98. package/runtime/node_modules/@metro-labs/mcp/src/db/users.ts +57 -0
  99. package/runtime/node_modules/@metro-labs/mcp/src/db/whatsapp-login.ts +18 -0
  100. package/runtime/node_modules/@metro-labs/mcp/src/mcp/accounts.ts +145 -0
  101. package/runtime/node_modules/@metro-labs/mcp/src/mcp/call-tools.ts +203 -0
  102. package/runtime/node_modules/@metro-labs/mcp/src/mcp/channel-owner.ts +29 -0
  103. package/runtime/node_modules/@metro-labs/mcp/src/mcp/ctx.ts +62 -0
  104. package/runtime/node_modules/@metro-labs/mcp/src/mcp/event-store.ts +91 -0
  105. package/runtime/node_modules/@metro-labs/mcp/src/mcp/frame-scope.ts +21 -0
  106. package/runtime/node_modules/@metro-labs/mcp/src/mcp/group-tools.ts +129 -0
  107. package/runtime/node_modules/@metro-labs/mcp/src/mcp/index.ts +192 -0
  108. package/runtime/node_modules/@metro-labs/mcp/src/mcp/member-tools.ts +72 -0
  109. package/runtime/node_modules/@metro-labs/mcp/src/mcp/permission-relay.ts +66 -0
  110. package/runtime/node_modules/@metro-labs/mcp/src/mcp/raw-get-stream.ts +207 -0
  111. package/runtime/node_modules/@metro-labs/mcp/src/mcp/request-identity.ts +73 -0
  112. package/runtime/node_modules/@metro-labs/mcp/src/mcp/session-registry.ts +172 -0
  113. package/runtime/node_modules/@metro-labs/mcp/src/mcp/session-route.ts +43 -0
  114. package/runtime/node_modules/@metro-labs/mcp/src/mcp/session.ts +211 -0
  115. package/runtime/node_modules/@metro-labs/mcp/src/mcp/str.ts +5 -0
  116. package/runtime/node_modules/@metro-labs/mcp/src/mcp/tool-dispatch.ts +212 -0
  117. package/runtime/node_modules/@metro-labs/mcp/src/mcp/tool-schemas.ts +397 -0
  118. package/runtime/node_modules/@metro-labs/mcp/src/mcp/upload-tool.ts +66 -0
  119. package/runtime/node_modules/@metro-labs/mcp/src/monitor/api.ts +240 -0
  120. package/runtime/node_modules/@metro-labs/mcp/src/server.ts +2 -0
  121. package/runtime/node_modules/@metro-labs/mcp/src/stations/account-store.ts +80 -0
  122. package/runtime/node_modules/@metro-labs/mcp/src/stations/attach-inline.ts +100 -0
  123. package/runtime/node_modules/@metro-labs/mcp/src/stations/attach-interactive.ts +161 -0
  124. package/runtime/node_modules/@metro-labs/mcp/src/stations/attach-resolve.ts +200 -0
  125. package/runtime/node_modules/@metro-labs/mcp/src/stations/attach-xmtp.ts +111 -0
  126. package/runtime/node_modules/@metro-labs/mcp/src/stations/attach.ts +182 -0
  127. package/runtime/node_modules/@metro-labs/mcp/src/stations/attachments.ts +196 -0
  128. package/runtime/node_modules/@metro-labs/mcp/src/stations/lines.ts +82 -0
  129. package/runtime/node_modules/@metro-labs/mcp/src/stations/messaging-normalize.ts +88 -0
  130. package/runtime/node_modules/@metro-labs/mcp/src/stations/registry.ts +35 -0
  131. package/runtime/node_modules/@metro-labs/mcp/src/stations/station-runtime.ts +64 -0
  132. package/runtime/node_modules/@metro-labs/mcp/src/stations/types.ts +107 -0
  133. package/runtime/node_modules/@metro-labs/telegram/package.json +25 -0
  134. package/runtime/node_modules/@metro-labs/telegram/src/accounts.ts +120 -0
  135. package/runtime/node_modules/@metro-labs/telegram/src/actions.ts +295 -0
  136. package/runtime/node_modules/@metro-labs/telegram/src/attachments.ts +128 -0
  137. package/runtime/node_modules/@metro-labs/telegram/src/format.ts +172 -0
  138. package/runtime/node_modules/@metro-labs/telegram/src/index.ts +103 -0
  139. package/runtime/node_modules/@metro-labs/telegram/src/media-actions.ts +166 -0
  140. package/runtime/node_modules/@metro-labs/telegram/src/members.ts +47 -0
  141. package/runtime/node_modules/@metro-labs/telegram/src/station.ts +17 -0
  142. package/runtime/node_modules/@metro-labs/telegram/src/types.ts +48 -0
  143. package/runtime/node_modules/@metro-labs/telegram/src/verify.ts +38 -0
  144. package/runtime/node_modules/@metro-labs/telegram/src/wire.ts +3 -0
  145. package/runtime/node_modules/@metro-labs/telegram-user/package.json +28 -0
  146. package/runtime/node_modules/@metro-labs/telegram-user/src/accounts.ts +81 -0
  147. package/runtime/node_modules/@metro-labs/telegram-user/src/actions.ts +254 -0
  148. package/runtime/node_modules/@metro-labs/telegram-user/src/attachments.ts +87 -0
  149. package/runtime/node_modules/@metro-labs/telegram-user/src/client.ts +77 -0
  150. package/runtime/node_modules/@metro-labs/telegram-user/src/format.ts +141 -0
  151. package/runtime/node_modules/@metro-labs/telegram-user/src/group.ts +261 -0
  152. package/runtime/node_modules/@metro-labs/telegram-user/src/history.ts +52 -0
  153. package/runtime/node_modules/@metro-labs/telegram-user/src/inbound.ts +78 -0
  154. package/runtime/node_modules/@metro-labs/telegram-user/src/index.ts +46 -0
  155. package/runtime/node_modules/@metro-labs/telegram-user/src/login.ts +166 -0
  156. package/runtime/node_modules/@metro-labs/telegram-user/src/media-actions.ts +80 -0
  157. package/runtime/node_modules/@metro-labs/telegram-user/src/members.ts +75 -0
  158. package/runtime/node_modules/@metro-labs/telegram-user/src/normalize.ts +22 -0
  159. package/runtime/node_modules/@metro-labs/telegram-user/src/reactions.ts +167 -0
  160. package/runtime/node_modules/@metro-labs/telegram-user/src/station.ts +24 -0
  161. package/runtime/node_modules/@metro-labs/telegram-user/src/types.ts +7 -0
  162. package/runtime/node_modules/@metro-labs/telegram-user/src/wire.ts +1 -0
  163. package/runtime/node_modules/@metro-labs/webhook/package.json +23 -0
  164. package/runtime/node_modules/@metro-labs/webhook/src/station.ts +40 -0
  165. package/runtime/node_modules/@metro-labs/whatsapp/package.json +29 -0
  166. package/runtime/node_modules/@metro-labs/whatsapp/src/accounts.ts +67 -0
  167. package/runtime/node_modules/@metro-labs/whatsapp/src/ack.ts +101 -0
  168. package/runtime/node_modules/@metro-labs/whatsapp/src/actions.ts +178 -0
  169. package/runtime/node_modules/@metro-labs/whatsapp/src/attachments.ts +72 -0
  170. package/runtime/node_modules/@metro-labs/whatsapp/src/auth-state.ts +129 -0
  171. package/runtime/node_modules/@metro-labs/whatsapp/src/client.ts +318 -0
  172. package/runtime/node_modules/@metro-labs/whatsapp/src/delivery.ts +49 -0
  173. package/runtime/node_modules/@metro-labs/whatsapp/src/format.ts +132 -0
  174. package/runtime/node_modules/@metro-labs/whatsapp/src/inbound.ts +57 -0
  175. package/runtime/node_modules/@metro-labs/whatsapp/src/index.ts +40 -0
  176. package/runtime/node_modules/@metro-labs/whatsapp/src/keys.ts +59 -0
  177. package/runtime/node_modules/@metro-labs/whatsapp/src/logger.ts +60 -0
  178. package/runtime/node_modules/@metro-labs/whatsapp/src/login.ts +176 -0
  179. package/runtime/node_modules/@metro-labs/whatsapp/src/media.ts +84 -0
  180. package/runtime/node_modules/@metro-labs/whatsapp/src/normalize.ts +22 -0
  181. package/runtime/node_modules/@metro-labs/whatsapp/src/outbox.ts +38 -0
  182. package/runtime/node_modules/@metro-labs/whatsapp/src/parse.ts +141 -0
  183. package/runtime/node_modules/@metro-labs/whatsapp/src/station.ts +17 -0
  184. package/runtime/node_modules/@metro-labs/whatsapp/src/token-store.ts +98 -0
  185. package/runtime/node_modules/@metro-labs/whatsapp/src/types.ts +6 -0
  186. package/runtime/node_modules/@metro-labs/whatsapp/src/wire.ts +5 -0
  187. package/runtime/node_modules/@metro-labs/xmtp/package.json +33 -0
  188. package/runtime/node_modules/@metro-labs/xmtp/src/accounts.ts +113 -0
  189. package/runtime/node_modules/@metro-labs/xmtp/src/actions-close.ts +110 -0
  190. package/runtime/node_modules/@metro-labs/xmtp/src/actions-conv.ts +299 -0
  191. package/runtime/node_modules/@metro-labs/xmtp/src/actions-meta.ts +157 -0
  192. package/runtime/node_modules/@metro-labs/xmtp/src/actions-push.ts +87 -0
  193. package/runtime/node_modules/@metro-labs/xmtp/src/actions.ts +375 -0
  194. package/runtime/node_modules/@metro-labs/xmtp/src/attachments.ts +107 -0
  195. package/runtime/node_modules/@metro-labs/xmtp/src/codecs.ts +171 -0
  196. package/runtime/node_modules/@metro-labs/xmtp/src/conv-helpers.ts +239 -0
  197. package/runtime/node_modules/@metro-labs/xmtp/src/emit-core.ts +55 -0
  198. package/runtime/node_modules/@metro-labs/xmtp/src/emit-payloads.ts +333 -0
  199. package/runtime/node_modules/@metro-labs/xmtp/src/emit.ts +78 -0
  200. package/runtime/node_modules/@metro-labs/xmtp/src/group-members.ts +34 -0
  201. package/runtime/node_modules/@metro-labs/xmtp/src/group.ts +56 -0
  202. package/runtime/node_modules/@metro-labs/xmtp/src/identity.ts +33 -0
  203. package/runtime/node_modules/@metro-labs/xmtp/src/index.ts +125 -0
  204. package/runtime/node_modules/@metro-labs/xmtp/src/labels.ts +157 -0
  205. package/runtime/node_modules/@metro-labs/xmtp/src/member-args.ts +40 -0
  206. package/runtime/node_modules/@metro-labs/xmtp/src/push.ts +349 -0
  207. package/runtime/node_modules/@metro-labs/xmtp/src/station.ts +13 -0
  208. package/runtime/node_modules/@metro-labs/xmtp/src/tools-handlers.ts +126 -0
  209. package/runtime/node_modules/@metro-labs/xmtp/src/tools.ts +212 -0
  210. package/runtime/node_modules/@metro-labs/xmtp/src/transcribe.ts +90 -0
  211. package/runtime/node_modules/@metro-labs/xmtp/src/verify.ts +84 -0
  212. package/runtime/node_modules/@metro-labs/xmtp/src/wire.ts +39 -0
  213. package/runtime/runtime.json +3 -0
  214. package/runtime/trains/.keep +0 -0
  215. package/LICENSE +0 -21
  216. package/README.md +0 -78
  217. package/dist/channels/discord.js +0 -148
  218. package/dist/channels/telegram.js +0 -137
  219. package/dist/lib/address.js +0 -21
  220. package/dist/lib/codex-rc.js +0 -274
  221. package/dist/lib/dotenv.js +0 -31
  222. package/dist/log.js +0 -12
  223. package/dist/paths.js +0 -45
  224. package/dist/tail.js +0 -161
  225. package/skills/metro/SKILL.md +0 -122
@@ -0,0 +1,333 @@
1
+ import type { Reaction } from '@xmtp/content-type-reaction';
2
+ import type { Reply } from '@xmtp/content-type-reply';
3
+ import { errMsg } from '@metro-labs/mcp/log';
4
+ import { transcribeAndEmit } from './transcribe.js';
5
+ import {
6
+ saveInlineAttachment,
7
+ saveRemoteAttachment,
8
+ type RemoteEntry,
9
+ } from './attachments.js';
10
+ import { emitInbound, emitAttachmentSaved } from './emit-core.js';
11
+
12
+ export interface EnvelopeCtx {
13
+ accountId: string;
14
+ msgId: string;
15
+ line: string;
16
+ baseId: string;
17
+ }
18
+
19
+ interface RemoteAtt {
20
+ url: string;
21
+ filename?: string;
22
+ contentDigest?: string;
23
+ nonce?: Uint8Array;
24
+ salt?: Uint8Array;
25
+ secret?: Uint8Array;
26
+ scheme?: string;
27
+ contentLength?: number;
28
+ }
29
+
30
+ interface AttView {
31
+ kind: string;
32
+ url: string;
33
+ name?: string;
34
+ size?: number;
35
+ remote: {
36
+ contentDigest?: string;
37
+ nonce?: string;
38
+ salt?: string;
39
+ secret?: string;
40
+ scheme?: string;
41
+ };
42
+ }
43
+
44
+ const b64 = (u?: Uint8Array): string | undefined =>
45
+ u ? Buffer.from(u).toString('base64') : undefined;
46
+
47
+ function remoteAtt(r: RemoteAtt, kind: string): AttView {
48
+ return {
49
+ kind,
50
+ url: r.url,
51
+ name: r.filename,
52
+ size: r.contentLength,
53
+ remote: {
54
+ contentDigest: r.contentDigest,
55
+ nonce: b64(r.nonce),
56
+ salt: b64(r.salt),
57
+ secret: b64(r.secret),
58
+ scheme: r.scheme,
59
+ },
60
+ };
61
+ }
62
+
63
+ const IMG_RE = /\.(png|jpg|jpeg|gif|webp|heic)(\?|$)/i;
64
+ const VID_RE = /\.(mp4|mov|webm|m4v)(\?|$)/i;
65
+
66
+ function attKindFor(r: RemoteAtt): string {
67
+ const isImg = IMG_RE.test(r.url) || IMG_RE.test(r.filename ?? '');
68
+ if (isImg) return 'image';
69
+ const isVid = VID_RE.test(r.url) || VID_RE.test(r.filename ?? '');
70
+ return isVid ? 'video' : 'file';
71
+ }
72
+
73
+ function singleAttText(one: AttView): string {
74
+ if (one.kind === 'video') return `🎥 ${one.name ?? 'video'}`;
75
+ return `[${one.kind}: ${one.name ?? one.url}]`;
76
+ }
77
+
78
+ function multiAttText(attachments: AttView[]): string {
79
+ const total = attachments.length;
80
+ const imgCount = attachments.filter((a) => a.kind === 'image').length;
81
+ const vidCount = attachments.filter((a) => a.kind === 'video').length;
82
+ if (imgCount === total && imgCount > 1) return `📷 ${imgCount} photos`;
83
+ if (vidCount === total && vidCount > 1) return `🎥 ${vidCount} videos`;
84
+ const one = attachments[0];
85
+ if (total === 1 && one) return singleAttText(one);
86
+ return `📎 ${total} attachments`;
87
+ }
88
+
89
+ function multiRemotePayload(
90
+ base: Record<string, unknown>,
91
+ typeId: string,
92
+ c: object,
93
+ ): Record<string, unknown> {
94
+ const m = c as { attachments?: RemoteAtt[] };
95
+ const list = Array.isArray(m.attachments) ? m.attachments : [];
96
+ const attachments = list.map((r) => remoteAtt(r, attKindFor(r)));
97
+ return {
98
+ ...base,
99
+ text: multiAttText(attachments),
100
+ payload: { contentType: typeId, attachments },
101
+ };
102
+ }
103
+
104
+ function reactionPayload(
105
+ base: Record<string, unknown>,
106
+ r: Reaction,
107
+ ): Record<string, unknown> {
108
+ const schemaStr = ((): string | undefined => {
109
+ const s = (r as { schema?: unknown }).schema;
110
+ if (typeof s === 'string') return s.toLowerCase();
111
+ if (s === 3) return 'custom';
112
+ if (s === 2) return 'shortcode';
113
+ if (s === 1) return 'unicode';
114
+ return undefined;
115
+ })();
116
+ const actionStr = ((): string | undefined => {
117
+ const a = (r as { action?: unknown }).action;
118
+ if (typeof a === 'string') return a.toLowerCase();
119
+ if (a === 2) return 'removed';
120
+ if (a === 1) return 'added';
121
+ return undefined;
122
+ })();
123
+ const removed = actionStr === 'removed';
124
+ return {
125
+ ...base,
126
+ text: `[react ${r.content ?? ''}${removed ? ' (removed)' : ''}]`,
127
+ event: { type: 'react', emoji: r.content, targetId: r.reference },
128
+ payload: {
129
+ contentType: 'reaction',
130
+ reactTo: r.reference,
131
+ emoji: r.content,
132
+ content: r.content,
133
+ schema: schemaStr,
134
+ action: actionStr,
135
+ removed,
136
+ optionIndex: schemaStr === 'custom' ? Number(r.content) : undefined,
137
+ },
138
+ };
139
+ }
140
+
141
+ function replyPayload(
142
+ base: Record<string, unknown>,
143
+ typeId: string,
144
+ c: Reply,
145
+ ): Record<string, unknown> {
146
+ return {
147
+ ...base,
148
+ text:
149
+ typeof c.content === 'string'
150
+ ? c.content
151
+ : `[reply with ${c.contentType?.typeId ?? 'unknown'}]`,
152
+ event: { type: 'reply', replyTo: c.reference },
153
+ payload: {
154
+ contentType: typeId,
155
+ replyTo: c.reference,
156
+ replyContentType: c.contentType?.typeId,
157
+ },
158
+ };
159
+ }
160
+
161
+ function attachmentKind(mime: string | undefined): string {
162
+ if (mime?.startsWith('image/')) return 'image';
163
+ if (mime?.startsWith('audio/')) return 'audio';
164
+ if (mime?.startsWith('video/')) return 'video';
165
+ return 'file';
166
+ }
167
+
168
+ function inlineAttachmentPayload(
169
+ base: Record<string, unknown>,
170
+ typeId: string,
171
+ c: { filename?: string; mimeType: string; content: Uint8Array },
172
+ ctx: EnvelopeCtx,
173
+ ): Record<string, unknown> {
174
+ const kind = attachmentKind(c.mimeType);
175
+ const dataB64 = Buffer.from(c.content).toString('base64');
176
+ const out = {
177
+ ...base,
178
+ text: `[${kind}: ${c.filename ?? 'attachment'}]`,
179
+ payload: {
180
+ contentType: typeId,
181
+ attachments: [{ kind, mime: c.mimeType, name: c.filename, dataB64 }],
182
+ },
183
+ };
184
+ if (kind === 'audio')
185
+ transcribeAndEmit(
186
+ c.content,
187
+ ctx.line,
188
+ ctx.accountId,
189
+ ctx.baseId,
190
+ emitInbound,
191
+ ).catch((err: unknown) => {
192
+ process.stderr.write(
193
+ `xmtp[${ctx.accountId}] voice transcription failed: ${errMsg(err)}\n`,
194
+ );
195
+ });
196
+ emitAttachmentSaved(
197
+ ctx.accountId,
198
+ ctx.line,
199
+ ctx.baseId,
200
+ 0,
201
+ saveInlineAttachment(c, ctx.msgId, 0),
202
+ );
203
+ return out;
204
+ }
205
+
206
+ function remoteStaticPayload(
207
+ base: Record<string, unknown>,
208
+ typeId: string,
209
+ c: RemoteAtt,
210
+ ctx: EnvelopeCtx,
211
+ ): Record<string, unknown> {
212
+ const kind = IMG_RE.test(c.url) ? 'image' : 'file';
213
+ emitAttachmentSaved(
214
+ ctx.accountId,
215
+ ctx.line,
216
+ ctx.baseId,
217
+ 0,
218
+ saveRemoteAttachment(c, ctx.msgId, 0),
219
+ );
220
+ return {
221
+ ...base,
222
+ text: `[${kind}: ${c.filename ?? c.url}]`,
223
+ payload: { contentType: typeId, attachments: [remoteAtt(c, kind)] },
224
+ };
225
+ }
226
+
227
+ function multiRemoteEnvelope(
228
+ base: Record<string, unknown>,
229
+ typeId: string,
230
+ c: object,
231
+ ctx: EnvelopeCtx,
232
+ ): Record<string, unknown> {
233
+ const m = c as { attachments?: RemoteEntry[] };
234
+ (Array.isArray(m.attachments) ? m.attachments : []).forEach((r, i) => {
235
+ emitAttachmentSaved(
236
+ ctx.accountId,
237
+ ctx.line,
238
+ ctx.baseId,
239
+ i,
240
+ saveRemoteAttachment(r, ctx.msgId, i),
241
+ );
242
+ });
243
+ return multiRemotePayload(base, typeId, c);
244
+ }
245
+
246
+ function pollPayload(
247
+ base: Record<string, unknown>,
248
+ typeId: string,
249
+ c: object,
250
+ ): Record<string, unknown> {
251
+ const p = c as { question?: string };
252
+ return {
253
+ ...base,
254
+ text: `Poll: ${p.question ?? ''}`,
255
+ payload: { contentType: typeId, poll: c },
256
+ };
257
+ }
258
+
259
+ function labeledPayload(
260
+ base: Record<string, unknown>,
261
+ typeId: string,
262
+ text: string,
263
+ key: string,
264
+ c: unknown,
265
+ ): Record<string, unknown> {
266
+ return { ...base, text, payload: { contentType: typeId, [key]: c } };
267
+ }
268
+
269
+ function attachmentEnvelope(
270
+ base: Record<string, unknown>,
271
+ typeId: string,
272
+ c: object,
273
+ ctx: EnvelopeCtx,
274
+ ): Record<string, unknown> | undefined {
275
+ if (typeId === 'attachment')
276
+ return inlineAttachmentPayload(
277
+ base,
278
+ typeId,
279
+ c as { filename?: string; mimeType: string; content: Uint8Array },
280
+ ctx,
281
+ );
282
+ if (typeId === 'remoteStaticAttachment')
283
+ return remoteStaticPayload(base, typeId, c as RemoteAtt, ctx);
284
+ if (
285
+ typeId === 'multiRemoteStaticAttachment' ||
286
+ typeId === 'multiRemoteAttachment'
287
+ )
288
+ return multiRemoteEnvelope(base, typeId, c, ctx);
289
+ return undefined;
290
+ }
291
+
292
+ function refEnvelope(
293
+ base: Record<string, unknown>,
294
+ typeId: string | undefined,
295
+ c: object,
296
+ ): Record<string, unknown> | undefined {
297
+ if (typeId === 'walletSendCalls')
298
+ return labeledPayload(
299
+ base,
300
+ typeId,
301
+ 'Payment request',
302
+ 'walletSendCalls',
303
+ c,
304
+ );
305
+ if (typeId === 'transactionReference')
306
+ return labeledPayload(
307
+ base,
308
+ typeId,
309
+ 'Transaction',
310
+ 'transactionReference',
311
+ c,
312
+ );
313
+ if (typeId === 'signatureRequest')
314
+ return labeledPayload(base, typeId, 'Signature request', 'signatureRequest', c);
315
+ if (typeId === 'signatureReference')
316
+ return labeledPayload(base, typeId, 'Signature', 'signatureReference', c);
317
+ return undefined;
318
+ }
319
+
320
+ export function typedEnvelope(
321
+ base: Record<string, unknown>,
322
+ typeId: string | undefined,
323
+ c: object,
324
+ ctx: EnvelopeCtx,
325
+ ): Record<string, unknown> | undefined {
326
+ if (typeId === 'reaction') return reactionPayload(base, c as Reaction);
327
+ if (typeId === 'reply') return replyPayload(base, typeId, c as Reply);
328
+ if (typeId === 'poll') return pollPayload(base, typeId, c);
329
+ return (
330
+ attachmentEnvelope(base, typeId ?? '', c, ctx) ??
331
+ refEnvelope(base, typeId, c)
332
+ );
333
+ }
@@ -0,0 +1,78 @@
1
+ import type { Conversation, DecodedMessage } from '@xmtp/node-sdk';
2
+ import { lineOf, parseLine } from './accounts.js';
3
+ import { emit, mintId, rememberUid, SELF_URI } from './wire.js';
4
+ import { fcmPushToAll } from './push.js';
5
+ import { emitInbound, emitAttachmentSaved } from './emit-core.js';
6
+ import { typedEnvelope, type EnvelopeCtx } from './emit-payloads.js';
7
+ import type { StructuredEvent } from '@metro-labs/mcp/events';
8
+
9
+ export { emitInbound, emitAttachmentSaved };
10
+
11
+ export function envelope(
12
+ accountId: string,
13
+ msg: DecodedMessage,
14
+ conv: Conversation,
15
+ ): Record<string, unknown> {
16
+ const typeId = msg.contentType?.typeId;
17
+ const c = msg.content;
18
+ const line = lineOf(accountId, conv.id);
19
+ const base = {
20
+ id: mintId(),
21
+ ts: msg.sentAt.toISOString(),
22
+ station: 'xmtp',
23
+ line,
24
+ from: `metro://xmtp/${accountId}/user/${msg.senderInboxId}`,
25
+ message_id: msg.id,
26
+ };
27
+ rememberUid(base.id, msg.id);
28
+ if (typeof c === 'string')
29
+ return { ...base, text: c, payload: { contentType: typeId } };
30
+ if (c && typeof c === 'object') {
31
+ const ctx: EnvelopeCtx = {
32
+ accountId,
33
+ msgId: msg.id,
34
+ line,
35
+ baseId: base.id,
36
+ };
37
+ const out = typedEnvelope(base, typeId, c, ctx);
38
+ if (out) return out;
39
+ }
40
+ return {
41
+ ...base,
42
+ text: `[${typeId ?? 'unknown'} payload]`,
43
+ payload: { contentType: typeId },
44
+ };
45
+ }
46
+
47
+ export function emitOutbound(
48
+ accountId: string,
49
+ line: string,
50
+ messageId: string,
51
+ text: string,
52
+ event?: StructuredEvent,
53
+ ): void {
54
+ const uid = mintId();
55
+ rememberUid(uid, messageId);
56
+ emit({
57
+ kind: 'outbound',
58
+ id: uid,
59
+ ts: new Date().toISOString(),
60
+ station: 'xmtp',
61
+ line,
62
+ from: SELF_URI,
63
+ to: line,
64
+ message_id: messageId,
65
+ text,
66
+ account: accountId,
67
+ ...(event ? { event } : {}),
68
+ payload: { account: accountId },
69
+ });
70
+ void (async (): Promise<void> => {
71
+ const data: Record<string, string> = { line, messageId };
72
+ {
73
+ const p = parseLine(line);
74
+ if (p) data.convId = p.convId.toLowerCase();
75
+ }
76
+ await fcmPushToAll(accountId, data);
77
+ })().catch(() => undefined);
78
+ }
@@ -0,0 +1,34 @@
1
+ import type {
2
+ MemberOutcome,
3
+ MemberOutcomeStatus,
4
+ } from '@metro-labs/mcp/stations/types';
5
+
6
+ type Args = Record<string, unknown>;
7
+
8
+ const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
9
+
10
+ function strList(value: unknown): string[] {
11
+ if (!Array.isArray(value)) return [];
12
+ return value.filter((v) => typeof v === 'string' && v.length > 0) as string[];
13
+ }
14
+
15
+ export function splitMembers(args: Args): {
16
+ addrs: string[];
17
+ inboxes: string[];
18
+ } {
19
+ const addrs = new Set(strList(args.addresses));
20
+ const inboxes = new Set(strList(args.inboxIds));
21
+ for (const m of strList(args.members)) {
22
+ if (ADDRESS_RE.test(m)) addrs.add(m);
23
+ else inboxes.add(m);
24
+ }
25
+ return { addrs: [...addrs], inboxes: [...inboxes] };
26
+ }
27
+
28
+ export function memberOutcomes(
29
+ addrs: string[],
30
+ inboxes: string[],
31
+ status: MemberOutcomeStatus,
32
+ ): MemberOutcome[] {
33
+ return [...addrs, ...inboxes].map((id) => ({ id, status }));
34
+ }
@@ -0,0 +1,56 @@
1
+ import { TrainError } from '@metro-labs/mcp/train-error';
2
+ import type { GroupResult } from '@metro-labs/mcp/stations/types';
3
+ import { accountForCall, convOf, lineOf } from './accounts.js';
4
+ import {
5
+ applyMemberOp,
6
+ createGroupWithMembers,
7
+ warmGroupName,
8
+ } from './conv-helpers.js';
9
+ import { memberOutcomes, splitMembers } from './group-members.js';
10
+
11
+ type Args = Record<string, unknown>;
12
+
13
+ export async function groupCreate(args: Args): Promise<GroupResult> {
14
+ const name = typeof args.name === 'string' ? args.name : '';
15
+ if (!name) throw new TrainError('INVALID_ARGS', 'groupCreate requires a `name`');
16
+ const acct = accountForCall(args);
17
+ const { addrs, inboxes } = splitMembers(args);
18
+ const group = await createGroupWithMembers(acct, addrs, inboxes, {
19
+ groupName: name,
20
+ });
21
+ warmGroupName(group.id, name);
22
+ return {
23
+ capability: { supported: true },
24
+ line: lineOf(acct.cfg.id, group.id),
25
+ id: group.id,
26
+ name,
27
+ members: memberOutcomes(addrs, inboxes, 'added'),
28
+ };
29
+ }
30
+
31
+ async function memberOp(
32
+ args: Args,
33
+ mode: 'add' | 'remove',
34
+ verb: string,
35
+ ): Promise<GroupResult> {
36
+ const line = typeof args.line === 'string' ? args.line : '';
37
+ if (!line) throw new TrainError('INVALID_ARGS', `${verb} requires a \`line\``);
38
+ const { addrs, inboxes } = splitMembers(args);
39
+ if (!addrs.length && !inboxes.length)
40
+ throw new TrainError('INVALID_ARGS', `${verb} requires members`);
41
+ const { conv } = await convOf(line);
42
+ if (!conv) throw new TrainError('NOT_FOUND', `conversation not found for ${line}`);
43
+ await applyMemberOp(conv, addrs, inboxes, mode);
44
+ return {
45
+ capability: { supported: true },
46
+ line,
47
+ id: conv.id,
48
+ members: memberOutcomes(addrs, inboxes, mode === 'add' ? 'added' : 'removed'),
49
+ };
50
+ }
51
+
52
+ export const groupAddMembers = (args: Args): Promise<GroupResult> =>
53
+ memberOp(args, 'add', 'groupAddMembers');
54
+
55
+ export const groupRemoveMembers = (args: Args): Promise<GroupResult> =>
56
+ memberOp(args, 'remove', 'groupRemoveMembers');
@@ -0,0 +1,33 @@
1
+ import { IdentifierKind, type Signer } from '@xmtp/node-sdk';
2
+ import { privateKeyToAccount } from 'viem/accounts';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+
6
+ export const XMTP_ENV = 'production' as const;
7
+
8
+ export const expandHome = (p: string): string =>
9
+ p.startsWith('~') ? join(homedir(), p.slice(1)) : p;
10
+
11
+ export function signerFor(privateKey: string): {
12
+ signer: Signer;
13
+ address: string;
14
+ } {
15
+ const acct = privateKeyToAccount(privateKey as `0x${string}`);
16
+ const signer: Signer = {
17
+ type: 'EOA',
18
+ getIdentifier: () =>
19
+ Promise.resolve({
20
+ identifier: acct.address,
21
+ identifierKind: IdentifierKind.Ethereum,
22
+ }),
23
+ signMessage: async (msg: string) => {
24
+ const sig = await acct.signMessage({ message: msg });
25
+ const hex = sig.slice(2);
26
+ const out = new Uint8Array(hex.length / 2);
27
+ for (let i = 0; i < out.length; i++)
28
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
29
+ return out;
30
+ },
31
+ };
32
+ return { signer, address: acct.address };
33
+ }
@@ -0,0 +1,125 @@
1
+ import { errMsg } from '@metro-labs/mcp/log';
2
+ import { ConsentState, type DecodedMessage } from '@xmtp/node-sdk';
3
+ import {
4
+ accounts,
5
+ bootAccount,
6
+ loadAccounts,
7
+ type Account,
8
+ } from './accounts.js';
9
+ import { emitInbound, envelope } from './emit.js';
10
+ import { groupNameFor } from './conv-helpers.js';
11
+ import { handleControlDm, pushInbound } from './push.js';
12
+ import { readCalls } from '@metro-labs/mcp/trains/protocol';
13
+ import { handleCall } from './actions.js';
14
+
15
+ readCalls('xmtp', handleCall);
16
+
17
+ const SYNC_MS = Number(process.env.XMTP_SYNC_MS ?? '60000');
18
+ const SILENT_TYPES = new Set([
19
+ 'readReceipt',
20
+ 'transactionReference',
21
+ 'walletSendCalls',
22
+ 'groupUpdated',
23
+ 'group_updated',
24
+ ]);
25
+
26
+ async function bootSync(acct: Account): Promise<void> {
27
+ const { id } = acct.cfg;
28
+ try {
29
+ await acct.client.conversations.syncAll([
30
+ ConsentState.Allowed,
31
+ ConsentState.Unknown,
32
+ ]);
33
+ const initial = await acct.client.conversations.list();
34
+ process.stderr.write(
35
+ `xmtp[${id}]: synced ${initial.length} conversation(s) at boot\n`,
36
+ );
37
+ } catch (err) {
38
+ process.stderr.write(
39
+ `xmtp[${id}] boot sync error: ${errMsg(err)}\n`,
40
+ );
41
+ }
42
+ }
43
+
44
+ function startPeriodicSync(acct: Account): void {
45
+ const { id } = acct.cfg;
46
+ setInterval(() => {
47
+ acct.client.conversations
48
+ .syncAll([ConsentState.Allowed, ConsentState.Unknown])
49
+ .catch((err: unknown) => {
50
+ process.stderr.write(`xmtp[${id}] sync error: ${errMsg(err)}\n`);
51
+ });
52
+ }, SYNC_MS).unref();
53
+ }
54
+
55
+ async function handleStreamMessage(
56
+ acct: Account,
57
+ msg: DecodedMessage,
58
+ ): Promise<void> {
59
+ const { id } = acct.cfg;
60
+ if (msg.senderInboxId === acct.client.inboxId) return;
61
+ if (SILENT_TYPES.has(msg.contentType?.typeId ?? '')) return;
62
+ if (handleControlDm(id, msg)) return;
63
+ const conv = await acct.client.conversations.getConversationById(
64
+ msg.conversationId,
65
+ );
66
+ if (!conv) return;
67
+ const env = envelope(id, msg, conv);
68
+ const name = await groupNameFor(msg.conversationId, conv);
69
+ if (name) {
70
+ env.line_name = name;
71
+ env.lineName = name;
72
+ const p = (env.payload ?? {}) as Record<string, unknown>;
73
+ env.payload = { ...p, lineName: name };
74
+ }
75
+ emitInbound(id, env);
76
+ pushInbound(id, env, msg, conv);
77
+ }
78
+
79
+ async function runAccount(acct: Account): Promise<void> {
80
+ const { id } = acct.cfg;
81
+ await bootSync(acct);
82
+ startPeriodicSync(acct);
83
+
84
+ for (;;) {
85
+ try {
86
+ const stream = await acct.client.conversations.streamAllMessages({
87
+ consentStates: [ConsentState.Allowed, ConsentState.Unknown],
88
+ });
89
+ for await (const msg of stream) {
90
+ if (!msg) continue;
91
+ await handleStreamMessage(acct, msg);
92
+ }
93
+ } catch (err) {
94
+ process.stderr.write(
95
+ `xmtp[${id}] stream error (retry 5s): ${errMsg(err)}\n`,
96
+ );
97
+ }
98
+ await new Promise((r) => setTimeout(r, 5000));
99
+ }
100
+ }
101
+
102
+ const cfgs = loadAccounts();
103
+ for (const cfg of cfgs) {
104
+ try {
105
+ await bootAccount(cfg);
106
+ } catch (err) {
107
+ process.stderr.write(
108
+ `xmtp[${cfg.id}] boot FAILED: ${errMsg(err)}\n`,
109
+ );
110
+ }
111
+ }
112
+ if (accounts.size === 0) {
113
+ process.stderr.write('xmtp: no accounts booted, exiting\n');
114
+ process.exit(2);
115
+ }
116
+ process.stderr.write(
117
+ `xmtp train ready — ${accounts.size} account(s): ${[...accounts.keys()].join(', ')}\n`,
118
+ );
119
+
120
+ for (const acct of accounts.values())
121
+ runAccount(acct).catch((err: unknown) => {
122
+ process.stderr.write(
123
+ `xmtp[${acct.cfg.id}] account loop failed: ${errMsg(err)}\n`,
124
+ );
125
+ });