@tool-bridge/server 0.26.2 → 0.28.0

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.
@@ -8,9 +8,10 @@ import {
8
8
  pkceChallenge
9
9
  } from "./chunk-U7PTOA3U.js";
10
10
  import {
11
+ BootstrapLockBusyError,
11
12
  BootstrapStateStore,
12
13
  package_default
13
- } from "./chunk-KTWFYFDL.js";
14
+ } from "./chunk-A5VV3P2S.js";
14
15
  import {
15
16
  createGuardedFetch
16
17
  } from "./chunk-NXLE6ZEK.js";
@@ -18231,9 +18232,10 @@ var PgStateStore = class {
18231
18232
 
18232
18233
  // src/keyManager.ts
18233
18234
  import { randomBytes, randomUUID as randomUUID2 } from "crypto";
18234
- import postgres from "postgres";
18235
+ import postgres2 from "postgres";
18235
18236
 
18236
18237
  // src/pgMaintenanceFence.ts
18238
+ import postgres from "postgres";
18237
18239
  import { createHash } from "crypto";
18238
18240
  function routerIdentity(url3) {
18239
18241
  return createHash("sha256").update(url3 ? new URL(url3).href : "local-only").digest("hex");
@@ -18248,6 +18250,7 @@ async function ensureRuntimeCoordinationSchema(sql) {
18248
18250
  await tx`CREATE TABLE IF NOT EXISTS tb_runtime_router (
18249
18251
  instance_id text PRIMARY KEY, identity text NOT NULL, enforce_identity boolean NOT NULL DEFAULT false)`;
18250
18252
  await tx`ALTER TABLE tb_runtime_replicas ADD COLUMN IF NOT EXISTS router_identity text`;
18253
+ await tx`ALTER TABLE tb_runtime_replicas ADD COLUMN IF NOT EXISTS session_fenced boolean NOT NULL DEFAULT false`;
18251
18254
  await tx`CREATE OR REPLACE FUNCTION tb_check_runtime_router() RETURNS trigger LANGUAGE plpgsql AS $$
18252
18255
  BEGIN
18253
18256
  IF EXISTS (SELECT 1 FROM tb_runtime_router WHERE instance_id=NEW.instance_id AND enforce_identity
@@ -18272,74 +18275,100 @@ async function assertRuntimeAuthority(sql, replicaId) {
18272
18275
  AND (owner_replica_id<>${replicaId} OR (purpose='database' AND phase<>'copying'))`;
18273
18276
  if (rows.length) throw new TBError("unavailable", "database authority is fenced for protected maintenance");
18274
18277
  }
18275
- async function runtimeLockHeld(sql, backendPid, mode = "ShareLock") {
18276
- if (backendPid === void 0) return false;
18277
- const [row] = await sql`SELECT EXISTS(SELECT 1 FROM pg_locks
18278
- WHERE pid=${backendPid} AND locktype='advisory' AND mode=${mode} AND granted) AS held`;
18279
- return row?.held === true;
18278
+ var RuntimeHandoffPendingError = class extends TBError {
18279
+ constructor(message = "another runtime still holds the database session lock") {
18280
+ super("unavailable", message, { retryable: true });
18281
+ this.name = "RuntimeHandoffPendingError";
18282
+ }
18283
+ };
18284
+ function lockConnection(sql, onclose) {
18285
+ const options = { ...sql.options, max: 1, idle_timeout: 0, max_lifetime: null, onclose };
18286
+ return postgres(options);
18287
+ }
18288
+ async function tryRuntimeLock(sql, shared) {
18289
+ const [row] = await sql`SELECT pg_backend_pid() AS pid, key::text,
18290
+ CASE WHEN ${shared}::boolean THEN pg_try_advisory_lock_shared(key) ELSE pg_try_advisory_lock(key) END AS acquired
18291
+ FROM (SELECT hashtextextended(current_schema() || ':tool-bridge-runtime',${RUNTIME_LOCK}) AS key) AS runtime`;
18292
+ return row?.acquired ? row : void 0;
18293
+ }
18294
+ async function runtimeLockHeld(sql, lock, shared) {
18295
+ const rows = await sql`SELECT 1 FROM pg_catalog.pg_locks
18296
+ WHERE locktype='advisory' AND granted AND pid=pg_backend_pid() AND pid=${lock.pid}
18297
+ AND database=(SELECT oid FROM pg_catalog.pg_database WHERE datname=current_database())
18298
+ AND mode=${shared ? "ShareLock" : "ExclusiveLock"} AND objsubid=1
18299
+ AND classid=((${lock.key}::bigint >> 32) & 4294967295)::oid
18300
+ AND objid=(${lock.key}::bigint & 4294967295)::oid`;
18301
+ return rows.length === 1;
18280
18302
  }
18281
18303
  async function acquireRuntimeLease(sql, input) {
18282
- await ensureRuntimeCoordinationSchema(sql);
18283
- const session = await sql.reserve();
18284
- let released = false;
18285
- let admitted = false;
18286
18304
  const router = routerIdentity(input.redisUrl);
18287
- let held = false;
18288
- let backendPid;
18289
- let lost = false;
18290
- const heartbeat = async () => {
18291
- if (released) throw new TBError("unavailable", "runtime lease has been released");
18292
- if (lost) throw new TBError("unavailable", "runtime database session was lost; drain and restart this replica");
18293
- await sql.begin(async (tx) => {
18294
- await tx`SELECT pg_advisory_xact_lock(${COORDINATION_LOCK})`;
18295
- await assertRuntimeAuthority(tx, input.replicaId);
18296
- if (!held) {
18297
- const [row] = await session`SELECT pg_backend_pid() AS pid,
18298
- pg_try_advisory_lock_shared(hashtextextended(current_schema() || ':tool-bridge-runtime',${RUNTIME_LOCK})) AS acquired`;
18299
- if (!row?.acquired) throw new TBError("unavailable", "database migration is draining its previous authority");
18300
- held = true;
18301
- backendPid = row.pid;
18302
- } else {
18303
- if (!await runtimeLockHeld(tx, backendPid)) {
18304
- lost = true;
18305
- throw new TBError("unavailable", "runtime database session was lost; drain and restart this replica");
18306
- }
18307
- }
18308
- if (!admitted) {
18309
- await tx`INSERT INTO tb_runtime_router(instance_id,identity) VALUES(${input.instanceId},${router}) ON CONFLICT DO NOTHING`;
18310
- const [current] = await tx`SELECT identity FROM tb_runtime_router WHERE instance_id=${input.instanceId}`;
18311
- if (current?.identity !== router) throw new TBError("conflict", "Redis configuration differs from the active router; update this replica before joining");
18312
- const duplicate = await tx`SELECT 1 FROM tb_runtime_replicas WHERE replica_id=${input.replicaId}`;
18313
- if (duplicate.length) throw new TBError("conflict", "runtime replica ID is already registered; drain the previous runtime");
18314
- }
18315
- const others = await tx`SELECT 1 FROM tb_runtime_replicas
18316
- WHERE instance_id=${input.instanceId} AND replica_id<>${input.replicaId} AND expires_at>now()`;
18317
- if (others.length && !input.redisUrl) throw new TBError("unavailable", "multiple replicas require a configured Redis device router");
18318
- await tx`INSERT INTO tb_runtime_replicas(replica_id,instance_id,expires_at,router_identity)
18319
- VALUES(${input.replicaId},${input.instanceId},now()+interval '60 seconds',${router})
18320
- ON CONFLICT(replica_id) DO UPDATE SET expires_at=excluded.expires_at`;
18321
- });
18305
+ const shared = Boolean(input.redisUrl);
18306
+ await ensureRuntimeCoordinationSchema(sql);
18307
+ let registered = false;
18308
+ let lost;
18309
+ let releasing;
18310
+ const markLost = () => {
18311
+ if (!lost) {
18312
+ lost = new TBError("unavailable", "runtime database session was lost; drain and restart this replica");
18313
+ if (registered && !releasing) input.onLost?.();
18314
+ }
18315
+ return lost;
18322
18316
  };
18323
- const release = async () => {
18324
- if (released) return;
18325
- released = true;
18317
+ const session = lockConnection(sql, markLost);
18318
+ const checkSession = () => {
18319
+ if (releasing) throw new TBError("unavailable", "runtime lease has been released");
18320
+ if (lost) throw lost;
18321
+ };
18322
+ const release = () => releasing ??= (async () => {
18326
18323
  try {
18327
- if (admitted) await sql`DELETE FROM tb_runtime_replicas WHERE replica_id=${input.replicaId}`;
18324
+ if (registered) await sql`DELETE FROM tb_runtime_replicas WHERE replica_id=${input.replicaId}`;
18328
18325
  } finally {
18329
- try {
18330
- if (held && await runtimeLockHeld(sql, backendPid)) await session`SELECT pg_advisory_unlock_shared(hashtextextended(current_schema() || ':tool-bridge-runtime',${RUNTIME_LOCK}))`;
18331
- } finally {
18332
- session.release();
18333
- }
18326
+ await session.end({ timeout: 5 });
18334
18327
  }
18335
- };
18328
+ })();
18336
18329
  try {
18337
- await heartbeat();
18338
- admitted = true;
18339
- return { heartbeat, release };
18340
- } catch (error) {
18341
- await release().catch(() => {
18330
+ const lock = await session.begin(async (tx) => {
18331
+ await tx`SELECT pg_advisory_xact_lock(${COORDINATION_LOCK})`;
18332
+ await assertRuntimeAuthority(tx, input.replicaId);
18333
+ await tx`INSERT INTO tb_runtime_router(instance_id,identity) VALUES(${input.instanceId},${router}) ON CONFLICT DO NOTHING`;
18334
+ const [current] = await tx`SELECT identity FROM tb_runtime_router WHERE instance_id=${input.instanceId}`;
18335
+ if (current?.identity !== router) throw new TBError("conflict", "Redis configuration differs from the active router; update this replica before joining");
18336
+ const lock2 = await tryRuntimeLock(tx, shared);
18337
+ if (!lock2) {
18338
+ const maintenance = await tx`SELECT 1 FROM tb_runtime_maintenance WHERE id=1 AND expires_at>now()`;
18339
+ if (shared || maintenance.length) throw new TBError("unavailable", "database authority is held by another runtime or maintenance");
18340
+ throw new RuntimeHandoffPendingError();
18341
+ }
18342
+ if (!shared) {
18343
+ const legacy = await tx`SELECT 1 FROM tb_runtime_replicas WHERE instance_id=${input.instanceId}
18344
+ AND session_fenced=false AND expires_at>now() LIMIT 1`;
18345
+ if (legacy.length) throw new RuntimeHandoffPendingError("waiting for the previous gateway version to drain");
18346
+ }
18347
+ const inserted = await tx`INSERT INTO tb_runtime_replicas(replica_id,instance_id,expires_at,router_identity,session_fenced)
18348
+ VALUES(${input.replicaId},${input.instanceId},now()+interval '60 seconds',${router},true)
18349
+ ON CONFLICT(replica_id) DO NOTHING RETURNING replica_id`;
18350
+ if (!inserted.length) throw new TBError("conflict", "runtime replica ID is already registered; drain the previous runtime");
18351
+ return lock2;
18342
18352
  });
18353
+ registered = true;
18354
+ checkSession();
18355
+ return {
18356
+ heartbeat: async () => {
18357
+ checkSession();
18358
+ await session.begin(async (tx) => {
18359
+ await tx`SELECT pg_advisory_xact_lock(${COORDINATION_LOCK})`;
18360
+ checkSession();
18361
+ await assertRuntimeAuthority(tx, input.replicaId);
18362
+ const updated = await tx`UPDATE tb_runtime_replicas SET expires_at=now()+interval '60 seconds'
18363
+ WHERE replica_id=${input.replicaId} RETURNING replica_id`;
18364
+ if (!updated.length || !await runtimeLockHeld(tx, lock, shared)) throw markLost();
18365
+ });
18366
+ checkSession();
18367
+ },
18368
+ release
18369
+ };
18370
+ } catch (error) {
18371
+ await release();
18343
18372
  throw error;
18344
18373
  }
18345
18374
  }
@@ -18358,27 +18387,24 @@ async function acquireMaintenanceFence(sql, input, purpose) {
18358
18387
  purpose=excluded.purpose,phase=excluded.phase,operation_id=excluded.operation_id`;
18359
18388
  });
18360
18389
  let session;
18361
- let locked = false;
18362
- let backendPid;
18363
18390
  const releaseLock = async () => {
18364
18391
  const previous = session;
18365
18392
  session = void 0;
18366
- if (!previous) return;
18367
- try {
18368
- if (locked && await runtimeLockHeld(sql, backendPid, "ExclusiveLock")) await previous`SELECT pg_advisory_unlock(hashtextextended(current_schema() || ':tool-bridge-runtime',${RUNTIME_LOCK}))`;
18369
- } finally {
18370
- locked = false;
18371
- previous.release();
18372
- }
18393
+ await previous?.end();
18373
18394
  };
18374
18395
  return {
18375
18396
  drain: async () => {
18376
- session = await sql.reserve();
18377
- const [row] = await session`SELECT pg_backend_pid() AS pid,
18378
- pg_try_advisory_lock(hashtextextended(current_schema() || ':tool-bridge-runtime',${RUNTIME_LOCK})) AS acquired`;
18379
- if (!row?.acquired) throw new TBError("conflict", "another runtime still holds this database; stop it before migration");
18380
- locked = true;
18381
- backendPid = row.pid;
18397
+ if (session) throw new TBError("conflict", "maintenance already has a drain in progress");
18398
+ const attempt2 = lockConnection(sql);
18399
+ session = attempt2;
18400
+ try {
18401
+ if (!await tryRuntimeLock(attempt2, false))
18402
+ throw new TBError("conflict", "another runtime still holds this database; stop it before migration");
18403
+ } catch (error) {
18404
+ if (session === attempt2) session = void 0;
18405
+ await attempt2.end();
18406
+ throw error;
18407
+ }
18382
18408
  },
18383
18409
  retire: async () => {
18384
18410
  const rows = await sql`UPDATE tb_runtime_maintenance SET phase='retired'
@@ -18436,7 +18462,7 @@ var KeyManager = class {
18436
18462
  constructor(hooks, options = {}) {
18437
18463
  this.hooks = hooks;
18438
18464
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
18439
- this.connect = options.connect ?? ((url3) => postgres(url3, { max: 3, connect_timeout: 5, onnotice: () => {
18465
+ this.connect = options.connect ?? ((url3) => postgres2(url3, { max: 3, connect_timeout: 5, onnotice: () => {
18440
18466
  } }));
18441
18467
  }
18442
18468
  hooks;
@@ -18640,7 +18666,7 @@ var KeyManager = class {
18640
18666
  // src/maintenanceManager.ts
18641
18667
  import { chmod, mkdtemp, rm, writeFile } from "fs/promises";
18642
18668
  import { execFile } from "child_process";
18643
- import postgres2 from "postgres";
18669
+ import postgres3 from "postgres";
18644
18670
  import { randomUUID as randomUUID3 } from "crypto";
18645
18671
  import { promisify } from "util";
18646
18672
  import { tmpdir } from "os";
@@ -18731,7 +18757,7 @@ async function probeRedis(redisUrl) {
18731
18757
  }
18732
18758
  }
18733
18759
  function sqlClient(url3) {
18734
- return postgres2(url3, {
18760
+ return postgres3(url3, {
18735
18761
  max: 2,
18736
18762
  connect_timeout: 5,
18737
18763
  idle_timeout: 5,
@@ -20600,9 +20626,9 @@ var PgSearchIndex = class extends SqlSearchIndex {
20600
20626
  };
20601
20627
 
20602
20628
  // src/server.ts
20603
- import { serve } from "@hono/node-server";
20604
20629
  import { AsyncLocalStorage } from "async_hooks";
20605
- import postgres3 from "postgres";
20630
+ import postgres4 from "postgres";
20631
+ import { serve } from "@hono/node-server";
20606
20632
  import { randomUUID as randomUUID10 } from "crypto";
20607
20633
  import { Hono as Hono4 } from "hono";
20608
20634
 
@@ -20957,7 +20983,8 @@ import { z as z7 } from "zod";
20957
20983
  var MCP_OAUTH_CLIENT_ID = "https://chatgpt.com/oauth/client.json";
20958
20984
  var MCP_OAUTH_REDIRECT_URI = "https://chatgpt.com/connector_platform_oauth_redirect";
20959
20985
  var MCP_OAUTH_SCOPE = "mcp";
20960
- var ACCESS_TOKEN_LIFETIME = 3600;
20986
+ var MCP_OAUTH_ACCESS_TOKEN_LIFETIME = 3600;
20987
+ var MCP_OAUTH_REFRESH_TOKEN_LIFETIME = 90 * 24 * 3600;
20961
20988
  var RECORD_PREFIX = "mcp-inbound:";
20962
20989
  var grantRecord = z7.object({
20963
20990
  clientId: z7.literal(MCP_OAUTH_CLIENT_ID),
@@ -20977,8 +21004,9 @@ function mcpClient() {
20977
21004
  return {
20978
21005
  id: MCP_OAUTH_CLIENT_ID,
20979
21006
  redirectUris: [MCP_OAUTH_REDIRECT_URI],
20980
- grants: ["authorization_code"],
20981
- accessTokenLifetime: ACCESS_TOKEN_LIFETIME
21007
+ grants: ["authorization_code", "refresh_token"],
21008
+ accessTokenLifetime: MCP_OAUTH_ACCESS_TOKEN_LIFETIME,
21009
+ refreshTokenLifetime: MCP_OAUTH_REFRESH_TOKEN_LIFETIME
20982
21010
  };
20983
21011
  }
20984
21012
  function isMcpScope(scope) {
@@ -21011,8 +21039,8 @@ async function activeKey(state, keyId, now) {
21011
21039
  const key = await state.get(KEY_SK_HASH + hash2);
21012
21040
  return key?.id === keyId && key.hash === hash2 && isKeyActive(key, now) ? key : null;
21013
21041
  }
21014
- async function readAccessToken(state, issuer, token, now) {
21015
- const parsed = grantRecord.safeParse(await state.get(await recordKey("token", issuer, token)));
21042
+ async function readGrant(state, kind, issuer, value, now) {
21043
+ const parsed = grantRecord.safeParse(await state.get(await recordKey(kind, issuer, value)));
21016
21044
  if (!parsed.success || !isCurrentGrant(parsed.data, issuer, now)) return null;
21017
21045
  const key = await activeKey(state, parsed.data.keyId, now);
21018
21046
  return key && { record: parsed.data, key };
@@ -21071,15 +21099,34 @@ function createMcpOAuthModel(state, issuer) {
21071
21099
  async saveToken(token, client, user) {
21072
21100
  const now = /* @__PURE__ */ new Date();
21073
21101
  const keyId = user.id;
21074
- const { accessToken, accessTokenExpiresAt } = token;
21075
- if (client.id !== MCP_OAUTH_CLIENT_ID || !isMcpScope(token.scope) || !accessToken || !accessTokenExpiresAt || !(accessTokenExpiresAt > now) || typeof keyId !== "string" || !await activeKey(state, keyId, now.toISOString())) return null;
21076
- const record3 = newGrant(issuer, keyId, accessTokenExpiresAt);
21077
- const key = await recordKey("token", issuer, accessToken);
21078
- if (!await cas(key, null, record3)) return null;
21079
- return { accessToken, accessTokenExpiresAt, client: mcpClient(), scope: [MCP_OAUTH_SCOPE], user: { id: keyId } };
21102
+ const { accessToken, accessTokenExpiresAt, refreshToken, refreshTokenExpiresAt } = token;
21103
+ if (client.id !== MCP_OAUTH_CLIENT_ID || !isMcpScope(token.scope) || !accessToken || !accessTokenExpiresAt || !(accessTokenExpiresAt > now) || !refreshToken || !refreshTokenExpiresAt || !(refreshTokenExpiresAt > now) || typeof keyId !== "string" || !await activeKey(state, keyId, now.toISOString())) return null;
21104
+ const accessKey = await recordKey("token", issuer, accessToken);
21105
+ const refreshKey = await recordKey("refresh", issuer, refreshToken);
21106
+ if (!await cas(accessKey, null, newGrant(issuer, keyId, accessTokenExpiresAt))) return null;
21107
+ let savedRefresh = false;
21108
+ try {
21109
+ savedRefresh = await cas(refreshKey, null, newGrant(issuer, keyId, refreshTokenExpiresAt));
21110
+ } catch (err) {
21111
+ await cas(accessKey, 0, null).catch(() => false);
21112
+ throw err;
21113
+ }
21114
+ if (!savedRefresh) {
21115
+ await cas(accessKey, 0, null).catch(() => false);
21116
+ return null;
21117
+ }
21118
+ return {
21119
+ accessToken,
21120
+ accessTokenExpiresAt,
21121
+ refreshToken,
21122
+ refreshTokenExpiresAt,
21123
+ client: mcpClient(),
21124
+ scope: [MCP_OAUTH_SCOPE],
21125
+ user: { id: keyId }
21126
+ };
21080
21127
  },
21081
21128
  async getAccessToken(accessToken) {
21082
- const hit = await readAccessToken(state, issuer, accessToken, (/* @__PURE__ */ new Date()).toISOString());
21129
+ const hit = await readGrant(state, "token", issuer, accessToken, (/* @__PURE__ */ new Date()).toISOString());
21083
21130
  if (!hit) return null;
21084
21131
  return {
21085
21132
  accessToken,
@@ -21089,6 +21136,22 @@ function createMcpOAuthModel(state, issuer) {
21089
21136
  user: { id: hit.key.id }
21090
21137
  };
21091
21138
  },
21139
+ async getRefreshToken(refreshToken) {
21140
+ const hit = await readGrant(state, "refresh", issuer, refreshToken, (/* @__PURE__ */ new Date()).toISOString());
21141
+ if (!hit) return null;
21142
+ return {
21143
+ refreshToken,
21144
+ refreshTokenExpiresAt: new Date(hit.record.expiresAt),
21145
+ client: mcpClient(),
21146
+ scope: [hit.record.scope],
21147
+ user: { id: hit.key.id }
21148
+ };
21149
+ },
21150
+ async revokeToken(token) {
21151
+ if (!(token.refreshTokenExpiresAt && token.refreshTokenExpiresAt.getTime() > Date.now())) return false;
21152
+ const key = await recordKey("refresh", issuer, token.refreshToken);
21153
+ return cas(key, 0, null);
21154
+ },
21092
21155
  async verifyScope(token, scope) {
21093
21156
  return isMcpScope(token.scope) && isMcpScope(scope);
21094
21157
  }
@@ -21097,7 +21160,7 @@ function createMcpOAuthModel(state, issuer) {
21097
21160
  async function identifyMcpToken(state, issuer, bearer, now) {
21098
21161
  const token = bearer?.trim().match(/^Bearer +([^\s]+)$/i)?.[1];
21099
21162
  if (!token) return null;
21100
- const hit = await readAccessToken(state, issuer, token, now);
21163
+ const hit = await readGrant(state, "token", issuer, token, now);
21101
21164
  if (!hit) return null;
21102
21165
  const { key } = hit;
21103
21166
  return {
@@ -21111,7 +21174,13 @@ async function identifyMcpToken(state, issuer, bearer, now) {
21111
21174
 
21112
21175
  // src/mcpOAuthPage.ts
21113
21176
  import { html } from "hono/html";
21177
+ function hostLabel(url3) {
21178
+ return URL.parse(url3)?.host ?? "";
21179
+ }
21114
21180
  function consentPage(action, redirectUri, invalidKey = false) {
21181
+ const gatewayHost = hostLabel(action);
21182
+ const callbackHost = hostLabel(redirectUri) || "ChatGPT";
21183
+ const describedBy = invalidKey ? "sk-error sk-note" : "sk-note";
21115
21184
  const page = html`<!doctype html>
21116
21185
  <html lang="zh-CN">
21117
21186
  <head>
@@ -21119,26 +21188,471 @@ function consentPage(action, redirectUri, invalidKey = false) {
21119
21188
  <meta name="viewport" content="width=device-width, initial-scale=1">
21120
21189
  <title>授权 ChatGPT 访问 Tool Bridge</title>
21121
21190
  <style>
21122
- :root { color-scheme: light dark; font: 100%/1.6 system-ui, sans-serif; }
21123
- main { max-width: 30rem; margin: 12vh auto; padding: 0 1.25rem; }
21124
- h1 { font-size: 1.5rem; line-height: 1.35; }
21125
- label, input, button { display: block; }
21126
- input, button { box-sizing: border-box; font: inherit; padding: .5rem .75rem; }
21127
- input { width: 100%; margin: .25rem 0 1rem; }
21128
- button { display: inline-block; cursor: pointer; }
21191
+ :root {
21192
+ color-scheme: light dark;
21193
+ --bg: #F6F6F8;
21194
+ --surface: #FFFFFF;
21195
+ --surface-subtle: #F7F7F9;
21196
+ --fg: #09090B;
21197
+ --muted: #52525B;
21198
+ --subtle: #686872;
21199
+ --border: #E4E4E8;
21200
+ --border-strong: #D4D4DC;
21201
+ --primary: #09090B;
21202
+ --primary-hover: #27272A;
21203
+ --primary-fg: #FFFFFF;
21204
+ --secondary-hover: #EFEFF3;
21205
+ --input-bg: #FFFFFF;
21206
+ --ring: #8A5A00;
21207
+ --ring-soft: rgba(138, 90, 0, 0.16);
21208
+ --destructive: #B92534;
21209
+ --destructive-soft: #FFF0F2;
21210
+ --destructive-border: rgba(185, 37, 52, 0.28);
21211
+ --destructive-ring: rgba(185, 37, 52, 0.16);
21212
+ --shadow: 0 1px 2px rgba(9, 9, 11, 0.04), 0 10px 28px -16px rgba(9, 9, 11, 0.12);
21213
+ --font-sans: 'IBM Plex Sans', -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', ui-sans-serif, system-ui, sans-serif;
21214
+ --font-mono: 'IBM Plex Mono', ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
21215
+ }
21216
+
21217
+ @media (prefers-color-scheme: dark) {
21218
+ :root {
21219
+ --bg: #09090B;
21220
+ --surface: #101013;
21221
+ --surface-subtle: #16161A;
21222
+ --fg: #F4F4F6;
21223
+ --muted: #B4B4BC;
21224
+ --subtle: #8A8A94;
21225
+ --border: #242429;
21226
+ --border-strong: #383842;
21227
+ --primary: #F4F4F6;
21228
+ --primary-hover: #E4E4E8;
21229
+ --primary-fg: #09090B;
21230
+ --secondary-hover: #1E1E24;
21231
+ --input-bg: #09090B;
21232
+ --ring: #F5C451;
21233
+ --ring-soft: rgba(245, 196, 81, 0.2);
21234
+ --destructive: #FF9DA6;
21235
+ --destructive-soft: #381D23;
21236
+ --destructive-border: rgba(255, 157, 166, 0.3);
21237
+ --destructive-ring: rgba(255, 157, 166, 0.2);
21238
+ --shadow: 0 1px 2px rgba(0, 0, 0, 0.35), 0 18px 38px -18px rgba(0, 0, 0, 0.7);
21239
+ }
21240
+ }
21241
+
21242
+ *, *::before, *::after { box-sizing: border-box; }
21243
+
21244
+ html, body { height: 100%; }
21245
+
21246
+ body {
21247
+ margin: 0;
21248
+ min-height: 100svh;
21249
+ display: grid;
21250
+ place-items: center;
21251
+ padding: 24px 16px;
21252
+ background: var(--bg);
21253
+ color: var(--fg);
21254
+ font-family: var(--font-sans);
21255
+ font-size: 14px;
21256
+ line-height: 1.5;
21257
+ -webkit-font-smoothing: antialiased;
21258
+ text-rendering: optimizeLegibility;
21259
+ }
21260
+
21261
+ .shell {
21262
+ width: 100%;
21263
+ max-width: 432px;
21264
+ }
21265
+
21266
+ .brand-bar {
21267
+ display: flex;
21268
+ align-items: center;
21269
+ justify-content: space-between;
21270
+ gap: 12px;
21271
+ margin-bottom: 14px;
21272
+ padding: 0 2px;
21273
+ }
21274
+
21275
+ .brand {
21276
+ display: inline-flex;
21277
+ align-items: center;
21278
+ gap: 9px;
21279
+ font-size: 14px;
21280
+ font-weight: 600;
21281
+ letter-spacing: -0.01em;
21282
+ color: var(--fg);
21283
+ flex-shrink: 0;
21284
+ }
21285
+
21286
+ .brand svg {
21287
+ width: 24px;
21288
+ height: 18px;
21289
+ display: block;
21290
+ }
21291
+
21292
+ .host {
21293
+ display: inline-flex;
21294
+ align-items: center;
21295
+ gap: 5px;
21296
+ min-width: 0;
21297
+ font-family: var(--font-mono);
21298
+ font-size: 12px;
21299
+ color: var(--muted);
21300
+ }
21301
+
21302
+ .host svg {
21303
+ width: 12px;
21304
+ height: 12px;
21305
+ flex-shrink: 0;
21306
+ color: var(--subtle);
21307
+ }
21308
+
21309
+ .host span {
21310
+ overflow: hidden;
21311
+ text-overflow: ellipsis;
21312
+ white-space: nowrap;
21313
+ }
21314
+
21315
+ .card {
21316
+ background: var(--surface);
21317
+ border: 1px solid var(--border);
21318
+ border-radius: 12px;
21319
+ box-shadow: var(--shadow);
21320
+ overflow: hidden;
21321
+ }
21322
+
21323
+ .card-head {
21324
+ padding: 24px 24px 20px;
21325
+ }
21326
+
21327
+ .eyebrow {
21328
+ margin: 0 0 8px;
21329
+ font-family: var(--font-mono);
21330
+ font-size: 11px;
21331
+ font-weight: 500;
21332
+ letter-spacing: 0.06em;
21333
+ text-transform: uppercase;
21334
+ color: var(--subtle);
21335
+ }
21336
+
21337
+ h1 {
21338
+ margin: 0 0 8px;
21339
+ font-size: 20px;
21340
+ font-weight: 600;
21341
+ line-height: 1.3;
21342
+ letter-spacing: -0.02em;
21343
+ }
21344
+
21345
+ .lead {
21346
+ margin: 0;
21347
+ font-size: 13.5px;
21348
+ line-height: 1.55;
21349
+ color: var(--muted);
21350
+ }
21351
+
21352
+ .facts {
21353
+ margin: 0;
21354
+ padding: 14px 24px;
21355
+ background: var(--surface-subtle);
21356
+ border-top: 1px solid var(--border);
21357
+ border-bottom: 1px solid var(--border);
21358
+ display: grid;
21359
+ gap: 10px;
21360
+ }
21361
+
21362
+ .fact {
21363
+ display: grid;
21364
+ grid-template-columns: 76px minmax(0, 1fr);
21365
+ gap: 12px;
21366
+ align-items: baseline;
21367
+ font-size: 13px;
21368
+ line-height: 1.45;
21369
+ }
21370
+
21371
+ .fact dt {
21372
+ color: var(--subtle);
21373
+ }
21374
+
21375
+ .fact dd {
21376
+ margin: 0;
21377
+ color: var(--fg);
21378
+ min-width: 0;
21379
+ overflow-wrap: anywhere;
21380
+ }
21381
+
21382
+ .mono {
21383
+ font-family: var(--font-mono);
21384
+ font-size: 12.5px;
21385
+ }
21386
+
21387
+ .dim {
21388
+ color: var(--subtle);
21389
+ }
21390
+
21391
+ .nowrap {
21392
+ white-space: nowrap;
21393
+ }
21394
+
21395
+ .card-body {
21396
+ padding: 22px 24px 24px;
21397
+ }
21398
+
21399
+ .field-head {
21400
+ display: flex;
21401
+ align-items: baseline;
21402
+ justify-content: space-between;
21403
+ gap: 8px;
21404
+ margin-bottom: 7px;
21405
+ }
21406
+
21407
+ label {
21408
+ font-size: 13px;
21409
+ font-weight: 500;
21410
+ color: var(--fg);
21411
+ }
21412
+
21413
+ .hint {
21414
+ font-size: 12px;
21415
+ color: var(--subtle);
21416
+ }
21417
+
21418
+ input[type="password"] {
21419
+ display: block;
21420
+ width: 100%;
21421
+ height: 42px;
21422
+ padding: 0 12px;
21423
+ border-radius: 8px;
21424
+ border: 1px solid var(--border-strong);
21425
+ background: var(--input-bg);
21426
+ color: var(--fg);
21427
+ font-family: var(--font-mono);
21428
+ font-size: 14px;
21429
+ line-height: 1.4;
21430
+ outline: none;
21431
+ transition: border-color 120ms ease, box-shadow 120ms ease;
21432
+ }
21433
+
21434
+ input[type="password"]::placeholder {
21435
+ color: var(--subtle);
21436
+ opacity: 0.75;
21437
+ }
21438
+
21439
+ input[type="password"]:focus {
21440
+ border-color: var(--ring);
21441
+ box-shadow: 0 0 0 3px var(--ring-soft);
21442
+ }
21443
+
21444
+ input[type="password"][aria-invalid="true"] {
21445
+ border-color: var(--destructive);
21446
+ }
21447
+
21448
+ input[type="password"][aria-invalid="true"]:focus {
21449
+ border-color: var(--destructive);
21450
+ box-shadow: 0 0 0 3px var(--destructive-ring);
21451
+ }
21452
+
21453
+ .alert {
21454
+ margin: 10px 0 0;
21455
+ padding: 10px 12px;
21456
+ border-radius: 8px;
21457
+ border: 1px solid var(--destructive-border);
21458
+ background: var(--destructive-soft);
21459
+ color: var(--destructive);
21460
+ font-size: 12.5px;
21461
+ line-height: 1.45;
21462
+ display: flex;
21463
+ align-items: flex-start;
21464
+ gap: 8px;
21465
+ }
21466
+
21467
+ .alert svg {
21468
+ width: 15px;
21469
+ height: 15px;
21470
+ flex-shrink: 0;
21471
+ margin-top: 2px;
21472
+ }
21473
+
21474
+ .actions {
21475
+ margin-top: 18px;
21476
+ display: flex;
21477
+ flex-direction: column;
21478
+ gap: 8px;
21479
+ }
21480
+
21481
+ .btn {
21482
+ width: 100%;
21483
+ height: 40px;
21484
+ padding: 0 16px;
21485
+ border-radius: 8px;
21486
+ font-family: var(--font-sans);
21487
+ font-size: 14px;
21488
+ font-weight: 500;
21489
+ cursor: pointer;
21490
+ display: inline-flex;
21491
+ align-items: center;
21492
+ justify-content: center;
21493
+ transition: background-color 120ms ease, border-color 120ms ease, color 120ms ease, opacity 120ms ease;
21494
+ }
21495
+
21496
+ .btn:focus-visible {
21497
+ outline: 2px solid var(--ring);
21498
+ outline-offset: 2px;
21499
+ }
21500
+
21501
+ .btn-primary {
21502
+ border: 1px solid transparent;
21503
+ background: var(--primary);
21504
+ color: var(--primary-fg);
21505
+ }
21506
+
21507
+ .btn-primary:hover {
21508
+ background: var(--primary-hover);
21509
+ }
21510
+
21511
+ .btn-secondary {
21512
+ border: 1px solid var(--border);
21513
+ background: transparent;
21514
+ color: var(--muted);
21515
+ }
21516
+
21517
+ .btn-secondary:hover {
21518
+ background: var(--secondary-hover);
21519
+ color: var(--fg);
21520
+ border-color: var(--border-strong);
21521
+ }
21522
+
21523
+ .footnote {
21524
+ margin: 14px 0 0;
21525
+ font-size: 12px;
21526
+ line-height: 1.5;
21527
+ color: var(--subtle);
21528
+ text-align: center;
21529
+ }
21530
+
21531
+ @media (pointer: coarse) {
21532
+ input[type="password"] {
21533
+ height: 46px;
21534
+ font-size: 16px;
21535
+ }
21536
+
21537
+ .btn {
21538
+ height: 46px;
21539
+ }
21540
+ }
21541
+
21542
+ @media (max-width: 440px) {
21543
+ body {
21544
+ padding: 16px 12px;
21545
+ }
21546
+
21547
+ .card-head {
21548
+ padding: 20px 18px 18px;
21549
+ }
21550
+
21551
+ .facts {
21552
+ padding: 14px 18px;
21553
+ }
21554
+
21555
+ .fact {
21556
+ grid-template-columns: 68px minmax(0, 1fr);
21557
+ gap: 10px;
21558
+ }
21559
+
21560
+ .card-body {
21561
+ padding: 18px;
21562
+ }
21563
+ }
21564
+
21565
+ @media (prefers-reduced-motion: reduce) {
21566
+ *, *::before, *::after {
21567
+ transition-duration: 0.01ms !important;
21568
+ }
21569
+ }
21129
21570
  </style>
21130
21571
  </head>
21131
- <body><main>
21132
- <h1>授权 ChatGPT 访问 Tool Bridge</h1>
21133
- <p>ChatGPT 将在一小时内通过 MCP 使用这把密钥允许的工具。密钥只提交到此网关。</p>
21134
- <form method="post" action="${action}">
21135
- <label for="sk">网关访问密钥(SK)</label>
21136
- <input id="sk" name="sk" type="password" autocomplete="off" required>
21137
- ${invalidKey ? html`<p role="alert">密钥无效或已过期,请重新输入。</p>` : ""}
21138
- <button type="submit">确认授权</button>
21139
- <button type="submit" name="decision" value="deny" formnovalidate>取消</button>
21140
- </form>
21141
- </main></body></html>`;
21572
+ <body>
21573
+ <main class="shell">
21574
+ <header class="brand-bar">
21575
+ <div class="brand">
21576
+ <svg viewBox="0 0 40 30" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
21577
+ <path d="M7.8 11.8Q20 1.4 32.2 11.8"/>
21578
+ <path d="M8.4 14.8H12.2V13Q12.2 11.8 13.6 11.7L16.6 11.5"/>
21579
+ <path d="M31.6 14.8H27.8V13Q27.8 11.8 26.4 11.7L23.4 11.5"/>
21580
+ <path d="M20 14.9V21.1"/>
21581
+ <circle cx="5" cy="14" r="3.4"/>
21582
+ <circle cx="35" cy="14" r="3.4"/>
21583
+ <circle cx="20" cy="11.5" r="3.4"/>
21584
+ <circle cx="20" cy="24.5" r="3.4"/>
21585
+ </svg>
21586
+ <span>Tool Bridge</span>
21587
+ </div>
21588
+ ${gatewayHost ? html`<div class="host" title="${gatewayHost}">
21589
+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
21590
+ <rect x="3.5" y="7.25" width="9" height="6.25" rx="1.5"/>
21591
+ <path d="M5.5 7.25V5.25a2.5 2.5 0 0 1 5 0v2"/>
21592
+ </svg>
21593
+ <span>${gatewayHost}</span>
21594
+ </div>` : ""}
21595
+ </header>
21596
+
21597
+ <section class="card" aria-labelledby="consent-title">
21598
+ <div class="card-head">
21599
+ <p class="eyebrow">MCP OAuth</p>
21600
+ <h1 id="consent-title">授权 ChatGPT 访问</h1>
21601
+ <p class="lead">使用访问密钥(SK)建立长期 MCP 连接。密钥仅提交至当前网关,不会传给 ChatGPT。</p>
21602
+ </div>
21603
+
21604
+ <dl class="facts">
21605
+ <div class="fact">
21606
+ <dt>客户端</dt>
21607
+ <dd>ChatGPT <span class="mono dim">· ${callbackHost}</span></dd>
21608
+ </div>
21609
+ <div class="fact">
21610
+ <dt>访问范围</dt>
21611
+ <dd>仅 <span class="mono">/~mcp</span>,权限与所填 SK 一致</dd>
21612
+ </div>
21613
+ <div class="fact">
21614
+ <dt>续期与撤销</dt>
21615
+ <dd>自动续期(90 天闲置过期);<span class="nowrap">禁删 SK 立即失效</span></dd>
21616
+ </div>
21617
+ </dl>
21618
+
21619
+ <div class="card-body">
21620
+ <form method="post" action="${action}">
21621
+ <div class="field-head">
21622
+ <label for="sk">网关访问密钥(SK)</label>
21623
+ <span class="hint">建议使用专用受限密钥</span>
21624
+ </div>
21625
+ <input
21626
+ id="sk"
21627
+ name="sk"
21628
+ type="password"
21629
+ autocomplete="off"
21630
+ spellcheck="false"
21631
+ placeholder="tbk_…"
21632
+ required
21633
+ autofocus
21634
+ aria-invalid="${invalidKey ? "true" : "false"}"
21635
+ aria-describedby="${describedBy}"
21636
+ >
21637
+ ${invalidKey ? html`<div id="sk-error" class="alert" role="alert">
21638
+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
21639
+ <circle cx="8" cy="8" r="6.25"/>
21640
+ <path d="M8 5v3.5"/>
21641
+ <circle cx="8" cy="11.25" r="0.5" fill="currentColor" stroke="none"/>
21642
+ </svg>
21643
+ <span>密钥无效、已禁用或已过期,请核对后重新输入。</span>
21644
+ </div>` : ""}
21645
+ <div class="actions">
21646
+ <button type="submit" class="btn btn-primary">确认授权</button>
21647
+ <button type="submit" name="decision" value="deny" formnovalidate class="btn btn-secondary">取消</button>
21648
+ </div>
21649
+ <p id="sk-note" class="footnote">确认后将返回 <span class="mono">${callbackHost}</span> 完成连接。</p>
21650
+ </form>
21651
+ </div>
21652
+ </section>
21653
+ </main>
21654
+ </body>
21655
+ </html>`;
21142
21656
  return new Response(page.toString(), {
21143
21657
  status: invalidKey ? 401 : 200,
21144
21658
  headers: {
@@ -21157,10 +21671,11 @@ var MCP_AUTHORIZE_PATH = "/~oauth/mcp/authorize";
21157
21671
  var TOKEN = "/~oauth/mcp/token";
21158
21672
  var FORM_TYPE = "application/x-www-form-urlencoded";
21159
21673
  var MAX_REQUEST = 8192;
21160
- var ACCESS_SECONDS = 3600;
21161
21674
  var commonFields = ["client_id", "redirect_uri", "resource", "scope"];
21162
21675
  var authorizeFields = [...commonFields, "response_type", "state", "code_challenge", "code_challenge_method"];
21163
- var tokenFields = [...commonFields, "grant_type", "code", "code_verifier"];
21676
+ var authCodeTokenFields = [...commonFields, "grant_type", "code", "code_verifier"];
21677
+ var refreshTokenFields = ["grant_type", "client_id", "refresh_token", "resource", "scope"];
21678
+ var tokenFields = [.../* @__PURE__ */ new Set([...authCodeTokenFields, ...refreshTokenFields])];
21164
21679
  var noStore = { "cache-control": "no-store", "pragma": "no-cache" };
21165
21680
  var EndpointError = class extends Error {
21166
21681
  constructor(code, status = 400) {
@@ -21284,7 +21799,7 @@ function createMcpOAuth(state, canonicalOrigin, fetchClientMetadata) {
21284
21799
  token_endpoint: issuer + TOKEN,
21285
21800
  scopes_supported: [MCP_OAUTH_SCOPE],
21286
21801
  response_types_supported: ["code"],
21287
- grant_types_supported: ["authorization_code"],
21802
+ grant_types_supported: ["authorization_code", "refresh_token"],
21288
21803
  token_endpoint_auth_methods_supported: ["none"],
21289
21804
  code_challenge_methods_supported: ["S256"],
21290
21805
  authorization_response_iss_parameter_supported: true,
@@ -21293,11 +21808,13 @@ function createMcpOAuth(state, canonicalOrigin, fetchClientMetadata) {
21293
21808
  };
21294
21809
  const oauth = new OAuth2Server({
21295
21810
  model: createMcpOAuthModel(state, issuer),
21296
- accessTokenLifetime: ACCESS_SECONDS,
21811
+ accessTokenLifetime: MCP_OAUTH_ACCESS_TOKEN_LIFETIME,
21812
+ refreshTokenLifetime: MCP_OAUTH_REFRESH_TOKEN_LIFETIME,
21297
21813
  authorizationCodeLifetime: 300,
21298
21814
  requirePKCE: true,
21299
21815
  allowEmptyState: true,
21300
- requireClientAuthentication: { authorization_code: false }
21816
+ alwaysIssueNewRefreshToken: true,
21817
+ requireClientAuthentication: { authorization_code: false, refresh_token: false }
21301
21818
  });
21302
21819
  const routes = new Hono2();
21303
21820
  routes.onError((err) => {
@@ -21342,17 +21859,41 @@ function createMcpOAuth(state, canonicalOrigin, fetchClientMetadata) {
21342
21859
  if (request2.method !== "POST") return methodError("POST");
21343
21860
  if (new URL(request2.url).search || request2.headers.has("authorization")) throw new EndpointError("invalid_request");
21344
21861
  const params = await form(request2, tokenFields);
21345
- if (params.get("grant_type") !== "authorization_code") throw new EndpointError("unsupported_grant_type");
21346
- checkBinding(params, resourceServerUrl.href);
21347
- if (!params.has("code") || !/^[A-Za-z0-9._~-]{43,128}$/.test(params.get("code_verifier") ?? "")) {
21348
- throw new EndpointError("invalid_request");
21862
+ const grantType = params.get("grant_type");
21863
+ if (!grantType) throw new EndpointError("invalid_request");
21864
+ if (grantType === "authorization_code") {
21865
+ for (const name of params.keys()) {
21866
+ if (!authCodeTokenFields.includes(name)) throw new EndpointError("invalid_request");
21867
+ }
21868
+ checkBinding(params, resourceServerUrl.href);
21869
+ if (!params.has("code") || !/^[A-Za-z0-9._~-]{43,128}$/.test(params.get("code_verifier") ?? "")) {
21870
+ throw new EndpointError("invalid_request");
21871
+ }
21872
+ } else if (grantType === "refresh_token") {
21873
+ for (const name of params.keys()) {
21874
+ if (!refreshTokenFields.includes(name)) throw new EndpointError("invalid_request");
21875
+ }
21876
+ if (params.get("client_id") !== MCP_OAUTH_CLIENT_ID) throw new EndpointError("invalid_client");
21877
+ if (params.has("resource") && params.get("resource") !== resourceServerUrl.href) {
21878
+ throw new EndpointError("invalid_target");
21879
+ }
21880
+ if ((params.get("scope") ?? MCP_OAUTH_SCOPE) !== MCP_OAUTH_SCOPE) throw new EndpointError("invalid_scope");
21881
+ if (!params.has("refresh_token")) throw new EndpointError("invalid_request");
21882
+ } else {
21883
+ throw new EndpointError("unsupported_grant_type");
21349
21884
  }
21350
21885
  const headers = { "content-type": FORM_TYPE, "content-length": String(Buffer.byteLength(params.toString())) };
21351
21886
  const token = await oauth.token(
21352
21887
  new OAuth2Server.Request({ headers, method: "POST", query: {}, body: Object.fromEntries(params) }),
21353
21888
  new OAuth2Server.Response()
21354
21889
  );
21355
- return Response.json({ access_token: token.accessToken, token_type: "Bearer", expires_in: ACCESS_SECONDS, scope: MCP_OAUTH_SCOPE }, { headers: noStore });
21890
+ return Response.json({
21891
+ access_token: token.accessToken,
21892
+ token_type: "Bearer",
21893
+ expires_in: MCP_OAUTH_ACCESS_TOKEN_LIFETIME,
21894
+ ...token.refreshToken ? { refresh_token: token.refreshToken } : {},
21895
+ scope: MCP_OAUTH_SCOPE
21896
+ }, { headers: noStore });
21356
21897
  });
21357
21898
  return {
21358
21899
  resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(resourceServerUrl),
@@ -21459,13 +22000,13 @@ function resolveUiAssets(uiDirOverride) {
21459
22000
  // src/server.ts
21460
22001
  var providerOAuthFetch = createGuardedFetch({ crossOriginRedirect: "error" });
21461
22002
  var chatGptMetadataFetch = createGuardedFetch({ maxRedirects: 0 });
21462
- function createTbServer(config) {
22003
+ function createTbServer(config, onOwnershipLost) {
21463
22004
  if (!config.databaseUrl)
21464
22005
  throw new TBError(
21465
22006
  "unavailable",
21466
22007
  "PostgreSQL must be configured before starting business services"
21467
22008
  );
21468
- const sql = postgres3(config.databaseUrl, {
22009
+ const sql = postgres4(config.databaseUrl, {
21469
22010
  onnotice: () => {
21470
22011
  },
21471
22012
  connect_timeout: 5
@@ -21486,6 +22027,7 @@ function createTbServer(config) {
21486
22027
  const storeRepository = new PgStoreRepository(sql);
21487
22028
  const eventRepository = new PgEventRepository(sql);
21488
22029
  const eventStreamShutdown = new AbortController();
22030
+ const shutdown = new AbortController();
21489
22031
  const mailboxRepository = new PgMailboxRepository(sql);
21490
22032
  const storage = new StorageManager(sql, secrets, {
21491
22033
  ...config.internalS3Origin ? { internalOrigin: config.internalS3Origin } : {}
@@ -21507,6 +22049,14 @@ function createTbServer(config) {
21507
22049
  }
21508
22050
  });
21509
22051
  let draining = false;
22052
+ let closing = false;
22053
+ let preparedForTraffic = false;
22054
+ const ownershipLost = new AbortController();
22055
+ const accepting = () => preparedForTraffic && !closing && !ownershipLost.signal.aborted;
22056
+ const assertOpen = () => {
22057
+ if (closing || ownershipLost.signal.aborted)
22058
+ throw new TBError("unavailable", "runtime is closed");
22059
+ };
21510
22060
  const probeOne = async (fn) => {
21511
22061
  let timer;
21512
22062
  try {
@@ -21528,18 +22078,12 @@ function createTbServer(config) {
21528
22078
  }
21529
22079
  };
21530
22080
  const readiness = async () => {
22081
+ if (!accepting()) return { ready: false, checks: { runtime: { ok: false, detail: "runtime not accepting requests" } } };
21531
22082
  const checks = {};
21532
22083
  const probes = [];
21533
- const statePing = async () => {
21534
- await sql`SELECT 1`;
21535
- };
21536
- if (statePing !== void 0) {
21537
- probes.push(
21538
- probeOne(statePing).then((r) => {
21539
- checks.state = r;
21540
- })
21541
- );
21542
- }
22084
+ probes.push(probeOne(() => assertRuntimeAuthority(sql, replicaId)).then((r) => {
22085
+ checks.state = r;
22086
+ }));
21543
22087
  if (redisBackend !== void 0) {
21544
22088
  probes.push(
21545
22089
  probeOne(async () => await redisBackend.ping()).then((r) => {
@@ -21579,6 +22123,8 @@ function createTbServer(config) {
21579
22123
  mailboxRepository,
21580
22124
  eventRepository,
21581
22125
  eventStreamShutdown: eventStreamShutdown.signal,
22126
+ // In-process MCP calls can also enter the inner HTBP app.
22127
+ ensureReady: async () => ownershipLost.signal.throwIfAborted(),
21582
22128
  storageManagement: storage,
21583
22129
  deploymentManagement: deployment,
21584
22130
  ...config.adminAudit ? { adminAudit: config.adminAudit } : {},
@@ -21638,20 +22184,24 @@ function createTbServer(config) {
21638
22184
  deps.storeCallAllowedContentTypes = config.storeCallAllowedContentTypes;
21639
22185
  }
21640
22186
  let server;
22187
+ let listening;
21641
22188
  let maintenanceTimer;
21642
22189
  let maintenancePromise;
21643
22190
  let replicaTimer;
21644
- let heartbeatInFlight = Promise.resolve();
22191
+ let heartbeatInFlight;
21645
22192
  let applied;
21646
22193
  const runMaintenance = async () => {
22194
+ if (closing) return;
21647
22195
  if (maintenancePromise) return maintenancePromise;
21648
22196
  const snapshot = deps;
21649
22197
  maintenancePromise = (async () => {
21650
22198
  await sql`DELETE FROM tb_kv WHERE key >= 'mcp-inbound:' AND key < 'mcp-inbound;'
21651
22199
  AND value->>'expiresAt' <= ${(/* @__PURE__ */ new Date()).toISOString()}`;
22200
+ if (ownershipLost.signal.aborted) return;
21652
22201
  await eventRepository.cleanup();
22202
+ if (ownershipLost.signal.aborted) return;
21653
22203
  await cleanupDefaultStore(snapshot);
21654
- if (snapshot.encryptionKey !== void 0)
22204
+ if (!ownershipLost.signal.aborted && snapshot.encryptionKey !== void 0)
21655
22205
  await cleanupDeviceMailbox(snapshot);
21656
22206
  })().finally(() => {
21657
22207
  maintenancePromise = void 0;
@@ -21662,6 +22212,7 @@ function createTbServer(config) {
21662
22212
  console.warn(JSON.stringify({ event: "tool_bridge_store_cleanup_failed" }));
21663
22213
  };
21664
22214
  function scheduleStoreCleanup() {
22215
+ if (closing) return;
21665
22216
  void runMaintenance().catch(reportStoreCleanupFailure);
21666
22217
  maintenanceTimer = setInterval(
21667
22218
  () => {
@@ -21684,6 +22235,7 @@ function createTbServer(config) {
21684
22235
  };
21685
22236
  currentApp = buildApp();
21686
22237
  }, async (next) => {
22238
+ ownershipLost.signal.throwIfAborted();
21687
22239
  await hub.setReclaimSec(next.deviceReclaimSec);
21688
22240
  const reschedule = applied?.storeCleanupIntervalSec !== next.storeCleanupIntervalSec;
21689
22241
  applied = next;
@@ -21699,7 +22251,17 @@ function createTbServer(config) {
21699
22251
  const drainWaiters = [];
21700
22252
  const requestContext = new AsyncLocalStorage();
21701
22253
  const app = new Hono4();
21702
- app.all("*", async (c) => {
22254
+ app.mount("/", async (raw, env, executionCtx) => {
22255
+ const path = new URL(raw.url).pathname;
22256
+ const read = raw.method === "GET" || raw.method === "HEAD";
22257
+ const probe = read && ["/healthz", "/livez", "/readyz"].includes(path);
22258
+ const unavailable = (message) => Response.json({ code: "unavailable", message }, { status: 503 });
22259
+ if (!accepting()) {
22260
+ if (probe) return currentApp.fetch(raw, env, executionCtx);
22261
+ return unavailable("runtime not accepting requests");
22262
+ }
22263
+ const transport = AbortSignal.any([raw.signal, ownershipLost.signal]);
22264
+ const signal = AbortSignal.any([transport, shutdown.signal]);
21703
22265
  activeRequests++;
21704
22266
  let released = false;
21705
22267
  const request2 = {
@@ -21712,45 +22274,114 @@ function createTbServer(config) {
21712
22274
  };
21713
22275
  return requestContext.run(request2, async () => {
21714
22276
  try {
21715
- const path = new URL(c.req.url).pathname;
21716
- if (!["/healthz", "/livez", "/readyz"].includes(path) && !path.startsWith("/ui")) {
22277
+ if (!probe && !(read && (path === "/ui" || path.startsWith("/ui/")))) {
21717
22278
  try {
21718
22279
  await assertRuntimeAuthority(sql, replicaId);
22280
+ transport.throwIfAborted();
21719
22281
  await settings.sync();
21720
22282
  } catch {
21721
- return trackResponseBody(c.json(
21722
- {
21723
- code: "unavailable",
21724
- message: "configuration authority unavailable"
21725
- },
21726
- 503
21727
- ), request2.release, c.req.raw.signal);
22283
+ request2.release();
22284
+ return unavailable("configuration authority unavailable");
21728
22285
  }
21729
22286
  }
21730
- const snapshot = currentApp;
21731
- return trackResponseBody(await snapshot.fetch(c.req.raw), request2.release, c.req.raw.signal);
22287
+ if (transport.aborted) {
22288
+ request2.release();
22289
+ return unavailable("request interrupted before dispatch");
22290
+ }
22291
+ const body = !raw.keepalive && raw.mode !== "no-cors" ? raw.body?.pipeThrough(new TransformStream(), { signal: transport }) : void 0;
22292
+ try {
22293
+ const init = { signal, ...body && { body, duplex: "half" } };
22294
+ const forwarded = new Request(raw, init);
22295
+ if (forwarded.method !== raw.method) Object.defineProperty(forwarded, "method", { value: raw.method });
22296
+ const response = await currentApp.fetch(forwarded, env, executionCtx);
22297
+ const sse = response.headers.get("content-type")?.split(";")[0] === "text/event-stream";
22298
+ return trackResponseBody(response, request2.release, sse ? AbortSignal.any([transport, eventStreamShutdown.signal]) : transport);
22299
+ } finally {
22300
+ if (body && !body.locked) void body.cancel().catch(() => {
22301
+ });
22302
+ }
21732
22303
  } catch (error) {
21733
22304
  request2.release();
21734
22305
  throw error;
21735
22306
  }
21736
22307
  });
21737
- });
22308
+ }, { replaceRequest: false });
21738
22309
  let prepared;
21739
22310
  let runtimeLease;
21740
22311
  let closePromise;
22312
+ let listenerClosed;
22313
+ const stopListening = async (listener) => {
22314
+ if (!listener.listening) await listening?.catch(() => {
22315
+ });
22316
+ if (!listener.listening) return;
22317
+ await new Promise((resolve2, reject) => {
22318
+ listener.close((err) => err ? reject(err) : resolve2());
22319
+ listener.closeIdleConnections();
22320
+ });
22321
+ };
22322
+ const close = async (options) => {
22323
+ const caller = options?.excludeCurrentRequest ? requestContext.getStore() : void 0;
22324
+ caller?.release();
22325
+ if (!closePromise) {
22326
+ closing = true;
22327
+ draining = true;
22328
+ if (server) listenerClosed = stopListening(server);
22329
+ closePromise = Promise.resolve().then(async () => {
22330
+ eventStreamShutdown.abort();
22331
+ if (!caller) shutdown.abort(new TBError("unavailable", "runtime is shutting down"));
22332
+ if (maintenanceTimer !== void 0) {
22333
+ clearInterval(maintenanceTimer);
22334
+ maintenanceTimer = void 0;
22335
+ }
22336
+ if (!preparedForTraffic) await prepared?.catch(() => {
22337
+ });
22338
+ await hub.close();
22339
+ if (activeRequests > 0)
22340
+ await new Promise((resolve2) => drainWaiters.push(resolve2));
22341
+ await maintenancePromise?.catch(() => {
22342
+ });
22343
+ if (replicaTimer) clearInterval(replicaTimer);
22344
+ await heartbeatInFlight;
22345
+ try {
22346
+ await runtimeLease?.release();
22347
+ } finally {
22348
+ storage.close();
22349
+ await eventRepository.close().finally(() => sql.end({ timeout: 5 }));
22350
+ }
22351
+ });
22352
+ }
22353
+ await Promise.all([closePromise, caller ? void 0 : listenerClosed]);
22354
+ };
21741
22355
  const prepare = async () => {
22356
+ assertOpen();
21742
22357
  prepared ??= (async () => {
21743
- await state.ensureSchema();
21744
- runtimeLease = await acquireRuntimeLease(sql, {
22358
+ const lease = await acquireRuntimeLease(sql, {
21745
22359
  instanceId: config.instanceId ?? "embedded",
21746
22360
  replicaId,
21747
- redisUrl: config.redisUrl
22361
+ redisUrl: config.redisUrl,
22362
+ onLost: () => {
22363
+ if (ownershipLost.signal.aborted) return;
22364
+ ownershipLost.abort(new TBError("unavailable", "runtime ownership lost"));
22365
+ if (replicaTimer) clearInterval(replicaTimer);
22366
+ console.error(JSON.stringify({ event: "tool_bridge_runtime_ownership_lost" }));
22367
+ void close().catch(() => {
22368
+ console.error(JSON.stringify({ event: "tool_bridge_runtime_close_failed" }));
22369
+ });
22370
+ server?.closeAllConnections();
22371
+ onOwnershipLost?.();
22372
+ }
21748
22373
  });
22374
+ runtimeLease = lease;
22375
+ assertOpen();
21749
22376
  replicaTimer = setInterval(() => {
21750
- heartbeatInFlight = heartbeatInFlight.then(() => runtimeLease?.heartbeat()).catch(() => {
22377
+ if (heartbeatInFlight) return;
22378
+ heartbeatInFlight = lease.heartbeat().catch(() => {
22379
+ }).finally(() => {
22380
+ heartbeatInFlight = void 0;
21751
22381
  });
21752
22382
  }, 15e3);
21753
22383
  replicaTimer.unref();
22384
+ await state.ensureSchema();
21754
22385
  await storeRepository.ensureSchema();
21755
22386
  await state.ensureContextReferencesSchema();
21756
22387
  await eventRepository.ensureSchema();
@@ -21768,6 +22399,7 @@ function createTbServer(config) {
21768
22399
  )
21769
22400
  )
21770
22401
  );
22402
+ assertOpen();
21771
22403
  await runBootstrap(state, {
21772
22404
  management: true,
21773
22405
  additionalModules: [
@@ -21776,6 +22408,7 @@ function createTbServer(config) {
21776
22408
  ],
21777
22409
  ...config.adminSk ? { adminSk: config.adminSk } : {}
21778
22410
  });
22411
+ assertOpen();
21779
22412
  const backends = (await storage.list()).items;
21780
22413
  let active2 = backends.find((backend) => backend.active);
21781
22414
  if (!active2 && config.objectStore) {
@@ -21810,12 +22443,17 @@ function createTbServer(config) {
21810
22443
  if (!active2)
21811
22444
  throw new TBError("unavailable", "no active storage backend");
21812
22445
  await storage.resolveBackend(active2.id);
22446
+ assertOpen();
21813
22447
  await hub.startRouter();
21814
22448
  await settings.sync();
22449
+ assertOpen();
21815
22450
  await hub.sweepOrphans();
22451
+ assertOpen();
21816
22452
  scheduleStoreCleanup();
22453
+ preparedForTraffic = true;
21817
22454
  })();
21818
22455
  await prepared;
22456
+ assertOpen();
21819
22457
  };
21820
22458
  return {
21821
22459
  app,
@@ -21827,15 +22465,20 @@ function createTbServer(config) {
21827
22465
  deviceHub: hub,
21828
22466
  async start() {
21829
22467
  await prepare();
21830
- return await new Promise((resolve2) => {
22468
+ assertOpen();
22469
+ listening ??= new Promise((resolve2, reject) => {
21831
22470
  server = serve(
21832
22471
  { fetch: app.fetch, port: config.port, hostname: config.host },
21833
22472
  (info) => {
22473
+ if (!closing) hub.attach(server);
21834
22474
  resolve2({ port: info.port });
21835
22475
  }
21836
22476
  );
21837
- hub.attach(server);
22477
+ server.once("error", reject);
21838
22478
  });
22479
+ const address = await listening;
22480
+ assertOpen();
22481
+ return address;
21839
22482
  },
21840
22483
  startDraining() {
21841
22484
  draining = true;
@@ -21843,43 +22486,7 @@ function createTbServer(config) {
21843
22486
  get shutdownDrainSec() {
21844
22487
  return applied?.shutdownDrainSec ?? config.shutdownDrainSec ?? 0;
21845
22488
  },
21846
- async close(options) {
21847
- if (options?.excludeCurrentRequest) requestContext.getStore()?.release();
21848
- return closePromise ??= (async () => {
21849
- draining = true;
21850
- eventStreamShutdown.abort();
21851
- if (maintenanceTimer !== void 0) {
21852
- clearInterval(maintenanceTimer);
21853
- maintenanceTimer = void 0;
21854
- }
21855
- let closed;
21856
- if (server !== void 0) {
21857
- const s = server;
21858
- closed = new Promise((resolve2, reject) => {
21859
- s.close((err) => err ? reject(err) : resolve2());
21860
- });
21861
- s.closeIdleConnections?.();
21862
- }
21863
- await hub.close();
21864
- if (activeRequests > 0)
21865
- await new Promise((resolve2) => drainWaiters.push(resolve2));
21866
- await maintenancePromise?.catch(() => {
21867
- });
21868
- if (replicaTimer) clearInterval(replicaTimer);
21869
- await heartbeatInFlight;
21870
- try {
21871
- await runtimeLease?.release();
21872
- } finally {
21873
- try {
21874
- if (closed !== void 0) await closed;
21875
- } finally {
21876
- server = void 0;
21877
- storage.close();
21878
- await eventRepository.close().finally(() => sql.end({ timeout: 5 }));
21879
- }
21880
- }
21881
- })();
21882
- }
22489
+ close
21883
22490
  };
21884
22491
  }
21885
22492
 
@@ -22123,54 +22730,90 @@ function builtinPluginBindings(env, opts = {}) {
22123
22730
  }
22124
22731
 
22125
22732
  // src/managedServer.ts
22126
- import { serve as serve2 } from "@hono/node-server";
22127
22733
  import { setTimeout as delay } from "timers/promises";
22128
22734
  import { secureHeaders } from "hono/secure-headers";
22129
22735
  import { bodyLimit } from "hono/body-limit";
22736
+ import { serve as serve2 } from "@hono/node-server";
22130
22737
  import { randomUUID as randomUUID11 } from "crypto";
22131
- import postgres4 from "postgres";
22738
+ import postgres5 from "postgres";
22739
+ import pRetry from "p-retry";
22132
22740
  import { Hono as Hono5 } from "hono";
22133
22741
  async function createManagedServer(options) {
22134
22742
  const store = new BootstrapStateStore(options.directory);
22135
22743
  let state;
22136
22744
  let phase = "setup";
22745
+ const startup = new AbortController();
22746
+ const ownershipLost = new AbortController();
22747
+ const drainDelay = new AbortController();
22137
22748
  let business;
22138
22749
  let listener;
22750
+ let listening;
22751
+ let closePromise;
22752
+ let managementTask;
22753
+ let managementClosed = false;
22139
22754
  let maintaining = false;
22140
22755
  let draining = false;
22141
22756
  let shutdownPromise;
22142
22757
  let lastShutdownDrainSec = 0;
22143
- let actualPort = options.port ?? 8787;
22144
22758
  const replicaId = randomUUID11();
22145
22759
  const assets = resolveUiAssets(options.uiDir);
22146
22760
  const app = new Hono5();
22147
22761
  const defaults = secureHeaders();
22148
22762
  const consent = secureHeaders({ referrerPolicy: "same-origin" });
22149
22763
  app.use("*", (c, next) => c.req.path === MCP_AUTHORIZE_PATH ? consent(c, next) : defaults(c, next));
22150
- app.use("/~setup/*", bodyLimit({ maxSize: 65536 }));
22151
22764
  app.use("/~setup/*", async (c, next) => {
22152
22765
  c.header("Cache-Control", "no-store");
22153
22766
  await next();
22154
22767
  });
22768
+ const assertOwnershipIntact = () => {
22769
+ if (ownershipLost.signal.aborted) throw new TBError("unavailable", "runtime ownership lost; restart required");
22770
+ };
22771
+ const handoffBlocked = () => ownershipLost.signal.aborted || phase === "starting";
22772
+ const runtimeState = () => ownershipLost.signal.aborted ? "ownership_lost" : phase;
22155
22773
  const status = () => ({
22156
- state: phase,
22774
+ state: handoffBlocked() ? "installing" : phase,
22157
22775
  instanceId: state?.instanceId,
22158
- pairingRequired: phase !== "ready"
22776
+ pairingRequired: !handoffBlocked() && phase !== "ready"
22159
22777
  });
22160
22778
  const management = {};
22161
- const launch = async (current, input, restoredKeys) => {
22779
+ const withManagementLock = (run) => store.exclusive(async () => {
22780
+ if (managementClosed) throw new TBError("unavailable", "server is closed");
22781
+ const task = run();
22782
+ managementTask = task;
22783
+ try {
22784
+ return await task;
22785
+ } finally {
22786
+ managementTask = void 0;
22787
+ }
22788
+ });
22789
+ const launch = async (current, input, restoredKeys, signal) => {
22790
+ let candidateLost = false;
22791
+ const checkLaunch = () => {
22792
+ signal?.throwIfAborted();
22793
+ assertOwnershipIntact();
22794
+ if (candidateLost) throw new TBError("unavailable", "runtime ownership lost during preparation");
22795
+ };
22796
+ checkLaunch();
22797
+ if (!current.databaseUrl)
22798
+ throw new TBError("unavailable", "bootstrap database connection is unavailable");
22162
22799
  const keys = restoredKeys ?? await store.read("keys.json");
22163
- if (!keys || !current.databaseUrl)
22800
+ if (!keys)
22164
22801
  throw new TBError(
22165
22802
  "unavailable",
22166
- "local bootstrap secrets or database connection are unavailable"
22803
+ "local bootstrap secrets are unavailable"
22167
22804
  );
22168
- const sql = postgres4(current.databaseUrl, {
22805
+ checkLaunch();
22806
+ const sql = postgres5(current.databaseUrl, {
22169
22807
  max: 1,
22170
22808
  connect_timeout: 5,
22171
22809
  onnotice: () => {
22172
22810
  }
22173
22811
  });
22812
+ const cancelIdentityCheck = () => {
22813
+ void sql.end({ timeout: 0 }).catch(() => {
22814
+ });
22815
+ };
22816
+ signal?.addEventListener("abort", cancelIdentityCheck, { once: true });
22174
22817
  try {
22175
22818
  await sql.begin(async (tx) => {
22176
22819
  await tx`SELECT pg_advisory_xact_lock(7283020)`;
@@ -22192,8 +22835,10 @@ async function createManagedServer(options) {
22192
22835
  await tx`INSERT INTO tb_instance(id,instance_id) VALUES(1,${current.instanceId})`;
22193
22836
  });
22194
22837
  } finally {
22838
+ signal?.removeEventListener("abort", cancelIdentityCheck);
22195
22839
  await sql.end({ timeout: 1 });
22196
22840
  }
22841
+ checkLaunch();
22197
22842
  const settings = input?.settings ?? runtimeConfigSchema.parse({});
22198
22843
  const candidate = createTbServer({
22199
22844
  databaseUrl: current.databaseUrl,
@@ -22226,7 +22871,7 @@ async function createManagedServer(options) {
22226
22871
  const current2 = await store.state();
22227
22872
  if (!current2?.databaseUrl)
22228
22873
  throw new TBError("unavailable", "audit authority unavailable");
22229
- const auditSql = postgres4(current2.databaseUrl, {
22874
+ const auditSql = postgres5(current2.databaseUrl, {
22230
22875
  max: 1,
22231
22876
  connect_timeout: 5,
22232
22877
  onnotice: () => {
@@ -22243,20 +22888,32 @@ async function createManagedServer(options) {
22243
22888
  pluginCatalog: BUILTIN_CATALOG,
22244
22889
  pluginRunnerSocket: options.pluginRunnerSocket,
22245
22890
  ...options.uiDir ? { uiDir: options.uiDir } : {}
22891
+ }, () => {
22892
+ candidateLost = true;
22893
+ if (business === candidate) ownershipLost.abort();
22246
22894
  });
22895
+ const cancelPreparation = () => {
22896
+ void candidate.close().catch(() => {
22897
+ });
22898
+ };
22899
+ signal?.addEventListener("abort", cancelPreparation, { once: true });
22247
22900
  try {
22248
22901
  await candidate.prepare();
22902
+ checkLaunch();
22903
+ if (business) await business.close();
22904
+ checkLaunch();
22249
22905
  } catch (error) {
22250
22906
  await candidate.close();
22251
22907
  throw error;
22908
+ } finally {
22909
+ signal?.removeEventListener("abort", cancelPreparation);
22252
22910
  }
22253
- await business?.close();
22254
22911
  business = candidate;
22255
22912
  if (draining) business.startDraining();
22256
22913
  if (listener) business.deviceHub.attach(listener);
22257
22914
  };
22258
22915
  const maintenanceHooks = {
22259
- exclusive: (run) => store.exclusive(run),
22916
+ exclusive: withManagementLock,
22260
22917
  readSnapshot: async () => {
22261
22918
  const current = await store.state();
22262
22919
  if (!current?.databaseUrl)
@@ -22319,7 +22976,7 @@ async function createManagedServer(options) {
22319
22976
  };
22320
22977
  management.maintenance = new MaintenanceManager(maintenanceHooks);
22321
22978
  management.keys = new KeyManager({
22322
- exclusive: (run) => store.exclusive(run),
22979
+ exclusive: withManagementLock,
22323
22980
  readSnapshot: async () => ({
22324
22981
  ...await maintenanceHooks.readSnapshot(),
22325
22982
  replicaId
@@ -22350,20 +23007,57 @@ async function createManagedServer(options) {
22350
23007
  phase = "ready";
22351
23008
  }
22352
23009
  });
22353
- try {
22354
- state = await store.initialize();
22355
- if (state.phase === "initialized") {
22356
- try {
22357
- await launch(state);
22358
- phase = "ready";
22359
- } catch {
22360
- phase = "recovery";
22361
- }
22362
- } else phase = state.phase;
22363
- } catch {
23010
+ const recover = (stage2, error) => {
22364
23011
  phase = "recovery";
22365
- }
23012
+ let reason = "dependency_or_io_failure";
23013
+ if (isTBError(error)) reason = error.code;
23014
+ else if (error instanceof SyntaxError) reason = "invalid_json";
23015
+ else if (error instanceof Error && error.name === "ZodError") reason = "invalid_configuration";
23016
+ console.error(JSON.stringify({ event: "tool_bridge_recovery_required", stage: stage2, reason }));
23017
+ };
23018
+ let stage = "bootstrap";
23019
+ const attemptStartup = () => store.withStartupState(state?.instanceId, async (current) => {
23020
+ startup.signal.throwIfAborted();
23021
+ state = current;
23022
+ if (state.phase !== "initialized") {
23023
+ phase = state.phase;
23024
+ return;
23025
+ }
23026
+ stage = "launch";
23027
+ await launch(state, void 0, void 0, startup.signal);
23028
+ phase = "ready";
23029
+ });
23030
+ let reportContention;
23031
+ const contention = new Promise((resolve2) => {
23032
+ reportContention = resolve2;
23033
+ });
23034
+ const startupTask = pRetry(attemptStartup, {
23035
+ signal: startup.signal,
23036
+ retries: Infinity,
23037
+ minTimeout: 1e3,
23038
+ maxTimeout: 1e4,
23039
+ randomize: true,
23040
+ unref: true,
23041
+ shouldRetry: ({ error, attemptNumber }) => {
23042
+ if (!(error instanceof BootstrapLockBusyError || error instanceof RuntimeHandoffPendingError)) return false;
23043
+ if (attemptNumber === 1) {
23044
+ phase = "starting";
23045
+ console.info(JSON.stringify({ event: "tool_bridge_waiting_for_runtime_owner" }));
23046
+ reportContention();
23047
+ }
23048
+ return true;
23049
+ }
23050
+ }).catch((error) => {
23051
+ if (!startup.signal.aborted && !ownershipLost.signal.aborted) recover(stage, error);
23052
+ });
23053
+ await Promise.race([startupTask, contention]);
22366
23054
  app.get("/~setup/status", (c) => c.json(status()));
23055
+ app.use("/~setup/*", async (c, next) => {
23056
+ if (handoffBlocked())
23057
+ return c.json({ code: "unavailable", state: runtimeState() }, 503);
23058
+ await next();
23059
+ });
23060
+ app.use("/~setup/*", bodyLimit({ maxSize: 65536 }));
22367
23061
  app.get("/~setup/defaults", async (c) => {
22368
23062
  await store.authorize(
22369
23063
  c.req.header("x-tb-setup-token"),
@@ -22384,7 +23078,7 @@ async function createManagedServer(options) {
22384
23078
  redisConfigured: Boolean(defaults2?.redisUrl)
22385
23079
  });
22386
23080
  });
22387
- const configure = async (request2, recovery) => store.exclusive(async () => {
23081
+ const configure = async (request2, recovery) => withManagementLock(async () => {
22388
23082
  const current = await store.authorize(
22389
23083
  request2.headers.get("x-tb-setup-token") ?? void 0,
22390
23084
  recovery ? "recovery" : "setup"
@@ -22440,6 +23134,7 @@ async function createManagedServer(options) {
22440
23134
  internalS3Origin: defaults2?.storage ? new URL(defaults2.storage.endpoint).origin : current.internalS3Origin,
22441
23135
  revision: current.revision + 1
22442
23136
  };
23137
+ assertOwnershipIntact();
22443
23138
  phase = "installing";
22444
23139
  await store.write(
22445
23140
  recovery ? "bootstrap-pending.json" : "bootstrap.json",
@@ -22448,6 +23143,7 @@ async function createManagedServer(options) {
22448
23143
  if (!recovery) state = next;
22449
23144
  try {
22450
23145
  await launch(next, input, restoredKeys);
23146
+ assertOwnershipIntact();
22451
23147
  if (restoredKeys) await store.write("keys.json", restoredKeys);
22452
23148
  await store.finish(next);
22453
23149
  state = await store.state();
@@ -22477,17 +23173,19 @@ async function createManagedServer(options) {
22477
23173
  (c) => c.json({
22478
23174
  healthy: true,
22479
23175
  version: package_default.version,
22480
- state: phase,
23176
+ state: runtimeState(),
22481
23177
  instanceId: state?.instanceId
22482
23178
  })
22483
23179
  );
22484
23180
  app.get(
22485
23181
  "/readyz",
22486
- async (c) => business && phase === "ready" && !maintaining ? business.app.fetch(c.req.raw) : c.json({ ready: false, state: phase }, 503)
23182
+ async (c) => business && phase === "ready" && !maintaining && !ownershipLost.signal.aborted ? business.app.fetch(c.req.raw) : c.json({ ready: false, state: runtimeState() }, 503)
22487
23183
  );
22488
23184
  app.all("*", async (c) => {
22489
- if (phase === "ready" && business && !maintaining)
23185
+ if (phase === "ready" && business && !maintaining && !ownershipLost.signal.aborted)
22490
23186
  return business.app.fetch(c.req.raw);
23187
+ if (handoffBlocked())
23188
+ return c.json({ code: "unavailable", state: runtimeState() }, 503);
22491
23189
  const path = new URL(c.req.url).pathname;
22492
23190
  if ((path === "/ui" || path.startsWith("/ui/")) && assets)
22493
23191
  return serveUiAssets(c.req.raw, assets);
@@ -22530,47 +23228,80 @@ async function createManagedServer(options) {
22530
23228
  });
22531
23229
  const startDraining = () => {
22532
23230
  draining = true;
23231
+ startup.abort();
22533
23232
  business?.startDraining();
22534
23233
  };
22535
- const close = async () => {
22536
- const closed = listener ? new Promise((resolve2, reject) => {
22537
- listener.close((error) => error ? reject(error) : resolve2());
22538
- listener.closeIdleConnections?.();
23234
+ const close = () => closePromise ??= (async () => {
23235
+ startDraining();
23236
+ drainDelay.abort();
23237
+ await listening?.catch(() => {
23238
+ });
23239
+ const socket = listener;
23240
+ const closed = socket?.listening ? new Promise((resolve2, reject) => {
23241
+ socket.close((error) => error ? reject(error) : resolve2());
23242
+ socket.closeIdleConnections();
22539
23243
  }) : Promise.resolve();
22540
- const previous = business;
22541
- await previous?.close();
22542
- await closed;
22543
- if (business !== previous) await business?.close();
22544
- listener = void 0;
22545
- business = void 0;
22546
- };
23244
+ let previous;
23245
+ const closeRuntime = async () => {
23246
+ await startupTask;
23247
+ previous = business;
23248
+ await previous?.close();
23249
+ };
23250
+ const disconnectClients = () => socket?.closeAllConnections();
23251
+ ownershipLost.signal.addEventListener("abort", disconnectClients, { once: true });
23252
+ if (ownershipLost.signal.aborted) disconnectClients();
23253
+ try {
23254
+ const [runtime, connections] = await Promise.allSettled([closeRuntime(), closed]);
23255
+ managementClosed = true;
23256
+ await managementTask?.catch(() => {
23257
+ });
23258
+ if (business !== previous) await business?.close();
23259
+ if (runtime.status === "rejected") throw runtime.reason;
23260
+ if (connections.status === "rejected") throw connections.reason;
23261
+ } finally {
23262
+ ownershipLost.signal.removeEventListener("abort", disconnectClients);
23263
+ listener = void 0;
23264
+ business = void 0;
23265
+ }
23266
+ })();
22547
23267
  return {
22548
23268
  app,
22549
23269
  store,
23270
+ ownershipLost: ownershipLost.signal,
22550
23271
  async start() {
22551
- return new Promise((resolve2, reject) => {
22552
- listener = serve2(
22553
- {
22554
- fetch: app.fetch,
22555
- port: options.port ?? state?.port ?? 8787,
22556
- hostname: options.host ?? state?.host ?? "0.0.0.0"
22557
- },
22558
- (info) => {
22559
- actualPort = info.port;
22560
- business?.deviceHub.attach(listener);
22561
- resolve2({ port: actualPort });
22562
- }
22563
- );
22564
- listener.once("error", reject);
22565
- });
23272
+ if (draining) throw new TBError("unavailable", "server is shutting down");
23273
+ return listening ??= (async () => {
23274
+ const bind = state ?? (phase === "starting" ? await store.state() : void 0);
23275
+ return new Promise((resolve2, reject) => {
23276
+ listener = serve2(
23277
+ {
23278
+ fetch: app.fetch,
23279
+ port: options.port ?? bind?.port ?? 8787,
23280
+ hostname: options.host ?? bind?.host ?? "0.0.0.0"
23281
+ },
23282
+ (info) => {
23283
+ if (listener && !draining && !ownershipLost.signal.aborted) business?.deviceHub.attach(listener);
23284
+ resolve2({ port: info.port });
23285
+ }
23286
+ );
23287
+ listener.once("error", reject);
23288
+ });
23289
+ })();
22566
23290
  },
22567
23291
  startDraining,
22568
23292
  close,
22569
23293
  shutdown() {
23294
+ if (closePromise) return closePromise;
22570
23295
  shutdownPromise ??= (async () => {
22571
23296
  startDraining();
22572
23297
  const seconds = business?.shutdownDrainSec ?? lastShutdownDrainSec;
22573
- if (seconds > 0) await delay(seconds * 1e3);
23298
+ if (seconds > 0) {
23299
+ try {
23300
+ await delay(seconds * 1e3, void 0, { signal: drainDelay.signal });
23301
+ } catch (error) {
23302
+ if (!drainDelay.signal.aborted) throw error;
23303
+ }
23304
+ }
22574
23305
  await close();
22575
23306
  })();
22576
23307
  return shutdownPromise;