replicas-engine 0.1.740 → 0.1.741

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
@@ -1,19 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- ENGINE_ENV,
4
- IS_WARMING_MODE,
5
3
  evaluateCommandProtection,
6
4
  extractToolCommand,
7
- monolithRequest,
8
- monolithService,
9
- reportCommandProtectionBlock,
10
- setAgentCredentialSnapshot
11
- } from "./chunk-3Z7CQNGC.js";
5
+ reportCommandProtectionBlock
6
+ } from "./chunk-25CMFABL.js";
12
7
  import {
13
8
  ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
14
9
  AGENT_MESSAGE_DELTA_METHOD,
15
- AppServerProcess,
16
- AspClient,
17
10
  COMMAND_EXECUTION_OUTPUT_DELTA_METHOD,
18
11
  FILE_CHANGE_OUTPUT_DELTA_METHOD,
19
12
  ITEM_COMPLETED_METHOD,
@@ -22,7 +15,6 @@ import {
22
15
  REASONING_SUMMARY_PART_ADDED_METHOD,
23
16
  REASONING_SUMMARY_TEXT_DELTA_METHOD,
24
17
  REASONING_TEXT_DELTA_METHOD,
25
- SUBPROCESS_MAX_BUFFER,
26
18
  THREAD_COMPACTED_METHOD,
27
19
  THREAD_GOAL_CLEARED_METHOD,
28
20
  THREAD_GOAL_UPDATED_METHOD,
@@ -30,13 +22,34 @@ import {
30
22
  TURN_COMPLETED_METHOD,
31
23
  TURN_PLAN_UPDATED_METHOD,
32
24
  TURN_STARTED_METHOD,
33
- buildCodexAgentEnv,
34
25
  dispatchAspNotification,
35
- execAsync,
36
- execFileAsync,
37
26
  putPresignedFile,
38
27
  recoverCompletedTurn
39
- } from "./chunk-ZZRN6VSK.js";
28
+ } from "./chunk-Z6P6S5HL.js";
29
+ import {
30
+ BaseRefreshManager,
31
+ CodexAspAuthMethodChangedError,
32
+ applyAuthEnvTransition,
33
+ codexTokenManager,
34
+ getCodexAspHost,
35
+ listCredentialFallbacks,
36
+ recordCredentialFallback,
37
+ recordExhaustedCredential,
38
+ restartCodexAspHost
39
+ } from "./chunk-UUKFVYYJ.js";
40
+ import {
41
+ ENGINE_ENV,
42
+ IS_WARMING_MODE,
43
+ monolithRequest,
44
+ monolithService,
45
+ setAgentCredentialSnapshot
46
+ } from "./chunk-TRGZSX4W.js";
47
+ import {
48
+ AspClient,
49
+ SUBPROCESS_MAX_BUFFER,
50
+ execAsync,
51
+ execFileAsync
52
+ } from "./chunk-ESGIWRVV.js";
40
53
  import {
41
54
  isRecord as isRecord2
42
55
  } from "./chunk-2RB7SIP3.js";
@@ -70,8 +83,6 @@ import {
70
83
  CLAUDE_SONNET_5_BEDROCK_MODEL,
71
84
  CLAUDE_SONNET_5_MODEL,
72
85
  CODEX_ASP_TRANSCRIPT_UPDATED_EVENT_TYPE,
73
- CODEX_AUTH_ENV_KEYS,
74
- CODEX_AUTH_ENV_KEYS_BY_METHOD,
75
86
  CODEX_QUOTA_STATUS_EVENT_TYPE,
76
87
  COMPACTION_STATUS_EVENT_TYPE,
77
88
  CONTEXT_USAGE_EVENT_TYPE,
@@ -132,7 +143,6 @@ import {
132
143
  clampWarmHookTimeoutMs,
133
144
  classifyCanvasFilename,
134
145
  claudeAuthEnvFromResponse,
135
- codexAuthEnvFromResponse,
136
146
  codexReasoningEffortForThinkingLevel,
137
147
  coerceBackgroundTaskPayload,
138
148
  coerceChatForkInfo,
@@ -230,7 +240,7 @@ import {
230
240
  shellQuotePosix,
231
241
  stripAgentDiagnosticErrors,
232
242
  withTimeout
233
- } from "./chunk-YPAI4W4G.js";
243
+ } from "./chunk-Q6F7J5DH.js";
234
244
 
235
245
  // src/index.ts
236
246
  import { serve } from "@hono/node-server";
@@ -242,168 +252,6 @@ import { connect } from "net";
242
252
  // src/managers/github-token-manager.ts
243
253
  import path from "path";
244
254
 
245
- // src/services/credential-fallbacks.ts
246
- var fallbacksByAgent = /* @__PURE__ */ new Map();
247
- var exhaustedByAgent = /* @__PURE__ */ new Map();
248
- function recordCredentialFallback(notice) {
249
- fallbacksByAgent.set(notice.provider, notice);
250
- }
251
- function listCredentialFallbacks() {
252
- return [...fallbacksByAgent.values()].filter((notice) => {
253
- const live = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS[notice.provider];
254
- if (!live) return false;
255
- return notice.status === "switched" ? live.method === notice.candidateMethod && live.scope === notice.candidateScope : live.method === notice.exhaustedMethod && live.scope === notice.exhaustedScope;
256
- });
257
- }
258
- function listExhaustedCredentials(provider) {
259
- return [...exhaustedByAgent.get(provider)?.values() ?? []];
260
- }
261
- function recordExhaustedCredential(provider, credential) {
262
- const spent = exhaustedByAgent.get(provider) ?? /* @__PURE__ */ new Map();
263
- spent.set(`${credential.method}|${credential.scope}`, credential);
264
- exhaustedByAgent.set(provider, spent);
265
- }
266
-
267
- // src/managers/base-refresh-manager.ts
268
- var BaseRefreshManager = class {
269
- constructor(managerName, intervalMs = 15 * 60 * 1e3) {
270
- this.managerName = managerName;
271
- this.intervalMs = intervalMs;
272
- this.health = {
273
- isRunning: false,
274
- intervalMs: this.intervalMs,
275
- lastAttemptAt: null,
276
- lastSuccessAt: null,
277
- lastErrorAt: null,
278
- lastErrorMessage: null
279
- };
280
- }
281
- managerName;
282
- intervalMs;
283
- intervalHandle = null;
284
- health;
285
- async start() {
286
- if (this.intervalHandle) {
287
- return;
288
- }
289
- const skipReason = this.getSkipReason();
290
- if (skipReason) {
291
- console.log(`[${this.managerName}] Skipping: ${skipReason}`);
292
- return;
293
- }
294
- console.log(`[${this.managerName}] Starting token refresh service`);
295
- this.health.isRunning = true;
296
- const config = this.getRuntimeConfig();
297
- if (config) {
298
- this.health.lastAttemptAt = (/* @__PURE__ */ new Date()).toISOString();
299
- for (let attempt = 1; attempt <= 3; attempt++) {
300
- try {
301
- await this.doRefresh(config);
302
- this.health.lastSuccessAt = (/* @__PURE__ */ new Date()).toISOString();
303
- this.health.lastErrorAt = null;
304
- this.health.lastErrorMessage = null;
305
- break;
306
- } catch (error) {
307
- const message = error instanceof Error ? error.message : "Unknown error";
308
- this.health.lastErrorAt = (/* @__PURE__ */ new Date()).toISOString();
309
- this.health.lastErrorMessage = message;
310
- if (attempt < 3) {
311
- console.warn(`[${this.managerName}] Initial refresh attempt ${attempt} failed, retrying in 2s...`);
312
- await new Promise((resolve5) => setTimeout(resolve5, 2e3));
313
- } else {
314
- console.error(`[${this.managerName}] Initial refresh failed after 3 attempts:`, error);
315
- }
316
- }
317
- }
318
- }
319
- this.scheduleNextRefresh();
320
- }
321
- async swapCredentials(params) {
322
- if (!this.getRuntimeConfig()) {
323
- return createErrorResult({ message: `${this.managerName} has no runtime config`, code: "not_configured" });
324
- }
325
- try {
326
- console.log(`[${this.managerName}] Fetching fresh credentials from monolith (${params.failureKind})...`);
327
- const excludeCredentials = listExhaustedCredentials(params.provider);
328
- await params.refresh({
329
- ...excludeCredentials.length > 0 ? { excludeCredentials } : {},
330
- ...params.allowedMethods ? { allowedMethods: [...params.allowedMethods] } : {}
331
- });
332
- if (params.isOauthNow()) {
333
- this.start().catch((error) => {
334
- console.error(`[${this.managerName}] Failed to restart OAuth refresh service after fallback:`, error);
335
- });
336
- }
337
- return createSuccessResult();
338
- } catch (error) {
339
- const message = error instanceof Error ? error.message : String(error);
340
- console.error(`[${this.managerName}] Failed to fetch fresh credentials:`, error);
341
- return createErrorResult({
342
- message,
343
- code: message.includes('"code":"no_credentials"') ? "no_credentials" : "refresh_failed"
344
- });
345
- }
346
- }
347
- stop() {
348
- if (!this.intervalHandle) {
349
- return;
350
- }
351
- clearTimeout(this.intervalHandle);
352
- this.intervalHandle = null;
353
- this.health.isRunning = false;
354
- console.log(`[${this.managerName}] Stopped`);
355
- }
356
- getHealthStatus() {
357
- return { ...this.health };
358
- }
359
- getSkipReason() {
360
- return null;
361
- }
362
- getNextRefreshDelayMs() {
363
- return this.intervalMs;
364
- }
365
- getRuntimeConfig() {
366
- if (!ENGINE_ENV.REPLICAS_WORKSPACE_ID) {
367
- return null;
368
- }
369
- return {
370
- monolithUrl: ENGINE_ENV.REPLICAS_MONOLITH_URL,
371
- workspaceId: ENGINE_ENV.REPLICAS_WORKSPACE_ID,
372
- engineSecret: ENGINE_ENV.REPLICAS_ENGINE_SECRET
373
- };
374
- }
375
- scheduleNextRefresh() {
376
- const delayMs = this.getNextRefreshDelayMs();
377
- this.health.intervalMs = delayMs;
378
- this.intervalHandle = setTimeout(async () => {
379
- await this.refreshOnce();
380
- if (this.intervalHandle) this.scheduleNextRefresh();
381
- }, delayMs);
382
- console.log(`[${this.managerName}] Token refresh scheduled in ${Math.round(delayMs / 1e3)} seconds`);
383
- }
384
- async refreshOnce() {
385
- if (this.getSkipReason()) {
386
- return createSuccessResult();
387
- }
388
- const config = this.getRuntimeConfig();
389
- if (!config) return createSuccessResult();
390
- this.health.lastAttemptAt = (/* @__PURE__ */ new Date()).toISOString();
391
- try {
392
- await this.doRefresh(config);
393
- this.health.lastSuccessAt = (/* @__PURE__ */ new Date()).toISOString();
394
- this.health.lastErrorAt = null;
395
- this.health.lastErrorMessage = null;
396
- return createSuccessResult();
397
- } catch (error) {
398
- const message = error instanceof Error ? error.message : "Unknown error";
399
- this.health.lastErrorAt = (/* @__PURE__ */ new Date()).toISOString();
400
- this.health.lastErrorMessage = message;
401
- console.error(`[${this.managerName}] Failed to refresh credentials:`, error);
402
- return createErrorResult({ message });
403
- }
404
- }
405
- };
406
-
407
255
  // src/utils/file.ts
408
256
  import { randomUUID } from "crypto";
409
257
  import { mkdir, readFile, rename, unlink, writeFile } from "fs/promises";
@@ -423,11 +271,11 @@ var AsyncLock = class {
423
271
  };
424
272
 
425
273
  // src/utils/file.ts
426
- async function atomicWriteFile(path6, data, options) {
427
- const tmpFile = `${path6}.${process.pid}.${randomUUID()}.tmp`;
274
+ async function atomicWriteFile(path5, data, options) {
275
+ const tmpFile = `${path5}.${process.pid}.${randomUUID()}.tmp`;
428
276
  try {
429
277
  await writeFile(tmpFile, data, { encoding: "utf-8", mode: options?.mode });
430
- await rename(tmpFile, path6);
278
+ await rename(tmpFile, path5);
431
279
  } catch (error) {
432
280
  await unlink(tmpFile).catch(() => void 0);
433
281
  throw error;
@@ -850,9 +698,9 @@ var GitService = class {
850
698
  try {
851
699
  const paths = await this.listUntrackedPaths(repoPath);
852
700
  let total = 0;
853
- for (const path6 of paths) {
701
+ for (const path5 of paths) {
854
702
  try {
855
- const contents = await readFile3(join4(repoPath, path6));
703
+ const contents = await readFile3(join4(repoPath, path5));
856
704
  if (contents.length === 0 || contents.includes(0)) {
857
705
  continue;
858
706
  }
@@ -1108,9 +956,9 @@ var GitService = class {
1108
956
  await saveRepoState(repo.name, state, state);
1109
957
  return state;
1110
958
  }
1111
- async safeStat(path6) {
959
+ async safeStat(path5) {
1112
960
  try {
1113
- return await stat(path6);
961
+ return await stat(path5);
1114
962
  } catch {
1115
963
  return null;
1116
964
  }
@@ -1261,26 +1109,6 @@ var gitlabTokenManager = new GitLabTokenManager();
1261
1109
  // src/managers/claude-token-manager.ts
1262
1110
  import { promises as fs } from "fs";
1263
1111
  import path3 from "path";
1264
-
1265
- // src/managers/auth-env-transition.ts
1266
- function applyAuthEnvTransition(params) {
1267
- const newOwned = new Set(params.authKeysByMethod[params.newMethod]);
1268
- const prevOwned = new Set(params.authKeysByMethod[params.prevMethod]);
1269
- for (const key of params.authKeys) {
1270
- const value = params.newEnvVars[key];
1271
- if (value !== void 0) {
1272
- for (const env of params.envs) {
1273
- env[key] = value;
1274
- }
1275
- } else if (prevOwned.has(key) && !newOwned.has(key)) {
1276
- for (const env of params.envs) {
1277
- delete env[key];
1278
- }
1279
- }
1280
- }
1281
- }
1282
-
1283
- // src/managers/claude-token-manager.ts
1284
1112
  var ClaudeTokenManager = class extends BaseRefreshManager {
1285
1113
  constructor() {
1286
1114
  super("ClaudeTokenManager");
@@ -1385,153 +1213,9 @@ var ClaudeTokenManager = class extends BaseRefreshManager {
1385
1213
  };
1386
1214
  var claudeTokenManager = new ClaudeTokenManager();
1387
1215
 
1388
- // src/managers/codex-token-manager.ts
1389
- import { promises as fs2 } from "fs";
1390
- import path4 from "path";
1391
- var CodexAspAuthMethodChangedError = class extends Error {
1392
- name = "CodexAspAuthMethodChangedError";
1393
- };
1394
- var CodexTokenManager = class extends BaseRefreshManager {
1395
- constructor() {
1396
- super("CodexTokenManager");
1397
- }
1398
- getSkipReason() {
1399
- if (ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD === "api_key" || ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD === "foundry") {
1400
- return `auth method is ${ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD}`;
1401
- }
1402
- if (!ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD && ENGINE_ENV.OPENAI_API_KEY) {
1403
- return "OPENAI_API_KEY is set";
1404
- }
1405
- return null;
1406
- }
1407
- async doRefresh(_config) {
1408
- await this.refreshWithRequest();
1409
- }
1410
- async refreshWithRequest(request) {
1411
- console.log("[CodexTokenManager] Refreshing Codex credentials...");
1412
- const response = await monolithRequest("/v1/engine/codex/refresh-credentials", {
1413
- body: request
1414
- });
1415
- if (!response.ok) {
1416
- const errorText = await response.text();
1417
- throw new Error(`Credentials refresh failed: ${response.status} ${errorText}`);
1418
- }
1419
- const data = await response.json();
1420
- await this.applyCredentialsResponse(data);
1421
- if (data.scope) {
1422
- setAgentCredentialSnapshot("codex", {
1423
- method: data.type,
1424
- scope: data.scope,
1425
- ...data.revision ? { revision: data.revision } : {}
1426
- });
1427
- }
1428
- console.log(`[CodexTokenManager] Credentials refreshed (method=${data.type})`);
1429
- return data;
1430
- }
1431
- async prepareAspOauthOptions() {
1432
- if (ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD !== "oauth") return {};
1433
- const response = await this.refreshWithRequest();
1434
- if (response.type !== "oauth") return {};
1435
- const login = this.buildAspOauthLogin(response);
1436
- let credential = login.credential;
1437
- return {
1438
- chatgptAuthTokens: login.tokens,
1439
- refreshChatgptAuthTokens: async (params) => {
1440
- const refreshed = await this.refreshAspOauthCredentials(
1441
- credential,
1442
- `Codex ASP requested an external token refresh (${params.reason})`
1443
- );
1444
- if (!refreshed.ok) {
1445
- if (refreshed.error.code === "method_changed") {
1446
- throw new CodexAspAuthMethodChangedError(refreshed.error.message);
1447
- }
1448
- throw new Error(refreshed.error.message);
1449
- }
1450
- credential = refreshed.data.credential;
1451
- return refreshed.data.tokens;
1452
- }
1453
- };
1454
- }
1455
- async refreshAspOauthCredentials(failedCredential, failureReason) {
1456
- try {
1457
- const response = await this.refreshWithRequest({
1458
- failedMethod: "oauth",
1459
- ...failedCredential?.method === "oauth" ? { failedCredential } : {},
1460
- failureKind: "rejected",
1461
- failureReason
1462
- });
1463
- if (response.type !== "oauth") {
1464
- return createErrorResult({
1465
- message: `${failureReason}; credentials changed to ${response.type}, so the app server must restart`,
1466
- code: "method_changed"
1467
- });
1468
- }
1469
- return createSuccessResult(this.buildAspOauthLogin(response));
1470
- } catch (error) {
1471
- const message = error instanceof Error ? error.message : String(error);
1472
- return createErrorResult({
1473
- message,
1474
- code: message.includes('"code":"no_credentials"') ? "no_credentials" : "refresh_failed"
1475
- });
1476
- }
1477
- }
1478
- async fetchFreshCredentials(failureReason, failureKind = "rejected", failedCredential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.codex, allowedMethods) {
1479
- const failedMethod = failedCredential?.method === "oauth" || failedCredential?.method === "api_key" || failedCredential?.method === "foundry" ? failedCredential.method : ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD;
1480
- return this.swapCredentials({
1481
- provider: "codex",
1482
- failureKind,
1483
- allowedMethods,
1484
- refresh: async (exclusions) => {
1485
- await this.refreshWithRequest(
1486
- failedMethod === "oauth" || failedMethod === "api_key" || failedMethod === "foundry" ? {
1487
- failedMethod,
1488
- ...failedCredential?.method === failedMethod ? { failedCredential } : {},
1489
- failureReason,
1490
- failureKind,
1491
- ...exclusions
1492
- } : exclusions
1493
- );
1494
- },
1495
- isOauthNow: () => ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD === "oauth"
1496
- });
1497
- }
1498
- async applyCredentialsResponse(response) {
1499
- await this.removeOauthCredentialsFile();
1500
- const envVars = codexAuthEnvFromResponse(response);
1501
- applyAuthEnvTransition({
1502
- prevMethod: ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD ?? "none",
1503
- newMethod: envVars.REPLICAS_CODEX_AUTH_METHOD ?? "none",
1504
- authKeys: CODEX_AUTH_ENV_KEYS,
1505
- authKeysByMethod: CODEX_AUTH_ENV_KEYS_BY_METHOD,
1506
- newEnvVars: envVars,
1507
- envs: [ENGINE_ENV, process.env]
1508
- });
1509
- }
1510
- buildAspOauthLogin(response) {
1511
- const credential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.codex;
1512
- return {
1513
- tokens: {
1514
- accessToken: response.accessToken,
1515
- chatgptAccountId: response.accountId,
1516
- chatgptPlanType: null
1517
- },
1518
- ...credential?.method === "oauth" ? { credential } : {}
1519
- };
1520
- }
1521
- async removeOauthCredentialsFile() {
1522
- const authPath = path4.join(ENGINE_ENV.HOME_DIR, ".codex", "auth.json");
1523
- try {
1524
- await fs2.unlink(authPath);
1525
- } catch (error) {
1526
- if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
1527
- }
1528
- }
1529
- };
1530
- var codexTokenManager = new CodexTokenManager();
1531
-
1532
1216
  // src/managers/infisical-token-manager.ts
1533
1217
  import { rm } from "fs/promises";
1534
- import path5 from "path";
1218
+ import path4 from "path";
1535
1219
  var InfisicalTokenManager = class extends BaseRefreshManager {
1536
1220
  constructor(request = monolithRequest, paths = {
1537
1221
  homeDir: ENGINE_ENV.HOME_DIR,
@@ -1559,8 +1243,8 @@ var InfisicalTokenManager = class extends BaseRefreshManager {
1559
1243
  }
1560
1244
  };
1561
1245
  async function applyInfisicalCredentials(data, paths) {
1562
- const credentialPath = path5.join(paths.homeDir, ".replicas", "infisical-env.sh");
1563
- const configPath = path5.join(paths.workspaceRoot, ".infisical.json");
1246
+ const credentialPath = path4.join(paths.homeDir, ".replicas", "infisical-env.sh");
1247
+ const configPath = path4.join(paths.workspaceRoot, ".infisical.json");
1564
1248
  if (!data.configured) {
1565
1249
  delete process.env.INFISICAL_TOKEN;
1566
1250
  delete process.env.INFISICAL_DOMAIN;
@@ -1602,8 +1286,8 @@ var StreamWriter = class {
1602
1286
  backpressured = false;
1603
1287
  droppedCount = 0;
1604
1288
  flushTimer = null;
1605
- open(path6, highWaterMark = DEFAULT_HIGH_WATER) {
1606
- this.stream = createWriteStream(path6, { flags: "a", highWaterMark });
1289
+ open(path5, highWaterMark = DEFAULT_HIGH_WATER) {
1290
+ this.stream = createWriteStream(path5, { flags: "a", highWaterMark });
1607
1291
  this.stream.on("error", () => {
1608
1292
  this.stream = null;
1609
1293
  });
@@ -3346,7 +3030,7 @@ async function saveNormalizedImagesToTempFiles(images, tempImageDir = join13(hom
3346
3030
  return tempPaths;
3347
3031
  }
3348
3032
  async function removeTempImageFiles(paths) {
3349
- await Promise.allSettled(paths.map((path6) => unlink2(path6)));
3033
+ await Promise.allSettled(paths.map((path5) => unlink2(path5)));
3350
3034
  }
3351
3035
 
3352
3036
  // src/managers/coding-agent-manager.ts
@@ -4216,7 +3900,7 @@ async function getSkillRegistryInventory(homeDir) {
4216
3900
  async function buildClaudeRegistryConfig(homeDir) {
4217
3901
  const inventory = await getSkillRegistryInventory(homeDir);
4218
3902
  return {
4219
- plugins: inventory.claudePluginRoots.map((path6) => ({ type: "local", path: path6 })),
3903
+ plugins: inventory.claudePluginRoots.map((path5) => ({ type: "local", path: path5 })),
4220
3904
  enableAllSkills: inventory.claudePluginRoots.length > 0 || inventory.standaloneSkills.length > 0
4221
3905
  };
4222
3906
  }
@@ -4374,31 +4058,31 @@ function uniqueStandaloneSkills(skills) {
4374
4058
  }
4375
4059
  return unique;
4376
4060
  }
4377
- async function safeReadDir(path6) {
4061
+ async function safeReadDir(path5) {
4378
4062
  try {
4379
- return await readdir3(path6, { withFileTypes: true });
4063
+ return await readdir3(path5, { withFileTypes: true });
4380
4064
  } catch (error) {
4381
4065
  if (isNotFoundError(error)) return [];
4382
4066
  throw error;
4383
4067
  }
4384
4068
  }
4385
- async function isDirectoryDirent(dirent, path6) {
4069
+ async function isDirectoryDirent(dirent, path5) {
4386
4070
  if (dirent.isDirectory()) return true;
4387
4071
  if (!dirent.isSymbolicLink()) return false;
4388
- return directoryExists(path6);
4072
+ return directoryExists(path5);
4389
4073
  }
4390
- async function directoryExists(path6) {
4074
+ async function directoryExists(path5) {
4391
4075
  try {
4392
- const pathStat = await stat2(path6);
4076
+ const pathStat = await stat2(path5);
4393
4077
  return pathStat.isDirectory();
4394
4078
  } catch (error) {
4395
4079
  if (isNotFoundError(error)) return false;
4396
4080
  throw error;
4397
4081
  }
4398
4082
  }
4399
- async function fileExists(path6) {
4083
+ async function fileExists(path5) {
4400
4084
  try {
4401
- const pathStat = await stat2(path6);
4085
+ const pathStat = await stat2(path5);
4402
4086
  return pathStat.isFile();
4403
4087
  } catch (error) {
4404
4088
  if (isNotFoundError(error)) return false;
@@ -5880,57 +5564,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
5880
5564
  import { readdir as readdir4 } from "fs/promises";
5881
5565
  import { join as join18 } from "path";
5882
5566
 
5883
- // src/managers/codex-asp/asp-host.ts
5884
- var hostPromise = null;
5885
- var activeProcess = null;
5886
- var restartPromise = null;
5887
- async function getCodexAspHost() {
5888
- if (restartPromise) {
5889
- await restartPromise;
5890
- }
5891
- hostPromise ??= (async () => {
5892
- try {
5893
- const oauthOptions = await codexTokenManager.prepareAspOauthOptions();
5894
- const process2 = new AppServerProcess({
5895
- cwd: ENGINE_ENV.WORKSPACE_ROOT,
5896
- env: buildCodexAgentEnv(),
5897
- ...oauthOptions
5898
- });
5899
- const { client: client2 } = await process2.start();
5900
- activeProcess = process2;
5901
- process2.on("exit", () => {
5902
- if (activeProcess === process2) {
5903
- activeProcess = null;
5904
- }
5905
- hostPromise = null;
5906
- });
5907
- return { client: client2 };
5908
- } catch (error) {
5909
- hostPromise = null;
5910
- throw error;
5911
- }
5912
- })();
5913
- return hostPromise;
5914
- }
5915
- async function restartCodexAspHost() {
5916
- if (restartPromise) {
5917
- return restartPromise;
5918
- }
5919
- restartPromise = (async () => {
5920
- const process2 = activeProcess;
5921
- hostPromise = null;
5922
- activeProcess = null;
5923
- if (process2) {
5924
- await process2.stop();
5925
- }
5926
- })();
5927
- try {
5928
- await restartPromise;
5929
- } finally {
5930
- restartPromise = null;
5931
- }
5932
- }
5933
-
5934
5567
  // src/utils/codex-quota.ts
5935
5568
  function buildCodexRateLimitsSnapshot(fields) {
5936
5569
  if (fields.authMethod !== "oauth") return null;
@@ -6114,16 +5747,16 @@ function transcriptItemsForTurn(turn) {
6114
5747
  const otherItems = turn.items.filter((item) => item.type !== "userMessage");
6115
5748
  return [...userItems, ...otherItems];
6116
5749
  }
6117
- function userImageForLocalPath(path6) {
6118
- const cached = localImageCache.get(path6);
5750
+ function userImageForLocalPath(path5) {
5751
+ const cached = localImageCache.get(path5);
6119
5752
  if (cached) return cached;
6120
- if (!existsSync7(path6)) return null;
5753
+ if (!existsSync7(path5)) return null;
6121
5754
  const image = {
6122
5755
  type: "image",
6123
- mediaType: inferMediaType(path6),
6124
- data: readFileSync3(path6).toString("base64")
5756
+ mediaType: inferMediaType(path5),
5757
+ data: readFileSync3(path5).toString("base64")
6125
5758
  };
6126
- if (image.data.length > 0) localImageCache.set(path6, image);
5759
+ if (image.data.length > 0) localImageCache.set(path5, image);
6127
5760
  return image;
6128
5761
  }
6129
5762
  function userImagesForInput(input) {
@@ -6521,9 +6154,9 @@ async function buildTurnInput(request) {
6521
6154
  }
6522
6155
  const normalizedImages = await normalizeImages(request.images);
6523
6156
  const tempImagePaths = await saveNormalizedImagesToTempFiles(normalizedImages);
6524
- input.push(...tempImagePaths.map((path6) => ({
6157
+ input.push(...tempImagePaths.map((path5) => ({
6525
6158
  type: "localImage",
6526
- path: path6
6159
+ path: path5
6527
6160
  })));
6528
6161
  return { input, tempImagePaths };
6529
6162
  }
@@ -8113,12 +7746,12 @@ var postToolHookPath = [
8113
7746
  join19(moduleDirectory, "post-tool-pr-hook.js"),
8114
7747
  join19(moduleDirectory, "..", "post-tool-pr-hook.ts")
8115
7748
  ].find(existsSync8);
8116
- function shellCommand(path6, provider) {
8117
- if (!path6) throw new Error("Replicas hook executable is missing.");
7749
+ function shellCommand(path5, provider) {
7750
+ if (!path5) throw new Error("Replicas hook executable is missing.");
8118
7751
  const args = [
8119
7752
  process.execPath,
8120
- ...path6.endsWith(".ts") && basename(process.execPath) !== "bun" ? ["--import", "tsx"] : [],
8121
- path6,
7753
+ ...path5.endsWith(".ts") && basename(process.execPath) !== "bun" ? ["--import", "tsx"] : [],
7754
+ path5,
8122
7755
  ...provider ? [provider] : []
8123
7756
  ];
8124
7757
  return args.map((value) => `'${value.replaceAll("'", "'\\''")}'`).join(" ");
@@ -8132,10 +7765,10 @@ function getPostToolPrHookPath() {
8132
7765
  return postToolHookPath;
8133
7766
  }
8134
7767
  async function ensureCursorCommandProtectionHook() {
8135
- const path6 = join19(ENGINE_ENV.HOME_DIR, ".cursor", "hooks.json");
7768
+ const path5 = join19(ENGINE_ENV.HOME_DIR, ".cursor", "hooks.json");
8136
7769
  let config = {};
8137
7770
  try {
8138
- const parsed = JSON.parse(await readFile10(path6, "utf8"));
7771
+ const parsed = JSON.parse(await readFile10(path5, "utf8"));
8139
7772
  if (!isRecord2(parsed)) throw new Error("Invalid Cursor hooks configuration.");
8140
7773
  config = parsed;
8141
7774
  } catch (error) {
@@ -8152,17 +7785,17 @@ async function ensureCursorCommandProtectionHook() {
8152
7785
  ...existingPost.filter((entry) => !isRecord2(entry) || typeof entry.command !== "string" || !entry.command.includes("post-tool-pr-hook")),
8153
7786
  { command: shellCommand(postToolHookPath) }
8154
7787
  ];
8155
- await mkdir11(dirname5(path6), { recursive: true });
8156
- await writeFile6(path6, `${JSON.stringify({ ...config, version: 1, hooks }, null, 2)}
7788
+ await mkdir11(dirname5(path5), { recursive: true });
7789
+ await writeFile6(path5, `${JSON.stringify({ ...config, version: 1, hooks }, null, 2)}
8157
7790
  `, "utf8");
8158
7791
  }
8159
7792
  async function ensureKimiCommandProtectionHook() {
8160
- const path6 = join19(ENGINE_ENV.HOME_DIR, ".kimi-code", "config.toml");
7793
+ const path5 = join19(ENGINE_ENV.HOME_DIR, ".kimi-code", "config.toml");
8161
7794
  const start = "# Replicas command protection hook";
8162
7795
  const end = "# End Replicas command protection hook";
8163
7796
  let config = "";
8164
7797
  try {
8165
- config = await readFile10(path6, "utf8");
7798
+ config = await readFile10(path5, "utf8");
8166
7799
  } catch (error) {
8167
7800
  if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
8168
7801
  }
@@ -8181,8 +7814,8 @@ ${end}`;
8181
7814
  const markerEnd = config.indexOf(end, markerStart + start.length);
8182
7815
  config = markerStart >= 0 && markerEnd >= 0 ? `${config.slice(0, markerStart)}${block}${config.slice(markerEnd + end.length)}` : `${config.trimEnd()}${config.trim() ? "\n\n" : ""}${block}
8183
7816
  `;
8184
- await mkdir11(dirname5(path6), { recursive: true });
8185
- await writeFile6(path6, config, "utf8");
7817
+ await mkdir11(dirname5(path5), { recursive: true });
7818
+ await writeFile6(path5, config, "utf8");
8186
7819
  }
8187
7820
 
8188
7821
  // src/managers/cursor-manager.ts
@@ -8682,8 +8315,8 @@ var DeepseekApiClient = class extends AbstractApiClient {
8682
8315
  if (!execution.success) throw new Error(`DeepSeek Harness did not recognize ${line}.`);
8683
8316
  if (execution.data.result.kind === "error") throw new Error(execution.data.result.text ?? `DeepSeek Harness rejected ${line}.`);
8684
8317
  }
8685
- async *readWebSocket(path6, signal, schema, onOpen) {
8686
- const url = new URL(path6, this.baseUrl);
8318
+ async *readWebSocket(path5, signal, schema, onOpen) {
8319
+ const url = new URL(path5, this.baseUrl);
8687
8320
  url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
8688
8321
  const socket = new WebSocket(url);
8689
8322
  const inbox = [];
@@ -10970,9 +10603,9 @@ function extractTextBlocks(content, textBlockType, separator = "\n") {
10970
10603
  const texts = content.map((block) => block && typeof block === "object" && "type" in block && block.type === textBlockType && "text" in block && typeof block.text === "string" ? block.text : "").filter(Boolean);
10971
10604
  return texts.length > 0 ? texts.join(separator) : null;
10972
10605
  }
10973
- async function engineFetch(path6, options) {
10606
+ async function engineFetch(path5, options) {
10974
10607
  const baseUrl = `http://localhost:${ENGINE_ENV.REPLICAS_ENGINE_PORT}`;
10975
- return fetch(`${baseUrl}${path6}`, {
10608
+ return fetch(`${baseUrl}${path5}`, {
10976
10609
  ...options,
10977
10610
  headers: {
10978
10611
  "Content-Type": "application/json",
@@ -13105,10 +12738,10 @@ function unansweredRequest(blocks) {
13105
12738
  const answered = blocks.slice(lastUser + 1).some((block) => block.startsWith("## Agent"));
13106
12739
  return answered ? null : lastUserBlockText(blocks);
13107
12740
  }
13108
- async function readHistoryTail(path6, maxBytes) {
12741
+ async function readHistoryTail(path5, maxBytes) {
13109
12742
  let handle;
13110
12743
  try {
13111
- handle = await open2(path6, "r");
12744
+ handle = await open2(path5, "r");
13112
12745
  } catch (error) {
13113
12746
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return { content: "", truncated: false };
13114
12747
  throw error;
@@ -13745,7 +13378,7 @@ var ChatService = class {
13745
13378
  historyPath,
13746
13379
  `${historyPath}.pages.jsonl`,
13747
13380
  `${historyPath}.pages.index.json`
13748
- ].map((path6) => rm3(path6, { force: true })));
13381
+ ].map((path5) => rm3(path5, { force: true })));
13749
13382
  await rm3(chatMessageSendersFilePath(persisted.id), { force: true });
13750
13383
  await rm3(join30(FORKS_DIR, persisted.id), { recursive: true, force: true });
13751
13384
  }
@@ -15665,11 +15298,11 @@ function createV1Routes(deps) {
15665
15298
  });
15666
15299
  app2.get("/repo-files/content", async (c) => {
15667
15300
  const repoName = c.req.query("repoName");
15668
- const path6 = c.req.query("path");
15669
- if (!repoName || !path6) {
15301
+ const path5 = c.req.query("path");
15302
+ if (!repoName || !path5) {
15670
15303
  return c.json(jsonError("repoName and path are required"), 400);
15671
15304
  }
15672
- const result = await deps.repoFileService.readFile(repoName, path6);
15305
+ const result = await deps.repoFileService.readFile(repoName, path5);
15673
15306
  if (!result) {
15674
15307
  return c.json(jsonError("File not found"), 404);
15675
15308
  }
@@ -15677,12 +15310,12 @@ function createV1Routes(deps) {
15677
15310
  });
15678
15311
  app2.put("/repo-files/content", async (c) => {
15679
15312
  const repoName = c.req.query("repoName");
15680
- const path6 = c.req.query("path");
15681
- if (!repoName || !path6) {
15313
+ const path5 = c.req.query("path");
15314
+ if (!repoName || !path5) {
15682
15315
  return c.json(jsonError("repoName and path are required"), 400);
15683
15316
  }
15684
15317
  const body = updateTextFileSchema(MAX_REPO_FILE_CONTENT_BYTES).parse(await c.req.json());
15685
- const result = await deps.repoFileService.updateFile(repoName, path6, body.content, body.expectedRevision);
15318
+ const result = await deps.repoFileService.updateFile(repoName, path5, body.content, body.expectedRevision);
15686
15319
  if (!result) return c.json(jsonError("File is not editable"), 400);
15687
15320
  return c.json(result);
15688
15321
  });
@@ -15821,7 +15454,7 @@ data: ${JSON.stringify("Terminal session not found")}
15821
15454
  });
15822
15455
  app2.post("/codex/refresh-now", async (c) => {
15823
15456
  try {
15824
- const result = await codexTokenManager.refreshOnce();
15457
+ const result = await codexTokenManager.refreshOnce(true);
15825
15458
  if (!result.ok) {
15826
15459
  return c.json(
15827
15460
  jsonError("Failed to refresh Codex credentials", result.error.message),