replicas-engine 0.1.964 → 0.1.967

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-ZRCBGXER.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-MHGSYSA2.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-YIKQKQQI.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-JH2UMGOT.js";
83
83
  import {
84
84
  AspClient,
85
85
  getCodexModelProvider
86
- } from "./chunk-TDVZOQMQ.js";
86
+ } from "./chunk-DMGFNUGG.js";
87
87
  import {
88
88
  SUBPROCESS_MAX_BUFFER,
89
89
  execAsync,
90
90
  execFileAsync
91
- } from "./chunk-33CDUZ6W.js";
91
+ } from "./chunk-EUMRQH4J.js";
92
92
  import {
93
93
  isRecord as isRecord2
94
94
  } from "./chunk-UZSNFLDQ.js";
@@ -110,23 +110,10 @@ import {
110
110
  CHAT_INTERRUPTED_EVENT_TYPE,
111
111
  CLAUDE_AUTH_ENV_KEYS,
112
112
  CLAUDE_AUTH_ENV_KEYS_BY_METHOD,
113
- CLAUDE_FABLE_5_1_BEDROCK_MODEL,
114
- CLAUDE_FABLE_5_1_MODEL,
115
- CLAUDE_FABLE_5_BEDROCK_MODEL,
116
- CLAUDE_FABLE_5_MODEL,
117
113
  CLAUDE_HAIKU_4_5_BEDROCK_MODEL,
118
- CLAUDE_HAIKU_4_5_MODEL,
119
114
  CLAUDE_OPUS_4_8_BEDROCK_MODEL,
120
- CLAUDE_OPUS_4_8_MODEL,
121
- CLAUDE_OPUS_5_5_BEDROCK_MODEL,
122
- CLAUDE_OPUS_5_5_MODEL,
123
- CLAUDE_OPUS_5_BEDROCK_MODEL,
124
- CLAUDE_OPUS_5_MODEL,
125
115
  CLAUDE_PARTIAL_MESSAGE_EVENT_TYPE,
126
- CLAUDE_SONNET_5_5_BEDROCK_MODEL,
127
- CLAUDE_SONNET_5_5_MODEL,
128
116
  CLAUDE_SONNET_5_BEDROCK_MODEL,
129
- CLAUDE_SONNET_5_MODEL,
130
117
  CODEX_ASP_ITEM_ID_PAYLOAD_KEY,
131
118
  CODEX_HISTORY_FORMAT_EVENT_TYPE,
132
119
  CODEX_QUOTA_STATUS_EVENT_TYPE,
@@ -179,6 +166,7 @@ import {
179
166
  SUBAGENT_MCP_SERVER_NAME,
180
167
  SUBAGENT_MCP_TOOLS,
181
168
  SUBAGENT_MCP_TOOL_NAMES,
169
+ TERMINAL_RTC_ICE_SERVER,
182
170
  TIMEOUT,
183
171
  TOKEN_USAGE_PATH,
184
172
  TaskAccumulator,
@@ -311,6 +299,7 @@ import {
311
299
  shouldRefreshPullRequests,
312
300
  spawnSubagentRequestSchema,
313
301
  stripAgentDiagnosticErrors,
302
+ toClaudeCodeModel,
314
303
  updateChatDisplayNameRequestSchema,
315
304
  waitSubagentRequestSchema,
316
305
  withTimeout,
@@ -318,7 +307,7 @@ import {
318
307
  workspaceCredentialProviderSchema,
319
308
  workspaceTokenRequestSchema,
320
309
  workspaceTokenResponseSchema
321
- } from "./chunk-MEN62XEB.js";
310
+ } from "./chunk-4KMPRAV6.js";
322
311
  import {
323
312
  cloneMcpConfig,
324
313
  ensureCompatibilityImports,
@@ -776,7 +765,7 @@ var require_parse = __commonJS({
776
765
  }
777
766
  return parsed;
778
767
  }
779
- function parse(command, args, options) {
768
+ function parse2(command, args, options) {
780
769
  if (args && !Array.isArray(args)) {
781
770
  options = args;
782
771
  args = null;
@@ -795,7 +784,7 @@ var require_parse = __commonJS({
795
784
  };
796
785
  return options.shell ? parsed : parseNonShell(parsed);
797
786
  }
798
- module.exports = parse;
787
+ module.exports = parse2;
799
788
  }
800
789
  });
801
790
 
@@ -854,16 +843,16 @@ var require_cross_spawn = __commonJS({
854
843
  "../node_modules/.bun/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(exports, module) {
855
844
  "use strict";
856
845
  var cp2 = __require("child_process");
857
- var parse = require_parse();
846
+ var parse2 = require_parse();
858
847
  var enoent = require_enoent();
859
848
  function spawn9(command, args, options) {
860
- const parsed = parse(command, args, options);
849
+ const parsed = parse2(command, args, options);
861
850
  const spawned = cp2.spawn(parsed.command, parsed.args, parsed.options);
862
851
  enoent.hookChildProcess(spawned, parsed);
863
852
  return spawned;
864
853
  }
865
854
  function spawnSync3(command, args, options) {
866
- const parsed = parse(command, args, options);
855
+ const parsed = parse2(command, args, options);
867
856
  const result = cp2.spawnSync(parsed.command, parsed.args, parsed.options);
868
857
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
869
858
  return result;
@@ -871,7 +860,7 @@ var require_cross_spawn = __commonJS({
871
860
  module.exports = spawn9;
872
861
  module.exports.spawn = spawn9;
873
862
  module.exports.sync = spawnSync3;
874
- module.exports._parse = parse;
863
+ module.exports._parse = parse2;
875
864
  module.exports._enoent = enoent;
876
865
  }
877
866
  });
@@ -4481,21 +4470,21 @@ var require_fast_uri2 = __commonJS({
4481
4470
  normalizeString(uri, options);
4482
4471
  } else if (typeof uri === "object") {
4483
4472
  uri = /** @type {T} */
4484
- parse(serialize(uri, options), options);
4473
+ parse2(serialize(uri, options), options);
4485
4474
  }
4486
4475
  return uri;
4487
4476
  }
4488
4477
  function resolve7(baseURI, relativeURI, options) {
4489
4478
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
4490
- const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
4479
+ const resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true);
4491
4480
  schemelessOptions.skipEscape = true;
4492
4481
  return serialize(resolved, schemelessOptions);
4493
4482
  }
4494
4483
  function resolveComponent(base, relative3, options, skipNormalization) {
4495
4484
  const target = {};
4496
4485
  if (!skipNormalization) {
4497
- base = parse(serialize(base, options), options);
4498
- relative3 = parse(serialize(relative3, options), options);
4486
+ base = parse2(serialize(base, options), options);
4487
+ relative3 = parse2(serialize(relative3, options), options);
4499
4488
  }
4500
4489
  options = options || {};
4501
4490
  if (!options.tolerant && relative3.scheme) {
@@ -4718,7 +4707,7 @@ var require_fast_uri2 = __commonJS({
4718
4707
  }
4719
4708
  return { parsed, malformedAuthorityOrPort };
4720
4709
  }
4721
- function parse(uri, opts) {
4710
+ function parse2(uri, opts) {
4722
4711
  return parseWithStatus(uri, opts).parsed;
4723
4712
  }
4724
4713
  function normalizeString(uri, opts) {
@@ -4747,7 +4736,7 @@ var require_fast_uri2 = __commonJS({
4747
4736
  resolveComponent,
4748
4737
  equal,
4749
4738
  serialize,
4750
- parse
4739
+ parse: parse2
4751
4740
  };
4752
4741
  module.exports = fastUri;
4753
4742
  module.exports.default = fastUri;
@@ -8561,6 +8550,7 @@ import { serve } from "@hono/node-server";
8561
8550
  import { Hono as Hono2 } from "hono";
8562
8551
  import { randomUUID as randomUUID13 } from "crypto";
8563
8552
  import { connect } from "net";
8553
+ import { WebSocketServer } from "ws";
8564
8554
 
8565
8555
  // src/managers/github-token-manager.ts
8566
8556
  import path from "path";
@@ -13184,31 +13174,6 @@ function supportsClaudeThinkingDisplay(model) {
13184
13174
  const normalized = (normalizeClaudeModel(model) ?? model).toLowerCase();
13185
13175
  return AGENT_MODELS.claude.includes(normalized) || /^claude-(?:opus|sonnet|haiku)-[4-9]/.test(normalized);
13186
13176
  }
13187
- function toClaudeCodeModel(model, bedrock) {
13188
- if (!bedrock) {
13189
- return model;
13190
- }
13191
- switch (normalizeClaudeModel(model)) {
13192
- case CLAUDE_FABLE_5_1_MODEL:
13193
- return CLAUDE_FABLE_5_1_BEDROCK_MODEL;
13194
- case CLAUDE_FABLE_5_MODEL:
13195
- return CLAUDE_FABLE_5_BEDROCK_MODEL;
13196
- case CLAUDE_OPUS_5_5_MODEL:
13197
- return CLAUDE_OPUS_5_5_BEDROCK_MODEL;
13198
- case CLAUDE_OPUS_5_MODEL:
13199
- return CLAUDE_OPUS_5_BEDROCK_MODEL;
13200
- case CLAUDE_OPUS_4_8_MODEL:
13201
- return "opus";
13202
- case CLAUDE_SONNET_5_5_MODEL:
13203
- return CLAUDE_SONNET_5_5_BEDROCK_MODEL;
13204
- case CLAUDE_SONNET_5_MODEL:
13205
- return "sonnet";
13206
- case CLAUDE_HAIKU_4_5_MODEL:
13207
- return "haiku";
13208
- default:
13209
- return model;
13210
- }
13211
- }
13212
13177
  var TOOL_INPUT_HANDLERS = {
13213
13178
  ExitPlanMode: {
13214
13179
  getRequest: () => ({
@@ -17754,20 +17719,20 @@ var OpencodeManager = class extends CodingAgentManager {
17754
17719
  }
17755
17720
  };
17756
17721
  }
17757
- const server2 = await createOpencodeServer({
17722
+ const server3 = await createOpencodeServer({
17758
17723
  port: 0,
17759
17724
  timeout: OPENCODE_SERVER_STARTUP_TIMEOUT_MS,
17760
17725
  config
17761
17726
  });
17762
17727
  const client = createOpencodeClient({
17763
- baseUrl: server2.url,
17728
+ baseUrl: server3.url,
17764
17729
  fetch: opencodeFetch,
17765
17730
  headers: {
17766
17731
  Authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`
17767
17732
  }
17768
17733
  });
17769
17734
  this.client = client;
17770
- this.server = server2;
17735
+ this.server = server3;
17771
17736
  this.serverSubagentMcpParentChatId = subagentMcpParentChatId;
17772
17737
  this.configuredModels = new Set(providerModels);
17773
17738
  const eventController = new AbortController();
@@ -22718,11 +22683,11 @@ var ResourceParseError = class extends McpUiError {
22718
22683
  };
22719
22684
  var ConsentError = class extends McpUiError {
22720
22685
  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}"`;
22686
+ constructor(server3, options) {
22687
+ const message = options.denied ? `Tool calls for "${server3}" were denied for this session` : `Tool call approval required for "${server3}"`;
22723
22688
  super(message, {
22724
22689
  code: options.denied ? "CONSENT_DENIED" : "CONSENT_REQUIRED",
22725
- context: { server: server2 },
22690
+ context: { server: server3 },
22726
22691
  recoveryHint: options.denied ? "The user denied tool access. Start a new session to try again." : "Prompt the user for consent before calling tools."
22727
22692
  });
22728
22693
  this.name = "ConsentError";
@@ -22785,13 +22750,13 @@ function findEmbeddedInputRequest(error) {
22785
22750
  const inputKey = boundedText(details?.inputKey, MAX_INPUT_REQUIRED_DETAIL_LENGTH);
22786
22751
  const inputMethod = boundedText(details?.inputMethod, MAX_INPUT_REQUIRED_DETAIL_LENGTH);
22787
22752
  if (inputKey && inputMethod && INPUT_REQUIRED_METHODS.has(inputMethod)) {
22788
- const server2 = boundedText(details?.server, MAX_INPUT_REQUIRED_SERVER_LENGTH);
22753
+ const server3 = boundedText(details?.server, MAX_INPUT_REQUIRED_SERVER_LENGTH);
22789
22754
  const tool = boundedText(details?.tool, MAX_INPUT_REQUIRED_TARGET_LENGTH);
22790
22755
  const resourceUri = boundedText(details?.resourceUri, MAX_INPUT_REQUIRED_TARGET_LENGTH);
22791
22756
  return {
22792
22757
  inputKey,
22793
22758
  inputMethod,
22794
- ...server2 ? { server: server2 } : {},
22759
+ ...server3 ? { server: server3 } : {},
22795
22760
  ...tool ? { tool } : {},
22796
22761
  ...resourceUri ? { resourceUri } : {}
22797
22762
  };
@@ -22812,15 +22777,15 @@ function findEmbeddedInputRequest(error) {
22812
22777
  function getInputRequiredNeedsUiDetails(error, identity) {
22813
22778
  const request = findEmbeddedInputRequest(error);
22814
22779
  if (!request) return void 0;
22815
- const server2 = boundedText(request.server ?? identity.server, MAX_INPUT_REQUIRED_SERVER_LENGTH) ?? "unknown";
22780
+ const server3 = boundedText(request.server ?? identity.server, MAX_INPUT_REQUIRED_SERVER_LENGTH) ?? "unknown";
22816
22781
  const tool = boundedText(request.tool ?? identity.tool, MAX_INPUT_REQUIRED_TARGET_LENGTH);
22817
22782
  const resourceUri = boundedText(request.resourceUri ?? identity.resourceUri, MAX_INPUT_REQUIRED_TARGET_LENGTH);
22818
22783
  const target = resourceUri ? `read resource "${resourceUri}"` : tool ? `call tool "${tool}"` : "complete the MCP request";
22819
22784
  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}`;
22785
+ const message = `MCP server "${server3}" requested input to ${target}, but this session has no handler for "${request.inputMethod}" (input "${request.inputKey}"). ${guidance}`;
22821
22786
  return {
22822
22787
  error: INPUT_REQUIRED_NEEDS_UI,
22823
- server: server2,
22788
+ server: server3,
22824
22789
  ...tool ? { tool } : {},
22825
22790
  ...resourceUri ? { resourceUri } : {},
22826
22791
  inputKey: request.inputKey,
@@ -28585,8 +28550,8 @@ var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => {
28585
28550
  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
28551
  var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
28587
28552
  var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
28588
- exports.parse = parse;
28589
- function parse(string3) {
28553
+ exports.parse = parse2;
28554
+ function parse2(string3) {
28590
28555
  if (!string3) throw new TypeError("argument string is required");
28591
28556
  var header = typeof string3 === "object" ? getcontenttype(string3) : string3;
28592
28557
  if (typeof header !== "string") throw new TypeError("argument string is required to be a string");
@@ -31741,21 +31706,21 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31741
31706
  const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils();
31742
31707
  const { SCHEMES, getSchemeHandler } = require_schemes();
31743
31708
  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);
31709
+ if (typeof uri === "string") uri = serialize(parse2(uri, options), options);
31710
+ else if (typeof uri === "object") uri = parse2(serialize(uri, options), options);
31746
31711
  return uri;
31747
31712
  }
31748
31713
  function resolve7(baseURI, relativeURI, options) {
31749
31714
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
31750
- const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
31715
+ const resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true);
31751
31716
  schemelessOptions.skipEscape = true;
31752
31717
  return serialize(resolved, schemelessOptions);
31753
31718
  }
31754
31719
  function resolveComponent(base, relative3, options, skipNormalization) {
31755
31720
  const target = {};
31756
31721
  if (!skipNormalization) {
31757
- base = parse(serialize(base, options), options);
31758
- relative3 = parse(serialize(relative3, options), options);
31722
+ base = parse2(serialize(base, options), options);
31723
+ relative3 = parse2(serialize(relative3, options), options);
31759
31724
  }
31760
31725
  options = options || {};
31761
31726
  if (!options.tolerant && relative3.scheme) {
@@ -31799,7 +31764,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31799
31764
  function equal(uriA, uriB, options) {
31800
31765
  if (typeof uriA === "string") {
31801
31766
  uriA = unescape(uriA);
31802
- uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), {
31767
+ uriA = serialize(normalizeComponentEncoding(parse2(uriA, options), true), {
31803
31768
  ...options,
31804
31769
  skipEscape: true
31805
31770
  });
@@ -31809,7 +31774,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31809
31774
  });
31810
31775
  if (typeof uriB === "string") {
31811
31776
  uriB = unescape(uriB);
31812
- uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), {
31777
+ uriB = serialize(normalizeComponentEncoding(parse2(uriB, options), true), {
31813
31778
  ...options,
31814
31779
  skipEscape: true
31815
31780
  });
@@ -31862,7 +31827,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31862
31827
  return uriTokens.join("");
31863
31828
  }
31864
31829
  const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
31865
- function parse(uri, opts) {
31830
+ function parse2(uri, opts) {
31866
31831
  const options = Object.assign({}, opts);
31867
31832
  const parsed = {
31868
31833
  scheme: void 0,
@@ -31923,7 +31888,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
31923
31888
  resolveComponent,
31924
31889
  equal,
31925
31890
  serialize,
31926
- parse
31891
+ parse: parse2
31927
31892
  };
31928
31893
  module.exports = fastUri;
31929
31894
  module.exports.default = fastUri;
@@ -40214,10 +40179,10 @@ var StdioClientTransport = class {
40214
40179
  onclose;
40215
40180
  onerror;
40216
40181
  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();
40182
+ constructor(server3) {
40183
+ this._serverParams = server3;
40184
+ this._readBuffer = new ReadBuffer({ maxBufferSize: server3.maxBufferSize });
40185
+ if (server3.stderr === "pipe" || server3.stderr === "overlapped") this._stderrStream = new PassThrough();
40221
40186
  }
40222
40187
  /**
40223
40188
  * Starts the server process and prepares to communicate with it.
@@ -44739,14 +44704,14 @@ function messageBytes(message) {
44739
44704
  return void 0;
44740
44705
  }
44741
44706
  }
44742
- function createMcpTraceEvent(direction, server2, transport, message, status, options) {
44707
+ function createMcpTraceEvent(direction, server3, transport, message, status, options) {
44743
44708
  const kind = messageKind(message);
44744
44709
  const bytes = messageBytes(message);
44745
44710
  const event = {
44746
44711
  version: MCP_TRACE_SCHEMA_VERSION,
44747
44712
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
44748
44713
  direction,
44749
- server: redactTraceText(server2, 120),
44714
+ server: redactTraceText(server3, 120),
44750
44715
  transport,
44751
44716
  kind,
44752
44717
  status,
@@ -44848,7 +44813,7 @@ function createMcpTraceWriter(sessionCwd, settings2 = {}, randomSuffix = Math.ra
44848
44813
  function isMcpTraceEnabled(definition, settings2) {
44849
44814
  return definition.trace ?? settings2?.enabled === true;
44850
44815
  }
44851
- function wrapTransportWithMcpTrace(transport, server2, transportKind, observer) {
44816
+ function wrapTransportWithMcpTrace(transport, server3, transportKind, observer) {
44852
44817
  let messageHandler = transport.onmessage;
44853
44818
  let tracedMessageHandler;
44854
44819
  const originalSend = transport.send;
@@ -44868,7 +44833,7 @@ function wrapTransportWithMcpTrace(transport, server2, transportKind, observer)
44868
44833
  set(handler) {
44869
44834
  messageHandler = handler;
44870
44835
  tracedMessageHandler = handler ? ((message, extra) => {
44871
- record3(createMcpTraceEvent("inbound", server2, transportKind, message, "received"));
44836
+ record3(createMcpTraceEvent("inbound", server3, transportKind, message, "received"));
44872
44837
  handler(message, extra);
44873
44838
  }) : void 0;
44874
44839
  }
@@ -44882,13 +44847,13 @@ function wrapTransportWithMcpTrace(transport, server2, transportKind, observer)
44882
44847
  try {
44883
44848
  await originalSend.call(transport, message, options);
44884
44849
  for (const item of messages) {
44885
- record3(createMcpTraceEvent("outbound", server2, transportKind, item, "sent", {
44850
+ record3(createMcpTraceEvent("outbound", server3, transportKind, item, "sent", {
44886
44851
  durationMs: performance.now() - started
44887
44852
  }));
44888
44853
  }
44889
44854
  } catch (error) {
44890
44855
  for (const item of messages) {
44891
- record3(createMcpTraceEvent("outbound", server2, transportKind, item, "error", {
44856
+ record3(createMcpTraceEvent("outbound", server3, transportKind, item, "error", {
44892
44857
  durationMs: performance.now() - started
44893
44858
  }));
44894
44859
  }
@@ -49953,7 +49918,7 @@ async function startUiServer(options) {
49953
49918
  const eventLog = [];
49954
49919
  let latestCheckpointEventId;
49955
49920
  let streamSummary;
49956
- let server2 = null;
49921
+ let server3 = null;
49957
49922
  let sandboxProxyServer = null;
49958
49923
  let sandboxProxyUrl = null;
49959
49924
  let closeTimer = null;
@@ -50114,7 +50079,7 @@ data: ${JSON.stringify(payload)}
50114
50079
  closeTimer = null;
50115
50080
  }
50116
50081
  try {
50117
- server2?.close();
50082
+ server3?.close();
50118
50083
  } catch {
50119
50084
  }
50120
50085
  try {
@@ -50468,7 +50433,7 @@ data: ${JSON.stringify(payload)}
50468
50433
  sendJson(res, status, { ok: false, error: wrapped.message });
50469
50434
  }
50470
50435
  });
50471
- server2 = hostServer;
50436
+ server3 = hostServer;
50472
50437
  if (options.initialResultPromise) {
50473
50438
  options.initialResultPromise.then(
50474
50439
  (result) => pushEvent("tool-result", result),
@@ -55322,11 +55287,11 @@ function normalizeSearchText(value) {
55322
55287
  function tokenize(value) {
55323
55288
  return normalizeSearchText(value).split(/[^a-z0-9]+/).filter(Boolean);
55324
55289
  }
55325
- function prepareToolSearch(tool, server2, keywords) {
55290
+ function prepareToolSearch(tool, server3, keywords) {
55326
55291
  const fields = {
55327
55292
  name: normalizeSearchText(tool.name),
55328
55293
  originalName: normalizeSearchText(tool.originalName),
55329
- server: normalizeSearchText(server2),
55294
+ server: normalizeSearchText(server3),
55330
55295
  description: normalizeSearchText(tool.description)
55331
55296
  };
55332
55297
  const preparedFields = Object.entries(fields).map(([field, value]) => [field, value, tokenize(value)]);
@@ -55432,14 +55397,14 @@ function getPreparedTools(state, serverName, metadata, definition, globalPrefix,
55432
55397
  }
55433
55398
  return prepared;
55434
55399
  }
55435
- function rankToolMatches(state, query2, server2, includeKeywords = true) {
55400
+ function rankToolMatches(state, query2, server3, includeKeywords = true) {
55436
55401
  const matches = [];
55437
55402
  const normalizedQuery = normalizeSearchText(query2).trim();
55438
55403
  const queryTokens = tokenize(query2);
55439
55404
  if (queryTokens.length === 0) return matches;
55440
55405
  const globalPrefix = state.config.settings?.toolPrefix ?? "server";
55441
55406
  for (const [serverName, metadata] of state.toolMetadata.entries()) {
55442
- if (server2 && serverName !== server2) continue;
55407
+ if (server3 && serverName !== server3) continue;
55443
55408
  const definition = state.config.mcpServers[serverName];
55444
55409
  if (isServerDisabled(definition)) continue;
55445
55410
  if (isServerInActiveFailureBackoff(state, serverName)) continue;
@@ -55464,7 +55429,7 @@ function paginate(items, offset, limit) {
55464
55429
  };
55465
55430
  }
55466
55431
  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));
55432
+ 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
55433
  const query2 = stripped[0] ?? name;
55469
55434
  return rankToolMatches(state, query2, void 0, false).slice(0, limit).map((match) => match.tool.name);
55470
55435
  }
@@ -55498,9 +55463,9 @@ function getToolMatches(metadata, toolName, exact) {
55498
55463
  }
55499
55464
  function getEnabledToolMatches(state, toolName, exact) {
55500
55465
  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 });
55466
+ for (const [server3, metadata] of state.toolMetadata) {
55467
+ if (isServerDisabled(state.config.mcpServers[server3])) continue;
55468
+ for (const tool of getToolMatches(metadata, toolName, exact)) matches.push({ server: server3, tool });
55504
55469
  }
55505
55470
  return matches;
55506
55471
  }
@@ -55754,34 +55719,34 @@ function executeStatus(state) {
55754
55719
  let text = `MCP: ${connectedCount}/${enabledServers.length} servers, ${totalTools} tools`;
55755
55720
  if (disabledCount > 0) text += ` (${disabledCount} disabled)`;
55756
55721
  text += "\n\n";
55757
- for (const server2 of servers) {
55758
- if (server2.disabled) {
55759
- text += `\u2298 ${server2.name} (disabled)
55722
+ for (const server3 of servers) {
55723
+ if (server3.disabled) {
55724
+ text += `\u2298 ${server3.name} (disabled)
55760
55725
  `;
55761
55726
  continue;
55762
55727
  }
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})
55728
+ if (server3.status === "connected") {
55729
+ 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";
55730
+ text += `\u2713 ${server3.name} (${server3.toolCount} tools${listen2})
55766
55731
  `;
55767
55732
  continue;
55768
55733
  }
55769
- if (server2.status === "needs-auth") {
55770
- text += `\u26A0 ${server2.name} (needs auth)
55734
+ if (server3.status === "needs-auth") {
55735
+ text += `\u26A0 ${server3.name} (needs auth)
55771
55736
  `;
55772
55737
  continue;
55773
55738
  }
55774
- if (server2.status === "cached") {
55775
- text += `\u25CB ${server2.name} (${server2.toolCount} tools, cached; not listening)
55739
+ if (server3.status === "cached") {
55740
+ text += `\u25CB ${server3.name} (${server3.toolCount} tools, cached; not listening)
55776
55741
  `;
55777
55742
  continue;
55778
55743
  }
55779
- if (server2.status === "failed") {
55780
- text += `\u2717 ${server2.name} (failed ${server2.failedAgo ?? 0}s ago)
55744
+ if (server3.status === "failed") {
55745
+ text += `\u2717 ${server3.name} (failed ${server3.failedAgo ?? 0}s ago)
55781
55746
  `;
55782
55747
  continue;
55783
55748
  }
55784
- text += `\u25CB ${server2.name} (not listening; disconnected)
55749
+ text += `\u25CB ${server3.name} (not listening; disconnected)
55785
55750
  `;
55786
55751
  }
55787
55752
  const directToolsFrozen = state.config.settings?.freezeDirectTools === true;
@@ -55880,18 +55845,18 @@ function executeDescribe(state, toolName) {
55880
55845
  let disabledMatch;
55881
55846
  let failedMatch;
55882
55847
  if (!toolMeta) {
55883
- for (const [server2, metadata] of state.toolMetadata.entries()) {
55848
+ for (const [server3, metadata] of state.toolMetadata.entries()) {
55884
55849
  const found = findToolByName(metadata, toolName);
55885
55850
  if (!found) continue;
55886
- if (isServerDisabled(state.config.mcpServers[server2])) {
55887
- disabledMatch ??= server2;
55851
+ if (isServerDisabled(state.config.mcpServers[server3])) {
55852
+ disabledMatch ??= server3;
55888
55853
  continue;
55889
55854
  }
55890
- if (isServerInActiveFailureBackoff(state, server2)) {
55891
- failedMatch ??= server2;
55855
+ if (isServerInActiveFailureBackoff(state, server3)) {
55856
+ failedMatch ??= server3;
55892
55857
  continue;
55893
55858
  }
55894
- serverName = server2;
55859
+ serverName = server3;
55895
55860
  toolMeta = found;
55896
55861
  break;
55897
55862
  }
@@ -55937,10 +55902,10 @@ No parameters defined.`;
55937
55902
  details: { mode: "describe", tool: toolMeta, server: serverName }
55938
55903
  };
55939
55904
  }
55940
- function executeSearch(state, query2, regex, server2, includeSchemas, limit = 12, offset = 0) {
55905
+ function executeSearch(state, query2, regex, server3, includeSchemas, limit = 12, offset = 0) {
55941
55906
  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);
55907
+ if (server3 && isServerDisabled(state.config.mcpServers[server3])) return disabledResult("search", server3);
55908
+ if (server3 && isServerInActiveFailureBackoff(state, server3)) return serverBackoffResult(state, "search", server3);
55944
55909
  let matches;
55945
55910
  if (regex) {
55946
55911
  let pattern;
@@ -55981,27 +55946,27 @@ function executeSearch(state, query2, regex, server2, includeSchemas, limit = 12
55981
55946
  const definition = state.config.mcpServers[serverName];
55982
55947
  if (isServerDisabled(definition)) continue;
55983
55948
  if (isServerInActiveFailureBackoff(state, serverName)) continue;
55984
- if (server2 && serverName !== server2) continue;
55949
+ if (server3 && serverName !== server3) continue;
55985
55950
  for (const tool of metadata) {
55986
55951
  const matched = pattern.test(tool.name) || pattern.test(tool.description) || resolveSearchKeywords(definition, tool.originalName, serverName, globalPrefix).some((keyword) => pattern.test(keyword));
55987
55952
  if (matched) matches.push({ server: serverName, tool, score: 0 });
55988
55953
  }
55989
55954
  }
55990
55955
  } else if (query2.trim().length === 0) {
55991
- if (!server2) {
55956
+ if (!server3) {
55992
55957
  return {
55993
55958
  content: [{ type: "text", text: "Search query cannot be empty" }],
55994
55959
  details: { mode: "search", error: "empty_query" }
55995
55960
  };
55996
55961
  }
55997
- matches = (state.toolMetadata.get(server2) ?? []).map((tool) => ({ server: server2, tool, score: 0 })).sort((a, b) => a.tool.name.localeCompare(b.tool.name));
55962
+ matches = (state.toolMetadata.get(server3) ?? []).map((tool) => ({ server: server3, tool, score: 0 })).sort((a, b) => a.tool.name.localeCompare(b.tool.name));
55998
55963
  } else {
55999
- matches = rankToolMatches(state, query2, server2);
55964
+ matches = rankToolMatches(state, query2, server3);
56000
55965
  }
56001
55966
  const page2 = paginate(matches, offset, limit);
56002
55967
  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}"`;
55968
+ 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));
55969
+ const msg = server3 ? `No tools matching "${query2}" in "${server3}"` : `No tools matching "${query2}"`;
56005
55970
  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
55971
  return {
56007
55972
  content: [{ type: "text", text: `${msg}${connectingMessage}` }],
@@ -56060,25 +56025,25 @@ ${page2.items.length} of ${page2.total} \u2014 offset: ${page2.nextOffset} for m
56060
56025
  }
56061
56026
  };
56062
56027
  }
56063
- function executeList(state, server2) {
56064
- const definition = state.config.mcpServers[server2];
56028
+ function executeList(state, server3) {
56029
+ const definition = state.config.mcpServers[server3];
56065
56030
  if (!definition) {
56066
56031
  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" }
56032
+ content: [{ type: "text", text: `Server "${server3}" not found. Use mcp({}) to see available servers.` }],
56033
+ details: { mode: "list", server: server3, tools: [], count: 0, error: "not_found" }
56069
56034
  };
56070
56035
  }
56071
- if (isServerDisabled(definition)) return disabledResult("list", server2);
56072
- const metadata = state.toolMetadata.get(server2);
56036
+ if (isServerDisabled(definition)) return disabledResult("list", server3);
56037
+ const metadata = state.toolMetadata.get(server3);
56073
56038
  const toolNames = metadata?.map((m) => m.name) ?? [];
56074
- const connection = state.manager.getConnection(server2);
56075
- if (isServerInActiveFailureBackoff(state, server2)) {
56039
+ const connection = state.manager.getConnection(server3);
56040
+ if (isServerInActiveFailureBackoff(state, server3)) {
56076
56041
  return {
56077
- ...serverBackoffResult(state, "list", server2),
56078
- details: { mode: "list", server: server2, tools: [], count: 0, error: "server_backoff" }
56042
+ ...serverBackoffResult(state, "list", server3),
56043
+ details: { mode: "list", server: server3, tools: [], count: 0, error: "server_backoff" }
56079
56044
  };
56080
56045
  }
56081
- const instructions = state.serverInstructions.get(server2);
56046
+ const instructions = state.serverInstructions.get(server3);
56082
56047
  let instructionsText = "";
56083
56048
  if (instructions) {
56084
56049
  const preview = truncateAtWord(instructions, INSTRUCTIONS_PREVIEW_LENGTH);
@@ -56088,36 +56053,36 @@ Server instructions:
56088
56053
  ${preview}`;
56089
56054
  if (preview !== instructions) {
56090
56055
  instructionsText += `
56091
- Use mcp({ instructions: "${server2}" }) for the full text.`;
56056
+ Use mcp({ instructions: "${server3}" }) for the full text.`;
56092
56057
  }
56093
56058
  }
56094
56059
  if (toolNames.length === 0) {
56095
56060
  if (connection?.status === "connected") {
56096
56061
  return {
56097
- content: [{ type: "text", text: `Server "${server2}" has no tools.${instructionsText}` }],
56098
- details: { mode: "list", server: server2, tools: [], count: 0, hasInstructions: Boolean(instructions) }
56062
+ content: [{ type: "text", text: `Server "${server3}" has no tools.${instructionsText}` }],
56063
+ details: { mode: "list", server: server3, tools: [], count: 0, hasInstructions: Boolean(instructions) }
56099
56064
  };
56100
56065
  }
56101
56066
  if (metadata !== void 0) {
56102
56067
  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) }
56068
+ content: [{ type: "text", text: `Server "${server3}" has no cached tools (not connected).${instructionsText}` }],
56069
+ details: { mode: "list", server: server3, tools: [], count: 0, cached: true, hasInstructions: Boolean(instructions) }
56105
56070
  };
56106
56071
  }
56107
56072
  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) }
56073
+ content: [{ type: "text", text: `Server "${server3}" is configured but not connected. Use mcp({ connect: "${server3}" }) or /mcp reconnect ${server3} to retry.${instructionsText}` }],
56074
+ details: { mode: "list", server: server3, tools: [], count: 0, error: "not_connected", hasInstructions: Boolean(instructions) }
56110
56075
  };
56111
56076
  }
56112
56077
  let cachedNote = "";
56113
56078
  if (connection?.status !== "connected") {
56114
56079
  if (connection?.status === "needs-auth") {
56115
- cachedNote = ` (needs auth \u2014 run mcp({ action: "auth-start", server: "${server2}" }))`;
56080
+ cachedNote = ` (needs auth \u2014 run mcp({ action: "auth-start", server: "${server3}" }))`;
56116
56081
  } else {
56117
- cachedNote = ` (lazy: tools from cache, not connected yet \u2014 mcp({ connect: "${server2}" }) to connect)`;
56082
+ cachedNote = ` (lazy: tools from cache, not connected yet \u2014 mcp({ connect: "${server3}" }) to connect)`;
56118
56083
  }
56119
56084
  }
56120
- let text = `${server2} (${toolNames.length} tools${cachedNote}):
56085
+ let text = `${server3} (${toolNames.length} tools${cachedNote}):
56121
56086
 
56122
56087
  `;
56123
56088
  const descMap = /* @__PURE__ */ new Map();
@@ -56136,38 +56101,38 @@ Use mcp({ instructions: "${server2}" }) for the full text.`;
56136
56101
  text += instructionsText;
56137
56102
  return {
56138
56103
  content: [{ type: "text", text: text.trim() }],
56139
- details: { mode: "list", server: server2, tools: toolNames, count: toolNames.length, hasInstructions: Boolean(instructions) }
56104
+ details: { mode: "list", server: server3, tools: toolNames, count: toolNames.length, hasInstructions: Boolean(instructions) }
56140
56105
  };
56141
56106
  }
56142
- function executeInstructions(state, server2) {
56143
- const definition = state.config.mcpServers[server2];
56107
+ function executeInstructions(state, server3) {
56108
+ const definition = state.config.mcpServers[server3];
56144
56109
  if (!definition) {
56145
56110
  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" }
56111
+ content: [{ type: "text", text: `Server "${server3}" not found. Use mcp({}) to see available servers.` }],
56112
+ details: { mode: "instructions", server: server3, error: "not_found" }
56148
56113
  };
56149
56114
  }
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);
56115
+ if (isServerDisabled(definition)) return disabledResult("instructions", server3);
56116
+ if (isServerInActiveFailureBackoff(state, server3)) return serverBackoffResult(state, "instructions", server3);
56117
+ const instructions = state.serverInstructions.get(server3);
56153
56118
  if (instructions) {
56154
56119
  return {
56155
- content: [{ type: "text", text: `${server2} instructions:
56120
+ content: [{ type: "text", text: `${server3} instructions:
56156
56121
 
56157
56122
  ${instructions}` }],
56158
- details: { mode: "instructions", server: server2, length: instructions.length }
56123
+ details: { mode: "instructions", server: server3, length: instructions.length }
56159
56124
  };
56160
56125
  }
56161
- const connection = state.manager.getConnection(server2);
56126
+ const connection = state.manager.getConnection(server3);
56162
56127
  if (connection?.status === "connected") {
56163
56128
  return {
56164
- content: [{ type: "text", text: `Server "${server2}" does not provide instructions.` }],
56165
- details: { mode: "instructions", server: server2, error: "no_instructions" }
56129
+ content: [{ type: "text", text: `Server "${server3}" does not provide instructions.` }],
56130
+ details: { mode: "instructions", server: server3, error: "no_instructions" }
56166
56131
  };
56167
56132
  }
56168
56133
  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" }
56134
+ content: [{ type: "text", text: `No instructions cached for "${server3}". Use mcp({ connect: "${server3}" }) to connect and refresh.` }],
56135
+ details: { mode: "instructions", server: server3, error: "not_connected" }
56171
56136
  };
56172
56137
  }
56173
56138
  async function executeConnect(state, serverName, signal) {
@@ -56278,26 +56243,26 @@ async function executeCall(state, toolName, args, serverOverride, getPiTools, si
56278
56243
  return ambiguousToolResult("call", toolName);
56279
56244
  }
56280
56245
  let disabledMatch;
56281
- for (const [server2, metadata] of state.toolMetadata.entries()) {
56246
+ for (const [server3, metadata] of state.toolMetadata.entries()) {
56282
56247
  const found = metadata.find((tool) => tool.name === toolName);
56283
56248
  if (!found) continue;
56284
- if (isServerDisabled(state.config.mcpServers[server2])) {
56285
- disabledMatch ??= { serverName: server2, toolMeta: found };
56249
+ if (isServerDisabled(state.config.mcpServers[server3])) {
56250
+ disabledMatch ??= { serverName: server3, toolMeta: found };
56286
56251
  continue;
56287
56252
  }
56288
- serverName = server2;
56253
+ serverName = server3;
56289
56254
  toolMeta = found;
56290
56255
  break;
56291
56256
  }
56292
56257
  if (!toolMeta && !disabledMatch) {
56293
- for (const [server2, metadata] of state.toolMetadata.entries()) {
56258
+ for (const [server3, metadata] of state.toolMetadata.entries()) {
56294
56259
  const found = findToolByName(metadata, toolName);
56295
56260
  if (!found) continue;
56296
- if (isServerDisabled(state.config.mcpServers[server2])) {
56297
- disabledMatch ??= { serverName: server2, toolMeta: found };
56261
+ if (isServerDisabled(state.config.mcpServers[server3])) {
56262
+ disabledMatch ??= { serverName: server3, toolMeta: found };
56298
56263
  continue;
56299
56264
  }
56300
- serverName = server2;
56265
+ serverName = server3;
56301
56266
  toolMeta = found;
56302
56267
  break;
56303
56268
  }
@@ -57026,11 +56991,11 @@ function collectCollapsedResultLines(content, maxLines, maxChars) {
57026
56991
  }
57027
56992
  function formatMcpToolResultIdentity(details) {
57028
56993
  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}`;
56994
+ const server3 = typeof details.server === "string" ? details.server : typeof details.hintServer === "string" ? details.hintServer : null;
56995
+ if (!server3) return null;
56996
+ if (typeof details.tool === "string") return `MCP ${server3}/${details.tool}`;
56997
+ if (typeof details.resourceUri === "string") return `MCP ${server3} resource ${details.resourceUri}`;
56998
+ if (typeof details.requestedTool === "string") return `MCP ${server3}/${details.requestedTool}`;
57034
56999
  return null;
57035
57000
  }
57036
57001
  function formatMcpToolResultLines(result, expanded, maxCollapsedLines = DEFAULT_BOXED_COLLAPSED_LINES, maxCollapsedChars = DEFAULT_MAX_COLLAPSED_CHARS) {
@@ -57201,10 +57166,10 @@ async function runMcpScript(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_
57201
57166
  if (query2.trim() === "") {
57202
57167
  return { items: [], total: 0, hasMore: false, nextOffset: null };
57203
57168
  }
57204
- const server2 = typeof input?.server === "string" ? input.server : void 0;
57169
+ const server3 = typeof input?.server === "string" ? input.server : void 0;
57205
57170
  const limit = typeof input?.limit === "number" ? input.limit : 12;
57206
57171
  const offset = typeof input?.offset === "number" ? input.offset : 0;
57207
- const page2 = paginate(rankToolMatches(state, query2, server2), offset, limit);
57172
+ const page2 = paginate(rankToolMatches(state, query2, server3), offset, limit);
57208
57173
  return {
57209
57174
  ...page2,
57210
57175
  items: page2.items.map(({ server: matchServer, tool, score }) => ({
@@ -57227,15 +57192,15 @@ async function runMcpScript(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_
57227
57192
  const path7 = typeof input?.path === "string" ? input.path : "";
57228
57193
  let error;
57229
57194
  try {
57230
- for (const [server2, metadata] of state.toolMetadata) {
57231
- if (isServerInActiveFailureBackoff(state, server2)) continue;
57195
+ for (const [server3, metadata] of state.toolMetadata) {
57196
+ if (isServerInActiveFailureBackoff(state, server3)) continue;
57232
57197
  const tool = findToolByName(metadata, path7);
57233
57198
  if (!tool) continue;
57234
57199
  const inputTypeScript = tool.inputSchema ? renderTsShape(tool.inputSchema) ?? formatSchema(tool.inputSchema) : null;
57235
57200
  return {
57236
57201
  path: tool.name,
57237
57202
  name: tool.originalName,
57238
- server: server2,
57203
+ server: server3,
57239
57204
  ...tool.description ? { description: tool.description } : {},
57240
57205
  ...inputTypeScript ? { inputTypeScript } : {}
57241
57206
  };
@@ -59072,8 +59037,8 @@ function mcpNameFromToolCall(message) {
59072
59037
  const parsedName = parseMcpToolName(message.tool);
59073
59038
  if (parsedName) return parsedName.server;
59074
59039
  if (message.tool.startsWith("mcp.")) {
59075
- const [server2, ...toolParts] = message.tool.slice("mcp.".length).split(".");
59076
- if (server2 && toolParts.length > 0) return server2;
59040
+ const [server3, ...toolParts] = message.tool.slice("mcp.".length).split(".");
59041
+ if (server3 && toolParts.length > 0) return server3;
59077
59042
  }
59078
59043
  return NON_MCP_SERVERS.has(message.server) ? null : message.server;
59079
59044
  }
@@ -59289,9 +59254,9 @@ function calculateCumulativeTokenUsageDelta(current, previous) {
59289
59254
  cacheWriteInputTokens: current.cacheWriteInputTokens - previous.cacheWriteInputTokens
59290
59255
  };
59291
59256
  }
59292
- function recordParsedTokenUsage(event, harness, parse) {
59257
+ function recordParsedTokenUsage(event, harness, parse2) {
59293
59258
  if (event.type !== "usage-updated") return void 0;
59294
- const usage = parse(event.payload);
59259
+ const usage = parse2(event.payload);
59295
59260
  if (!usage) return void 0;
59296
59261
  return {
59297
59262
  records: [{
@@ -60227,9 +60192,13 @@ function uploadChatTranscript(chatId, filePath, chat, capture) {
60227
60192
  async function uploadChatTranscriptNow(chatId, filePath, chat, capture) {
60228
60193
  const { size } = await stat5(filePath);
60229
60194
  if (size === 0) return null;
60195
+ const credential = chat && ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS[chat.provider];
60230
60196
  const metadata = chat ? {
60231
60197
  provider: chat.provider,
60232
- credential: ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS[chat.provider],
60198
+ credential,
60199
+ // Without a stored credential the agent can only have run on environment-variable auth.
60200
+ credentialSource: credential ? "stored" : detectAgentAuthMethod(chat.provider) === "none" ? void 0 : "environment",
60201
+ model: chat.model,
60233
60202
  title: chat.title,
60234
60203
  displayName: chat.displayName,
60235
60204
  createdAt: chat.createdAt,
@@ -62424,7 +62393,7 @@ var RepoFileService = class {
62424
62393
 
62425
62394
  // src/v1-routes.ts
62426
62395
  import { Hono } from "hono";
62427
- import { z as z4 } from "zod";
62396
+ import { z as z5 } from "zod";
62428
62397
  import { readdir as readdir11, stat as stat7, readFile as readFile23 } from "fs/promises";
62429
62398
  import { join as join39, resolve as resolve5 } from "path";
62430
62399
 
@@ -62816,9 +62785,18 @@ ${combinedScript}` : combinedScript;
62816
62785
  import { randomUUID as randomUUID12 } from "crypto";
62817
62786
  import { existsSync as existsSync20 } from "fs";
62818
62787
  import { spawn as spawn8 } from "node-pty";
62788
+ import { z as z4 } from "zod";
62819
62789
  var MAX_REPLAY_CHARS = 1024 * 1024;
62820
62790
  var MAX_TERMINAL_SESSIONS = 8;
62821
62791
  var MAX_PENDING_INPUT = 64;
62792
+ var terminalSizeSchema = z4.object({
62793
+ cols: z4.number().int().min(2).max(500),
62794
+ rows: z4.number().int().min(1).max(200)
62795
+ });
62796
+ var terminalCommandSchema = z4.discriminatedUnion("type", [
62797
+ z4.object({ type: z4.literal("input"), data: z4.string() }),
62798
+ terminalSizeSchema.extend({ type: z4.literal("resize") })
62799
+ ]);
62822
62800
  var TerminalService = class {
62823
62801
  sessions = /* @__PURE__ */ new Map();
62824
62802
  nextTitleNumber = 1;
@@ -62894,6 +62872,12 @@ var TerminalService = class {
62894
62872
  }
62895
62873
  return true;
62896
62874
  }
62875
+ command(id, command) {
62876
+ const session = this.sessions.get(id);
62877
+ if (!session || session.exited) return;
62878
+ if (command.type === "input") session.pty.write(command.data);
62879
+ else session.pty.resize(command.cols, command.rows);
62880
+ }
62897
62881
  resize(id, cols, rows) {
62898
62882
  const session = this.sessions.get(id);
62899
62883
  if (!session || session.exited) return false;
@@ -62932,32 +62916,28 @@ var TerminalService = class {
62932
62916
  var terminalService = new TerminalService();
62933
62917
 
62934
62918
  // 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)
62919
+ var createPreviewSchema = z5.object({
62920
+ port: z5.number().int().min(1).max(65535),
62921
+ publicUrl: z5.string().min(1)
62942
62922
  });
62943
- var writeTerminalSessionSchema = z4.object({
62944
- data: z4.string().max(64 * 1024),
62945
- generation: z4.number().int().nonnegative(),
62946
- sequence: z4.number().int().nonnegative()
62923
+ var writeTerminalSessionSchema = z5.object({
62924
+ data: z5.string().max(64 * 1024),
62925
+ generation: z5.number().int().nonnegative(),
62926
+ sequence: z5.number().int().nonnegative()
62947
62927
  });
62948
- var respondToolInputSchema = z4.object({
62949
- requestId: z4.string().min(1),
62950
- selectionId: z4.string().min(1)
62928
+ var respondToolInputSchema = z5.object({
62929
+ requestId: z5.string().min(1),
62930
+ selectionId: z5.string().min(1)
62951
62931
  });
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()
62932
+ var updateGoalSchema = z5.object({
62933
+ objective: z5.string().trim().min(1).max(MAX_CODEX_GOAL_OBJECTIVE_CHARS).optional(),
62934
+ status: z5.enum(["active", "paused"]).optional()
62955
62935
  }).refine((body) => body.objective !== void 0 || body.status !== void 0, {
62956
62936
  message: "Goal objective or status required"
62957
62937
  });
62958
- var updateTextFileSchema = (maxLength) => z4.object({
62959
- content: z4.string().max(maxLength),
62960
- expectedRevision: z4.string().regex(/^[a-f0-9]{64}$/)
62938
+ var updateTextFileSchema = (maxLength) => z5.object({
62939
+ content: z5.string().max(maxLength),
62940
+ expectedRevision: z5.string().regex(/^[a-f0-9]{64}$/)
62961
62941
  });
62962
62942
  function jsonError(message, details) {
62963
62943
  return { error: message, details };
@@ -63007,11 +62987,11 @@ function createV1Routes(deps) {
63007
62987
  const app2 = new Hono();
63008
62988
  app2.post("/pull-requests/check", async (c) => {
63009
62989
  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()
62990
+ const result = z5.object({
62991
+ toolName: z5.string(),
62992
+ toolInput: z5.unknown(),
62993
+ output: z5.unknown(),
62994
+ success: z5.boolean()
63015
62995
  }).safeParse(await c.req.json().catch(() => null));
63016
62996
  if (!result.success) return c.json({ error: "Invalid PR tool result" }, 400);
63017
62997
  await pullRequestCheckService.onToolResult(result.data);
@@ -63240,7 +63220,7 @@ function createV1Routes(deps) {
63240
63220
  const chat = await deps.chatService.updateDisplayName(c.req.param("chatId"), body.displayName);
63241
63221
  return c.json({ chat });
63242
63222
  } catch (error) {
63243
- if (error instanceof z4.ZodError) {
63223
+ if (error instanceof z5.ZodError) {
63244
63224
  return c.json(jsonError(error.issues[0]?.message || "Invalid tab name"), 400);
63245
63225
  }
63246
63226
  if (error instanceof ChatNotFoundError) {
@@ -63345,7 +63325,7 @@ function createV1Routes(deps) {
63345
63325
  const result = await deps.chatService.updateGoal(c.req.param("chatId"), body);
63346
63326
  return c.json(result);
63347
63327
  } catch (error) {
63348
- if (error instanceof z4.ZodError) {
63328
+ if (error instanceof z5.ZodError) {
63349
63329
  return c.json(jsonError(error.issues[0]?.message || "Invalid goal update"), 400);
63350
63330
  }
63351
63331
  if (error instanceof ChatNotFoundError) {
@@ -63967,6 +63947,104 @@ data: ${JSON.stringify("Terminal session not found")}
63967
63947
  return app2;
63968
63948
  }
63969
63949
 
63950
+ // src/services/terminal-socket.ts
63951
+ import { z as z6 } from "zod";
63952
+ var ndcModule;
63953
+ var loadNdc = () => ndcModule ??= import("node-datachannel").then((module) => module.default, () => null);
63954
+ var CHANNEL_CHUNK_CHARS = 16384;
63955
+ var MAX_QUEUED_CANDIDATES = 32;
63956
+ var MAX_BUFFERED_BYTES = 8 * 1024 * 1024;
63957
+ var socketMessageSchema = z6.union([
63958
+ terminalCommandSchema,
63959
+ z6.object({ type: z6.literal("rtc-offer"), sdp: z6.string().max(64 * 1024) }),
63960
+ z6.object({ type: z6.literal("rtc-candidate"), candidate: z6.string().max(1024), mid: z6.string().max(64) }),
63961
+ z6.object({ type: z6.literal("rtc-switch") })
63962
+ ]);
63963
+ function parse(schema, raw) {
63964
+ try {
63965
+ const result = schema.safeParse(JSON.parse(raw));
63966
+ return result.success ? result.data : null;
63967
+ } catch {
63968
+ return null;
63969
+ }
63970
+ }
63971
+ function attachTerminalSocket(id, socket) {
63972
+ const send = (message) => socket.send(JSON.stringify(message));
63973
+ let peer = null;
63974
+ let channel = null;
63975
+ const candidates = [];
63976
+ let early = [];
63977
+ const subscription = terminalService.subscribe(id, (data) => {
63978
+ if (socket.bufferedAmount > MAX_BUFFERED_BYTES || (channel?.bufferedAmount() ?? 0) > MAX_BUFFERED_BYTES) {
63979
+ socket.terminate();
63980
+ return;
63981
+ }
63982
+ if (!channel?.isOpen()) {
63983
+ send({ type: "output", data });
63984
+ return;
63985
+ }
63986
+ for (let start = 0; start < data.length; ) {
63987
+ let end = Math.min(start + CHANNEL_CHUNK_CHARS, data.length);
63988
+ if (end < data.length && /[\uD800-\uDBFF]/.test(data[end - 1])) end--;
63989
+ channel.sendMessage(data.slice(start, end));
63990
+ start = end;
63991
+ }
63992
+ });
63993
+ if (!subscription) {
63994
+ socket.close(4410, "Terminal session not found");
63995
+ return;
63996
+ }
63997
+ if (subscription.replay) send({ type: "output", data: subscription.replay });
63998
+ const negotiate = async (offer) => {
63999
+ const ndc = await loadNdc();
64000
+ if (!ndc || peer || socket.readyState !== socket.OPEN) return;
64001
+ const connection = new ndc.PeerConnection(`terminal-${id}`, { iceServers: [TERMINAL_RTC_ICE_SERVER] });
64002
+ peer = connection;
64003
+ connection.onLocalDescription((sdp) => send({ type: "rtc-answer", sdp }));
64004
+ connection.onLocalCandidate((candidate, mid) => send({ type: "rtc-candidate", candidate, mid }));
64005
+ connection.onDataChannel((dc) => {
64006
+ dc.onMessage((raw) => {
64007
+ const command = typeof raw === "string" ? parse(terminalCommandSchema, raw) : null;
64008
+ if (!command) return;
64009
+ if (early) early.push(command);
64010
+ else terminalService.command(id, command);
64011
+ });
64012
+ dc.onClosed(() => {
64013
+ if (channel === dc) channel = null;
64014
+ });
64015
+ const activate2 = () => {
64016
+ channel = dc;
64017
+ send({ type: "rtc-switch" });
64018
+ };
64019
+ if (dc.isOpen()) activate2();
64020
+ else dc.onOpen(activate2);
64021
+ });
64022
+ connection.setRemoteDescription(offer, "offer");
64023
+ for (const { candidate, mid } of candidates.splice(0)) connection.addRemoteCandidate(candidate, mid);
64024
+ };
64025
+ socket.on("message", (raw) => {
64026
+ const message = parse(socketMessageSchema, raw.toString());
64027
+ if (!message) return;
64028
+ if (message.type === "rtc-offer") {
64029
+ negotiate(message.sdp).catch(() => {
64030
+ peer?.close();
64031
+ peer = null;
64032
+ });
64033
+ } else if (message.type === "rtc-candidate") {
64034
+ if (peer) peer.addRemoteCandidate(message.candidate, message.mid);
64035
+ else if (candidates.length < MAX_QUEUED_CANDIDATES) candidates.push(message);
64036
+ } else if (message.type === "rtc-switch") {
64037
+ for (const command of early ?? []) terminalService.command(id, command);
64038
+ early = null;
64039
+ } else terminalService.command(id, message);
64040
+ });
64041
+ socket.on("close", () => {
64042
+ subscription.unsubscribe();
64043
+ channel = null;
64044
+ peer?.close();
64045
+ });
64046
+ }
64047
+
63970
64048
  // src/services/heartbeat-service.ts
63971
64049
  function unrefTimer(timer) {
63972
64050
  if (typeof timer === "object" && timer !== null && "unref" in timer && typeof timer.unref === "function") {
@@ -64053,7 +64131,7 @@ function startGitPushTracker() {
64053
64131
  async function listen() {
64054
64132
  await mkdir23(ENGINE_DIR2, { recursive: true });
64055
64133
  await rm5(SOCKET_PATH, { force: true });
64056
- const server2 = createServer2((socket) => {
64134
+ const server3 = createServer2((socket) => {
64057
64135
  let buffered = "";
64058
64136
  let ignored = false;
64059
64137
  let push = false;
@@ -64095,10 +64173,10 @@ async function listen() {
64095
64173
  });
64096
64174
  });
64097
64175
  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));
64176
+ server3.once("error", reject);
64177
+ server3.listen(SOCKET_PATH, () => {
64178
+ server3.off("error", reject);
64179
+ server3.on("error", (error) => console.error("[GitPushTracker] Socket error:", error));
64102
64180
  resolve7();
64103
64181
  });
64104
64182
  });
@@ -64483,7 +64561,9 @@ async function sleep2() {
64483
64561
  await engineLogger.flush();
64484
64562
  return createSuccessResult({ state: lifecycle.state, workspaceId: lifecycle.workspaceId });
64485
64563
  }
64486
- serve(
64564
+ var terminalSockets = new WebSocketServer({ noServer: true });
64565
+ var TERMINAL_SOCKET_PATH = /^\/terminal\/sessions\/([^/]+)\/ws$/;
64566
+ var server2 = serve(
64487
64567
  {
64488
64568
  fetch: app.fetch,
64489
64569
  port
@@ -64502,6 +64582,17 @@ serve(
64502
64582
  }
64503
64583
  }
64504
64584
  );
64585
+ server2.on("upgrade", (req, socket, head) => {
64586
+ const sessionId = TERMINAL_SOCKET_PATH.exec(new URL(req.url ?? "/", "http://engine").pathname)?.[1];
64587
+ if (!sessionId || req.headers["x-replicas-engine-secret"] !== ENGINE_ENV.REPLICAS_ENGINE_SECRET || !lifecycle.active) {
64588
+ socket.end(`HTTP/1.1 ${sessionId ? "401 Unauthorized" : "404 Not Found"}\r
64589
+ Connection: close\r
64590
+ \r
64591
+ `);
64592
+ return;
64593
+ }
64594
+ terminalSockets.handleUpgrade(req, socket, head, (ws) => attachTerminalSocket(decodeURIComponent(sessionId), ws));
64595
+ });
64505
64596
  /*! Bundled license information:
64506
64597
 
64507
64598
  @modelcontextprotocol/client/dist/src-D_zzAWoS.mjs: