teapot-coding-agent 0.29.30 → 0.29.32

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.
@@ -0,0 +1,429 @@
1
+ /**
2
+ * MCP OAuth 2.1 (#67 follow-up): discovery, PKCE, token exchange, refresh.
3
+ *
4
+ * An OAuth-protected MCP server answers an unauthenticated request with **401 and a
5
+ * `WWW-Authenticate: Bearer …` challenge**. That single response carries everything
6
+ * needed to find the authorization server, so no configuration is required from the
7
+ * operator: probe → discover → register → authorize → retry.
8
+ *
9
+ * The chain, and the spec each link comes from:
10
+ *
11
+ * 401 + WWW-Authenticate RFC 6750 (the challenge, with `resource_metadata`)
12
+ * → protected-resource metadata RFC 9728 (`authorization_servers`, `scopes_supported`)
13
+ * → authorization-server metadata RFC 8414 (`/.well-known/oauth-authorization-server`)
14
+ * → optional dynamic registration RFC 7591 (`registration_endpoint`)
15
+ * → authorization code + PKCE S256 RFC 7636 (MCP requires PKCE; it leaks nothing
16
+ * because the verifier never leaves us)
17
+ * → token exchange / refresh
18
+ *
19
+ * What is modelled from the reference implementations (akku1139/deepseek-pp PR #1 and
20
+ * easywebui), and why:
21
+ * - send a REAL `initialize` POST when probing, because servers police the request
22
+ * shape differently and a bare GET can 200 on a health page;
23
+ * - only trust a 401 that carries a Bearer challenge — a plain 401 with no
24
+ * `WWW-Authenticate` is a "wrong token", not "use OAuth here";
25
+ * - keep the access token in MEMORY only, bound to a fingerprint of the credentials,
26
+ * so a changed client id can never reuse a stale token;
27
+ * - persist the REFRESH token, and persist a ROTATED one immediately — a server that
28
+ * rotates invalidates the old token, and reusing it fails with `invalid_grant`;
29
+ * - re-request the originally granted scopes on refresh, or the token endpoint can
30
+ * return 200 with a token the resource server then refuses.
31
+ *
32
+ * What is DELIBERATELY different: the redirect. easywebui runs serverless and needs a
33
+ * host-provided browser identity port; teapot is a local server with a browser UI, so
34
+ * it runs a real loopback callback (`OAuthPending`). That removes the copy-paste step
35
+ * entirely — the operator opens a URL and the tab closes itself.
36
+ */
37
+ import { createHash, randomBytes } from "node:crypto";
38
+ /**
39
+ * Parse the FIRST Bearer challenge out of a `WWW-Authenticate` header.
40
+ *
41
+ * The header can carry several challenges (`Digest …, Bearer …`), and commas appear
42
+ * both between challenges and INSIDE the Bearer parameters, so this scans for
43
+ * `Bearer` and then reads `key="value"` / `key=token` pairs without splitting on
44
+ * commas — splitting first is the classic way to lose `resource_metadata` when its URL
45
+ * contains one.
46
+ */
47
+ export function parseBearerChallenge(header) {
48
+ if (!header)
49
+ return null;
50
+ const at = header.search(/\bBearer\b/i);
51
+ if (at === -1)
52
+ return null;
53
+ const rest = header.slice(at + "Bearer".length);
54
+ const out = { raw: header };
55
+ // stop at the next scheme if another challenge follows
56
+ const nextScheme = rest.search(/,\s*[A-Za-z][A-Za-z0-9_-]*\s+[^=,\s]/);
57
+ const body = nextScheme === -1 ? rest : rest.slice(0, nextScheme);
58
+ const re = /([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]+))/g;
59
+ let m;
60
+ while ((m = re.exec(body))) {
61
+ const key = m[1].toLowerCase();
62
+ const value = (m[2] ?? m[3] ?? "").replace(/\\(.)/g, "$1");
63
+ if (key === "resource_metadata")
64
+ out.resourceMetadataUrl = value;
65
+ else if (key === "scope")
66
+ out.scope = value;
67
+ else if (key === "error")
68
+ out.error = value;
69
+ }
70
+ return out;
71
+ }
72
+ /** PKCE verifier + S256 challenge (RFC 7636) */
73
+ export function pkcePair() {
74
+ // 32 random bytes → 43 base64url chars, inside the spec's 43..128 range
75
+ const verifier = randomBytes(32).toString("base64url");
76
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
77
+ return { verifier, challenge };
78
+ }
79
+ const PROBE_TIMEOUT_MS = 15_000;
80
+ async function fetchJson(url, signal) {
81
+ const ac = new AbortController();
82
+ const timer = setTimeout(() => ac.abort(), PROBE_TIMEOUT_MS);
83
+ const onAbort = () => ac.abort();
84
+ signal?.addEventListener("abort", onAbort, { once: true });
85
+ try {
86
+ const res = await fetch(url, {
87
+ headers: { accept: "application/json" },
88
+ signal: ac.signal,
89
+ redirect: "follow",
90
+ });
91
+ if (!res.ok)
92
+ throw new Error(`${url} returned HTTP ${res.status}`);
93
+ const text = await res.text();
94
+ try {
95
+ return JSON.parse(text);
96
+ }
97
+ catch {
98
+ // keep the body visible: an HTML login page with a JSON content type is a
99
+ // completely different problem from a malformed metadata document
100
+ throw new Error(`${url} did not return JSON: ${text.slice(0, 160)}`);
101
+ }
102
+ }
103
+ finally {
104
+ clearTimeout(timer);
105
+ signal?.removeEventListener("abort", onAbort);
106
+ }
107
+ }
108
+ const str = (v) => (typeof v === "string" && v ? v : undefined);
109
+ const strList = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string" && !!x) : undefined;
110
+ /**
111
+ * Probe an MCP endpoint and, when it demands OAuth, resolve its authorization server.
112
+ *
113
+ * Returns `requiresOAuth: false` with no error for a healthy endpoint (nothing to do)
114
+ * and for one whose 401 carries no Bearer challenge (a bad token, not a missing grant).
115
+ */
116
+ export async function detectOAuth(endpoint, opts = {}) {
117
+ let url;
118
+ try {
119
+ url = new URL(endpoint);
120
+ }
121
+ catch {
122
+ return { requiresOAuth: false, reason: `invalid url: ${endpoint}` };
123
+ }
124
+ if (!["http:", "https:"].includes(url.protocol))
125
+ return { requiresOAuth: false, reason: `not an http(s) url: ${endpoint}` };
126
+ // A REAL initialize request: servers police the shape differently, and a bare GET
127
+ // often 200s on a landing page, which would read as "no auth needed".
128
+ const ac = new AbortController();
129
+ const timer = setTimeout(() => ac.abort(), PROBE_TIMEOUT_MS);
130
+ const onAbort = () => ac.abort();
131
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
132
+ let res;
133
+ try {
134
+ res = await fetch(url, {
135
+ method: "POST",
136
+ headers: {
137
+ "content-type": "application/json",
138
+ accept: "application/json, text/event-stream",
139
+ ...(opts.headers ?? {}),
140
+ },
141
+ body: JSON.stringify({
142
+ jsonrpc: "2.0",
143
+ id: 1,
144
+ method: "initialize",
145
+ params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "teapot", version: "1" } },
146
+ }),
147
+ // manual so an HTML login page is visible rather than silently followed
148
+ redirect: "manual",
149
+ signal: ac.signal,
150
+ });
151
+ }
152
+ catch (err) {
153
+ return {
154
+ requiresOAuth: false,
155
+ reason: err.name === "AbortError" ? "probe timed out" : err.message,
156
+ };
157
+ }
158
+ finally {
159
+ clearTimeout(timer);
160
+ opts.signal?.removeEventListener("abort", onAbort);
161
+ }
162
+ // drain so the socket is released
163
+ await res.body?.cancel().catch(() => { });
164
+ if (res.status !== 401)
165
+ return { requiresOAuth: false };
166
+ const challenge = parseBearerChallenge(res.headers.get("www-authenticate"));
167
+ if (!challenge)
168
+ return {
169
+ requiresOAuth: false,
170
+ reason: "the server answered 401 without a Bearer challenge — this is a rejected credential, " +
171
+ "not a missing OAuth grant",
172
+ };
173
+ const resource = opts.resource ?? url.toString();
174
+ if (!challenge.resourceMetadataUrl)
175
+ return {
176
+ requiresOAuth: true,
177
+ challenge,
178
+ reason: "the 401 challenge names no resource_metadata document",
179
+ };
180
+ let metadataUrl;
181
+ try {
182
+ // the parameter is usually absolute, but is allowed to be relative
183
+ metadataUrl = new URL(challenge.resourceMetadataUrl, url).toString();
184
+ }
185
+ catch {
186
+ return { requiresOAuth: true, challenge, reason: "the resource_metadata url is malformed" };
187
+ }
188
+ try {
189
+ const protectedResource = await fetchJson(metadataUrl, opts.signal);
190
+ const servers = strList(protectedResource.authorization_servers);
191
+ const issuer = servers?.[0];
192
+ if (!issuer)
193
+ return {
194
+ requiresOAuth: true,
195
+ challenge,
196
+ reason: "the protected-resource metadata names no authorization server",
197
+ };
198
+ // Authorization-server metadata: try EVERY shape the specs define, in order.
199
+ //
200
+ // MEASURED against real servers, which is the only way to get this right:
201
+ //
202
+ // GitHub (issuer https://github.com/login/oauth) serves
203
+ // https://github.com/.well-known/oauth-authorization-server/login/oauth 200
204
+ // https://github.com/login/oauth/.well-known/oauth-authorization-server 404
205
+ // Notion (issuer https://mcp.notion.com, no path) serves the root form.
206
+ //
207
+ // So RFC 8414 §3.1 is "insert the well-known segment BEFORE the issuer's path"
208
+ // (`/.well-known/oauth-authorization-server` + path), and the ".../path/.well-known/…"
209
+ // shape is the **OIDC Discovery 1.0** form, which GitHub uses for
210
+ // `.well-known/openid-configuration`. An earlier version of this code tried only the
211
+ // post-path form and hardcoded the conclusion that the pre-path form was wrong —
212
+ // GitHub returned 404 and the whole discovery failed.
213
+ //
214
+ // Both are legitimate and different providers publish different ones, so the fix is
215
+ // to TRY ALL of them rather than to pick a favourite.
216
+ //
217
+ // Built by string concatenation, NOT `new URL("/.well-known/…", issuer)`: a leading
218
+ // slash replaces the path, which silently drops the issuer's segment.
219
+ const issuerUrl = new URL(issuer);
220
+ const basePath = issuerUrl.pathname.replace(/\/$/, "");
221
+ const candidates = [
222
+ // RFC 8414 §3.1 — well-known BEFORE the path (GitHub's shape)
223
+ `${issuerUrl.origin}/.well-known/oauth-authorization-server${basePath}`,
224
+ // OIDC Discovery 1.0 §4 — well-known AFTER the path
225
+ `${issuerUrl.origin}${basePath}/.well-known/openid-configuration`,
226
+ // the same two for the OAuth metadata name, for providers that publish both
227
+ `${issuerUrl.origin}${basePath}/.well-known/oauth-authorization-server`,
228
+ // no path at all: the common case for a bare issuer
229
+ `${issuerUrl.origin}/.well-known/oauth-authorization-server`,
230
+ ];
231
+ let meta = null;
232
+ let lastErr = "";
233
+ for (const candidate of [...new Set(candidates)]) {
234
+ try {
235
+ const m = await fetchJson(candidate, opts.signal);
236
+ // accept only a document that actually describes an authorization server
237
+ if (str(m.authorization_endpoint) && str(m.token_endpoint)) {
238
+ meta = m;
239
+ break;
240
+ }
241
+ lastErr = `${candidate} has no authorization_endpoint/token_endpoint`;
242
+ }
243
+ catch (e) {
244
+ lastErr = e.message;
245
+ }
246
+ }
247
+ if (!meta) {
248
+ return {
249
+ requiresOAuth: true,
250
+ challenge,
251
+ reason: `could not resolve authorization-server metadata for ${issuer}: ${lastErr}`,
252
+ };
253
+ }
254
+ // `meta` is guaranteed to carry both endpoints by the loop above.
255
+ const authorizationEndpoint = meta.authorization_endpoint;
256
+ const tokenEndpoint = meta.token_endpoint;
257
+ return {
258
+ requiresOAuth: true,
259
+ challenge,
260
+ authServer: {
261
+ authorizationEndpoint,
262
+ tokenEndpoint,
263
+ ...(str(meta.registration_endpoint)
264
+ ? { registrationEndpoint: meta.registration_endpoint }
265
+ : {}),
266
+ // the RESOURCE's scopes win: they describe what this MCP server accepts
267
+ scopes: strList(protectedResource.scopes_supported) ?? strList(meta.scopes_supported) ?? [],
268
+ resource,
269
+ ...(str(meta.issuer) ? { issuer: meta.issuer } : {}),
270
+ },
271
+ };
272
+ }
273
+ catch (err) {
274
+ return { requiresOAuth: true, challenge, reason: err.message };
275
+ }
276
+ }
277
+ /** POST an `application/x-www-form-urlencoded` body; returns the JSON response */
278
+ async function postForm(url, body, signal) {
279
+ const ac = new AbortController();
280
+ const timer = setTimeout(() => ac.abort(), PROBE_TIMEOUT_MS);
281
+ const onAbort = () => ac.abort();
282
+ signal?.addEventListener("abort", onAbort, { once: true });
283
+ try {
284
+ const res = await fetch(url, {
285
+ method: "POST",
286
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
287
+ body: new URLSearchParams(body).toString(),
288
+ signal: ac.signal,
289
+ });
290
+ const text = await res.text();
291
+ let json = {};
292
+ try {
293
+ json = text ? JSON.parse(text) : {};
294
+ }
295
+ catch {
296
+ /* an HTML error page — reported with the status below */
297
+ }
298
+ if (!res.ok) {
299
+ const detail = str(json.error_description) ?? str(json.error) ?? text.slice(0, 200);
300
+ throw new Error(`${url} returned HTTP ${res.status}: ${detail || "(no body)"}`);
301
+ }
302
+ return json;
303
+ }
304
+ finally {
305
+ clearTimeout(timer);
306
+ signal?.removeEventListener("abort", onAbort);
307
+ }
308
+ }
309
+ const toExpiry = (v) => {
310
+ const n = typeof v === "number" ? v : typeof v === "string" ? Number(v) : NaN;
311
+ return Number.isFinite(n) && n > 0 ? Date.now() + n * 1000 : null;
312
+ };
313
+ const tokensFrom = (payload, keepRefresh) => {
314
+ const accessToken = str(payload.access_token);
315
+ if (!accessToken)
316
+ throw new Error("the token endpoint returned no access_token");
317
+ const out = {
318
+ accessToken,
319
+ tokenType: str(payload.token_type) ?? "Bearer",
320
+ expiresAt: toExpiry(payload.expires_in),
321
+ };
322
+ const rt = str(payload.refresh_token) ?? keepRefresh;
323
+ if (rt)
324
+ out.refreshToken = rt;
325
+ if (str(payload.scope))
326
+ out.scope = payload.scope;
327
+ return out;
328
+ };
329
+ /**
330
+ * Dynamic client registration (RFC 7591).
331
+ *
332
+ * Required by the MCP spec for servers that hand out no static client id. Sent as a
333
+ * public client (`token_endpoint_auth_method: "none"`) because a local harness cannot
334
+ * keep a client secret meaningful — the code runs on the operator's own machine.
335
+ */
336
+ export async function registerClient(registrationEndpoint, redirectUri, signal) {
337
+ const ac = new AbortController();
338
+ const timer = setTimeout(() => ac.abort(), PROBE_TIMEOUT_MS);
339
+ const onAbort = () => ac.abort();
340
+ signal?.addEventListener("abort", onAbort, { once: true });
341
+ try {
342
+ const res = await fetch(registrationEndpoint, {
343
+ method: "POST",
344
+ headers: { "content-type": "application/json", accept: "application/json" },
345
+ body: JSON.stringify({
346
+ client_name: "teapot",
347
+ redirect_uris: [redirectUri],
348
+ grant_types: ["authorization_code", "refresh_token"],
349
+ response_types: ["code"],
350
+ token_endpoint_auth_method: "none",
351
+ }),
352
+ signal: ac.signal,
353
+ });
354
+ const text = await res.text();
355
+ if (!res.ok)
356
+ throw new Error(`dynamic client registration failed (HTTP ${res.status}): ${text.slice(0, 200)}`);
357
+ const json = JSON.parse(text);
358
+ const clientId = str(json.client_id);
359
+ if (!clientId)
360
+ throw new Error("dynamic client registration returned no client_id");
361
+ return { clientId, ...(str(json.client_secret) ? { clientSecret: json.client_secret } : {}) };
362
+ }
363
+ finally {
364
+ clearTimeout(timer);
365
+ signal?.removeEventListener("abort", onAbort);
366
+ }
367
+ }
368
+ /** build the URL the operator is sent to */
369
+ export function buildAuthorizeUrl(input) {
370
+ const url = new URL(input.authServer.authorizationEndpoint);
371
+ url.searchParams.set("response_type", "code");
372
+ url.searchParams.set("client_id", input.clientId);
373
+ url.searchParams.set("redirect_uri", input.redirectUri);
374
+ url.searchParams.set("code_challenge", input.codeChallenge);
375
+ // S256 only: MCP requires PKCE and forbids `plain`
376
+ url.searchParams.set("code_challenge_method", "S256");
377
+ url.searchParams.set("state", input.state);
378
+ const scopes = input.scopes?.length ? input.scopes : input.authServer.scopes;
379
+ if (scopes.length)
380
+ url.searchParams.set("scope", scopes.join(" "));
381
+ // RFC 8707: bind the grant to THIS resource, so a token minted for another server
382
+ // cannot be replayed here
383
+ if (input.authServer.resource)
384
+ url.searchParams.set("resource", input.authServer.resource);
385
+ return url.toString();
386
+ }
387
+ /** exchange an authorization code for tokens */
388
+ export async function exchangeCode(input) {
389
+ const body = {
390
+ grant_type: "authorization_code",
391
+ code: input.code,
392
+ code_verifier: input.codeVerifier,
393
+ redirect_uri: input.redirectUri,
394
+ client_id: input.clientId,
395
+ };
396
+ if (input.clientSecret)
397
+ body.client_secret = input.clientSecret;
398
+ if (input.authServer.resource)
399
+ body.resource = input.authServer.resource;
400
+ const payload = await postForm(input.authServer.tokenEndpoint, body, input.signal);
401
+ return tokensFrom(payload);
402
+ }
403
+ /**
404
+ * Refresh an access token.
405
+ *
406
+ * The previously granted SCOPES are re-requested: a refresh that silently drops them
407
+ * can return 200 with a token the resource server then refuses, which looks like an
408
+ * authentication failure at the wrong end of the chain. A ROTATED refresh token is
409
+ * returned in the result so the caller can persist it immediately — a server that
410
+ * rotates invalidates the old one, so a discarded rotation breaks the next refresh.
411
+ */
412
+ export async function refreshTokens(input) {
413
+ const body = {
414
+ grant_type: "refresh_token",
415
+ refresh_token: input.refreshToken,
416
+ client_id: input.clientId,
417
+ };
418
+ if (input.clientSecret)
419
+ body.client_secret = input.clientSecret;
420
+ const scopes = input.scopes?.length ? input.scopes : input.authServer.scopes;
421
+ if (scopes.length)
422
+ body.scope = scopes.join(" ");
423
+ if (input.authServer.resource)
424
+ body.resource = input.authServer.resource;
425
+ const payload = await postForm(input.authServer.tokenEndpoint, body, input.signal);
426
+ // keepRefresh: a server that does not rotate omits refresh_token, and dropping it
427
+ // would end the grant after one refresh
428
+ return tokensFrom(payload, input.refreshToken);
429
+ }
@@ -15,6 +15,7 @@
15
15
  * original name is what gets sent to the server.
