replicas-engine 0.1.964 → 0.1.965

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/src/index.js CHANGED
@@ -32,7 +32,7 @@ import {
32
32
  reportCommandProtectionBlock,
33
33
  resolveDiffBase,
34
34
  runGitCommand
35
- } from "./chunk-3NDASIOV.js";
35
+ } from "./chunk-SLRHEFTS.js";
36
36
  import {
37
37
  ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
38
38
  AGENT_MESSAGE_DELTA_METHOD,
@@ -56,7 +56,7 @@ import {
56
56
  } from "./chunk-UPCC4BX5.js";
57
57
  import {
58
58
  publishedPullRequestUrls
59
- } from "./chunk-N6JCCYO3.js";
59
+ } from "./chunk-YDKFWJY7.js";
60
60
  import {
61
61
  BaseRefreshManager,
62
62
  CodexAspAuthMethodChangedError,
@@ -71,7 +71,7 @@ import {
71
71
  refreshDelayMs,
72
72
  restartCodexAspHost,
73
73
  routineRefreshExclusions
74
- } from "./chunk-5M2ZF4NX.js";
74
+ } from "./chunk-MEVE5U5A.js";
75
75
  import {
76
76
  ENGINE_ENV,
77
77
  monolithRequest,
@@ -79,16 +79,16 @@ import {
79
79
  readRuntimeEnvFile,
80
80
  reloadEngineEnv,
81
81
  setAgentCredentialSnapshot
82
- } from "./chunk-3ZBHY2YI.js";
82
+ } from "./chunk-ACUYRC4H.js";
83
83
  import {
84
84
  AspClient,
85
85
  getCodexModelProvider
86
- } from "./chunk-TDVZOQMQ.js";
86
+ } from "./chunk-AOF42AV2.js";
87
87
  import {
88
88
  SUBPROCESS_MAX_BUFFER,
89
89
  execAsync,
90
90
  execFileAsync
91
- } from "./chunk-33CDUZ6W.js";
91
+ } from "./chunk-TP5NFRFE.js";
92
92
  import {
93
93
  isRecord as isRecord2
94
94
  } from "./chunk-UZSNFLDQ.js";
