@mrrlin-dev/mcp 0.4.217 → 0.4.218

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bin.cjs +366 -211
  2. package/package.json +1 -1
package/dist/bin.cjs CHANGED
@@ -97626,11 +97626,11 @@ function createOwnedStreamingFetch(scope, origin) {
97626
97626
  if (!Number.isFinite(remaining) || remaining <= 0 || remaining > 2147483647 || signal?.aborted) throw aborted2();
97627
97627
  let onDeadline = expire;
97628
97628
  const timer = setTimeout(() => onDeadline(), Math.ceil(remaining));
97629
- let canceledBeforeDeadline = false;
97629
+ let canceledExternally = false;
97630
97630
  const caller = signal ? (0, import_node_events3.addAbortListener)(signal, () => {
97631
97631
  if (deadlineSignal?.aborted && signal.reason === deadlineSignal.reason) onDeadline();
97632
97632
  else {
97633
- canceledBeforeDeadline = performance.now() < deadlineAt;
97633
+ canceledExternally = true;
97634
97634
  expire();
97635
97635
  }
97636
97636
  }) : void 0;
@@ -97647,7 +97647,7 @@ function createOwnedStreamingFetch(scope, origin) {
97647
97647
  });
97648
97648
  let waitingForHeaders = false;
97649
97649
  const rotate = () => {
97650
- if (waitingForHeaders && !canceledBeforeDeadline) input.rotateOnHeaderTimeout?.rotate(operation.generation);
97650
+ if (waitingForHeaders && !canceledExternally) input.rotateOnHeaderTimeout?.rotate(operation.generation);
97651
97651
  };
97652
97652
  onDeadline = () => {
97653
97653
  rotate();
@@ -99653,7 +99653,7 @@ Do NOT derail the current task - if the operator has an in-flight question, answ
99653
99653
  }
99654
99654
 
99655
99655
  // src/_generated/version.ts
99656
- var PKG_VERSION = "0.4.217";
99656
+ var PKG_VERSION = "0.4.218";
99657
99657
 
99658
99658
  // src/bridge-allowed-origins.ts
99659
99659
  var DEFAULT_DIRECTOR_BRIDGE_ALLOWED_ORIGINS = [
@@ -101911,6 +101911,178 @@ var BridgeOperationScope = class {
101911
101911
  }
101912
101912
  };
101913
101913
 
