@tool-bridge/server 0.26.2 → 0.27.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.
package/dist/admin.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  BootstrapStateStore,
4
4
  package_default
5
- } from "./chunk-KTWFYFDL.js";
5
+ } from "./chunk-TMO3OAV5.js";
6
6
  import {
7
7
  httpsReleaseUrl,
8
8
  pluginImageSchema
@@ -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-TMO3OAV5.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
 
@@ -21459,13 +21485,13 @@ function resolveUiAssets(uiDirOverride) {
21459
21485
  // src/server.ts
21460
21486
  var providerOAuthFetch = createGuardedFetch({ crossOriginRedirect: "error" });
21461
21487
  var chatGptMetadataFetch = createGuardedFetch({ maxRedirects: 0 });
21462
- function createTbServer(config) {
21488
+ function createTbServer(config, onOwnershipLost) {
21463
21489
  if (!config.databaseUrl)
21464
21490
  throw new TBError(
21465
21491
  "unavailable",
21466
21492
  "PostgreSQL must be configured before starting business services"
21467
21493
  );
21468
- const sql = postgres3(config.databaseUrl, {
21494
+ const sql = postgres4(config.databaseUrl, {
21469
21495
  onnotice: () => {
21470
21496
  },
21471
21497
  connect_timeout: 5
@@ -21486,6 +21512,7 @@ function createTbServer(config) {
21486
21512
  const storeRepository = new PgStoreRepository(sql);
21487
21513
  const eventRepository = new PgEventRepository(sql);
21488
21514
  const eventStreamShutdown = new AbortController();
21515
+ const shutdown = new AbortController();
21489
21516
  const mailboxRepository = new PgMailboxRepository(sql);
21490
21517
  const storage = new StorageManager(sql, secrets, {
21491
21518
  ...config.internalS3Origin ? { internalOrigin: config.internalS3Origin } : {}
@@ -21507,6 +21534,14 @@ function createTbServer(config) {
21507
21534
  }
21508
21535
  });
21509
21536
  let draining = false;
21537
+ let closing = false;
21538
+ let preparedForTraffic = false;
21539
+ const ownershipLost = new AbortController();
21540
+ const accepting = () => preparedForTraffic && !closing && !ownershipLost.signal.aborted;
21541
+ const assertOpen = () => {
21542
+ if (closing || ownershipLost.signal.aborted)
21543
+ throw new TBError("unavailable", "runtime is closed");
21544
+ };
21510
21545
  const probeOne = async (fn) => {
21511
21546
  let timer;
21512
21547
  try {
@@ -21528,18 +21563,12 @@ function createTbServer(config) {
21528
21563
  }
21529
21564
  };
21530
21565
  const readiness = async () => {
21566
+ if (!accepting()) return { ready: false, checks: { runtime: { ok: false, detail: "runtime not accepting requests" } } };
21531
21567
  const checks = {};
21532
21568
  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
- }
21569
+ probes.push(probeOne(() => assertRuntimeAuthority(sql, replicaId)).then((r) => {
21570
+ checks.state = r;
21571
+ }));
21543
21572
  if (redisBackend !== void 0) {
21544
21573
  probes.push(
21545
21574
  probeOne(async () => await redisBackend.ping()).then((r) => {
@@ -21579,6 +21608,8 @@ function createTbServer(config) {
21579
21608
  mailboxRepository,
21580
21609
  eventRepository,
21581
21610
  eventStreamShutdown: eventStreamShutdown.signal,
21611
+ // In-process MCP calls can also enter the inner HTBP app.
21612
+ ensureReady: async () => ownershipLost.signal.throwIfAborted(),
21582
21613
  storageManagement: storage,
21583
21614
  deploymentManagement: deployment,
21584
21615
  ...config.adminAudit ? { adminAudit: config.adminAudit } : {},
@@ -21638,20 +21669,24 @@ function createTbServer(config) {
21638
21669
  deps.storeCallAllowedContentTypes = config.storeCallAllowedContentTypes;
21639
21670
  }
21640
21671
  let server;
21672
+ let listening;
21641
21673
  let maintenanceTimer;
21642
21674
  let maintenancePromise;
21643
21675
  let replicaTimer;
21644
- let heartbeatInFlight = Promise.resolve();
21676
+ let heartbeatInFlight;
21645
21677
  let applied;
21646
21678
  const runMaintenance = async () => {
21679
+ if (closing) return;
21647
21680
  if (maintenancePromise) return maintenancePromise;
21648
21681
  const snapshot = deps;
21649
21682
  maintenancePromise = (async () => {
21650
21683
  await sql`DELETE FROM tb_kv WHERE key >= 'mcp-inbound:' AND key < 'mcp-inbound;'
21651
21684
  AND value->>'expiresAt' <= ${(/* @__PURE__ */ new Date()).toISOString()}`;
21685
+ if (ownershipLost.signal.aborted) return;
21652
21686
  await eventRepository.cleanup();
21687
+ if (ownershipLost.signal.aborted) return;
21653
21688
  await cleanupDefaultStore(snapshot);
21654
- if (snapshot.encryptionKey !== void 0)
21689
+ if (!ownershipLost.signal.aborted && snapshot.encryptionKey !== void 0)
21655
21690
  await cleanupDeviceMailbox(snapshot);
21656
21691
  })().finally(() => {
21657
21692
  maintenancePromise = void 0;
@@ -21662,6 +21697,7 @@ function createTbServer(config) {
21662
21697
  console.warn(JSON.stringify({ event: "tool_bridge_store_cleanup_failed" }));
21663
21698
  };
21664
21699
  function scheduleStoreCleanup() {
21700
+ if (closing) return;
21665
21701
  void runMaintenance().catch(reportStoreCleanupFailure);
21666
21702
  maintenanceTimer = setInterval(
21667
21703
  () => {
@@ -21684,6 +21720,7 @@ function createTbServer(config) {
21684
21720
  };
21685
21721
  currentApp = buildApp();
21686
21722
  }, async (next) => {
21723
+ ownershipLost.signal.throwIfAborted();
21687
21724
  await hub.setReclaimSec(next.deviceReclaimSec);
21688
21725
  const reschedule = applied?.storeCleanupIntervalSec !== next.storeCleanupIntervalSec;
21689
21726
  applied = next;
@@ -21699,7 +21736,17 @@ function createTbServer(config) {
21699
21736
  const drainWaiters = [];
21700
21737
  const requestContext = new AsyncLocalStorage();
21701
21738
  const app = new Hono4();
21702
- app.all("*", async (c) => {
21739
+ app.mount("/", async (raw, env, executionCtx) => {
21740
+ const path = new URL(raw.url).pathname;
21741
+ const read = raw.method === "GET" || raw.method === "HEAD";
21742
+ const probe = read && ["/healthz", "/livez", "/readyz"].includes(path);
21743
+ const unavailable = (message) => Response.json({ code: "unavailable", message }, { status: 503 });
21744
+ if (!accepting()) {
21745
+ if (probe) return currentApp.fetch(raw, env, executionCtx);
21746
+ return unavailable("runtime not accepting requests");
21747
+ }
21748
+ const transport = AbortSignal.any([raw.signal, ownershipLost.signal]);
21749
+ const signal = AbortSignal.any([transport, shutdown.signal]);
21703
21750
  activeRequests++;
21704
21751
  let released = false;
21705
21752
  const request2 = {
@@ -21712,45 +21759,114 @@ function createTbServer(config) {
21712
21759
  };
21713
21760
  return requestContext.run(request2, async () => {
21714
21761
  try {
21715
- const path = new URL(c.req.url).pathname;
21716
- if (!["/healthz", "/livez", "/readyz"].includes(path) && !path.startsWith("/ui")) {
21762
+ if (!probe && !(read && (path === "/ui" || path.startsWith("/ui/")))) {
21717
21763
  try {
21718
21764
  await assertRuntimeAuthority(sql, replicaId);
21765
+ transport.throwIfAborted();
21719
21766
  await settings.sync();
21720
21767
  } 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);
21768
+ request2.release();
21769
+ return unavailable("configuration authority unavailable");
21728
21770
  }
21729
21771
  }
21730
- const snapshot = currentApp;
21731
- return trackResponseBody(await snapshot.fetch(c.req.raw), request2.release, c.req.raw.signal);
21772
+ if (transport.aborted) {
21773
+ request2.release();
21774
+ return unavailable("request interrupted before dispatch");
21775
+ }
21776
+ const body = !raw.keepalive && raw.mode !== "no-cors" ? raw.body?.pipeThrough(new TransformStream(), { signal: transport }) : void 0;
21777
+ try {
21778
+ const init = { signal, ...body && { body, duplex: "half" } };
21779
+ const forwarded = new Request(raw, init);
21780
+ if (forwarded.method !== raw.method) Object.defineProperty(forwarded, "method", { value: raw.method });
21781
+ const response = await currentApp.fetch(forwarded, env, executionCtx);
21782
+ const sse = response.headers.get("content-type")?.split(";")[0] === "text/event-stream";
21783
+ return trackResponseBody(response, request2.release, sse ? AbortSignal.any([transport, eventStreamShutdown.signal]) : transport);
21784
+ } finally {
21785
+ if (body && !body.locked) void body.cancel().catch(() => {
21786
+ });
21787
+ }
21732
21788
  } catch (error) {
21733
21789
  request2.release();
21734
21790
  throw error;
21735
21791
  }
21736
21792
  });
21737
- });
21793
+ }, { replaceRequest: false });
21738
21794
  let prepared;
21739
21795
  let runtimeLease;
21740
21796
  let closePromise;
21797
+ let listenerClosed;
21798
+ const stopListening = async (listener) => {
21799
+ if (!listener.listening) await listening?.catch(() => {
21800
+ });
21801
+ if (!listener.listening) return;
21802
+ await new Promise((resolve2, reject) => {
21803
+ listener.close((err) => err ? reject(err) : resolve2());
21804
+ listener.closeIdleConnections();
21805
+ });
21806
+ };
21807
+ const close = async (options) => {
21808
+ const caller = options?.excludeCurrentRequest ? requestContext.getStore() : void 0;
21809
+ caller?.release();
21810
+ if (!closePromise) {
21811
+ closing = true;
21812
+ draining = true;
21813
+ if (server) listenerClosed = stopListening(server);
21814
+ closePromise = Promise.resolve().then(async () => {
21815
+ eventStreamShutdown.abort();
21816
+ if (!caller) shutdown.abort(new TBError("unavailable", "runtime is shutting down"));
21817
+ if (maintenanceTimer !== void 0) {
21818
+ clearInterval(maintenanceTimer);
21819
+ maintenanceTimer = void 0;
21820
+ }
21821
+ if (!preparedForTraffic) await prepared?.catch(() => {
21822
+ });
21823
+ await hub.close();
21824
+ if (activeRequests > 0)
21825
+ await new Promise((resolve2) => drainWaiters.push(resolve2));
21826
+ await maintenancePromise?.catch(() => {
21827
+ });
21828
+ if (replicaTimer) clearInterval(replicaTimer);
21829
+ await heartbeatInFlight;
21830
+ try {
21831
+ await runtimeLease?.release();
21832
+ } finally {
21833
+ storage.close();
21834
+ await eventRepository.close().finally(() => sql.end({ timeout: 5 }));
21835
+ }
21836
+ });
21837
+ }
21838
+ await Promise.all([closePromise, caller ? void 0 : listenerClosed]);
21839
+ };
21741
21840
  const prepare = async () => {
21841
+ assertOpen();
21742
21842
  prepared ??= (async () => {
21743
- await state.ensureSchema();
21744
- runtimeLease = await acquireRuntimeLease(sql, {
21843
+ const lease = await acquireRuntimeLease(sql, {
21745
21844
  instanceId: config.instanceId ?? "embedded",
21746
21845
  replicaId,
21747
- redisUrl: config.redisUrl
21846
+ redisUrl: config.redisUrl,
21847
+ onLost: () => {
21848
+ if (ownershipLost.signal.aborted) return;
21849
+ ownershipLost.abort(new TBError("unavailable", "runtime ownership lost"));
21850
+ if (replicaTimer) clearInterval(replicaTimer);
21851
+ console.error(JSON.stringify({ event: "tool_bridge_runtime_ownership_lost" }));
21852
+ void close().catch(() => {
21853
+ console.error(JSON.stringify({ event: "tool_bridge_runtime_close_failed" }));
21854
+ });
21855
+ server?.closeAllConnections();
21856
+ onOwnershipLost?.();
21857
+ }
21748
21858
  });
21859
+ runtimeLease = lease;
21860
+ assertOpen();
21749
21861
  replicaTimer = setInterval(() => {
21750
- heartbeatInFlight = heartbeatInFlight.then(() => runtimeLease?.heartbeat()).catch(() => {
21862
+ if (heartbeatInFlight) return;
21863
+ heartbeatInFlight = lease.heartbeat().catch(() => {
21864
+ }).finally(() => {
21865
+ heartbeatInFlight = void 0;
21751
21866
  });
21752
21867
  }, 15e3);
21753
21868
  replicaTimer.unref();
21869
+ await state.ensureSchema();
21754
21870
  await storeRepository.ensureSchema();
21755
21871
  await state.ensureContextReferencesSchema();
21756
21872
  await eventRepository.ensureSchema();
@@ -21768,6 +21884,7 @@ function createTbServer(config) {
21768
21884
  )
21769
21885
  )
21770
21886
  );
21887
+ assertOpen();
21771
21888
  await runBootstrap(state, {
21772
21889
  management: true,
21773
21890
  additionalModules: [
@@ -21776,6 +21893,7 @@ function createTbServer(config) {
21776
21893
  ],
21777
21894
  ...config.adminSk ? { adminSk: config.adminSk } : {}
21778
21895
  });
21896
+ assertOpen();
21779
21897
  const backends = (await storage.list()).items;
21780
21898
  let active2 = backends.find((backend) => backend.active);
21781
21899
  if (!active2 && config.objectStore) {
@@ -21810,12 +21928,17 @@ function createTbServer(config) {
21810
21928
  if (!active2)
21811
21929
  throw new TBError("unavailable", "no active storage backend");
21812
21930
  await storage.resolveBackend(active2.id);
21931
+ assertOpen();
21813
21932
  await hub.startRouter();
21814
21933
  await settings.sync();
21934
+ assertOpen();
21815
21935
  await hub.sweepOrphans();
21936
+ assertOpen();
21816
21937
  scheduleStoreCleanup();
21938
+ preparedForTraffic = true;
21817
21939
  })();
21818
21940
  await prepared;
21941
+ assertOpen();
21819
21942
  };
21820
21943
  return {
21821
21944
  app,
@@ -21827,15 +21950,20 @@ function createTbServer(config) {
21827
21950
  deviceHub: hub,
21828
21951
  async start() {
21829
21952
  await prepare();
21830
- return await new Promise((resolve2) => {
21953
+ assertOpen();
21954
+ listening ??= new Promise((resolve2, reject) => {
21831
21955
  server = serve(
21832
21956
  { fetch: app.fetch, port: config.port, hostname: config.host },
21833
21957
  (info) => {
21958
+ if (!closing) hub.attach(server);
21834
21959
  resolve2({ port: info.port });
21835
21960
  }
21836
21961
  );
21837
- hub.attach(server);
21962
+ server.once("error", reject);
21838
21963
  });
21964
+ const address = await listening;
21965
+ assertOpen();
21966
+ return address;
21839
21967
  },
21840
21968
  startDraining() {
21841
21969
  draining = true;
@@ -21843,43 +21971,7 @@ function createTbServer(config) {
21843
21971
  get shutdownDrainSec() {
21844
21972
  return applied?.shutdownDrainSec ?? config.shutdownDrainSec ?? 0;
21845
21973
  },
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
- }
21974
+ close
21883
21975
  };
21884
21976
  }
21885
21977
 
@@ -22123,54 +22215,90 @@ function builtinPluginBindings(env, opts = {}) {
22123
22215
  }
22124
22216
 
22125
22217
  // src/managedServer.ts
22126
- import { serve as serve2 } from "@hono/node-server";
22127
22218
  import { setTimeout as delay } from "timers/promises";
22128
22219
  import { secureHeaders } from "hono/secure-headers";
22129
22220
  import { bodyLimit } from "hono/body-limit";
22221
+ import { serve as serve2 } from "@hono/node-server";
22130
22222
  import { randomUUID as randomUUID11 } from "crypto";
22131
- import postgres4 from "postgres";
22223
+ import postgres5 from "postgres";
22224
+ import pRetry from "p-retry";
22132
22225
  import { Hono as Hono5 } from "hono";
22133
22226
  async function createManagedServer(options) {
22134
22227
  const store = new BootstrapStateStore(options.directory);
22135
22228
  let state;
22136
22229
  let phase = "setup";
22230
+ const startup = new AbortController();
22231
+ const ownershipLost = new AbortController();
22232
+ const drainDelay = new AbortController();
22137
22233
  let business;
22138
22234
  let listener;
22235
+ let listening;
22236
+ let closePromise;
22237
+ let managementTask;
22238
+ let managementClosed = false;
22139
22239
  let maintaining = false;
22140
22240
  let draining = false;
22141
22241
  let shutdownPromise;
22142
22242
  let lastShutdownDrainSec = 0;
22143
- let actualPort = options.port ?? 8787;
22144
22243
  const replicaId = randomUUID11();
22145
22244
  const assets = resolveUiAssets(options.uiDir);
22146
22245
  const app = new Hono5();
22147
22246
  const defaults = secureHeaders();
22148
22247
  const consent = secureHeaders({ referrerPolicy: "same-origin" });
22149
22248
  app.use("*", (c, next) => c.req.path === MCP_AUTHORIZE_PATH ? consent(c, next) : defaults(c, next));
22150
- app.use("/~setup/*", bodyLimit({ maxSize: 65536 }));
22151
22249
  app.use("/~setup/*", async (c, next) => {
22152
22250
  c.header("Cache-Control", "no-store");
22153
22251
  await next();
22154
22252
  });
22253
+ const assertOwnershipIntact = () => {
22254
+ if (ownershipLost.signal.aborted) throw new TBError("unavailable", "runtime ownership lost; restart required");
22255
+ };
22256
+ const handoffBlocked = () => ownershipLost.signal.aborted || phase === "starting";
22257
+ const runtimeState = () => ownershipLost.signal.aborted ? "ownership_lost" : phase;
22155
22258
  const status = () => ({
22156
- state: phase,
22259
+ state: handoffBlocked() ? "installing" : phase,
22157
22260
  instanceId: state?.instanceId,
22158
- pairingRequired: phase !== "ready"
22261
+ pairingRequired: !handoffBlocked() && phase !== "ready"
22159
22262
  });
22160
22263
  const management = {};
22161
- const launch = async (current, input, restoredKeys) => {
22264
+ const withManagementLock = (run) => store.exclusive(async () => {
22265
+ if (managementClosed) throw new TBError("unavailable", "server is closed");
22266
+ const task = run();
22267
+ managementTask = task;
22268
+ try {
22269
+ return await task;
22270
+ } finally {
22271
+ managementTask = void 0;
22272
+ }
22273
+ });
22274
+ const launch = async (current, input, restoredKeys, signal) => {
22275
+ let candidateLost = false;
22276
+ const checkLaunch = () => {
22277
+ signal?.throwIfAborted();
22278
+ assertOwnershipIntact();
22279
+ if (candidateLost) throw new TBError("unavailable", "runtime ownership lost during preparation");
22280
+ };
22281
+ checkLaunch();
22282
+ if (!current.databaseUrl)
22283
+ throw new TBError("unavailable", "bootstrap database connection is unavailable");
22162
22284
  const keys = restoredKeys ?? await store.read("keys.json");
22163
- if (!keys || !current.databaseUrl)
22285
+ if (!keys)
22164
22286
  throw new TBError(
22165
22287
  "unavailable",
22166
- "local bootstrap secrets or database connection are unavailable"
22288
+ "local bootstrap secrets are unavailable"
22167
22289
  );
22168
- const sql = postgres4(current.databaseUrl, {
22290
+ checkLaunch();
22291
+ const sql = postgres5(current.databaseUrl, {
22169
22292
  max: 1,
22170
22293
  connect_timeout: 5,
22171
22294
  onnotice: () => {
22172
22295
  }
22173
22296
  });
22297
+ const cancelIdentityCheck = () => {
22298
+ void sql.end({ timeout: 0 }).catch(() => {
22299
+ });
22300
+ };
22301
+ signal?.addEventListener("abort", cancelIdentityCheck, { once: true });
22174
22302
  try {
22175
22303
  await sql.begin(async (tx) => {
22176
22304
  await tx`SELECT pg_advisory_xact_lock(7283020)`;
@@ -22192,8 +22320,10 @@ async function createManagedServer(options) {
22192
22320
  await tx`INSERT INTO tb_instance(id,instance_id) VALUES(1,${current.instanceId})`;
22193
22321
  });
22194
22322
  } finally {
22323
+ signal?.removeEventListener("abort", cancelIdentityCheck);
22195
22324
  await sql.end({ timeout: 1 });
22196
22325
  }
22326
+ checkLaunch();
22197
22327
  const settings = input?.settings ?? runtimeConfigSchema.parse({});
22198
22328
  const candidate = createTbServer({
22199
22329
  databaseUrl: current.databaseUrl,
@@ -22226,7 +22356,7 @@ async function createManagedServer(options) {
22226
22356
  const current2 = await store.state();
22227
22357
  if (!current2?.databaseUrl)
22228
22358
  throw new TBError("unavailable", "audit authority unavailable");
22229
- const auditSql = postgres4(current2.databaseUrl, {
22359
+ const auditSql = postgres5(current2.databaseUrl, {
22230
22360
  max: 1,
22231
22361
  connect_timeout: 5,
22232
22362
  onnotice: () => {
@@ -22243,20 +22373,32 @@ async function createManagedServer(options) {
22243
22373
  pluginCatalog: BUILTIN_CATALOG,
22244
22374
  pluginRunnerSocket: options.pluginRunnerSocket,
22245
22375
  ...options.uiDir ? { uiDir: options.uiDir } : {}
22376
+ }, () => {
22377
+ candidateLost = true;
22378
+ if (business === candidate) ownershipLost.abort();
22246
22379
  });
22380
+ const cancelPreparation = () => {
22381
+ void candidate.close().catch(() => {
22382
+ });
22383
+ };
22384
+ signal?.addEventListener("abort", cancelPreparation, { once: true });
22247
22385
  try {
22248
22386
  await candidate.prepare();
22387
+ checkLaunch();
22388
+ if (business) await business.close();
22389
+ checkLaunch();
22249
22390
  } catch (error) {
22250
22391
  await candidate.close();
22251
22392
  throw error;
22393
+ } finally {
22394
+ signal?.removeEventListener("abort", cancelPreparation);
22252
22395
  }
22253
- await business?.close();
22254
22396
  business = candidate;
22255
22397
  if (draining) business.startDraining();
22256
22398
  if (listener) business.deviceHub.attach(listener);
22257
22399
  };
22258
22400
  const maintenanceHooks = {
22259
- exclusive: (run) => store.exclusive(run),
22401
+ exclusive: withManagementLock,
22260
22402
  readSnapshot: async () => {
22261
22403
  const current = await store.state();
22262
22404
  if (!current?.databaseUrl)
@@ -22319,7 +22461,7 @@ async function createManagedServer(options) {
22319
22461
  };
22320
22462
  management.maintenance = new MaintenanceManager(maintenanceHooks);
22321
22463
  management.keys = new KeyManager({
22322
- exclusive: (run) => store.exclusive(run),
22464
+ exclusive: withManagementLock,
22323
22465
  readSnapshot: async () => ({
22324
22466
  ...await maintenanceHooks.readSnapshot(),
22325
22467
  replicaId
@@ -22350,20 +22492,57 @@ async function createManagedServer(options) {
22350
22492
  phase = "ready";
22351
22493
  }
22352
22494
  });
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 {
22495
+ const recover = (stage2, error) => {
22364
22496
  phase = "recovery";
22365
- }
22497
+ let reason = "dependency_or_io_failure";
22498
+ if (isTBError(error)) reason = error.code;
22499
+ else if (error instanceof SyntaxError) reason = "invalid_json";
22500
+ else if (error instanceof Error && error.name === "ZodError") reason = "invalid_configuration";
22501
+ console.error(JSON.stringify({ event: "tool_bridge_recovery_required", stage: stage2, reason }));
22502
+ };
22503
+ let stage = "bootstrap";
22504
+ const attemptStartup = () => store.withStartupState(state?.instanceId, async (current) => {
22505
+ startup.signal.throwIfAborted();
22506
+ state = current;
22507
+ if (state.phase !== "initialized") {
22508
+ phase = state.phase;
22509
+ return;
22510
+ }
22511
+ stage = "launch";
22512
+ await launch(state, void 0, void 0, startup.signal);
22513
+ phase = "ready";
22514
+ });
22515
+ let reportContention;
22516
+ const contention = new Promise((resolve2) => {
22517
+ reportContention = resolve2;
22518
+ });
22519
+ const startupTask = pRetry(attemptStartup, {
22520
+ signal: startup.signal,
22521
+ retries: Infinity,
22522
+ minTimeout: 1e3,
22523
+ maxTimeout: 1e4,
22524
+ randomize: true,
22525
+ unref: true,
22526
+ shouldRetry: ({ error, attemptNumber }) => {
22527
+ if (!(error instanceof BootstrapLockBusyError || error instanceof RuntimeHandoffPendingError)) return false;
22528
+ if (attemptNumber === 1) {
22529
+ phase = "starting";
22530
+ console.info(JSON.stringify({ event: "tool_bridge_waiting_for_runtime_owner" }));
22531
+ reportContention();
22532
+ }
22533
+ return true;
22534
+ }
22535
+ }).catch((error) => {
22536
+ if (!startup.signal.aborted && !ownershipLost.signal.aborted) recover(stage, error);
22537
+ });
22538
+ await Promise.race([startupTask, contention]);
22366
22539
  app.get("/~setup/status", (c) => c.json(status()));
22540
+ app.use("/~setup/*", async (c, next) => {
22541
+ if (handoffBlocked())
22542
+ return c.json({ code: "unavailable", state: runtimeState() }, 503);
22543
+ await next();
22544
+ });
22545
+ app.use("/~setup/*", bodyLimit({ maxSize: 65536 }));
22367
22546
  app.get("/~setup/defaults", async (c) => {
22368
22547
  await store.authorize(
22369
22548
  c.req.header("x-tb-setup-token"),
@@ -22384,7 +22563,7 @@ async function createManagedServer(options) {
22384
22563
  redisConfigured: Boolean(defaults2?.redisUrl)
22385
22564
  });
22386
22565
  });
22387
- const configure = async (request2, recovery) => store.exclusive(async () => {
22566
+ const configure = async (request2, recovery) => withManagementLock(async () => {
22388
22567
  const current = await store.authorize(
22389
22568
  request2.headers.get("x-tb-setup-token") ?? void 0,
22390
22569
  recovery ? "recovery" : "setup"
@@ -22440,6 +22619,7 @@ async function createManagedServer(options) {
22440
22619
  internalS3Origin: defaults2?.storage ? new URL(defaults2.storage.endpoint).origin : current.internalS3Origin,
22441
22620
  revision: current.revision + 1
22442
22621
  };
22622
+ assertOwnershipIntact();
22443
22623
  phase = "installing";
22444
22624
  await store.write(
22445
22625
  recovery ? "bootstrap-pending.json" : "bootstrap.json",
@@ -22448,6 +22628,7 @@ async function createManagedServer(options) {
22448
22628
  if (!recovery) state = next;
22449
22629
  try {
22450
22630
  await launch(next, input, restoredKeys);
22631
+ assertOwnershipIntact();
22451
22632
  if (restoredKeys) await store.write("keys.json", restoredKeys);
22452
22633
  await store.finish(next);
22453
22634
  state = await store.state();
@@ -22477,17 +22658,19 @@ async function createManagedServer(options) {
22477
22658
  (c) => c.json({
22478
22659
  healthy: true,
22479
22660
  version: package_default.version,
22480
- state: phase,
22661
+ state: runtimeState(),
22481
22662
  instanceId: state?.instanceId
22482
22663
  })
22483
22664
  );
22484
22665
  app.get(
22485
22666
  "/readyz",
22486
- async (c) => business && phase === "ready" && !maintaining ? business.app.fetch(c.req.raw) : c.json({ ready: false, state: phase }, 503)
22667
+ async (c) => business && phase === "ready" && !maintaining && !ownershipLost.signal.aborted ? business.app.fetch(c.req.raw) : c.json({ ready: false, state: runtimeState() }, 503)
22487
22668
  );
22488
22669
  app.all("*", async (c) => {
22489
- if (phase === "ready" && business && !maintaining)
22670
+ if (phase === "ready" && business && !maintaining && !ownershipLost.signal.aborted)
22490
22671
  return business.app.fetch(c.req.raw);
22672
+ if (handoffBlocked())
22673
+ return c.json({ code: "unavailable", state: runtimeState() }, 503);
22491
22674
  const path = new URL(c.req.url).pathname;
22492
22675
  if ((path === "/ui" || path.startsWith("/ui/")) && assets)
22493
22676
  return serveUiAssets(c.req.raw, assets);
@@ -22530,47 +22713,80 @@ async function createManagedServer(options) {
22530
22713
  });
22531
22714
  const startDraining = () => {
22532
22715
  draining = true;
22716
+ startup.abort();
22533
22717
  business?.startDraining();
22534
22718
  };
22535
- const close = async () => {
22536
- const closed = listener ? new Promise((resolve2, reject) => {
22537
- listener.close((error) => error ? reject(error) : resolve2());
22538
- listener.closeIdleConnections?.();
22719
+ const close = () => closePromise ??= (async () => {
22720
+ startDraining();
22721
+ drainDelay.abort();
22722
+ await listening?.catch(() => {
22723
+ });
22724
+ const socket = listener;
22725
+ const closed = socket?.listening ? new Promise((resolve2, reject) => {
22726
+ socket.close((error) => error ? reject(error) : resolve2());
22727
+ socket.closeIdleConnections();
22539
22728
  }) : 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
- };
22729
+ let previous;
22730
+ const closeRuntime = async () => {
22731
+ await startupTask;
22732
+ previous = business;
22733
+ await previous?.close();
22734
+ };
22735
+ const disconnectClients = () => socket?.closeAllConnections();
22736
+ ownershipLost.signal.addEventListener("abort", disconnectClients, { once: true });
22737
+ if (ownershipLost.signal.aborted) disconnectClients();
22738
+ try {
22739
+ const [runtime, connections] = await Promise.allSettled([closeRuntime(), closed]);
22740
+ managementClosed = true;
22741
+ await managementTask?.catch(() => {
22742
+ });
22743
+ if (business !== previous) await business?.close();
22744
+ if (runtime.status === "rejected") throw runtime.reason;
22745
+ if (connections.status === "rejected") throw connections.reason;
22746
+ } finally {
22747
+ ownershipLost.signal.removeEventListener("abort", disconnectClients);
22748
+ listener = void 0;
22749
+ business = void 0;
22750
+ }
22751
+ })();
22547
22752
  return {
22548
22753
  app,
22549
22754
  store,
22755
+ ownershipLost: ownershipLost.signal,
22550
22756
  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
- });
22757
+ if (draining) throw new TBError("unavailable", "server is shutting down");
22758
+ return listening ??= (async () => {
22759
+ const bind = state ?? (phase === "starting" ? await store.state() : void 0);
22760
+ return new Promise((resolve2, reject) => {
22761
+ listener = serve2(
22762
+ {
22763
+ fetch: app.fetch,
22764
+ port: options.port ?? bind?.port ?? 8787,
22765
+ hostname: options.host ?? bind?.host ?? "0.0.0.0"
22766
+ },
22767
+ (info) => {
22768
+ if (listener && !draining && !ownershipLost.signal.aborted) business?.deviceHub.attach(listener);
22769
+ resolve2({ port: info.port });
22770
+ }
22771
+ );
22772
+ listener.once("error", reject);
22773
+ });
22774
+ })();
22566
22775
  },
22567
22776
  startDraining,
22568
22777
  close,
22569
22778
  shutdown() {
22779
+ if (closePromise) return closePromise;
22570
22780
  shutdownPromise ??= (async () => {
22571
22781
  startDraining();
22572
22782
  const seconds = business?.shutdownDrainSec ?? lastShutdownDrainSec;
22573
- if (seconds > 0) await delay(seconds * 1e3);
22783
+ if (seconds > 0) {
22784
+ try {
22785
+ await delay(seconds * 1e3, void 0, { signal: drainDelay.signal });
22786
+ } catch (error) {
22787
+ if (!drainDelay.signal.aborted) throw error;
22788
+ }
22789
+ }
22574
22790
  await close();
22575
22791
  })();
22576
22792
  return shutdownPromise;
@@ -25,6 +25,11 @@ var stateSchema = z.strictObject({
25
25
  port: z.number().int().min(0).max(65535).default(8787),
26
26
  host: z.string().default("0.0.0.0")
27
27
  });
28
+ var BootstrapLockBusyError = class extends TBError {
29
+ constructor() {
30
+ super("conflict", "another local maintenance operation is running");
31
+ }
32
+ };
28
33
  var BootstrapStateStore = class {
29
34
  constructor(directory) {
30
35
  this.directory = directory;
@@ -41,7 +46,7 @@ var BootstrapStateStore = class {
41
46
  update: 1e4
42
47
  }).catch((error) => {
43
48
  if (error.code === "ELOCKED") {
44
- throw new TBError("conflict", "another local maintenance operation is running");
49
+ throw new BootstrapLockBusyError();
45
50
  }
46
51
  throw error;
47
52
  });
@@ -78,38 +83,45 @@ var BootstrapStateStore = class {
78
83
  return value === void 0 ? void 0 : stateSchema.parse(value);
79
84
  }
80
85
  async initialize() {
81
- return this.exclusive(async () => {
82
- const current = await this.state();
83
- if (current) {
84
- if (await this.read("initialized.json"))
85
- return { ...current, phase: "initialized" };
86
- return current;
87
- }
88
- if (await this.read("identity.json"))
89
- throw new TBError(
90
- "unavailable",
91
- "bootstrap state requires local recovery"
92
- );
93
- const state = {
94
- instanceId: randomUUID(),
95
- revision: 1,
96
- phase: "setup",
97
- port: 8787,
98
- host: "0.0.0.0"
99
- };
100
- await this.write("identity.json", { instanceId: state.instanceId });
101
- await this.write("keys.json", {
102
- keyring: createEncryptionKeyring(randomBytes(32).toString("base64url")),
103
- storeTokenKeyring: createEncryptionKeyring(
104
- randomBytes(32).toString("base64url")
105
- ),
106
- oauthKey: randomBytes(32).toString("base64url"),
107
- adminSk: `tb_sk_${randomBytes(32).toString("base64url")}`
108
- });
109
- await this.write("bootstrap.json", state);
110
- await this.pair(state.instanceId, "setup");
111
- return state;
112
- }, 5);
86
+ return this.exclusive(() => this.readOrInitialize(), 5);
87
+ }
88
+ /** Keep bootstrap reads, including the first initialization, locked through admission. */
89
+ async withStartupState(initializedInstanceId, admit) {
90
+ return this.exclusive(async () => admit(await this.readOrInitialize(initializedInstanceId)));
91
+ }
92
+ async readOrInitialize(initializedInstanceId) {
93
+ const current = await this.state();
94
+ if (initializedInstanceId && current?.instanceId !== initializedInstanceId)
95
+ throw new TBError("conflict", "bootstrap identity changed during handoff");
96
+ if (current) {
97
+ if (initializedInstanceId || await this.read("initialized.json"))
98
+ return { ...current, phase: "initialized" };
99
+ return current;
100
+ }
101
+ if (await this.read("identity.json"))
102
+ throw new TBError(
103
+ "unavailable",
104
+ "bootstrap state requires local recovery"
105
+ );
106
+ const state = {
107
+ instanceId: randomUUID(),
108
+ revision: 1,
109
+ phase: "setup",
110
+ port: 8787,
111
+ host: "0.0.0.0"
112
+ };
113
+ await this.write("identity.json", { instanceId: state.instanceId });
114
+ await this.write("keys.json", {
115
+ keyring: createEncryptionKeyring(randomBytes(32).toString("base64url")),
116
+ storeTokenKeyring: createEncryptionKeyring(
117
+ randomBytes(32).toString("base64url")
118
+ ),
119
+ oauthKey: randomBytes(32).toString("base64url"),
120
+ adminSk: `tb_sk_${randomBytes(32).toString("base64url")}`
121
+ });
122
+ await this.write("bootstrap.json", state);
123
+ await this.pair(state.instanceId, "setup");
124
+ return state;
113
125
  }
114
126
  async pair(instanceId, mode) {
115
127
  const token = randomBytes(32).toString("base64url");
@@ -216,7 +228,7 @@ var BootstrapStateStore = class {
216
228
  // package.json
217
229
  var package_default = {
218
230
  name: "@tool-bridge/server",
219
- version: "0.26.2",
231
+ version: "0.27.0",
220
232
  description: "Self-hosted Tool Bridge Node server with PostgreSQL, S3 object storage and WebSocket device channels",
221
233
  type: "module",
222
234
  license: "MIT",
@@ -299,6 +311,7 @@ var package_default = {
299
311
  };
300
312
 
301
313
  export {
314
+ BootstrapLockBusyError,
302
315
  BootstrapStateStore,
303
316
  package_default
304
317
  };
package/dist/index.d.ts CHANGED
@@ -1764,6 +1764,9 @@ declare class BootstrapStateStore {
1764
1764
  write(name: string, value: unknown): Promise<void>;
1765
1765
  state(): Promise<BootstrapState | undefined>;
1766
1766
  initialize(): Promise<BootstrapState>;
1767
+ /** Keep bootstrap reads, including the first initialization, locked through admission. */
1768
+ withStartupState(initializedInstanceId: string | undefined, admit: (state: BootstrapState) => Promise<void>): Promise<void>;
1769
+ private readOrInitialize;
1767
1770
  private pair;
1768
1771
  createLocalPairing(mode: Pairing['mode']): Promise<string>;
1769
1772
  private hash;
@@ -2327,6 +2330,7 @@ interface ManagedServerOptions {
2327
2330
  declare function createManagedServer(options: ManagedServerOptions): Promise<{
2328
2331
  app: Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">;
2329
2332
  store: BootstrapStateStore;
2333
+ ownershipLost: AbortSignal;
2330
2334
  start(): Promise<{
2331
2335
  port: number;
2332
2336
  }>;
@@ -2632,6 +2636,6 @@ interface TbServer {
2632
2636
  state: StateStore;
2633
2637
  storage: StorageManager;
2634
2638
  }
2635
- declare function createTbServer(config: ServerConfig): TbServer;
2639
+ declare function createTbServer(config: ServerConfig, onOwnershipLost?: () => void): TbServer;
2636
2640
 
2637
2641
  export { BootstrapStateStore, DEVICE_FORWARD_TIMEOUT_MS, DEVICE_ROUTE_TTL_SEC, DEVICE_WS_PATH, DeviceHub, type DeviceLocalCall, DeviceRouter, type DeviceRouterBackend, type KeyManagementHooks, KeyManager, type MaintenanceHooks, MaintenanceManager, type ManagedServerOptions, PgEventRepository, PgKeyRotation, PgMailboxRepository, PgSearchIndex, PgStateStore, PgStoreRepository, RedisDeviceRouterBackend, type S3ObjectStore, type S3ObjectStoreOptions, type S3ProbeResult, type ServerConfig, StorageManager, type TbServer, createManagedServer, createS3ObjectStore, createTbServer, probeS3ObjectStore, runtimeAppSettings };
package/dist/index.js CHANGED
@@ -19,11 +19,11 @@ import {
19
19
  createTbServer,
20
20
  probeS3ObjectStore,
21
21
  runtimeAppSettings
22
- } from "./chunk-VKZYPURU.js";
22
+ } from "./chunk-IZZ5C42L.js";
23
23
  import "./chunk-U7PTOA3U.js";
24
24
  import {
25
25
  BootstrapStateStore
26
- } from "./chunk-KTWFYFDL.js";
26
+ } from "./chunk-TMO3OAV5.js";
27
27
  import "./chunk-NXLE6ZEK.js";
28
28
  import "./chunk-6W5WJCKR.js";
29
29
  import "./chunk-4WDQGEOC.js";
package/dist/main.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  createManagedServer
4
- } from "./chunk-VKZYPURU.js";
4
+ } from "./chunk-IZZ5C42L.js";
5
5
  import "./chunk-U7PTOA3U.js";
6
6
  import {
7
7
  package_default
8
- } from "./chunk-KTWFYFDL.js";
8
+ } from "./chunk-TMO3OAV5.js";
9
9
  import "./chunk-NXLE6ZEK.js";
10
10
  import "./chunk-6W5WJCKR.js";
11
11
  import "./chunk-4WDQGEOC.js";
@@ -51,12 +51,14 @@ var program = new Command("tool-bridge-server").version(package_default.version)
51
51
  stopping = true;
52
52
  console.log(JSON.stringify({ event: "tool_bridge_draining" }));
53
53
  void server.shutdown().then(
54
- () => process.exit(0),
54
+ () => process.exit(server.ownershipLost.aborted ? 1 : 0),
55
55
  () => process.exit(1)
56
56
  );
57
57
  };
58
58
  process.on("SIGINT", shutdown);
59
59
  process.on("SIGTERM", shutdown);
60
+ server.ownershipLost.addEventListener("abort", shutdown, { once: true });
61
+ if (server.ownershipLost.aborted) shutdown();
60
62
  });
61
63
  try {
62
64
  await program.parseAsync();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tool-bridge/server",
3
- "version": "0.26.2",
3
+ "version": "0.27.0",
4
4
  "description": "Self-hosted Tool Bridge Node server with PostgreSQL, S3 object storage and WebSocket device channels",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -60,9 +60,9 @@
60
60
  "@types/write-file-atomic": "^4.0.3",
61
61
  "@types/proper-lockfile": "^4.1.4",
62
62
  "@types/negotiator": "^0.6.4",
63
+ "@tool-bridge/core": "0.1.0",
63
64
  "@tool-bridge/app": "0.25.0",
64
- "@tool-bridge/plugins": "0.1.0",
65
- "@tool-bridge/core": "0.1.0"
65
+ "@tool-bridge/plugins": "0.1.0"
66
66
  },
67
67
  "repository": {
68
68
  "type": "git",