@stage-labs/metro 0.1.0-beta.115 → 0.1.0-beta.116

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stage-labs/metro",
3
- "version": "0.1.0-beta.115",
3
+ "version": "0.1.0-beta.116",
4
4
  "description": "The metro command line. Sign in once per machine, then hand your MCP connector list to Claude Code without the credentials touching disk, argv or shell history.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "metro",
3
- "version": "0.1.0-beta.115",
3
+ "version": "0.1.0-beta.116",
4
4
  "description": "Metro for Claude Code, installed by the metro daemon on this machine: every connector the agent holds as its own MCP server relayed through the daemon, the orchestrator-only guard on the main thread, the standing rules loaded at each session start, and a refresh skill for when the daemon could not keep the server list current. No vendor credential ever sits in a config file.",
5
5
  "author": {
6
6
  "name": "Bonustrack",
@@ -97,6 +97,7 @@ export interface Station {
97
97
  hasTrain: boolean;
98
98
  messageVerbs: ReadonlySet<Verb>;
99
99
  groupOps?: ReadonlySet<GroupOp>;
100
+ resolvesSenders?: boolean;
100
101
  attachmentMode: AttachmentMode;
101
102
  sendAttachments?(
102
103
  line: string,
@@ -0,0 +1,70 @@
1
+ import { isStationName, parseAccountId } from './account-attach.js';
2
+ import type { StationName } from '@metro-labs/core/station-names';
3
+ import { ATTACH_ID_RE } from '../stations/attach-session.js';
4
+
5
+ export type AccountRoute =
6
+ | { kind: 'start' }
7
+ | { kind: 'session'; attachId: string }
8
+ | { kind: 'step'; attachId: string }
9
+ | { kind: 'account'; station: StationName; accountId: string }
10
+ | { kind: 'allowlist'; station: StationName; accountId: string }
11
+ | { kind: 'senders'; station: StationName; accountId: string }
12
+ | { kind: 'resolve'; station: StationName; accountId: string }
13
+ | { kind: 'enabled'; station: StationName; accountId: string };
14
+
15
+ const ROUTE_METHODS: Record<AccountRoute['kind'], string[]> = {
16
+ start: ['POST'],
17
+ session: ['GET', 'DELETE'],
18
+ step: ['POST'],
19
+ account: ['DELETE'],
20
+ allowlist: ['PUT'],
21
+ senders: ['GET'],
22
+ resolve: ['GET'],
23
+ enabled: ['PUT'],
24
+ };
25
+
26
+ const SUB_ROUTES = ['allowlist', 'senders', 'resolve', 'enabled'] as const;
27
+
28
+ type SubRoute = (typeof SUB_ROUTES)[number];
29
+
30
+ const isSubRoute = (value: string | undefined): value is SubRoute =>
31
+ SUB_ROUTES.some((sub) => sub === value);
32
+
33
+ function twoSegmentRoute(head: string, tail: string): AccountRoute | null {
34
+ if (ATTACH_ID_RE.test(head))
35
+ return tail === 'step' ? { kind: 'step', attachId: head } : null;
36
+ if (!isStationName(head)) return null;
37
+ const accountId = parseAccountId(tail);
38
+ return accountId === null ? null : { kind: 'account', station: head, accountId };
39
+ }
40
+
41
+ function accountSubRoute(
42
+ head: string,
43
+ tail: string,
44
+ sub: string | undefined,
45
+ ): AccountRoute | null {
46
+ if (!isStationName(head) || !isSubRoute(sub)) return null;
47
+ const accountId = parseAccountId(tail);
48
+ return accountId === null ? null : { kind: sub, station: head, accountId };
49
+ }
50
+
51
+ export function accountRoute(rest: string[]): AccountRoute | null {
52
+ const [head, tail] = rest;
53
+ if (head === undefined) return null;
54
+ if (rest.length === 1)
55
+ return head === 'start'
56
+ ? { kind: 'start' }
57
+ : ATTACH_ID_RE.test(head)
58
+ ? { kind: 'session', attachId: head }
59
+ : null;
60
+ if (rest.length === 3 && tail !== undefined) return accountSubRoute(head, tail, rest[2]);
61
+ if (rest.length !== 2 || tail === undefined) return null;
62
+ return twoSegmentRoute(head, tail);
63
+ }
64
+
65
+ export function accountRouteAllows(
66
+ route: AccountRoute,
67
+ method: string | undefined,
68
+ ): boolean {
69
+ return ROUTE_METHODS[route.kind].includes(method ?? '');
70
+ }
@@ -10,11 +10,9 @@ import {
10
10
  sendJson,
11
11
  type ApiSession,
12
12
  } from '@metro-labs/http/api-http';
13
- import {
14
- isStationName,
15
- parseAccountId,
16
- type AccountRef,
17
- } from './account-attach.js';
13
+ import { type AccountRef } from './account-attach.js';
14
+ import { type AccountRoute } from './account-routes.js';
15
+ import { stationByName } from '../stations/registry.js';
18
16
  import type { StationName } from '@metro-labs/core/station-names';
19
17
  import {
20
18
  ATTACHABLE_STATIONS,
@@ -30,7 +28,6 @@ import {
30
28
  type InteractiveStation,
31
29
  } from '../stations/attach-interactive.js';
32
30
  import {
33
- ATTACH_ID_RE,
34
31
  type AttachOwner,
35
32
  type AttachView,
36
33
  } from '../stations/attach-session.js';
@@ -75,6 +72,11 @@ export interface AccountApiDeps {
75
72
  allowlist: string[],
76
73
  ) => Promise<string[]>;
77
74
  recentSenders: (station: StationName, accountId: string) => RecentSender[];
75
+ resolveSender: (
76
+ station: StationName,
77
+ accountId: string,
78
+ query: string,
79
+ ) => Promise<unknown>;
78
80
  setAccountEnabled: (
79
81
  subject: string,
80
82
  agentId: string,
@@ -84,63 +86,28 @@ export interface AccountApiDeps {
84
86
  ) => Promise<boolean>;
85
87
  }
86
88
 
87
- export type AccountRoute =
88
- | { kind: 'start' }
89
- | { kind: 'session'; attachId: string }
90
- | { kind: 'step'; attachId: string }
91
- | { kind: 'account'; station: StationName; accountId: string }
92
- | { kind: 'allowlist'; station: StationName; accountId: string }
93
- | { kind: 'senders'; station: StationName; accountId: string }
94
- | { kind: 'enabled'; station: StationName; accountId: string };
95
-
96
89
  export const ATTACHABLE: string[] = [
97
90
  ...ATTACHABLE_STATIONS,
98
91
  ...INTERACTIVE_STATIONS,
99
92
  ];
100
93
 
101
- const ROUTE_METHODS: Record<AccountRoute['kind'], string[]> = {
102
- start: ['POST'],
103
- session: ['GET', 'DELETE'],
104
- step: ['POST'],
105
- account: ['DELETE'],
106
- allowlist: ['PUT'],
107
- senders: ['GET'],
108
- enabled: ['PUT'],
109
- };
110
-
111
- function twoSegmentRoute(head: string, tail: string): AccountRoute | null {
112
- if (ATTACH_ID_RE.test(head))
113
- return tail === 'step' ? { kind: 'step', attachId: head } : null;
114
- if (!isStationName(head)) return null;
115
- const accountId = parseAccountId(tail);
116
- return accountId === null ? null : { kind: 'account', station: head, accountId };
117
- }
118
-
119
- export function accountRoute(rest: string[]): AccountRoute | null {
120
- const [head, tail] = rest;
121
- if (head === undefined) return null;
122
- if (rest.length === 1)
123
- return head === 'start'
124
- ? { kind: 'start' }
125
- : ATTACH_ID_RE.test(head)
126
- ? { kind: 'session', attachId: head }
127
- : null;
128
- if (rest.length === 3 && tail !== undefined) return accountSubRoute(head, tail, rest[2]);
129
- if (rest.length !== 2 || tail === undefined) return null;
130
- return twoSegmentRoute(head, tail);
94
+ function lookupQuery(req: IncomingMessage): string {
95
+ const params = new URLSearchParams((req.url ?? '').split('?')[1] ?? '');
96
+ return (params.get('q') ?? '').trim();
131
97
  }
132
98
 
133
- function accountSubRoute(head: string, tail: string, sub: string | undefined): AccountRoute | null {
134
- if (!isStationName(head) || (sub !== 'allowlist' && sub !== 'senders' && sub !== 'enabled')) return null;
135
- const accountId = parseAccountId(tail);
136
- return accountId === null ? null : { kind: sub, station: head, accountId };
137
- }
138
-
139
- export function accountRouteAllows(
140
- route: AccountRoute,
141
- method: string | undefined,
142
- ): boolean {
143
- return ROUTE_METHODS[route.kind].includes(method ?? '');
99
+ async function handleResolve(
100
+ req: IncomingMessage,
101
+ res: ServerResponse,
102
+ deps: AccountApiDeps,
103
+ target: { station: StationName; accountId: string },
104
+ ): Promise<void> {
105
+ if (stationByName(target.station)?.resolvesSenders !== true)
106
+ throw new ApiError(`metro cannot look a sender up on ${target.station}`, 400);
107
+ const query = lookupQuery(req);
108
+ if (query === '') throw new ApiError('a number to look up is required', 400);
109
+ const found = await deps.resolveSender(target.station, target.accountId, query);
110
+ sendJson(req, res, 200, found);
144
111
  }
145
112
 
146
113
  async function activate(
@@ -374,6 +341,7 @@ async function dispatchRoute(
374
341
  return handleStep(req, res, deps, ownerOf(session, agentId), route.attachId);
375
342
  if (route.kind === 'allowlist') return handleAllowlist(req, res, deps, session, agentId, route);
376
343
  if (route.kind === 'enabled') return handleEnabled(req, res, deps, session, agentId, route);
344
+ if (route.kind === 'resolve') return handleResolve(req, res, deps, route);
377
345
  if (route.kind === 'senders') {
378
346
  sendJson(req, res, 200, { senders: deps.recentSenders(route.station, route.accountId) });
379
347
  return;
@@ -11,14 +11,12 @@ import {
11
11
  sendJson,
12
12
  type ApiSession,
13
13
  } from '@metro-labs/http/api-http';
14
+ import { ATTACHABLE, handleAccountRoute, type AccountApiDeps } from './accounts-api.js';
14
15
  import {
15
16
  accountRoute,
16
17
  accountRouteAllows,
17
- ATTACHABLE,
18
- handleAccountRoute,
19
- type AccountApiDeps,
20
18
  type AccountRoute,
21
- } from './accounts-api.js';
19
+ } from './account-routes.js';
22
20
  import {
23
21
  type AgentSummary,
24
22
  type CreatedAgent,
@@ -2,6 +2,7 @@ import { ApiError } from '@metro-labs/http/api-error';
2
2
  import { errMsg, log } from '@metro-labs/core/log';
3
3
  import { AttachSessions } from '../stations/attach-session.js';
4
4
  import { recentSenders } from '../agents/senders.js';
5
+ import { forwardTrainCall } from '../stations/train-call.js';
5
6
  import { syncPluginServers } from '../connectors/plugin-sync.js';
6
7
  import type { AgentApiDeps } from '../agents/api.js';
7
8
  import { ATTACHABLE, type AccountApiDeps } from '../agents/accounts-api.js';
@@ -106,6 +107,7 @@ function agentApi(deps: LocalModeDeps): AgentApiDeps {
106
107
  setAllowlist: localSetAllowlist,
107
108
  setAccountEnabled: localSetAccountEnabled,
108
109
  recentSenders,
110
+ resolveSender,
109
111
  reloadAgents: deps.reloadAgents,
110
112
  };
111
113
  }
@@ -179,6 +181,27 @@ function localModeInfo(): ModeInfo {
179
181
  return { mode: 'local', owner: localOwner(), project: LOCAL_PROJECT_ID, version: METRO_VERSION };
180
182
  }
181
183
 
184
+ async function resolveSender(
185
+ station: StationName,
186
+ accountId: string,
187
+ query: string,
188
+ ): Promise<unknown> {
189
+ let response;
190
+ try {
191
+ response = await forwardTrainCall(station, 'resolve_sender', {
192
+ account: accountId,
193
+ query,
194
+ });
195
+ } catch (err) {
196
+ throw new ApiError(
197
+ `metro could not reach the ${station} train: ${errMsg(err)}`,
198
+ 503,
199
+ );
200
+ }
201
+ if (response.error !== undefined) throw new ApiError(response.error, 400);
202
+ return response.result;
203
+ }
204
+
182
205
  export function localSessionApis(deps: LocalModeDeps): SessionApis {
183
206
  allowLocalConnectors(true);
184
207
  return {
@@ -9,6 +9,7 @@ import {
9
9
  } from '@metro-labs/core/stations/station-runtime';
10
10
  import { accountFor, accounts, targetOf } from './accounts.js';
11
11
  import { normalizeWhatsApp } from './normalize.js';
12
+ import { phoneNumberOf, senderLookup } from './resolve.js';
12
13
  import type { WAClient } from './client.js';
13
14
 
14
15
  type Args = Record<string, unknown>;
@@ -162,6 +163,16 @@ function makeAccounts(clientFor: ClientFor): StationHandler {
162
163
  };
163
164
  }
164
165
 
166
+ function makeResolveSender(clientFor: ClientFor): StationHandler {
167
+ return async (id, args) => {
168
+ const accountId = accountFor({ account: str(args.account) });
169
+ const query = str(args.query) ?? '';
170
+ const number = phoneNumberOf(query);
171
+ const found = await guard(() => clientFor(accountId).lookupSender(number));
172
+ respond(id, { result: { account: accountId, ...senderLookup(query, number, found) } });
173
+ };
174
+ }
175
+
165
176
  export function makeHandleCall(
166
177
  clientFor: ClientFor,
167
178
  ): (msg: CallMsg) => Promise<void> {
@@ -172,6 +183,7 @@ export function makeHandleCall(
172
183
  react: makeReact(clientFor),
173
184
  edit: makeEdit(clientFor),
174
185
  delete: makeDelete(clientFor),
186
+ resolve_sender: makeResolveSender(clientFor),
175
187
  },
176
188
  normalize: normalizeWhatsApp,
177
189
  });
@@ -12,6 +12,7 @@ import { TrainError } from '@metro-labs/core/train-error';
12
12
  import { errMsg } from '@metro-labs/core/log';
13
13
  import type { WhatsAppAccount } from './types.js';
14
14
  import type { InboundMessage, ReactionInput } from './format.js';
15
+ import type { SenderFound } from './resolve.js';
15
16
  import { toInbound, toReaction, type ReactionEvent, type SelfRef } from './parse.js';
16
17
  import { baileysLogger } from './logger.js';
17
18
  import { useAccountAuthState } from './auth-state.js';
@@ -49,6 +50,7 @@ export interface WAClient {
49
50
  editMessage(jid: string, messageId: string, text: string): Promise<void>;
50
51
  deleteMessage(jid: string, messageId: string): Promise<void>;
51
52
  reuploadMedia(m: WAMessage): Promise<WAMessage>;
53
+ lookupSender(number: string): Promise<SenderFound>;
52
54
  disconnect(): Promise<void>;
53
55
  }
54
56
 
@@ -200,6 +202,17 @@ async function connect(st: State): Promise<void> {
200
202
  bindDelivery(st, sock);
201
203
  }
202
204
 
205
+ async function lidFor(st: State, sock: WASocket, jid: string): Promise<string | null> {
206
+ try {
207
+ return await sock.signalRepository.lidMapping.getLIDForPN(jid);
208
+ } catch (e) {
209
+ process.stderr.write(
210
+ `whatsapp[${st.account.id}] no lid on file for ${jid}: ${errMsg(e)}\n`,
211
+ );
212
+ return null;
213
+ }
214
+ }
215
+
203
216
  async function ready(st: State): Promise<WASocket> {
204
217
  await st.openPromise;
205
218
  if (!st.sock) throw new TrainError('whatsapp_call', 'socket not connected');
@@ -315,6 +328,13 @@ export function createClient(account: WhatsAppAccount): WAClient {
315
328
  const sock = await ready(st);
316
329
  return sock.updateMediaMessage(m);
317
330
  },
331
+ async lookupSender(number) {
332
+ const sock = await ready(st);
333
+ const found = (await sock.onWhatsApp(number))?.[0];
334
+ if (found?.exists !== true) return { exists: false, jid: null, lid: null };
335
+ const jid = jidNormalizedUser(found.jid);
336
+ return { exists: true, jid, lid: await lidFor(st, sock, jid) };
337
+ },
318
338
  async disconnect() {
319
339
  st.closed = true;
320
340
  try {
@@ -0,0 +1,52 @@
1
+ import { TrainError } from '@metro-labs/core/train-error';
2
+
3
+ const INTERNATIONAL = /^[1-9]\d{5,17}$/;
4
+
5
+ export interface SenderFound {
6
+ exists: boolean;
7
+ jid: string | null;
8
+ lid: string | null;
9
+ }
10
+
11
+ export interface SenderLookup extends SenderFound {
12
+ query: string;
13
+ number: string;
14
+ id: string | null;
15
+ }
16
+
17
+ function refuse(query: string, why: string): never {
18
+ throw new TrainError('bad_request', `'${query}' ${why}`);
19
+ }
20
+
21
+ function international(query: string, digits: string): string {
22
+ if (digits.startsWith('00')) return digits.slice(2);
23
+ if (digits.startsWith('0'))
24
+ refuse(
25
+ query,
26
+ 'is a national number, so metro cannot tell which country it is in; write it in full international form, as in 41791234567 for a Swiss 079 123 45 67',
27
+ );
28
+ return digits;
29
+ }
30
+
31
+ export function phoneNumberOf(raw: string): string {
32
+ const query = raw.trim();
33
+ if (query.toLowerCase().endsWith('@lid'))
34
+ refuse(query, 'is already a sender id, so add it directly instead of looking it up');
35
+ const local = query.split('@')[0] ?? '';
36
+ const digits = local.replace(/\D/g, '');
37
+ const number = local.startsWith('+') ? digits : international(query, digits);
38
+ if (!INTERNATIONAL.test(number))
39
+ refuse(query, 'is not a phone number metro can look up; write it in full international form, as in 41791234567');
40
+ return number;
41
+ }
42
+
43
+ export function senderLookup(query: string, number: string, found: SenderFound): SenderLookup {
44
+ return {
45
+ query: query.trim(),
46
+ number,
47
+ exists: found.exists,
48
+ jid: found.jid,
49
+ lid: found.lid,
50
+ id: found.lid ?? found.jid,
51
+ };
52
+ }
@@ -13,5 +13,6 @@ export const whatsappStation: Station = {
13
13
  'delete',
14
14
  ]),
15
15
  attachmentMode: 'canonical',
16
+ resolvesSenders: true,
16
17
  tools: [],
17
18
  };
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.1.0-beta.115"
2
+ "version": "0.1.0-beta.116"
3
3
  }