@stage-labs/metro 0.1.0-beta.15 → 0.1.0-beta.151

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 (327) hide show
  1. package/dist/api.js +9 -0
  2. package/dist/claude-settings.js +40 -0
  3. package/dist/claude.js +182 -0
  4. package/dist/cli.js +86 -0
  5. package/dist/control.js +74 -0
  6. package/dist/hold.js +211 -0
  7. package/dist/local.js +77 -0
  8. package/dist/mcp-config.js +25 -0
  9. package/dist/node-name.js +71 -0
  10. package/dist/onboarding.js +43 -0
  11. package/dist/provider-flags.js +9 -0
  12. package/dist/route.js +50 -0
  13. package/dist/runtime-install.js +97 -0
  14. package/dist/runtime.js +74 -0
  15. package/dist/serve.js +155 -0
  16. package/dist/service.js +242 -0
  17. package/dist/tail.js +119 -0
  18. package/dist/update.js +45 -0
  19. package/dist/version.js +97 -0
  20. package/package.json +14 -28
  21. package/runtime/marketplace/.claude-plugin/marketplace.json +12 -0
  22. package/runtime/marketplace/plugin/.claude-plugin/plugin.json +18 -0
  23. package/runtime/marketplace/plugin/.mcp.json +1 -0
  24. package/runtime/marketplace/plugin/bin/guard.mjs +55 -0
  25. package/runtime/marketplace/plugin/bin/metro-plugin.mjs +40 -0
  26. package/runtime/marketplace/plugin/bin/session-start.mjs +31 -0
  27. package/runtime/marketplace/plugin/hooks/hooks.json +25 -0
  28. package/runtime/marketplace/plugin/orchestrator.md +16 -0
  29. package/runtime/node_modules/@metro-labs/core/package.json +43 -0
  30. package/runtime/node_modules/@metro-labs/core/src/address.ts +6 -0
  31. package/runtime/node_modules/@metro-labs/core/src/endpoints.ts +7 -0
  32. package/runtime/node_modules/@metro-labs/core/src/events.ts +120 -0
  33. package/runtime/node_modules/@metro-labs/core/src/identity.ts +7 -0
  34. package/runtime/node_modules/@metro-labs/core/src/ids.ts +21 -0
  35. package/runtime/node_modules/@metro-labs/core/src/is-record.ts +2 -0
  36. package/runtime/node_modules/@metro-labs/core/src/lines.ts +87 -0
  37. package/runtime/node_modules/@metro-labs/core/src/log.ts +42 -0
  38. package/runtime/node_modules/@metro-labs/core/src/protocol.ts +226 -0
  39. package/runtime/node_modules/@metro-labs/core/src/secure-fs.ts +57 -0
  40. package/runtime/node_modules/@metro-labs/core/src/station-names.ts +13 -0
  41. package/runtime/node_modules/@metro-labs/core/src/stations/account-store.ts +60 -0
  42. package/runtime/node_modules/@metro-labs/core/src/stations/attachments.ts +196 -0
  43. package/runtime/node_modules/@metro-labs/core/src/stations/messaging-normalize.ts +88 -0
  44. package/runtime/node_modules/@metro-labs/core/src/stations/station-runtime.ts +64 -0
  45. package/runtime/node_modules/@metro-labs/core/src/stations/types.ts +108 -0
  46. package/runtime/node_modules/@metro-labs/core/src/str.ts +5 -0
  47. package/runtime/node_modules/@metro-labs/core/src/train-error.ts +53 -0
  48. package/runtime/node_modules/@metro-labs/core/src/version.ts +2 -0
  49. package/runtime/node_modules/@metro-labs/daemon/package.json +47 -0
  50. package/runtime/node_modules/@metro-labs/daemon/src/agents/account-attach.ts +19 -0
  51. package/runtime/node_modules/@metro-labs/daemon/src/agents/account-routes.ts +70 -0
  52. package/runtime/node_modules/@metro-labs/daemon/src/agents/accounts-api.ts +365 -0
  53. package/runtime/node_modules/@metro-labs/daemon/src/agents/admin.ts +39 -0
  54. package/runtime/node_modules/@metro-labs/daemon/src/agents/allowlist.ts +37 -0
  55. package/runtime/node_modules/@metro-labs/daemon/src/agents/api.ts +225 -0
  56. package/runtime/node_modules/@metro-labs/daemon/src/agents/bundle.ts +122 -0
  57. package/runtime/node_modules/@metro-labs/daemon/src/agents/file-admin.ts +364 -0
  58. package/runtime/node_modules/@metro-labs/daemon/src/agents/files.ts +185 -0
  59. package/runtime/node_modules/@metro-labs/daemon/src/agents/keys.ts +40 -0
  60. package/runtime/node_modules/@metro-labs/daemon/src/agents/map.ts +95 -0
  61. package/runtime/node_modules/@metro-labs/daemon/src/agents/scope.ts +64 -0
  62. package/runtime/node_modules/@metro-labs/daemon/src/agents/senders.ts +38 -0
  63. package/runtime/node_modules/@metro-labs/daemon/src/boot/boot.ts +200 -0
  64. package/runtime/node_modules/@metro-labs/daemon/src/boot/connect-hint.ts +39 -0
  65. package/runtime/node_modules/@metro-labs/daemon/src/boot/crash-guard.ts +49 -0
  66. package/runtime/node_modules/@metro-labs/daemon/src/boot/local-owner.ts +30 -0
  67. package/runtime/node_modules/@metro-labs/daemon/src/boot/paths.ts +106 -0
  68. package/runtime/node_modules/@metro-labs/daemon/src/channels/addressed.ts +25 -0
  69. package/runtime/node_modules/@metro-labs/daemon/src/channels/dedupe.ts +24 -0
  70. package/runtime/node_modules/@metro-labs/daemon/src/channels/inbound.ts +380 -0
  71. package/runtime/node_modules/@metro-labs/daemon/src/channels/media-note.ts +85 -0
  72. package/runtime/node_modules/@metro-labs/daemon/src/channels/pending.ts +75 -0
  73. package/runtime/node_modules/@metro-labs/daemon/src/channels/relay.ts +129 -0
  74. package/runtime/node_modules/@metro-labs/daemon/src/channels/webhook-note.ts +51 -0
  75. package/runtime/node_modules/@metro-labs/daemon/src/claude/api.ts +354 -0
  76. package/runtime/node_modules/@metro-labs/daemon/src/claude/files.ts +358 -0
  77. package/runtime/node_modules/@metro-labs/daemon/src/claude/login.ts +169 -0
  78. package/runtime/node_modules/@metro-labs/daemon/src/claude/onboarding.ts +56 -0
  79. package/runtime/node_modules/@metro-labs/daemon/src/claude/plugin-install.ts +140 -0
  80. package/runtime/node_modules/@metro-labs/daemon/src/claude/session-files.ts +90 -0
  81. package/runtime/node_modules/@metro-labs/daemon/src/claude/session.ts +253 -0
  82. package/runtime/node_modules/@metro-labs/daemon/src/claude/settings.ts +117 -0
  83. package/runtime/node_modules/@metro-labs/daemon/src/claude/setup.ts +263 -0
  84. package/runtime/node_modules/@metro-labs/daemon/src/claude/skills.ts +118 -0
  85. package/runtime/node_modules/@metro-labs/daemon/src/claude/version.ts +109 -0
  86. package/runtime/node_modules/@metro-labs/daemon/src/connectors/api.ts +313 -0
  87. package/runtime/node_modules/@metro-labs/daemon/src/connectors/config.ts +157 -0
  88. package/runtime/node_modules/@metro-labs/daemon/src/connectors/health.ts +18 -0
  89. package/runtime/node_modules/@metro-labs/daemon/src/connectors/model.ts +69 -0
  90. package/runtime/node_modules/@metro-labs/daemon/src/connectors/oauth-client.ts +166 -0
  91. package/runtime/node_modules/@metro-labs/daemon/src/connectors/oauth-discovery.ts +139 -0
  92. package/runtime/node_modules/@metro-labs/daemon/src/connectors/oauth-pending.ts +65 -0
  93. package/runtime/node_modules/@metro-labs/daemon/src/connectors/oauth-routes.ts +171 -0
  94. package/runtime/node_modules/@metro-labs/daemon/src/connectors/oauth.ts +155 -0
  95. package/runtime/node_modules/@metro-labs/daemon/src/connectors/plugin-sync.ts +122 -0
  96. package/runtime/node_modules/@metro-labs/daemon/src/connectors/reach.ts +27 -0
  97. package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay-target.ts +39 -0
  98. package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay.ts +304 -0
  99. package/runtime/node_modules/@metro-labs/daemon/src/connectors/store.ts +299 -0
  100. package/runtime/node_modules/@metro-labs/daemon/src/connectors/tools.ts +108 -0
  101. package/runtime/node_modules/@metro-labs/daemon/src/connectors/url.ts +59 -0
  102. package/runtime/node_modules/@metro-labs/daemon/src/connectors/verify.ts +101 -0
  103. package/runtime/node_modules/@metro-labs/daemon/src/files/attach-grant.ts +99 -0
  104. package/runtime/node_modules/@metro-labs/daemon/src/files/attach-owner.ts +32 -0
  105. package/runtime/node_modules/@metro-labs/daemon/src/files/attach-serve.ts +121 -0
  106. package/runtime/node_modules/@metro-labs/daemon/src/files/upload-api.ts +294 -0
  107. package/runtime/node_modules/@metro-labs/daemon/src/files/upload-store.ts +181 -0
  108. package/runtime/node_modules/@metro-labs/daemon/src/gateway/bedrock.ts +259 -0
  109. package/runtime/node_modules/@metro-labs/daemon/src/gateway/codex-auth.ts +231 -0
  110. package/runtime/node_modules/@metro-labs/daemon/src/gateway/codex-device.ts +91 -0
  111. package/runtime/node_modules/@metro-labs/daemon/src/gateway/codex-stream.ts +288 -0
  112. package/runtime/node_modules/@metro-labs/daemon/src/gateway/codex-translate.ts +203 -0
  113. package/runtime/node_modules/@metro-labs/daemon/src/gateway/codex.ts +231 -0
  114. package/runtime/node_modules/@metro-labs/daemon/src/gateway/eventstream.ts +123 -0
  115. package/runtime/node_modules/@metro-labs/daemon/src/gateway/forward.ts +187 -0
  116. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gateway.ts +247 -0
  117. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gemini-auth.ts +182 -0
  118. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gemini-client.ts +46 -0
  119. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gemini-setup.ts +150 -0
  120. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gemini-stream.ts +148 -0
  121. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gemini-translate.ts +201 -0
  122. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gemini.ts +257 -0
  123. package/runtime/node_modules/@metro-labs/daemon/src/gateway/model-api.ts +353 -0
  124. package/runtime/node_modules/@metro-labs/daemon/src/gateway/model-config.ts +232 -0
  125. package/runtime/node_modules/@metro-labs/daemon/src/gateway/openrouter.ts +90 -0
  126. package/runtime/node_modules/@metro-labs/daemon/src/gateway/provider-models.ts +65 -0
  127. package/runtime/node_modules/@metro-labs/daemon/src/gateway/served.ts +17 -0
  128. package/runtime/node_modules/@metro-labs/daemon/src/gateway/usage.ts +242 -0
  129. package/runtime/node_modules/@metro-labs/daemon/src/mcp/accounts.ts +151 -0
  130. package/runtime/node_modules/@metro-labs/daemon/src/mcp/call-tools.ts +216 -0
  131. package/runtime/node_modules/@metro-labs/daemon/src/mcp/channel-owner.ts +29 -0
  132. package/runtime/node_modules/@metro-labs/daemon/src/mcp/ctx.ts +62 -0
  133. package/runtime/node_modules/@metro-labs/daemon/src/mcp/event-store.ts +91 -0
  134. package/runtime/node_modules/@metro-labs/daemon/src/mcp/frame-scope.ts +21 -0
  135. package/runtime/node_modules/@metro-labs/daemon/src/mcp/group-tools.ts +129 -0
  136. package/runtime/node_modules/@metro-labs/daemon/src/mcp/index.ts +186 -0
  137. package/runtime/node_modules/@metro-labs/daemon/src/mcp/member-tools.ts +72 -0
  138. package/runtime/node_modules/@metro-labs/daemon/src/mcp/permission-relay.ts +66 -0
  139. package/runtime/node_modules/@metro-labs/daemon/src/mcp/raw-get-stream.ts +207 -0
  140. package/runtime/node_modules/@metro-labs/daemon/src/mcp/request-identity.ts +47 -0
  141. package/runtime/node_modules/@metro-labs/daemon/src/mcp/session-registry.ts +172 -0
  142. package/runtime/node_modules/@metro-labs/daemon/src/mcp/session-route.ts +43 -0
  143. package/runtime/node_modules/@metro-labs/daemon/src/mcp/session.ts +215 -0
  144. package/runtime/node_modules/@metro-labs/daemon/src/mcp/tool-dispatch.ts +215 -0
  145. package/runtime/node_modules/@metro-labs/daemon/src/mcp/tool-schemas.ts +400 -0
  146. package/runtime/node_modules/@metro-labs/daemon/src/mcp/upload-tool.ts +66 -0
  147. package/runtime/node_modules/@metro-labs/daemon/src/monitor/api.ts +237 -0
  148. package/runtime/node_modules/@metro-labs/daemon/src/net/tunnel.ts +389 -0
  149. package/runtime/node_modules/@metro-labs/daemon/src/routes/bearer.ts +35 -0
  150. package/runtime/node_modules/@metro-labs/daemon/src/routes/body.ts +24 -0
  151. package/runtime/node_modules/@metro-labs/daemon/src/routes/http.ts +370 -0
  152. package/runtime/node_modules/@metro-labs/daemon/src/routes/local-mode.ts +210 -0
  153. package/runtime/node_modules/@metro-labs/daemon/src/routes/session-apis.ts +58 -0
  154. package/runtime/node_modules/@metro-labs/daemon/src/routes/session.ts +29 -0
  155. package/runtime/node_modules/@metro-labs/daemon/src/routes/threema-callback.ts +103 -0
  156. package/runtime/node_modules/@metro-labs/daemon/src/server/control.ts +65 -0
  157. package/runtime/node_modules/@metro-labs/daemon/src/server/machine.ts +80 -0
  158. package/runtime/node_modules/@metro-labs/daemon/src/server/owner.ts +48 -0
  159. package/runtime/node_modules/@metro-labs/daemon/src/server/update.ts +117 -0
  160. package/runtime/node_modules/@metro-labs/daemon/src/server.ts +2 -0
  161. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-inline.ts +100 -0
  162. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-interactive.ts +161 -0
  163. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-resolve.ts +202 -0
  164. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-session.ts +280 -0
  165. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-xmtp.ts +111 -0
  166. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach.ts +248 -0
  167. package/runtime/node_modules/@metro-labs/daemon/src/stations/materialize.ts +261 -0
  168. package/runtime/node_modules/@metro-labs/daemon/src/stations/registry.ts +37 -0
  169. package/runtime/node_modules/@metro-labs/daemon/src/stations/runtime-deps.ts +82 -0
  170. package/runtime/node_modules/@metro-labs/daemon/src/stations/supervisor-io.ts +97 -0
  171. package/runtime/node_modules/@metro-labs/daemon/src/stations/supervisor.ts +320 -0
  172. package/runtime/node_modules/@metro-labs/daemon/src/stations/threema-callbacks.ts +32 -0
  173. package/runtime/node_modules/@metro-labs/daemon/src/stations/train-call.ts +22 -0
  174. package/runtime/node_modules/@metro-labs/daemon/src/terminal/api.ts +97 -0
  175. package/runtime/node_modules/@metro-labs/daemon/src/terminal/socket.ts +123 -0
  176. package/runtime/node_modules/@metro-labs/daemon/src/terminal/tickets.ts +40 -0
  177. package/runtime/node_modules/@metro-labs/discord-bot/package.json +28 -0
  178. package/runtime/node_modules/@metro-labs/discord-bot/src/accounts.ts +118 -0
  179. package/runtime/node_modules/@metro-labs/discord-bot/src/actions.ts +388 -0
  180. package/runtime/node_modules/@metro-labs/discord-bot/src/api-base.ts +1 -0
  181. package/runtime/node_modules/@metro-labs/discord-bot/src/attachments.ts +29 -0
  182. package/runtime/node_modules/@metro-labs/discord-bot/src/format.ts +220 -0
  183. package/runtime/node_modules/@metro-labs/discord-bot/src/group-actions.ts +50 -0
  184. package/runtime/node_modules/@metro-labs/discord-bot/src/group.ts +115 -0
  185. package/runtime/node_modules/@metro-labs/discord-bot/src/index.ts +127 -0
  186. package/runtime/node_modules/@metro-labs/discord-bot/src/members.ts +215 -0
  187. package/runtime/node_modules/@metro-labs/discord-bot/src/send-files.ts +43 -0
  188. package/runtime/node_modules/@metro-labs/discord-bot/src/station.ts +19 -0
  189. package/runtime/node_modules/@metro-labs/discord-bot/src/verify.ts +82 -0
  190. package/runtime/node_modules/@metro-labs/discord-bot/src/voice-speak.ts +195 -0
  191. package/runtime/node_modules/@metro-labs/discord-bot/src/voice-transcribe.ts +292 -0
  192. package/runtime/node_modules/@metro-labs/discord-bot/src/voice.ts +197 -0
  193. package/runtime/node_modules/@metro-labs/discord-bot/src/wire.ts +5 -0
  194. package/runtime/node_modules/@metro-labs/http/package.json +29 -0
  195. package/runtime/node_modules/@metro-labs/http/src/api-error.ts +8 -0
  196. package/runtime/node_modules/@metro-labs/http/src/api-http.ts +106 -0
  197. package/runtime/node_modules/@metro-labs/http/src/cors.ts +29 -0
  198. package/runtime/node_modules/@metro-labs/http/src/mode-api.ts +32 -0
  199. package/runtime/node_modules/@metro-labs/http/src/return-to.ts +21 -0
  200. package/runtime/node_modules/@metro-labs/http/src/workos-token.ts +150 -0
  201. package/runtime/node_modules/@metro-labs/telegram/package.json +26 -0
  202. package/runtime/node_modules/@metro-labs/telegram/src/accounts.ts +80 -0
  203. package/runtime/node_modules/@metro-labs/telegram/src/actions.ts +254 -0
  204. package/runtime/node_modules/@metro-labs/telegram/src/attachments.ts +87 -0
  205. package/runtime/node_modules/@metro-labs/telegram/src/client.ts +77 -0
  206. package/runtime/node_modules/@metro-labs/telegram/src/format.ts +156 -0
  207. package/runtime/node_modules/@metro-labs/telegram/src/group.ts +261 -0
  208. package/runtime/node_modules/@metro-labs/telegram/src/history.ts +52 -0
  209. package/runtime/node_modules/@metro-labs/telegram/src/inbound.ts +78 -0
  210. package/runtime/node_modules/@metro-labs/telegram/src/index.ts +46 -0
  211. package/runtime/node_modules/@metro-labs/telegram/src/login.ts +166 -0
  212. package/runtime/node_modules/@metro-labs/telegram/src/media-actions.ts +80 -0
  213. package/runtime/node_modules/@metro-labs/telegram/src/members.ts +75 -0
  214. package/runtime/node_modules/@metro-labs/telegram/src/normalize.ts +22 -0
  215. package/runtime/node_modules/@metro-labs/telegram/src/reactions.ts +167 -0
  216. package/runtime/node_modules/@metro-labs/telegram/src/station.ts +24 -0
  217. package/runtime/node_modules/@metro-labs/telegram/src/types.ts +7 -0
  218. package/runtime/node_modules/@metro-labs/telegram/src/wire.ts +1 -0
  219. package/runtime/node_modules/@metro-labs/telegram-bot/package.json +25 -0
  220. package/runtime/node_modules/@metro-labs/telegram-bot/src/accounts.ts +120 -0
  221. package/runtime/node_modules/@metro-labs/telegram-bot/src/actions.ts +295 -0
  222. package/runtime/node_modules/@metro-labs/telegram-bot/src/attachments.ts +128 -0
  223. package/runtime/node_modules/@metro-labs/telegram-bot/src/format.ts +201 -0
  224. package/runtime/node_modules/@metro-labs/telegram-bot/src/index.ts +109 -0
  225. package/runtime/node_modules/@metro-labs/telegram-bot/src/media-actions.ts +166 -0
  226. package/runtime/node_modules/@metro-labs/telegram-bot/src/members.ts +47 -0
  227. package/runtime/node_modules/@metro-labs/telegram-bot/src/station.ts +17 -0
  228. package/runtime/node_modules/@metro-labs/telegram-bot/src/types.ts +58 -0
  229. package/runtime/node_modules/@metro-labs/telegram-bot/src/verify.ts +38 -0
  230. package/runtime/node_modules/@metro-labs/telegram-bot/src/wire.ts +3 -0
  231. package/runtime/node_modules/@metro-labs/threema/package.json +26 -0
  232. package/runtime/node_modules/@metro-labs/threema/src/accounts.ts +100 -0
  233. package/runtime/node_modules/@metro-labs/threema/src/actions.ts +223 -0
  234. package/runtime/node_modules/@metro-labs/threema/src/api.ts +130 -0
  235. package/runtime/node_modules/@metro-labs/threema/src/crypto.ts +132 -0
  236. package/runtime/node_modules/@metro-labs/threema/src/format.ts +123 -0
  237. package/runtime/node_modules/@metro-labs/threema/src/ids.ts +21 -0
  238. package/runtime/node_modules/@metro-labs/threema/src/index.ts +29 -0
  239. package/runtime/node_modules/@metro-labs/threema/src/station.ts +10 -0
  240. package/runtime/node_modules/@metro-labs/threema/src/verify.ts +117 -0
  241. package/runtime/node_modules/@metro-labs/webhook/package.json +23 -0
  242. package/runtime/node_modules/@metro-labs/webhook/src/station.ts +37 -0
  243. package/runtime/node_modules/@metro-labs/whatsapp/package.json +27 -0
  244. package/runtime/node_modules/@metro-labs/whatsapp/src/accounts.ts +66 -0
  245. package/runtime/node_modules/@metro-labs/whatsapp/src/ack.ts +101 -0
  246. package/runtime/node_modules/@metro-labs/whatsapp/src/actions.ts +190 -0
  247. package/runtime/node_modules/@metro-labs/whatsapp/src/attachments.ts +72 -0
  248. package/runtime/node_modules/@metro-labs/whatsapp/src/auth-state.ts +129 -0
  249. package/runtime/node_modules/@metro-labs/whatsapp/src/client.ts +347 -0
  250. package/runtime/node_modules/@metro-labs/whatsapp/src/delivery.ts +49 -0
  251. package/runtime/node_modules/@metro-labs/whatsapp/src/format.ts +138 -0
  252. package/runtime/node_modules/@metro-labs/whatsapp/src/inbound.ts +57 -0
  253. package/runtime/node_modules/@metro-labs/whatsapp/src/index.ts +40 -0
  254. package/runtime/node_modules/@metro-labs/whatsapp/src/keys.ts +59 -0
  255. package/runtime/node_modules/@metro-labs/whatsapp/src/logger.ts +60 -0
  256. package/runtime/node_modules/@metro-labs/whatsapp/src/login.ts +176 -0
  257. package/runtime/node_modules/@metro-labs/whatsapp/src/media.ts +84 -0
  258. package/runtime/node_modules/@metro-labs/whatsapp/src/normalize.ts +22 -0
  259. package/runtime/node_modules/@metro-labs/whatsapp/src/outbox.ts +38 -0
  260. package/runtime/node_modules/@metro-labs/whatsapp/src/parse.ts +185 -0
  261. package/runtime/node_modules/@metro-labs/whatsapp/src/resolve.ts +52 -0
  262. package/runtime/node_modules/@metro-labs/whatsapp/src/station.ts +18 -0
  263. package/runtime/node_modules/@metro-labs/whatsapp/src/token-store.ts +98 -0
  264. package/runtime/node_modules/@metro-labs/whatsapp/src/types.ts +6 -0
  265. package/runtime/node_modules/@metro-labs/whatsapp/src/wire.ts +5 -0
  266. package/runtime/node_modules/@metro-labs/xmtp/package.json +33 -0
  267. package/runtime/node_modules/@metro-labs/xmtp/src/accounts.ts +112 -0
  268. package/runtime/node_modules/@metro-labs/xmtp/src/actions-close.ts +110 -0
  269. package/runtime/node_modules/@metro-labs/xmtp/src/actions-conv.ts +299 -0
  270. package/runtime/node_modules/@metro-labs/xmtp/src/actions-meta.ts +157 -0
  271. package/runtime/node_modules/@metro-labs/xmtp/src/actions-push.ts +87 -0
  272. package/runtime/node_modules/@metro-labs/xmtp/src/actions.ts +375 -0
  273. package/runtime/node_modules/@metro-labs/xmtp/src/attachments.ts +107 -0
  274. package/runtime/node_modules/@metro-labs/xmtp/src/codecs.ts +171 -0
  275. package/runtime/node_modules/@metro-labs/xmtp/src/conv-helpers.ts +239 -0
  276. package/runtime/node_modules/@metro-labs/xmtp/src/emit-core.ts +55 -0
  277. package/runtime/node_modules/@metro-labs/xmtp/src/emit-payloads.ts +335 -0
  278. package/runtime/node_modules/@metro-labs/xmtp/src/emit.ts +80 -0
  279. package/runtime/node_modules/@metro-labs/xmtp/src/group-members.ts +34 -0
  280. package/runtime/node_modules/@metro-labs/xmtp/src/group.ts +56 -0
  281. package/runtime/node_modules/@metro-labs/xmtp/src/identity.ts +33 -0
  282. package/runtime/node_modules/@metro-labs/xmtp/src/index.ts +125 -0
  283. package/runtime/node_modules/@metro-labs/xmtp/src/labels.ts +157 -0
  284. package/runtime/node_modules/@metro-labs/xmtp/src/member-args.ts +40 -0
  285. package/runtime/node_modules/@metro-labs/xmtp/src/push.ts +349 -0
  286. package/runtime/node_modules/@metro-labs/xmtp/src/station.ts +13 -0
  287. package/runtime/node_modules/@metro-labs/xmtp/src/tools-handlers.ts +126 -0
  288. package/runtime/node_modules/@metro-labs/xmtp/src/tools.ts +212 -0
  289. package/runtime/node_modules/@metro-labs/xmtp/src/transcribe.ts +90 -0
  290. package/runtime/node_modules/@metro-labs/xmtp/src/verify.ts +84 -0
  291. package/runtime/node_modules/@metro-labs/xmtp/src/wire.ts +53 -0
  292. package/runtime/runtime.json +3 -0
  293. package/runtime/server.ts +1 -0
  294. package/runtime/stations.json +37 -0
  295. package/runtime/trains/.keep +0 -0
  296. package/LICENSE +0 -21
  297. package/README.md +0 -139
  298. package/dist/broker/claims.js +0 -144
  299. package/dist/broker/history-stream.js +0 -149
  300. package/dist/cli/config.js +0 -179
  301. package/dist/cli/index.js +0 -175
  302. package/dist/cli/messenger-api.js +0 -214
  303. package/dist/cli/messenger-transcribe.js +0 -43
  304. package/dist/cli/messenger-uploads.js +0 -116
  305. package/dist/cli/monitor-api.js +0 -205
  306. package/dist/cli/tail.js +0 -95
  307. package/dist/cli/util.js +0 -72
  308. package/dist/cli/webhook.js +0 -181
  309. package/dist/codex-rc/client.js +0 -225
  310. package/dist/codex-rc/protocol.js +0 -38
  311. package/dist/dispatcher/server.js +0 -122
  312. package/dist/dispatcher.js +0 -97
  313. package/dist/history.js +0 -143
  314. package/dist/ipc.js +0 -90
  315. package/dist/lines.js +0 -54
  316. package/dist/local-identity.js +0 -80
  317. package/dist/log.js +0 -15
  318. package/dist/paths.js +0 -114
  319. package/dist/trains/protocol.js +0 -99
  320. package/dist/trains/supervisor.js +0 -210
  321. package/dist/tunnel.js +0 -102
  322. package/docs/broker.md +0 -166
  323. package/docs/monitor.md +0 -241
  324. package/docs/uri-scheme.md +0 -127
  325. package/examples/README.md +0 -32
  326. package/examples/telegram.ts +0 -121
  327. package/skills/metro/SKILL.md +0 -110