101914
+ // src/owned-api-transport.ts
101915
+ var import_node_async_hooks = require("node:async_hooks");
101916
+ var import_node_events8 = require("node:events");
101917
+ var LOGICAL_LIMIT = 20;
101918
+ var HTTP_METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"];
101919
+ var StdioLocalError = class extends Error {
101920
+ };
101921
+ function parseUrl(value) {
101922
+ try {
101923
+ return new URL(value);
101924
+ } catch {
101925
+ throw new StdioLocalError("STDIO_UNSUPPORTED_REQUEST");
101926
+ }
101927
+ }
101928
+ async function untilCanceled(pending, signal) {
101929
+ if (signal.aborted) {
101930
+ void pending.catch(() => {
101931
+ });
101932
+ signal.throwIfAborted();
101933
+ }
101934
+ let subscription;
101935
+ try {
101936
+ return await Promise.race([pending, new Promise((_, reject) => {
101937
+ subscription = (0, import_node_events8.addAbortListener)(signal, () => reject(signal.reason));
101938
+ })]);
101939
+ } finally {
101940
+ subscription?.[Symbol.dispose]();
101941
+ }
101942
+ }
101943
+ function boundedResponse(response, relativePath) {
101944
+ if (!response.body) return response;
101945
+ const artifact = /^\/projects\/[^/]+\/artifact-files\/[^/]+\/content$/u.test(relativePath);
101946
+ const limit = !response.ok ? 64 * 1024 : artifact ? MRRLIN_ARTIFACT_INLINE_MAX_BYTES : 8 * 1024 * 1024;
101947
+ let size = 0;
101948
+ const body = response.body.pipeThrough(new TransformStream({
101949
+ transform(chunk, controller) {
101950
+ size += chunk.byteLength;
101951
+ if (size > limit) throw new MrrlinResponseTooLargeError(limit);
101952
+ controller.enqueue(chunk);
101953
+ }
101954
+ }));
101955
+ const bounded = new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
101956
+ return new Proxy(bounded, {
101957
+ get(target, key) {
101958
+ if (key === "url") return response.url;
101959
+ const value = Reflect.get(target, key, target);
101960
+ return typeof value === "function" ? value.bind(target) : value;
101961
+ }
101962
+ });
101963
+ }
101964
+ function createOwnedApiTransport(options, dependencies = {}) {
101965
+ const base = parseUrl(options.apiBaseUrl);
101966
+ if (!["http:", "https:"].includes(base.protocol) || base.username || base.password || base.hash || base.search) {
101967
+ throw new StdioLocalError("STDIO_INVALID_API_BASE");
101968
+ }
101969
+ const prefix = base.pathname.replace(/\/$/u, "");
101970
+ const generations = new BridgeGenerationManager(base.origin, { ownedOrdinary: true });
101971
+ const scope = new BridgeOperationScope(generations);
101972
+ const attempts = new BridgeHttpAdmission({ limits: {
101973
+ ordinary: { active: 4, waiting: 16 },
101974
+ heartbeat: { active: 1, waiting: 0 },
101975
+ scheduler: { active: 1, waiting: 0 },
101976
+ refresh: { active: 1, waiting: 0 }
101977
+ } });
101978
+ const stream = createOwnedStreamingFetch(scope, base.origin);
101979
+ const shutdown = new AbortController();
101980
+ const invocations = new import_node_async_hooks.AsyncLocalStorage();
101981
+ let logical = 0;
101982
+ function dispose() {
101983
+ shutdown.abort(new DOMException("Owned API transport closed", "AbortError"));
101984
+ attempts.dispose();
101985
+ scope.dispose();
101986
+ return generations.dispose();
101987
+ }
101988
+ if (!dependencies.deferStart) {
101989
+ try {
101990
+ generations.start();
101991
+ } catch (error51) {
101992
+ void dispose();
101993
+ throw error51;
101994
+ }
101995
+ }
101996
+ const createOperation = () => {
101997
+ if (shutdown.signal.aborted) throw new StdioLocalError("STDIO_TRANSPORT_CLOSED");
101998
+ const invocation = invocations.getStore();
101999
+ invocation?.signal?.throwIfAborted();
102000
+ invocation?.deadline?.signal.throwIfAborted();
102001
+ if (logical >= LOGICAL_LIMIT) throw new StdioLocalError("STDIO_LOGICAL_OVERLOAD");
102002
+ logical++;
102003
+ const timeoutMs = dependencies.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
102004
+ const deadlineAt = invocation?.deadline?.at ?? performance.now() + timeoutMs;
102005
+ const deadlineSignal = invocation?.deadline?.signal ?? AbortSignal.timeout(timeoutMs);
102006
+ const signals = [deadlineSignal, shutdown.signal];
102007
+ if (invocation?.signal) signals.push(invocation.signal);
102008
+ const signal = AbortSignal.any(signals);
102009
+ let closed = false;
102010
+ return {
102011
+ signal,
102012
+ deadlineAt,
102013
+ deadlineSignal,
102014
+ close() {
102015
+ if (!closed) {
102016
+ closed = true;
102017
+ logical--;
102018
+ }
102019
+ },
102020
+ shouldRetryError: (error51) => !(error51 instanceof StdioLocalError || error51 instanceof BridgeAdmissionError),
102021
+ fetch: async (input, init) => {
102022
+ if (typeof input !== "string") throw new StdioLocalError("STDIO_UNSUPPORTED_REQUEST");
102023
+ const url2 = parseUrl(input);
102024
+ const method = (init?.method ?? "GET").toUpperCase();
102025
+ const body = init?.body;
102026
+ if (url2.origin !== base.origin || url2.username || url2.password || url2.hash || !url2.pathname.startsWith(prefix + "/") || /%2f|%5c/iu.test(url2.pathname) || !HTTP_METHODS.includes(method) || body != null && (!(typeof body === "string" || body instanceof Uint8Array) || method === "GET" || method === "HEAD")) {
102027
+ throw new StdioLocalError("STDIO_UNSUPPORTED_REQUEST");
102028
+ }
102029
+ const attemptSignal = init?.signal ? AbortSignal.any([init.signal, signal]) : signal;
102030
+ const admission = attempts.acquire("ordinary", { signal: attemptSignal, deadline: deadlineAt });
102031
+ if (dependencies.onAttemptQueued) {
102032
+ const { waiting } = attempts.counts("ordinary");
102033
+ if (waiting > 0) dependencies.onAttemptQueued(waiting);
102034
+ }
102035
+ const permit = await admission;
102036
+ const pending = (async () => {
102037
+ let dispatched = false;
102038
+ try {
102039
+ attemptSignal.throwIfAborted();
102040
+ const headers = new Headers(init?.headers);
102041
+ try {
102042
+ const { token, executor } = await options.readBearer();
102043
+ if (token && (executor || !headers.has("authorization"))) headers.set("authorization", "Bearer " + token);
102044
+ } catch {
102045
+ throw new StdioLocalError("STDIO_CREDENTIAL_UNAVAILABLE");
102046
+ }
102047
+ attemptSignal.throwIfAborted();
102048
+ if (performance.now() >= deadlineAt) throw new DOMException("Request expired", "AbortError");
102049
+ dispatched = true;
102050
+ const response = await stream({
102051
+ url: url2.href,
102052
+ method,
102053
+ body: body ?? void 0,
102054
+ headers: Object.fromEntries(headers),
102055
+ deadlineAt,
102056
+ deadlineSignal,
102057
+ signal: attemptSignal,
102058
+ rotateOnHeaderTimeout: generations,
102059
+ onReleased: permit.release,
102060
+ onGeneration: dependencies.onGeneration,
102061
+ rejectRedirect: () => new StdioLocalError("STDIO_REDIRECT_REFUSED")
102062
+ });
102063
+ return boundedResponse(response, url2.pathname.slice(prefix.length));
102064
+ } finally {
102065
+ if (!dispatched) permit.release();
102066
+ }
102067
+ })();
102068
+ return untilCanceled(pending, attemptSignal);
102069
+ }
102070
+ };
102071
+ };
102072
+ return {
102073
+ createOperation,
102074
+ start: () => generations.start(),
102075
+ runInvocation(signal, invoke2) {
102076
+ return invocations.run({ signal }, invoke2);
102077
+ },
102078
+ runWithinDeadline(signal, budgetMs, invoke2) {
102079
+ const at = performance.now() + budgetMs;
102080
+ return invocations.run({ signal, deadline: { at, signal: AbortSignal.timeout(budgetMs) } }, invoke2);
102081
+ },
102082
+ dispose
102083
+ };
102084
+ }
102085
+
101914
102086
  // src/retention/pruner.ts
101915
102087
  var import_promises15 = require("node:fs/promises");
101916
102088
  var import_node_path36 = __toESM(require("node:path"), 1);
@@ -111253,7 +111425,7 @@ function createToolBusyClock(opts) {
111253
111425
  }
111254
111426
 
111255
111427
  // src/remote-phone-relay.ts
111256
- var import_node_events8 = require("node:events");
111428
+ var import_node_events9 = require("node:events");
111257
111429
  var import_node_fs30 = require("node:fs");
111258
111430
  var import_node_os22 = require("node:os");
111259
111431
  var import_node_path45 = require("node:path");
@@ -114872,7 +115044,7 @@ function saveAgentPairing(record2) {
114872
115044
  }