@@ -179,6 +179,7 @@ import {
179
179
  SUBAGENT_MCP_SERVER_NAME,
180
180
  SUBAGENT_MCP_TOOLS,
181
181
  SUBAGENT_MCP_TOOL_NAMES,
182
+ TERMINAL_RTC_ICE_SERVER,
182
183
  TIMEOUT,
183
184
  TOKEN_USAGE_PATH,
184
185
  TaskAccumulator,
@@ -318,7 +319,7 @@ import {
318
319
  workspaceCredentialProviderSchema,
319
320
  workspaceTokenRequestSchema,
320
321
  workspaceTokenResponseSchema
321
- } from "./chunk-MEN62XEB.js";
322
+ } from "./chunk-BYJ6CIME.js";
322
323
  import {
323
324
  cloneMcpConfig,
324
325
  ensureCompatibilityImports,
@@ -776,7 +777,7 @@ var require_parse = __commonJS({
776
777
  }
777
778
  return parsed;
778
779
  }
779
- function parse(command, args, options) {
780
+ function parse2(command, args, options) {
780
781
  if (args && !Array.isArray(args)) {
781
782
  options = args;
782
783
  args = null;
@@ -795,7 +796,7 @@ var require_parse = __commonJS({
795
796
  };
796
797
  return options.shell ? parsed : parseNonShell(parsed);
797
798
  }
798
- module.exports = parse;
799
+ module.exports = parse2;
799
800
  }
800
801
  });
801
802
 
@@ -854,16 +855,16 @@ var require_cross_spawn = __commonJS({
854
855
  "../node_modules/.bun/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(exports, module) {
855
856
  "use strict";
856
857
  var cp2 = __require("child_process");
857
- var parse = require_parse();
858
+ var parse2 = require_parse();
858
859
  var enoent = require_enoent();
859
860
  function spawn9(command, args, options) {
860
- const parsed = parse(command, args, options);
861
+ const parsed = parse2(command, args, options);
861
862
  const spawned = cp2.spawn(parsed.command, parsed.args, parsed.options);
862
863
  enoent.hookChildProcess(spawned, parsed);
863
864
  return spawned;
864
865
  }
865
866
  function spawnSync3(command, args, options) {
866
- const parsed = parse(command, args, options);
867
+ const parsed = parse2(command, args, options);
867
868
  const result = cp2.spawnSync(parsed.command, parsed.args, parsed.options);
868
869
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
869
870
  return result;
@@ -871,7 +872,7 @@ var require_cross_spawn = __commonJS({
871
872
  module.exports = spawn9;
872
873
  module.exports.spawn = spawn9;
873
874
  module.exports.sync = spawnSync3;
874
- module.exports._parse = parse;
875
+ module.exports._parse = parse2;
875
876
  module.exports._enoent = enoent;
876
877
  }
877
878
  });
@@ -4481,21 +4482,21 @@ var require_fast_uri2 = __commonJS({
4481
4482
  normalizeString(uri, options);
4482
4483
  } else if (typeof uri === "object") {
4483
4484
  uri = /** @type {T} */
4484
- parse(serialize(uri, options), options);
4485
+ parse2(serialize(uri, options), options);
4485
4486
  }
4486
4487
  return uri;
4487
4488
  }
4488
4489
  function resolve7(baseURI, relativeURI, options) {
4489
4490
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
4490
- const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
4491
+ const resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true);
4491
4492
  schemelessOptions.skipEscape = true;
4492
4493
  return serialize(resolved, schemelessOptions);
4493
4494
  }
4494
4495
  function resolveComponent(base, relative3, options, skipNormalization) {
4495
4496
  const target = {};
4496
4497
  if (!skipNormalization) {
4497
- base = parse(serialize(base, options), options);
4498
- relative3 = parse(serialize(relative3, options), options);
4498
+ base = parse2(serialize(base, options), options);
4499
+ relative3 = parse2(serialize(relative3, options), options);
4499
4500
  }
4500
4501
  options = options || {};
4501
4502
  if (!options.tolerant && relative3.scheme) {
@@ -4718,7 +4719,7 @@ var require_fast_uri2 = __commonJS({
4718
4719
  }
4719
4720
  return { parsed, malformedAuthorityOrPort };
4720
4721
  }
4721
- function parse(uri, opts) {
4722
+ function parse2(uri, opts) {
4722
4723
  return parseWithStatus(uri, opts).parsed;
4723
4724
  }
4724
4725
  function normalizeString(uri, opts) {
@@ -4747,7 +4748,7 @@ var require_fast_uri2 = __commonJS({
4747
4748
  resolveComponent,
4748
4749
  equal,
4749
4750
  serialize,
4750
- parse
4751
+ parse: parse2
4751
4752
  };
4752
4753
  module.exports = fastUri;
4753
4754
  module.exports.default = fastUri;
@@ -8561,6 +8562,7 @@ import { serve } from "@hono/node-server";
8561
8562
  import { Hono as Hono2 } from "hono";
8562
8563
  import { randomUUID as randomUUID13 } from "crypto";
8563
8564
  import { connect } from "net";
8565
+ import { WebSocketServer } from "ws";
8564
8566
 
8565
8567
  // src/managers/github-token-manager.ts
8566
8568
  import path from "path";
@@ -17754,20 +17756,20 @@ var OpencodeManager = class extends CodingAgentManager {
17754
17756
  }
17755
17757
  };
17756
17758
  }
17757
- const server2 = await createOpencodeServer({
17759
+ const server3 = await createOpencodeServer({
17758
17760
  port: 0,
17759
17761
  timeout: OPENCODE_SERVER_STARTUP_TIMEOUT_MS,
17760
17762
  config
17761
17763
  });
17762
17764
  const client = createOpencodeClient({
17763
- baseUrl: server2.url,
17765
+ baseUrl: server3.url,
17764
17766
  fetch: opencodeFetch,
17765
17767
  headers: {
17766
17768
  Authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`
17767
17769
  }
17768
17770
  });
17769
17771
  this.client = client;
17770
- this.server = server2;
17772
+ this.server = server3;
17771
17773
  this.serverSubagentMcpParentChatId = subagentMcpParentChatId;
17772
17774
  this.configuredModels = new Set(providerModels);
17773
17775
  const eventController = new AbortController();
@@ -22718,11 +22720,11 @@ var ResourceParseError = class extends McpUiError {
22718
22720
  };
22719
22721
  var ConsentError = class extends McpUiError {
22720
22722
  denied;
22721
- constructor(server2, options) {
22722
- const message = options.denied ? `Tool calls for "${server2}" were denied for this session` : `Tool call approval required for "${server2}"`;
22723
+ constructor(server3, options) {
22724
+ const message = options.denied ? `Tool calls for "${server3}" were denied for this session` : `Tool call approval required for "${server3}"`;
22723
22725
  super(message, {
22724
22726
  code: options.denied ? "CONSENT_DENIED" : "CONSENT_REQUIRED",
22725
- context: { server: server2 },
22727
+ context: { server: server3 },
22726
22728
  recoveryHint: options.denied ? "The user denied tool access. Start a new session to try again." : "Prompt the user for consent before calling tools."
22727
22729
  });
22728
22730
  this.name = "ConsentError";
@@ -22785,13 +22787,13 @@ function findEmbeddedInputRequest(error) {
22785
22787
  const inputKey = boundedText(details?.inputKey, MAX_INPUT_REQUIRED_DETAIL_LENGTH);
22786
22788
  const inputMethod = boundedText(details?.inputMethod, MAX_INPUT_REQUIRED_DETAIL_LENGTH);
22787
22789
  if (inputKey && inputMethod && INPUT_REQUIRED_METHODS.has(inputMethod)) {
22788
- const server2 = boundedText(details?.server, MAX_INPUT_REQUIRED_SERVER_LENGTH);
22790
+ const server3 = boundedText(details?.server, MAX_INPUT_REQUIRED_SERVER_LENGTH);
22789
22791
  const tool = boundedText(details?.tool, MAX_INPUT_REQUIRED_TARGET_LENGTH);
22790
22792
  const resourceUri = boundedText(details?.resourceUri, MAX_INPUT_REQUIRED_TARGET_LENGTH);
22791
22793
  return {
22792
22794
  inputKey,
22793
22795
  inputMethod,
22794
- ...server2 ? { server: server2 } : {},
22796
+ ...server3 ? { server: server3 } : {},
22795
22797
  ...tool ? { tool } : {},
22796
22798
  ...resourceUri ? { resourceUri } : {}
22797
22799
  };
@@ -22812,15 +22814,15 @@ function findEmbeddedInputRequest(error) {
22812
22814
  function getInputRequiredNeedsUiDetails(error, identity) {
22813
22815
  const request = findEmbeddedInputRequest(error);
22814
22816
  if (!request) return void 0;
22815
- const server2 = boundedText(request.server ?? identity.server, MAX_INPUT_REQUIRED_SERVER_LENGTH) ?? "unknown";
22817
+ const server3 = boundedText(request.server ?? identity.server, MAX_INPUT_REQUIRED_SERVER_LENGTH) ?? "unknown";
22816
22818
  const tool = boundedText(request.tool ?? identity.tool, MAX_INPUT_REQUIRED_TARGET_LENGTH);
22817
22819
  const resourceUri = boundedText(request.resourceUri ?? identity.resourceUri, MAX_INPUT_REQUIRED_TARGET_LENGTH);
22818
22820
  const target = resourceUri ? `read resource "${resourceUri}"` : tool ? `call tool "${tool}"` : "complete the MCP request";
22819
22821
  const guidance = request.inputMethod === "elicitation/create" ? "Run this call in an interactive Pi session with elicitation enabled, then retry." : "Run this call in an interactive Pi session with the required MCP capability enabled, then retry.";
22820
- const message = `MCP server "${server2}" requested input to ${target}, but this session has no handler for "${request.inputMethod}" (input "${request.inputKey}"). ${guidance}`;
22822
+ const message = `MCP server "${server3}" requested input to ${target}, but this session has no handler for "${request.inputMethod}" (input "${request.inputKey}"). ${guidance}`;
22821
22823
  return {
22822
22824
  error: INPUT_REQUIRED_NEEDS_UI,
22823
- server: server2,
22825
+ server: server3,
22824
22826
  ...tool ? { tool } : {},
22825
22827
  ...resourceUri ? { resourceUri } : {},
22826
22828
  inputKey: request.inputKey,
@@ -28585,8 +28587,8 @@ var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => {
28585
28587
  var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
28586
28588
  var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
28587
28589
  var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
28588
- exports.parse = parse;
28589
- function parse(string3) {
28590
+ exports.parse = parse2;
28591
+ function parse2(string3) {
28590
28592
  if (!string3) throw new TypeError("argument string is required");
28591
28593
  var header = typeof string3 === "object" ? getcontenttype(string3) : string3;
28592
28594
  if (typeof header !== "string") throw new TypeError("argument string is required to be a string");
@@ -31741,21 +31743,21 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31741
31743
  const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils();
31742
31744
  const { SCHEMES, getSchemeHandler } = require_schemes();
31743
31745
  function normalize(uri, options) {
31744
- if (typeof uri === "string") uri = serialize(parse(uri, options), options);
31745
- else if (typeof uri === "object") uri = parse(serialize(uri, options), options);
31746
+ if (typeof uri === "string") uri = serialize(parse2(uri, options), options);
31747
+ else if (typeof uri === "object") uri = parse2(serialize(uri, options), options);
31746
31748
  return uri;
31747
31749
  }
31748
31750
  function resolve7(baseURI, relativeURI, options) {
31749
31751
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
31750
- const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
31752
+ const resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true);
31751
31753
  schemelessOptions.skipEscape = true;
31752
31754
  return serialize(resolved, schemelessOptions);
31753
31755
  }
31754
31756
  function resolveComponent(base, relative3, options, skipNormalization) {
31755
31757
  const target = {};
31756
31758
  if (!skipNormalization) {
31757
- base = parse(serialize(base, options), options);
31758
- relative3 = parse(serialize(relative3, options), options);
31759
+ base = parse2(serialize(base, options), options);
31760
+ relative3 = parse2(serialize(relative3, options), options);
31759
31761
  }
31760
31762
  options = options || {};
31761
31763
  if (!options.tolerant && relative3.scheme) {
@@ -31799,7 +31801,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31799
31801
  function equal(uriA, uriB, options) {
31800
31802
  if (typeof uriA === "string") {
31801
31803
  uriA = unescape(uriA);
31802
- uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), {
31804
+ uriA = serialize(normalizeComponentEncoding(parse2(uriA, options), true), {
31803
31805
  ...options,
31804
31806
  skipEscape: true
31805
31807
  });
@@ -31809,7 +31811,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31809
31811
  });
31810
31812
  if (typeof uriB === "string") {
31811
31813
  uriB = unescape(uriB);
31812
- uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), {
31814
+ uriB = serialize(normalizeComponentEncoding(parse2(uriB, options), true), {
31813
31815
  ...options,
31814
31816
  skipEscape: true
31815
31817
  });
@@ -31862,7 +31864,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31862
31864
  return uriTokens.join("");
31863
31865
  }
31864
31866
  const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
31865
- function parse(uri, opts) {
31867
+ function parse2(uri, opts) {
31866
31868
  const options = Object.assign({}, opts);
31867
31869
  const parsed = {
31868
31870
  scheme: void 0,
@@ -31923,7 +31925,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31923
31925
  resolveComponent,
31924
31926
  equal,
31925
31927
  serialize,
31926
- parse
31928
+ parse: parse2
31927
31929
  };
31928
31930
  module.exports = fastUri;
31929
31931
  module.exports.default = fastUri;
@@ -40214,10 +40216,10 @@ var StdioClientTransport = class {
40214
40216
  onclose;
40215
40217
  onerror;
40216
40218
  onmessage;
40217
- constructor(server2) {
40218
- this._serverParams = server2;
40219
- this._readBuffer = new ReadBuffer({ maxBufferSize: server2.maxBufferSize });
40220
- if (server2.stderr === "pipe" || server2.stderr === "overlapped") this._stderrStream = new PassThrough();
40219
+ constructor(server3) {
40220
+ this._serverParams = server3;
40221
+ this._readBuffer = new ReadBuffer({ maxBufferSize: server3.maxBufferSize });
40222
+ if (server3.stderr === "pipe" || server3.stderr === "overlapped") this._stderrStream = new PassThrough();
40221
40223
  }
40222
40224
  /**
40223
40225
  * Starts the server process and prepares to communicate with it.
@@ -44739,14 +44741,14 @@ function messageBytes(message) {
44739
44741
  return void 0;
44740
44742
  }
44741
44743
  }
44742
- function createMcpTraceEvent(direction, server2, transport, message, status, options) {
44744
+ function createMcpTraceEvent(direction, server3, transport, message, status, options) {
44743
44745
  const kind = messageKind(message);
44744
44746
  const bytes = messageBytes(message);
44745
44747
  const event = {
44746
44748
  version: MCP_TRACE_SCHEMA_VERSION,
44747
44749
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
44748
44750
  direction,
44749
- server: redactTraceText(server2, 120),
44751
+ server: redactTraceText(server3, 120),
44750
44752
  transport,
44751
44753
  kind,
44752
44754
  status,
@@ -44848,7 +44850,7 @@ function createMcpTraceWriter(sessionCwd, settings2 = {}, randomSuffix = Math.ra
44848
44850
  function isMcpTraceEnabled(definition, settings2) {
44849
44851
  return definition.trace ?? settings2?.enabled === true;
44850
44852
  }
44851
- function wrapTransportWithMcpTrace(transport, server2, transportKind, observer) {
44853
+ function wrapTransportWithMcpTrace(transport, server3, transportKind, observer) {
44852
44854
  let messageHandler = transport.onmessage;
44853
44855
  let tracedMessageHandler;
44854
44856
  const originalSend = transport.send;
@@ -44868,7 +44870,7 @@ function wrapTransportWithMcpTrace(transport, server2, transportKind, observer)
44868
44870
  set(handler) {
44869
44871
  messageHandler = handler;
44870
44872
  tracedMessageHandler = handler ? ((message, extra) => {
44871
- record3(createMcpTraceEvent("inbound", server2, transportKind, message, "received"));
44873
+ record3(createMcpTraceEvent("inbound", server3, transportKind, message, "received"));
44872
44874
  handler(message, extra);
44873
44875
  }) : void 0;
44874
44876
  }
@@ -44882,13 +44884,13 @@ function wrapTransportWithMcpTrace(transport, server2, transportKind, observer)
44882
44884
  try {
44883
44885
  await originalSend.call(transport, message, options);
44884
44886
  for (const item of messages) {
44885
- record3(createMcpTraceEvent("outbound", server2, transportKind, item, "sent", {
44887
+ record3(createMcpTraceEvent("outbound", server3, transportKind, item, "sent", {
44886
44888
  durationMs: performance.now() - started
44887
44889
  }));
44888
44890
  }
44889
44891
  } catch (error) {
44890
44892
  for (const item of messages) {
44891
- record3(createMcpTraceEvent("outbound", server2, transportKind, item, "error", {
44893
+ record3(createMcpTraceEvent("outbound", server3, transportKind, item, "error", {
44892
44894
  durationMs: performance.now() - started
44893
44895
  }));
44894
44896
  }
@@ -49953,7 +49955,7 @@ async function startUiServer(options) {
49953
49955
  const eventLog = [];
49954
49956
  let latestCheckpointEventId;
49955
49957
  let streamSummary;
49956
- let server2 = null;
49958
+ let server3 = null;
49957
49959
  let sandboxProxyServer = null;
49958
49960
  let sandboxProxyUrl = null;
49959
49961
  let closeTimer = null;
@@ -50114,7 +50116,7 @@ data: ${JSON.stringify(payload)}
50114
50116
  closeTimer = null;
50115
50117
  }
50116
50118
  try {
50117
- server2?.close();
50119
+ server3?.close();
50118
50120
  } catch {
50119
50121
  }
50120
50122
  try {
@@ -50468,7 +50470,7 @@ data: ${JSON.stringify(payload)}
50468
50470
  sendJson(res, status, { ok: false, error: wrapped.message });
50469
50471
  }
50470
50472
  });
50471
- server2 = hostServer;
50473
+ server3 = hostServer;
50472
50474
  if (options.initialResultPromise) {
50473
50475
  options.initialResultPromise.then(
50474
50476
  (result) => pushEvent("tool-result", result),
@@ -55322,11 +55324,11 @@ function normalizeSearchText(value) {
55322
55324
  function tokenize(value) {
55323
55325
  return normalizeSearchText(value).split(/[^a-z0-9]+/).filter(Boolean);
55324
55326
  }
55325
- function prepareToolSearch(tool, server2, keywords) {
55327
+ function prepareToolSearch(tool, server3, keywords) {
55326
55328
  const fields = {
55327
55329
  name: normalizeSearchText(tool.name),
55328
55330
  originalName: normalizeSearchText(tool.originalName),
55329
- server: normalizeSearchText(server2),
55331
+ server: normalizeSearchText(server3),
55330
55332
  description: normalizeSearchText(tool.description)
55331
55333
  };
55332
55334
  const preparedFields = Object.entries(fields).map(([field, value]) => [field, value, tokenize(value)]);
@@ -55432,14 +55434,14 @@ function getPreparedTools(state, serverName, metadata, definition, globalPrefix,
55432
55434
  }
55433
55435
  return prepared;
55434
55436
  }
55435
- function rankToolMatches(state, query2, server2, includeKeywords = true) {
55437
+ function rankToolMatches(state, query2, server3, includeKeywords = true) {
55436
55438
  const matches = [];
55437
55439
  const normalizedQuery = normalizeSearchText(query2).trim();
55438
55440
  const queryTokens = tokenize(query2);
55439
55441
  if (queryTokens.length === 0) return matches;
55440
55442
  const globalPrefix = state.config.settings?.toolPrefix ?? "server";
55441
55443
  for (const [serverName, metadata] of state.toolMetadata.entries()) {
55442
- if (server2 && serverName !== server2) continue;
55444
+ if (server3 && serverName !== server3) continue;
55443
55445
  const definition = state.config.mcpServers[serverName];
55444
55446
  if (isServerDisabled(definition)) continue;
55445
55447
  if (isServerInActiveFailureBackoff(state, serverName)) continue;
@@ -55464,7 +55466,7 @@ function paginate(items, offset, limit) {
55464
55466
  };
55465
55467
  }
55466
55468
  function rankSuggestions(state, name, limit) {
55467
- const stripped = Object.keys(state.config.mcpServers).flatMap((server2) => ["server", "short", "mcp"].map((prefix) => getServerPrefix(server2, prefix))).filter((candidate) => Boolean(candidate) && name.startsWith(`${candidate}_`)).sort((a, b) => b.length - a.length).map((candidate) => name.slice(candidate.length + 1));
55469
+ const stripped = Object.keys(state.config.mcpServers).flatMap((server3) => ["server", "short", "mcp"].map((prefix) => getServerPrefix(server3, prefix))).filter((candidate) => Boolean(candidate) && name.startsWith(`${candidate}_`)).sort((a, b) => b.length - a.length).map((candidate) => name.slice(candidate.length + 1));
55468
55470
  const query2 = stripped[0] ?? name;
55469
55471
  return rankToolMatches(state, query2, void 0, false).slice(0, limit).map((match) => match.tool.name);
55470
55472
  }
@@ -55498,9 +55500,9 @@ function getToolMatches(metadata, toolName, exact) {
55498
55500
  }
55499
55501
  function getEnabledToolMatches(state, toolName, exact) {
55500
55502
  const matches = [];
55501
- for (const [server2, metadata] of state.toolMetadata) {
55502
- if (isServerDisabled(state.config.mcpServers[server2])) continue;
55503
- for (const tool of getToolMatches(metadata, toolName, exact)) matches.push({ server: server2, tool });
55503
+ for (const [server3, metadata] of state.toolMetadata) {
55504
+ if (isServerDisabled(state.config.mcpServers[server3])) continue;
55505
+ for (const tool of getToolMatches(metadata, toolName, exact)) matches.push({ server: server3, tool });
55504
55506
  }
55505
55507
  return matches;
55506
55508
  }
@@ -55754,34 +55756,34 @@ function executeStatus(state) {
55754
55756
  let text = `MCP: ${connectedCount}/${enabledServers.length} servers, ${totalTools} tools`;
55755
55757
  if (disabledCount > 0) text += ` (${disabledCount} disabled)`;
55756
55758
  text += "\n\n";
55757
- for (const server2 of servers) {
55758
- if (server2.disabled) {
55759
- text += `\u2298 ${server2.name} (disabled)
55759
+ for (const server3 of servers) {
55760
+ if (server3.disabled) {
55761
+ text += `\u2298 ${server3.name} (disabled)
55760
55762
  `;
55761
55763
  continue;
55762
55764
  }
55763
- if (server2.status === "connected") {
55764
- const listen2 = server2.listenState === "active" ? server2.catalogStale ? ", listen active, catalog may be stale" : ", listen active" : server2.listenState === "dropped" ? ", catalog may be stale; will reconcile on next keep-alive or tool use" : server2.listenState === "re-establishing" ? ", re-establishing listen" : server2.listenState === "legacy" ? ", legacy notification path" : ", not listening for catalog updates";
55765
- text += `\u2713 ${server2.name} (${server2.toolCount} tools${listen2})
55765
+ if (server3.status === "connected") {
55766
+ const listen2 = server3.listenState === "active" ? server3.catalogStale ? ", listen active, catalog may be stale" : ", listen active" : server3.listenState === "dropped" ? ", catalog may be stale; will reconcile on next keep-alive or tool use" : server3.listenState === "re-establishing" ? ", re-establishing listen" : server3.listenState === "legacy" ? ", legacy notification path" : ", not listening for catalog updates";
55767
+ text += `\u2713 ${server3.name} (${server3.toolCount} tools${listen2})
55766
55768
  `;
55767
55769
  continue;
55768
55770
  }
55769
- if (server2.status === "needs-auth") {
55770
- text += `\u26A0 ${server2.name} (needs auth)
55771
+ if (server3.status === "needs-auth") {
55772
+ text += `\u26A0 ${server3.name} (needs auth)
55771
55773
  `;
55772
55774
  continue;
55773
55775
  }
55774
- if (server2.status === "cached") {
55775
- text += `\u25CB ${server2.name} (${server2.toolCount} tools, cached; not listening)
55776
+ if (server3.status === "cached") {
55777
+ text += `\u25CB ${server3.name} (${server3.toolCount} tools, cached; not listening)
55776
55778
  `;
55777
55779
  continue;
55778
55780
  }
55779
- if (server2.status === "failed") {
55780
- text += `\u2717 ${server2.name} (failed ${server2.failedAgo ?? 0}s ago)
55781
+ if (server3.status === "failed") {
55782
+ text += `\u2717 ${server3.name} (failed ${server3.failedAgo ?? 0}s ago)
55781
55783
  `;
55782
55784
  continue;
55783
55785
  }
55784
- text += `\u25CB ${server2.name} (not listening; disconnected)
55786
+ text += `\u25CB ${server3.name} (not listening; disconnected)
55785
55787
  `;
55786
55788
  }
55787
55789
  const directToolsFrozen = state.config.settings?.freezeDirectTools === true;
@@ -55880,18 +55882,18 @@ function executeDescribe(state, toolName) {
55880
55882
  let disabledMatch;
55881
55883
  let failedMatch;
55882
55884
  if (!toolMeta) {
55883
- for (const [server2, metadata] of state.toolMetadata.entries()) {
55885
+ for (const [server3, metadata] of state.toolMetadata.entries()) {
55884
55886
  const found = findToolByName(metadata, toolName);
55885
55887
  if (!found) continue;
55886
- if (isServerDisabled(state.config.mcpServers[server2])) {
55887
- disabledMatch ??= server2;
55888
+ if (isServerDisabled(state.config.mcpServers[server3])) {
55889
+ disabledMatch ??= server3;
55888
55890
  continue;
55889
55891
  }
55890
- if (isServerInActiveFailureBackoff(state, server2)) {
55891
- failedMatch ??= server2;
55892
+ if (isServerInActiveFailureBackoff(state, server3)) {
55893
+ failedMatch ??= server3;
55892
55894
  continue;
55893
55895
  }
55894
- serverName = server2;
55896
+ serverName = server3;
55895
55897
  toolMeta = found;
55896
55898
  break;
55897
55899
  }
@@ -55937,10 +55939,10 @@ No parameters defined.`;
55937
55939
  details: { mode: "describe", tool: toolMeta, server: serverName }
55938
55940
  };
55939
55941
  }
55940
- function executeSearch(state, query2, regex, server2, includeSchemas, limit = 12, offset = 0) {
55942
+ function executeSearch(state, query2, regex, server3, includeSchemas, limit = 12, offset = 0) {
55941
55943
  const showSchemas = includeSchemas !== false;
55942
- if (server2 && isServerDisabled(state.config.mcpServers[server2])) return disabledResult("search", server2);
55943
- if (server2 && isServerInActiveFailureBackoff(state, server2)) return serverBackoffResult(state, "search", server2);
55944
+ if (server3 && isServerDisabled(state.config.mcpServers[server3])) return disabledResult("search", server3);
55945
+ if (server3 && isServerInActiveFailureBackoff(state, server3)) return serverBackoffResult(state, "search", server3);
55944
55946
  let matches;
55945
55947
  if (regex) {
55946
55948
  let pattern;
@@ -55981,27 +55983,27 @@ function executeSearch(state, query2, regex, server2, includeSchemas, limit = 12
55981
55983
  const definition = state.config.mcpServers[serverName];
55982
55984
  if (isServerDisabled(definition)) continue;
55983
55985
  if (isServerInActiveFailureBackoff(state, serverName)) continue;
55984
- if (server2 && serverName !== server2) continue;
55986
+ if (server3 && serverName !== server3) continue;
55985
55987
  for (const tool of metadata) {
55986
55988
  const matched = pattern.test(tool.name) || pattern.test(tool.description) || resolveSearchKeywords(definition, tool.originalName, serverName, globalPrefix).some((keyword) => pattern.test(keyword));
55987
55989
  if (matched) matches.push({ server: serverName, tool, score: 0 });
55988
55990
  }
55989
55991
  }
55990
55992
  } else if (query2.trim().length === 0) {
55991
- if (!server2) {
55993
+ if (!server3) {
55992
55994
  return {
55993
55995
  content: [{ type: "text", text: "Search query cannot be empty" }],
55994
55996
  details: { mode: "search", error: "empty_query" }
55995
55997
  };
55996
55998
  }
55997
- matches = (state.toolMetadata.get(server2) ?? []).map((tool) => ({ server: server2, tool, score: 0 })).sort((a, b) => a.tool.name.localeCompare(b.tool.name));
55999
+ matches = (state.toolMetadata.get(server3) ?? []).map((tool) => ({ server: server3, tool, score: 0 })).sort((a, b) => a.tool.name.localeCompare(b.tool.name));
55998
56000
  } else {
55999
- matches = rankToolMatches(state, query2, server2);
56001
+ matches = rankToolMatches(state, query2, server3);
56000
56002
  }
56001
56003
  const page2 = paginate(matches, offset, limit);
56002
56004
  if (page2.total === 0) {
56003
- const connectingServers = server2 ? state.config.mcpServers[server2] && state.manager.isConnecting(server2) ? [server2] : [] : Object.keys(state.config.mcpServers).filter((name) => !isServerDisabled(state.config.mcpServers[name]) && state.manager.isConnecting(name)).sort((a, b) => a.localeCompare(b));
56004
- const msg = server2 ? `No tools matching "${query2}" in "${server2}"` : `No tools matching "${query2}"`;
56005
+ const connectingServers = server3 ? state.config.mcpServers[server3] && state.manager.isConnecting(server3) ? [server3] : [] : Object.keys(state.config.mcpServers).filter((name) => !isServerDisabled(state.config.mcpServers[name]) && state.manager.isConnecting(name)).sort((a, b) => a.localeCompare(b));
56006
+ const msg = server3 ? `No tools matching "${query2}" in "${server3}"` : `No tools matching "${query2}"`;
56005
56007
  const connectingMessage = connectingServers.length === 1 ? ` Server "${connectingServers[0]}" is still connecting; retry in a moment.` : connectingServers.length > 1 ? ` Servers ${connectingServers.map((name) => `"${name}"`).join(", ")} are still connecting; retry in a moment.` : "";
56006
56008
  return {
56007
56009
  content: [{ type: "text", text: `${msg}${connectingMessage}` }],
@@ -56060,25 +56062,25 @@ ${page2.items.length} of ${page2.total} \u2014 offset: ${page2.nextOffset} for m
56060
56062
  }
56061
56063
  };
56062
56064
  }
56063
- function executeList(state, server2) {
56064
- const definition = state.config.mcpServers[server2];
56065
+ function executeList(state, server3) {
56066
+ const definition = state.config.mcpServers[server3];
56065
56067
  if (!definition) {
56066
56068
  return {
56067
- content: [{ type: "text", text: `Server "${server2}" not found. Use mcp({}) to see available servers.` }],
56068
- details: { mode: "list", server: server2, tools: [], count: 0, error: "not_found" }
56069
+ content: [{ type: "text", text: `Server "${server3}" not found. Use mcp({}) to see available servers.` }],
56070
+ details: { mode: "list", server: server3, tools: [], count: 0, error: "not_found" }
56069
56071
  };
56070
56072
  }
56071
- if (isServerDisabled(definition)) return disabledResult("list", server2);
56072
- const metadata = state.toolMetadata.get(server2);
56073
+ if (isServerDisabled(definition)) return disabledResult("list", server3);
56074
+ const metadata = state.toolMetadata.get(server3);
56073
56075
  const toolNames = metadata?.map((m) => m.name) ?? [];
56074
- const connection = state.manager.getConnection(server2);
56075
- if (isServerInActiveFailureBackoff(state, server2)) {
56076
+ const connection = state.manager.getConnection(server3);
56077
+ if (isServerInActiveFailureBackoff(state, server3)) {
56076
56078
  return {
56077
- ...serverBackoffResult(state, "list", server2),
56078
- details: { mode: "list", server: server2, tools: [], count: 0, error: "server_backoff" }
56079
+ ...serverBackoffResult(state, "list", server3),
56080
+ details: { mode: "list", server: server3, tools: [], count: 0, error: "server_backoff" }
56079
56081
  };
56080
56082
  }
56081
- const instructions = state.serverInstructions.get(server2);
56083
+ const instructions = state.serverInstructions.get(server3);
56082
56084
  let instructionsText = "";
56083
56085
  if (instructions) {
56084
56086
  const preview = truncateAtWord(instructions, INSTRUCTIONS_PREVIEW_LENGTH);
@@ -56088,36 +56090,36 @@ Server instructions:
56088
56090
  ${preview}`;
56089
56091
  if (preview !== instructions) {
56090
56092
  instructionsText += `
56091
- Use mcp({ instructions: "${server2}" }) for the full text.`;
56093
+ Use mcp({ instructions: "${server3}" }) for the full text.`;
56092
56094
  }
56093
56095
  }
56094
56096
  if (toolNames.length === 0) {
56095
56097
  if (connection?.status === "connected") {
56096
56098
  return {
56097
- content: [{ type: "text", text: `Server "${server2}" has no tools.${instructionsText}` }],
56098
- details: { mode: "list", server: server2, tools: [], count: 0, hasInstructions: Boolean(instructions) }
56099
+ content: [{ type: "text", text: `Server "${server3}" has no tools.${instructionsText}` }],
56100
+ details: { mode: "list", server: server3, tools: [], count: 0, hasInstructions: Boolean(instructions) }
56099
56101
  };
56100
56102
  }
56101
56103
  if (metadata !== void 0) {
56102
56104
  return {
56103
- content: [{ type: "text", text: `Server "${server2}" has no cached tools (not connected).${instructionsText}` }],
56104
- details: { mode: "list", server: server2, tools: [], count: 0, cached: true, hasInstructions: Boolean(instructions) }
56105
+ content: [{ type: "text", text: `Server "${server3}" has no cached tools (not connected).${instructionsText}` }],
56106
+ details: { mode: "list", server: server3, tools: [], count: 0, cached: true, hasInstructions: Boolean(instructions) }
56105
56107
  };
56106
56108
  }
56107
56109
  return {
56108
- content: [{ type: "text", text: `Server "${server2}" is configured but not connected. Use mcp({ connect: "${server2}" }) or /mcp reconnect ${server2} to retry.${instructionsText}` }],
56109
- details: { mode: "list", server: server2, tools: [], count: 0, error: "not_connected", hasInstructions: Boolean(instructions) }
56110
+ content: [{ type: "text", text: `Server "${server3}" is configured but not connected. Use mcp({ connect: "${server3}" }) or /mcp reconnect ${server3} to retry.${instructionsText}` }],
56111
+ details: { mode: "list", server: server3, tools: [], count: 0, error: "not_connected", hasInstructions: Boolean(instructions) }
56110
56112
  };
56111
56113
  }
56112
56114
  let cachedNote = "";
56113
56115
  if (connection?.status !== "connected") {
56114
56116
  if (connection?.status === "needs-auth") {
56115
- cachedNote = ` (needs auth \u2014 run mcp({ action: "auth-start", server: "${server2}" }))`;
56117
+ cachedNote = ` (needs auth \u2014 run mcp({ action: "auth-start", server: "${server3}" }))`;
56116
56118
  } else {
56117
- cachedNote = ` (lazy: tools from cache, not connected yet \u2014 mcp({ connect: "${server2}" }) to connect)`;
56119
+ cachedNote = ` (lazy: tools from cache, not connected yet \u2014 mcp({ connect: "${server3}" }) to connect)`;
56118
56120
  }
56119
56121
  }
56120
- let text = `${server2} (${toolNames.length} tools${cachedNote}):
56122
+ let text = `${server3} (${toolNames.length} tools${cachedNote}):
56121
56123
 
56122
56124
  `;
56123
56125
  const descMap = /* @__PURE__ */ new Map();
@@ -56136,38 +56138,38 @@ Use mcp({ instructions: "${server2}" }) for the full text.`;
56136
56138
  text += instructionsText;
56137
56139
  return {
56138
56140
  content: [{ type: "text", text: text.trim() }],
56139
- details: { mode: "list", server: server2, tools: toolNames, count: toolNames.length, hasInstructions: Boolean(instructions) }
56141
+ details: { mode: "list", server: server3, tools: toolNames, count: toolNames.length, hasInstructions: Boolean(instructions) }
56140
56142
  };
56141
56143
  }
56142
- function executeInstructions(state, server2) {
56143
- const definition = state.config.mcpServers[server2];
56144
+ function executeInstructions(state, server3) {
56145
+ const definition = state.config.mcpServers[server3];
56144
56146
  if (!definition) {
56145
56147
  return {
56146
- content: [{ type: "text", text: `Server "${server2}" not found. Use mcp({}) to see available servers.` }],
56147
- details: { mode: "instructions", server: server2, error: "not_found" }
56148
+ content: [{ type: "text", text: `Server "${server3}" not found. Use mcp({}) to see available servers.` }],
56149
+ details: { mode: "instructions", server: server3, error: "not_found" }
56148
56150
  };
56149
56151
  }
56150
- if (isServerDisabled(definition)) return disabledResult("instructions", server2);
56151
- if (isServerInActiveFailureBackoff(state, server2)) return serverBackoffResult(state, "instructions", server2);
56152
- const instructions = state.serverInstructions.get(server2);
56152
+ if (isServerDisabled(definition)) return disabledResult("instructions", server3);
56153
+ if (isServerInActiveFailureBackoff(state, server3)) return serverBackoffResult(state, "instructions", server3);
56154
+ const instructions = state.serverInstructions.get(server3);
56153
56155
  if (instructions) {
56154
56156
  return {
56155
- content: [{ type: "text", text: `${server2} instructions:
56157
+ content: [{ type: "text", text: `${server3} instructions:
56156
56158
 
56157
56159
  ${instructions}` }],
56158
- details: { mode: "instructions", server: server2, length: instructions.length }
56160
+ details: { mode: "instructions", server: server3, length: instructions.length }
56159
56161
  };
56160
56162
  }
56161
- const connection = state.manager.getConnection(server2);
56163
+ const connection = state.manager.getConnection(server3);
56162
56164
  if (connection?.status === "connected") {
56163
56165
  return {
56164
- content: [{ type: "text", text: `Server "${server2}" does not provide instructions.` }],
56165
- details: { mode: "instructions", server: server2, error: "no_instructions" }
56166
+ content: [{ type: "text", text: `Server "${server3}" does not provide instructions.` }],
56167
+ details: { mode: "instructions", server: server3, error: "no_instructions" }
56166
56168
  };
56167
56169
  }
56168
56170
  return {
56169
- content: [{ type: "text", text: `No instructions cached for "${server2}". Use mcp({ connect: "${server2}" }) to connect and refresh.` }],
56170
- details: { mode: "instructions", server: server2, error: "not_connected" }
56171
+ content: [{ type: "text", text: `No instructions cached for "${server3}". Use mcp({ connect: "${server3}" }) to connect and refresh.` }],
56172
+ details: { mode: "instructions", server: server3, error: "not_connected" }
56171
56173
  };
56172
56174
  }
56173
56175
  async function executeConnect(state, serverName, signal) {
@@ -56278,26 +56280,26 @@ async function executeCall(state, toolName, args, serverOverride, getPiTools, si
56278
56280
  return ambiguousToolResult("call", toolName);
56279
56281
  }
56280
56282
  let disabledMatch;
56281
- for (const [server2, metadata] of state.toolMetadata.entries()) {
56283
+ for (const [server3, metadata] of state.toolMetadata.entries()) {
56282
56284
  const found = metadata.find((tool) => tool.name === toolName);
56283
56285
  if (!found) continue;
56284
- if (isServerDisabled(state.config.mcpServers[server2])) {
56285
- disabledMatch ??= { serverName: server2, toolMeta: found };
56286
+ if (isServerDisabled(state.config.mcpServers[server3])) {
56287
+ disabledMatch ??= { serverName: server3, toolMeta: found };
56286
56288
  continue;
56287
56289
  }
56288
- serverName = server2;
56290
+ serverName = server3;
56289
56291
  toolMeta = found;
56290
56292
  break;
56291
56293
  }
56292
56294
  if (!toolMeta && !disabledMatch) {
56293
- for (const [server2, metadata] of state.toolMetadata.entries()) {
56295
+ for (const [server3, metadata] of state.toolMetadata.entries()) {
56294
56296
  const found = findToolByName(metadata, toolName);
56295
56297
  if (!found) continue;
56296
- if (isServerDisabled(state.config.mcpServers[server2])) {
56297
- disabledMatch ??= { serverName: server2, toolMeta: found };
56298
+ if (isServerDisabled(state.config.mcpServers[server3])) {
56299
+ disabledMatch ??= { serverName: server3, toolMeta: found };
56298
56300
  continue;
56299
56301
  }
56300
- serverName = server2;
56302
+ serverName = server3;
56301
56303
  toolMeta = found;
56302
56304
  break;
56303
56305
  }
@@ -57026,11 +57028,11 @@ function collectCollapsedResultLines(content, maxLines, maxChars) {
57026
57028
  }
57027
57029
  function formatMcpToolResultIdentity(details) {
57028
57030
  if (details?.mode !== "call") return null;
57029
- const server2 = typeof details.server === "string" ? details.server : typeof details.hintServer === "string" ? details.hintServer : null;
57030
- if (!server2) return null;
57031
- if (typeof details.tool === "string") return `MCP ${server2}/${details.tool}`;
57032
- if (typeof details.resourceUri === "string") return `MCP ${server2} resource ${details.resourceUri}`;
57033
- if (typeof details.requestedTool === "string") return `MCP ${server2}/${details.requestedTool}`;
57031
+ const server3 = typeof details.server === "string" ? details.server : typeof details.hintServer === "string" ? details.hintServer : null;
57032
+ if (!server3) return null;
57033
+ if (typeof details.tool === "string") return `MCP ${server3}/${details.tool}`;
57034
+ if (typeof details.resourceUri === "string") return `MCP ${server3} resource ${details.resourceUri}`;
57035
+ if (typeof details.requestedTool === "string") return `MCP ${server3}/${details.requestedTool}`;
57034
57036
  return null;
57035
57037
  }
57036
57038
  function formatMcpToolResultLines(result, expanded, maxCollapsedLines = DEFAULT_BOXED_COLLAPSED_LINES, maxCollapsedChars = DEFAULT_MAX_COLLAPSED_CHARS) {
@@ -57201,10 +57203,10 @@ async function runMcpScript(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_
57201
57203
  if (query2.trim() === "") {
57202
57204
  return { items: [], total: 0, hasMore: false, nextOffset: null };
57203
57205
  }
57204
- const server2 = typeof input?.server === "string" ? input.server : void 0;
57206
+ const server3 = typeof input?.server === "string" ? input.server : void 0;
57205
57207
  const limit = typeof input?.limit === "number" ? input.limit : 12;
57206
57208
  const offset = typeof input?.offset === "number" ? input.offset : 0;
57207
- const page2 = paginate(rankToolMatches(state, query2, server2), offset, limit);
57209
+ const page2 = paginate(rankToolMatches(state, query2, server3), offset, limit);
57208
57210
  return {
57209
57211
  ...page2,
57210
57212
  items: page2.items.map(({ server: matchServer, tool, score }) => ({
@@ -57227,15 +57229,15 @@ async function runMcpScript(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_
57227
57229
  const path7 = typeof input?.path === "string" ? input.path : "";
57228
57230
  let error;
57229
57231
  try {
57230
- for (const [server2, metadata] of state.toolMetadata) {
57231
- if (isServerInActiveFailureBackoff(state, server2)) continue;
57232
+ for (const [server3, metadata] of state.toolMetadata) {
57233
+ if (isServerInActiveFailureBackoff(state, server3)) continue;
57232
57234
  const tool = findToolByName(metadata, path7);
57233
57235
  if (!tool) continue;
57234
57236
  const inputTypeScript = tool.inputSchema ? renderTsShape(tool.inputSchema) ?? formatSchema(tool.inputSchema) : null;
57235
57237
  return {
57236
57238
  path: tool.name,
57237
57239
  name: tool.originalName,
57238
- server: server2,
57240
+ server: server3,
57239
57241
  ...tool.description ? { description: tool.description } : {},
57240
57242
  ...inputTypeScript ? { inputTypeScript } : {}
57241
57243
  };
@@ -59072,8 +59074,8 @@ function mcpNameFromToolCall(message) {
59072
59074
  const parsedName = parseMcpToolName(message.tool);
59073
59075
  if (parsedName) return parsedName.server;
59074
59076
  if (message.tool.startsWith("mcp.")) {
59075
- const [server2, ...toolParts] = message.tool.slice("mcp.".length).split(".");
59076
- if (server2 && toolParts.length > 0) return server2;
59077
+ const [server3, ...toolParts] = message.tool.slice("mcp.".length).split(".");
59078
+ if (server3 && toolParts.length > 0) return server3;
59077
59079
  }
59078
59080
  return NON_MCP_SERVERS.has(message.server) ? null : message.server;
59079
59081
  }
@@ -59289,9 +59291,9 @@ function calculateCumulativeTokenUsageDelta(current, previous) {
59289
59291
  cacheWriteInputTokens: current.cacheWriteInputTokens - previous.cacheWriteInputTokens
59290
59292
  };
59291
59293
  }
59292
- function recordParsedTokenUsage(event, harness, parse) {
59294
+ function recordParsedTokenUsage(event, harness, parse2) {
59293
59295
  if (event.type !== "usage-updated") return void 0;
59294
- const usage = parse(event.payload);
59296
+ const usage = parse2(event.payload);
59295
59297
  if (!usage) return void 0;
59296
59298
  return {
59297
59299
  records: [{
@@ -62424,7 +62426,7 @@ var RepoFileService = class {
62424
62426
 
62425
62427
  // src/v1-routes.ts
62426
62428
  import { Hono } from "hono";
62427
- import { z as z4 } from "zod";
62429
+ import { z as z5 } from "zod";
62428
62430
  import { readdir as readdir11, stat as stat7, readFile as readFile23 } from "fs/promises";
62429
62431
  import { join as join39, resolve as resolve5 } from "path";
62430
62432
 
@@ -62816,9 +62818,18 @@ ${combinedScript}` : combinedScript;
62816
62818
  import { randomUUID as randomUUID12 } from "crypto";
62817
62819
  import { existsSync as existsSync20 } from "fs";
62818
62820
  import { spawn as spawn8 } from "node-pty";
62821
+ import { z as z4 } from "zod";
62819
62822
  var MAX_REPLAY_CHARS = 1024 * 1024;
62820
62823
  var MAX_TERMINAL_SESSIONS = 8;
62821
62824
  var MAX_PENDING_INPUT = 64;
62825
+ var terminalSizeSchema = z4.object({
62826
+ cols: z4.number().int().min(2).max(500),
62827
+ rows: z4.number().int().min(1).max(200)
62828
+ });
62829
+ var terminalCommandSchema = z4.discriminatedUnion("type", [
62830
+ z4.object({ type: z4.literal("input"), data: z4.string() }),
62831
+ terminalSizeSchema.extend({ type: z4.literal("resize") })
62832
+ ]);
62822
62833
  var TerminalService = class {
62823
62834
  sessions = /* @__PURE__ */ new Map();
62824
62835
  nextTitleNumber = 1;
@@ -62894,6 +62905,12 @@ var TerminalService = class {
62894
62905
  }
62895
62906
  return true;
62896
62907
  }
62908
+ command(id, command) {
62909
+ const session = this.sessions.get(id);
62910
+ if (!session || session.exited) return;
62911
+ if (command.type === "input") session.pty.write(command.data);
62912
+ else session.pty.resize(command.cols, command.rows);
62913
+ }
62897
62914
  resize(id, cols, rows) {
62898
62915
  const session = this.sessions.get(id);
62899
62916
  if (!session || session.exited) return false;
@@ -62932,32 +62949,28 @@ var TerminalService = class {
62932
62949
  var terminalService = new TerminalService();
62933
62950
 
62934
62951
  // src/v1-routes.ts
62935
- var createPreviewSchema = z4.object({
62936
- port: z4.number().int().min(1).max(65535),
62937
- publicUrl: z4.string().min(1)
62938
- });
62939
- var terminalSizeSchema = z4.object({
62940
- cols: z4.number().int().min(2).max(500),
62941
- rows: z4.number().int().min(1).max(200)
62952
+ var createPreviewSchema = z5.object({
62953
+ port: z5.number().int().min(1).max(65535),
62954
+ publicUrl: z5.string().min(1)
62942
62955
  });
62943
- var writeTerminalSessionSchema = z4.object({
62944
- data: z4.string().max(64 * 1024),
62945
- generation: z4.number().int().nonnegative(),
62946
- sequence: z4.number().int().nonnegative()
62956
+ var writeTerminalSessionSchema = z5.object({
62957
+ data: z5.string().max(64 * 1024),
62958
+ generation: z5.number().int().nonnegative(),
62959
+ sequence: z5.number().int().nonnegative()
62947
62960
  });
62948
- var respondToolInputSchema = z4.object({
62949
- requestId: z4.string().min(1),
62950
- selectionId: z4.string().min(1)
62961
+ var respondToolInputSchema = z5.object({
62962
+ requestId: z5.string().min(1),
62963
+ selectionId: z5.string().min(1)
62951
62964
  });
62952
- var updateGoalSchema = z4.object({
62953
- objective: z4.string().trim().min(1).max(MAX_CODEX_GOAL_OBJECTIVE_CHARS).optional(),
62954
- status: z4.enum(["active", "paused"]).optional()
62965
+ var updateGoalSchema = z5.object({
62966
+ objective: z5.string().trim().min(1).max(MAX_CODEX_GOAL_OBJECTIVE_CHARS).optional(),
62967
+ status: z5.enum(["active", "paused"]).optional()
62955
62968
  }).refine((body) => body.objective !== void 0 || body.status !== void 0, {
62956
62969
  message: "Goal objective or status required"
62957
62970
  });
62958
- var updateTextFileSchema = (maxLength) => z4.object({
62959
- content: z4.string().max(maxLength),
62960
- expectedRevision: z4.string().regex(/^[a-f0-9]{64}$/)
62971
+ var updateTextFileSchema = (maxLength) => z5.object({
62972
+ content: z5.string().max(maxLength),
62973
+ expectedRevision: z5.string().regex(/^[a-f0-9]{64}$/)
62961
62974
  });
62962
62975
  function jsonError(message, details) {
62963
62976
  return { error: message, details };
@@ -63007,11 +63020,11 @@ function createV1Routes(deps) {
63007
63020
  const app2 = new Hono();
63008
63021
  app2.post("/pull-requests/check", async (c) => {
63009
63022
  if (c.req.header("content-type")?.includes("application/json")) {
63010
- const result = z4.object({
63011
- toolName: z4.string(),
63012
- toolInput: z4.unknown(),
63013
- output: z4.unknown(),
63014
- success: z4.boolean()
63023
+ const result = z5.object({
63024
+ toolName: z5.string(),
63025
+ toolInput: z5.unknown(),
63026
+ output: z5.unknown(),
63027
+ success: z5.boolean()
63015
63028
  }).safeParse(await c.req.json().catch(() => null));
63016
63029
  if (!result.success) return c.json({ error: "Invalid PR tool result" }, 400);
63017
63030
  await pullRequestCheckService.onToolResult(result.data);
@@ -63240,7 +63253,7 @@ function createV1Routes(deps) {
63240
63253
  const chat = await deps.chatService.updateDisplayName(c.req.param("chatId"), body.displayName);
63241
63254
  return c.json({ chat });
63242
63255
  } catch (error) {
63243
- if (error instanceof z4.ZodError) {
63256
+ if (error instanceof z5.ZodError) {
63244
63257
  return c.json(jsonError(error.issues[0]?.message || "Invalid tab name"), 400);
63245
63258
  }
63246
63259
  if (error instanceof ChatNotFoundError) {
@@ -63345,7 +63358,7 @@ function createV1Routes(deps) {
63345
63358
  const result = await deps.chatService.updateGoal(c.req.param("chatId"), body);
63346
63359
  return c.json(result);
63347
63360
  } catch (error) {
63348
- if (error instanceof z4.ZodError) {
63361
+ if (error instanceof z5.ZodError) {
63349
63362
  return c.json(jsonError(error.issues[0]?.message || "Invalid goal update"), 400);
63350
63363
  }
63351
63364
  if (error instanceof ChatNotFoundError) {
@@ -63967,6 +63980,104 @@ data: ${JSON.stringify("Terminal session not found")}
63967
63980
  return app2;
63968
63981
  }
63969
63982
 
63983
+ // src/services/terminal-socket.ts
63984
+ import { z as z6 } from "zod";
63985
+ var ndcModule;
63986
+ var loadNdc = () => ndcModule ??= import("node-datachannel").then((module) => module.default, () => null);
63987
+ var CHANNEL_CHUNK_CHARS = 16384;
63988
+ var MAX_QUEUED_CANDIDATES = 32;
63989
+ var MAX_BUFFERED_BYTES = 8 * 1024 * 1024;
63990
+ var socketMessageSchema = z6.union([
63991
+ terminalCommandSchema,
63992
+ z6.object({ type: z6.literal("rtc-offer"), sdp: z6.string().max(64 * 1024) }),
63993
+ z6.object({ type: z6.literal("rtc-candidate"), candidate: z6.string().max(1024), mid: z6.string().max(64) }),
63994
+ z6.object({ type: z6.literal("rtc-switch") })
63995
+ ]);
63996
+ function parse(schema, raw) {
63997
+ try {
63998
+ const result = schema.safeParse(JSON.parse(raw));
63999
+ return result.success ? result.data : null;
64000
+ } catch {
64001
+ return null;
64002
+ }
64003
+ }
64004
+ function attachTerminalSocket(id, socket) {
64005
+ const send = (message) => socket.send(JSON.stringify(message));
64006
+ let peer = null;
64007
+ let channel = null;
64008
+ const candidates = [];
64009
+ let early = [];
64010
+ const subscription = terminalService.subscribe(id, (data) => {
64011
+ if (socket.bufferedAmount > MAX_BUFFERED_BYTES || (channel?.bufferedAmount() ?? 0) > MAX_BUFFERED_BYTES) {
64012
+ socket.terminate();
64013
+ return;
64014
+ }
64015
+ if (!channel?.isOpen()) {
64016
+ send({ type: "output", data });
64017
+ return;
64018
+ }
64019
+ for (let start = 0; start < data.length; ) {
64020
+ let end = Math.min(start + CHANNEL_CHUNK_CHARS, data.length);
64021
+ if (end < data.length && /[\uD800-\uDBFF]/.test(data[end - 1])) end--;
64022
+ channel.sendMessage(data.slice(start, end));
64023
+ start = end;
64024
+ }
64025
+ });
64026
+ if (!subscription) {
64027
+ socket.close(4410, "Terminal session not found");
64028
+ return;
64029
+ }
64030
+ if (subscription.replay) send({ type: "output", data: subscription.replay });
64031
+ const negotiate = async (offer) => {
64032
+ const ndc = await loadNdc();
64033
+ if (!ndc || peer || socket.readyState !== socket.OPEN) return;
64034
+ const connection = new ndc.PeerConnection(`terminal-${id}`, { iceServers: [TERMINAL_RTC_ICE_SERVER] });
64035
+ peer = connection;
64036
+ connection.onLocalDescription((sdp) => send({ type: "rtc-answer", sdp }));
64037
+ connection.onLocalCandidate((candidate, mid) => send({ type: "rtc-candidate", candidate, mid }));
64038
+ connection.onDataChannel((dc) => {
64039
+ dc.onMessage((raw) => {
64040
+ const command = typeof raw === "string" ? parse(terminalCommandSchema, raw) : null;
64041
+ if (!command) return;
64042
+ if (early) early.push(command);
64043
+ else terminalService.command(id, command);
64044
+ });
64045
+ dc.onClosed(() => {
64046
+ if (channel === dc) channel = null;
64047
+ });
64048
+ const activate2 = () => {
64049
+ channel = dc;
64050
+ send({ type: "rtc-switch" });
64051
+ };
64052
+ if (dc.isOpen()) activate2();
64053
+ else dc.onOpen(activate2);
64054
+ });
64055
+ connection.setRemoteDescription(offer, "offer");
64056
+ for (const { candidate, mid } of candidates.splice(0)) connection.addRemoteCandidate(candidate, mid);
64057
+ };
64058
+ socket.on("message", (raw) => {
64059
+ const message = parse(socketMessageSchema, raw.toString());
64060
+ if (!message) return;
64061
+ if (message.type === "rtc-offer") {
64062
+ negotiate(message.sdp).catch(() => {
64063
+ peer?.close();
64064
+ peer = null;
64065
+ });
64066
+ } else if (message.type === "rtc-candidate") {
64067
+ if (peer) peer.addRemoteCandidate(message.candidate, message.mid);
64068
+ else if (candidates.length < MAX_QUEUED_CANDIDATES) candidates.push(message);
64069
+ } else if (message.type === "rtc-switch") {
64070
+ for (const command of early ?? []) terminalService.command(id, command);
64071
+ early = null;
64072
+ } else terminalService.command(id, message);
64073
+ });
64074
+ socket.on("close", () => {
64075
+ subscription.unsubscribe();
64076
+ channel = null;
64077
+ peer?.close();
64078
+ });
64079
+ }
64080
+
63970
64081
  // src/services/heartbeat-service.ts
63971
64082
  function unrefTimer(timer) {
63972
64083
  if (typeof timer === "object" && timer !== null && "unref" in timer && typeof timer.unref === "function") {
@@ -64053,7 +64164,7 @@ function startGitPushTracker() {
64053
64164
  async function listen() {
64054
64165
  await mkdir23(ENGINE_DIR2, { recursive: true });
64055
64166
  await rm5(SOCKET_PATH, { force: true });
64056
- const server2 = createServer2((socket) => {
64167
+ const server3 = createServer2((socket) => {
64057
64168
  let buffered = "";
64058
64169
  let ignored = false;
64059
64170
  let push = false;
@@ -64095,10 +64206,10 @@ async function listen() {
64095
64206
  });
64096
64207
  });
64097
64208
  await new Promise((resolve7, reject) => {
64098
- server2.once("error", reject);
64099
- server2.listen(SOCKET_PATH, () => {
64100
- server2.off("error", reject);
64101
- server2.on("error", (error) => console.error("[GitPushTracker] Socket error:", error));
64209
+ server3.once("error", reject);
64210
+ server3.listen(SOCKET_PATH, () => {
64211
+ server3.off("error", reject);
64212
+ server3.on("error", (error) => console.error("[GitPushTracker] Socket error:", error));
64102
64213
  resolve7();
64103
64214
  });
64104
64215
  });
@@ -64483,7 +64594,9 @@ async function sleep2() {
64483
64594
  await engineLogger.flush();
64484
64595
  return createSuccessResult({ state: lifecycle.state, workspaceId: lifecycle.workspaceId });
64485
64596
  }
64486
- serve(
64597
+ var terminalSockets = new WebSocketServer({ noServer: true });
64598
+ var TERMINAL_SOCKET_PATH = /^\/terminal\/sessions\/([^/]+)\/ws$/;
64599
+ var server2 = serve(
64487
64600
  {
64488
64601
  fetch: app.fetch,
64489
64602
  port
@@ -64502,6 +64615,17 @@ serve(
64502
64615
  }
64503
64616
  }
64504
64617
  );
64618
+ server2.on("upgrade", (req, socket, head) => {
64619
+ const sessionId = TERMINAL_SOCKET_PATH.exec(new URL(req.url ?? "/", "http://engine").pathname)?.[1];
64620
+ if (!sessionId || req.headers["x-replicas-engine-secret"] !== ENGINE_ENV.REPLICAS_ENGINE_SECRET || !lifecycle.active) {
64621
+ socket.end(`HTTP/1.1 ${sessionId ? "401 Unauthorized" : "404 Not Found"}\r
64622
+ Connection: close\r
64623
+ \r
64624
+ `);
64625
+ return;
64626
+ }
64627
+ terminalSockets.handleUpgrade(req, socket, head, (ws) => attachTerminalSocket(decodeURIComponent(sessionId), ws));
64628
+ });
64505
64629
  /*! Bundled license information:
64506
64630
 
64507
64631
  @modelcontextprotocol/client/dist/src-D_zzAWoS.mjs: