replicas-engine 0.1.889 → 0.1.892

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
@@ -91,7 +91,7 @@ import {
91
91
  evaluateCommandProtection,
92
92
  extractToolCommand,
93
93
  reportCommandProtectionBlock
94
- } from "./chunk-WMRZEQIH.js";
94
+ } from "./chunk-ER4NIWP5.js";
95
95
  import {
96
96
  ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
97
97
  AGENT_MESSAGE_DELTA_METHOD,
@@ -114,6 +114,9 @@ import {
114
114
  putPresignedFile,
115
115
  recoverCompletedTurn
116
116
  } from "./chunk-FLDA7BX3.js";
117
+ import {
118
+ publishedPullRequestUrls
119
+ } from "./chunk-OIVQZXGH.js";
117
120
  import {
118
121
  RELAY_MCP_TOOLS,
119
122
  RELAY_MCP_TOOL_NAMES,
@@ -134,21 +137,21 @@ import {
134
137
  refreshDelayMs,
135
138
  restartCodexAspHost,
136
139
  routineRefreshExclusions
137
- } from "./chunk-N7JSMN3R.js";
140
+ } from "./chunk-VUM4ESLZ.js";
138
141
  import {
139
142
  ENGINE_ENV,
140
143
  IS_WARMING_MODE,
141
144
  monolithRequest,
142
145
  monolithService,
143
146
  setAgentCredentialSnapshot
144
- } from "./chunk-RG6ZP2EU.js";
147
+ } from "./chunk-7AZIY6NQ.js";
145
148
  import {
146
149
  AspClient,
147
150
  SUBPROCESS_MAX_BUFFER,
148
151
  execAsync,
149
152
  execFileAsync,
150
153
  getCodexModelProvider
151
- } from "./chunk-F33TXACU.js";
154
+ } from "./chunk-576ALV46.js";
152
155
  import {
153
156
  isRecord as isRecord2
154
157
  } from "./chunk-UZSNFLDQ.js";
