@stage-labs/metro 0.1.0-beta.325 → 0.1.0-beta.327

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 (194) hide show
  1. package/dist/agent.js +1 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/lock.js +15 -3
  4. package/dist/root-release-io.js +1 -2
  5. package/dist/root-release.js +2 -3
  6. package/dist/route.js +1 -1
  7. package/dist/service.js +4 -4
  8. package/dist/version.js +1 -1
  9. package/package.json +2 -2
  10. package/runtime/node_modules/@metro-labs/core/package.json +3 -1
  11. package/runtime/node_modules/@metro-labs/core/src/automation-store.ts +1 -1
  12. package/runtime/node_modules/@metro-labs/core/src/automation-types.ts +2 -2
  13. package/runtime/node_modules/@metro-labs/core/src/brands.ts +100 -0
  14. package/runtime/node_modules/@metro-labs/core/src/favicon.ts +38 -0
  15. package/runtime/node_modules/@metro-labs/core/src/lines.ts +2 -8
  16. package/runtime/node_modules/@metro-labs/core/src/protocol.ts +0 -6
  17. package/runtime/node_modules/@metro-labs/core/src/skill-source.ts +6 -6
  18. package/runtime/node_modules/@metro-labs/core/src/stations/account-status.ts +1 -1
  19. package/runtime/node_modules/@metro-labs/core/src/stations/attachments.ts +5 -9
  20. package/runtime/node_modules/@metro-labs/core/src/stations/channel-directory.ts +1 -1
  21. package/runtime/node_modules/@metro-labs/core/src/stations/mail-text.ts +4 -4
  22. package/runtime/node_modules/@metro-labs/core/src/stations/mail.ts +3 -2
  23. package/runtime/node_modules/@metro-labs/core/src/stations/messaging-normalize.ts +1 -1
  24. package/runtime/node_modules/@metro-labs/core/src/stations/oauth.ts +1 -1
  25. package/runtime/node_modules/@metro-labs/core/src/stations/profile.ts +2 -2
  26. package/runtime/node_modules/@metro-labs/core/src/stations/types.ts +2 -2
  27. package/runtime/node_modules/@metro-labs/core/src/train-error.ts +4 -4
  28. package/runtime/node_modules/@metro-labs/daemon/package.json +1 -1
  29. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/files.ts +2 -6
  30. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/schedules.ts +6 -6
  31. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/user.ts +0 -24
  32. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/view.ts +3 -3
  33. package/runtime/node_modules/@metro-labs/daemon/src/agents/bundle.ts +3 -4
  34. package/runtime/node_modules/@metro-labs/daemon/src/agents/file-admin.ts +4 -9
  35. package/runtime/node_modules/@metro-labs/daemon/src/agents/files.ts +1 -6
  36. package/runtime/node_modules/@metro-labs/daemon/src/channels/inbound.ts +3 -3
  37. package/runtime/node_modules/@metro-labs/daemon/src/channels/pending.ts +2 -2
  38. package/runtime/node_modules/@metro-labs/daemon/src/claude/files.ts +1 -1
  39. package/runtime/node_modules/@metro-labs/daemon/src/claude/github-fetch.ts +2 -2
  40. package/runtime/node_modules/@metro-labs/daemon/src/claude/github-skills.ts +2 -2
  41. package/runtime/node_modules/@metro-labs/daemon/src/claude/skills.ts +1 -1
  42. package/runtime/node_modules/@metro-labs/daemon/src/files/attach-grant.ts +3 -2
  43. package/runtime/node_modules/@metro-labs/daemon/src/files/attach-serve.ts +1 -1
  44. package/runtime/node_modules/@metro-labs/daemon/src/files/upload-api.ts +3 -7
  45. package/runtime/node_modules/@metro-labs/daemon/src/mcp/accounts.ts +10 -19
  46. package/runtime/node_modules/@metro-labs/daemon/src/mcp/call-tools.ts +1 -5
  47. package/runtime/node_modules/@metro-labs/daemon/src/mcp/event-store.ts +3 -4
  48. package/runtime/node_modules/@metro-labs/daemon/src/mcp/group-tools.ts +1 -2
  49. package/runtime/node_modules/@metro-labs/daemon/src/mcp/index.ts +2 -4
  50. package/runtime/node_modules/@metro-labs/daemon/src/mcp/policy-gate.ts +5 -6
  51. package/runtime/node_modules/@metro-labs/daemon/src/mcp/server-approvals.ts +2 -5
  52. package/runtime/node_modules/@metro-labs/daemon/src/mcp/session.ts +1 -5
  53. package/runtime/node_modules/@metro-labs/daemon/src/mcp/tool-catalog.ts +2 -4
  54. package/runtime/node_modules/@metro-labs/daemon/src/mcp-server/announced.ts +1 -1
  55. package/runtime/node_modules/@metro-labs/daemon/src/metro-user/helper-script.ts +0 -1
  56. package/runtime/node_modules/@metro-labs/daemon/src/metro-user/install.ts +2 -0
  57. package/runtime/node_modules/@metro-labs/daemon/src/metro-user/tailscale-guard.ts +26 -0
  58. package/runtime/node_modules/@metro-labs/daemon/src/monitor/api.ts +1 -3
  59. package/runtime/node_modules/@metro-labs/daemon/src/routes/gmail-attach.ts +3 -3
  60. package/runtime/node_modules/@metro-labs/daemon/src/routes/http.ts +6 -21
  61. package/runtime/node_modules/@metro-labs/daemon/src/routes/local-mode.ts +1 -5
  62. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-resolve.ts +6 -6
  63. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach.ts +0 -1
  64. package/runtime/node_modules/@metro-labs/daemon/src/stations/materialize.ts +12 -61
  65. package/runtime/node_modules/@metro-labs/daemon/src/stations/supervisor.ts +13 -25
  66. package/runtime/node_modules/@metro-labs/daemon/src/stations/threema-callbacks.ts +5 -5
  67. package/runtime/node_modules/@metro-labs/daemon/src/stations/webhook-endpoints.ts +2 -7
  68. package/runtime/node_modules/@metro-labs/daemon/src/voice/call.ts +2 -6
  69. package/runtime/node_modules/@metro-labs/daemon/src/voice/calls.ts +12 -12
  70. package/runtime/node_modules/@metro-labs/discord-bot/package.json +1 -1
  71. package/runtime/node_modules/@metro-labs/discord-bot/src/actions.ts +5 -23
  72. package/runtime/node_modules/@metro-labs/discord-bot/src/attachments.ts +1 -7
  73. package/runtime/node_modules/@metro-labs/discord-bot/src/channels.ts +2 -2
  74. package/runtime/node_modules/@metro-labs/discord-bot/src/group.ts +10 -35
  75. package/runtime/node_modules/@metro-labs/discord-bot/src/index.ts +5 -11
  76. package/runtime/node_modules/@metro-labs/discord-bot/src/members.ts +6 -34
  77. package/runtime/node_modules/@metro-labs/discord-bot/src/profile.ts +11 -14
  78. package/runtime/node_modules/@metro-labs/discord-bot/src/send-files.ts +1 -3
  79. package/runtime/node_modules/@metro-labs/discord-bot/src/verify.ts +2 -3
  80. package/runtime/node_modules/@metro-labs/gmail/package.json +1 -1
  81. package/runtime/node_modules/@metro-labs/gmail/src/accounts.ts +3 -3
  82. package/runtime/node_modules/@metro-labs/gmail/src/auth.ts +8 -8
  83. package/runtime/node_modules/@metro-labs/gmail/src/managed.ts +3 -2
  84. package/runtime/node_modules/@metro-labs/http/package.json +1 -1
  85. package/runtime/node_modules/@metro-labs/http/src/agent-signature.ts +1 -1
  86. package/runtime/node_modules/@metro-labs/http/src/api-http.ts +3 -4
  87. package/runtime/node_modules/@metro-labs/http/src/connector-discovery.ts +0 -113
  88. package/runtime/node_modules/@metro-labs/http/src/connector-input.ts +1 -1
  89. package/runtime/node_modules/@metro-labs/http/src/connector-mcp.ts +12 -13
  90. package/runtime/node_modules/@metro-labs/http/src/connector-oauth.ts +2 -1
  91. package/runtime/node_modules/@metro-labs/http/src/connector-policy.ts +1 -6
  92. package/runtime/node_modules/@metro-labs/http/src/connector-public-url.ts +4 -2
  93. package/runtime/node_modules/@metro-labs/http/src/connector-tools.ts +43 -13
  94. package/runtime/node_modules/@metro-labs/http/src/connector-url.ts +0 -6
  95. package/runtime/node_modules/@metro-labs/http/src/mcp-server-protocol.ts +1 -1
  96. package/runtime/node_modules/@metro-labs/http/src/mcp-server-tools.ts +0 -2
  97. package/runtime/node_modules/@metro-labs/http/src/mode-api.ts +1 -1
  98. package/runtime/node_modules/@metro-labs/http/src/return-to.ts +2 -2
  99. package/runtime/node_modules/@metro-labs/http/src/workos-token.ts +6 -7
  100. package/runtime/node_modules/@metro-labs/inference/package.json +2 -1
  101. package/runtime/node_modules/@metro-labs/inference/src/attempts.ts +3 -3
  102. package/runtime/node_modules/@metro-labs/inference/src/bedrock.ts +1 -1
  103. package/runtime/node_modules/@metro-labs/inference/src/codex-translate.ts +2 -2
  104. package/runtime/node_modules/@metro-labs/inference/src/delivered.ts +1 -1
  105. package/runtime/node_modules/@metro-labs/inference/src/effort.ts +0 -6
  106. package/runtime/node_modules/@metro-labs/inference/src/fallback.ts +1 -1
  107. package/runtime/node_modules/@metro-labs/inference/src/forward.ts +5 -5
  108. package/runtime/node_modules/@metro-labs/inference/src/measure.ts +2 -3
  109. package/runtime/node_modules/@metro-labs/inference/src/named.ts +3 -3
  110. package/runtime/node_modules/@metro-labs/inference/src/probes.ts +98 -0
  111. package/runtime/node_modules/@metro-labs/inference/src/usage.ts +5 -5
  112. package/runtime/node_modules/@metro-labs/outlook/package.json +1 -1
  113. package/runtime/node_modules/@metro-labs/outlook/src/accounts.ts +6 -8
  114. package/runtime/node_modules/@metro-labs/outlook/src/auth.ts +2 -1
  115. package/runtime/node_modules/@metro-labs/outlook/src/inbound.ts +3 -5
  116. package/runtime/node_modules/@metro-labs/outlook/src/me.ts +6 -6
  117. package/runtime/node_modules/@metro-labs/outlook/src/outbound.ts +10 -13
  118. package/runtime/node_modules/@metro-labs/telegram/package.json +1 -1
  119. package/runtime/node_modules/@metro-labs/telegram/src/actions.ts +7 -26
  120. package/runtime/node_modules/@metro-labs/telegram/src/attachments.ts +1 -1
  121. package/runtime/node_modules/@metro-labs/telegram/src/login.ts +3 -6
  122. package/runtime/node_modules/@metro-labs/telegram/src/profile.ts +3 -2
  123. package/runtime/node_modules/@metro-labs/telegram-bot/package.json +1 -1
  124. package/runtime/node_modules/@metro-labs/telegram-bot/src/actions.ts +6 -20
  125. package/runtime/node_modules/@metro-labs/telegram-bot/src/attachments.ts +1 -7
  126. package/runtime/node_modules/@metro-labs/telegram-bot/src/format.ts +0 -2
  127. package/runtime/node_modules/@metro-labs/telegram-bot/src/media-actions.ts +1 -16
  128. package/runtime/node_modules/@metro-labs/telegram-bot/src/members.ts +1 -8
  129. package/runtime/node_modules/@metro-labs/telegram-bot/src/profile.ts +2 -1
  130. package/runtime/node_modules/@metro-labs/threema/package.json +1 -1
  131. package/runtime/node_modules/@metro-labs/threema/src/actions.ts +1 -8
  132. package/runtime/node_modules/@metro-labs/threema/src/chats.ts +4 -3
  133. package/runtime/node_modules/@metro-labs/threema/src/format.ts +15 -17
  134. package/runtime/node_modules/@metro-labs/threema/src/groups.ts +2 -4
  135. package/runtime/node_modules/@metro-labs/threema/src/inbound.ts +2 -1
  136. package/runtime/node_modules/@metro-labs/threema/src/messages.ts +2 -1
  137. package/runtime/node_modules/@metro-labs/threema/src/outbound.ts +7 -7
  138. package/runtime/node_modules/@metro-labs/webhook/package.json +1 -1
  139. package/runtime/node_modules/@metro-labs/whatsapp/package.json +1 -1
  140. package/runtime/node_modules/@metro-labs/whatsapp/src/actions.ts +1 -3
  141. package/runtime/node_modules/@metro-labs/whatsapp/src/attachments.ts +0 -2
  142. package/runtime/node_modules/@metro-labs/whatsapp/src/client.ts +1 -1
  143. package/runtime/node_modules/@metro-labs/whatsapp/src/login.ts +1 -1
  144. package/runtime/node_modules/@metro-labs/xmtp/package.json +1 -1
  145. package/runtime/node_modules/@metro-labs/xmtp/src/accounts.ts +7 -0
  146. package/runtime/node_modules/@metro-labs/xmtp/src/actions-conv.ts +4 -10
  147. package/runtime/node_modules/@metro-labs/xmtp/src/actions-meta.ts +4 -5
  148. package/runtime/node_modules/@metro-labs/xmtp/src/actions.ts +14 -26
  149. package/runtime/node_modules/@metro-labs/xmtp/src/attachments.ts +1 -7
  150. package/runtime/node_modules/@metro-labs/xmtp/src/codecs.ts +17 -58
  151. package/runtime/node_modules/@metro-labs/xmtp/src/conv-helpers.ts +1 -6
  152. package/runtime/node_modules/@metro-labs/xmtp/src/emit-payloads.ts +10 -31
  153. package/runtime/node_modules/@metro-labs/xmtp/src/frames.ts +12 -14
  154. package/runtime/node_modules/@metro-labs/xmtp/src/group.ts +2 -3
  155. package/runtime/node_modules/@metro-labs/xmtp/src/identity.ts +3 -9
  156. package/runtime/node_modules/@metro-labs/xmtp/src/labels.ts +8 -9
  157. package/runtime/node_modules/@metro-labs/xmtp/src/names.ts +4 -2
  158. package/runtime/node_modules/@metro-labs/xmtp/src/network.ts +2 -3
  159. package/runtime/node_modules/@metro-labs/xmtp/src/profile.ts +2 -1
  160. package/runtime/node_modules/@metro-labs/xmtp/src/read-attachments.ts +2 -2
  161. package/runtime/node_modules/@metro-labs/xmtp/src/sender.ts +2 -1
  162. package/runtime/node_modules/@metro-labs/xmtp/src/transcribe.ts +23 -46
  163. package/runtime/node_modules/@metro-labs/xmtp/src/wallet.ts +5 -4
  164. package/runtime/node_modules/@metro-labs/xmtp/src/wire.ts +12 -15
  165. package/runtime/runtime.json +1 -1
  166. package/runtime/sdk-runner/node_modules/@metro-labs/core/package.json +3 -1
  167. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/automation-store.ts +1 -1
  168. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/automation-types.ts +2 -2
  169. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/brands.ts +100 -0
  170. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/favicon.ts +38 -0
  171. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/lines.ts +2 -8
  172. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/protocol.ts +0 -6
  173. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/skill-source.ts +6 -6
  174. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/stations/account-status.ts +1 -1
  175. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/stations/attachments.ts +5 -9
  176. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/stations/channel-directory.ts +1 -1
  177. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/stations/mail-text.ts +4 -4
  178. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/stations/mail.ts +3 -2
  179. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/stations/messaging-normalize.ts +1 -1
  180. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/stations/oauth.ts +1 -1
  181. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/stations/profile.ts +2 -2
  182. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/stations/types.ts +2 -2
  183. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/train-error.ts +4 -4
  184. package/runtime/sdk-runner/runner.json +1 -1
  185. package/runtime/sdk-runner/src/approvals.ts +2 -2
  186. package/runtime/sdk-runner/src/automation-command.ts +2 -2
  187. package/runtime/sdk-runner/src/calls.ts +0 -6
  188. package/runtime/sdk-runner/src/errors.ts +1 -1
  189. package/runtime/sdk-runner/src/link.ts +1 -1
  190. package/runtime/sdk-runner/src/runner.ts +2 -2
  191. package/runtime/sdk-runner/src/session-watch.ts +5 -34
  192. package/runtime/sdk-runner/src/task-state.ts +1 -1
  193. package/runtime/sdk-runner/src/tool-proxy.ts +1 -1
  194. package/runtime/node_modules/@metro-labs/xmtp/src/member-args.ts +0 -40