114873
115045
  function runPhoneTurn(handler, directorSessionId, text, emit) {
114874
115046
  return new Promise((resolve3) => {
114875
- const emitter = new import_node_events8.EventEmitter();
115047
+ const emitter = new import_node_events9.EventEmitter();
114876
115048
  const fakeSocket = {
114877
115049
  on: (event, cb) => {
114878
115050
  emitter.on(event, cb);
@@ -119150,27 +119322,49 @@ ${effectiveText}` : effectiveText;
119150
119322
  };
119151
119323
  }
119152
119324
  function createBridgeShutdown(deps) {
119153
- let invoked = false;
119154
- return async () => {
119155
- if (invoked) return;
119156
- invoked = true;
119157
- deps.log?.("[mrrlin-mcp director-bridge] shutting down (closing servers, stopping codex)...");
119158
- for (const close of deps.closers) {
119159
- try {
119160
- close();
119161
- } catch {
119162
- }
119163
- }
119325
+ const log2 = (message) => {
119164
119326
  try {
119165
- deps.shutdownCodex();
119327
+ deps.log?.(message);
119166
119328
  } catch {
119167
119329
  }
119330
+ };
119331
+ let shutdown;
119332
+ return () => {
119333
+ if (shutdown) return deps.stopTransport ? shutdown : Promise.resolve();
119334
+ let resolve3;
119335
+ let reject;
119336
+ shutdown = new Promise((done, failed) => {
119337
+ resolve3 = done;
119338
+ reject = failed;
119339
+ });
119340
+ const reportUnconfirmed = () => log2("[mrrlin-mcp director-bridge] owned transport close was not confirmed");
119341
+ let transport;
119168
119342
  try {
119169
- if (deps.stopExecution) await deps.stopExecution();
119343
+ transport = deps.stopTransport?.().catch(reportUnconfirmed);
119170
119344
  } catch {
119171
- deps.log?.("[mrrlin-mcp director-bridge] execution shutdown did not settle before exit");
119345
+ reportUnconfirmed();
119172
119346
  }
119173
- deps.exit(0);
119347
+ void (async () => {
119348
+ log2("[mrrlin-mcp director-bridge] shutting down (closing servers, stopping codex)...");
119349
+ for (const close of deps.closers) {
119350
+ try {
119351
+ close();
119352
+ } catch {
119353
+ }
119354
+ }
119355
+ try {
119356
+ deps.shutdownCodex();
119357
+ } catch {
119358
+ }
119359
+ try {
119360
+ if (deps.stopExecution) await deps.stopExecution();
119361
+ } catch {
119362
+ log2("[mrrlin-mcp director-bridge] execution shutdown did not settle before exit");
119363
+ }
119364
+ if (transport) await transport;
119365
+ deps.exit(0);
119366
+ })().then(resolve3, reject);
119367
+ return shutdown;
119174
119368
  };
119175
119369
  }
119176
119370
  function shouldReapIdleThread(thread, now, suspendedMsNow, idleThreadTtlMs) {
@@ -119319,8 +119513,54 @@ async function runStartupPruneSafely(prune2, log2) {
119319
119513
  );
119320
119514
  }
119321
119515
  }
119516
+ function closeStartupHttpServer(server) {
119517
+ return new Promise((resolve3, reject) => {
119518
+ server.close((error51) => {
119519
+ if (error51 && error51.code !== "ERR_SERVER_NOT_RUNNING") reject(error51);
119520
+ else resolve3();
119521
+ });
119522
+ server.closeAllConnections();
119523
+ });
119524
+ }
119525
+ function closeStartupWebSocketServer(server) {
119526
+ return new Promise((resolve3, reject) => {
119527
+ server.close((error51) => {
119528
+ if (error51) reject(error51);
119529
+ else resolve3();
119530
+ });
119531
+ for (const socket of server.clients) socket.terminate();
119532
+ });
119533
+ }
119322
119534
  async function startDirectorBridge(startupDeps = {}) {
119323
119535
  const agentSecret = readAgentSecret();
119536
+ const staticBearer = !agentSecret && process.env.MRRLIN_BRIDGE_STATIC_OWNED_SDK === "1" ? process.env.MRRLIN_TOKEN?.trim() || readOperatorToken() || void 0 : void 0;
119537
+ const rollback = [];
119538
+ let disposeTransport;
119539
+ try {
119540
+ await startBridge(startupDeps, agentSecret, staticBearer ? { bearer: staticBearer, add: (close) => {
119541
+ rollback.push(close);
119542
+ }, transport: (close) => {
119543
+ disposeTransport = close;
119544
+ } } : void 0);
119545
+ } catch (error51) {
119546
+ const closeBounded = async (close, resource) => {
119547
+ try {
119548
+ await withTimeout2(Promise.resolve(close()), 6e3, "static_bridge_rollback_timeout");
119549
+ } catch {
119550
+ try {
119551
+ process.stderr.write(`[mrrlin-mcp director-bridge] startup rollback could not confirm owned ${resource} close
119552
+ `);
119553
+ } catch {
119554
+ }
119555
+ }
119556
+ };
119557
+ const transport = disposeTransport && closeBounded(disposeTransport, "transport");
119558
+ const resources = rollback.reverse().map((close) => closeBounded(close, "resource"));
119559
+ await Promise.allSettled([transport, ...resources]);
119560
+ throw error51;
119561
+ }
119562
+ }
119563
+ async function startBridge(startupDeps, agentSecret, startupRollback) {
119324
119564
  const scopedScheduler = process.env.MRRLIN_BRIDGE_SCOPED_SCHEDULER === "1";
119325
119565
  const compactTickFlag = process.env.MRRLIN_BRIDGE_COMPACT_SCHEDULER?.trim().toLowerCase();
119326
119566
  if (compactTickFlag && !["0", "1", "false"].includes(compactTickFlag)) {
@@ -119391,7 +119631,9 @@ async function startDirectorBridge(startupDeps = {}) {
119391
119631
  );
119392
119632
  }
119393
119633
  });
119634
+ startupRollback?.add(() => selfUpdateHandle2.stop());
119394
119635
  const codexProbeHandle2 = startCodexProbe();
119636
+ startupRollback?.add(() => codexProbeHandle2.stop());
119395
119637
  try {
119396
119638
  migrateRetiredApiBaseUrls();
119397
119639
  } catch {
@@ -119414,6 +119656,7 @@ async function startDirectorBridge(startupDeps = {}) {
119414
119656
  const ownedSdk = Boolean(agentSecret) && scopedScheduler && process.env.MRRLIN_BRIDGE_OWNED_SDK === "1";
119415
119657
  const scopedRunRead = Boolean(agentSecret) && scopedScheduler && process.env.MRRLIN_BRIDGE_SCOPED_RUN_READ === "1";
119416
119658
  const baseFetch = globalThis.fetch;
119659
+ let staticToken;
119417
119660
  let authedFetch;
119418
119661
  if (agentSecret) {
119419
119662
  const provider = createAgentTokenProvider({ secret: agentSecret, baseUrl: apiBaseUrl });
@@ -119467,7 +119710,8 @@ async function startDirectorBridge(startupDeps = {}) {
119467
119710
  else await tokenRefresher.start();
119468
119711
  process.stderr.write("[mrrlin-mcp director-bridge] agent credential active; operator token auto-refresh enabled.\n");
119469
119712
  } else {
119470
- const apiToken = envToken ?? readOperatorToken() ?? void 0;
119713
+ const apiToken = startupRollback?.bearer ?? envToken ?? readOperatorToken() ?? void 0;
119714
+ staticToken = apiToken;
119471
119715
  if (envToken) {
119472
119716
  try {
119473
119717
  persistOperatorToken(envToken);
@@ -119488,7 +119732,15 @@ async function startDirectorBridge(startupDeps = {}) {
119488
119732
  return baseFetch(input, { ...init, headers });
119489
119733
  };
119490
119734
  }
119491
- const hasStaticToken = !agentSecret && Boolean(envToken ?? readOperatorToken());
119735
+ const hasStaticToken = !agentSecret && Boolean(startupRollback ? staticToken : envToken ?? readOperatorToken());
119736
+ const staticTransport = startupRollback && staticToken ? createOwnedApiTransport({ apiBaseUrl, readBearer: async () => ({ token: staticToken }) }, { deferStart: true }) : void 0;
119737
+ let staticDisposal;
119738
+ const stopStaticTransport = staticTransport ? () => staticDisposal ??= (async () => {
119739
+ const result = await withTimeout2(staticTransport.dispose(), 6e3, "static_sdk_close_timeout");
119740
+ if (result !== "closed") process.stderr.write("[mrrlin-mcp director-bridge] owned transport close was not confirmed\n");
119741
+ })() : void 0;
119742
+ if (stopStaticTransport) startupRollback?.transport(stopStaticTransport);
119743
+ staticTransport?.start();
119492
119744
  const hostArtifactPayloads = (client2, signal, assertActive) => {
119493
119745
  const appendExecutionArtifact = client2.appendExecutionArtifact.bind(client2);
119494
119746
  const withExecutionAuthority = client2.withExecutionAuthority?.bind(client2);
@@ -119518,7 +119770,7 @@ async function startDirectorBridge(startupDeps = {}) {
119518
119770
  timeoutMs: DEFAULT_OPERATION_TIMEOUT_MS
119519
119771
  }) : () => {
119520
119772
  throw new Error("BRIDGE_SDK_TRANSPORT_START_FAILED");
119521
- } : void 0;
119773
+ } : staticTransport?.createOperation;
119522
119774
  const client = hostArtifactPayloads(createMrrlinClient({ baseUrl: apiBaseUrl, fetch: authedFetch, createOperation }));
119523
119775
  if (scopedRunRead && !ownedSdk) {
119524
119776
  const scope = schedulerScope;
@@ -119558,11 +119810,13 @@ async function startDirectorBridge(startupDeps = {}) {
119558
119810
  }
119559
119811
  const { selfUpdateHandle, codexProbeHandle } = legacyBackgroundServices ?? startBackgroundServices();
119560
119812
  const artifactsGc = startArtifactsGc(config2.stateDir);
119813
+ startupRollback?.add(() => artifactsGc.stop());
119561
119814
  const agentKeepalive = createAgentKeepalive({
119562
119815
  acquire: (providerId) => resolveProvider(process.env, providerId).acquireWarm(),
119563
119816
  release: (providerId) => resolveProvider(process.env, providerId).releaseWarm(),
119564
119817
  idleMs: (providerId) => agentIdleMs(providerId)
119565
119818
  });
119819
+ startupRollback?.add(() => agentKeepalive.dropNow());
119566
119820
  const checkoutRegistry = new CheckoutRegistry(config2.stateDir);
119567
119821
  const connectionStore = new LocalConnectionStore(config2.stateDir);
119568
119822
  const installInfo = connectionStore.getInstallationInfo();
@@ -119784,6 +120038,12 @@ async function startDirectorBridge(startupDeps = {}) {
119784
120038
  };
119785
120039
  const driveRunNow = driveTracked;
119786
120040
  const asyncShutdown = progressExecution ? new AbortController() : void 0;
120041
+ startupRollback?.add(() => {
120042
+ executionStopping = true;
120043
+ asyncShutdown?.abort();
120044
+ reportShutdown?.abort();
120045
+ for (const controller of activeDrives.keys()) controller.abort();
120046
+ });
119787
120047
  const driveAsyncTracked = (slug, jobId) => {
119788
120048
  if (asyncShutdown?.signal.aborted) return;
119789
120049
  void driveAsyncJob(asyncConsumerDeps, slug, jobId, asyncShutdown?.signal).catch((error51) => {
@@ -119811,7 +120071,9 @@ async function startDirectorBridge(startupDeps = {}) {
119811
120071
  })
119812
120072
  );
119813
120073
  const threads = /* @__PURE__ */ new Map();
120074
+ startupRollback?.add(() => closeStartupHttpServer(server));
119814
120075
  const suspensionDetector = createSuspensionDetector();
120076
+ startupRollback?.add(() => suspensionDetector.dispose());
119815
120077
  resumableCountHolder.fn = () => {
119816
120078
  const now = Date.now();
119817
120079
  const suspended = suspensionDetector.suspendedMs();
@@ -119892,6 +120154,7 @@ async function startDirectorBridge(startupDeps = {}) {
119892
120154
  if (reaped.length > 0 || evicted.length > 0) persistThreads();
119893
120155
  }, 6e4);
119894
120156
  cleanupTimer.unref?.();
120157
+ startupRollback?.add(() => clearInterval(cleanupTimer));
119895
120158
  let remoteRelay = null;
119896
120159
  const relayUrl = process.env.MRRLIN_RELAY_URL?.trim();
119897
120160
  const relayConfigured = Boolean(agentSecret && relayUrl);
@@ -120022,31 +120285,34 @@ async function startDirectorBridge(startupDeps = {}) {
120022
120285
  snapshotProjectObjects: async (projectSlug, opts) => {
120023
120286
  const signal = opts?.signal;
120024
120287
  if (signal?.aborted) throw new Error("snapshot aborted");
120025
- const tasks = await client.listTasks(
120026
- projectSlug,
120027
- { archived: "all", limit: CLOSURE_MAX_SNAPSHOT_TASKS + 1 },
120028
- { view: "summary", signal }
120029
- );
120030
- if (tasks.length > CLOSURE_MAX_SNAPSHOT_TASKS) {
120031
- throw new Error(`${tasks.length} tasks exceed the closure snapshot cap (${CLOSURE_MAX_SNAPSHOT_TASKS})`);
120032
- }
120033
- const [pages, inbox] = await Promise.all([
120034
- client.listWikiPages(
120035
- projectSlug,
120036
- { folder: "Specs", limit: CLOSURE_MAX_SNAPSHOT_PAGES + 1 },
120037
- { view: "summary", signal }
120038
- ),
120039
- client.listInboxItems(
120288
+ const snapshot = async () => {
120289
+ const tasks = await client.listTasks(
120040
120290
  projectSlug,
120041
- { status: "pending", limit: CLOSURE_MAX_SNAPSHOT_INBOX + 1 },
120291
+ { archived: "all", limit: CLOSURE_MAX_SNAPSHOT_TASKS + 1 },
120042
120292
  { view: "summary", signal }
120043
- )
120044
- ]);
120045
- return {
120046
- inbox: inbox.length > CLOSURE_MAX_SNAPSHOT_INBOX ? null : new Set(inbox.map((item) => item.id)),
120047
- tasks: new Map(tasks.map((task) => [task.id, { title: task.title, updatedAt: task.updatedAt ?? null }])),
120048
- pages: pages.length > CLOSURE_MAX_SNAPSHOT_PAGES ? null : new Map(pages.map((page) => [page.id, { title: page.title, updatedAt: page.updatedAt }]))
120293
+ );
120294
+ if (tasks.length > CLOSURE_MAX_SNAPSHOT_TASKS) {
120295
+ throw new Error(`${tasks.length} tasks exceed the closure snapshot cap (${CLOSURE_MAX_SNAPSHOT_TASKS})`);
120296
+ }
120297
+ const [pages, inbox] = await Promise.all([
120298
+ client.listWikiPages(
120299
+ projectSlug,
120300
+ { folder: "Specs", limit: CLOSURE_MAX_SNAPSHOT_PAGES + 1 },
120301
+ { view: "summary", signal }
120302
+ ),
120303
+ client.listInboxItems(
120304
+ projectSlug,
120305
+ { status: "pending", limit: CLOSURE_MAX_SNAPSHOT_INBOX + 1 },
120306
+ { view: "summary", signal }
120307
+ )
120308
+ ]);
120309
+ return {
120310
+ inbox: inbox.length > CLOSURE_MAX_SNAPSHOT_INBOX ? null : new Set(inbox.map((item) => item.id)),
120311
+ tasks: new Map(tasks.map((task) => [task.id, { title: task.title, updatedAt: task.updatedAt ?? null }])),
120312
+ pages: pages.length > CLOSURE_MAX_SNAPSHOT_PAGES ? null : new Map(pages.map((page) => [page.id, { title: page.title, updatedAt: page.updatedAt }]))
120313
+ };
120049
120314
  };
120315
+ return staticTransport ? staticTransport.runWithinDeadline(signal, 1500, snapshot) : snapshot();
120050
120316
  },
120051
120317
  getProject: (projectSlug) => client.getProject(projectSlug),
120052
120318
  // Compaction runner for `compact-request` (agent-seat-surfaces task 2.5). Closes over `config`
@@ -120069,7 +120335,7 @@ async function startDirectorBridge(startupDeps = {}) {
120069
120335
  bridgeBinShaShort = import_node_crypto30.default.createHash("sha256").update(import_node_fs34.default.readFileSync(process.argv[1] ?? "")).digest("hex").slice(0, 12);
120070
120336
  } catch {
120071
120337
  }
120072
- attachBridgeWss(server, {
120338
+ const bridgeWss = attachBridgeWss(server, {
120073
120339
  token: config2.token,
120074
120340
  allowedOrigins: config2.allowedOrigins,
120075
120341
  host: config2.host,
@@ -120095,6 +120361,23 @@ async function startDirectorBridge(startupDeps = {}) {
120095
120361
  getUpdateCommand: () => codexProbeHandle.getUpdateCommand()
120096
120362
  }
120097
120363
  });
120364
+ let bridgeListening = false;
120365
+ let startupWebSocketError;
120366
+ let rejectWebSocketStartup;
120367
+ if (staticTransport) {
120368
+ bridgeWss.on("error", (error51) => {
120369
+ if (!bridgeListening) {
120370
+ startupWebSocketError ??= error51;
120371
+ rejectWebSocketStartup?.(startupWebSocketError);
120372
+ return;
120373
+ }
120374
+ try {
120375
+ process.stderr.write("[mrrlin-mcp director-bridge] owned WebSocket listener reported an error\n");
120376
+ } catch {
120377
+ }
120378
+ });
120379
+ }
120380
+ startupRollback?.add(() => closeStartupWebSocketServer(bridgeWss));
120098
120381
  if (agentSecret && relayUrl) {
120099
120382
  const getRelaySession = schedulerScope && schedulerGenerations && tokenProvider ? createScopedSession({
120100
120383
  scope: schedulerScope,
@@ -120152,6 +120435,7 @@ async function startDirectorBridge(startupDeps = {}) {
120152
120435
  const dispatchServer = import_node_http5.default.createServer(
120153
120436
  createWorkerDispatchListener(workerToken, driveRunNow, driveAsyncNow, asyncShutdown?.signal)
120154
120437
  );
120438
+ startupRollback?.add(() => closeStartupHttpServer(dispatchServer));
120155
120439
  await new Promise((resolve3, reject) => {
120156
120440
  dispatchServer.on("error", reject);
120157
120441
  dispatchServer.listen(workerPort(), "127.0.0.1", () => resolve3());
@@ -120160,6 +120444,7 @@ async function startDirectorBridge(startupDeps = {}) {
120160
120444
  stateDir: config2.stateDir,
120161
120445
  hasLiveTurn: () => wrappedTurnLock.activeCount() > 0 || (resumableCountHolder.fn?.() ?? 0) > 0
120162
120446
  });
120447
+ startupRollback?.add(() => bridgeHealth.dispose());
120163
120448
  const runTrackedSweep = async (id, label, fn) => {
120164
120449
  try {
120165
120450
  await fn();
@@ -120176,6 +120461,10 @@ async function startDirectorBridge(startupDeps = {}) {
120176
120461
  };
120177
120462
  let claimLoopStopped = false;
120178
120463
  let claimTimer = null;
120464
+ startupRollback?.add(() => {
120465
+ claimLoopStopped = true;
120466
+ if (claimTimer) clearTimeout(claimTimer);
120467
+ });
120179
120468
  const scheduleClaimLoop = () => {
120180
120469
  if (claimLoopStopped) return;
120181
120470
  claimTimer = setTimeout(() => {
@@ -120330,6 +120619,7 @@ async function startDirectorBridge(startupDeps = {}) {
120330
120619
  else driveAsyncNow(projectSlug, work.jobId);
120331
120620
  }
120332
120621
  });
120622
+ startupRollback?.add(() => schedulerTickHandle?.stop());
120333
120623
  } else if (!tokenProvider) {
120334
120624
  process.stderr.write(
120335
120625
  "[mrrlin-mcp director-bridge] no durable agent credential; skipping bridge scheduler tick loop.\n"
@@ -120345,6 +120635,9 @@ async function startDirectorBridge(startupDeps = {}) {
120345
120635
  void refresh();
120346
120636
  selectedProviderTimer = setInterval(() => void refresh(), 6e4);
120347
120637
  selectedProviderTimer.unref?.();
120638
+ startupRollback?.add(() => {
120639
+ if (selectedProviderTimer) clearInterval(selectedProviderTimer);
120640
+ });
120348
120641
  }
120349
120642
  await runStartupPruneSafely(
120350
120643
  startupDeps.pruneExternalAgentsAtStartup ?? runExternalAgentsPruneAtStartup,
@@ -120359,8 +120652,14 @@ async function startDirectorBridge(startupDeps = {}) {
120359
120652
  suppressedPushLine("provider-readiness push", err)
120360
120653
  )
120361
120654
  });
120655
+ startupRollback?.add(() => providerReadinessLoopHandle?.stop());
120362
120656
  }
120363
120657
  await new Promise((resolve3, reject) => {
120658
+ if (startupWebSocketError) {
120659
+ reject(startupWebSocketError);
120660
+ return;
120661
+ }
120662
+ rejectWebSocketStartup = reject;
120364
120663
  server.on("error", (err) => {
120365
120664
  if (err.code === "EADDRINUSE") {
120366
120665
  const conflictingPids = scanForOtherBridges();
@@ -120372,11 +120671,15 @@ async function startDirectorBridge(startupDeps = {}) {
120372
120671
  })}
120373
120672
  `
120374
120673
  );
120375
- process.exit(1);
120674
+ if (!staticTransport) process.exit(1);
120376
120675
  }
120377
120676
  reject(err);
120378
120677
  });
120379
- server.listen(config2.port, config2.host, () => resolve3());
120678
+ server.listen(config2.port, config2.host, () => {
120679
+ bridgeListening = true;
120680
+ rejectWebSocketStartup = void 0;
120681
+ resolve3();
120682
+ });
120380
120683
  });