16
16
  */
17
17
  import { connectMcp, McpError } from "./mcp.js";
18
+ import { oauth } from "./mcp-oauth-manager.js";
18
19
  /** the prefix a model-visible MCP tool name carries */
19
20
  export const MCP_PREFIX = "mcp__";
20
21
  /** `mcp__server__tool` — the flat name handed to the LLM */
@@ -75,7 +76,19 @@ export class McpRegistry {
75
76
  states() {
76
77
  return [...this.servers.values()];
77
78
  }
78
- /** connect one server (idempotent) and discover its tools */
79
+ /** the OAuth state for one server, for the settings panel */
80
+ oauthStatus(name) {
81
+ return oauth.status(name);
82
+ }
83
+ /**
84
+ * Connect one server (idempotent) and discover its tools.
85
+ *
86
+ * A 401 is not the end of the story: an OAuth-protected server answers with a Bearer
87
+ * challenge, so on auth failure we DETECT and RECORD that, which is what lets the
88
+ * settings panel offer "authorize" instead of showing a bare "error". Detection is
89
+ * tried BEFORE the challenge reaches the operator — the reference implementations do
90
+ * the same, and it turns "it just says 401" into "click authorize".
91
+ */
79
92
  async connect(name) {
80
93
  const st = this.servers.get(name);
81
94
  if (!st)
@@ -88,8 +101,15 @@ export class McpRegistry {
88
101
  return st;
89
102
  st.status = "connecting";
90
103
  st.lastError = undefined;
104
+ // Attach the OAuth authorization when a grant exists, resolved PER REQUEST so a
105
+ // refreshed token takes effect without reconnecting.
106
+ const withOAuth = {
107
+ ...st.config,
108
+ oauthAuthorization: () => oauth.authorization(name),
109
+ onUnauthorized: () => oauth.invalidate(name),
110
+ };
91
111
  try {
92
- const conn = await connectMcp(st.config);
112
+ const conn = await connectMcp(withOAuth);
93
113
  const tools = await conn.tools();
94
114
  st.connection = conn;
95
115
  st.tools = tools;
@@ -103,6 +123,29 @@ export class McpRegistry {
103
123
  st.lastChecked = Date.now();
104
124
  st.connection = undefined;
105
125
  st.tools = [];
126
+ // A 401 means "find out what auth this wants" — the challenge names it. Only for
127
+ // HTTP transports: a stdio server has no OAuth to discover.
128
+ if (err instanceof McpError && err.authRequired && st.config.url) {
129
+ try {
130
+ const d = await oauth.detect(name, st.config.url, {
131
+ ...(st.config.headers ? { headers: st.config.headers } : {}),
132
+ });
133
+ if (d.requiresOAuth) {
134
+ st.oauthRequired = true;
135
+ st.lastError =
136
+ `this server requires OAuth` +
137
+ (d.authServer
138
+ ? ` (authorization server: ${new URL(d.authServer.authorizationEndpoint).host})`
139
+ : d.reason
140
+ ? ` — ${d.reason}`
141
+ : "") +
142
+ " — use “authorize” in ⚙ settings → MCP servers";
143
+ }
144
+ }
145
+ catch {
146
+ /* detection is best-effort: the original error stands */
147
+ }
148
+ }
106
149
  throw err;
107
150
  }
108
151
  }
package/dist/agent/mcp.js CHANGED
@@ -167,6 +167,22 @@ async function connectHttp(cfg) {
167
167
  accept: "application/json, text/event-stream",
168
168
  ...(cfg.headers ?? {}),
169
169
  };
170
+ // OAuth wins over a static authorization header: it is the more specific grant, and
171
+ // resolving it per request is what lets a refresh take effect mid-session.
172
+ if (cfg.oauthAuthorization) {
173
+ const auth = await cfg.oauthAuthorization().catch(() => null);
174
+ if (auth) {
175
+ // Remove any spelling of the header the CONFIG supplied first. Keys are
176
+ // case-insensitive on the wire but not in a JS object, so leaving
177
+ // `Authorization` beside `authorization` would send BOTH and let the server
178
+ // pick — the exact ambiguity this precedence rule exists to remove.
179
+ for (const k of Object.keys(headers)) {
180
+ if (k.toLowerCase() === "authorization")
181
+ delete headers[k];
182
+ }
183
+ headers.authorization = auth;
184
+ }
185
+ }
170
186
  if (sessionId)
171
187
  headers["mcp-session-id"] = sessionId;
172
188
  if (version)
@@ -197,6 +213,10 @@ async function connectHttp(cfg) {
197
213
  const body = (await res.text().catch(() => "")).slice(0, 300);
198
214
  if (res.status === 405)
199
215
  throw new McpError(`MCP endpoint answered 405 — it does not accept POST (Streamable HTTP): ${body || "(no body)"}`);
216
+ // Tell the caller so it can drop a cached token: a 401 here means the access
217
+ // token was rejected, and retrying with the same one would loop.
218
+ if (res.status === 401 || res.status === 403)
219
+ cfg.onUnauthorized?.();
200
220
  throw new McpError(`MCP server returned HTTP ${res.status}: ${body || "(no body)"}`, res.status === 401 || res.status === 403);
201
221
  }
202
222
  if (notification) {
package/dist/master.js CHANGED
@@ -1915,49 +1915,80 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
1915
1915
  * (the files survived, but nothing in the UI could reach them again).
1916
1916
  */
1917
1917
  async archiveAgent(id) {
1918
- const ac = this.config.agents.find((a) => a.id === id);
1919
- if (!ac)
1918
+ const root = this.config.agents.find((a) => a.id === id);
1919
+ if (!root)
1920
1920
  throw new Error(`no such agent: ${id}`);
1921
- const live = this.agents.get(id);
1922
- if (live) {
1923
- this.agents.delete(id);
1924
- await live.dispose();
1921
+ // The whole SUBTREE goes with it. A sub-agent whose parent is archived can never
1922
+ // run again — its parent is what spawns and messages it — so leaving it un-archived
1923
+ // put orphans in the list that look usable and are not. The descendants are found
1924
+ // from the config (not the live map), so sub-agents that are already stopped or
1925
+ // suspended are included.
1926
+ const ids = [id, ...this.subtreeOf(id).map((s) => s.id)];
1927
+ const now = Date.now();
1928
+ for (const one of ids) {
1929
+ const live = this.agents.get(one);
1930
+ if (live) {
1931
+ this.agents.delete(one);
1932
+ await live.dispose();
1933
+ }
1934
+ const ac = this.config.agents.find((a) => a.id === one);
1935
+ if (!ac)
1936
+ continue;
1937
+ ac.archived = true;
1938
+ ac.archivedAt = now;
1925
1939
  }
1926
- ac.archived = true;
1927
- ac.archivedAt = Date.now();
1928
1940
  this.saveConfig();
1929
- return { archived: true };
1941
+ return { archived: true, ids };
1930
1942
  }
1931
- /** Bring an archived agent back. Its session pointer was never touched. */
1943
+ /**
1944
+ * Bring an archived agent back. Its session pointer was never touched.
1945
+ *
1946
+ * Restores the SUBTREE too, because archiving took it: a parent restored without its
1947
+ * children would come back unable to reach the work it delegated, and the children
1948
+ * would sit invisibly in the archive with no way to know why.
1949
+ */
1932
1950
  async restoreAgent(id) {
1933
1951
  const ac = this.config.agents.find((a) => a.id === id);
1934
1952
  if (!ac)
1935
1953
  throw new Error(`no such agent: ${id}`);
1936
- delete ac.archived;
1937
- delete ac.archivedAt;
1954
+ const ids = [id, ...this.subtreeOf(id).map((s) => s.id)];
1955
+ for (const one of ids) {
1956
+ const e = this.config.agents.find((a) => a.id === one);
1957
+ if (!e)
1958
+ continue;
1959
+ delete e.archived;
1960
+ delete e.archivedAt;
1961
+ }
1938
1962
  this.saveConfig();
1939
1963
  // start it again unless it was never configured to run (it is in the list, so it
1940
1964
  // was) — a restore is the operator asking for it back, so it comes back LIVE
1941
1965
  try {
1942
1966
  await this.addAgent(ac);
1943
- return { restored: true, live: true };
1967
+ return { restored: true, live: true, ids };
1944
1968
  }
1945
1969
  catch (err) {
1946
1970
  // the entry is restored either way; starting it can fail on a provider/auth
1947
1971
  // problem, and reporting that is more useful than undoing the restore
1948
1972
  console.error(`[teapot] restored "${id}" but could not start it: ${err.message}`);
1949
- return { restored: true, live: false };
1973
+ return { restored: true, live: false, ids };
1950
1974
  }
1951
1975
  }
1952
1976
  /** Archived entries, newest first — what the settings panel lists. */
1953
1977
  archivedAgents() {
1954
- return this.config.agents
1955
- .filter((a) => a.archived)
1978
+ const archived = this.config.agents.filter((a) => a.archived);
1979
+ const ids = new Set(archived.map((a) => a.id));
1980
+ return archived
1956
1981
  .map((a) => ({
1957
1982
  id: a.id,
1958
1983
  workspace: a.workspace,
1959
1984
  ...(a.archivedAt !== undefined ? { archivedAt: a.archivedAt } : {}),
1960
1985
  sessions: this.sessionsOf(a.id).length,
1986
+ // A sub-agent is listed under its parent rather than as an equal entry: the
1987
+ // operator archived ONE thing, and a flat list of every descendant makes it
1988
+ // look like they did several. Only an ARCHIVED parent counts — otherwise a
1989
+ // live parent would hide a genuinely standalone entry.
1990
+ ...(a.parent && ids.has(a.parent) ? { parent: a.parent } : {}),
1991
+ subs: this.subtreeOf(a.id).filter((s) => ids.has(s.id)).length,
1961
1992
  }))
1962
1993
  .sort((a, b) => (b.archivedAt ?? 0) - (a.archivedAt ?? 0));
1963
1994
  }