@@ -216,6 +219,7 @@ import {
216
219
  GIT_CREDENTIAL_HELPER_FILENAME,
217
220
  HOOK_EXEC_MAX_BUFFER_BYTES,
218
221
  IDENTITY_PROXY_PORT,
222
+ IDENTITY_TOKEN_PATH,
219
223
  IMAGE_MEDIA_TYPES,
220
224
  InFlightMap,
221
225
  MAX_CANVAS_FILE_BYTES,
@@ -239,11 +243,12 @@ import {
239
243
  TaskAccumulator,
240
244
  USER_MESSAGE_ID_PAYLOAD_KEY,
241
245
  VALID_AGENT_PROVIDERS,
242
- WORKSPACE_TOKEN_ENV,
246
+ WORKSPACE_IDENTITY_AUDIENCE,
243
247
  agentQuotaExhaustedPayloadSchema,
244
248
  areSameUserMessageEvents,
245
249
  areUserMessagesWithinMatchWindow,
246
250
  autoCompactThresholdField,
251
+ buildCodeHostPrUrl,
247
252
  buildCodexTokenUsageContextUsagePayload,
248
253
  buildGitCredentialHelperScript,
249
254
  buildHookOutputPreview,
@@ -272,7 +277,6 @@ import {
272
277
  createProviderSlashCommand,
273
278
  createSuccessResult,
274
279
  createUuidFromHex,
275
- currentWorkspaceToken,
276
280
  decodePathSegments,
277
281
  defaultForkChatTitle,
278
282
  describeQuotaLimit,
@@ -330,6 +334,7 @@ import {
330
334
  isValidEngineLogSessionId,
331
335
  isValidRelayBaseProvider,
332
336
  lastUserBlockText,
337
+ legacyWorkspaceTokenBundleSchema,
333
338
  listOllamaModels,
334
339
  mergeSlashCommands,
335
340
  messageRelaySubagentRequestSchema,
@@ -343,6 +348,7 @@ import {
343
348
  parseAgentEvents,
344
349
  parseChatHistoryCursor,
345
350
  parseChatTranscriptArtifact,
351
+ parseCodeHostPrUrl,
346
352
  parseDisplayMessages,
347
353
  parseFrontmatter,
348
354
  parseGitRemote,
@@ -366,8 +372,11 @@ import {
366
372
  updateChatDisplayNameRequestSchema,
367
373
  waitRelaySubagentRequestSchema,
368
374
  withTimeout,
369
- workspaceCredentialProviderSchema
370
- } from "./chunk-45I2CJU6.js";
375
+ workspaceAudienceSchema,
376
+ workspaceCredentialProviderSchema,
377
+ workspaceTokenRequestSchema,
378
+ workspaceTokenResponseSchema
379
+ } from "./chunk-HIMILSEB.js";
371
380
  import {
372
381
  __commonJS,
373
382
  __export,
@@ -382,7 +391,7 @@ var require_windows = __commonJS({
382
391
  module.exports = isexe;
383
392
  isexe.sync = sync;
384
393
  var fs8 = __require("fs");
385
- function checkPathExt(path8, options) {
394
+ function checkPathExt(path7, options) {
386
395
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
387
396
  if (!pathext) {
388
397
  return true;
@@ -393,25 +402,25 @@ var require_windows = __commonJS({
393
402
  }
394
403
  for (var i = 0; i < pathext.length; i++) {
395
404
  var p = pathext[i].toLowerCase();
396
- if (p && path8.substr(-p.length).toLowerCase() === p) {
405
+ if (p && path7.substr(-p.length).toLowerCase() === p) {
397
406
  return true;
398
407
  }
399
408
  }
400
409
  return false;
401
410
  }
402
- function checkStat(stat8, path8, options) {
411
+ function checkStat(stat8, path7, options) {
403
412
  if (!stat8.isSymbolicLink() && !stat8.isFile()) {
404
413
  return false;
405
414
  }
406
- return checkPathExt(path8, options);
415
+ return checkPathExt(path7, options);
407
416
  }
408
- function isexe(path8, options, cb) {
409
- fs8.stat(path8, function(er, stat8) {
410
- cb(er, er ? false : checkStat(stat8, path8, options));
417
+ function isexe(path7, options, cb) {
418
+ fs8.stat(path7, function(er, stat8) {
419
+ cb(er, er ? false : checkStat(stat8, path7, options));
411
420
  });
412
421
  }
413
- function sync(path8, options) {
414
- return checkStat(fs8.statSync(path8), path8, options);
422
+ function sync(path7, options) {
423
+ return checkStat(fs8.statSync(path7), path7, options);
415
424
  }
416
425
  }
417
426
  });
@@ -423,13 +432,13 @@ var require_mode = __commonJS({
423
432
  module.exports = isexe;
424
433
  isexe.sync = sync;
425
434
  var fs8 = __require("fs");
426
- function isexe(path8, options, cb) {
427
- fs8.stat(path8, function(er, stat8) {
435
+ function isexe(path7, options, cb) {
436
+ fs8.stat(path7, function(er, stat8) {
428
437
  cb(er, er ? false : checkStat(stat8, options));
429
438
  });
430
439
  }
431
- function sync(path8, options) {
432
- return checkStat(fs8.statSync(path8), options);
440
+ function sync(path7, options) {
441
+ return checkStat(fs8.statSync(path7), options);
433
442
  }
434
443
  function checkStat(stat8, options) {
435
444
  return stat8.isFile() && checkMode(stat8, options);
@@ -463,7 +472,7 @@ var require_isexe = __commonJS({
463
472
  }
464
473
  module.exports = isexe;
465
474
  isexe.sync = sync;
466
- function isexe(path8, options, cb) {
475
+ function isexe(path7, options, cb) {
467
476
  if (typeof options === "function") {
468
477
  cb = options;
469
478
  options = {};
@@ -472,17 +481,17 @@ var require_isexe = __commonJS({
472
481
  if (typeof Promise !== "function") {
473
482
  throw new TypeError("callback not provided");
474
483
  }
475
- return new Promise(function(resolve7, reject) {
476
- isexe(path8, options || {}, function(er, is) {
484
+ return new Promise(function(resolve8, reject) {
485
+ isexe(path7, options || {}, function(er, is) {
477
486
  if (er) {
478
487
  reject(er);
479
488
  } else {
480
- resolve7(is);
489
+ resolve8(is);
481
490
  }
482
491
  });
483
492
  });
484
493
  }
485
- core(path8, options || {}, function(er, is) {
494
+ core(path7, options || {}, function(er, is) {
486
495
  if (er) {
487
496
  if (er.code === "EACCES" || options && options.ignoreErrors) {
488
497
  er = null;
@@ -492,9 +501,9 @@ var require_isexe = __commonJS({
492
501
  cb(er, is);
493
502
  });
494
503
  }
495
- function sync(path8, options) {
504
+ function sync(path7, options) {
496
505
  try {
497
- return core.sync(path8, options || {});
506
+ return core.sync(path7, options || {});
498
507
  } catch (er) {
499
508
  if (options && options.ignoreErrors || er.code === "EACCES") {
500
509
  return false;
@@ -511,7 +520,7 @@ var require_which = __commonJS({
511
520
  "../node_modules/.bun/which@2.0.2/node_modules/which/which.js"(exports, module) {
512
521
  "use strict";
513
522
  var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
514
- var path8 = __require("path");
523
+ var path7 = __require("path");
515
524
  var COLON = isWindows ? ";" : ":";
516
525
  var isexe = require_isexe();
517
526
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -544,27 +553,27 @@ var require_which = __commonJS({
544
553
  opt = {};
545
554
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
546
555
  const found = [];
547
- const step = (i) => new Promise((resolve7, reject) => {
556
+ const step = (i) => new Promise((resolve8, reject) => {
548
557
  if (i === pathEnv.length)
549
- return opt.all && found.length ? resolve7(found) : reject(getNotFoundError(cmd));
558
+ return opt.all && found.length ? resolve8(found) : reject(getNotFoundError(cmd));
550
559
  const ppRaw = pathEnv[i];
551
560
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
552
- const pCmd = path8.join(pathPart, cmd);
561
+ const pCmd = path7.join(pathPart, cmd);
553
562
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
554
- resolve7(subStep(p, i, 0));
563
+ resolve8(subStep(p, i, 0));
555
564
  });
556
- const subStep = (p, i, ii) => new Promise((resolve7, reject) => {
565
+ const subStep = (p, i, ii) => new Promise((resolve8, reject) => {
557
566
  if (ii === pathExt.length)
558
- return resolve7(step(i + 1));
567
+ return resolve8(step(i + 1));
559
568
  const ext = pathExt[ii];
560
569
  isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
561
570
  if (!er && is) {
562
571
  if (opt.all)
563
572
  found.push(p + ext);
564
573
  else
565
- return resolve7(p + ext);
574
+ return resolve8(p + ext);
566
575
  }
567
- return resolve7(subStep(p, i, ii + 1));
576
+ return resolve8(subStep(p, i, ii + 1));
568
577
  });
569
578
  });
570
579
  return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
@@ -576,7 +585,7 @@ var require_which = __commonJS({
576
585
  for (let i = 0; i < pathEnv.length; i++) {
577
586
  const ppRaw = pathEnv[i];
578
587
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
579
- const pCmd = path8.join(pathPart, cmd);
588
+ const pCmd = path7.join(pathPart, cmd);
580
589
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
581
590
  for (let j = 0; j < pathExt.length; j++) {
582
591
  const cur = p + pathExt[j];
@@ -624,7 +633,7 @@ var require_path_key = __commonJS({
624
633
  var require_resolveCommand = __commonJS({
625
634
  "../node_modules/.bun/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
626
635
  "use strict";
627
- var path8 = __require("path");
636
+ var path7 = __require("path");
628
637
  var which = require_which();
629
638
  var getPathKey = require_path_key();
630
639
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -642,7 +651,7 @@ var require_resolveCommand = __commonJS({
642
651
  try {
643
652
  resolved = which.sync(parsed.command, {
644
653
  path: env[getPathKey({ env })],
645
- pathExt: withoutPathExt ? path8.delimiter : void 0
654
+ pathExt: withoutPathExt ? path7.delimiter : void 0
646
655
  });
647
656
  } catch (e) {
648
657
  } finally {
@@ -651,7 +660,7 @@ var require_resolveCommand = __commonJS({
651
660
  }
652
661
  }
653
662
  if (resolved) {
654
- resolved = path8.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
663
+ resolved = path7.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
655
664
  }
656
665
  return resolved;
657
666
  }
@@ -705,8 +714,8 @@ var require_shebang_command = __commonJS({
705
714
  if (!match) {
706
715
  return null;
707
716
  }
708
- const [path8, argument] = match[0].replace(/#! ?/, "").split(" ");
709
- const binary = path8.split("/").pop();
717
+ const [path7, argument] = match[0].replace(/#! ?/, "").split(" ");
718
+ const binary = path7.split("/").pop();
710
719
  if (binary === "env") {
711
720
  return argument;
712
721
  }
@@ -741,7 +750,7 @@ var require_readShebang = __commonJS({
741
750
  var require_parse = __commonJS({
742
751
  "../node_modules/.bun/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(exports, module) {
743
752
  "use strict";
744
- var path8 = __require("path");
753
+ var path7 = __require("path");
745
754
  var resolveCommand = require_resolveCommand();
746
755
  var escape2 = require_escape();
747
756
  var readShebang = require_readShebang();
@@ -766,7 +775,7 @@ var require_parse = __commonJS({
766
775
  const needsShell = !isExecutableRegExp.test(commandFile);
767
776
  if (parsed.options.forceShell || needsShell) {
768
777
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
769
- parsed.command = path8.normalize(parsed.command);
778
+ parsed.command = path7.normalize(parsed.command);
770
779
  parsed.command = escape2.command(parsed.command);
771
780
  parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
772
781
  const shellCommand2 = [parsed.command].concat(parsed.args).join(" ");
@@ -3827,7 +3836,7 @@ var require_compile2 = __commonJS({
3827
3836
  const schOrFunc = root.refs[ref];
3828
3837
  if (schOrFunc)
3829
3838
  return schOrFunc;
3830
- let _sch = resolve7.call(this, root, ref);
3839
+ let _sch = resolve8.call(this, root, ref);
3831
3840
  if (_sch === void 0) {
3832
3841
  const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
3833
3842
  const { schemaId } = this.opts;
@@ -3854,7 +3863,7 @@ var require_compile2 = __commonJS({
3854
3863
  function sameSchemaEnv(s1, s2) {
3855
3864
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
3856
3865
  }
3857
- function resolve7(root, ref) {
3866
+ function resolve8(root, ref) {
3858
3867
  let sch;
3859
3868
  while (typeof (sch = this.refs[ref]) == "string")
3860
3869
  ref = sch;
@@ -4072,8 +4081,8 @@ var require_utils2 = __commonJS({
4072
4081
  }
4073
4082
  return ind;
4074
4083
  }
4075
- function removeDotSegments(path8) {
4076
- let input = path8;
4084
+ function removeDotSegments(path7) {
4085
+ let input = path7;
4077
4086
  const output = [];
4078
4087
  let nextSlash = -1;
4079
4088
  let len = 0;
@@ -4325,8 +4334,8 @@ var require_schemes2 = __commonJS({
4325
4334
  wsComponent.secure = void 0;
4326
4335
  }
4327
4336
  if (wsComponent.resourceName) {
4328
- const [path8, query2] = wsComponent.resourceName.split("?");
4329
- wsComponent.path = path8 && path8 !== "/" ? path8 : void 0;
4337
+ const [path7, query2] = wsComponent.resourceName.split("?");
4338
+ wsComponent.path = path7 && path7 !== "/" ? path7 : void 0;
4330
4339
  wsComponent.query = query2;
4331
4340
  wsComponent.resourceName = void 0;
4332
4341
  }
@@ -4485,7 +4494,7 @@ var require_fast_uri2 = __commonJS({
4485
4494
  }
4486
4495
  return uri;
4487
4496
  }
4488
- function resolve7(baseURI, relativeURI, options) {
4497
+ function resolve8(baseURI, relativeURI, options) {
4489
4498
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
4490
4499
  const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
4491
4500
  schemelessOptions.skipEscape = true;
@@ -4743,7 +4752,7 @@ var require_fast_uri2 = __commonJS({
4743
4752
  var fastUri = {
4744
4753
  SCHEMES,
4745
4754
  normalize,
4746
- resolve: resolve7,
4755
+ resolve: resolve8,
4747
4756
  resolveComponent,
4748
4757
  equal,
4749
4758
  serialize,
@@ -8585,11 +8594,11 @@ var AsyncLock = class {
8585
8594
  };
8586
8595
 
8587
8596
  // src/utils/file.ts
8588
- async function atomicWriteFile(path8, data, options) {
8589
- const tmpFile = `${path8}.${process.pid}.${randomUUID()}.tmp`;
8597
+ async function atomicWriteFile(path7, data, options) {
8598
+ const tmpFile = `${path7}.${process.pid}.${randomUUID()}.tmp`;
8590
8599
  try {
8591
8600
  await writeFile(tmpFile, data, { encoding: "utf-8", mode: options?.mode });
8592
- await rename(tmpFile, path8);
8601
+ await rename(tmpFile, path7);
8593
8602
  } catch (error) {
8594
8603
  await unlink(tmpFile).catch(() => void 0);
8595
8604
  throw error;
@@ -8655,11 +8664,12 @@ var DEFAULT_STATE = {
8655
8664
  };
8656
8665
  var stateWriteLock = new AsyncLock();
8657
8666
  async function updateEngineState(updater) {
8658
- await stateWriteLock.run(async () => {
8667
+ return stateWriteLock.run(async () => {
8659
8668
  await mkdir2(STATE_DIR, { recursive: true });
8660
8669
  const currentState = await loadEngineState();
8661
8670
  const nextState = updater(currentState);
8662
8671
  await atomicWriteFile(STATE_FILE, JSON.stringify(nextState, null, 2));
8672
+ return nextState;
8663
8673
  });
8664
8674
  }
8665
8675
  function isEngineRepoDiff(value) {
@@ -8730,7 +8740,7 @@ async function loadRepoState(repoName) {
8730
8740
  return state.repos[repoName] ?? null;
8731
8741
  }
8732
8742
  async function saveRepoState(repoName, state, fallbackState) {
8733
- await updateEngineState((currentState) => {
8743
+ const updated = await updateEngineState((currentState) => {
8734
8744
  const currentRepoState = currentState.repos[repoName] ?? fallbackState;
8735
8745
  return {
8736
8746
  ...currentState,
@@ -8738,16 +8748,19 @@ async function saveRepoState(repoName, state, fallbackState) {
8738
8748
  ...currentState.repos,
8739
8749
  [repoName]: {
8740
8750
  ...currentRepoState,
8741
- ...state
8751
+ ...state,
8752
+ // Publication events and repository refreshes can finish in either order.
8753
+ prUrls: [.../* @__PURE__ */ new Set([...currentRepoState.prUrls, ...state.prUrls ?? []])]
8742
8754
  }
8743
8755
  }
8744
8756
  };
8745
8757
  });
8758
+ return updated.repos[repoName];
8746
8759
  }
8747
8760
 
8748
8761
  // src/git/commands.ts
8749
- import { readFileSync } from "fs";
8750
- import { join as join3 } from "path";
8762
+ import { readdirSync, readFileSync, statSync } from "fs";
8763
+ import { join as join3, resolve } from "path";
8751
8764
  async function runGitCommand(args, cwd, options = {}) {
8752
8765
  const { stdout } = await execFileAsync("git", args, {
8753
8766
  cwd,
@@ -8756,14 +8769,37 @@ async function runGitCommand(args, cwd, options = {}) {
8756
8769
  });
8757
8770
  return stdout.trim();
8758
8771
  }
8759
- function readRepoHeadBranch(repoPath) {
8772
+ function readRepoHeadBranches(repoPath) {
8773
+ const branches = /* @__PURE__ */ new Set();
8760
8774
  try {
8761
- const contents = readFileSync(join3(repoPath, ".git", "HEAD"), "utf-8").trim();
8762
- const match = contents.match(/^ref:\s+refs\/heads\/(.+)$/);
8763
- return match ? match[1] : null;
8775
+ let gitDir = join3(repoPath, ".git");
8776
+ if (statSync(gitDir).isFile()) {
8777
+ const target = readFileSync(gitDir, "utf8").trim().match(/^gitdir: (.+)$/)?.[1];
8778
+ if (!target) return branches;
8779
+ gitDir = resolve(repoPath, target);
8780
+ }
8781
+ let commonDir = gitDir;
8782
+ try {
8783
+ commonDir = resolve(gitDir, readFileSync(join3(gitDir, "commondir"), "utf8").trim());
8784
+ } catch {
8785
+ }
8786
+ const headDirs = /* @__PURE__ */ new Set([gitDir, commonDir]);
8787
+ try {
8788
+ for (const entry of readdirSync(join3(commonDir, "worktrees"))) {
8789
+ headDirs.add(join3(commonDir, "worktrees", entry));
8790
+ }
8791
+ } catch {
8792
+ }
8793
+ for (const dir of headDirs) {
8794
+ try {
8795
+ const branch = readFileSync(join3(dir, "HEAD"), "utf8").trim().match(/^ref:\s+refs\/heads\/(.+)$/)?.[1];
8796
+ if (branch) branches.add(branch);
8797
+ } catch {
8798
+ }
8799
+ }
8764
8800
  } catch {
8765
- return null;
8766
8801
  }
8802
+ return branches;
8767
8803
  }
8768
8804
  async function branchExists(branchName, cwd) {
8769
8805
  try {
@@ -8893,7 +8929,10 @@ var GitService = class {
8893
8929
  const persistedState = await loadRepoState(repo.name);
8894
8930
  const currentBranch = await getCurrentBranch(repo.path) ?? repo.defaultBranch;
8895
8931
  const startHooksCompleted = persistedState?.startHooksCompleted ?? false;
8896
- const observed = observedBranchesByRepo?.get(repo.name);
8932
+ const observed = /* @__PURE__ */ new Set([
8933
+ ...readRepoHeadBranches(repo.path),
8934
+ ...observedBranchesByRepo?.get(repo.name) ?? []
8935
+ ]);
8897
8936
  const state = await this.refreshRepoMetadata(
8898
8937
  repo,
8899
8938
  currentBranch,
@@ -8912,19 +8951,33 @@ var GitService = class {
8912
8951
  }
8913
8952
  return { repos: states, complete: complete2 };
8914
8953
  }
8915
- // Fast branch snapshot for per-event observation during a turn. Reads
8916
- // .git/HEAD directly for each repo (no subprocess) so callers can safely
8917
- // invoke this on every agent event without measurable overhead.
8918
8954
  async snapshotCurrentBranches() {
8919
8955
  const repos = await this.listRepositories();
8920
- const branches = /* @__PURE__ */ new Map();
8956
+ return new Map(repos.map((repo) => [repo.name, readRepoHeadBranches(repo.path)]));
8957
+ }
8958
+ async recordPublishedPullRequest(prUrl) {
8959
+ if (!URL.canParse(prUrl)) return false;
8960
+ const parsed = parseCodeHostPrUrl(prUrl);
8961
+ if (!parsed || !Number.isSafeInteger(parsed.number) || parsed.number <= 0) return false;
8962
+ const url3 = new URL(prUrl);
8963
+ if (url3.host.toLowerCase() !== parsed.host || !["https:", "http:"].includes(url3.protocol)) return false;
8964
+ const canonicalUrl = buildCodeHostPrUrl(parsed.repoUrl, parsed.provider, parsed.number);
8965
+ const repos = await this.listRepositories();
8921
8966
  for (const repo of repos) {
8922
- const branch = readRepoHeadBranch(repo.path);
8923
- if (branch) {
8924
- branches.set(repo.name, branch);
8925
- }
8967
+ const remote = parseGitRemote(await runGitCommand(["remote", "get-url", "origin"], repo.path).catch(() => ""));
8968
+ if (!remote || remote.host !== parsed.host) continue;
8969
+ const sameRepository = parsed.provider === "github" ? remote.path.toLowerCase() === parsed.repositoryPath.toLowerCase() : remote.path === parsed.repositoryPath;
8970
+ if (!sameRepository) continue;
8971
+ await saveRepoState(repo.name, { prUrls: [canonicalUrl] }, {
8972
+ ...repo,
8973
+ currentBranch: await getCurrentBranch(repo.path) ?? repo.defaultBranch,
8974
+ prUrls: [],
8975
+ gitDiff: null,
8976
+ startHooksCompleted: false
8977
+ });
8978
+ return true;
8926
8979
  }
8927
- return branches;
8980
+ return false;
8928
8981
  }
8929
8982
  getGitDiffStats(repoPath, defaultBranch) {
8930
8983
  return this.diffStatsInFlight.run(repoPath, async () => {
@@ -8980,7 +9033,7 @@ var GitService = class {
8980
9033
  }
8981
9034
  }
8982
9035
  readUntrackedDiff(repoPath, paths) {
8983
- return new Promise((resolve7) => {
9036
+ return new Promise((resolve8) => {
8984
9037
  const child = spawn("git", ["diff", "--", ...paths], {
8985
9038
  cwd: repoPath,
8986
9039
  stdio: ["ignore", "pipe", "pipe"]
@@ -9001,12 +9054,12 @@ var GitService = class {
9001
9054
  });
9002
9055
  child.stderr.on("data", () => {
9003
9056
  });
9004
- child.on("error", () => resolve7(""));
9057
+ child.on("error", () => resolve8(""));
9005
9058
  child.on("close", (code) => {
9006
9059
  if (code === 0 || code === 1 || truncated) {
9007
- resolve7(Buffer.concat(chunks).toString("utf-8"));
9060
+ resolve8(Buffer.concat(chunks).toString("utf-8"));
9008
9061
  } else {
9009
- resolve7("");
9062
+ resolve8("");
9010
9063
  }
9011
9064
  });
9012
9065
  });
@@ -9015,9 +9068,9 @@ var GitService = class {
9015
9068
  try {
9016
9069
  const paths = await this.listUntrackedPaths(repoPath);
9017
9070
  let total = 0;
9018
- for (const path8 of paths) {
9071
+ for (const path7 of paths) {
9019
9072
  try {
9020
- const contents = await readFile3(join4(repoPath, path8));
9073
+ const contents = await readFile3(join4(repoPath, path7));
9021
9074
  if (contents.length === 0 || contents.includes(0)) {
9022
9075
  continue;
9023
9076
  }
@@ -9270,12 +9323,11 @@ var GitService = class {
9270
9323
  startHooksCompleted,
9271
9324
  ...await this.resolveCodeHost(repo.path)
9272
9325
  };
9273
- await saveRepoState(repo.name, state, state);
9274
- return state;
9326
+ return saveRepoState(repo.name, state, state);
9275
9327
  }
9276
- async safeStat(path8) {
9328
+ async safeStat(path7) {
9277
9329
  try {
9278
- return await stat(path8);
9330
+ return await stat(path7);
9279
9331
  } catch {
9280
9332
  return null;
9281
9333
  }
@@ -9589,62 +9641,58 @@ async function applyInfisicalCredentials(data, paths) {
9589
9641
  }
9590
9642
  var infisicalTokenManager = new InfisicalTokenManager();
9591
9643
 
9592
- // src/managers/workspace-identity-token-manager.ts
9593
- import { rm as rm2 } from "fs/promises";
9594
- import path5 from "path";
9595
- var MAX_REFRESH_MS = 5 * 60 * 1e3;
9596
- var WorkspaceIdentityTokenManager = class extends BaseRefreshManager {
9597
- constructor(request = monolithRequest, homeDir = ENGINE_ENV.HOME_DIR) {
9598
- super("WorkspaceIdentityTokenManager", MAX_REFRESH_MS);
9644
+ // src/workspace-identity-tokens.ts
9645
+ var MIN_REMAINING_MS = 5 * 60 * 1e3;
9646
+ var MAX_CACHED_AUDIENCES = 32;
9647
+ var WorkspaceIdentityTokens = class {
9648
+ constructor(request = monolithRequest) {
9599
9649
  this.request = request;
9600
- this.homeDir = homeDir;
9601
9650
  }
9602
9651
  request;
9603
- homeDir;
9604
- nextRefreshDelayMs = MAX_REFRESH_MS;
9605
- bundle = null;
9606
- async doRefresh() {
9607
- const response = await this.request("/v1/engine/workspace-identity/token");
9608
- if (!response.ok) throw new Error(`Workspace identity refresh failed: ${response.status} ${await response.text()}`);
9609
- const data = await response.json();
9610
- const bundleFile = path5.join(this.homeDir, ".replicas", "credentials", "tokens.json");
9611
- const envFile = path5.join(this.homeDir, ".replicas", "workspace-identity-env.sh");
9612
- if (!data.configured) {
9613
- this.bundle = null;
9614
- for (const key of Object.values(WORKSPACE_TOKEN_ENV)) delete process.env[key];
9615
- await Promise.all([rm2(bundleFile, { force: true }), rm2(envFile, { force: true })]);
9616
- this.nextRefreshDelayMs = MAX_REFRESH_MS;
9617
- return;
9652
+ cache = /* @__PURE__ */ new Map();
9653
+ inflight = /* @__PURE__ */ new Map();
9654
+ async get(audience = WORKSPACE_IDENTITY_AUDIENCE) {
9655
+ const parsed = workspaceAudienceSchema.safeParse(audience);
9656
+ if (!parsed.success) {
9657
+ return createErrorResult({ message: parsed.error.issues[0]?.message ?? "Invalid audience", code: 400 });
9618
9658
  }
9619
- const { configured: _configured, ...bundle } = data;
9620
- this.bundle = bundle;
9621
- const env = {
9622
- [WORKSPACE_TOKEN_ENV.TOKEN]: currentWorkspaceToken(bundle) ?? "",
9623
- [WORKSPACE_TOKEN_ENV.TOKEN_FILE]: bundleFile,
9624
- [WORKSPACE_TOKEN_ENV.AUDIENCE]: bundle.default_audience,
9625
- [WORKSPACE_TOKEN_ENV.ISSUER]: bundle.issuer
9626
- };
9627
- Object.assign(process.env, env);
9628
- await Promise.all([
9629
- writeSecureCredentialFile(bundleFile, `${JSON.stringify(bundle)}
9630
- `, { ensureParentDir: true }),
9631
- writeSecureCredentialFile(
9632
- envFile,
9633
- `${Object.entries(env).map(([key, value]) => `export ${key}=${shellQuotePosix(value)}`).join("\n")}
9634
- `,
9635
- { ensureParentDir: true }
9636
- )
9637
- ]);
9638
- this.nextRefreshDelayMs = refreshDelayMs(
9639
- Math.min(...Object.values(bundle.tokens).map((entry) => Date.parse(entry.expires_at))),
9640
- MAX_REFRESH_MS
9641
- );
9659
+ const cached = this.cache.get(audience);
9660
+ if (cached && Date.parse(cached.expires_at) - Date.now() > MIN_REMAINING_MS) return createSuccessResult(cached);
9661
+ let pending = this.inflight.get(audience);
9662
+ if (!pending) {
9663
+ pending = this.mint(audience).finally(() => this.inflight.delete(audience));
9664
+ this.inflight.set(audience, pending);
9665
+ }
9666
+ return pending;
9642
9667
  }
9643
- getNextRefreshDelayMs() {
9644
- return this.nextRefreshDelayMs;
9668
+ async mint(audience) {
9669
+ let response;
9670
+ try {
9671
+ response = await this.request("/v1/engine/workspace-identity/token", { body: { audience } });
9672
+ } catch (error) {
9673
+ return createErrorResult({ message: error instanceof Error ? error.message : "Workspace identity request failed", code: 503 });
9674
+ }
9675
+ if (!response.ok) {
9676
+ return createErrorResult({ message: `Workspace identity request failed: ${response.status} ${await response.text()}`, code: response.status === 400 ? 400 : 503 });
9677
+ }
9678
+ const data = await response.json().catch(() => null);
9679
+ if (isRecord(data) && data.configured === false) {
9680
+ return createErrorResult({ message: "Workspace identity is not enabled for this workspace", code: 503 });
9681
+ }
9682
+ const parsed = workspaceTokenResponseSchema.safeParse(data);
9683
+ const legacy = parsed.success ? null : legacyWorkspaceTokenBundleSchema.safeParse(data);
9684
+ const token = parsed.success ? parsed.data : legacy?.success && legacy.data.tokens[audience] ? { issuer: legacy.data.issuer, audience, ...legacy.data.tokens[audience] } : null;
9685
+ if (!token) {
9686
+ return createErrorResult({ message: `Workspace identity token for ${audience} is unavailable from this Replicas version`, code: 503 });
9687
+ }
9688
+ this.cache.delete(audience);
9689
+ const oldest = this.cache.keys().next();
9690
+ if (this.cache.size >= MAX_CACHED_AUDIENCES && !oldest.done) this.cache.delete(oldest.value);
9691
+ this.cache.set(audience, token);
9692
+ return createSuccessResult(token);
9645
9693
  }
9646
9694
  };
9647
- var workspaceIdentityTokenManager = new WorkspaceIdentityTokenManager();
9695
+ var workspaceIdentityTokens = new WorkspaceIdentityTokens();
9648
9696
 
9649
9697
  // src/identity-proxy.ts
9650
9698
  import http from "http";
@@ -9661,6 +9709,7 @@ var STRIPPED_HEADERS = /* @__PURE__ */ new Set([
9661
9709
  "trailer",
9662
9710
  "upgrade"
9663
9711
  ]);
9712
+ var MAX_TOKEN_REQUEST_BYTES = 4096;
9664
9713
  var decode = (segment) => Buffer.from(segment, "base64url").toString("utf8");
9665
9714
  function resolveIdentityRoute(requestUrl) {
9666
9715
  const url3 = new URL(requestUrl, "http://127.0.0.1");
@@ -9678,24 +9727,59 @@ function resolveIdentityRoute(requestUrl) {
9678
9727
  target.search = url3.search;
9679
9728
  return { target, audience: decode(encodedAudience) };
9680
9729
  }
9681
- function createIdentityProxy(getBundle) {
9682
- return http.createServer((request, response) => {
9730
+ function readJsonBody(request) {
9731
+ return new Promise((resolve8) => {
9732
+ const chunks = [];
9733
+ let size = 0;
9734
+ request.on("data", (chunk) => {
9735
+ size += chunk.length;
9736
+ if (size <= MAX_TOKEN_REQUEST_BYTES) chunks.push(chunk);
9737
+ });
9738
+ request.on("end", () => {
9739
+ if (size > MAX_TOKEN_REQUEST_BYTES) return resolve8(null);
9740
+ const text = Buffer.concat(chunks).toString("utf8").trim();
9741
+ try {
9742
+ resolve8(text ? JSON.parse(text) : {});
9743
+ } catch {
9744
+ resolve8(null);
9745
+ }
9746
+ });
9747
+ request.on("error", () => resolve8(null));
9748
+ });
9749
+ }
9750
+ function createIdentityProxy(tokens) {
9751
+ return http.createServer(async (request, response) => {
9752
+ const url3 = new URL(request.url ?? "/", "http://127.0.0.1");
9753
+ if (url3.pathname === IDENTITY_TOKEN_PATH) {
9754
+ if (request.method !== "POST") {
9755
+ response.writeHead(405, { allow: "POST" }).end();
9756
+ return;
9757
+ }
9758
+ const body = workspaceTokenRequestSchema.safeParse(await readJsonBody(request));
9759
+ if (!body.success) {
9760
+ response.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ error: 'Body must be JSON with an optional printable "audience" string' }));
9761
+ return;
9762
+ }
9763
+ const result = await tokens.get(body.data.audience);
9764
+ response.writeHead(result.ok ? 200 : result.error.code ?? 503, { "content-type": "application/json", "cache-control": "no-store" });
9765
+ response.end(JSON.stringify(result.ok ? result.data : { error: result.error.message }));
9766
+ return;
9767
+ }
9683
9768
  const route = resolveIdentityRoute(request.url ?? "/");
9684
9769
  if (!route) {
9685
9770
  response.writeHead(404).end("Unknown identity route");
9686
9771
  return;
9687
9772
  }
9688
- const bundle = getBundle();
9689
- const token = bundle && currentWorkspaceToken(bundle, route.audience);
9690
- if (!token) {
9691
- response.writeHead(503).end("Workspace token unavailable; waiting for renewal");
9773
+ const token = await tokens.get(route.audience);
9774
+ if (!token.ok) {
9775
+ response.writeHead(token.error.code ?? 503).end(token.error.message);
9692
9776
  return;
9693
9777
  }
9694
9778
  const headers = { host: route.target.host };
9695
9779
  for (const [name, value] of Object.entries(request.headers)) {
9696
9780
  if (!STRIPPED_HEADERS.has(name) && !name.startsWith("x-replicas-") && value !== void 0) headers[name] = value;
9697
9781
  }
9698
- headers.authorization = `Bearer ${token}`;
9782
+ headers.authorization = `Bearer ${token.data.token}`;
9699
9783
  const upstream = (route.target.protocol === "https:" ? https : http).request(
9700
9784
  route.target,
9701
9785
  { method: request.method, headers },
@@ -9729,8 +9813,8 @@ var StreamWriter = class {
9729
9813
  backpressured = false;
9730
9814
  droppedCount = 0;
9731
9815
  flushTimer = null;
9732
- open(path8, highWaterMark = DEFAULT_HIGH_WATER) {
9733
- this.stream = createWriteStream(path8, { flags: "a", highWaterMark });
9816
+ open(path7, highWaterMark = DEFAULT_HIGH_WATER) {
9817
+ this.stream = createWriteStream(path7, { flags: "a", highWaterMark });
9734
9818
  this.stream.on("error", () => {
9735
9819
  this.stream = null;
9736
9820
  });
@@ -9752,9 +9836,9 @@ var StreamWriter = class {
9752
9836
  return true;
9753
9837
  }
9754
9838
  flush(signal) {
9755
- return new Promise((resolve7, reject) => {
9839
+ return new Promise((resolve8, reject) => {
9756
9840
  if (!this.stream) {
9757
- resolve7();
9841
+ resolve8();
9758
9842
  return;
9759
9843
  }
9760
9844
  if (this.flushTimer) {
@@ -9771,7 +9855,7 @@ var StreamWriter = class {
9771
9855
  s.write("", (error) => {
9772
9856
  signal?.removeEventListener("abort", onAbort);
9773
9857
  if (error) reject(error);
9774
- else resolve7();
9858
+ else resolve8();
9775
9859
  });
9776
9860
  });
9777
9861
  }
@@ -10395,7 +10479,7 @@ var ReplicasConfigService = class {
10395
10479
  await this.logToFile(`[${params.repoName}] --- Running: ${params.label} ---`);
10396
10480
  emit(`$ ${params.label}
10397
10481
  `);
10398
- return new Promise((resolve7) => {
10482
+ return new Promise((resolve8) => {
10399
10483
  const proc = spawn2("bash", ["-lc", params.command], {
10400
10484
  cwd: params.cwd,
10401
10485
  env: process.env,
@@ -10406,7 +10490,7 @@ var ReplicasConfigService = class {
10406
10490
  const finish = (result) => {
10407
10491
  if (settled) return;
10408
10492
  settled = true;
10409
- resolve7(result);
10493
+ resolve8(result);
10410
10494
  };
10411
10495
  const timer = setTimeout(() => {
10412
10496
  timedOut = true;
@@ -10832,7 +10916,7 @@ async function registerDesktopPreview() {
10832
10916
  if (await attemptRegistration()) {
10833
10917
  return;
10834
10918
  }
10835
- await new Promise((resolve7) => setTimeout(resolve7, RETRY_DELAY_MS));
10919
+ await new Promise((resolve8) => setTimeout(resolve8, RETRY_DELAY_MS));
10836
10920
  }
10837
10921
  console.error(
10838
10922
  `[DesktopPreview] Gave up registering port ${DESKTOP_STREAM_PORT} after ${REGISTRATION_TIMEOUT_MS}ms`
@@ -10840,7 +10924,7 @@ async function registerDesktopPreview() {
10840
10924
  }
10841
10925
 
10842
10926
  // src/services/chat/chat-service.ts
10843
- import { appendFile as appendFile5, copyFile as copyFile2, mkdir as mkdir22, readFile as readFile22, rename as rename5, rm as rm5 } from "fs/promises";
10927
+ import { appendFile as appendFile5, copyFile as copyFile2, mkdir as mkdir22, readFile as readFile22, rename as rename5, rm as rm4 } from "fs/promises";
10844
10928
  import { join as join37 } from "path";
10845
10929
  import { randomUUID as randomUUID13 } from "crypto";
10846
10930
 
@@ -11489,7 +11573,7 @@ async function saveNormalizedImagesToTempFiles(images, tempImageDir = join13(hom
11489
11573
  return tempPaths;
11490
11574
  }
11491
11575
  async function removeTempImageFiles(paths) {
11492
- await Promise.allSettled(paths.map((path8) => unlink2(path8)));
11576
+ await Promise.allSettled(paths.map((path7) => unlink2(path7)));
11493
11577
  }
11494
11578
 
11495
11579
  // src/managers/coding-agent-manager.ts
@@ -12322,6 +12406,22 @@ var CHECK_TIMEOUT_MS = 3e4;
12322
12406
  var PullRequestCheckService = class {
12323
12407
  running = null;
12324
12408
  trailing = null;
12409
+ async recordPublishedPullRequest(url3) {
12410
+ if (await gitService.recordPublishedPullRequest(url3)) {
12411
+ this.check().catch((error) => console.error("[PullRequestCheck] Failed to report published PR:", error));
12412
+ }
12413
+ }
12414
+ async onToolResult(result) {
12415
+ if (!result.success) return;
12416
+ const urls = publishedPullRequestUrls(result);
12417
+ try {
12418
+ for (const url3 of urls) await gitService.recordPublishedPullRequest(url3);
12419
+ } finally {
12420
+ if (urls.length > 0 || shouldRefreshPullRequests(result.toolName, result.toolInput)) {
12421
+ this.check().catch((error) => console.error("[PullRequestCheck] Failed to report tool result:", error));
12422
+ }
12423
+ }
12424
+ }
12325
12425
  // Plain single-flight would hand a caller a result gathered before its PR
12326
12426
  // existed, so callers arriving mid-run instead share one trailing run that
12327
12427
  // starts after the current one settles.
@@ -12351,7 +12451,7 @@ var pullRequestCheckService = new PullRequestCheckService();
12351
12451
 
12352
12452
  // src/services/skill-registry-service.ts
12353
12453
  import { readFile as readFile9, readdir as readdir3, stat as stat2 } from "fs/promises";
12354
- import { dirname as dirname3, isAbsolute, join as join15, relative, resolve } from "path";
12454
+ import { dirname as dirname3, isAbsolute, join as join15, relative, resolve as resolve2 } from "path";
12355
12455
  var REGISTRY_ROOT_DIR = ".replicas/skill-registries";
12356
12456
  var REGISTRY_MANIFEST = "manifest.json";
12357
12457
  async function getSkillRegistryInventory(homeDir) {
@@ -12384,7 +12484,7 @@ async function getSkillRegistryInventory(homeDir) {
12384
12484
  async function buildClaudeRegistryConfig(homeDir) {
12385
12485
  const inventory = await getSkillRegistryInventory(homeDir);
12386
12486
  return {
12387
- plugins: inventory.claudePluginRoots.map((path8) => ({ type: "local", path: path8 })),
12487
+ plugins: inventory.claudePluginRoots.map((path7) => ({ type: "local", path: path7 })),
12388
12488
  enableAllSkills: inventory.claudePluginRoots.length > 0 || inventory.standaloneSkills.length > 0
12389
12489
  };
12390
12490
  }
@@ -12542,31 +12642,31 @@ function uniqueStandaloneSkills(skills) {
12542
12642
  }
12543
12643
  return unique;
12544
12644
  }
12545
- async function safeReadDir(path8) {
12645
+ async function safeReadDir(path7) {
12546
12646
  try {
12547
- return await readdir3(path8, { withFileTypes: true });
12647
+ return await readdir3(path7, { withFileTypes: true });
12548
12648
  } catch (error) {
12549
12649
  if (isNotFoundError(error)) return [];
12550
12650
  throw error;
12551
12651
  }
12552
12652
  }
12553
- async function isDirectoryDirent(dirent, path8) {
12653
+ async function isDirectoryDirent(dirent, path7) {
12554
12654
  if (dirent.isDirectory()) return true;
12555
12655
  if (!dirent.isSymbolicLink()) return false;
12556
- return directoryExists(path8);
12656
+ return directoryExists(path7);
12557
12657
  }
12558
- async function directoryExists(path8) {
12658
+ async function directoryExists(path7) {
12559
12659
  try {
12560
- const pathStat = await stat2(path8);
12660
+ const pathStat = await stat2(path7);
12561
12661
  return pathStat.isDirectory();
12562
12662
  } catch (error) {
12563
12663
  if (isNotFoundError(error)) return false;
12564
12664
  throw error;
12565
12665
  }
12566
12666
  }
12567
- async function fileExists(path8) {
12667
+ async function fileExists(path7) {
12568
12668
  try {
12569
- const pathStat = await stat2(path8);
12669
+ const pathStat = await stat2(path7);
12570
12670
  return pathStat.isFile();
12571
12671
  } catch (error) {
12572
12672
  if (isNotFoundError(error)) return false;
@@ -12574,8 +12674,8 @@ async function fileExists(path8) {
12574
12674
  }
12575
12675
  }
12576
12676
  function isPathInside(parentPath, childPath) {
12577
- const parent = resolve(parentPath);
12578
- const child = resolve(childPath);
12677
+ const parent = resolve2(parentPath);
12678
+ const child = resolve2(childPath);
12579
12679
  const childRelativePath = relative(parent, child);
12580
12680
  return childRelativePath === "" || !childRelativePath.startsWith("..") && !isAbsolute(childRelativePath);
12581
12681
  }
@@ -12842,8 +12942,8 @@ var PromptStream = class {
12842
12942
  if (this.closed) {
12843
12943
  return Promise.resolve({ value: void 0, done: true });
12844
12944
  }
12845
- return new Promise((resolve7) => {
12846
- this.waiters.push(resolve7);
12945
+ return new Promise((resolve8) => {
12946
+ this.waiters.push(resolve8);
12847
12947
  });
12848
12948
  }
12849
12949
  };
@@ -13230,14 +13330,14 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13230
13330
  const requestId = randomUUID5();
13231
13331
  const toolUseId = options.toolUseID;
13232
13332
  const { options: requestOptions, questions: requestQuestions } = handler.getRequest(input);
13233
- const result = await new Promise((resolve7) => {
13333
+ const result = await new Promise((resolve8) => {
13234
13334
  this.pendingToolInputs.set(requestId, {
13235
13335
  requestId,
13236
13336
  toolUseId,
13237
13337
  toolName,
13238
13338
  input,
13239
13339
  handler,
13240
- resolve: resolve7
13340
+ resolve: resolve8
13241
13341
  });
13242
13342
  const onAbort = () => {
13243
13343
  const pending = this.pendingToolInputs.get(requestId);
@@ -13388,7 +13488,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13388
13488
  error
13389
13489
  );
13390
13490
  await this.tearDownSession();
13391
- await new Promise((resolve7) => setTimeout(resolve7, delayMs));
13491
+ await new Promise((resolve8) => setTimeout(resolve8, delayMs));
13392
13492
  currentRequest = { ...request, message: CLAUDE_MIDTURN_CONTINUE_PROMPT, images: [] };
13393
13493
  attempt++;
13394
13494
  continue;
@@ -13401,7 +13501,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13401
13501
  error
13402
13502
  );
13403
13503
  await this.tearDownSession();
13404
- await new Promise((resolve7) => setTimeout(resolve7, delayMs));
13504
+ await new Promise((resolve8) => setTimeout(resolve8, delayMs));
13405
13505
  attempt++;
13406
13506
  continue;
13407
13507
  }
@@ -13562,8 +13662,8 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13562
13662
  this.pendingInterrupt = false;
13563
13663
  return;
13564
13664
  }
13565
- await new Promise((resolve7, reject) => {
13566
- this.pendingTurn = { resolve: resolve7, reject, sawActivity: false, userMessageUuid };
13665
+ await new Promise((resolve8, reject) => {
13666
+ this.pendingTurn = { resolve: resolve8, reject, sawActivity: false, userMessageUuid };
13567
13667
  promptStream.push(userMessage);
13568
13668
  });
13569
13669
  }
@@ -14248,6 +14348,11 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14248
14348
  this.supportedSlashCommands = normalizeClaudeSlashCommands(message.commands);
14249
14349
  this.slashCommandsDiscoveredAt = Date.now();
14250
14350
  }
14351
+ if (message.type === "system" && String(message.subtype) === "code_change_published" && "url" in message && typeof message.url === "string") {
14352
+ await pullRequestCheckService.recordPublishedPullRequest(message.url).catch((error) => {
14353
+ console.error("[ClaudeManager] Failed to record published PR:", error);
14354
+ });
14355
+ }
14251
14356
  this.trackNativeCompaction(message);
14252
14357
  if (message.type === "system" && message.subtype === "task_started" && message.ambient) {
14253
14358
  this.ambientTaskIds.add(message.task_id);
@@ -14472,16 +14577,16 @@ function transcriptItemsForTurn(turn) {
14472
14577
  const otherItems = turn.items.filter((item) => item.type !== "userMessage");
14473
14578
  return [...userItems, ...otherItems];
14474
14579
  }
14475
- function userImageForLocalPath(path8) {
14476
- const cached = localImageCache.get(path8);
14580
+ function userImageForLocalPath(path7) {
14581
+ const cached = localImageCache.get(path7);
14477
14582
  if (cached) return cached;
14478
- if (!existsSync7(path8)) return null;
14583
+ if (!existsSync7(path7)) return null;
14479
14584
  const image = {
14480
14585
  type: "image",
14481
- mediaType: inferMediaType(path8),
14482
- data: readFileSync3(path8).toString("base64")
14586
+ mediaType: inferMediaType(path7),
14587
+ data: readFileSync3(path7).toString("base64")
14483
14588
  };
14484
- if (image.data.length > 0) localImageCache.set(path8, image);
14589
+ if (image.data.length > 0) localImageCache.set(path7, image);
14485
14590
  return image;
14486
14591
  }
14487
14592
  function userImagesForInput(input) {
@@ -14772,9 +14877,9 @@ async function buildTurnInput(request) {
14772
14877
  }
14773
14878
  const normalizedImages = await normalizeImages(request.images);
14774
14879
  const tempImagePaths = await saveNormalizedImagesToTempFiles(normalizedImages);
14775
- input.push(...tempImagePaths.map((path8) => ({
14880
+ input.push(...tempImagePaths.map((path7) => ({
14776
14881
  type: "localImage",
14777
- path: path8
14882
+ path: path7
14778
14883
  })));
14779
14884
  return { input, tempImagePaths };
14780
14885
  }
@@ -15429,8 +15534,8 @@ ${text.slice(-24e3)}`
15429
15534
  }
15430
15535
  async observeTurn(host, threadId, request, startTurn) {
15431
15536
  let resolveCompleted;
15432
- const completed = new Promise((resolve7) => {
15433
- resolveCompleted = resolve7;
15537
+ const completed = new Promise((resolve8) => {
15538
+ resolveCompleted = resolve8;
15434
15539
  });
15435
15540
  let rejectDisposed = () => {
15436
15541
  };
@@ -15527,8 +15632,10 @@ ${text.slice(-24e3)}`
15527
15632
  );
15528
15633
  linearForwarder.sendEvent(convertCodexAspNotification(notification, linearSessionId ?? ""));
15529
15634
  const completedItem = notification.params.item;
15530
- if (completedItem.type === "commandExecution" && completedItem.exitCode === 0 && shouldRefreshPullRequests("commandExecution", { command: completedItem.command }) || completedItem.type === "mcpToolCall" && completedItem.status === "completed" && shouldRefreshPullRequests(completedItem.tool, completedItem.arguments) || completedItem.type === "dynamicToolCall" && completedItem.success !== false && shouldRefreshPullRequests(completedItem.tool, completedItem.arguments)) {
15531
- pullRequestCheckService.check().catch(() => {
15635
+ const toolResult = completedItem.type === "commandExecution" ? { toolName: "commandExecution", toolInput: { command: completedItem.command }, output: completedItem.aggregatedOutput, success: completedItem.exitCode === 0 } : completedItem.type === "mcpToolCall" ? { toolName: completedItem.tool, toolInput: completedItem.arguments, output: completedItem.result, success: completedItem.status === "completed" && !completedItem.error } : completedItem.type === "dynamicToolCall" ? { toolName: completedItem.tool, toolInput: completedItem.arguments, output: completedItem.contentItems, success: completedItem.success === true } : null;
15636
+ if (toolResult) {
15637
+ pullRequestCheckService.onToolResult(toolResult).catch((error) => {
15638
+ console.error("[CodexAspManager] Failed to capture published PR:", error);
15532
15639
  });
15533
15640
  }
15534
15641
  },
@@ -15975,12 +16082,12 @@ var postToolHookPath = [
15975
16082
  join18(moduleDirectory, "post-tool-pr-hook.js"),
15976
16083
  join18(moduleDirectory, "..", "post-tool-pr-hook.ts")
15977
16084
  ].find(existsSync8);
15978
- function shellCommand(path8, provider) {
15979
- if (!path8) throw new Error("Replicas hook executable is missing.");
16085
+ function shellCommand(path7, provider) {
16086
+ if (!path7) throw new Error("Replicas hook executable is missing.");
15980
16087
  const args = [
15981
16088
  process.execPath,
15982
- ...path8.endsWith(".ts") && basename(process.execPath) !== "bun" ? ["--import", "tsx"] : [],
15983
- path8,
16089
+ ...path7.endsWith(".ts") && basename(process.execPath) !== "bun" ? ["--import", "tsx"] : [],
16090
+ path7,
15984
16091
  ...provider ? [provider] : []
15985
16092
  ];
15986
16093
  return args.map((value) => `'${value.replaceAll("'", "'\\''")}'`).join(" ");
@@ -15994,10 +16101,10 @@ function getPostToolPrHookPath() {
15994
16101
  return postToolHookPath;
15995
16102
  }
15996
16103
  async function ensureCursorCommandProtectionHook() {
15997
- const path8 = join18(ENGINE_ENV.HOME_DIR, ".cursor", "hooks.json");
16104
+ const path7 = join18(ENGINE_ENV.HOME_DIR, ".cursor", "hooks.json");
15998
16105
  let config = {};
15999
16106
  try {
16000
- const parsed = JSON.parse(await readFile11(path8, "utf8"));
16107
+ const parsed = JSON.parse(await readFile11(path7, "utf8"));
16001
16108
  if (!isRecord2(parsed)) throw new Error("Invalid Cursor hooks configuration.");
16002
16109
  config = parsed;
16003
16110
  } catch (error) {
@@ -16014,15 +16121,15 @@ async function ensureCursorCommandProtectionHook() {
16014
16121
  ...existingPost.filter((entry) => !isRecord2(entry) || typeof entry.command !== "string" || !entry.command.includes("post-tool-pr-hook")),
16015
16122
  { command: shellCommand(postToolHookPath) }
16016
16123
  ];
16017
- await mkdir12(dirname5(path8), { recursive: true });
16018
- await writeFile7(path8, `${JSON.stringify({ ...config, version: 1, hooks }, null, 2)}
16124
+ await mkdir12(dirname5(path7), { recursive: true });
16125
+ await writeFile7(path7, `${JSON.stringify({ ...config, version: 1, hooks }, null, 2)}
16019
16126
  `, "utf8");
16020
16127
  }
16021
16128
  async function ensureGeminiCommandProtectionHook() {
16022
- const path8 = join18(ENGINE_ENV.HOME_DIR, ".gemini", "settings.json");
16129
+ const path7 = join18(ENGINE_ENV.HOME_DIR, ".gemini", "settings.json");
16023
16130
  let config = {};
16024
16131
  try {
16025
- const parsed = JSON.parse(await readFile11(path8, "utf8"));
16132
+ const parsed = JSON.parse(await readFile11(path7, "utf8"));
16026
16133
  if (!isRecord2(parsed)) throw new Error("Invalid Gemini hooks configuration.");
16027
16134
  config = parsed;
16028
16135
  } catch (error) {
@@ -16042,17 +16149,17 @@ async function ensureGeminiCommandProtectionHook() {
16042
16149
  ...without(hooks.AfterTool, "replicas-post-tool-pr-check"),
16043
16150
  hook("replicas-post-tool-pr-check", shellCommand(postToolHookPath))
16044
16151
  ];
16045
- await mkdir12(dirname5(path8), { recursive: true });
16046
- await writeFile7(path8, `${JSON.stringify({ ...config, hooks }, null, 2)}
16152
+ await mkdir12(dirname5(path7), { recursive: true });
16153
+ await writeFile7(path7, `${JSON.stringify({ ...config, hooks }, null, 2)}
16047
16154
  `, "utf8");
16048
16155
  }
16049
16156
  async function ensureKimiCommandProtectionHook() {
16050
- const path8 = join18(ENGINE_ENV.HOME_DIR, ".kimi-code", "config.toml");
16157
+ const path7 = join18(ENGINE_ENV.HOME_DIR, ".kimi-code", "config.toml");
16051
16158
  const start = "# Replicas command protection hook";
16052
16159
  const end = "# End Replicas command protection hook";
16053
16160
  let config = "";
16054
16161
  try {
16055
- config = await readFile11(path8, "utf8");
16162
+ config = await readFile11(path7, "utf8");
16056
16163
  } catch (error) {
16057
16164
  if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
16058
16165
  }
@@ -16071,8 +16178,8 @@ ${end}`;
16071
16178
  const markerEnd = config.indexOf(end, markerStart + start.length);
16072
16179
  config = markerStart >= 0 && markerEnd >= 0 ? `${config.slice(0, markerStart)}${block}${config.slice(markerEnd + end.length)}` : `${config.trimEnd()}${config.trim() ? "\n\n" : ""}${block}
16073
16180
  `;
16074
- await mkdir12(dirname5(path8), { recursive: true });
16075
- await writeFile7(path8, config, "utf8");
16181
+ await mkdir12(dirname5(path7), { recursive: true });
16182
+ await writeFile7(path7, config, "utf8");
16076
16183
  }
16077
16184
 
16078
16185
  // src/managers/cursor-run-recovery.ts
@@ -16285,8 +16392,8 @@ var CursorManager = class extends CodingAgentManager {
16285
16392
  let agent = null;
16286
16393
  let sawCursorActivity = false;
16287
16394
  let reconnectNoticeTimer = null;
16288
- const aborted = new Promise((resolve7) => {
16289
- this.abortActiveTurn = () => resolve7(TURN_ABORTED);
16395
+ const aborted = new Promise((resolve8) => {
16396
+ this.abortActiveTurn = () => resolve8(TURN_ABORTED);
16290
16397
  });
16291
16398
  const linearSessionId = this.linearSessionId;
16292
16399
  const linearForwarder = new LinearEventForwarder(linearSessionId);
@@ -16641,8 +16748,8 @@ var DeepseekApiClient = class extends AbstractApiClient {
16641
16748
  if (!execution.success) throw new Error(`DeepSeek Harness did not recognize ${line}.`);
16642
16749
  if (execution.data.result.kind === "error") throw new Error(execution.data.result.text ?? `DeepSeek Harness rejected ${line}.`);
16643
16750
  }
16644
- async *readWebSocket(path8, signal, schema, onOpen) {
16645
- const url3 = new URL(path8, this.baseUrl);
16751
+ async *readWebSocket(path7, signal, schema, onOpen) {
16752
+ const url3 = new URL(path7, this.baseUrl);
16646
16753
  url3.protocol = url3.protocol === "https:" ? "wss:" : "ws:";
16647
16754
  const socket = new WebSocket(url3);
16648
16755
  const inbox = [];
@@ -16672,8 +16779,8 @@ var DeepseekApiClient = class extends AbstractApiClient {
16672
16779
  if (item === null) return;
16673
16780
  if (item) yield item;
16674
16781
  }
16675
- await new Promise((resolve7) => {
16676
- wake = resolve7;
16782
+ await new Promise((resolve8) => {
16783
+ wake = resolve8;
16677
16784
  });
16678
16785
  }
16679
16786
  } finally {
@@ -16832,7 +16939,7 @@ var DeepseekManager = class extends CodingAgentManager {
16832
16939
  stdio: ["ignore", "pipe", "pipe"]
16833
16940
  });
16834
16941
  this.process = child;
16835
- const baseUrl = await new Promise((resolve7, reject) => {
16942
+ const baseUrl = await new Promise((resolve8, reject) => {
16836
16943
  let stdout = "";
16837
16944
  let stderr = "";
16838
16945
  const timeout = setTimeout(() => {
@@ -16844,7 +16951,7 @@ var DeepseekManager = class extends CodingAgentManager {
16844
16951
  const match = stdout.match(/dsh web:\s+(http:\/\/[^\s]+)/);
16845
16952
  if (!match?.[1]) return;
16846
16953
  clearTimeout(timeout);
16847
- resolve7(match[1]);
16954
+ resolve8(match[1]);
16848
16955
  });
16849
16956
  child.stderr?.on("data", (chunk) => {
16850
16957
  stderr = (stderr + chunk.toString()).slice(-8e3);
@@ -17018,8 +17125,8 @@ var DeepseekManager = class extends CodingAgentManager {
17018
17125
  }));
17019
17126
  }
17020
17127
  this.recordUserMessageHistoryEvent(request, this.historyFile);
17021
- this.turnCompletion = new Promise((resolve7) => {
17022
- this.resolveTurnCompletion = resolve7;
17128
+ this.turnCompletion = new Promise((resolve8) => {
17129
+ this.resolveTurnCompletion = resolve8;
17023
17130
  });
17024
17131
  const images = await normalizeImages(request.images ?? []);
17025
17132
  const combinedInstructions = this.activeAgentPreset ? "" : this.buildCombinedInstructions(request.customInstructions);
@@ -17294,8 +17401,8 @@ var AcpManager = class extends CodingAgentManager {
17294
17401
  outputByteLimit,
17295
17402
  truncated: false,
17296
17403
  exitStatus: null,
17297
- exited: new Promise((resolve7) => {
17298
- resolveExit = resolve7;
17404
+ exited: new Promise((resolve8) => {
17405
+ resolveExit = resolve8;
17299
17406
  })
17300
17407
  };
17301
17408
  const append = (chunk) => {
@@ -17411,8 +17518,8 @@ var AcpManager = class extends CodingAgentManager {
17411
17518
  if (!this.interactiveTools) return { outcome: { outcome: "cancelled" } };
17412
17519
  const requestId = randomUUID7();
17413
17520
  const toolCallId = params.toolCall.toolCallId;
17414
- return new Promise((resolve7) => {
17415
- this.pendingPermissions.set(requestId, { toolCallId, options: params.options, resolve: resolve7 });
17521
+ return new Promise((resolve8) => {
17522
+ this.pendingPermissions.set(requestId, { toolCallId, options: params.options, resolve: resolve8 });
17416
17523
  this.recordHistoryEvent("acp-session-update", {
17417
17524
  provider: this.acp.provider,
17418
17525
  update: { ...params.toolCall, sessionUpdate: "tool_call", status: "pending" }
@@ -17565,14 +17672,14 @@ ${request.message}` : request.message
17565
17672
  async function ensureResolvableDnsConfig() {
17566
17673
  const contents = await readFile15("/etc/resolv.conf");
17567
17674
  if (contents.length === 0 || contents.at(-1) === 10) return;
17568
- await new Promise((resolve7, reject) => {
17675
+ await new Promise((resolve8, reject) => {
17569
17676
  const child = spawn5("sudo", ["tee", "-a", "/etc/resolv.conf"], { stdio: ["pipe", "ignore", "pipe"] });
17570
17677
  let stderr = "";
17571
17678
  child.stderr.on("data", (chunk) => {
17572
17679
  stderr += chunk;
17573
17680
  });
17574
17681
  child.on("error", reject);
17575
- child.on("exit", (code) => code === 0 ? resolve7() : reject(new Error(`Failed to normalize /etc/resolv.conf: ${stderr.trim()}`)));
17682
+ child.on("exit", (code) => code === 0 ? resolve8() : reject(new Error(`Failed to normalize /etc/resolv.conf: ${stderr.trim()}`)));
17576
17683
  child.stdin.end("\n");
17577
17684
  });
17578
17685
  }
@@ -17970,8 +18077,8 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
17970
18077
  userMessageRecorded = true;
17971
18078
  }
17972
18079
  if (/^\/compact$/i.test(request.message.trim())) {
17973
- const completed2 = new Promise((resolve7) => {
17974
- this.compactionComplete = { resolve: resolve7 };
18080
+ const completed2 = new Promise((resolve8) => {
18081
+ this.compactionComplete = { resolve: resolve8 };
17975
18082
  });
17976
18083
  const result2 = await this.request("session/compact", {
17977
18084
  commandId: uuidV7(),
@@ -18003,8 +18110,8 @@ ${pending}
18003
18110
 
18004
18111
  ` : ""}${request.planMode ? "Plan the requested work without modifying files or running mutating commands.\n\n" : ""}${request.message}`;
18005
18112
  this.turnError = null;
18006
- const completed = new Promise((resolve7) => {
18007
- this.turnComplete = { resolve: resolve7 };
18113
+ const completed = new Promise((resolve8) => {
18114
+ this.turnComplete = { resolve: resolve8 };
18008
18115
  });
18009
18116
  const result = await this.request("turn/start", {
18010
18117
  commandId: uuidV7(),
@@ -18187,7 +18294,7 @@ ${pending}
18187
18294
 
18188
18295
  // src/managers/opencode-manager.ts
18189
18296
  import { existsSync as existsSync10 } from "fs";
18190
- import { copyFile, mkdir as mkdir17, readFile as readFile16, rm as rm3 } from "fs/promises";
18297
+ import { copyFile, mkdir as mkdir17, readFile as readFile16, rm as rm2 } from "fs/promises";
18191
18298
  import { delimiter, dirname as dirname10, join as join22 } from "path";
18192
18299
  import { randomBytes as randomBytes3 } from "crypto";
18193
18300
  import { fileURLToPath as fileURLToPath3 } from "url";
@@ -18518,8 +18625,8 @@ var OpencodeManager = class extends CodingAgentManager {
18518
18625
  const previousUpdate = this.clientUpdate;
18519
18626
  let finishUpdate = () => {
18520
18627
  };
18521
- this.clientUpdate = new Promise((resolve7) => {
18522
- finishUpdate = resolve7;
18628
+ this.clientUpdate = new Promise((resolve8) => {
18629
+ finishUpdate = resolve8;
18523
18630
  });
18524
18631
  await previousUpdate;
18525
18632
  try {
@@ -18549,7 +18656,7 @@ var OpencodeManager = class extends CodingAgentManager {
18549
18656
  }
18550
18657
  await mkdir17(dirname10(OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH), { recursive: true });
18551
18658
  await copyFile(OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE, OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH);
18552
- await rm3(OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH, { force: true });
18659
+ await rm2(OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH, { force: true });
18553
18660
  process.env.REPLICAS_COMMAND_PROTECTION_HOOK_PATH = getCommandProtectionHookPath();
18554
18661
  process.env.REPLICAS_POST_TOOL_PR_HOOK_PATH = getPostToolPrHookPath();
18555
18662
  process.env.REPLICAS_COMMAND_PROTECTION_RUNTIME_PATH = process.execPath;
@@ -18593,8 +18700,8 @@ var OpencodeManager = class extends CodingAgentManager {
18593
18700
  this.configuredModels = new Set(providerModels);
18594
18701
  const eventController = new AbortController();
18595
18702
  this.eventAbortController = eventController;
18596
- this.eventSubscriptionReady = new Promise((resolve7) => {
18597
- this.resolveEventSubscriptionReady = resolve7;
18703
+ this.eventSubscriptionReady = new Promise((resolve8) => {
18704
+ this.resolveEventSubscriptionReady = resolve8;
18598
18705
  });
18599
18706
  this.subscribeToEvents(client2, eventController).catch((error) => {
18600
18707
  this.resolveEventSubscriptionReady?.();
@@ -18604,7 +18711,7 @@ var OpencodeManager = class extends CodingAgentManager {
18604
18711
  });
18605
18712
  await Promise.race([
18606
18713
  this.eventSubscriptionReady,
18607
- new Promise((resolve7) => setTimeout(resolve7, 2e3))
18714
+ new Promise((resolve8) => setTimeout(resolve8, 2e3))
18608
18715
  ]);
18609
18716
  return client2;
18610
18717
  } finally {
@@ -27439,9 +27546,9 @@ var rev2026Codec = {
27439
27546
  });
27440
27547
  const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta);
27441
27548
  if (!parsed.success) for (const issue of parsed.error.issues) {
27442
- const path8 = issue.path.map(String);
27443
- const key = path8.length > 0 ? path8.join(".") : "_meta";
27444
- if (path8.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue;
27549
+ const path7 = issue.path.map(String);
27550
+ const key = path7.length > 0 ? path7.join(".") : "_meta";
27551
+ if (path7.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue;
27445
27552
  issues.push({
27446
27553
  key,
27447
27554
  problem: issue.message
@@ -27740,29 +27847,29 @@ var PERMITTED_X_MCP_HEADER_TYPES = /* @__PURE__ */ new Set([
27740
27847
  function scanXMcpHeaderDeclarations(inputSchema) {
27741
27848
  const declarations = [];
27742
27849
  const seenLower = /* @__PURE__ */ new Map();
27743
- const visit = (node, path8, reachable) => {
27850
+ const visit = (node, path7, reachable) => {
27744
27851
  if (node === null || typeof node !== "object") return void 0;
27745
27852
  const schema = node;
27746
27853
  if (X_MCP_HEADER_KEY in schema) {
27747
- if (!reachable || path8.length === 0) return `${pathName(path8)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
27854
+ if (!reachable || path7.length === 0) return `${pathName(path7)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
27748
27855
  const raw = schema[X_MCP_HEADER_KEY];
27749
- if (typeof raw !== "string" || raw.length === 0) return `${pathName(path8)}: x-mcp-header MUST be a non-empty string`;
27750
- if (!RFC9110_TOKEN.test(raw)) return `${pathName(path8)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
27856
+ if (typeof raw !== "string" || raw.length === 0) return `${pathName(path7)}: x-mcp-header MUST be a non-empty string`;
27857
+ if (!RFC9110_TOKEN.test(raw)) return `${pathName(path7)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
27751
27858
  const type = typeof schema.type === "string" ? schema.type : void 0;
27752
- if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path8)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
27859
+ if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path7)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
27753
27860
  const lower = raw.toLowerCase();
27754
27861
  const prior = seenLower.get(lower);
27755
27862
  if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;
27756
27863
  seenLower.set(lower, raw);
27757
27864
  declarations.push({
27758
- path: path8,
27865
+ path: path7,
27759
27866
  headerName: raw,
27760
27867
  type
27761
27868
  });
27762
27869
  }
27763
27870
  const properties = schema.properties;
27764
27871
  if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) {
27765
- const fault$1 = visit(child, [...path8, key], reachable);
27872
+ const fault$1 = visit(child, [...path7, key], reachable);
27766
27873
  if (fault$1 !== void 0) return fault$1;
27767
27874
  }
27768
27875
  for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {
@@ -27770,7 +27877,7 @@ function scanXMcpHeaderDeclarations(inputSchema) {
27770
27877
  if (sub === void 0) continue;
27771
27878
  const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub];
27772
27879
  for (const branch of branches) {
27773
- const fault$1 = visit(branch, [...path8, `<${k}>`], false);
27880
+ const fault$1 = visit(branch, [...path7, `<${k}>`], false);
27774
27881
  if (fault$1 !== void 0) return fault$1;
27775
27882
  }
27776
27883
  }
@@ -27810,8 +27917,8 @@ var OBJECT_VALUED_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set([
27810
27917
  "$defs",
27811
27918
  "definitions"
27812
27919
  ]);
27813
- function pathName(path8) {
27814
- return path8.length === 0 ? "<root>" : path8.join(".");
27920
+ function pathName(path7) {
27921
+ return path7.length === 0 ? "<root>" : path7.join(".");
27815
27922
  }
27816
27923
  var BASE64_SENTINEL_PREFIX = "=?base64?";
27817
27924
  var BASE64_SENTINEL_SUFFIX = "?=";
@@ -27844,9 +27951,9 @@ function utf8ToBase64(s) {
27844
27951
  function encodeMcpParamValue(value) {
27845
27952
  return needsBase64(value) ? `${BASE64_SENTINEL_PREFIX}${utf8ToBase64(value)}${BASE64_SENTINEL_SUFFIX}` : value;
27846
27953
  }
27847
- function valueAtPath(root, path8) {
27954
+ function valueAtPath(root, path7) {
27848
27955
  let node = root;
27849
- for (const key of path8) {
27956
+ for (const key of path7) {
27850
27957
  if (node === null || typeof node !== "object") return void 0;
27851
27958
  node = node[key];
27852
27959
  }
@@ -28101,7 +28208,7 @@ var PROPERTY_KEYS_BY_TYPE = {
28101
28208
  array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema])
28102
28209
  };
28103
28210
  var SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options);
28104
- function walkProperty(node, path8, vendor, unsupported) {
28211
+ function walkProperty(node, path7, vendor, unsupported) {
28105
28212
  if (!isJsonObject(node)) return node;
28106
28213
  const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0;
28107
28214
  if (allowedKeys === void 0) return node;
@@ -28109,8 +28216,8 @@ function walkProperty(node, path8, vendor, unsupported) {
28109
28216
  for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value;
28110
28217
  else if (key === "pattern" && node.type === "string" && typeof node.format === "string") {
28111
28218
  if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value;
28112
- else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path8}.${key}`);
28113
- } else unsupported.push(`${path8}.${key}`);
28219
+ else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path7}.${key}`);
28220
+ } else unsupported.push(`${path7}.${key}`);
28114
28221
  return pruned;
28115
28222
  }
28116
28223
  function walkRequestedSchema(converted, vendor) {
@@ -28127,11 +28234,11 @@ function describeUnsupportedProperties(pruned, fallback) {
28127
28234
  const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`);
28128
28235
  return offenders.length > 0 ? offenders.join(", ") : fallback;
28129
28236
  }
28130
- function findDroppedConstraintPaths(original, parsed, path8 = "") {
28131
- if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path8}[${index}]`));
28237
+ function findDroppedConstraintPaths(original, parsed, path7 = "") {
28238
+ if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path7}[${index}]`));
28132
28239
  if (!isJsonObject(original) || !isJsonObject(parsed)) return [];
28133
28240
  return Object.entries(original).flatMap(([key, value]) => {
28134
- const childPath = path8 ? `${path8}.${key}` : key;
28241
+ const childPath = path7 ? `${path7}.${key}` : key;
28135
28242
  if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath];
28136
28243
  return findDroppedConstraintPaths(value, parsed[key], childPath);
28137
28244
  });
@@ -28218,14 +28325,14 @@ function inputRequiredRoundsExceededMessage(method, maxRounds) {
28218
28325
  return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
28219
28326
  }
28220
28327
  function sleep(ms, signal) {
28221
- return new Promise((resolve7, reject) => {
28328
+ return new Promise((resolve8, reject) => {
28222
28329
  if (signal?.aborted) {
28223
28330
  reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason)));
28224
28331
  return;
28225
28332
  }
28226
28333
  const timer = setTimeout(() => {
28227
28334
  signal?.removeEventListener("abort", onAbort);
28228
- resolve7();
28335
+ resolve8();
28229
28336
  }, ms);
28230
28337
  const onAbort = () => {
28231
28338
  clearTimeout(timer);
@@ -29064,7 +29171,7 @@ var Protocol = class {
29064
29171
  const flowStartedAt = Date.now();
29065
29172
  let onAbort;
29066
29173
  let cleanupMessageId;
29067
- return new Promise((resolve7, reject) => {
29174
+ return new Promise((resolve8, reject) => {
29068
29175
  const earlyReject = (error) => {
29069
29176
  reject(error);
29070
29177
  };
@@ -29132,7 +29239,7 @@ var Protocol = class {
29132
29239
  }
29133
29240
  if (decoded.kind === "invalid") return reject(decoded.error);
29134
29241
  if (decoded.kind === "input_required") {
29135
- if (options?.allowInputRequired === true) return resolve7(manualInputRequiredValue(decoded));
29242
+ if (options?.allowInputRequired === true) return resolve8(manualInputRequiredValue(decoded));
29136
29243
  const flow = {
29137
29244
  codec,
29138
29245
  request,
@@ -29144,11 +29251,11 @@ var Protocol = class {
29144
29251
  params
29145
29252
  }, resultSchema, legOptions)
29146
29253
  };
29147
- return resolve7(this._resolveNonCompleteResult(decoded, flow));
29254
+ return resolve8(this._resolveNonCompleteResult(decoded, flow));
29148
29255
  }
29149
29256
  const result = decoded.result;
29150
29257
  validateStandardSchema(resultSchema, result).then((parseResult) => {
29151
- if (parseResult.success) resolve7(parseResult.data);
29258
+ if (parseResult.success) resolve8(parseResult.data);
29152
29259
  else reject(new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`));
29153
29260
  }, reject);
29154
29261
  });
@@ -32100,7 +32207,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
32100
32207
  ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
32101
32208
  const schOrFunc = root.refs[ref];
32102
32209
  if (schOrFunc) return schOrFunc;
32103
- let _sch = resolve7.call(this, root, ref);
32210
+ let _sch = resolve8.call(this, root, ref);
32104
32211
  if (_sch === void 0) {
32105
32212
  const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
32106
32213
  const { schemaId } = this.opts;
@@ -32126,7 +32233,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
32126
32233
  function sameSchemaEnv(s1, s2) {
32127
32234
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
32128
32235
  }
32129
- function resolve7(root, ref) {
32236
+ function resolve8(root, ref) {
32130
32237
  let sch;
32131
32238
  while (typeof (sch = this.refs[ref]) == "string") ref = sch;
32132
32239
  return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
@@ -32311,8 +32418,8 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
32311
32418
  for (let i = 0; i < str.length; i++) if (str[i] === token) ind++;
32312
32419
  return ind;
32313
32420
  }
32314
- function removeDotSegments(path8) {
32315
- let input = path8;
32421
+ function removeDotSegments(path7) {
32422
+ let input = path7;
32316
32423
  const output = [];
32317
32424
  let nextSlash = -1;
32318
32425
  let len = 0;
@@ -32465,8 +32572,8 @@ var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
32465
32572
  wsComponent.secure = void 0;
32466
32573
  }
32467
32574
  if (wsComponent.resourceName) {
32468
- const [path8, query2] = wsComponent.resourceName.split("?");
32469
- wsComponent.path = path8 && path8 !== "/" ? path8 : void 0;
32575
+ const [path7, query2] = wsComponent.resourceName.split("?");
32576
+ wsComponent.path = path7 && path7 !== "/" ? path7 : void 0;
32470
32577
  wsComponent.query = query2;
32471
32578
  wsComponent.resourceName = void 0;
32472
32579
  }
@@ -32576,7 +32683,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
32576
32683
  else if (typeof uri === "object") uri = parse(serialize(uri, options), options);
32577
32684
  return uri;
32578
32685
  }
32579
- function resolve7(baseURI, relativeURI, options) {
32686
+ function resolve8(baseURI, relativeURI, options) {
32580
32687
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
32581
32688
  const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
32582
32689
  schemelessOptions.skipEscape = true;
@@ -32750,7 +32857,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
32750
32857
  const fastUri = {
32751
32858
  SCHEMES,
32752
32859
  normalize,
32753
- resolve: resolve7,
32860
+ resolve: resolve8,
32754
32861
  resolveComponent,
32755
32862
  equal,
32756
32863
  serialize,
@@ -38563,14 +38670,14 @@ var ProbeWindow = class ProbeWindow2 {
38563
38670
  */
38564
38671
  async exchange(buildRequest, timeoutMs) {
38565
38672
  const id = `server-discover-probe-${++this._probeCounter}`;
38566
- return new Promise((resolve7) => {
38673
+ return new Promise((resolve8) => {
38567
38674
  let settled = false;
38568
38675
  const settle = (reply) => {
38569
38676
  if (settled) return;
38570
38677
  settled = true;
38571
38678
  clearTimeout(timer);
38572
38679
  if (this._pending?.id === id) this._pending = void 0;
38573
- resolve7(reply);
38680
+ resolve8(reply);
38574
38681
  };
38575
38682
  const timer = setTimeout(() => settle({ kind: "timeout" }), timeoutMs);
38576
38683
  this._pending = {
@@ -39776,13 +39883,13 @@ var Client = class extends Protocol {
39776
39883
  let onCallerAbort;
39777
39884
  let resolveOpening;
39778
39885
  let rejectOpening;
39779
- const opening = new Promise((resolve7, reject) => {
39780
- resolveOpening = resolve7;
39886
+ const opening = new Promise((resolve8, reject) => {
39887
+ resolveOpening = resolve8;
39781
39888
  rejectOpening = reject;
39782
39889
  });
39783
39890
  let resolveClosed;
39784
- const closed = new Promise((resolve7) => {
39785
- resolveClosed = resolve7;
39891
+ const closed = new Promise((resolve8) => {
39892
+ resolveClosed = resolve8;
39786
39893
  });
39787
39894
  const settle = (outcome) => {
39788
39895
  if (state === "closed") return;
@@ -40262,7 +40369,7 @@ var SSEClientTransport = class {
40262
40369
  }
40263
40370
  _startOrAuth() {
40264
40371
  const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
40265
- return new Promise((resolve7, reject) => {
40372
+ return new Promise((resolve8, reject) => {
40266
40373
  this._eventSource = new EventSource(this._url.href, {
40267
40374
  ...this._eventSourceInit,
40268
40375
  fetch: async (url3, init) => {
@@ -40294,7 +40401,7 @@ var SSEClientTransport = class {
40294
40401
  response,
40295
40402
  serverUrl: this._url,
40296
40403
  fetchFn: this._fetchWithInit
40297
- }).then(() => this._startOrAuth().then(resolve7, reject), (error$2) => {
40404
+ }).then(() => this._startOrAuth().then(resolve8, reject), (error$2) => {
40298
40405
  markAuthSeamEscape(error$2);
40299
40406
  this.onerror?.(error$2);
40300
40407
  reject(error$2);
@@ -40323,7 +40430,7 @@ var SSEClientTransport = class {
40323
40430
  this.close();
40324
40431
  return;
40325
40432
  }
40326
- resolve7();
40433
+ resolve8();
40327
40434
  });
40328
40435
  this._eventSource.onmessage = (event) => {
40329
40436
  const messageEvent = event;
@@ -40999,7 +41106,7 @@ var StreamableHTTPClientTransport = class {
40999
41106
  };
41000
41107
 
41001
41108
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/server-manager.ts
41002
- import { mkdirSync as mkdirSync2, statSync as statSync2 } from "fs";
41109
+ import { mkdirSync as mkdirSync2, statSync as statSync3 } from "fs";
41003
41110
  import { isDeepStrictEqual } from "util";
41004
41111
 
41005
41112
  // ../node_modules/.bun/@modelcontextprotocol+client@2.0.0/node_modules/@modelcontextprotocol/client/dist/stdio.mjs
@@ -41055,7 +41162,7 @@ var StdioClientTransport = class {
41055
41162
  */
41056
41163
  async start() {
41057
41164
  if (this._process) throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");
41058
- return new Promise((resolve7, reject) => {
41165
+ return new Promise((resolve8, reject) => {
41059
41166
  this._process = (0, import_cross_spawn.default)(this._serverParams.command, this._serverParams.args ?? [], {
41060
41167
  env: {
41061
41168
  ...getDefaultEnvironment(),
@@ -41075,7 +41182,7 @@ var StdioClientTransport = class {
41075
41182
  this.onerror?.(error);
41076
41183
  });
41077
41184
  this._process.on("spawn", () => {
41078
- resolve7();
41185
+ resolve8();
41079
41186
  });
41080
41187
  this._process.on("close", (_code) => {
41081
41188
  this._process = void 0;
@@ -41140,7 +41247,7 @@ var StdioClientTransport = class {
41140
41247
  const proc = this._process;
41141
41248
  this._process = void 0;
41142
41249
  if (proc && proc.exitCode === null && proc.signalCode === null) {
41143
- const exited = new Promise((resolve7) => proc.once("exit", () => resolve7()));
41250
+ const exited = new Promise((resolve8) => proc.once("exit", () => resolve8()));
41144
41251
  try {
41145
41252
  proc.stdin?.end();
41146
41253
  } catch {
@@ -41149,7 +41256,7 @@ var StdioClientTransport = class {
41149
41256
  proc.kill("SIGTERM");
41150
41257
  } catch {
41151
41258
  }
41152
- await Promise.race([exited, new Promise((resolve7) => setTimeout(resolve7, 1e3).unref())]);
41259
+ await Promise.race([exited, new Promise((resolve8) => setTimeout(resolve8, 1e3).unref())]);
41153
41260
  if (proc.exitCode === null && proc.signalCode === null) try {
41154
41261
  proc.kill("SIGKILL");
41155
41262
  } catch {
@@ -41174,22 +41281,22 @@ var StdioClientTransport = class {
41174
41281
  if (this._process) {
41175
41282
  const processToClose = this._process;
41176
41283
  this._process = void 0;
41177
- const closePromise = new Promise((resolve7) => {
41284
+ const closePromise = new Promise((resolve8) => {
41178
41285
  processToClose.once("close", () => {
41179
- resolve7();
41286
+ resolve8();
41180
41287
  });
41181
41288
  });
41182
41289
  try {
41183
41290
  processToClose.stdin?.end();
41184
41291
  } catch {
41185
41292
  }
41186
- await Promise.race([closePromise, new Promise((resolve7) => setTimeout(resolve7, 2e3).unref())]);
41293
+ await Promise.race([closePromise, new Promise((resolve8) => setTimeout(resolve8, 2e3).unref())]);
41187
41294
  if (processToClose.exitCode === null) {
41188
41295
  try {
41189
41296
  processToClose.kill("SIGTERM");
41190
41297
  } catch {
41191
41298
  }
41192
- await Promise.race([closePromise, new Promise((resolve7) => setTimeout(resolve7, 2e3).unref())]);
41299
+ await Promise.race([closePromise, new Promise((resolve8) => setTimeout(resolve8, 2e3).unref())]);
41193
41300
  }
41194
41301
  if (processToClose.exitCode === null) try {
41195
41302
  processToClose.kill("SIGKILL");
@@ -41199,11 +41306,11 @@ var StdioClientTransport = class {
41199
41306
  this._readBuffer.clear();
41200
41307
  }
41201
41308
  send(message) {
41202
- return new Promise((resolve7) => {
41309
+ return new Promise((resolve8) => {
41203
41310
  if (!this._process?.stdin) throw new SdkError(SdkErrorCode.NotConnected, "Not connected");
41204
41311
  const json = serializeMessage(message);
41205
- if (this._process.stdin.write(json)) resolve7();
41206
- else this._process.stdin.once("drain", resolve7);
41312
+ if (this._process.stdin.write(json)) resolve8();
41313
+ else this._process.stdin.once("drain", resolve8);
41207
41314
  });
41208
41315
  }
41209
41316
  };
@@ -41224,13 +41331,13 @@ var UnixSocketClientTransport = class {
41224
41331
  if (this.socket) {
41225
41332
  throw new Error("UnixSocketClientTransport already started");
41226
41333
  }
41227
- await new Promise((resolve7, reject) => {
41334
+ await new Promise((resolve8, reject) => {
41228
41335
  const socket = createConnection(this.socketPath);
41229
41336
  this.socket = socket;
41230
41337
  let connected = false;
41231
41338
  socket.once("connect", () => {
41232
41339
  connected = true;
41233
- resolve7();
41340
+ resolve8();
41234
41341
  });
41235
41342
  socket.on("data", (chunk) => {
41236
41343
  try {
@@ -41262,12 +41369,12 @@ var UnixSocketClientTransport = class {
41262
41369
  this.socket = void 0;
41263
41370
  this.readBuffer.clear();
41264
41371
  if (!socket || socket.destroyed) return;
41265
- await new Promise((resolve7) => {
41372
+ await new Promise((resolve8) => {
41266
41373
  const timeout = setTimeout(() => socket.destroy(), 2e3);
41267
41374
  timeout.unref();
41268
41375
  socket.once("close", () => {
41269
41376
  clearTimeout(timeout);
41270
- resolve7();
41377
+ resolve8();
41271
41378
  });
41272
41379
  socket.end();
41273
41380
  });
@@ -41275,10 +41382,10 @@ var UnixSocketClientTransport = class {
41275
41382
  async send(message) {
41276
41383
  const socket = this.socket;
41277
41384
  if (!socket || socket.destroyed) throw new Error("Unix socket is not connected");
41278
- await new Promise((resolve7, reject) => {
41385
+ await new Promise((resolve8, reject) => {
41279
41386
  socket.write(serializeMessage(message), (error) => {
41280
41387
  if (error) reject(error);
41281
- else resolve7();
41388
+ else resolve8();
41282
41389
  });
41283
41390
  });
41284
41391
  }
@@ -41432,8 +41539,8 @@ async function probeMcpEndpoint(url3) {
41432
41539
  }
41433
41540
 
41434
41541
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/npx-resolver.ts
41435
- import { existsSync as existsSync11, readFileSync as readFileSync4, realpathSync, readdirSync, statSync, writeFileSync, renameSync, mkdirSync, openSync, readSync, closeSync, unlinkSync } from "fs";
41436
- import { join as join24, dirname as dirname11, extname as extname2, resolve as resolve2, sep } from "path";
41542
+ import { existsSync as existsSync11, readFileSync as readFileSync4, realpathSync, readdirSync as readdirSync2, statSync as statSync2, writeFileSync, renameSync, mkdirSync, openSync, readSync, closeSync, unlinkSync } from "fs";
41543
+ import { join as join24, dirname as dirname11, extname as extname2, resolve as resolve3, sep } from "path";
41437
41544
 
41438
41545
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/abort.ts
41439
41546
  function throwIfAborted(signal) {
@@ -41443,7 +41550,7 @@ function throwIfAborted(signal) {
41443
41550
  async function abortable(promise, signal) {
41444
41551
  if (!signal) return promise;
41445
41552
  throwIfAborted(signal);
41446
- return await new Promise((resolve7, reject) => {
41553
+ return await new Promise((resolve8, reject) => {
41447
41554
  let settled = false;
41448
41555
  const cleanup = () => signal.removeEventListener("abort", onAbort);
41449
41556
  const onAbort = () => {
@@ -41458,7 +41565,7 @@ async function abortable(promise, signal) {
41458
41565
  if (settled) return;
41459
41566
  settled = true;
41460
41567
  cleanup();
41461
- resolve7(value);
41568
+ resolve8(value);
41462
41569
  },
41463
41570
  (error) => {
41464
41571
  if (settled) return;
@@ -41627,7 +41734,7 @@ function resolveFromNpmCache(packageSpec, binName) {
41627
41734
  const binLink = chosenBinName ? join24(nodeModulesDir, ".bin", chosenBinName) : null;
41628
41735
  let resolvedBin = binLink && existsSync11(binLink) ? safeRealpath(binLink) : "";
41629
41736
  if (!resolvedBin) {
41630
- resolvedBin = resolve2(packageDir, binRel);
41737
+ resolvedBin = resolve3(packageDir, binRel);
41631
41738
  if (!existsSync11(resolvedBin)) return null;
41632
41739
  }
41633
41740
  const isJs = detectJsBinary(resolvedBin);
@@ -41642,7 +41749,7 @@ var FORCE_CACHE_TIMEOUT_MS = 3e4;
41642
41749
  async function forceNpxCache(packageSpec, signal) {
41643
41750
  throwIfAborted(signal);
41644
41751
  try {
41645
- await new Promise((resolve7, reject) => {
41752
+ await new Promise((resolve8, reject) => {
41646
41753
  const proc = (0, import_cross_spawn2.default)(
41647
41754
  "npm",
41648
41755
  ["exec", "--yes", "--package", packageSpec, "--", "node", "-e", "1"],
@@ -41661,7 +41768,7 @@ async function forceNpxCache(packageSpec, signal) {
41661
41768
  proc.on("close", () => {
41662
41769
  clearTimeout(timer);
41663
41770
  signal?.removeEventListener("abort", abort);
41664
- resolve7();
41771
+ resolve8();
41665
41772
  });
41666
41773
  proc.on("error", (err) => {
41667
41774
  clearTimeout(timer);
@@ -41729,7 +41836,7 @@ function findCachedPackageDir(cacheDir, packageName, exactVersion) {
41729
41836
  const npxDir = join24(cacheDir, "_npx");
41730
41837
  if (!existsSync11(npxDir)) return null;
41731
41838
  const packagePathParts = packageName.startsWith("@") ? packageName.split("/") : [packageName];
41732
- const candidates = readdirSync(npxDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => {
41839
+ const candidates = readdirSync2(npxDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => {
41733
41840
  const full = join24(npxDir, entry.name);
41734
41841
  const mtime = safeStatMtime(full);
41735
41842
  return { name: entry.name, mtime };
@@ -41785,8 +41892,8 @@ function getNpmCacheDir() {
41785
41892
  try {
41786
41893
  const result = import_cross_spawn2.default.sync("npm", ["config", "get", "cache"], { encoding: "utf-8" });
41787
41894
  if (result.status === 0) {
41788
- const path8 = String(result.stdout).trim();
41789
- npmCacheDirCached = path8 || null;
41895
+ const path7 = String(result.stdout).trim();
41896
+ npmCacheDirCached = path7 || null;
41790
41897
  return npmCacheDirCached;
41791
41898
  }
41792
41899
  } catch {
@@ -41874,16 +41981,16 @@ function saveCacheEntry(key, entry) {
41874
41981
  } catch {
41875
41982
  }
41876
41983
  }
41877
- function safeRealpath(path8) {
41984
+ function safeRealpath(path7) {
41878
41985
  try {
41879
- return realpathSync(path8);
41986
+ return realpathSync(path7);
41880
41987
  } catch {
41881
41988
  return "";
41882
41989
  }
41883
41990
  }
41884
- function safeStatMtime(path8) {
41991
+ function safeStatMtime(path7) {
41885
41992
  try {
41886
- return statSync(path8).mtimeMs;
41993
+ return statSync2(path7).mtimeMs;
41887
41994
  } catch {
41888
41995
  return 0;
41889
41996
  }
@@ -42628,8 +42735,8 @@ function setOAuthCallbackPort(port2) {
42628
42735
  function getOAuthCallbackPath() {
42629
42736
  return oauthCallbackPath;
42630
42737
  }
42631
- function setOAuthCallbackPath(path8) {
42632
- oauthCallbackPath = path8.startsWith("/") ? path8 : `/${path8}`;
42738
+ function setOAuthCallbackPath(path7) {
42739
+ oauthCallbackPath = path7.startsWith("/") ? path7 : `/${path7}`;
42633
42740
  }
42634
42741
  var reservedAuthorizationParams = /* @__PURE__ */ new Set([
42635
42742
  "client_id",
@@ -43142,7 +43249,7 @@ var McpOAuthProvider = class {
43142
43249
  // ../node_modules/.bun/open@10.2.0/node_modules/open/index.js
43143
43250
  import process9 from "process";
43144
43251
  import { Buffer as Buffer2 } from "buffer";
43145
- import path6 from "path";
43252
+ import path5 from "path";
43146
43253
  import { fileURLToPath as fileURLToPath5 } from "url";
43147
43254
  import { promisify as promisify5 } from "util";
43148
43255
  import childProcess from "child_process";
@@ -43400,8 +43507,8 @@ async function defaultBrowser2() {
43400
43507
 
43401
43508
  // ../node_modules/.bun/open@10.2.0/node_modules/open/index.js
43402
43509
  var execFile5 = promisify5(childProcess.execFile);
43403
- var __dirname = path6.dirname(fileURLToPath5(import.meta.url));
43404
- var localXdgOpenPath = path6.join(__dirname, "xdg-open");
43510
+ var __dirname = path5.dirname(fileURLToPath5(import.meta.url));
43511
+ var localXdgOpenPath = path5.join(__dirname, "xdg-open");
43405
43512
  var { platform, arch } = process9;
43406
43513
  async function getWindowsDefaultBrowserFromWsl() {
43407
43514
  const powershellPath = await powerShellPath();
@@ -43574,14 +43681,14 @@ var baseOpen = async (options) => {
43574
43681
  }
43575
43682
  const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
43576
43683
  if (options.wait) {
43577
- return new Promise((resolve7, reject) => {
43684
+ return new Promise((resolve8, reject) => {
43578
43685
  subprocess.once("error", reject);
43579
43686
  subprocess.once("close", (exitCode) => {
43580
43687
  if (!options.allowNonzeroExitCode && exitCode > 0) {
43581
43688
  reject(new Error(`Exited with code ${exitCode}`));
43582
43689
  return;
43583
43690
  }
43584
- resolve7(subprocess);
43691
+ resolve8(subprocess);
43585
43692
  });
43586
43693
  });
43587
43694
  }
@@ -43909,12 +44016,12 @@ async function ensureCallbackServerLocked(options = {}) {
43909
44016
  const candidateServer = createServer(handleRequest);
43910
44017
  const listenPort = strictPort ? requiredPort : 0;
43911
44018
  try {
43912
- await new Promise((resolve7, reject) => {
44019
+ await new Promise((resolve8, reject) => {
43913
44020
  candidateServer.once("error", (err) => {
43914
44021
  reject(err);
43915
44022
  });
43916
44023
  candidateServer.listen(listenPort, requestedHost, () => {
43917
- resolve7();
44024
+ resolve8();
43918
44025
  });
43919
44026
  });
43920
44027
  if (strictPort) {
@@ -43927,8 +44034,8 @@ async function ensureCallbackServerLocked(options = {}) {
43927
44034
  setOAuthCallbackPort(address.port);
43928
44035
  }
43929
44036
  if (previousServer && (needsStrictRebind || needsHostSwitch)) {
43930
- await new Promise((resolve7) => {
43931
- previousServer.close(() => resolve7());
44037
+ await new Promise((resolve8) => {
44038
+ previousServer.close(() => resolve8());
43932
44039
  });
43933
44040
  }
43934
44041
  callbackServerHost = requestedHost;
@@ -43944,8 +44051,8 @@ async function ensureCallbackServerLocked(options = {}) {
43944
44051
  reservedAuthStates.delete(reservedState);
43945
44052
  }
43946
44053
  const nodeError = error;
43947
- await new Promise((resolve7) => {
43948
- candidateServer.close(() => resolve7());
44054
+ await new Promise((resolve8) => {
44055
+ candidateServer.close(() => resolve8());
43949
44056
  });
43950
44057
  if (strictPort && nodeError.code === "EADDRINUSE") {
43951
44058
  throw new Error(
@@ -43961,14 +44068,14 @@ function releaseCallbackServer(oauthState) {
43961
44068
  }
43962
44069
  function waitForCallback(oauthState) {
43963
44070
  reservedAuthStates.delete(oauthState);
43964
- return new Promise((resolve7, reject) => {
44071
+ return new Promise((resolve8, reject) => {
43965
44072
  const timeout = setTimeout(() => {
43966
44073
  if (pendingAuths.has(oauthState)) {
43967
44074
  pendingAuths.delete(oauthState);
43968
44075
  reject(new Error("OAuth callback timeout - authorization took too long"));
43969
44076
  }
43970
44077
  }, CALLBACK_TIMEOUT_MS);
43971
- pendingAuths.set(oauthState, { resolve: resolve7, reject, timeout });
44078
+ pendingAuths.set(oauthState, { resolve: resolve8, reject, timeout });
43972
44079
  });
43973
44080
  }
43974
44081
  function cancelPendingCallback(oauthState) {
@@ -43993,9 +44100,9 @@ function stopCallbackServer() {
43993
44100
  });
43994
44101
  }
43995
44102
  if (server) {
43996
- await new Promise((resolve7) => {
44103
+ await new Promise((resolve8) => {
43997
44104
  server.close(() => {
43998
- resolve7();
44105
+ resolve8();
43999
44106
  });
44000
44107
  });
44001
44108
  server = void 0;
@@ -45537,7 +45644,7 @@ function humanizeName(name) {
45537
45644
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/mcp-trace.ts
45538
45645
  import { appendFile as appendFile3, mkdir as mkdir18, writeFile as writeFile10 } from "fs/promises";
45539
45646
  import { Buffer as Buffer3 } from "buffer";
45540
- import { dirname as dirname14, isAbsolute as isAbsolute2, resolve as resolve3 } from "path";
45647
+ import { dirname as dirname14, isAbsolute as isAbsolute2, resolve as resolve4 } from "path";
45541
45648
  var MCP_TRACE_SCHEMA_VERSION = 1;
45542
45649
  var DEFAULT_MCP_TRACE_MAX_BYTES = 256 * 1024;
45543
45650
  var DEFAULT_MCP_TRACE_MAX_EVENTS = 1e4;
@@ -45600,14 +45707,14 @@ var McpTraceWriter = class {
45600
45707
  this.options = options;
45601
45708
  this.maxBytes = boundedPositiveInteger(options.maxBytes, DEFAULT_MCP_TRACE_MAX_BYTES);
45602
45709
  this.maxEvents = boundedPositiveInteger(options.maxEvents, DEFAULT_MCP_TRACE_MAX_EVENTS);
45603
- this.append = options.appendFile ?? (async (path8, data, appendOptions) => {
45604
- await appendFile3(path8, data, appendOptions);
45710
+ this.append = options.appendFile ?? (async (path7, data, appendOptions) => {
45711
+ await appendFile3(path7, data, appendOptions);
45605
45712
  });
45606
- this.resetFile = options.writeFile ?? (async (path8, data, writeOptions) => {
45607
- await writeFile10(path8, data, writeOptions);
45713
+ this.resetFile = options.writeFile ?? (async (path7, data, writeOptions) => {
45714
+ await writeFile10(path7, data, writeOptions);
45608
45715
  });
45609
- this.makeDirectory = options.mkdir ?? (async (path8) => {
45610
- await mkdir18(path8, { recursive: true });
45716
+ this.makeDirectory = options.mkdir ?? (async (path7) => {
45717
+ await mkdir18(path7, { recursive: true });
45611
45718
  return void 0;
45612
45719
  });
45613
45720
  this.fileReady = this.makeDirectory(dirname14(this.options.filePath), { recursive: true }).then(() => this.resetFile(this.options.filePath, "", { encoding: "utf8" })).catch(() => {
@@ -45669,7 +45776,7 @@ var McpTraceWriter = class {
45669
45776
  function createMcpTraceWriter(sessionCwd, settings2 = {}, randomSuffix = Math.random().toString(36).slice(2, 10)) {
45670
45777
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
45671
45778
  const configuredPath = settings2.file;
45672
- const filePath = configuredPath ? isAbsolute2(configuredPath) ? configuredPath : resolve3(sessionCwd ?? process.cwd(), configuredPath) : resolve3(sessionCwd ?? process.cwd(), ".pi", "mcp-traces", `mcp-${timestamp}-${randomSuffix}.jsonl`);
45779
+ const filePath = configuredPath ? isAbsolute2(configuredPath) ? configuredPath : resolve4(sessionCwd ?? process.cwd(), configuredPath) : resolve4(sessionCwd ?? process.cwd(), ".pi", "mcp-traces", `mcp-${timestamp}-${randomSuffix}.jsonl`);
45673
45780
  return new McpTraceWriter({
45674
45781
  filePath,
45675
45782
  ...settings2.maxBytes !== void 0 ? { maxBytes: settings2.maxBytes } : {},
@@ -45884,7 +45991,7 @@ function resolvedCommand(config) {
45884
45991
  async function invokeRequestHeadersCommand(config, envelope, signal) {
45885
45992
  const resolved = resolvedCommand(config);
45886
45993
  if (USE_PROCESS_GROUP) assertPosixProcessDiscoveryAvailable();
45887
- return new Promise((resolve7, reject) => {
45994
+ return new Promise((resolve8, reject) => {
45888
45995
  let stdout = Buffer.alloc(0);
45889
45996
  let settled = false;
45890
45997
  const cleanupToken = randomUUID8();
@@ -45913,7 +46020,7 @@ async function invokeRequestHeadersCommand(config, envelope, signal) {
45913
46020
  if (descendantTracker) clearInterval(descendantTracker);
45914
46021
  signal.removeEventListener("abort", abort);
45915
46022
  if (result.status === "error") reject(result.error);
45916
- else resolve7(result.headers);
46023
+ else resolve8(result.headers);
45917
46024
  };
45918
46025
  const finishAfterKill = (result) => {
45919
46026
  try {
@@ -46535,7 +46642,7 @@ var McpServerManager = class {
46535
46642
  let args = (definition.args ?? []).map((argument) => interpolateEnvVars(argument));
46536
46643
  const cwd = resolveConfigPath(definition.cwd) ?? this.defaultCwd;
46537
46644
  if (cwd !== void 0) {
46538
- const cwdStats = statSync2(cwd, { throwIfNoEntry: false });
46645
+ const cwdStats = statSync3(cwd, { throwIfNoEntry: false });
46539
46646
  if (!cwdStats) throw new Error(`MCP server "${name}" configured cwd does not exist: "${cwd}"`);
46540
46647
  if (!cwdStats.isDirectory()) throw new Error(`MCP server "${name}" configured cwd is not a directory: "${cwd}"`);
46541
46648
  }
@@ -48746,10 +48853,10 @@ function getOnboardingStatePath() {
48746
48853
  return getAgentPath("mcp-onboarding.json");
48747
48854
  }
48748
48855
  function loadOnboardingState() {
48749
- const path8 = getOnboardingStatePath();
48750
- if (!existsSync14(path8)) return { ...DEFAULT_STATE2 };
48856
+ const path7 = getOnboardingStatePath();
48857
+ if (!existsSync14(path7)) return { ...DEFAULT_STATE2 };
48751
48858
  try {
48752
- const raw = JSON.parse(readFileSync6(path8, "utf-8"));
48859
+ const raw = JSON.parse(readFileSync6(path7, "utf-8"));
48753
48860
  if (!raw || typeof raw !== "object") return { ...DEFAULT_STATE2 };
48754
48861
  return {
48755
48862
  version: 1,
@@ -48762,12 +48869,12 @@ function loadOnboardingState() {
48762
48869
  }
48763
48870
  }
48764
48871
  function saveOnboardingState(state) {
48765
- const path8 = getOnboardingStatePath();
48766
- mkdirSync3(dirname15(path8), { recursive: true });
48767
- const tmpPath = `${path8}.${process.pid}.tmp`;
48872
+ const path7 = getOnboardingStatePath();
48873
+ mkdirSync3(dirname15(path7), { recursive: true });
48874
+ const tmpPath = `${path7}.${process.pid}.tmp`;
48768
48875
  writeFileSync2(tmpPath, `${JSON.stringify(state, null, 2)}
48769
48876
  `, "utf-8");
48770
- renameSync2(tmpPath, path8);
48877
+ renameSync2(tmpPath, path7);
48771
48878
  }
48772
48879
  function updateOnboardingState(updater) {
48773
48880
  const next = updater(loadOnboardingState());
@@ -49180,23 +49287,23 @@ async function openMcpSetup(state, pi, ctx, configOverridePath, mode = "setup",
49180
49287
  return result;
49181
49288
  },
49182
49289
  scaffoldConfig: async (target) => {
49183
- const path8 = writeStarterSharedConfig(target, ctx.cwd);
49290
+ const path7 = writeStarterSharedConfig(target, ctx.cwd);
49184
49291
  configChanged = true;
49185
- return { path: path8 };
49292
+ return { path: path7 };
49186
49293
  },
49187
49294
  addRepoPrompt: async (target) => {
49188
49295
  const repoPrompt = getMcpDiscoverySummary(configOverridePath, ctx.cwd, options).repoPrompt;
49189
49296
  if (!repoPrompt.entry || !repoPrompt.targetPath || !repoPrompt.serverName) {
49190
49297
  throw new Error("RepoPrompt is not available to add from this setup screen.");
49191
49298
  }
49192
- const path8 = writeSharedServerEntry(getSharedConfigPath(target, ctx.cwd), repoPrompt.serverName, repoPrompt.entry);
49299
+ const path7 = writeSharedServerEntry(getSharedConfigPath(target, ctx.cwd), repoPrompt.serverName, repoPrompt.entry);
49193
49300
  configChanged = true;
49194
- return { path: path8, serverName: repoPrompt.serverName };
49301
+ return { path: path7, serverName: repoPrompt.serverName };
49195
49302
  },
49196
49303
  addKnownServer: async (preset, target) => {
49197
- const path8 = writeSharedServerEntry(getSharedConfigPath(target, ctx.cwd), preset.id, preset.entry);
49304
+ const path7 = writeSharedServerEntry(getSharedConfigPath(target, ctx.cwd), preset.id, preset.entry);
49198
49305
  configChanged = true;
49199
- return { path: path8, serverName: preset.name };
49306
+ return { path: path7, serverName: preset.name };
49200
49307
  },
49201
49308
  openPath: async (targetPath) => {
49202
49309
  await openPath(pi, targetPath);
@@ -49205,12 +49312,12 @@ async function openMcpSetup(state, pi, ctx, configOverridePath, mode = "setup",
49205
49312
  markSetupCompleted(discovery.fingerprint);
49206
49313
  }
49207
49314
  };
49208
- return new Promise((resolve7) => {
49315
+ return new Promise((resolve8) => {
49209
49316
  ctx.ui.custom(
49210
49317
  (tui, _theme, keybindings, done) => {
49211
49318
  return createMcpSetupPanel(discovery, callbacks, { mode, onboardingState, keybindings }, tui, () => {
49212
49319
  done(void 0);
49213
- resolve7({ configChanged });
49320
+ resolve8({ configChanged });
49214
49321
  });
49215
49322
  },
49216
49323
  { overlay: true, overlayOptions: { anchor: "center", width: 92 } }
@@ -49292,7 +49399,7 @@ async function openMcpPanel(state, pi, ctx, configOverridePath, onDirectToolsCon
49292
49399
  const callbacks = buildMcpPanelCallbacks(state, config, ctx, () => overlayHandle);
49293
49400
  const { createMcpPanel } = await import("./mcp-panel-IBIVWX27.js");
49294
49401
  let configChanged = false;
49295
- await new Promise((resolve7) => {
49402
+ await new Promise((resolve8) => {
49296
49403
  ctx.ui.custom(
49297
49404
  (tui, _theme, keybindings, done) => {
49298
49405
  return createMcpPanel(config, cache2, provenanceMap, callbacks, tui, (result) => {
@@ -49315,13 +49422,13 @@ async function openMcpPanel(state, pi, ctx, configOverridePath, onDirectToolsCon
49315
49422
  ctx.ui.notify("Direct tools updated for this session.", "info");
49316
49423
  }
49317
49424
  done(void 0);
49318
- resolve7();
49425
+ resolve8();
49319
49426
  })().catch((error) => {
49320
49427
  const message = error instanceof Error ? error.message : String(error);
49321
49428
  ctx.ui.notify(`Direct tools updated, but live refresh failed: ${message}`, "error");
49322
49429
  configChanged = true;
49323
49430
  done(void 0);
49324
- resolve7();
49431
+ resolve8();
49325
49432
  });
49326
49433
  }, { noticeLines, keybindings });
49327
49434
  },
@@ -49363,12 +49470,12 @@ async function openMcpAuthPanel(state, pi, ctx, configOverridePath) {
49363
49470
  let overlayHandle;
49364
49471
  const callbacks = buildMcpPanelCallbacks(state, config, ctx, () => overlayHandle);
49365
49472
  const { createMcpPanel } = await import("./mcp-panel-IBIVWX27.js");
49366
- await new Promise((resolve7) => {
49473
+ await new Promise((resolve8) => {
49367
49474
  ctx.ui.custom(
49368
49475
  (tui, _theme, keybindings, done) => {
49369
49476
  return createMcpPanel(config, cache2, provenanceMap, callbacks, tui, () => {
49370
49477
  done(void 0);
49371
- resolve7();
49478
+ resolve8();
49372
49479
  }, {
49373
49480
  authOnly: true,
49374
49481
  keybindings,
@@ -49592,7 +49699,7 @@ function stringifyStructuredContent(value) {
49592
49699
 
49593
49700
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/mcp-output-guard.ts
49594
49701
  import { randomBytes as randomBytes4 } from "crypto";
49595
- import { mkdtemp, rm as rm4, writeFile as writeFile11 } from "fs/promises";
49702
+ import { mkdtemp, rm as rm3, writeFile as writeFile11 } from "fs/promises";
49596
49703
  import { tmpdir as tmpdir2 } from "os";
49597
49704
  import { dirname as dirname16, join as join28 } from "path";
49598
49705
  var DEFAULT_MCP_OUTPUT_MAX_BYTES = 50 * 1024;
@@ -49903,16 +50010,16 @@ function serializedObjectEntryBytes(key, value, hasPrevious) {
49903
50010
  async function saveArtifact(kind, text) {
49904
50011
  try {
49905
50012
  const dir = await mkdtemp(join28(tmpdir2(), "pi-mcp-output-"));
49906
- const path8 = join28(dir, `${kind}-${randomBytes4(4).toString("hex")}.txt`);
49907
- await writeFile11(path8, text, { encoding: "utf8", mode: 384 });
49908
- return { path: path8 };
50013
+ const path7 = join28(dir, `${kind}-${randomBytes4(4).toString("hex")}.txt`);
50014
+ await writeFile11(path7, text, { encoding: "utf8", mode: 384 });
50015
+ return { path: path7 };
49909
50016
  } catch (error) {
49910
50017
  return { error: error instanceof Error ? error.message : String(error) };
49911
50018
  }
49912
50019
  }
49913
- async function discardArtifact(path8) {
50020
+ async function discardArtifact(path7) {
49914
50021
  try {
49915
- await rm4(dirname16(path8), { recursive: true, force: true });
50022
+ await rm3(dirname16(path7), { recursive: true, force: true });
49916
50023
  } catch {
49917
50024
  }
49918
50025
  }
@@ -49958,7 +50065,7 @@ import net from "net";
49958
50065
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/ui-server.ts
49959
50066
  import http2 from "http";
49960
50067
  import fs7 from "fs/promises";
49961
- import path7 from "path";
50068
+ import path6 from "path";
49962
50069
  import { randomUUID as randomUUID10 } from "crypto";
49963
50070
 
49964
50071
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/host-html-template.ts
@@ -51055,7 +51162,7 @@ data: ${JSON.stringify(payload)}
51055
51162
  return;
51056
51163
  }
51057
51164
  if (method === "GET" && url3.pathname === "/app-bridge.bundle.js") {
51058
- const bundlePath = path7.join(import.meta.dirname, "app-bridge.bundle.js");
51165
+ const bundlePath = path6.join(import.meta.dirname, "app-bridge.bundle.js");
51059
51166
  try {
51060
51167
  const content = await fs7.readFile(bundlePath, "utf-8");
51061
51168
  res.writeHead(200, {
@@ -51315,7 +51422,7 @@ data: ${JSON.stringify(payload)}
51315
51422
  markCompleted("stale");
51316
51423
  }, WATCHDOG_INTERVAL_MS);
51317
51424
  watchdog.unref();
51318
- return new Promise((resolve7, reject) => {
51425
+ return new Promise((resolve8, reject) => {
51319
51426
  const candidates = resolvePortCandidates(options.port);
51320
51427
  let candidateIndex = 0;
51321
51428
  const startSandboxProxy = (parentOrigin) => {
@@ -51452,7 +51559,7 @@ data: ${JSON.stringify(payload)}
51452
51559
  getSessionMessages: () => ({ ...sessionMessages }),
51453
51560
  getStreamSummary: () => streamSummary ? { ...streamSummary, phases: [...streamSummary.phases] } : void 0
51454
51561
  };
51455
- resolve7(handle);
51562
+ resolve8(handle);
51456
51563
  }).catch((error) => {
51457
51564
  log.error("Failed to start sandbox proxy", error instanceof Error ? error : void 0);
51458
51565
  closeListeners();
@@ -51477,7 +51584,7 @@ async function parseBody(req, res) {
51477
51584
  }
51478
51585
  }
51479
51586
  function readBody(req) {
51480
- return new Promise((resolve7, reject) => {
51587
+ return new Promise((resolve8, reject) => {
51481
51588
  let size = 0;
51482
51589
  const chunks = [];
51483
51590
  req.on("data", (chunk) => {
@@ -51491,7 +51598,7 @@ function readBody(req) {
51491
51598
  });
51492
51599
  req.on("end", () => {
51493
51600
  try {
51494
- resolve7(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
51601
+ resolve8(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
51495
51602
  } catch (error) {
51496
51603
  reject(error);
51497
51604
  }
@@ -51672,22 +51779,22 @@ function isRemoteSession() {
51672
51779
  return Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY);
51673
51780
  }
51674
51781
  function hasActiveRemoteLogin() {
51675
- return new Promise((resolve7) => {
51782
+ return new Promise((resolve8) => {
51676
51783
  execFile6("who", { encoding: "utf8", timeout: 2e3 }, (error, out) => {
51677
51784
  if (error) {
51678
- resolve7(false);
51785
+ resolve8(false);
51679
51786
  return;
51680
51787
  }
51681
- resolve7(/\(.+\)\s*$/m.test(out));
51788
+ resolve8(/\(.+\)\s*$/m.test(out));
51682
51789
  });
51683
51790
  });
51684
51791
  }
51685
51792
  function probeMoshiGateway() {
51686
- return new Promise((resolve7) => {
51793
+ return new Promise((resolve8) => {
51687
51794
  const socket = net.connect({ host: "127.0.0.1", port: 24543 });
51688
51795
  const done = (ok) => {
51689
51796
  socket.destroy();
51690
- resolve7(ok);
51797
+ resolve8(ok);
51691
51798
  };
51692
51799
  socket.setTimeout(300);
51693
51800
  socket.once("connect", () => done(true));
@@ -58003,22 +58110,22 @@ async function runMcpScript(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_
58003
58110
  durationMs: "error" in operation && operation.error === "incomplete" ? Math.max(0, Date.now() - startedAt) : operation.durationMs
58004
58111
  }));
58005
58112
  let callsSnapshot;
58006
- const callTool = async (path8, args) => {
58113
+ const callTool = async (path7, args) => {
58007
58114
  const startedAt = Date.now();
58008
- const index = calls.push({ operation: "call", path: path8, ok: false, error: "incomplete", durationMs: 0, startedAt }) - 1;
58009
- const result = await executeCall(state, path8, args, void 0, getPiTools, callSignal, "script");
58115
+ const index = calls.push({ operation: "call", path: path7, ok: false, error: "incomplete", durationMs: 0, startedAt }) - 1;
58116
+ const result = await executeCall(state, path7, args, void 0, getPiTools, callSignal, "script");
58010
58117
  const details = result.details;
58011
58118
  if (details.error !== void 0) {
58012
58119
  const errorCode2 = String(details.error);
58013
58120
  const suggestions = Array.isArray(details.suggestions) ? details.suggestions.filter((suggestion) => typeof suggestion === "string") : [];
58014
- const message = errorCode2 === "tool_not_found" ? `Tool "${path8}" not found. Use await tools.search({ query: "..." }) inside mcpScript.${suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}` : ""}` : typeof details.message === "string" ? details.message : textFromContent(result.content);
58015
- calls[index] = { operation: "call", path: path8, ok: false, error: errorCode2, durationMs: Date.now() - startedAt, startedAt };
58121
+ const message = errorCode2 === "tool_not_found" ? `Tool "${path7}" not found. Use await tools.search({ query: "..." }) inside mcpScript.${suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}` : ""}` : typeof details.message === "string" ? details.message : textFromContent(result.content);
58122
+ calls[index] = { operation: "call", path: path7, ok: false, error: errorCode2, durationMs: Date.now() - startedAt, startedAt };
58016
58123
  return {
58017
58124
  ok: false,
58018
58125
  error: { code: errorCode2, message }
58019
58126
  };
58020
58127
  }
58021
- calls[index] = { operation: "call", path: path8, ok: true, durationMs: Date.now() - startedAt, startedAt };
58128
+ calls[index] = { operation: "call", path: path7, ok: true, durationMs: Date.now() - startedAt, startedAt };
58022
58129
  return {
58023
58130
  ok: true,
58024
58131
  data: details.mcpResult !== void 0 ? details.mcpResult : textFromContent(result.content)
@@ -58055,12 +58162,12 @@ async function runMcpScript(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_
58055
58162
  };
58056
58163
  const describeTool = (input) => {
58057
58164
  const startedAt = Date.now();
58058
- const path8 = typeof input?.path === "string" ? input.path : "";
58165
+ const path7 = typeof input?.path === "string" ? input.path : "";
58059
58166
  let error;
58060
58167
  try {
58061
58168
  for (const [server2, metadata] of state.toolMetadata) {
58062
58169
  if (isServerInActiveFailureBackoff(state, server2)) continue;
58063
- const tool = findToolByName(metadata, path8);
58170
+ const tool = findToolByName(metadata, path7);
58064
58171
  if (!tool) continue;
58065
58172
  const inputTypeScript = tool.inputSchema ? renderTsShape(tool.inputSchema) ?? formatSchema(tool.inputSchema) : null;
58066
58173
  return {
@@ -58071,13 +58178,13 @@ async function runMcpScript(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_
58071
58178
  ...inputTypeScript ? { inputTypeScript } : {}
58072
58179
  };
58073
58180
  }
58074
- const suggestions = path8 ? rankSuggestions(state, path8, 5) : [];
58181
+ const suggestions = path7 ? rankSuggestions(state, path7, 5) : [];
58075
58182
  error = "tool_not_found";
58076
58183
  return {
58077
- path: path8,
58184
+ path: path7,
58078
58185
  error: {
58079
58186
  code: "tool_not_found",
58080
- message: `Tool not found: ${path8}`,
58187
+ message: `Tool not found: ${path7}`,
58081
58188
  suggestions
58082
58189
  }
58083
58190
  };
@@ -58085,7 +58192,7 @@ async function runMcpScript(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_
58085
58192
  error = caught;
58086
58193
  throw caught;
58087
58194
  } finally {
58088
- calls.push(error === void 0 ? { operation: "describe", path: path8, ok: true, durationMs: Date.now() - startedAt, startedAt } : { operation: "describe", path: path8, ok: false, error: error instanceof Error ? error.message : String(error), durationMs: Date.now() - startedAt, startedAt });
58195
+ calls.push(error === void 0 ? { operation: "describe", path: path7, ok: true, durationMs: Date.now() - startedAt, startedAt } : { operation: "describe", path: path7, ok: false, error: error instanceof Error ? error.message : String(error), durationMs: Date.now() - startedAt, startedAt });
58089
58196
  }
58090
58197
  };
58091
58198
  let worker;
@@ -58107,7 +58214,7 @@ async function runMcpScript(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_
58107
58214
  trackUnmanagedFds: false
58108
58215
  });
58109
58216
  const activeWorker = worker;
58110
- const execution = new Promise((resolve7, reject) => {
58217
+ const execution = new Promise((resolve8, reject) => {
58111
58218
  let completed = false;
58112
58219
  activeWorker.on("message", (value) => {
58113
58220
  const message = parseWorkerMessage(value);
@@ -58119,7 +58226,7 @@ async function runMcpScript(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_
58119
58226
  if (message.type === "done") {
58120
58227
  completed = true;
58121
58228
  if ("returnBlock" in message) output.push(toContentBlock(message.returnBlock));
58122
- resolve7();
58229
+ resolve8();
58123
58230
  return;
58124
58231
  }
58125
58232
  if (message.type === "error") {
@@ -58398,8 +58505,8 @@ async function awaitWithTimeout(promise, timeoutMs) {
58398
58505
  try {
58399
58506
  return await Promise.race([
58400
58507
  promise,
58401
- new Promise((resolve7) => {
58402
- timer = setTimeout(() => resolve7(INIT_WAIT_TIMED_OUT), timeoutMs);
58508
+ new Promise((resolve8) => {
58509
+ timer = setTimeout(() => resolve8(INIT_WAIT_TIMED_OUT), timeoutMs);
58403
58510
  timer.unref?.();
58404
58511
  })
58405
58512
  ]);
@@ -59777,7 +59884,7 @@ import {
59777
59884
  rename as rename4,
59778
59885
  unlink as unlink3
59779
59886
  } from "fs/promises";
59780
- import { existsSync as existsSync16, readFileSync as readFileSync7, readdirSync as readdirSync2 } from "fs";
59887
+ import { existsSync as existsSync16, readFileSync as readFileSync7, readdirSync as readdirSync3 } from "fs";
59781
59888
  import { join as join31 } from "path";
59782
59889
  var MAX_FAILED_RECORDS = 500;
59783
59890
  var FLUSH_DEBOUNCE_MS = 15e3;
@@ -59826,7 +59933,7 @@ var AnalyticsRecordBuffer = class {
59826
59933
  }
59827
59934
  readStoredRecords() {
59828
59935
  if (!existsSync16(ENGINE_DIR2)) return [];
59829
- return readdirSync2(ENGINE_DIR2, { withFileTypes: true }).filter((entry) => entry.isFile() && this.storageNames.some(
59936
+ return readdirSync3(ENGINE_DIR2, { withFileTypes: true }).filter((entry) => entry.isFile() && this.storageNames.some(
59830
59937
  (storageName) => entry.name === `${storageName}.jsonl` || entry.name.startsWith(`${storageName}.`) && (entry.name.endsWith(".jsonl") || entry.name.endsWith(`.jsonl${UPLOADED_SUFFIX}`))
59831
59938
  )).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync7(join31(ENGINE_DIR2, name), "utf-8"))).map((record3) => {
59832
59939
  const recordId = this.options.getRecordId?.(record3);
@@ -60758,11 +60865,11 @@ import { join as join32 } from "path";
60758
60865
 
60759
60866
  // src/utils/contained-file.ts
60760
60867
  import { realpath, stat as stat3 } from "fs/promises";
60761
- import { resolve as resolve4 } from "path";
60868
+ import { resolve as resolve5 } from "path";
60762
60869
  async function resolveContainedFile(root, relativePath) {
60763
60870
  try {
60764
60871
  const [fullPath, resolvedRoot] = await Promise.all([
60765
- realpath(resolve4(root, relativePath)),
60872
+ realpath(resolve5(root, relativePath)),
60766
60873
  realpath(root)
60767
60874
  ]);
60768
60875
  const fileStat = await stat3(fullPath);
@@ -60931,7 +61038,7 @@ function isReconcileCanvasItemsResponse(value) {
60931
61038
  }
60932
61039
  async function withCanvasUploadSlot(operation) {
60933
61040
  if (activeCanvasUploads >= MAX_CONCURRENT_CANVAS_UPLOADS) {
60934
- await new Promise((resolve7) => pendingCanvasUploads.push(resolve7));
61041
+ await new Promise((resolve8) => pendingCanvasUploads.push(resolve8));
60935
61042
  } else {
60936
61043
  activeCanvasUploads++;
60937
61044
  }
@@ -61257,13 +61364,13 @@ function runBeforeDeadline(operation, deadline) {
61257
61364
  const timeoutMs = deadline - Date.now();
61258
61365
  if (timeoutMs <= 0) return Promise.reject(new DOMException("engine log flush deadline exceeded", "TimeoutError"));
61259
61366
  const signal = AbortSignal.timeout(timeoutMs);
61260
- return new Promise((resolve7, reject) => {
61367
+ return new Promise((resolve8, reject) => {
61261
61368
  const onAbort = () => reject(signal.reason);
61262
61369
  signal.addEventListener("abort", onAbort, { once: true });
61263
61370
  operation(signal).then(
61264
61371
  (value) => {
61265
61372
  signal.removeEventListener("abort", onAbort);
61266
- resolve7(value);
61373
+ resolve8(value);
61267
61374
  },
61268
61375
  (error) => {
61269
61376
  signal.removeEventListener("abort", onAbort);
@@ -61298,10 +61405,10 @@ function unansweredRequest(blocks) {
61298
61405
  const answered = blocks.slice(lastUser + 1).some((block) => block.startsWith("## Agent"));
61299
61406
  return answered ? null : lastUserBlockText(blocks);
61300
61407
  }
61301
- async function readHistoryTail(path8, maxBytes) {
61408
+ async function readHistoryTail(path7, maxBytes) {
61302
61409
  let handle;
61303
61410
  try {
61304
- handle = await open3(path8, "r");
61411
+ handle = await open3(path7, "r");
61305
61412
  } catch (error) {
61306
61413
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return { content: "", truncated: false };
61307
61414
  throw error;
@@ -61674,8 +61781,8 @@ var ChatService = class {
61674
61781
  if (result.status === "completed") return result;
61675
61782
  const remainingMs = timeoutMs === null ? null : timeoutMs - (Date.now() - startedAt);
61676
61783
  if (remainingMs !== null && remainingMs <= 0) return { ...result, timedOut: true };
61677
- await new Promise((resolve7) => setTimeout(
61678
- resolve7,
61784
+ await new Promise((resolve8) => setTimeout(
61785
+ resolve8,
61679
61786
  remainingMs === null ? RELAY_SUBAGENT_POLL_INTERVAL_MS : Math.min(RELAY_SUBAGENT_POLL_INTERVAL_MS, remainingMs)
61680
61787
  ));
61681
61788
  }
@@ -62092,9 +62199,9 @@ var ChatService = class {
62092
62199
  historyPath,
62093
62200
  `${historyPath}.pages.jsonl`,
62094
62201
  `${historyPath}.pages.index.json`
62095
- ].map((path8) => rm5(path8, { force: true })));
62096
- await rm5(chatMessageSendersFilePath(persisted.id), { force: true });
62097
- await rm5(join37(FORKS_DIR, persisted.id), { recursive: true, force: true });
62202
+ ].map((path7) => rm4(path7, { force: true })));
62203
+ await rm4(chatMessageSendersFilePath(persisted.id), { force: true });
62204
+ await rm4(join37(FORKS_DIR, persisted.id), { recursive: true, force: true });
62098
62205
  }
62099
62206
  /** Resolves once the target chat exists; the handoff and its first turn run in the background. */
62100
62207
  async forkChat(sourceChatId, request, trigger = "manual", reason) {
@@ -62729,13 +62836,13 @@ var ChatService = class {
62729
62836
  async observeCurrentBranches(chat) {
62730
62837
  try {
62731
62838
  const snapshot = await gitService.snapshotCurrentBranches();
62732
- for (const [repoName, branch] of snapshot) {
62839
+ for (const [repoName, branches] of snapshot) {
62733
62840
  let observed = chat.observedBranchesByRepo.get(repoName);
62734
62841
  if (!observed) {
62735
62842
  observed = /* @__PURE__ */ new Set();
62736
62843
  chat.observedBranchesByRepo.set(repoName, observed);
62737
62844
  }
62738
- observed.add(branch);
62845
+ for (const branch of branches) observed.add(branch);
62739
62846
  }
62740
62847
  } catch {
62741
62848
  }
@@ -62925,10 +63032,10 @@ var LanguageServerService = class {
62925
63032
  const uri = "targetUri" in location ? location.targetUri : location.uri;
62926
63033
  const range = "targetSelectionRange" in location ? location.targetSelectionRange : location.range;
62927
63034
  const absolutePath = fileURLToPath6(uri);
62928
- const path8 = relative2(repoPath, absolutePath);
62929
- if (path8.startsWith("..")) return [];
63035
+ const path7 = relative2(repoPath, absolutePath);
63036
+ if (path7.startsWith("..")) return [];
62930
63037
  const preview = readFileSync8(absolutePath, "utf8").split("\n")[range.start.line]?.trim() ?? "";
62931
- return [{ repoName, path: path8, line: range.start.line + 1, character: range.start.character, endCharacter: range.end.character, preview }];
63038
+ return [{ repoName, path: path7, line: range.start.line + 1, character: range.start.character, endCharacter: range.end.character, preview }];
62932
63039
  });
62933
63040
  return { symbol: "", detail: null, documentation: null, locations, provider: "language-server" };
62934
63041
  } catch {
@@ -62980,7 +63087,7 @@ function isBinaryExtension(filePath) {
62980
63087
  return classifyCanvasFilename(filePath).kind === "image" || binaryExts.has(ext);
62981
63088
  }
62982
63089
  function execGitAsync(args, cwd, timeoutMs) {
62983
- return new Promise((resolve7, reject) => {
63090
+ return new Promise((resolve8, reject) => {
62984
63091
  const child = execFile7("git", args, {
62985
63092
  cwd,
62986
63093
  encoding: "utf-8",
@@ -62990,7 +63097,7 @@ function execGitAsync(args, cwd, timeoutMs) {
62990
63097
  if (error) {
62991
63098
  reject(error);
62992
63099
  } else {
62993
- resolve7(stdout);
63100
+ resolve8(stdout);
62994
63101
  }
62995
63102
  });
62996
63103
  child.stdin?.end();
@@ -63246,7 +63353,7 @@ var RepoFileService = class {
63246
63353
  import { Hono } from "hono";
63247
63354
  import { z as z6 } from "zod";
63248
63355
  import { readdir as readdir12, stat as stat7, readFile as readFile26 } from "fs/promises";
63249
- import { join as join41, resolve as resolve5 } from "path";
63356
+ import { join as join41, resolve as resolve6 } from "path";
63250
63357
 
63251
63358
  // src/services/warm-hooks-service.ts
63252
63359
  import { spawn as spawn10 } from "child_process";
@@ -63423,7 +63530,7 @@ async function executeHookScriptStreaming(params) {
63423
63530
  let bufferExceeded = false;
63424
63531
  params.onChunk(`$ ${params.label}
63425
63532
  `);
63426
- return new Promise((resolve7) => {
63533
+ return new Promise((resolve8) => {
63427
63534
  const proc = spawn10("bash", ["-lc", params.content], {
63428
63535
  cwd: params.cwd,
63429
63536
  env: process.env,
@@ -63456,7 +63563,7 @@ async function executeHookScriptStreaming(params) {
63456
63563
  proc.on("close", (code) => {
63457
63564
  clearTimeout(timer);
63458
63565
  const output = [`$ ${params.label}`, ...outputParts].join("");
63459
- resolve7({
63566
+ resolve8({
63460
63567
  exitCode: bufferExceeded ? 1 : code ?? 1,
63461
63568
  output,
63462
63569
  timedOut: killed && !bufferExceeded
@@ -63466,7 +63573,7 @@ async function executeHookScriptStreaming(params) {
63466
63573
  clearTimeout(timer);
63467
63574
  const output = [`$ ${params.label}
63468
63575
  `, ...outputParts, err.message].join("");
63469
- resolve7({
63576
+ resolve8({
63470
63577
  exitCode: 1,
63471
63578
  output,
63472
63579
  timedOut: false
@@ -63826,8 +63933,19 @@ function createJsonEventStream(run, onError) {
63826
63933
  function createV1Routes(deps) {
63827
63934
  const app2 = new Hono();
63828
63935
  app2.post("/pull-requests/check", async (c) => {
63829
- pullRequestCheckService.check().catch(() => {
63830
- });
63936
+ if (c.req.header("content-type")?.includes("application/json")) {
63937
+ const result = z6.object({
63938
+ toolName: z6.string(),
63939
+ toolInput: z6.unknown(),
63940
+ output: z6.unknown(),
63941
+ success: z6.boolean()
63942
+ }).safeParse(await c.req.json().catch(() => null));
63943
+ if (!result.success) return c.json({ error: "Invalid PR tool result" }, 400);
63944
+ await pullRequestCheckService.onToolResult(result.data);
63945
+ } else {
63946
+ pullRequestCheckService.check().catch(() => {
63947
+ });
63948
+ }
63831
63949
  return c.json({ accepted: true }, 202);
63832
63950
  });
63833
63951
  const loadChatHistory = async (c, chatId, page2, failureMessage, unexpectedStatus, legacy = false) => {
@@ -64310,11 +64428,11 @@ function createV1Routes(deps) {
64310
64428
  });
64311
64429
  app2.get("/repo-files/content", async (c) => {
64312
64430
  const repoName = c.req.query("repoName");
64313
- const path8 = c.req.query("path");
64314
- if (!repoName || !path8) {
64431
+ const path7 = c.req.query("path");
64432
+ if (!repoName || !path7) {
64315
64433
  return c.json(jsonError("repoName and path are required"), 400);
64316
64434
  }
64317
- const result = await deps.repoFileService.readFile(repoName, path8);
64435
+ const result = await deps.repoFileService.readFile(repoName, path7);
64318
64436
  if (!result) {
64319
64437
  return c.json(jsonError("File not found"), 404);
64320
64438
  }
@@ -64322,25 +64440,25 @@ function createV1Routes(deps) {
64322
64440
  });
64323
64441
  app2.put("/repo-files/content", async (c) => {
64324
64442
  const repoName = c.req.query("repoName");
64325
- const path8 = c.req.query("path");
64326
- if (!repoName || !path8) {
64443
+ const path7 = c.req.query("path");
64444
+ if (!repoName || !path7) {
64327
64445
  return c.json(jsonError("repoName and path are required"), 400);
64328
64446
  }
64329
64447
  const body = updateTextFileSchema(MAX_REPO_FILE_CONTENT_BYTES).parse(await c.req.json());
64330
- const result = await deps.repoFileService.updateFile(repoName, path8, body.content, body.expectedRevision);
64448
+ const result = await deps.repoFileService.updateFile(repoName, path7, body.content, body.expectedRevision);
64331
64449
  if (!result) return c.json(jsonError("File is not editable"), 400);
64332
64450
  return c.json(result);
64333
64451
  });
64334
64452
  app2.get("/repo-files/symbol", async (c) => {
64335
64453
  const repoName = c.req.query("repoName");
64336
- const path8 = c.req.query("path");
64454
+ const path7 = c.req.query("path");
64337
64455
  const action = c.req.query("action");
64338
64456
  const line = Number(c.req.query("line"));
64339
64457
  const character = Number(c.req.query("character"));
64340
- if (!repoName || !path8 || action !== "hover" && action !== "definition" && action !== "references" || !Number.isInteger(line) || !Number.isInteger(character)) {
64458
+ if (!repoName || !path7 || action !== "hover" && action !== "definition" && action !== "references" || !Number.isInteger(line) || !Number.isInteger(character)) {
64341
64459
  return c.json(jsonError("Invalid symbol request"), 400);
64342
64460
  }
64343
- const result = await deps.repoFileService.inspectSymbol(repoName, path8, line, character, action);
64461
+ const result = await deps.repoFileService.inspectSymbol(repoName, path7, line, character, action);
64344
64462
  if (!result) return c.json(jsonError("Symbol not found"), 404);
64345
64463
  return c.json(result);
64346
64464
  });
@@ -64750,8 +64868,8 @@ data: ${JSON.stringify("Terminal session not found")}
64750
64868
  if (!isValidEngineLogSessionId(sessionId)) {
64751
64869
  return c.json(jsonError("Invalid session ID"), 400);
64752
64870
  }
64753
- const filePath = resolve5(LOG_DIR, `${sessionId}.log`);
64754
- if (!filePath.startsWith(resolve5(LOG_DIR))) {
64871
+ const filePath = resolve6(LOG_DIR, `${sessionId}.log`);
64872
+ if (!filePath.startsWith(resolve6(LOG_DIR))) {
64755
64873
  return c.json(jsonError("Invalid session ID"), 400);
64756
64874
  }
64757
64875
  let content;
@@ -64828,12 +64946,12 @@ var heartbeatService = new HeartbeatService();
64828
64946
 
64829
64947
  // src/services/workspace-sdk-service.ts
64830
64948
  import { cp, mkdir as mkdir24 } from "fs/promises";
64831
- import { dirname as dirname20, resolve as resolve6 } from "path";
64949
+ import { dirname as dirname20, resolve as resolve7 } from "path";
64832
64950
  import { fileURLToPath as fileURLToPath7 } from "url";
64833
64951
  async function installWorkspaceSdk() {
64834
- const source = resolve6(dirname20(fileURLToPath7(import.meta.url)), "../../workspace-sdk");
64952
+ const source = resolve7(dirname20(fileURLToPath7(import.meta.url)), "../../workspace-sdk");
64835
64953
  const targets = [
64836
- resolve6(ENGINE_ENV.HOME_DIR, "node_modules/@replicas/sdk"),
64954
+ resolve7(ENGINE_ENV.HOME_DIR, "node_modules/@replicas/sdk"),
64837
64955
  "/tmp/node_modules/@replicas/sdk"
64838
64956
  ];
64839
64957
  await Promise.all(targets.map(async (target) => {
@@ -64848,8 +64966,8 @@ var startupTimings = {};
64848
64966
  var ENGINE_INIT_GATE_TIMEOUT_MS = 35 * 60 * 1e3;
64849
64967
  var resolveEngineReady = () => {
64850
64968
  };
64851
- var engineReadyPromise = new Promise((resolve7) => {
64852
- resolveEngineReady = resolve7;
64969
+ var engineReadyPromise = new Promise((resolve8) => {
64970
+ resolveEngineReady = resolve8;
64853
64971
  });
64854
64972
  async function timeStartupStep(name, fn) {
64855
64973
  const startedAt = performance.now();
@@ -64869,7 +64987,7 @@ async function waitForInitializationGate() {
64869
64987
  if (Date.now() >= deadline) {
64870
64988
  throw new Error("Timed out waiting for deferred engine initialization gate");
64871
64989
  }
64872
- await new Promise((resolve7) => setTimeout(resolve7, 25));
64990
+ await new Promise((resolve8) => setTimeout(resolve8, 25));
64873
64991
  }
64874
64992
  }
64875
64993
  await timeStartupStep("engine_logger_initialize", () => engineLogger.initialize());
@@ -64901,11 +65019,11 @@ async function checkActiveSSHSessions() {
64901
65019
  }
64902
65020
  }
64903
65021
  function checkDesktopReady() {
64904
- return new Promise((resolve7) => {
65022
+ return new Promise((resolve8) => {
64905
65023
  const socket = connect({ host: "127.0.0.1", port: DESKTOP_STREAM_PORT });
64906
65024
  const done = (ready) => {
64907
65025
  socket.destroy();
64908
- resolve7(ready);
65026
+ resolve8(ready);
64909
65027
  };
64910
65028
  socket.once("connect", () => done(true));
64911
65029
  socket.once("error", () => done(false));
@@ -64942,7 +65060,7 @@ app.get("/health", async (c) => {
64942
65060
  if (!engineReady && waitMs > 0) {
64943
65061
  await Promise.race([
64944
65062
  engineReadyPromise,
64945
- new Promise((resolve7) => setTimeout(resolve7, waitMs))
65063
+ new Promise((resolve8) => setTimeout(resolve8, waitMs))
64946
65064
  ]);
64947
65065
  }
64948
65066
  c.header(ENGINE_HEALTH_WAIT_HEADER, "1");
@@ -64991,8 +65109,7 @@ app.get("/token-refresh/health", async (c) => {
64991
65109
  gitlab: gitlabTokenManager.getHealthStatus(),
64992
65110
  claude: claudeTokenManager.getHealthStatus(),
64993
65111
  codex: codexTokenManager.getHealthStatus(),
64994
- infisical: infisicalTokenManager.getHealthStatus(),
64995
- workspaceIdentity: workspaceIdentityTokenManager.getHealthStatus()
65112
+ infisical: infisicalTokenManager.getHealthStatus()
64996
65113
  });
64997
65114
  });
64998
65115
  app.post(GITHUB_CREDENTIAL_REFRESH_PATH, async (c) => {
@@ -65165,8 +65282,7 @@ serve(
65165
65282
  await claudeTokenManager.start();
65166
65283
  await codexTokenManager.start();
65167
65284
  await infisicalTokenManager.start();
65168
- await workspaceIdentityTokenManager.start();
65169
- createIdentityProxy(() => workspaceIdentityTokenManager.bundle).on("error", (error) => console.error("[identity-proxy] failed to listen:", error)).listen(IDENTITY_PROXY_PORT, "127.0.0.1");
65285
+ createIdentityProxy(workspaceIdentityTokens).on("error", (error) => console.error("[identity-proxy] failed to listen:", error)).listen(IDENTITY_PROXY_PORT, "127.0.0.1");
65170
65286
  }
65171
65287
  const repos = await gitService.listRepos();
65172
65288
  await eventService.publish({