@@ -0,0 +1,90 @@
1
+ import { errMsg } from '@metro-labs/core/log';
2
+ import { mintId, SELF_URI } from './wire.js';
3
+
4
+ type EmitInbound = (accountId: string, e: Record<string, unknown>) => void;
5
+
6
+ const WHISPER_BIN = process.env.METRO_WHISPER_BIN ?? 'whisper-cli';
7
+ const WHISPER_MODEL =
8
+ process.env.METRO_WHISPER_MODEL ??
9
+ `${process.env.HOME}/.cache/whisper-cpp/ggml-base.bin`;
10
+ const FFMPEG_BIN = process.env.METRO_FFMPEG_BIN ?? 'ffmpeg';
11
+
12
+ export async function transcribeAndEmit(
13
+ audio: Uint8Array,
14
+ line: string,
15
+ accountId: string,
16
+ sourceMsgId: string,
17
+ emitInbound: EmitInbound,
18
+ ): Promise<void> {
19
+ const {
20
+ existsSync: ex,
21
+ readFileSync: rf,
22
+ writeFileSync: wf,
23
+ unlinkSync,
24
+ mkdtempSync,
25
+ } = await import('node:fs');
26
+ const { tmpdir } = await import('node:os');
27
+ const path = await import('node:path');
28
+ const j = (...parts: string[]): string => path.join(...parts);
29
+ const { spawn } = await import('node:child_process');
30
+ if (!ex(WHISPER_MODEL)) return;
31
+ const dir = mkdtempSync(j(tmpdir(), 'xmtp-tx-'));
32
+ const inFile = j(dir, 'in.m4a');
33
+ const wav = j(dir, 'in.wav');
34
+ const out = j(dir, 'in');
35
+ const run = (bin: string, args: string[]): Promise<void> =>
36
+ new Promise((res, rej) => {
37
+ const p = spawn(bin, args, { stdio: 'ignore' });
38
+ p.on('error', rej);
39
+ p.on('exit', (c) => {
40
+ if (c === 0) res();
41
+ else rej(new Error(`${bin} ${String(c)}`));
42
+ });
43
+ });
44
+ try {
45
+ wf(inFile, audio);
46
+ await run(FFMPEG_BIN, [
47
+ '-y',
48
+ '-i',
49
+ inFile,
50
+ '-ar',
51
+ '16000',
52
+ '-ac',
53
+ '1',
54
+ wav,
55
+ ]);
56
+ await run(WHISPER_BIN, [
57
+ '-m',
58
+ WHISPER_MODEL,
59
+ '-f',
60
+ wav,
61
+ '--output-txt',
62
+ '-of',
63
+ out,
64
+ ]);
65
+ const text = rf(`${out}.txt`, 'utf8').trim();
66
+ if (!text) return;
67
+ emitInbound(accountId, {
68
+ id: mintId(),
69
+ ts: new Date().toISOString(),
70
+ station: 'xmtp',
71
+ line,
72
+ from: SELF_URI,
73
+ text: `🎙️ ${text}`,
74
+ payload: {
75
+ contentType: 'transcript',
76
+ transcribeFor: sourceMsgId,
77
+ transcript: text,
78
+ },
79
+ });
80
+ } catch (err) {
81
+ process.stderr.write(`xmtp transcribe failed: ${errMsg(err)}\n`);
82
+ } finally {
83
+ for (const f of [inFile, wav, `${out}.txt`]) {
84
+ try {
85
+ unlinkSync(f);
86
+ } catch {
87
+ }
88
+ }
89
+ }
90
+ }
@@ -0,0 +1,84 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { Client, type ClientOptions, type Signer } from '@xmtp/node-sdk';
4
+ import { expandHome, signerFor, XMTP_ENV } from './identity.js';
5
+
6
+ export class XmtpVerifyError extends Error {}
7
+
8
+ export interface XmtpVerified {
9
+ inboxId: string;
10
+ address: string;
11
+ installationId: string;
12
+ dbPath: string;
13
+ }
14
+
15
+ interface RegisteredClient {
16
+ inboxId: string;
17
+ installationId: string;
18
+ isRegistered: boolean;
19
+ }
20
+
21
+ export type CreateXmtpClient = (
22
+ signer: Signer,
23
+ dbPath: string,
24
+ ) => Promise<RegisteredClient>;
25
+
26
+ const openInbox: CreateXmtpClient = (signer, dbPath) => {
27
+ const options: ClientOptions = { env: XMTP_ENV, dbPath };
28
+ return Client.create(signer, options);
29
+ };
30
+
31
+ const reason = (err: unknown): string =>
32
+ err instanceof Error && err.message !== '' ? err.message : 'no reason given';
33
+
34
+ export async function verifyXmtpKey(
35
+ privateKey: string,
36
+ dbPath: string,
37
+ create: CreateXmtpClient = openInbox,
38
+ ): Promise<XmtpVerified> {
39
+ let signer: Signer;
40
+ let address: string;
41
+ try {
42
+ ({ signer, address } = signerFor(privateKey));
43
+ } catch {
44
+ throw new XmtpVerifyError('that is not a usable XMTP private key');
45
+ }
46
+ const resolved = expandHome(dbPath);
47
+ mkdirSync(dirname(resolved), { recursive: true });
48
+ const client = await create(signer, resolved).catch((err: unknown) => {
49
+ throw new XmtpVerifyError(
50
+ `XMTP would not open an inbox for that key: ${reason(err)}`,
51
+ );
52
+ });
53
+ if (!client.isRegistered)
54
+ throw new XmtpVerifyError('XMTP did not register an inbox for that key');
55
+ if (client.inboxId === '')
56
+ throw new XmtpVerifyError('XMTP returned no inbox id for that key');
57
+ return {
58
+ inboxId: client.inboxId,
59
+ address,
60
+ installationId: client.installationId,
61
+ dbPath: resolved,
62
+ };
63
+ }
64
+
65
+ async function runCli(): Promise<void> {
66
+ let out: Record<string, unknown>;
67
+ try {
68
+ const input = JSON.parse(readFileSync(0, 'utf8')) as {
69
+ privateKey?: unknown;
70
+ dbPath?: unknown;
71
+ };
72
+ if (typeof input.privateKey !== 'string' || typeof input.dbPath !== 'string')
73
+ throw new XmtpVerifyError('xmtp verify needs a privateKey and a dbPath');
74
+ out = { ok: true, ...(await verifyXmtpKey(input.privateKey, input.dbPath)) };
75
+ } catch (err) {
76
+ out = { ok: false, error: reason(err) };
77
+ }
78
+ writeFileSync(1, `${JSON.stringify(out)}\n`);
79
+ }
80
+
81
+ if (import.meta.main) {
82
+ await runCli();
83
+ process.exit(0);
84
+ }
@@ -0,0 +1,53 @@
1
+ export { emit, respond, mintId } from '@metro-labs/core/stations/station-runtime';
2
+
3
+ export const SELF_URI = process.env.METRO_SELF_URI ?? '';
4
+
5
+ const UID_MAP_MAX = 5000;
6
+ const uidToXmtp = new Map<string, string>();
7
+
8
+ const INBOX_ETH_CACHE_MAX = 5000;
9
+ export const inboxEthCache = new Map<string, string>();
10
+
11
+ export function cacheInboxEth(inboxId: string, eth: string): void {
12
+ inboxEthCache.set(inboxId, eth);
13
+ if (inboxEthCache.size > INBOX_ETH_CACHE_MAX) {
14
+ const oldest = inboxEthCache.keys().next().value;
15
+ if (oldest !== undefined) inboxEthCache.delete(oldest);
16
+ }
17
+ }
18
+
19
+ export function rememberUid(
20
+ uid: string | undefined,
21
+ xmtpId: string | undefined,
22
+ ): void {
23
+ if (!uid || !xmtpId || !uid.startsWith('msg_')) return;
24
+ uidToXmtp.set(uid, xmtpId);
25
+ if (uidToXmtp.size > UID_MAP_MAX) {
26
+ const oldest = uidToXmtp.keys().next().value;
27
+ if (oldest !== undefined) uidToXmtp.delete(oldest);
28
+ }
29
+ }
30
+
31
+ export function resolveMsgId(rawId: string): string {
32
+ if (!rawId.startsWith('msg_')) return rawId;
33
+ const mapped = uidToXmtp.get(rawId);
34
+ if (mapped) return mapped;
35
+ throw new Error(
36
+ `could not resolve universal id ${rawId} to an xmtp message id ` +
37
+ '(not seen by this train; pass the raw xmtp message_id)',
38
+ );
39
+ }
40
+
41
+ const SENT_MAX = 5000;
42
+ const sentIds = new Set<string>();
43
+
44
+ export function rememberSent(xmtpId: string | undefined): void {
45
+ if (!xmtpId) return;
46
+ sentIds.add(xmtpId);
47
+ if (sentIds.size > SENT_MAX) {
48
+ const oldest = sentIds.values().next().value;
49
+ if (oldest !== undefined) sentIds.delete(oldest);
50
+ }
51
+ }
52
+
53
+ export const sentByMe = (xmtpId: string): boolean => sentIds.has(xmtpId);
@@ -0,0 +1,3 @@
1
+ {
2
+ "version": "0.1.0-beta.151"
3
+ }
@@ -0,0 +1 @@
1
+ import './node_modules/@metro-labs/daemon/src/server.ts';
@@ -0,0 +1,37 @@
1
+ {
2
+ "core": {
3
+ "@modelcontextprotocol/sdk": "^1.12.0",
4
+ "pino": "^9.5.0",
5
+ "pino-pretty": "^13.1.3",
6
+ "ws": "^8.18.0",
7
+ "zod": "^3.23.8"
8
+ },
9
+ "stations": {
10
+ "xmtp": {
11
+ "@xmtp/content-type-primitives": "^3.0.1",
12
+ "@xmtp/content-type-reaction": "^2.0.2",
13
+ "@xmtp/content-type-remote-attachment": "^2.0.4",
14
+ "@xmtp/content-type-reply": "^2.0.3",
15
+ "@xmtp/content-type-wallet-send-calls": "^2.0.0",
16
+ "@xmtp/node-bindings": "1.9.1",
17
+ "@xmtp/node-sdk": "^6.0.0",
18
+ "viem": "^2.52.2"
19
+ },
20
+ "telegram-bot": {},
21
+ "telegram": {
22
+ "@mtcute/bun": "0.30.1"
23
+ },
24
+ "discord-bot": {
25
+ "@discordjs/voice": "^0.19.2",
26
+ "discord.js": "^14.26.4",
27
+ "prism-media": "^1.3.5"
28
+ },
29
+ "whatsapp": {
30
+ "baileys": "7.0.0-rc14"
31
+ },
32
+ "threema": {
33
+ "tweetnacl": "^1.0.3"
34
+ },
35
+ "webhook": {}
36
+ }
37
+ }
File without changes
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Stage Labs
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/README.md DELETED
@@ -1,139 +0,0 @@
1
- # Metro
2
-
3
- [![npm](https://img.shields.io/npm/v/@stage-labs/metro/beta?label=npm&color=cb3837)](https://www.npmjs.com/package/@stage-labs/metro)
4
- [![lines of code](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fapi.codetabs.com%2Fv1%2Floc%2F%3Fgithub%3Dbonustrack%2Fmetro%26ignored%3Dapps%2Ctest&query=%24%5B0%5D.linesOfCode&label=lines%20of%20TypeScript&color=blue)](https://github.com/bonustrack/metro)
5
-
6
- > **Event-interception wire. Supervises train subprocesses, multiplexes their stdout into one
7
- > JSON event stream, routes outbound action calls back via stdin. Per-platform code lives in
8
- > train scripts under `~/.metro/trains/` — outside this repo — written by the user (or agent)
9
- > on demand.**
10
-
11
- Metro is not a framework with platform connectors. Metro is the wire.
12
-
13
- ```
14
- [Claude Code session]
15
-
16
- $ metro & # backgrounded
17
- $ Monitor( … metro's stdout … )
18
-
19
- >>> {"kind":"inbound","station":"discord","line":"metro://discord/123…","message_id":"9876",
20
- "text":"@metro 5xx spike on /v1/sync — look?",
21
- "payload":{"channelId":"123…","guildId":"456…","content":"<@…> 5xx spike…",
22
- "mentions":{"users":["<bot-id>"],"roles":[],"everyone":false},…}}
23
-
24
- [I'd grep services/sync.ts, then…]
25
- Bash: metro call discord send '{"line":"metro://discord/123…","text":"three deploys in the last 24h…","replyTo":"9876"}'
26
- ```
27
-
28
- You own streaming, tool calls, and reply timing. Metro is the wire.
29
-
30
- ---
31
-
32
- ## Quickstart
33
-
34
- ```bash
35
- npm install -g @stage-labs/metro@beta # or: bun add -g @stage-labs/metro@beta
36
-
37
- # One-time train setup (Telegram — no npm deps needed; uses native fetch)
38
- mkdir -p ~/.metro && cd ~/.metro && bun init -y
39
- cp $(npm root -g)/@stage-labs/metro/examples/telegram.ts ~/.metro/trains/
40
- echo 'TELEGRAM_BOT_TOKEN=your-token' >> ~/.metro/.env
41
-
42
- metro doctor # verify
43
- metro # run the daemon
44
- ```
45
-
46
- For Discord, copy the same `telegram.ts` and port it — swap the API base for
47
- `https://discord.com/api/v10` with `Authorization: Bot $TOKEN`, install
48
- `discord.js` for the gateway (`cd ~/.metro && bun add discord.js`), and keep
49
- the same envelope + `op:"call"` ↔ `op:"response"` protocol. See
50
- [`examples/README.md`](./examples/README.md) for the wire-format reference.
51
-
52
- Requires **Bun ≥ 1.3** (trains run under `bun run`). Metro core itself works under Node ≥ 22.
53
-
54
- ---
55
-
56
- ## Architecture
57
-
58
- ```
59
- ~/.metro/trains/discord.ts ──> stdout JSON ──┐
60
- ~/.metro/trains/telegram.ts ─> stdout JSON ──┤
61
- ~/.metro/trains/<anything>.ts ─> stdout ─────┼──> metro daemon ──> stdout (Monitor / Codex push)
62
- │ history.jsonl
63
- HTTP /wh/<id> (builtin webhook receiver) ───┤
64
- IPC `notify` (builtin cross-user channel) ─┘
65
-
66
- metro call discord send {…} ──> IPC ──> daemon ──> train stdin ──> response ──> CLI stdout
67
- ```
68
-
69
- Every event metro emits is a `HistoryEntry`. Trains produce the full envelope; metro
70
- enriches `id`/`display` and appends to `history.jsonl`. Outbound action calls are
71
- train-defined — metro core knows the protocol (`{op:"call", id, action, args}` → `{op:"response", id, result|error}`),
72
- not what any specific action does.
73
-
74
- ---
75
-
76
- ## Train protocol
77
-
78
- **Inbound (train → metro stdout)** — one JSON line per event (wire fields are `snake_case`):
79
-
80
- ```json
81
- {"kind":"inbound","station":"discord","line":"metro://discord/123","from":"metro://discord/user/456","from_name":"alice","message_id":"789","text":"hi","is_private":false,"ts":"2026-05-17T18:00:00Z","payload":{...}}
82
- ```
83
-
84
- **Outbound (metro → train stdin)** — one JSON line per action call:
85
-
86
- ```json
87
- {"op":"call","id":"req_abc","action":"send","args":{"line":"metro://discord/123","text":"hi"}}
88
- ```
89
-
90
- Train responds on stdout:
91
-
92
- ```json
93
- {"op":"response","id":"req_abc","result":{"messageId":"999"}}
94
- ```
95
-
96
- See [`examples/telegram.ts`](./examples/telegram.ts) (a self-contained ~110 LOC reference train) and [`examples/README.md`](./examples/README.md) for the full protocol + Discord port notes.
97
-
98
- ---
99
-
100
- ## CLI
101
-
102
- ```
103
- metro # start the daemon (foreground)
104
- metro trains list # supervised trains + state
105
- metro trains new <name> # scaffold ~/.metro/trains/<name>.ts from the example
106
- metro trains restart <name> # kill + respawn a train (resets backoff)
107
- metro call <train> <action> <args> # forward an action call; args = JSON / @file / - / string
108
- metro tail [--as=<user-uri>] [--follow] # subscribe to the event log; claim-aware
109
- metro history [--limit=50] [--line=…] # recent history (newest first), filterable
110
- metro lines # recently-seen conversations
111
- metro claim <line> # take exclusive ownership of a line
112
- metro release <line> # release
113
- metro claims # print the claims map
114
- metro webhook add <label> [--secret=…] # add an HTTP receive endpoint
115
- metro webhook list | remove <id> # manage endpoints
116
- metro tunnel setup <name> <hostname> # configure a Cloudflare named tunnel
117
- metro tunnel status # show current tunnel config
118
- metro setup [skill [clear]] # status; or install/remove the skill into ~/.claude / ~/.codex
119
- metro doctor # health check (trains, deps, tunnel, webhooks, env vars)
120
- metro update # upgrade in place
121
- ```
122
-
123
- No more `metro send / reply / edit / react / download / fetch` — outbound is always
124
- `metro call <train> <action> <args>`, with action names defined by the train.
125
-
126
- ---
127
-
128
- ## State
129
-
130
- - `~/.metro/trains/` — your train scripts
131
- - `~/.metro/.env` — your credentials (trains read these)
132
- - `~/.metro/package.json` — `bun add` here for train deps
133
- - `$METRO_STATE_DIR` (default `~/.cache/metro/`) — history, claims, cursors, monitor data
134
-
135
- ---
136
-
137
- ## License
138
-
139
- MIT
@@ -1,144 +0,0 @@
1
- /** Claims map: per-line owner registry under an O_EXCL lockfile. */
2
- import { closeSync, existsSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
3
- import { join } from 'node:path';
4
- import { log } from '../log.js';
5
- import { STATE_DIR } from '../paths.js';
6
- import { Line } from '../lines.js';
7
- export const CLAIMS_FILE = join(STATE_DIR, 'claims.json');
8
- const CLAIMS_LOCK = join(STATE_DIR, 'claims.json.lock');
9
- export const HISTORY_FILE = join(STATE_DIR, 'history.jsonl');
10
- /** Read claims.json. Returns empty map if missing or malformed (retries once on race). */
11
- export function readClaims() {
12
- if (!existsSync(CLAIMS_FILE))
13
- return {};
14
- for (let attempt = 0; attempt < 2; attempt++) {
15
- try {
16
- return JSON.parse(readFileSync(CLAIMS_FILE, 'utf8'));
17
- }
18
- catch { /* race with writer — retry once */ }
19
- }
20
- log.warn({ path: CLAIMS_FILE }, 'claims: malformed, treating as empty');
21
- return {};
22
- }
23
- /** Mutate claims under an O_EXCL lockfile. Throws if another writer holds the lock past timeout. */
24
- function withClaimsLock(fn) {
25
- const deadline = Date.now() + 2_000;
26
- while (true) {
27
- try {
28
- closeSync(openSync(CLAIMS_LOCK, 'wx'));
29
- break;
30
- }
31
- catch (err) {
32
- if (err.code !== 'EEXIST')
33
- throw err;
34
- if (Date.now() > deadline)
35
- throw new Error('claims.json: lock contention (held >2s)');
36
- }
37
- }
38
- try {
39
- const next = readClaims();
40
- const result = fn(next);
41
- /** atomic publish: tmpfile + rename so readers never see a half-written file */
42
- const tmp = `${CLAIMS_FILE}.tmp.${process.pid}`;
43
- writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n');
44
- renameSync(tmp, CLAIMS_FILE);
45
- return result;
46
- }
47
- finally {
48
- try {
49
- unlinkSync(CLAIMS_LOCK);
50
- }
51
- catch { /* ignore */ }
52
- }
53
- }
54
- export function claimLine(line, owner) {
55
- return withClaimsLock(m => { m[line] = owner; return m; });
56
- }
57
- export function releaseLine(line) {
58
- return withClaimsLock(m => {
59
- const released = line in m;
60
- delete m[line];
61
- return { released, claims: m };
62
- });
63
- }
64
- /** Classify a chat line as DM/group/unknown for the auto-claim group-skip rule. */
65
- /** TG: chatId<0⇒group. Discord: peek payload.guildId on most-recent inbound. Claude/Codex⇒dm. */
66
- export function classifyLine(line) {
67
- const station = Line.station(line);
68
- if (station === 'telegram') {
69
- const parsed = Line.parseTelegram(line);
70
- if (!parsed)
71
- return 'unknown';
72
- return parsed.chatId < 0 ? 'group' : 'dm';
73
- }
74
- if (station === 'claude' || station === 'codex')
75
- return 'dm';
76
- if (station === 'webhook')
77
- return 'group';
78
- if (station === 'discord') {
79
- /** Lazy tail-scan of history.jsonl to avoid a static dep on the history filter helpers. */
80
- const recent = readRecentInbound(line);
81
- if (!recent)
82
- return 'unknown';
83
- const payload = recent.payload;
84
- if (!payload || !('guildId' in payload)) {
85
- /** Older entries may not have a guildId — fall back to the `to` field: DMs route to a user URI. */
86
- if (recent.to && recent.to !== recent.line)
87
- return 'dm';
88
- return 'unknown';
89
- }
90
- return payload.guildId == null ? 'dm' : 'group';
91
- }
92
- return 'unknown';
93
- }
94
- /** Most-recent inbound (from-someone-else) on `line`. Walks `history.jsonl` from the tail. */
95
- function readRecentInbound(line) {
96
- if (!existsSync(HISTORY_FILE))
97
- return undefined;
98
- const lines = readFileSync(HISTORY_FILE, 'utf8').split('\n');
99
- for (let i = lines.length - 1; i >= 0; i--) {
100
- if (!lines[i].trim())
101
- continue;
102
- try {
103
- const e = JSON.parse(lines[i]);
104
- if (e.line === line && !Line.isLocal(e.from))
105
- return e;
106
- }
107
- catch { /* skip */ }
108
- }
109
- return undefined;
110
- }
111
- /** Per-line decision: should auto-claim run on a successful outbound? */
112
- function shouldAutoClaim(line, kind) {
113
- const station = Line.station(line);
114
- /** Webhook lines are a broadcast stream — claiming one is a footgun. */
115
- if (station === 'webhook')
116
- return { ok: false, reason: 'webhook' };
117
- /** Claude/Codex cross-user lines are 1:1 by construction — always safe. */
118
- if (station === 'claude' || station === 'codex')
119
- return { ok: true };
120
- if (kind === 'group')
121
- return { ok: false, reason: 'group' };
122
- return { ok: true };
123
- }
124
- export function tryAutoClaim(line, owner, opts = {}) {
125
- if (!opts.force) {
126
- const decision = shouldAutoClaim(line, opts.lineKind ?? 'unknown');
127
- if (!decision.ok)
128
- return { status: decision.reason, line };
129
- }
130
- try {
131
- return withClaimsLock(m => {
132
- const existing = m[line];
133
- if (existing && existing !== owner)
134
- return { status: 'skipped', existing };
135
- if (existing === owner)
136
- return { status: 'kept', owner };
137
- m[line] = owner;
138
- return { status: 'claimed', owner };
139
- });
140
- }
141
- catch (err) {
142
- return { status: 'error', error: err.message };
143
- }
144
- }