@@ -22,21 +22,18 @@ function membersOf(args: Record<string, unknown>): string[] {
22
22
  return raw.filter((v) => typeof v === 'string' && v.length > 0) as string[];
23
23
  }
24
24
 
25
- async function addThreadMembers(
25
+ async function threadMembers(
26
26
  rest: RestFn,
27
27
  accountId: string,
28
28
  threadId: string,
29
- members: string[],
29
+ args: Record<string, unknown>,
30
+ method: 'PUT' | 'DELETE',
30
31
  ): Promise<MemberOutcome[]> {
31
32
  const outcomes: MemberOutcome[] = [];
32
- for (const userId of members) {
33
+ for (const userId of membersOf(args)) {
33
34
  try {
34
- await rest(
35
- accountId,
36
- 'PUT',
37
- `/channels/${threadId}/thread-members/${userId}`,
38
- );
39
- outcomes.push({ id: userId, status: 'added' });
35
+ await rest(accountId, method, `/channels/${threadId}/thread-members/${userId}`);
36
+ outcomes.push({ id: userId, status: method === 'PUT' ? 'added' : 'removed' });
40
37
  } catch (e) {
41
38
  outcomes.push({ id: userId, status: 'failed', reason: errMsg(e) });
42
39
  }
@@ -60,12 +57,7 @@ export async function groupCreate(
60
57
  `/channels/${parentChannelId}/threads`,
61
58
  { name, type, auto_archive_duration: AUTO_ARCHIVE },
62
59
  );
63
- const members = await addThreadMembers(
64
- rest,
65
- accountId,
66
- thread.id,
67
- membersOf(args),
68
- );
60
+ const members = await threadMembers(rest, accountId, thread.id, args, 'PUT');
69
61
  return {
70
62
  capability: { supported: true },
71
63
  line: lineOf(accountId, thread.id),
@@ -82,12 +74,7 @@ export async function groupAddMembers(
82
74
  line: string,
83
75
  args: Record<string, unknown>,
84
76
  ): Promise<GroupResult> {
85
- const members = await addThreadMembers(
86
- rest,
87
- accountId,
88
- threadId,
89
- membersOf(args),
90
- );
77
+ const members = await threadMembers(rest, accountId, threadId, args, 'PUT');
91
78
  return { capability: { supported: true }, line, id: threadId, members };
92
79
  }
93
80
 
@@ -98,18 +85,6 @@ export async function groupRemoveMembers(
98
85
  line: string,
99
86
  args: Record<string, unknown>,
100
87
  ): Promise<GroupResult> {
101
- const outcomes: MemberOutcome[] = [];
102
- for (const userId of membersOf(args)) {
103
- try {
104
- await rest(
105
- accountId,
106
- 'DELETE',
107
- `/channels/${threadId}/thread-members/${userId}`,
108
- );
109
- outcomes.push({ id: userId, status: 'removed' });
110
- } catch (e) {
111
- outcomes.push({ id: userId, status: 'failed', reason: errMsg(e) });
112
- }
113
- }
114
- return { capability: { supported: true }, line, id: threadId, members: outcomes };
88
+ const members = await threadMembers(rest, accountId, threadId, args, 'DELETE');
89
+ return { capability: { supported: true }, line, id: threadId, members };
115
90
  }
@@ -70,7 +70,7 @@ async function bootAccount(cfg: AccountConfig): Promise<void> {
70
70
  });
71
71
 
72
72
  client.on(Events.MessageReactionAdd, (r, u) => {
73
- void (async () => {
73
+ (async () => {
74
74
  try {
75
75
  if (r.partial) await r.fetch();
76
76
  if (u.partial) await u.fetch();
@@ -85,18 +85,12 @@ async function bootAccount(cfg: AccountConfig): Promise<void> {
85
85
  });
86
86
  });
87
87
 
88
- client.on(Events.MessageUpdate, (_old, _new) => {
89
- void (async () => {
90
- try {
91
- onEdit(accountId, _new.partial ? await _new.fetch() : _new);
92
- } catch (err) {
93
- process.stderr.write(
94
- `discord-bot[${accountId}] message update fetch failed: ${errMsg(err)}\n`,
95
- );
96
- }
88
+ client.on(Events.MessageUpdate, (_old, updated) => {
89
+ (async () => {
90
+ onEdit(accountId, updated.partial ? await updated.fetch() : updated);
97
91
  })().catch((err: unknown) => {
98
92
  process.stderr.write(
99
- `discord-bot[${accountId}] message update handler failed: ${errMsg(err)}\n`,
93
+ `discord-bot[${accountId}] message update fetch failed: ${errMsg(err)}\n`,
100
94
  );
101
95
  });
102
96
  });
@@ -97,38 +97,6 @@ export function mapRecipients(users: DiscordUser[]): MetroMember[] {
97
97
  });
98
98
  }
99
99
 
100
- async function fetchRoles(
101
- accountId: string,
102
- guildId: string,
103
- ): Promise<Map<string, RoleInfo>> {
104
- try {
105
- const roles = await rest<DiscordRole[]>(
106
- accountId,
107
- 'GET',
108
- `/guilds/${guildId}/roles`,
109
- );
110
- return indexRoles(roles);
111
- } catch {
112
- return new Map();
113
- }
114
- }
115
-
116
- async function fetchOwnerId(
117
- accountId: string,
118
- guildId: string,
119
- ): Promise<string | undefined> {
120
- try {
121
- const g = await rest<{ owner_id?: string }>(
122
- accountId,
123
- 'GET',
124
- `/guilds/${guildId}`,
125
- );
126
- return g.owner_id;
127
- } catch {
128
- return undefined;
129
- }
130
- }
131
-
132
100
  interface Collected {
133
101
  raw: DiscordGuildMember[];
134
102
  exhausted: boolean;
@@ -168,8 +136,12 @@ export async function listGuildMembers(
168
136
  limit?: number,
169
137
  ): Promise<MemberList> {
170
138
  const cap = Math.min(Math.max(1, limit ?? PAGE), 10_000);
171
- const roles = await fetchRoles(accountId, guildId);
172
- const ownerId = await fetchOwnerId(accountId, guildId);
139
+ const roles = await rest<DiscordRole[]>(accountId, 'GET', `/guilds/${guildId}/roles`)
140
+ .then(indexRoles)
141
+ .catch(() => new Map<string, RoleInfo>());
142
+ const ownerId = await rest<{ owner_id?: string }>(accountId, 'GET', `/guilds/${guildId}`)
143
+ .then((g) => g.owner_id)
144
+ .catch(() => undefined);
173
145
  try {
174
146
  const { raw, exhausted } = await paginate(accountId, guildId, cap);
175
147
  const members = mapGuildMembers(raw, roles, ownerId);
@@ -9,7 +9,7 @@ import {
9
9
  type ProfileChange,
10
10
  } from '@metro-labs/core/stations/profile';
11
11
  import type { SenderProfile } from '@metro-labs/core/stations/sender-profile';
12
- import { accountFor, accounts } from './accounts.js';
12
+ import { accountFor, accounts, type Account } from './accounts.js';
13
13
  import { respond } from '@metro-labs/core/stations/station-runtime';
14
14
 
15
15
  export async function applyProfile(
@@ -32,29 +32,26 @@ export async function applyProfile(
32
32
  }
33
33
  }
34
34
 
35
+ function accountOf(args: Record<string, unknown>): Account {
36
+ const accountId = accountFor({ account: args.account as string | undefined });
37
+ const acct = accounts.get(accountId);
38
+ if (!acct) throw new Error(`unknown account '${accountId}'`);
39
+ return acct;
40
+ }
41
+
35
42
  export async function setProfile(
36
43
  id: string,
37
44
  args: Record<string, unknown>,
38
45
  ): Promise<void> {
39
- const accountId = accountFor({ account: args.account as string | undefined });
40
- const acct = accounts.get(accountId);
41
- if (!acct) {
42
- respond(id, { error: `unknown account '${accountId}'` });
43
- return;
44
- }
46
+ const acct = accountOf(args);
45
47
  const change = parseProfileChange(args);
46
48
  await applyProfile(acct.client, change);
47
- const result: ProfileApplied = { account: accountId, applied: fieldsOf(change) };
49
+ const result: ProfileApplied = { account: acct.cfg.id, applied: fieldsOf(change) };
48
50
  respond(id, { result });
49
51
  }
50
52
 
51
53
  export async function readProfile(id: string, args: Record<string, unknown>): Promise<void> {
52
- const accountId = accountFor({ account: args.account as string | undefined });
53
- const acct = accounts.get(accountId);
54
- if (!acct) {
55
- respond(id, { error: `unknown account '${accountId}'` });
56
- return;
57
- }
54
+ const acct = accountOf(args);
58
55
  const user = typeof args.user === 'string' ? args.user.trim() : '';
59
56
  if (!/^\d+$/.test(user)) throw new TrainError('discord_user_required', 'profile needs the Discord id of the person', { retryable: false });
60
57
  const found = await acct.client.users.fetch(user);
@@ -32,9 +32,7 @@ export async function appendFiles(
32
32
  files: OutgoingFile[],
33
33
  ): Promise<string[]> {
34
34
  const delivered: string[] = [];
35
- for (let i = 0; i < files.length; i++) {
36
- const file = files[i];
37
- if (!file) continue;
35
+ for (const [i, file] of files.entries()) {
38
36
  await appendFile(form, `files[${i}]`, file.path, file.name);
39
37
  delivered.push(file.kind);
40
38
  }
@@ -1,3 +1,4 @@
1
+ import { isRecord } from '@metro-labs/core/is-record';
1
2
  import { API } from './api-base.js';
2
3
 
3
4
  export class DiscordTokenError extends Error {}
@@ -25,9 +26,7 @@ function botFetch(token: string, path: string): Promise<Response> {
25
26
  async function readJson(res: Response): Promise<Record<string, unknown>> {
26
27
  try {
27
28
  const body: unknown = await res.json();
28
- return typeof body === 'object' && body !== null
29
- ? (body as Record<string, unknown>)
30
- : {};
29
+ return isRecord(body) ? body : {};
31
30
  } catch {
32
31
  throw new DiscordTokenError('Discord returned a response Metro could not read');
33
32
  }
@@ -18,7 +18,7 @@
18
18
  "@metro-labs/core": "workspace:*"
19
19
  },
20
20
  "devDependencies": {
21
- "@stage-labs/config": "0.1.0-beta.3",
21
+ "@stage-labs/config": "0.1.0-beta.5",
22
22
  "eslint": "^10.3.0",
23
23
  "knip": "^6.15.0",
24
24
  "madge": "^8.0.0",
@@ -1,3 +1,4 @@
1
+ import { errMsg } from '@metro-labs/core/log';
1
2
  import { makeAccountStore, resolveAccountId, type Die } from '@metro-labs/core/stations/account-store';
2
3
  import { threadOfLine } from '@metro-labs/core/stations/mail';
3
4
  import { TokenKeeper, type FetchLike } from '@metro-labs/core/stations/oauth';
@@ -43,7 +44,7 @@ export const { loadAccounts } = makeAccountStore<AccountConfig>({
43
44
  });
44
45
 
45
46
  const signedOut = (err: unknown): never => {
46
- throw new TrainError('gmail_signed_out', err instanceof Error ? err.message : String(err), { retryable: false });
47
+ throw new TrainError('gmail_signed_out', errMsg(err), { retryable: false });
47
48
  };
48
49
 
49
50
  export class Account {
@@ -63,10 +64,9 @@ export class Account {
63
64
  const client = { clientId: cfg.clientId ?? '', clientSecret: cfg.clientSecret ?? '' };
64
65
  this.keeper = new TokenKeeper(this.state, async (refreshToken) => {
65
66
  checkManagedBinding(cfg);
66
- const tokens = await (cfg.managed === true
67
+ return (cfg.managed === true
67
68
  ? renewManaged(refreshToken, this.state.refreshGrant ?? '', cfg.managedHost ?? '', this.fetchImpl)
68
69
  : refreshTokens(client, refreshToken, this.fetchImpl, Date.now(), cfg.sendEnabled)).catch(signedOut);
69
- return tokens;
70
70
  }, () => {
71
71
  this.save();
72
72
  });
@@ -1,3 +1,5 @@
1
+ import { errMsg } from '@metro-labs/core/log';
2
+ import { str } from '@metro-labs/core/stations/mail';
1
3
  import { postForm, SignInError, tokensOf, type FetchLike, type OAuthBody, type Tokens } from '@metro-labs/core/stations/oauth';
2
4
  import { apiBase, authorizeBase, redirectUri, scopesFor, tokenUrl } from './config.js';
3
5
 
@@ -15,11 +17,9 @@ export interface GmailClient {
15
17
 
16
18
  const CLIENT_ID_RE = /^[\w.-]+\.apps\.googleusercontent\.com$/;
17
19
 
18
- const text = (v: unknown): string => (typeof v === 'string' ? v.trim() : '');
19
-
20
20
  export function clientOf(rawId: unknown, rawSecret: unknown): GmailClient {
21
- const clientId = text(rawId);
22
- const clientSecret = text(rawSecret);
21
+ const clientId = str(rawId);
22
+ const clientSecret = str(rawSecret);
23
23
  if (!CLIENT_ID_RE.test(clientId))
24
24
  throw new SignInError('Paste the client ID of your Google OAuth client. It ends with .apps.googleusercontent.com.');
25
25
  if (clientSecret === '' || /\s/.test(clientSecret)) throw new SignInError('Paste the client secret of your Google OAuth client.');
@@ -27,13 +27,13 @@ export function clientOf(rawId: unknown, rawSecret: unknown): GmailClient {
27
27
  }
28
28
 
29
29
  export function failureOf(body: OAuthBody): string {
30
- const error = text(body.error);
30
+ const error = str(body.error);
31
31
  if (error === 'access_denied') return 'The sign-in was declined, so nothing was connected.';
32
32
  if (error === 'invalid_client' || error === 'unauthorized_client')
33
33
  return 'Google does not accept this client ID and secret. Check both on the Clients page of your Google Cloud project.';
34
34
  if (error === 'redirect_uri_mismatch') return `Your Google OAuth client must list ${redirectUri()} as an authorized redirect URI.`;
35
35
  if (error === 'admin_policy_enforced') return 'Your Google Workspace administrator blocks this app. Trust it in the Admin console under API controls, then start again.';
36
- const detail = text(body.error_description);
36
+ const detail = str(body.error_description);
37
37
  return detail === '' ? `Google refused the sign-in (${error === '' ? 'no reason given' : error}).` : `Google refused the sign-in: ${detail}`;
38
38
  }
39
39
 
@@ -101,14 +101,14 @@ export async function verifyMailbox(accessToken: string, fetchImpl: FetchLike, w
101
101
  headers: { authorization: `Bearer ${accessToken}`, accept: 'application/json' },
102
102
  });
103
103
  } catch (err) {
104
- throw new SignInError(`Metro could not reach Gmail: ${err instanceof Error ? err.message : String(err)}`);
104
+ throw new SignInError(`Metro could not reach Gmail: ${errMsg(err)}`);
105
105
  }
106
106
  if (!res.ok) {
107
107
  const hint = res.status === 403 ? ' Check that the Gmail API is enabled in your Google Cloud project.' : '';
108
108
  throw new SignInError(`Gmail refused the new sign-in (${await googleMessage(res)}), so nothing was connected.${hint}`);
109
109
  }
110
110
  const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
111
- const email = text(body.emailAddress).toLowerCase();
111
+ const email = str(body.emailAddress).toLowerCase();
112
112
  if (email === '') throw new SignInError('Gmail did not say which mailbox this is, so nothing was connected.');
113
113
  if (wanted !== null && wanted !== email) throw new SignInError(wrongMailbox(email, wanted));
114
114
  return email;
@@ -1,3 +1,4 @@
1
+ import { isRecord } from '@metro-labs/core/is-record';
1
2
  import { SignInError, type FetchLike, type Tokens } from '@metro-labs/core/stations/oauth';
2
3
 
3
4
  const BASE = 'https://api.metro.box/api/gmail';
@@ -25,8 +26,8 @@ export async function managedRequest(path: 'start' | 'exchange' | 'cancel' | 're
25
26
  throw new SignInError(`Metro could not complete managed Gmail sign-in. ${retry}`);
26
27
  }
27
28
  const value: unknown = await response.json().catch(() => null);
28
- if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new SignInError('Metro returned an invalid Gmail answer.');
29
- return value as Record<string, unknown>;
29
+ if (!isRecord(value)) throw new SignInError('Metro returned an invalid Gmail answer.');
30
+ return value;
30
31
  }
31
32
 
32
33
  export function managedTokens(value: Record<string, unknown>): ManagedTokens {
@@ -35,7 +35,7 @@
35
35
  "@metro-labs/core": "workspace:*"
36
36
  },
37
37
  "devDependencies": {
38
- "@stage-labs/config": "0.1.0-beta.3",
38
+ "@stage-labs/config": "0.1.0-beta.5",
39
39
  "eslint": "^10.3.0",
40
40
  "knip": "^6.15.0",
41
41
  "madge": "^8.0.0",
@@ -1,7 +1,7 @@
1
1
  import { createHash, createPublicKey, randomBytes, sign, verify, type KeyObject } from 'node:crypto';
2
2
  import { strongEd25519 } from './ed25519.js';
3
3
 
4
- export const AGENT_SCHEME = 'MetroAgent';
4
+ const AGENT_SCHEME = 'MetroAgent';
5
5
  export const AGENT_CLOCK_SKEW_MS = 5 * 60_000;
6
6
 
7
7
  const VERSION = 'metro-agent-request/v1';
@@ -1,10 +1,11 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { ApiError } from './api-error.js';
3
+ import { isRecord } from '@metro-labs/core/is-record';
3
4
  import { errMsg, log } from '@metro-labs/core/log';
4
5
 
5
6
  const BODY_MAX = 4 * 1024;
6
7
 
7
- export type Role = 'admin' | 'member';
8
+ type Role = 'admin' | 'member';
8
9
 
9
10
  export interface ApiSession {
10
11
  subject: string;
@@ -151,9 +152,7 @@ export function sessionRoute(
151
152
  }
152
153
 
153
154
  export function bodyField(body: unknown, key: string): unknown {
154
- return typeof body === 'object' && body !== null && !Array.isArray(body)
155
- ? (body as Record<string, unknown>)[key]
156
- : undefined;
155
+ return isRecord(body) ? body[key] : undefined;
157
156
  }
158
157
 
159
158
  export const stringOf = (value: unknown): string => (typeof value === 'string' ? value : '');
@@ -1,10 +1,3 @@
1
- import { isRecord } from '@metro-labs/core/is-record';
2
- import type { FetchLike } from '@metro-labs/core/stations/oauth';
3
- import { stringOf } from './api-http.js';
4
- import { parseConnectorUrl, refused } from './connector-url.js';
5
-
6
- const DISCOVERY_TIMEOUT_MS = 10_000;
7
-
8
1
  export interface OAuthServer {
9
2
  issuer: string;
10
3
  authorizationEndpoint: string;
@@ -14,30 +7,6 @@ export interface OAuthServer {
14
7
  scopes: string[];
15
8
  }
16
9
 
17
- interface ResourceMetadata {
18
- issuer: URL;
19
- scopes: string[];
20
- }
21
-
22
- async function getJson(url: URL, fetchImpl: FetchLike): Promise<Record<string, unknown> | null> {
23
- let res: Response;
24
- try {
25
- res = await fetchImpl(url.toString(), {
26
- redirect: 'manual',
27
- signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),
28
- headers: { accept: 'application/json' },
29
- });
30
- } catch {
31
- return null;
32
- }
33
- if (!res.ok) {
34
- await res.body?.cancel().catch(() => undefined);
35
- return null;
36
- }
37
- const body: unknown = await res.json().catch(() => null);
38
- return isRecord(body) ? body : null;
39
- }
40
-
41
10
  function wellKnown(base: URL, suffix: string): URL {
42
11
  const url = new URL(base.toString());
43
12
  url.pathname = `/.well-known/${suffix}`;
@@ -56,77 +25,6 @@ export function resourceMetadataUrls(resource: URL): URL[] {
56
25
  return urls;
57
26
  }
58
27
 
59
- export async function advertisesOAuth(resource: URL, fetchImpl: FetchLike = fetch): Promise<boolean> {
60
- for (const candidate of resourceMetadataUrls(resource)) {
61
- const body = await getJson(candidate, fetchImpl);
62
- const servers: unknown = body?.authorization_servers;
63
- const first: unknown = Array.isArray(servers) ? servers[0] : undefined;
64
- if (typeof first === 'string' && first !== '') return true;
65
- }
66
- return false;
67
- }
68
-
69
- function scopesOf(body: Record<string, unknown> | null): string[] {
70
- const raw: unknown = body?.scopes_supported;
71
- if (!Array.isArray(raw)) return [];
72
- const out: string[] = [];
73
- for (const entry of raw) {
74
- const scope = stringOf(entry).trim();
75
- if (scope !== '' && !/\s/.test(scope) && !out.includes(scope)) out.push(scope);
76
- }
77
- return out;
78
- }
79
-
80
- async function resourceMetadata(resource: URL, fetchImpl: FetchLike): Promise<ResourceMetadata> {
81
- for (const candidate of resourceMetadataUrls(resource)) {
82
- const body = await getJson(candidate, fetchImpl);
83
- const servers: unknown = body?.authorization_servers;
84
- const first: unknown = Array.isArray(servers) ? servers[0] : undefined;
85
- if (typeof first === 'string' && first !== '')
86
- return { issuer: parseConnectorUrl(first), scopes: scopesOf(body) };
87
- }
88
- return { issuer: parseConnectorUrl(resource.origin), scopes: [] };
89
- }
90
-
91
- const webAddress = (text: string): boolean => {
92
- try {
93
- parseConnectorUrl(text);
94
- return true;
95
- } catch {
96
- return false;
97
- }
98
- };
99
-
100
- function endpointOf(raw: unknown, issuer: URL): string {
101
- const text = stringOf(raw);
102
- if (text !== '' && !webAddress(text)) throw refused(`${issuer.hostname} advertises a sign-in address Metro will not open.`);
103
- return text;
104
- }
105
-
106
- function toServer(
107
- body: Record<string, unknown>,
108
- issuer: URL,
109
- scopes: string[],
110
- ): OAuthServer {
111
- const authorizationEndpoint = endpointOf(body.authorization_endpoint, issuer);
112
- const tokenEndpoint = endpointOf(body.token_endpoint, issuer);
113
- if (authorizationEndpoint === '' || tokenEndpoint === '')
114
- throw refused(
115
- `${issuer.hostname} advertises OAuth but not where to sign in.`,
116
- );
117
- const methods = body.code_challenge_methods_supported;
118
- const offered = stringOf(body.registration_endpoint);
119
- const registration = webAddress(offered) ? offered : '';
120
- return {
121
- issuer: stringOf(body.issuer) === '' ? issuer.origin : stringOf(body.issuer),
122
- authorizationEndpoint,
123
- tokenEndpoint,
124
- registrationEndpoint: registration === '' ? null : registration,
125
- supportsS256: Array.isArray(methods) ? methods.includes('S256') : false,
126
- scopes,
127
- };
128
- }
129
-
130
28
  export function authServerMetadataUrls(issuer: URL): URL[] {
131
29
  const path = issuer.pathname.replace(/\/$/, '');
132
30
  const suffixes = ['oauth-authorization-server', 'openid-configuration'];
@@ -137,14 +35,3 @@ export function authServerMetadataUrls(issuer: URL): URL[] {
137
35
  );
138
36
  return [...aware, new URL(`${path}/.well-known/openid-configuration`, issuer.origin), ...urls];
139
37
  }
140
-
141
- export async function discoverOAuth(resource: URL, fetchImpl: FetchLike = fetch): Promise<OAuthServer> {
142
- const { issuer, scopes } = await resourceMetadata(resource, fetchImpl);
143
- for (const candidate of authServerMetadataUrls(issuer)) {
144
- const body = await getJson(candidate, fetchImpl);
145
- if (body !== null) return toServer(body, issuer, scopes);
146
- }
147
- throw refused(
148
- `${resource.hostname} needs authorization, but publishes no OAuth metadata Metro can use.`,
149
- );
150
- }
@@ -10,7 +10,7 @@ const CLIENT_ID_RE = /^[\x21-\x7e]{1,256}$/;
10
10
  const CLIENT_SECRET_RE = /^[\x21-\x7e]{1,1024}$/;
11
11
  const DEFAULT_HEADER = 'Authorization';
12
12
 
13
- export class ConnectorError extends ApiError {}
13
+ class ConnectorError extends ApiError {}
14
14
 
15
15
  function hasControlChar(value: string): boolean {
16
16
  for (const ch of value) {
@@ -10,7 +10,7 @@ export interface OAuthTokens {
10
10
  expiresAt?: number;
11
11
  }
12
12
 
13
- export interface OAuthAuth extends OAuthTokens {
13
+ interface OAuthAuth extends OAuthTokens {
14
14
  kind: 'oauth';
15
15
  issuer: string;
16
16
  tokenEndpoint: string;
@@ -30,10 +30,6 @@ export interface VerifiedServer {
30
30
  server: string;
31
31
  }
32
32
 
33
- export interface VerifiedRecord extends VerifiedServer {
34
- at: string;
35
- }
36
-
37
33
  const PROBE_TIMEOUT_MS = 10_000;
38
34
 
39
35
  export const INITIALIZE = {
@@ -49,12 +45,21 @@ export function authHeaders(auth: ConnectorAuth): Record<string, string> {
49
45
  return {};
50
46
  }
51
47
 
52
- export function payloadOf(text: string, contentType: string): string {
48
+ function payloadOf(text: string, contentType: string): string {
53
49
  if (!contentType.includes('text/event-stream')) return text;
54
50
  for (const line of text.replace(/\r\n/g, '\n').split('\n')) if (line.startsWith('data:')) return line.slice(5).trim();
55
51
  return '';
56
52
  }
57
53
 
54
+ export function resultOf(text: string, contentType: string): Record<string, unknown> | null {
55
+ try {
56
+ const parsed: unknown = JSON.parse(payloadOf(text, contentType));
57
+ return isRecord(parsed) && isRecord(parsed.result) ? parsed.result : null;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
58
63
  export async function mcpPost(
59
64
  url: URL,
60
65
  auth: ConnectorAuth,
@@ -77,13 +82,7 @@ export async function mcpPost(
77
82
  }
78
83
 
79
84
  function serverNameOf(url: URL, text: string, contentType: string): string {
80
- let parsed: unknown;
81
- try {
82
- parsed = JSON.parse(payloadOf(text, contentType));
83
- } catch {
84
- throw refused(`${url.hostname} answered, but it does not speak MCP.`);
85
- }
86
- const result = isRecord(parsed) && isRecord(parsed.result) ? parsed.result : null;
85
+ const result = resultOf(text, contentType);
87
86
  if (result === null || typeof result.protocolVersion !== 'string') throw refused(`${url.hostname} answered, but it does not speak MCP.`);
88
87
  const info = isRecord(result.serverInfo) ? result.serverInfo : {};
89
88
  const title = typeof info.title === 'string' ? info.title : '';
@@ -16,13 +16,14 @@ const SIGN_IN_AGAIN = new Set(['invalid_grant', 'invalid_client', 'unauthorized_
16
16
  export interface OAuthClient {
17
17
  clientId: string;
18
18
  clientSecret?: string;
19
+ redirectUri?: string;
19
20
  }
20
21
 
21
22
  export function newVerifier(): string {
22
23
  return randomBytes(32).toString('base64url');
23
24
  }
24
25
 
25
- export function challengeOf(verifier: string): string {
26
+ function challengeOf(verifier: string): string {
26
27
  return createHash('sha256').update(verifier).digest('base64url');
27
28
  }
28
29
 
@@ -1,6 +1,6 @@
1
1
  import { isRecord } from '@metro-labs/core/is-record';
2
2
 
3
- export type ConnectorDecision = 'allow' | 'ask' | 'deny';
3
+ type ConnectorDecision = 'allow' | 'ask' | 'deny';
4
4
 
5
5
  type ToolGroup = 'read' | 'write';
6
6
 
@@ -45,11 +45,6 @@ function toolPolicyOf(value: unknown): Record<string, ConnectorDecision> {
45
45
  return out;
46
46
  }
47
47
 
48
- export function connectorPolicyLayersOf(value: unknown): ConnectorPolicyLayers {
49
- if (!isRecord(value) || Object.keys(value).some((key) => !['organization', 'agent'].includes(key))) throw new Error('Invalid connector policy layers.');
50
- return { organization: connectorPolicyOf(value.organization), agent: connectorPolicyOf(value.agent) };
51
- }
52
-
53
48
  const strictest = (...values: (ConnectorDecision | undefined)[]): ConnectorDecision => values.reduce<ConnectorDecision>((held, next) => next !== undefined && RANK[next] > RANK[held] ? next : held, 'allow');
54
49
  const toolRule = (policy: ConnectorPolicy, name: string): ConnectorDecision | undefined => policy.tools !== undefined && Object.hasOwn(policy.tools, name) ? policy.tools[name] : undefined;
55
50
  const toolGroup = (groups: Record<string, ToolGroup>, name: string): ToolGroup => Object.hasOwn(groups, name) && groups[name] === 'read' ? 'read' : 'write';
@@ -40,14 +40,16 @@ export function parsePublicConnectorUrl(raw: unknown): URL {
40
40
  return url;
41
41
  }
42
42
 
43
+ const RESOURCE_REFUSED = 'The public OAuth resource must be a public HTTPS identifier without a query, user information or a fragment. Do not enter credentials.';
44
+
43
45
  export function publicOAuthResource(raw: unknown): string {
44
46
  try {
45
47
  const url = parsePublicConnectorUrl(raw);
46
48
  if (typeof raw === 'string' && !raw.includes('?') && url.search === '') return raw;
47
49
  } catch {
48
- throw refused('The public OAuth resource must be a public HTTPS identifier without a query, user information or a fragment. Do not enter credentials.');
50
+ throw refused(RESOURCE_REFUSED);
49
51
  }
50
- throw refused('The public OAuth resource must be a public HTTPS identifier without a query, user information or a fragment. Do not enter credentials.');
52
+ throw refused(RESOURCE_REFUSED);
51
53
  }
52
54
 
53
55
  export function optionalOAuthResource(raw: unknown): string | undefined {