120381
120684
  const orphans = scanForOtherBridges();
120382
120685
  if (orphans.length > 0) {
@@ -120416,6 +120719,7 @@ async function startDirectorBridge(startupDeps = {}) {
120416
120719
  () => artifactsGc.stop()
120417
120720
  ],
120418
120721
  shutdownCodex: () => codexServerManager.shutdown(),
120722
+ stopTransport: stopStaticTransport,
120419
120723
  ...progressExecution || reportDelivery || compactHeartbeat ? { stopExecution: async () => {
120420
120724
  executionStopping = true;
120421
120725
  compactHeartbeatShutdown?.abort();
@@ -120429,10 +120733,14 @@ async function startDirectorBridge(startupDeps = {}) {
120429
120733
  `)
120430
120734
  });
120431
120735
  const shutdown = shutdownHolder.fn;
120736
+ const requestDrain = () => selfUpdateHandle.requestDrain();
120432
120737
  process.on("SIGTERM", shutdown);
120433
120738
  process.on("SIGINT", shutdown);
120434
- process.on("SIGUSR2", () => {
120435
- selfUpdateHandle.requestDrain();
120739
+ process.on("SIGUSR2", requestDrain);
120740
+ startupRollback?.add(() => {
120741
+ process.off("SIGTERM", shutdown);
120742
+ process.off("SIGINT", shutdown);
120743
+ process.off("SIGUSR2", requestDrain);
120436
120744
  });
120437
120745
  startupDeps.onApiClientReady?.(client);
120438
120746
  process.stderr.write(`[mrrlin-mcp director-bridge] listening on http://${config2.host}:${config2.port} (ws://${config2.host}:${config2.port}/ws)
@@ -121865,27 +122173,14 @@ function assertToolContractCoverage(publicNames, registry3, schemaMap, toolMap)
121865
122173
  }
121866
122174
 
121867
122175
  // src/stdio-owned-transport.ts
121868
- var import_node_async_hooks = require("node:async_hooks");
121869
- var import_node_events9 = require("node:events");
121870
122176
  var import_node_fs35 = require("node:fs");
121871
122177
  var import_promises25 = require("node:fs/promises");
121872
122178
  var TOKEN_LIMIT = 32 * 1024;
121873
- var LOGICAL_LIMIT = 20;
121874
- var HTTP_METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"];
121875
- var StdioLocalError = class extends Error {
121876
- };
121877
- function parseUrl(value) {
121878
- try {
121879
- return new URL(value);
121880
- } catch {
121881
- throw new StdioLocalError("STDIO_UNSUPPORTED_REQUEST");
121882
- }
121883
- }
121884
122179
  async function readCredential(path40) {
121885
- if (process.platform === "win32") throw new StdioLocalError("STDIO_CREDENTIAL_FILE_PLATFORM_UNVERIFIED");
122180
+ if (process.platform === "win32") throw new Error("STDIO_CREDENTIAL_FILE_PLATFORM_UNVERIFIED");
121886
122181
  const handle = await (0, import_promises25.open)(path40, import_node_fs35.constants.O_RDONLY | import_node_fs35.constants.O_NONBLOCK);
121887
122182
  try {
121888
- if (!(await handle.stat()).isFile()) throw new StdioLocalError("STDIO_CREDENTIAL_NOT_REGULAR");
122183
+ if (!(await handle.stat()).isFile()) throw new Error("STDIO_CREDENTIAL_NOT_REGULAR");
121889
122184
  const bytes3 = Buffer.alloc(TOKEN_LIMIT + 1);
121890
122185
  let count2 = 0;
121891
122186
  while (count2 < bytes3.length) {
@@ -121893,7 +122188,7 @@ async function readCredential(path40) {
121893
122188
  if (result.bytesRead === 0) break;
121894
122189
  count2 += result.bytesRead;
121895
122190
  }
121896
- if (count2 > TOKEN_LIMIT) throw new StdioLocalError("STDIO_CREDENTIAL_TOO_LARGE");
122191
+ if (count2 > TOKEN_LIMIT) throw new Error("STDIO_CREDENTIAL_TOO_LARGE");
121897
122192
  return new TextDecoder("utf-8", { fatal: true }).decode(bytes3.subarray(0, count2)).trim() || void 0;
121898
122193
  } finally {
121899
122194
  await handle.close();
@@ -121902,9 +122197,9 @@ async function readCredential(path40) {
121902
122197
  async function resolveBearer(explicitToken) {
121903
122198
  const file2 = process.env.MRRLIN_EXECUTOR_BEARER_FILE;
121904
122199
  if (isExecutorThread() && (file2 || process.env.MRRLIN_EXECUTOR_RUN_ID || process.env.MRRLIN_EXECUTOR_LEASE_ID || process.env.MRRLIN_F54_PROGRESS_LEASE === "1")) {
121905
- if (!file2) throw new StdioLocalError("STDIO_EXECUTOR_CREDENTIAL_UNAVAILABLE");
122200
+ if (!file2) throw new Error("STDIO_EXECUTOR_CREDENTIAL_UNAVAILABLE");
121906
122201
  const token = await readCredential(file2);
121907
- if (!token?.startsWith("mrrlin_executor_v1.")) throw new StdioLocalError("STDIO_EXECUTOR_CREDENTIAL_UNAVAILABLE");
122202
+ if (!token?.startsWith("mrrlin_executor_v1.")) throw new Error("STDIO_EXECUTOR_CREDENTIAL_UNAVAILABLE");
121908
122203
  return { token, executor: true };
121909
122204
  }
121910
122205
  const configured = explicitToken ?? process.env.MRRLIN_TOKEN;
@@ -121916,148 +122211,8 @@ async function resolveBearer(explicitToken) {
121916
122211
  throw error51;
121917
122212
  }
121918
122213
  }
121919
- async function untilCanceled(pending, signal) {
121920
- if (signal.aborted) {
121921
- void pending.catch(() => {
121922
- });
121923
- signal.throwIfAborted();
121924
- }
121925
- let subscription;
121926
- try {
121927
- return await Promise.race([pending, new Promise((_, reject) => {
121928
- subscription = (0, import_node_events9.addAbortListener)(signal, () => reject(signal.reason));
121929
- })]);
121930
- } finally {
121931
- subscription?.[Symbol.dispose]();
121932
- }
121933
- }
121934
- function boundedResponse(response, relativePath) {
121935
- if (!response.body) return response;
121936
- const artifact = /^\/projects\/[^/]+\/artifact-files\/[^/]+\/content$/u.test(relativePath);
121937
- const limit = !response.ok ? 64 * 1024 : artifact ? MRRLIN_ARTIFACT_INLINE_MAX_BYTES : 8 * 1024 * 1024;
121938
- let size = 0;
121939
- const body = response.body.pipeThrough(new TransformStream({
121940
- transform(chunk, controller) {
121941
- size += chunk.byteLength;
121942
- if (size > limit) throw new MrrlinResponseTooLargeError(limit);
121943
- controller.enqueue(chunk);
121944
- }
121945
- }));
121946
- const bounded = new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
121947
- return new Proxy(bounded, {
121948
- get(target, key) {
121949
- if (key === "url") return response.url;
121950
- const value = Reflect.get(target, key, target);
121951
- return typeof value === "function" ? value.bind(target) : value;
121952
- }
121953
- });
121954
- }
121955
- function createStdioOwnedTransport(options, dependencies = {}) {
121956
- const base = parseUrl(options.apiBaseUrl);
121957
- if (!["http:", "https:"].includes(base.protocol) || base.username || base.password || base.hash || base.search) {
121958
- throw new StdioLocalError("STDIO_INVALID_API_BASE");
121959
- }
121960
- const prefix = base.pathname.replace(/\/$/u, "");
121961
- const generations = new BridgeGenerationManager(base.origin, { ownedOrdinary: true });
121962
- const scope = new BridgeOperationScope(generations);
121963
- const attempts = new BridgeHttpAdmission({ limits: {
121964
- ordinary: { active: 4, waiting: 16 },
121965
- heartbeat: { active: 1, waiting: 0 },
121966
- scheduler: { active: 1, waiting: 0 },
121967
- refresh: { active: 1, waiting: 0 }
121968
- } });
121969
- const stream = createOwnedStreamingFetch(scope, base.origin);
121970
- const shutdown = new AbortController();
121971
- const invocations = new import_node_async_hooks.AsyncLocalStorage();
121972
- const readBearer = dependencies.readBearer ?? resolveBearer;
121973
- let logical = 0;
121974
- generations.start();
121975
- const createOperation = () => {
121976
- if (shutdown.signal.aborted) throw new StdioLocalError("STDIO_TRANSPORT_CLOSED");
121977
- const invocation = invocations.getStore();
121978
- invocation?.throwIfAborted();
121979
- if (logical >= LOGICAL_LIMIT) throw new StdioLocalError("STDIO_LOGICAL_OVERLOAD");
121980
- logical++;
121981
- const timeoutMs = dependencies.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
121982
- const deadlineAt = performance.now() + timeoutMs;
121983
- const deadlineSignal = AbortSignal.timeout(timeoutMs);
121984
- const signals = invocation ? [deadlineSignal, shutdown.signal, invocation] : [deadlineSignal, shutdown.signal];
121985
- const signal = AbortSignal.any(signals);
121986
- let closed = false;
121987
- return {
121988
- signal,
121989
- deadlineAt,
121990
- deadlineSignal,
121991
- close() {
121992
- if (!closed) {
121993
- closed = true;
121994
- logical--;
121995
- }
121996
- },
121997
- shouldRetryError: (error51) => !(error51 instanceof StdioLocalError || error51 instanceof BridgeAdmissionError),
121998
- fetch: async (input, init) => {
121999
- if (typeof input !== "string") throw new StdioLocalError("STDIO_UNSUPPORTED_REQUEST");
122000
- const url2 = parseUrl(input);
122001
- const method = (init?.method ?? "GET").toUpperCase();
122002
- const body = init?.body;
122003
- if (url2.origin !== base.origin || url2.username || url2.password || url2.hash || !url2.pathname.startsWith(prefix + "/") || /%2f|%5c/iu.test(url2.pathname) || !HTTP_METHODS.includes(method) || body != null && (!(typeof body === "string" || body instanceof Uint8Array) || method === "GET" || method === "HEAD")) {
122004
- throw new StdioLocalError("STDIO_UNSUPPORTED_REQUEST");
122005
- }
122006
- const attemptSignal = init?.signal ? AbortSignal.any([init.signal, signal]) : signal;
122007
- const admission = attempts.acquire("ordinary", { signal: attemptSignal, deadline: deadlineAt });
122008
- if (dependencies.onAttemptQueued) {
122009
- const { waiting } = attempts.counts("ordinary");
122010
- if (waiting > 0) dependencies.onAttemptQueued(waiting);
122011
- }
122012
- const permit = await admission;
122013
- const pending = (async () => {
122014
- let dispatched = false;
122015
- try {
122016
- attemptSignal.throwIfAborted();
122017
- const headers = new Headers(init?.headers);
122018
- try {
122019
- const { token, executor } = await readBearer(options.token);
122020
- if (token && (executor || !headers.has("authorization"))) headers.set("authorization", "Bearer " + token);
122021
- } catch {
122022
- throw new StdioLocalError("STDIO_CREDENTIAL_UNAVAILABLE");
122023
- }
122024
- attemptSignal.throwIfAborted();
122025
- if (performance.now() >= deadlineAt) throw new DOMException("Request expired", "AbortError");
122026
- dispatched = true;
122027
- const response = await stream({
122028
- url: url2.href,
122029
- method,
122030
- body: body ?? void 0,
122031
- headers: Object.fromEntries(headers),
122032
- deadlineAt,
122033
- deadlineSignal,
122034
- signal: attemptSignal,
122035
- rotateOnHeaderTimeout: generations,
122036
- onReleased: permit.release,
122037
- onGeneration: dependencies.onGeneration,
122038
- rejectRedirect: () => new StdioLocalError("STDIO_REDIRECT_REFUSED")
122039
- });
122040
- return boundedResponse(response, url2.pathname.slice(prefix.length));
122041
- } finally {
122042
- if (!dispatched) permit.release();
122043
- }
122044
- })();
122045
- return untilCanceled(pending, attemptSignal);
122046
- }
122047
- };
122048
- };
122049
- return {
122050
- createOperation,
122051
- runInvocation(signal, invoke2) {
122052
- return invocations.run(signal, invoke2);
122053
- },
122054
- dispose() {
122055
- shutdown.abort(new DOMException("Stdio transport closed", "AbortError"));
122056
- attempts.dispose();
122057
- scope.dispose();
122058
- return generations.dispose();
122059
- }
122060
- };
122214
+ function createStdioOwnedTransport(options, { readBearer = resolveBearer, ...dependencies } = {}) {
122215
+ return createOwnedApiTransport({ apiBaseUrl: options.apiBaseUrl, readBearer: () => readBearer(options.token) }, dependencies);
122061
122216
  }
122062
122217
 
122063
122218
  // src/server.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrrlin-dev/mcp",
3
- "version": "0.4.217",
3
+ "version": "0.4.218",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "mrrlin-mcp": "dist/bin.cjs"