replicas-engine 0.1.963 → 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-KSVPXW5Y.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-DPCVYN2Z.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-LVLSEAYD.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-GSQ7ILGR.js";
82
+ } from "./chunk-ACUYRC4H.js";
83
83
  import {
84
84
  AspClient,
85
85
  getCodexModelProvider
86
- } from "./chunk-KAMPG4XF.js";
86
+ } from "./chunk-AOF42AV2.js";
87
87
  import {
88
88
  SUBPROCESS_MAX_BUFFER,
89
89
  execAsync,
90
90
  execFileAsync
91
- } from "./chunk-43I2SLDL.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,
@@ -230,6 +231,7 @@ import {
230
231
  extractLatestContextUsage,
231
232
  extractToolResultText,
232
233
  fetchOpenCodeGoCatalog,
234
+ fileContentDiff,
233
235
  forkChatRequestSchema,
234
236
  formatChatForkHandoffMessage,
235
237
  formatSideChatUpdateMessage,
@@ -317,7 +319,7 @@ import {
317
319
  workspaceCredentialProviderSchema,
318
320
  workspaceTokenRequestSchema,
319
321
  workspaceTokenResponseSchema
320
- } from "./chunk-LZ3GKDSS.js";
322
+ } from "./chunk-BYJ6CIME.js";
321
323
  import {
322
324
  cloneMcpConfig,
323
325
  ensureCompatibilityImports,
@@ -775,7 +777,7 @@ var require_parse = __commonJS({
775
777
  }
776
778
  return parsed;
777
779
  }
778
- function parse(command, args, options) {
780
+ function parse2(command, args, options) {
779
781
  if (args && !Array.isArray(args)) {
780
782
  options = args;
781
783
  args = null;
@@ -794,7 +796,7 @@ var require_parse = __commonJS({
794
796
  };
795
797
  return options.shell ? parsed : parseNonShell(parsed);
796
798
  }
797
- module.exports = parse;
799
+ module.exports = parse2;
798
800
  }
799
801
  });
800
802
 
@@ -853,16 +855,16 @@ var require_cross_spawn = __commonJS({
853
855
  "../node_modules/.bun/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(exports, module) {
854
856
  "use strict";
855
857
  var cp2 = __require("child_process");
856
- var parse = require_parse();
858
+ var parse2 = require_parse();
857
859
  var enoent = require_enoent();
858
860
  function spawn9(command, args, options) {
859
- const parsed = parse(command, args, options);
861
+ const parsed = parse2(command, args, options);
860
862
  const spawned = cp2.spawn(parsed.command, parsed.args, parsed.options);
861
863
  enoent.hookChildProcess(spawned, parsed);
862
864
  return spawned;
863
865
  }
864
866
  function spawnSync3(command, args, options) {
865
- const parsed = parse(command, args, options);
867
+ const parsed = parse2(command, args, options);
866
868
  const result = cp2.spawnSync(parsed.command, parsed.args, parsed.options);
867
869
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
868
870
  return result;
@@ -870,7 +872,7 @@ var require_cross_spawn = __commonJS({
870
872
  module.exports = spawn9;
871
873
  module.exports.spawn = spawn9;
872
874
  module.exports.sync = spawnSync3;
873
- module.exports._parse = parse;
875
+ module.exports._parse = parse2;
874
876
  module.exports._enoent = enoent;
875
877
  }
876
878
  });
@@ -4480,21 +4482,21 @@ var require_fast_uri2 = __commonJS({
4480
4482
  normalizeString(uri, options);
4481
4483
  } else if (typeof uri === "object") {
4482
4484
  uri = /** @type {T} */
4483
- parse(serialize(uri, options), options);
4485
+ parse2(serialize(uri, options), options);
4484
4486
  }
4485
4487
  return uri;
4486
4488
  }
4487
4489
  function resolve7(baseURI, relativeURI, options) {
4488
4490
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
4489
- const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
4491
+ const resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true);
4490
4492
  schemelessOptions.skipEscape = true;
4491
4493
  return serialize(resolved, schemelessOptions);
4492
4494
  }
4493
4495
  function resolveComponent(base, relative3, options, skipNormalization) {
4494
4496
  const target = {};
4495
4497
  if (!skipNormalization) {
4496
- base = parse(serialize(base, options), options);
4497
- relative3 = parse(serialize(relative3, options), options);
4498
+ base = parse2(serialize(base, options), options);
4499
+ relative3 = parse2(serialize(relative3, options), options);
4498
4500
  }
4499
4501
  options = options || {};
4500
4502
  if (!options.tolerant && relative3.scheme) {
@@ -4717,7 +4719,7 @@ var require_fast_uri2 = __commonJS({
4717
4719
  }
4718
4720
  return { parsed, malformedAuthorityOrPort };
4719
4721
  }
4720
- function parse(uri, opts) {
4722
+ function parse2(uri, opts) {
4721
4723
  return parseWithStatus(uri, opts).parsed;
4722
4724
  }
4723
4725
  function normalizeString(uri, opts) {
@@ -4746,7 +4748,7 @@ var require_fast_uri2 = __commonJS({
4746
4748
  resolveComponent,
4747
4749
  equal,
4748
4750
  serialize,
4749
- parse
4751
+ parse: parse2
4750
4752
  };
4751
4753
  module.exports = fastUri;
4752
4754
  module.exports.default = fastUri;
@@ -8560,6 +8562,7 @@ import { serve } from "@hono/node-server";
8560
8562
  import { Hono as Hono2 } from "hono";
8561
8563
  import { randomUUID as randomUUID13 } from "crypto";
8562
8564
  import { connect } from "net";
8565
+ import { WebSocketServer } from "ws";
8563
8566
 
8564
8567
  // src/managers/github-token-manager.ts
8565
8568
  import path from "path";
@@ -14818,11 +14821,13 @@ function appendCodexAspTranscriptOutput(current, delta, maxChars = MAX_CODEX_ASP
14818
14821
  return truncateCodexAspTranscriptOutput(`${current ?? ""}${delta}`, maxChars);
14819
14822
  }
14820
14823
  function transcriptPatchOperation(change) {
14824
+ const action = change.kind.type;
14825
+ const diff = change.diff.trim().length === 0 ? void 0 : action === "update" ? change.diff : fileContentDiff(change.path, change.diff, action);
14821
14826
  return {
14822
- action: change.kind.type,
14827
+ action,
14823
14828
  path: change.path,
14824
14829
  ...change.kind.type === "update" && change.kind.move_path ? { moveTo: change.kind.move_path } : {},
14825
- ...change.diff.trim().length > 0 ? { diff: change.diff } : {}
14830
+ ...diff ? { diff } : {}
14826
14831
  };
14827
14832
  }
14828
14833
  function transcriptItemsForTurn(turn) {
@@ -17751,20 +17756,20 @@ var OpencodeManager = class extends CodingAgentManager {
17751
17756
  }
17752
17757
  };
17753
17758
  }
17754
- const server2 = await createOpencodeServer({
17759
+ const server3 = await createOpencodeServer({
17755
17760
  port: 0,
17756
17761
  timeout: OPENCODE_SERVER_STARTUP_TIMEOUT_MS,
17757
17762
  config
17758
17763
  });
17759
17764
  const client = createOpencodeClient({
17760
- baseUrl: server2.url,
17765
+ baseUrl: server3.url,
17761
17766
  fetch: opencodeFetch,
17762
17767
  headers: {
17763
17768
  Authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`
17764
17769
  }
17765
17770
  });
17766
17771
  this.client = client;
17767
- this.server = server2;
17772
+ this.server = server3;
17768
17773
  this.serverSubagentMcpParentChatId = subagentMcpParentChatId;
17769
17774
  this.configuredModels = new Set(providerModels);
17770
17775
  const eventController = new AbortController();
@@ -22715,11 +22720,11 @@ var ResourceParseError = class extends McpUiError {
22715
22720
  };
22716
22721
  var ConsentError = class extends McpUiError {
22717
22722
  denied;
22718
- constructor(server2, options) {
22719
- 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}"`;
22720
22725
  super(message, {
22721
22726
  code: options.denied ? "CONSENT_DENIED" : "CONSENT_REQUIRED",
22722
- context: { server: server2 },
22727
+ context: { server: server3 },
22723
22728
  recoveryHint: options.denied ? "The user denied tool access. Start a new session to try again." : "Prompt the user for consent before calling tools."
22724
22729
  });
22725
22730
  this.name = "ConsentError";
@@ -22782,13 +22787,13 @@ function findEmbeddedInputRequest(error) {
22782
22787
  const inputKey = boundedText(details?.inputKey, MAX_INPUT_REQUIRED_DETAIL_LENGTH);
22783
22788
  const inputMethod = boundedText(details?.inputMethod, MAX_INPUT_REQUIRED_DETAIL_LENGTH);
22784
22789
  if (inputKey && inputMethod && INPUT_REQUIRED_METHODS.has(inputMethod)) {
22785
- const server2 = boundedText(details?.server, MAX_INPUT_REQUIRED_SERVER_LENGTH);
22790
+ const server3 = boundedText(details?.server, MAX_INPUT_REQUIRED_SERVER_LENGTH);
22786
22791
  const tool = boundedText(details?.tool, MAX_INPUT_REQUIRED_TARGET_LENGTH);
22787
22792
  const resourceUri = boundedText(details?.resourceUri, MAX_INPUT_REQUIRED_TARGET_LENGTH);
22788
22793
  return {
22789
22794
  inputKey,
22790
22795
  inputMethod,
22791
- ...server2 ? { server: server2 } : {},
22796
+ ...server3 ? { server: server3 } : {},
22792
22797
  ...tool ? { tool } : {},
22793
22798
  ...resourceUri ? { resourceUri } : {}
22794
22799
  };
@@ -22809,15 +22814,15 @@ function findEmbeddedInputRequest(error) {
22809
22814
  function getInputRequiredNeedsUiDetails(error, identity) {
22810
22815
  const request = findEmbeddedInputRequest(error);
22811
22816
  if (!request) return void 0;
22812
- 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";
22813
22818
  const tool = boundedText(request.tool ?? identity.tool, MAX_INPUT_REQUIRED_TARGET_LENGTH);
22814
22819
  const resourceUri = boundedText(request.resourceUri ?? identity.resourceUri, MAX_INPUT_REQUIRED_TARGET_LENGTH);
22815
22820
  const target = resourceUri ? `read resource "${resourceUri}"` : tool ? `call tool "${tool}"` : "complete the MCP request";
22816
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.";
22817
- 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}`;
22818
22823
  return {
22819
22824
  error: INPUT_REQUIRED_NEEDS_UI,
22820
- server: server2,
22825
+ server: server3,
22821
22826
  ...tool ? { tool } : {},
22822
22827
  ...resourceUri ? { resourceUri } : {},
22823
22828
  inputKey: request.inputKey,
@@ -28582,8 +28587,8 @@ var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => {
28582
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;
28583
28588
  var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
28584
28589
  var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
28585
- exports.parse = parse;
28586
- function parse(string3) {
28590
+ exports.parse = parse2;
28591
+ function parse2(string3) {
28587
28592
  if (!string3) throw new TypeError("argument string is required");
28588
28593
  var header = typeof string3 === "object" ? getcontenttype(string3) : string3;
28589
28594
  if (typeof header !== "string") throw new TypeError("argument string is required to be a string");
@@ -31738,21 +31743,21 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31738
31743
  const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils();
31739
31744
  const { SCHEMES, getSchemeHandler } = require_schemes();
31740
31745
  function normalize(uri, options) {
31741
- if (typeof uri === "string") uri = serialize(parse(uri, options), options);
31742
- 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);
31743
31748
  return uri;
31744
31749
  }
31745
31750
  function resolve7(baseURI, relativeURI, options) {
31746
31751
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
31747
- const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
31752
+ const resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true);
31748
31753
  schemelessOptions.skipEscape = true;
31749
31754
  return serialize(resolved, schemelessOptions);
31750
31755
  }
31751
31756
  function resolveComponent(base, relative3, options, skipNormalization) {
31752
31757
  const target = {};
31753
31758
  if (!skipNormalization) {
31754
- base = parse(serialize(base, options), options);
31755
- relative3 = parse(serialize(relative3, options), options);
31759
+ base = parse2(serialize(base, options), options);
31760
+ relative3 = parse2(serialize(relative3, options), options);
31756
31761
  }
31757
31762
  options = options || {};
31758
31763
  if (!options.tolerant && relative3.scheme) {
@@ -31796,7 +31801,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31796
31801
  function equal(uriA, uriB, options) {
31797
31802
  if (typeof uriA === "string") {
31798
31803
  uriA = unescape(uriA);
31799
- uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), {
31804
+ uriA = serialize(normalizeComponentEncoding(parse2(uriA, options), true), {
31800
31805
  ...options,
31801
31806
  skipEscape: true
31802
31807
  });
@@ -31806,7 +31811,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31806
31811
  });
31807
31812
  if (typeof uriB === "string") {
31808
31813
  uriB = unescape(uriB);
31809
- uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), {
31814
+ uriB = serialize(normalizeComponentEncoding(parse2(uriB, options), true), {
31810
31815
  ...options,
31811
31816
  skipEscape: true
31812
31817
  });
@@ -31859,7 +31864,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31859
31864
  return uriTokens.join("");
31860
31865
  }
31861
31866
  const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
31862
- function parse(uri, opts) {
31867
+ function parse2(uri, opts) {
31863
31868
  const options = Object.assign({}, opts);
31864
31869
  const parsed = {
31865
31870
  scheme: void 0,
@@ -31920,7 +31925,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31920
31925
  resolveComponent,
31921
31926
  equal,
31922
31927
  serialize,
31923
- parse
31928
+ parse: parse2
31924
31929
  };
31925
31930
  module.exports = fastUri;
31926
31931
  module.exports.default = fastUri;
@@ -40211,10 +40216,10 @@ var StdioClientTransport = class {
40211
40216
  onclose;
40212
40217
  onerror;
40213
40218
  onmessage;
40214
- constructor(server2) {
40215
- this._serverParams = server2;
40216
- this._readBuffer = new ReadBuffer({ maxBufferSize: server2.maxBufferSize });
40217
- 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();
40218
40223
  }
40219
40224
  /**
40220
40225
  * Starts the server process and prepares to communicate with it.
@@ -44736,14 +44741,14 @@ function messageBytes(message) {
44736
44741
  return void 0;
44737
44742
  }
44738
44743
  }
44739
- function createMcpTraceEvent(direction, server2, transport, message, status, options) {
44744
+ function createMcpTraceEvent(direction, server3, transport, message, status, options) {
44740
44745
  const kind = messageKind(message);
44741
44746
  const bytes = messageBytes(message);
44742
44747
  const event = {
44743
44748
  version: MCP_TRACE_SCHEMA_VERSION,
44744
44749
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
44745
44750
  direction,
44746
- server: redactTraceText(server2, 120),
44751
+ server: redactTraceText(server3, 120),
44747
44752
  transport,
44748
44753
  kind,
44749
44754
  status,
@@ -44845,7 +44850,7 @@ function createMcpTraceWriter(sessionCwd, settings2 = {}, randomSuffix = Math.ra
44845
44850
  function isMcpTraceEnabled(definition, settings2) {
44846
44851
  return definition.trace ?? settings2?.enabled === true;
44847
44852
  }
44848
- function wrapTransportWithMcpTrace(transport, server2, transportKind, observer) {
44853
+ function wrapTransportWithMcpTrace(transport, server3, transportKind, observer) {
44849
44854
  let messageHandler = transport.onmessage;
44850
44855
  let tracedMessageHandler;
44851
44856
  const originalSend = transport.send;
@@ -44865,7 +44870,7 @@ function wrapTransportWithMcpTrace(transport, server2, transportKind, observer)
44865
44870
  set(handler) {
44866
44871
  messageHandler = handler;
44867
44872
  tracedMessageHandler = handler ? ((message, extra) => {
44868
- record3(createMcpTraceEvent("inbound", server2, transportKind, message, "received"));
44873
+ record3(createMcpTraceEvent("inbound", server3, transportKind, message, "received"));
44869
44874
  handler(message, extra);
44870
44875
  }) : void 0;
44871
44876
  }
@@ -44879,13 +44884,13 @@ function wrapTransportWithMcpTrace(transport, server2, transportKind, observer)
44879
44884
  try {
44880
44885
  await originalSend.call(transport, message, options);
44881
44886
  for (const item of messages) {
44882
- record3(createMcpTraceEvent("outbound", server2, transportKind, item, "sent", {
44887
+ record3(createMcpTraceEvent("outbound", server3, transportKind, item, "sent", {
44883
44888
  durationMs: performance.now() - started
44884
44889
  }));
44885
44890
  }
44886
44891
  } catch (error) {
44887
44892
  for (const item of messages) {
44888
- record3(createMcpTraceEvent("outbound", server2, transportKind, item, "error", {
44893
+ record3(createMcpTraceEvent("outbound", server3, transportKind, item, "error", {
44889
44894
  durationMs: performance.now() - started
44890
44895
  }));
44891
44896
  }
@@ -49950,7 +49955,7 @@ async function startUiServer(options) {
49950
49955
  const eventLog = [];
49951
49956
  let latestCheckpointEventId;
49952
49957
  let streamSummary;
49953
- let server2 = null;
49958
+ let server3 = null;
49954
49959
  let sandboxProxyServer = null;
49955
49960
  let sandboxProxyUrl = null;
49956
49961
  let closeTimer = null;
@@ -50111,7 +50116,7 @@ data: ${JSON.stringify(payload)}
50111
50116
  closeTimer = null;
50112
50117
  }
50113
50118
  try {
50114
- server2?.close();
50119
+ server3?.close();
50115
50120
  } catch {
50116
50121
  }
50117
50122
  try {
@@ -50465,7 +50470,7 @@ data: ${JSON.stringify(payload)}
50465
50470
  sendJson(res, status, { ok: false, error: wrapped.message });
50466
50471
  }
50467
50472
  });
50468
- server2 = hostServer;
50473
+ server3 = hostServer;
50469
50474
  if (options.initialResultPromise) {
50470
50475
  options.initialResultPromise.then(
50471
50476
  (result) => pushEvent("tool-result", result),
@@ -55319,11 +55324,11 @@ function normalizeSearchText(value) {
55319
55324
  function tokenize(value) {
55320
55325
  return normalizeSearchText(value).split(/[^a-z0-9]+/).filter(Boolean);
55321
55326
  }
55322
- function prepareToolSearch(tool, server2, keywords) {
55327
+ function prepareToolSearch(tool, server3, keywords) {
55323
55328
  const fields = {
55324
55329
  name: normalizeSearchText(tool.name),
55325
55330
  originalName: normalizeSearchText(tool.originalName),
55326
- server: normalizeSearchText(server2),
55331
+ server: normalizeSearchText(server3),
55327
55332
  description: normalizeSearchText(tool.description)
55328
55333
  };
55329
55334
  const preparedFields = Object.entries(fields).map(([field, value]) => [field, value, tokenize(value)]);
@@ -55429,14 +55434,14 @@ function getPreparedTools(state, serverName, metadata, definition, globalPrefix,
55429
55434
  }
55430
55435
  return prepared;
55431
55436
  }
55432
- function rankToolMatches(state, query2, server2, includeKeywords = true) {
55437
+ function rankToolMatches(state, query2, server3, includeKeywords = true) {
55433
55438
  const matches = [];
55434
55439
  const normalizedQuery = normalizeSearchText(query2).trim();
55435
55440
  const queryTokens = tokenize(query2);
55436
55441
  if (queryTokens.length === 0) return matches;
55437
55442
  const globalPrefix = state.config.settings?.toolPrefix ?? "server";
55438
55443
  for (const [serverName, metadata] of state.toolMetadata.entries()) {
55439
- if (server2 && serverName !== server2) continue;
55444
+ if (server3 && serverName !== server3) continue;
55440
55445
  const definition = state.config.mcpServers[serverName];
55441
55446
  if (isServerDisabled(definition)) continue;
55442
55447
  if (isServerInActiveFailureBackoff(state, serverName)) continue;
@@ -55461,7 +55466,7 @@ function paginate(items, offset, limit) {
55461
55466
  };
55462
55467
  }
55463
55468
  function rankSuggestions(state, name, limit) {
55464
- 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));
55465
55470
  const query2 = stripped[0] ?? name;
55466
55471
  return rankToolMatches(state, query2, void 0, false).slice(0, limit).map((match) => match.tool.name);
55467
55472
  }
@@ -55495,9 +55500,9 @@ function getToolMatches(metadata, toolName, exact) {
55495
55500
  }
55496
55501
  function getEnabledToolMatches(state, toolName, exact) {
55497
55502
  const matches = [];
55498
- for (const [server2, metadata] of state.toolMetadata) {
55499
- if (isServerDisabled(state.config.mcpServers[server2])) continue;
55500
- 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 });
55501
55506
  }
55502
55507
  return matches;
55503
55508
  }
@@ -55751,34 +55756,34 @@ function executeStatus(state) {
55751
55756
  let text = `MCP: ${connectedCount}/${enabledServers.length} servers, ${totalTools} tools`;
55752
55757
  if (disabledCount > 0) text += ` (${disabledCount} disabled)`;
55753
55758
  text += "\n\n";
55754
- for (const server2 of servers) {
55755
- if (server2.disabled) {
55756
- text += `\u2298 ${server2.name} (disabled)
55759
+ for (const server3 of servers) {
55760
+ if (server3.disabled) {
55761
+ text += `\u2298 ${server3.name} (disabled)
55757
55762
  `;
55758
55763
  continue;
55759
55764
  }
55760
- if (server2.status === "connected") {
55761
- 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";
55762
- 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})
55763
55768
  `;
55764
55769
  continue;
55765
55770
  }
55766
- if (server2.status === "needs-auth") {
55767
- text += `\u26A0 ${server2.name} (needs auth)
55771
+ if (server3.status === "needs-auth") {
55772
+ text += `\u26A0 ${server3.name} (needs auth)
55768
55773
  `;
55769
55774
  continue;
55770
55775
  }
55771
- if (server2.status === "cached") {
55772
- 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)
55773
55778
  `;
55774
55779
  continue;
55775
55780
  }
55776
- if (server2.status === "failed") {
55777
- 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)
55778
55783
  `;
55779
55784
  continue;
55780
55785
  }
55781
- text += `\u25CB ${server2.name} (not listening; disconnected)
55786
+ text += `\u25CB ${server3.name} (not listening; disconnected)
55782
55787
  `;
55783
55788
  }
55784
55789
  const directToolsFrozen = state.config.settings?.freezeDirectTools === true;
@@ -55877,18 +55882,18 @@ function executeDescribe(state, toolName) {
55877
55882
  let disabledMatch;
55878
55883
  let failedMatch;
55879
55884
  if (!toolMeta) {
55880
- for (const [server2, metadata] of state.toolMetadata.entries()) {
55885
+ for (const [server3, metadata] of state.toolMetadata.entries()) {
55881
55886
  const found = findToolByName(metadata, toolName);
55882
55887
  if (!found) continue;
55883
- if (isServerDisabled(state.config.mcpServers[server2])) {
55884
- disabledMatch ??= server2;
55888
+ if (isServerDisabled(state.config.mcpServers[server3])) {
55889
+ disabledMatch ??= server3;
55885
55890
  continue;
55886
55891
  }
55887
- if (isServerInActiveFailureBackoff(state, server2)) {
55888
- failedMatch ??= server2;
55892
+ if (isServerInActiveFailureBackoff(state, server3)) {
55893
+ failedMatch ??= server3;
55889
55894
  continue;
55890
55895
  }
55891
- serverName = server2;
55896
+ serverName = server3;
55892
55897
  toolMeta = found;
55893
55898
  break;
55894
55899
  }
@@ -55934,10 +55939,10 @@ No parameters defined.`;
55934
55939
  details: { mode: "describe", tool: toolMeta, server: serverName }
55935
55940
  };
55936
55941
  }
55937
- function executeSearch(state, query2, regex, server2, includeSchemas, limit = 12, offset = 0) {
55942
+ function executeSearch(state, query2, regex, server3, includeSchemas, limit = 12, offset = 0) {
55938
55943
  const showSchemas = includeSchemas !== false;
55939
- if (server2 && isServerDisabled(state.config.mcpServers[server2])) return disabledResult("search", server2);
55940
- 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);
55941
55946
  let matches;
55942
55947
  if (regex) {
55943
55948
  let pattern;
@@ -55978,27 +55983,27 @@ function executeSearch(state, query2, regex, server2, includeSchemas, limit = 12
55978
55983
  const definition = state.config.mcpServers[serverName];
55979
55984
  if (isServerDisabled(definition)) continue;
55980
55985
  if (isServerInActiveFailureBackoff(state, serverName)) continue;
55981
- if (server2 && serverName !== server2) continue;
55986
+ if (server3 && serverName !== server3) continue;
55982
55987
  for (const tool of metadata) {
55983
55988
  const matched = pattern.test(tool.name) || pattern.test(tool.description) || resolveSearchKeywords(definition, tool.originalName, serverName, globalPrefix).some((keyword) => pattern.test(keyword));
55984
55989
  if (matched) matches.push({ server: serverName, tool, score: 0 });
55985
55990
  }
55986
55991
  }
55987
55992
  } else if (query2.trim().length === 0) {
55988
- if (!server2) {
55993
+ if (!server3) {
55989
55994
  return {
55990
55995
  content: [{ type: "text", text: "Search query cannot be empty" }],
55991
55996
  details: { mode: "search", error: "empty_query" }
55992
55997
  };
55993
55998
  }
55994
- 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));
55995
56000
  } else {
55996
- matches = rankToolMatches(state, query2, server2);
56001
+ matches = rankToolMatches(state, query2, server3);
55997
56002
  }
55998
56003
  const page2 = paginate(matches, offset, limit);
55999
56004
  if (page2.total === 0) {
56000
- 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));
56001
- 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}"`;
56002
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.` : "";
56003
56008
  return {
56004
56009
  content: [{ type: "text", text: `${msg}${connectingMessage}` }],
@@ -56057,25 +56062,25 @@ ${page2.items.length} of ${page2.total} \u2014 offset: ${page2.nextOffset} for m
56057
56062
  }
56058
56063
  };
56059
56064
  }
56060
- function executeList(state, server2) {
56061
- const definition = state.config.mcpServers[server2];
56065
+ function executeList(state, server3) {
56066
+ const definition = state.config.mcpServers[server3];
56062
56067
  if (!definition) {
56063
56068
  return {
56064
- content: [{ type: "text", text: `Server "${server2}" not found. Use mcp({}) to see available servers.` }],
56065
- 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" }
56066
56071
  };
56067
56072
  }
56068
- if (isServerDisabled(definition)) return disabledResult("list", server2);
56069
- const metadata = state.toolMetadata.get(server2);
56073
+ if (isServerDisabled(definition)) return disabledResult("list", server3);
56074
+ const metadata = state.toolMetadata.get(server3);
56070
56075
  const toolNames = metadata?.map((m) => m.name) ?? [];
56071
- const connection = state.manager.getConnection(server2);
56072
- if (isServerInActiveFailureBackoff(state, server2)) {
56076
+ const connection = state.manager.getConnection(server3);
56077
+ if (isServerInActiveFailureBackoff(state, server3)) {
56073
56078
  return {
56074
- ...serverBackoffResult(state, "list", server2),
56075
- 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" }
56076
56081
  };
56077
56082
  }
56078
- const instructions = state.serverInstructions.get(server2);
56083
+ const instructions = state.serverInstructions.get(server3);
56079
56084
  let instructionsText = "";
56080
56085
  if (instructions) {
56081
56086
  const preview = truncateAtWord(instructions, INSTRUCTIONS_PREVIEW_LENGTH);
@@ -56085,36 +56090,36 @@ Server instructions:
56085
56090
  ${preview}`;
56086
56091
  if (preview !== instructions) {
56087
56092
  instructionsText += `
56088
- Use mcp({ instructions: "${server2}" }) for the full text.`;
56093
+ Use mcp({ instructions: "${server3}" }) for the full text.`;
56089
56094
  }
56090
56095
  }
56091
56096
  if (toolNames.length === 0) {
56092
56097
  if (connection?.status === "connected") {
56093
56098
  return {
56094
- content: [{ type: "text", text: `Server "${server2}" has no tools.${instructionsText}` }],
56095
- 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) }
56096
56101
  };
56097
56102
  }
56098
56103
  if (metadata !== void 0) {
56099
56104
  return {
56100
- content: [{ type: "text", text: `Server "${server2}" has no cached tools (not connected).${instructionsText}` }],
56101
- 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) }
56102
56107
  };
56103
56108
  }
56104
56109
  return {
56105
- content: [{ type: "text", text: `Server "${server2}" is configured but not connected. Use mcp({ connect: "${server2}" }) or /mcp reconnect ${server2} to retry.${instructionsText}` }],
56106
- 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) }
56107
56112
  };
56108
56113
  }
56109
56114
  let cachedNote = "";
56110
56115
  if (connection?.status !== "connected") {
56111
56116
  if (connection?.status === "needs-auth") {
56112
- cachedNote = ` (needs auth \u2014 run mcp({ action: "auth-start", server: "${server2}" }))`;
56117
+ cachedNote = ` (needs auth \u2014 run mcp({ action: "auth-start", server: "${server3}" }))`;
56113
56118
  } else {
56114
- 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)`;
56115
56120
  }
56116
56121
  }
56117
- let text = `${server2} (${toolNames.length} tools${cachedNote}):
56122
+ let text = `${server3} (${toolNames.length} tools${cachedNote}):
56118
56123
 
56119
56124
  `;
56120
56125
  const descMap = /* @__PURE__ */ new Map();
@@ -56133,38 +56138,38 @@ Use mcp({ instructions: "${server2}" }) for the full text.`;
56133
56138
  text += instructionsText;
56134
56139
  return {
56135
56140
  content: [{ type: "text", text: text.trim() }],
56136
- 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) }
56137
56142
  };
56138
56143
  }
56139
- function executeInstructions(state, server2) {
56140
- const definition = state.config.mcpServers[server2];
56144
+ function executeInstructions(state, server3) {
56145
+ const definition = state.config.mcpServers[server3];
56141
56146
  if (!definition) {
56142
56147
  return {
56143
- content: [{ type: "text", text: `Server "${server2}" not found. Use mcp({}) to see available servers.` }],
56144
- 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" }
56145
56150
  };
56146
56151
  }
56147
- if (isServerDisabled(definition)) return disabledResult("instructions", server2);
56148
- if (isServerInActiveFailureBackoff(state, server2)) return serverBackoffResult(state, "instructions", server2);
56149
- 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);
56150
56155
  if (instructions) {
56151
56156
  return {
56152
- content: [{ type: "text", text: `${server2} instructions:
56157
+ content: [{ type: "text", text: `${server3} instructions:
56153
56158
 
56154
56159
  ${instructions}` }],
56155
- details: { mode: "instructions", server: server2, length: instructions.length }
56160
+ details: { mode: "instructions", server: server3, length: instructions.length }
56156
56161
  };
56157
56162
  }
56158
- const connection = state.manager.getConnection(server2);
56163
+ const connection = state.manager.getConnection(server3);
56159
56164
  if (connection?.status === "connected") {
56160
56165
  return {
56161
- content: [{ type: "text", text: `Server "${server2}" does not provide instructions.` }],
56162
- 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" }
56163
56168
  };
56164
56169
  }
56165
56170
  return {
56166
- content: [{ type: "text", text: `No instructions cached for "${server2}". Use mcp({ connect: "${server2}" }) to connect and refresh.` }],
56167
- 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" }
56168
56173
  };
56169
56174
  }
56170
56175
  async function executeConnect(state, serverName, signal) {
@@ -56275,26 +56280,26 @@ async function executeCall(state, toolName, args, serverOverride, getPiTools, si
56275
56280
  return ambiguousToolResult("call", toolName);
56276
56281
  }
56277
56282
  let disabledMatch;
56278
- for (const [server2, metadata] of state.toolMetadata.entries()) {
56283
+ for (const [server3, metadata] of state.toolMetadata.entries()) {
56279
56284
  const found = metadata.find((tool) => tool.name === toolName);
56280
56285
  if (!found) continue;
56281
- if (isServerDisabled(state.config.mcpServers[server2])) {
56282
- disabledMatch ??= { serverName: server2, toolMeta: found };
56286
+ if (isServerDisabled(state.config.mcpServers[server3])) {
56287
+ disabledMatch ??= { serverName: server3, toolMeta: found };
56283
56288
  continue;
56284
56289
  }
56285
- serverName = server2;
56290
+ serverName = server3;
56286
56291
  toolMeta = found;
56287
56292
  break;
56288
56293
  }
56289
56294
  if (!toolMeta && !disabledMatch) {
56290
- for (const [server2, metadata] of state.toolMetadata.entries()) {
56295
+ for (const [server3, metadata] of state.toolMetadata.entries()) {
56291
56296
  const found = findToolByName(metadata, toolName);
56292
56297
  if (!found) continue;
56293
- if (isServerDisabled(state.config.mcpServers[server2])) {
56294
- disabledMatch ??= { serverName: server2, toolMeta: found };
56298
+ if (isServerDisabled(state.config.mcpServers[server3])) {
56299
+ disabledMatch ??= { serverName: server3, toolMeta: found };
56295
56300
  continue;
56296
56301
  }
56297
- serverName = server2;
56302
+ serverName = server3;
56298
56303
  toolMeta = found;
56299
56304
  break;
56300
56305
  }
@@ -57023,11 +57028,11 @@ function collectCollapsedResultLines(content, maxLines, maxChars) {
57023
57028
  }
57024
57029
  function formatMcpToolResultIdentity(details) {
57025
57030
  if (details?.mode !== "call") return null;
57026
- const server2 = typeof details.server === "string" ? details.server : typeof details.hintServer === "string" ? details.hintServer : null;
57027
- if (!server2) return null;
57028
- if (typeof details.tool === "string") return `MCP ${server2}/${details.tool}`;
57029
- if (typeof details.resourceUri === "string") return `MCP ${server2} resource ${details.resourceUri}`;
57030
- 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}`;
57031
57036
  return null;
57032
57037
  }
57033
57038
  function formatMcpToolResultLines(result, expanded, maxCollapsedLines = DEFAULT_BOXED_COLLAPSED_LINES, maxCollapsedChars = DEFAULT_MAX_COLLAPSED_CHARS) {
@@ -57198,10 +57203,10 @@ async function runMcpScript(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_
57198
57203
  if (query2.trim() === "") {
57199
57204
  return { items: [], total: 0, hasMore: false, nextOffset: null };
57200
57205
  }
57201
- const server2 = typeof input?.server === "string" ? input.server : void 0;
57206
+ const server3 = typeof input?.server === "string" ? input.server : void 0;
57202
57207
  const limit = typeof input?.limit === "number" ? input.limit : 12;
57203
57208
  const offset = typeof input?.offset === "number" ? input.offset : 0;
57204
- const page2 = paginate(rankToolMatches(state, query2, server2), offset, limit);
57209
+ const page2 = paginate(rankToolMatches(state, query2, server3), offset, limit);
57205
57210
  return {
57206
57211
  ...page2,
57207
57212
  items: page2.items.map(({ server: matchServer, tool, score }) => ({
@@ -57224,15 +57229,15 @@ async function runMcpScript(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_
57224
57229
  const path7 = typeof input?.path === "string" ? input.path : "";
57225
57230
  let error;
57226
57231
  try {
57227
- for (const [server2, metadata] of state.toolMetadata) {
57228
- if (isServerInActiveFailureBackoff(state, server2)) continue;
57232
+ for (const [server3, metadata] of state.toolMetadata) {
57233
+ if (isServerInActiveFailureBackoff(state, server3)) continue;
57229
57234
  const tool = findToolByName(metadata, path7);
57230
57235
  if (!tool) continue;
57231
57236
  const inputTypeScript = tool.inputSchema ? renderTsShape(tool.inputSchema) ?? formatSchema(tool.inputSchema) : null;
57232
57237
  return {
57233
57238
  path: tool.name,
57234
57239
  name: tool.originalName,
57235
- server: server2,
57240
+ server: server3,
57236
57241
  ...tool.description ? { description: tool.description } : {},
57237
57242
  ...inputTypeScript ? { inputTypeScript } : {}
57238
57243
  };
@@ -59069,8 +59074,8 @@ function mcpNameFromToolCall(message) {
59069
59074
  const parsedName = parseMcpToolName(message.tool);
59070
59075
  if (parsedName) return parsedName.server;
59071
59076
  if (message.tool.startsWith("mcp.")) {
59072
- const [server2, ...toolParts] = message.tool.slice("mcp.".length).split(".");
59073
- 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;
59074
59079
  }
59075
59080
  return NON_MCP_SERVERS.has(message.server) ? null : message.server;
59076
59081
  }
@@ -59286,9 +59291,9 @@ function calculateCumulativeTokenUsageDelta(current, previous) {
59286
59291
  cacheWriteInputTokens: current.cacheWriteInputTokens - previous.cacheWriteInputTokens
59287
59292
  };
59288
59293
  }
59289
- function recordParsedTokenUsage(event, harness, parse) {
59294
+ function recordParsedTokenUsage(event, harness, parse2) {
59290
59295
  if (event.type !== "usage-updated") return void 0;
59291
- const usage = parse(event.payload);
59296
+ const usage = parse2(event.payload);
59292
59297
  if (!usage) return void 0;
59293
59298
  return {
59294
59299
  records: [{
@@ -62421,7 +62426,7 @@ var RepoFileService = class {
62421
62426
 
62422
62427
  // src/v1-routes.ts
62423
62428
  import { Hono } from "hono";
62424
- import { z as z4 } from "zod";
62429
+ import { z as z5 } from "zod";
62425
62430
  import { readdir as readdir11, stat as stat7, readFile as readFile23 } from "fs/promises";
62426
62431
  import { join as join39, resolve as resolve5 } from "path";
62427
62432
 
@@ -62813,9 +62818,18 @@ ${combinedScript}` : combinedScript;
62813
62818
  import { randomUUID as randomUUID12 } from "crypto";
62814
62819
  import { existsSync as existsSync20 } from "fs";
62815
62820
  import { spawn as spawn8 } from "node-pty";
62821
+ import { z as z4 } from "zod";
62816
62822
  var MAX_REPLAY_CHARS = 1024 * 1024;
62817
62823
  var MAX_TERMINAL_SESSIONS = 8;
62818
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
+ ]);
62819
62833
  var TerminalService = class {
62820
62834
  sessions = /* @__PURE__ */ new Map();
62821
62835
  nextTitleNumber = 1;
@@ -62891,6 +62905,12 @@ var TerminalService = class {
62891
62905
  }
62892
62906
  return true;
62893
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
+ }
62894
62914
  resize(id, cols, rows) {
62895
62915
  const session = this.sessions.get(id);
62896
62916
  if (!session || session.exited) return false;
@@ -62929,32 +62949,28 @@ var TerminalService = class {
62929
62949
  var terminalService = new TerminalService();
62930
62950
 
62931
62951
  // src/v1-routes.ts
62932
- var createPreviewSchema = z4.object({
62933
- port: z4.number().int().min(1).max(65535),
62934
- publicUrl: z4.string().min(1)
62935
- });
62936
- var terminalSizeSchema = z4.object({
62937
- cols: z4.number().int().min(2).max(500),
62938
- 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)
62939
62955
  });
62940
- var writeTerminalSessionSchema = z4.object({
62941
- data: z4.string().max(64 * 1024),
62942
- generation: z4.number().int().nonnegative(),
62943
- 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()
62944
62960
  });
62945
- var respondToolInputSchema = z4.object({
62946
- requestId: z4.string().min(1),
62947
- selectionId: z4.string().min(1)
62961
+ var respondToolInputSchema = z5.object({
62962
+ requestId: z5.string().min(1),
62963
+ selectionId: z5.string().min(1)
62948
62964
  });
62949
- var updateGoalSchema = z4.object({
62950
- objective: z4.string().trim().min(1).max(MAX_CODEX_GOAL_OBJECTIVE_CHARS).optional(),
62951
- 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()
62952
62968
  }).refine((body) => body.objective !== void 0 || body.status !== void 0, {
62953
62969
  message: "Goal objective or status required"
62954
62970
  });
62955
- var updateTextFileSchema = (maxLength) => z4.object({
62956
- content: z4.string().max(maxLength),
62957
- 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}$/)
62958
62974
  });
62959
62975
  function jsonError(message, details) {
62960
62976
  return { error: message, details };
@@ -63004,11 +63020,11 @@ function createV1Routes(deps) {
63004
63020
  const app2 = new Hono();
63005
63021
  app2.post("/pull-requests/check", async (c) => {
63006
63022
  if (c.req.header("content-type")?.includes("application/json")) {
63007
- const result = z4.object({
63008
- toolName: z4.string(),
63009
- toolInput: z4.unknown(),
63010
- output: z4.unknown(),
63011
- success: z4.boolean()
63023
+ const result = z5.object({
63024
+ toolName: z5.string(),
63025
+ toolInput: z5.unknown(),
63026
+ output: z5.unknown(),
63027
+ success: z5.boolean()
63012
63028
  }).safeParse(await c.req.json().catch(() => null));
63013
63029
  if (!result.success) return c.json({ error: "Invalid PR tool result" }, 400);
63014
63030
  await pullRequestCheckService.onToolResult(result.data);
@@ -63237,7 +63253,7 @@ function createV1Routes(deps) {
63237
63253
  const chat = await deps.chatService.updateDisplayName(c.req.param("chatId"), body.displayName);
63238
63254
  return c.json({ chat });
63239
63255
  } catch (error) {
63240
- if (error instanceof z4.ZodError) {
63256
+ if (error instanceof z5.ZodError) {
63241
63257
  return c.json(jsonError(error.issues[0]?.message || "Invalid tab name"), 400);
63242
63258
  }
63243
63259
  if (error instanceof ChatNotFoundError) {
@@ -63342,7 +63358,7 @@ function createV1Routes(deps) {
63342
63358
  const result = await deps.chatService.updateGoal(c.req.param("chatId"), body);
63343
63359
  return c.json(result);
63344
63360
  } catch (error) {
63345
- if (error instanceof z4.ZodError) {
63361
+ if (error instanceof z5.ZodError) {
63346
63362
  return c.json(jsonError(error.issues[0]?.message || "Invalid goal update"), 400);
63347
63363
  }
63348
63364
  if (error instanceof ChatNotFoundError) {
@@ -63964,6 +63980,104 @@ data: ${JSON.stringify("Terminal session not found")}
63964
63980
  return app2;
63965
63981
  }
63966
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
+
63967
64081
  // src/services/heartbeat-service.ts
63968
64082
  function unrefTimer(timer) {
63969
64083
  if (typeof timer === "object" && timer !== null && "unref" in timer && typeof timer.unref === "function") {
@@ -64050,7 +64164,7 @@ function startGitPushTracker() {
64050
64164
  async function listen() {
64051
64165
  await mkdir23(ENGINE_DIR2, { recursive: true });
64052
64166
  await rm5(SOCKET_PATH, { force: true });
64053
- const server2 = createServer2((socket) => {
64167
+ const server3 = createServer2((socket) => {
64054
64168
  let buffered = "";
64055
64169
  let ignored = false;
64056
64170
  let push = false;
@@ -64092,10 +64206,10 @@ async function listen() {
64092
64206
  });
64093
64207
  });
64094
64208
  await new Promise((resolve7, reject) => {
64095
- server2.once("error", reject);
64096
- server2.listen(SOCKET_PATH, () => {
64097
- server2.off("error", reject);
64098
- 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));
64099
64213
  resolve7();
64100
64214
  });
64101
64215
  });
@@ -64480,7 +64594,9 @@ async function sleep2() {
64480
64594
  await engineLogger.flush();
64481
64595
  return createSuccessResult({ state: lifecycle.state, workspaceId: lifecycle.workspaceId });
64482
64596
  }
64483
- serve(
64597
+ var terminalSockets = new WebSocketServer({ noServer: true });
64598
+ var TERMINAL_SOCKET_PATH = /^\/terminal\/sessions\/([^/]+)\/ws$/;
64599
+ var server2 = serve(
64484
64600
  {
64485
64601
  fetch: app.fetch,
64486
64602
  port
@@ -64499,6 +64615,17 @@ serve(
64499
64615
  }
64500
64616
  }
64501
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
+ });
64502
64629
  /*! Bundled license information:
64503
64630
 
64504
64631
  @modelcontextprotocol/client/dist/src-D_zzAWoS.mjs: