replicas-engine 0.1.920 → 0.1.922

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
@@ -27,7 +27,7 @@ import {
27
27
  evaluateCommandProtection,
28
28
  extractToolCommand,
29
29
  reportCommandProtectionBlock
30
- } from "./chunk-AOBS7XEL.js";
30
+ } from "./chunk-HEYQCKMN.js";
31
31
  import {
32
32
  ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
33
33
  AGENT_MESSAGE_DELTA_METHOD,
@@ -52,7 +52,7 @@ import {
52
52
  } from "./chunk-FLDA7BX3.js";
53
53
  import {
54
54
  publishedPullRequestUrls
55
- } from "./chunk-CO3743XW.js";
55
+ } from "./chunk-2J5TLHIA.js";
56
56
  import {
57
57
  RELAY_MCP_TOOLS,
58
58
  RELAY_MCP_TOOL_NAMES,
@@ -73,21 +73,22 @@ import {
73
73
  refreshDelayMs,
74
74
  restartCodexAspHost,
75
75
  routineRefreshExclusions
76
- } from "./chunk-FJV46MRD.js";
76
+ } from "./chunk-5VE2EIS6.js";
77
77
  import {
78
78
  ENGINE_ENV,
79
- IS_WARMING_MODE,
80
79
  monolithRequest,
81
80
  monolithService,
81
+ readRuntimeEnvFile,
82
+ reloadEngineEnv,
82
83
  setAgentCredentialSnapshot
83
- } from "./chunk-UMXQF6DT.js";
84
+ } from "./chunk-LYX74DW2.js";
84
85
  import {
85
86
  AspClient,
86
87
  SUBPROCESS_MAX_BUFFER,
87
88
  execAsync,
88
89
  execFileAsync,
89
90
  getCodexModelProvider
90
- } from "./chunk-6GY7ZCSO.js";
91
+ } from "./chunk-75D2W6N3.js";
91
92
  import {
92
93
  isRecord as isRecord2
93
94
  } from "./chunk-UZSNFLDQ.js";
@@ -144,9 +145,11 @@ import {
144
145
  DEFAULT_RELAY_BASE_PROVIDER,
145
146
  DEFAULT_START_HOOK_TIMEOUT_MS,
146
147
  DESKTOP_STREAM_PORT,
148
+ ENGINE_ACTIVATE_PATH,
147
149
  ENGINE_HEALTH_MAX_WAIT_MS,
148
150
  ENGINE_HEALTH_WAIT_HEADER,
149
151
  ENGINE_HEALTH_WAIT_QUERY_PARAM,
152
+ ENGINE_SLEEP_PATH,
150
153
  GITHUB_CREDENTIAL_REFRESH_PATH,
151
154
  GITLAB_CREDENTIAL_REFRESH_PATH,
152
155
  GIT_CREDENTIAL_HELPER_FILENAME,
@@ -170,7 +173,7 @@ import {
170
173
  RELAY_MCP_SERVER_NAME,
171
174
  REMOVED_MESSAGE_IDS_PAYLOAD_KEY,
172
175
  REPLICAS_CONFIG_FILENAMES,
173
- SANDBOX_PATHS,
176
+ REPLICAS_RUNTIME_ENV_ALIASES,
174
177
  TIMEOUT,
175
178
  TOKEN_USAGE_PATH,
176
179
  TaskAccumulator,
@@ -291,6 +294,7 @@ import {
291
294
  raceWithTimeout,
292
295
  readJsonlPage,
293
296
  readOllamaAuthEnv,
297
+ readReplicasRuntimeEnv,
294
298
  resolveWarmHookConfig,
295
299
  safeJsonParse,
296
300
  sanitizeCanvasFilename,
@@ -309,7 +313,7 @@ import {
309
313
  workspaceCredentialProviderSchema,
310
314
  workspaceTokenRequestSchema,
311
315
  workspaceTokenResponseSchema
312
- } from "./chunk-MLSB5HUT.js";
316
+ } from "./chunk-VT557AFP.js";
313
317
  import {
314
318
  cloneMcpConfig,
315
319
  ensureCompatibilityImports,
@@ -8550,7 +8554,6 @@ var require_dist2 = __commonJS({
8550
8554
  // src/index.ts
8551
8555
  import { serve } from "@hono/node-server";
8552
8556
  import { Hono as Hono2 } from "hono";
8553
- import { existsSync as existsSync19 } from "fs";
8554
8557
  import { randomUUID as randomUUID13 } from "crypto";
8555
8558
  import { connect } from "net";
8556
8559
 
@@ -9804,6 +9807,57 @@ function createIdentityProxy(tokens) {
9804
9807
  });
9805
9808
  }
9806
9809
 
9810
+ // src/lifecycle.ts
9811
+ import { readFileSync as readFileSync2, rmSync, writeFileSync } from "fs";
9812
+ var CLAIM_FILE = "/tmp/replicas-engine.claim";
9813
+ var EngineLifecycle = class {
9814
+ state = "parked";
9815
+ workspaceId = null;
9816
+ activeWaiters = [];
9817
+ transitions = Promise.resolve();
9818
+ get active() {
9819
+ return this.state === "active";
9820
+ }
9821
+ /** The workspace an earlier run of this engine activated for and never slept. */
9822
+ get claimedWorkspaceId() {
9823
+ try {
9824
+ return readFileSync2(CLAIM_FILE, "utf-8").trim() || null;
9825
+ } catch {
9826
+ return null;
9827
+ }
9828
+ }
9829
+ claim(workspaceId) {
9830
+ this.workspaceId = workspaceId;
9831
+ writeFileSync(CLAIM_FILE, workspaceId);
9832
+ }
9833
+ releaseClaim() {
9834
+ rmSync(CLAIM_FILE, { force: true });
9835
+ }
9836
+ set(state) {
9837
+ this.state = state;
9838
+ if (state === "active") {
9839
+ for (const wake of this.activeWaiters.splice(0)) wake();
9840
+ }
9841
+ }
9842
+ waitForActive(timeoutMs) {
9843
+ if (this.active) return Promise.resolve();
9844
+ return new Promise((resolve8) => {
9845
+ const timer = setTimeout(resolve8, timeoutMs);
9846
+ this.activeWaiters.push(() => {
9847
+ clearTimeout(timer);
9848
+ resolve8();
9849
+ });
9850
+ });
9851
+ }
9852
+ /** Overlapping activate/sleep requests apply one after another instead of interleaving. */
9853
+ transition(run) {
9854
+ const next = this.transitions.then(run, run);
9855
+ this.transitions = next.catch(() => void 0);
9856
+ return next;
9857
+ }
9858
+ };
9859
+ var lifecycle = new EngineLifecycle();
9860
+
9807
9861
  // src/utils/logger.ts
9808
9862
  import { mkdir as mkdir3, writeFile as writeFile2 } from "fs/promises";
9809
9863
  import { homedir as homedir2 } from "os";
@@ -10364,12 +10418,14 @@ var ReplicasConfigService = class {
10364
10418
  hooksRunning = false;
10365
10419
  hooksCompleted = false;
10366
10420
  hooksFailed = false;
10421
+ /** By hook owner; their background processes outlive the run, and survive a pause along with the engine. */
10422
+ hookProcessGroups = /* @__PURE__ */ new Map();
10367
10423
  /**
10368
10424
  * Initialize by reading all replicas config files and running start hooks.
10369
10425
  */
10370
10426
  async initialize() {
10371
10427
  await this.loadConfigs();
10372
- if (IS_WARMING_MODE || ENGINE_ENV.REPLICAS_DISABLE_AUTO_START_HOOKS) {
10428
+ if (ENGINE_ENV.REPLICAS_DISABLE_AUTO_START_HOOKS) {
10373
10429
  this.hooksRunning = false;
10374
10430
  this.hooksCompleted = false;
10375
10431
  this.hooksFailed = false;
@@ -10382,6 +10438,23 @@ var ReplicasConfigService = class {
10382
10438
  console.error("[ReplicasConfig] Start hooks execution failed:", errorMessage);
10383
10439
  });
10384
10440
  }
10441
+ /** Otherwise a rerun starts a second copy of every server the owner's previous run left running. */
10442
+ async stopStartHookProcesses(owner) {
10443
+ const groups = this.hookProcessGroups.get(owner) ?? [];
10444
+ this.hookProcessGroups.delete(owner);
10445
+ const signal = (name) => groups.filter((pgid) => {
10446
+ try {
10447
+ process.kill(-pgid, name);
10448
+ return true;
10449
+ } catch {
10450
+ return false;
10451
+ }
10452
+ });
10453
+ if (signal("SIGTERM").length === 0) return;
10454
+ const deadline = Date.now() + 5e3;
10455
+ while (signal(0).length > 0 && Date.now() < deadline) await new Promise((resolve8) => setTimeout(resolve8, 25));
10456
+ signal("SIGKILL");
10457
+ }
10385
10458
  /**
10386
10459
  * Load and parse replicas config from each discovered repository root.
10387
10460
  * Checks replicas.json first, then falls back to replicas.yaml/replicas.yml.
@@ -10426,6 +10499,7 @@ var ReplicasConfigService = class {
10426
10499
  }
10427
10500
  }
10428
10501
  async executeEnvironmentStartHook(params) {
10502
+ await this.stopStartHookProcesses("environment");
10429
10503
  await this.logToFile(`[environment] --- Running env-level start hook ---`);
10430
10504
  const result = await this.execStartHookCommand({
10431
10505
  command: params.content,
@@ -10458,8 +10532,10 @@ var ReplicasConfigService = class {
10458
10532
  const proc = spawn2("bash", ["-lc", params.command], {
10459
10533
  cwd: params.cwd,
10460
10534
  env: process.env,
10461
- stdio: ["pipe", "pipe", "pipe"]
10535
+ stdio: ["pipe", "pipe", "pipe"],
10536
+ detached: true
10462
10537
  });
10538
+ if (proc.pid) this.hookProcessGroups.set(params.repoName, [...this.hookProcessGroups.get(params.repoName) ?? [], proc.pid]);
10463
10539
  let timedOut = false;
10464
10540
  let settled = false;
10465
10541
  const finish = (result) => {
@@ -10600,6 +10676,7 @@ Repositories: ${hookEntries.length}
10600
10676
  await environmentDetailsService.setRepositoryStartHook(entry.repoName, "yes");
10601
10677
  continue;
10602
10678
  }
10679
+ await this.stopStartHookProcesses(entry.repoName);
10603
10680
  const timeout = params.timeoutMs ?? startHookConfig.timeout ?? DEFAULT_START_HOOK_TIMEOUT_MS;
10604
10681
  let repoFailed = false;
10605
10682
  let lastExitCode = 0;
@@ -10856,14 +10933,15 @@ var PreviewService = class {
10856
10933
  var previewService = new PreviewService();
10857
10934
 
10858
10935
  // src/services/desktop-preview-service.ts
10936
+ import { setTimeout as setTimeout2 } from "timers/promises";
10859
10937
  var REGISTRATION_TIMEOUT_MS = 3e4;
10860
10938
  var RETRY_DELAY_MS = 2e3;
10861
10939
  var ATTEMPT_TIMEOUT_MS = 8e3;
10862
- async function attemptRegistration() {
10940
+ async function attemptRegistration(signal) {
10863
10941
  try {
10864
10942
  const response = await monolithRequest("/v1/previews", {
10865
10943
  body: { port: DESKTOP_STREAM_PORT, authenticated: true },
10866
- signal: AbortSignal.timeout(ATTEMPT_TIMEOUT_MS)
10944
+ signal: AbortSignal.any([signal, AbortSignal.timeout(ATTEMPT_TIMEOUT_MS)])
10867
10945
  });
10868
10946
  if (response.ok || response.status === 409) {
10869
10947
  console.log(
@@ -10877,22 +10955,25 @@ async function attemptRegistration() {
10877
10955
  );
10878
10956
  return false;
10879
10957
  } catch (error) {
10958
+ if (signal.aborted) return false;
10880
10959
  const message = error instanceof Error ? error.message : String(error);
10881
10960
  console.error(`[DesktopPreview] Registration error: ${message}`);
10882
10961
  return false;
10883
10962
  }
10884
10963
  }
10885
- async function registerDesktopPreview() {
10886
- if (IS_WARMING_MODE || !ENGINE_ENV.REPLICAS_WORKSPACE_ID) {
10964
+ async function registerDesktopPreview(signal) {
10965
+ if (!ENGINE_ENV.REPLICAS_WORKSPACE_ID) {
10887
10966
  return;
10888
10967
  }
10889
10968
  const deadline = Date.now() + REGISTRATION_TIMEOUT_MS;
10890
- while (Date.now() < deadline) {
10891
- if (await attemptRegistration()) {
10969
+ while (!signal.aborted && Date.now() < deadline) {
10970
+ if (await attemptRegistration(signal)) {
10892
10971
  return;
10893
10972
  }
10894
- await new Promise((resolve8) => setTimeout(resolve8, RETRY_DELAY_MS));
10973
+ await setTimeout2(RETRY_DELAY_MS, void 0, { signal }).catch(() => {
10974
+ });
10895
10975
  }
10976
+ if (signal.aborted) return;
10896
10977
  console.error(
10897
10978
  `[DesktopPreview] Gave up registering port ${DESKTOP_STREAM_PORT} after ${REGISTRATION_TIMEOUT_MS}ms`
10898
10979
  );
@@ -11343,7 +11424,7 @@ function codexAspChangePaths(item) {
11343
11424
  function codexAspStatusResult(status) {
11344
11425
  return status === "completed" ? "Done" : status || "Done";
11345
11426
  }
11346
- function convertCodexAspItem(item, lifecycle, linearSessionId) {
11427
+ function convertCodexAspItem(item, lifecycle2, linearSessionId) {
11347
11428
  if (item.type === "agentMessage") {
11348
11429
  if (!item.text) return null;
11349
11430
  return {
@@ -11372,7 +11453,7 @@ function convertCodexAspItem(item, lifecycle, linearSessionId) {
11372
11453
  type: "action",
11373
11454
  action: "Running command",
11374
11455
  parameter: item.command,
11375
- ...lifecycle === "completed" ? { result: item.exitCode !== null ? `Exit code: ${item.exitCode}` : item.aggregatedOutput || "Done" } : {}
11456
+ ...lifecycle2 === "completed" ? { result: item.exitCode !== null ? `Exit code: ${item.exitCode}` : item.aggregatedOutput || "Done" } : {}
11376
11457
  }
11377
11458
  };
11378
11459
  }
@@ -11383,7 +11464,7 @@ function convertCodexAspItem(item, lifecycle, linearSessionId) {
11383
11464
  type: "action",
11384
11465
  action: "File change",
11385
11466
  parameter: codexAspChangePaths(item),
11386
- ...lifecycle === "completed" ? { result: codexAspStatusResult(item.status) } : {}
11467
+ ...lifecycle2 === "completed" ? { result: codexAspStatusResult(item.status) } : {}
11387
11468
  }
11388
11469
  };
11389
11470
  }
@@ -11394,7 +11475,7 @@ function convertCodexAspItem(item, lifecycle, linearSessionId) {
11394
11475
  type: "action",
11395
11476
  action: item.tool || "MCP tool call",
11396
11477
  parameter: item.server,
11397
- ...lifecycle === "completed" ? { result: item.error?.message ?? codexAspStatusResult(item.status) } : {}
11478
+ ...lifecycle2 === "completed" ? { result: item.error?.message ?? codexAspStatusResult(item.status) } : {}
11398
11479
  }
11399
11480
  };
11400
11481
  }
@@ -11405,7 +11486,7 @@ function convertCodexAspItem(item, lifecycle, linearSessionId) {
11405
11486
  type: "action",
11406
11487
  action: item.tool,
11407
11488
  parameter: item.namespace ?? "",
11408
- ...lifecycle === "completed" ? { result: item.success === false ? "Failed" : codexAspStatusResult(item.status) } : {}
11489
+ ...lifecycle2 === "completed" ? { result: item.success === false ? "Failed" : codexAspStatusResult(item.status) } : {}
11409
11490
  }
11410
11491
  };
11411
11492
  }
@@ -11416,7 +11497,7 @@ function convertCodexAspItem(item, lifecycle, linearSessionId) {
11416
11497
  type: "action",
11417
11498
  action: "Web search",
11418
11499
  parameter: item.query,
11419
- ...lifecycle === "completed" ? { result: "Done" } : {}
11500
+ ...lifecycle2 === "completed" ? { result: "Done" } : {}
11420
11501
  }
11421
11502
  };
11422
11503
  }
@@ -11427,7 +11508,7 @@ function convertCodexAspItem(item, lifecycle, linearSessionId) {
11427
11508
  type: "action",
11428
11509
  action: "Updating plan",
11429
11510
  parameter: item.text,
11430
- ...lifecycle === "completed" ? { result: "Done" } : {}
11511
+ ...lifecycle2 === "completed" ? { result: "Done" } : {}
11431
11512
  }
11432
11513
  };
11433
11514
  }
@@ -14527,7 +14608,7 @@ var CodexQuotaStatusTracker = class {
14527
14608
  };
14528
14609
 
14529
14610
  // src/managers/codex-asp/mappers.ts
14530
- import { existsSync as existsSync7, readFileSync as readFileSync2 } from "fs";
14611
+ import { existsSync as existsSync7, readFileSync as readFileSync3 } from "fs";
14531
14612
  var localImageCache = /* @__PURE__ */ new Map();
14532
14613
  var DEFAULT_MODEL = DEFAULT_CODEX_MODEL;
14533
14614
  var THREAD_START_METHOD = "thread/start";
@@ -14655,7 +14736,7 @@ function userImageForLocalPath(path7) {
14655
14736
  const image = {
14656
14737
  type: "image",
14657
14738
  mediaType: inferMediaType(path7),
14658
- data: readFileSync2(path7).toString("base64")
14739
+ data: readFileSync3(path7).toString("base64")
14659
14740
  };
14660
14741
  if (image.data.length > 0) localImageCache.set(path7, image);
14661
14742
  return image;
@@ -40401,7 +40482,7 @@ async function probeMcpEndpoint(url3) {
40401
40482
  }
40402
40483
 
40403
40484
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/npx-resolver.ts
40404
- import { existsSync as existsSync10, readFileSync as readFileSync3, realpathSync, readdirSync as readdirSync2, statSync as statSync2, writeFileSync, renameSync, mkdirSync, openSync, readSync, closeSync, unlinkSync } from "fs";
40485
+ import { existsSync as existsSync10, readFileSync as readFileSync4, realpathSync, readdirSync as readdirSync2, statSync as statSync2, writeFileSync as writeFileSync2, renameSync, mkdirSync, openSync, readSync, closeSync, unlinkSync } from "fs";
40405
40486
  import { join as join22, dirname as dirname9, extname as extname2, resolve as resolve3, sep } from "path";
40406
40487
 
40407
40488
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/abort.ts
@@ -40563,7 +40644,7 @@ function resolveFromNpmCache(packageSpec, binName) {
40563
40644
  if (!existsSync10(packageJsonPath)) return null;
40564
40645
  let pkg = null;
40565
40646
  try {
40566
- pkg = JSON.parse(readFileSync3(packageJsonPath, "utf-8"));
40647
+ pkg = JSON.parse(readFileSync4(packageJsonPath, "utf-8"));
40567
40648
  } catch {
40568
40649
  return null;
40569
40650
  }
@@ -40709,7 +40790,7 @@ function findCachedPackageDir(cacheDir, packageName, exactVersion) {
40709
40790
  if (!existsSync10(packageJsonPath)) continue;
40710
40791
  if (exactVersion) {
40711
40792
  try {
40712
- const pkg = JSON.parse(readFileSync3(packageJsonPath, "utf-8"));
40793
+ const pkg = JSON.parse(readFileSync4(packageJsonPath, "utf-8"));
40713
40794
  if (pkg.version !== exactVersion) continue;
40714
40795
  } catch {
40715
40796
  continue;
@@ -40771,7 +40852,7 @@ function getNpxCachePath() {
40771
40852
  function readNpxCachePayload(cachePath) {
40772
40853
  if (!existsSync10(cachePath)) return null;
40773
40854
  try {
40774
- return JSON.parse(readFileSync3(cachePath, "utf-8"));
40855
+ return JSON.parse(readFileSync4(cachePath, "utf-8"));
40775
40856
  } catch {
40776
40857
  return null;
40777
40858
  }
@@ -40816,7 +40897,7 @@ function clearLegacyCache() {
40816
40897
  unlinkSync(cachePath);
40817
40898
  } catch {
40818
40899
  try {
40819
- writeFileSync(cachePath, "", "utf-8");
40900
+ writeFileSync2(cachePath, "", "utf-8");
40820
40901
  } catch {
40821
40902
  }
40822
40903
  }
@@ -40838,7 +40919,7 @@ function saveCacheEntry(key, entry) {
40838
40919
  const merged = { version: CACHE_VERSION, entries };
40839
40920
  merged.entries[key] = entry;
40840
40921
  const tmpPath = `${cachePath}.${process.pid}.tmp`;
40841
- writeFileSync(tmpPath, JSON.stringify(merged, null, 2), "utf-8");
40922
+ writeFileSync2(tmpPath, JSON.stringify(merged, null, 2), "utf-8");
40842
40923
  renameSync(tmpPath, cachePath);
40843
40924
  } catch {
40844
40925
  }
@@ -40916,7 +40997,7 @@ function createJsonSchemaValidator() {
40916
40997
  import { spawnSync } from "child_process";
40917
40998
  import { createHash as createHash2 } from "crypto";
40918
40999
  import { createRequire } from "module";
40919
- import { readFileSync as readFileSync4, existsSync as existsSync11, rmSync } from "fs";
41000
+ import { readFileSync as readFileSync5, existsSync as existsSync11, rmSync as rmSync2 } from "fs";
40920
41001
  import { dirname as dirname10, join as join23 } from "path";
40921
41002
  import { fileURLToPath as fileURLToPath3 } from "url";
40922
41003
  var require2 = createRequire(import.meta.url);
@@ -41337,20 +41418,20 @@ function readChunkedAuthEntry(store, serverName, account, manifest) {
41337
41418
  function readLegacyAuthEntry(serverName, options) {
41338
41419
  const filePath = getAuthEntryFilePath(serverName, options);
41339
41420
  if (!existsSync11(filePath)) return void 0;
41340
- const data = readFileSync4(filePath, "utf-8");
41421
+ const data = readFileSync5(filePath, "utf-8");
41341
41422
  return parseAuthEntryPayload(serverName, data, filePath);
41342
41423
  }
41343
41424
  function removeLegacyAuthEntry(serverName, options) {
41344
41425
  const filePath = getAuthEntryFilePath(serverName, options);
41345
41426
  if (!existsSync11(filePath)) return;
41346
41427
  try {
41347
- rmSync(filePath, { force: true });
41428
+ rmSync2(filePath, { force: true });
41348
41429
  } catch (error) {
41349
41430
  throw new Error(`Failed to remove legacy plaintext OAuth credentials for ${serverName} at ${filePath}`, { cause: error });
41350
41431
  }
41351
41432
  const dir = getServerDir(serverName, options);
41352
41433
  try {
41353
- rmSync(dir, { recursive: true });
41434
+ rmSync2(dir, { recursive: true });
41354
41435
  } catch {
41355
41436
  }
41356
41437
  }
@@ -47226,7 +47307,7 @@ async function initializeMcp(pi, ctx, owner = createMcpRuntimeOwner(), options =
47226
47307
  allowUrl: mode === "tui"
47227
47308
  });
47228
47309
  }
47229
- const lifecycle = new McpLifecycleManager(manager, (serverName) => hasPendingAuth(serverName, void 0, oauthRuntime));
47310
+ const lifecycle2 = new McpLifecycleManager(manager, (serverName) => hasPendingAuth(serverName, void 0, oauthRuntime));
47230
47311
  const toolMetadata = /* @__PURE__ */ new Map();
47231
47312
  const resourceCounts = /* @__PURE__ */ new Map();
47232
47313
  const promptMetadata = /* @__PURE__ */ new Map();
@@ -47240,7 +47321,7 @@ async function initializeMcp(pi, ctx, owner = createMcpRuntimeOwner(), options =
47240
47321
  const state = {
47241
47322
  owner,
47242
47323
  manager,
47243
- lifecycle,
47324
+ lifecycle: lifecycle2,
47244
47325
  toolMetadata,
47245
47326
  resourceCounts,
47246
47327
  promptMetadata,
@@ -47273,7 +47354,7 @@ async function initializeMcp(pi, ctx, owner = createMcpRuntimeOwner(), options =
47273
47354
  deliver();
47274
47355
  return;
47275
47356
  }
47276
- void lifecycle.ensureConverged(owner.signal).then(deliver, (error) => {
47357
+ void lifecycle2.ensureConverged(owner.signal).then(deliver, (error) => {
47277
47358
  if (!owner.isActive() || isAbortError(error, owner.signal)) return;
47278
47359
  const detail = error instanceof Error ? error.message : String(error);
47279
47360
  logger.debug(`MCP: pre-turn keep-alive convergence failed: ${sanitizeTerminalText(detail)}`);
@@ -47294,7 +47375,7 @@ async function initializeMcp(pi, ctx, owner = createMcpRuntimeOwner(), options =
47294
47375
  if (!owner.isActive()) return;
47295
47376
  updateStatusBar(state);
47296
47377
  });
47297
- owner.addCleanup(() => lifecycle.gracefulShutdown());
47378
+ owner.addCleanup(() => lifecycle2.gracefulShutdown());
47298
47379
  owner.addCleanup(() => {
47299
47380
  if (state.uiServer) {
47300
47381
  state.uiServer.close("runtime_owner_stopped");
@@ -47311,7 +47392,7 @@ async function initializeMcp(pi, ctx, owner = createMcpRuntimeOwner(), options =
47311
47392
  return state;
47312
47393
  }
47313
47394
  const idleSetting = typeof config.settings?.idleTimeout === "number" ? config.settings.idleTimeout : 10;
47314
- lifecycle.setGlobalIdleTimeout(idleSetting);
47395
+ lifecycle2.setGlobalIdleTimeout(idleSetting);
47315
47396
  const cachePath = getMetadataCachePath();
47316
47397
  const cacheFileExists = existsSync12(cachePath);
47317
47398
  let cache2 = loadMetadataCache();
@@ -47329,13 +47410,13 @@ async function initializeMcp(pi, ctx, owner = createMcpRuntimeOwner(), options =
47329
47410
  const lifecycleMode = definition.lifecycle ?? "lazy";
47330
47411
  const persistsAfterFirstSpawn = lifecycleMode === "eager" || lifecycleMode === "lazy-keep-alive";
47331
47412
  const idleOverride = definition.idleTimeout ?? (persistsAfterFirstSpawn ? 0 : void 0);
47332
- lifecycle.registerServer(
47413
+ lifecycle2.registerServer(
47333
47414
  name,
47334
47415
  definition,
47335
47416
  idleOverride !== void 0 ? { idleTimeout: idleOverride } : void 0
47336
47417
  );
47337
47418
  if (lifecycleMode === "keep-alive") {
47338
- lifecycle.markKeepAlive(name, definition);
47419
+ lifecycle2.markKeepAlive(name, definition);
47339
47420
  }
47340
47421
  const cachedEntry = cache2?.servers?.[name];
47341
47422
  if (cachedEntry && isServerCacheValid(cachedEntry, definition)) {
@@ -47495,7 +47576,7 @@ async function initializeMcp(pi, ctx, owner = createMcpRuntimeOwner(), options =
47495
47576
  }
47496
47577
  }
47497
47578
  }
47498
- lifecycle.setReconnectCallback((serverName) => {
47579
+ lifecycle2.setReconnectCallback((serverName) => {
47499
47580
  if (!owner.isActive()) return;
47500
47581
  updateServerMetadata(state, serverName);
47501
47582
  updateMetadataCache(state, serverName);
@@ -47503,30 +47584,30 @@ async function initializeMcp(pi, ctx, owner = createMcpRuntimeOwner(), options =
47503
47584
  if (!restored) notifyToolMetadataUpdated(state, serverName, "lifecycle-reconnect");
47504
47585
  updateStatusBar(state);
47505
47586
  });
47506
- lifecycle.setReconnectFailureCallback((serverName, error) => {
47587
+ lifecycle2.setReconnectFailureCallback((serverName, error) => {
47507
47588
  if (!owner.isActive()) return;
47508
47589
  const message = error instanceof Error ? error.message : String(error);
47509
47590
  recordFailure(state, serverName, message);
47510
47591
  updateStatusBar(state);
47511
47592
  });
47512
- lifecycle.setHealthRestoredCallback((serverName) => {
47593
+ lifecycle2.setHealthRestoredCallback((serverName) => {
47513
47594
  if (!owner.isActive()) return;
47514
47595
  clearFailure(state, serverName, "health-restored");
47515
47596
  updateStatusBar(state);
47516
47597
  });
47517
- lifecycle.setAuthRequiredCallback((serverName) => {
47598
+ lifecycle2.setAuthRequiredCallback((serverName) => {
47518
47599
  if (!owner.isActive()) return;
47519
47600
  clearFailure(state, serverName, "auth-required");
47520
47601
  updateStatusBar(state);
47521
47602
  });
47522
- lifecycle.setIdleShutdownCallback((serverName) => {
47603
+ lifecycle2.setIdleShutdownCallback((serverName) => {
47523
47604
  if (!owner.isActive()) return;
47524
47605
  const idleMinutes = getEffectiveIdleTimeoutMinutes(state, serverName);
47525
47606
  logger.debug(`${serverName} shut down (idle ${idleMinutes}m)`);
47526
47607
  updateStatusBar(state);
47527
47608
  });
47528
47609
  owner.throwIfInactive();
47529
- lifecycle.startHealthChecks(runtimeSignal);
47610
+ lifecycle2.startHealthChecks(runtimeSignal);
47530
47611
  if (config.settings?.mcpFooterStatus === "off") {
47531
47612
  ui?.setStatus("mcp", void 0);
47532
47613
  }
@@ -47704,7 +47785,7 @@ function getEffectiveIdleTimeoutMinutes(state, serverName) {
47704
47785
  }
47705
47786
 
47706
47787
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/onboarding-state.ts
47707
- import { existsSync as existsSync13, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync2, renameSync as renameSync2 } from "fs";
47788
+ import { existsSync as existsSync13, mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync3, renameSync as renameSync2 } from "fs";
47708
47789
  import { dirname as dirname13 } from "path";
47709
47790
  var DEFAULT_STATE2 = {
47710
47791
  version: 1,
@@ -47718,7 +47799,7 @@ function loadOnboardingState() {
47718
47799
  const path7 = getOnboardingStatePath();
47719
47800
  if (!existsSync13(path7)) return { ...DEFAULT_STATE2 };
47720
47801
  try {
47721
- const raw = JSON.parse(readFileSync5(path7, "utf-8"));
47802
+ const raw = JSON.parse(readFileSync6(path7, "utf-8"));
47722
47803
  if (!raw || typeof raw !== "object") return { ...DEFAULT_STATE2 };
47723
47804
  return {
47724
47805
  version: 1,
@@ -47734,7 +47815,7 @@ function saveOnboardingState(state) {
47734
47815
  const path7 = getOnboardingStatePath();
47735
47816
  mkdirSync3(dirname13(path7), { recursive: true });
47736
47817
  const tmpPath = `${path7}.${process.pid}.tmp`;
47737
- writeFileSync2(tmpPath, `${JSON.stringify(state, null, 2)}
47818
+ writeFileSync3(tmpPath, `${JSON.stringify(state, null, 2)}
47738
47819
  `, "utf-8");
47739
47820
  renameSync2(tmpPath, path7);
47740
47821
  }
@@ -48357,7 +48438,7 @@ async function openMcpAuthPanel(state, pi, ctx, configOverridePath) {
48357
48438
  }
48358
48439
 
48359
48440
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/tool-registrar.ts
48360
- import { mkdtempSync, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
48441
+ import { mkdtempSync, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
48361
48442
  import { tmpdir } from "os";
48362
48443
  import { join as join25 } from "path";
48363
48444
  var MAX_BINARY_RESOURCE_BYTES = 10 * 1024 * 1024;
@@ -48415,7 +48496,7 @@ function drainPendingCleanupDirectories() {
48415
48496
  const failures = [];
48416
48497
  for (const directory of Array.from(pendingCleanupDirectories)) {
48417
48498
  try {
48418
- rmSync2(directory, { recursive: true, force: true });
48499
+ rmSync3(directory, { recursive: true, force: true });
48419
48500
  pendingCleanupDirectories.delete(directory);
48420
48501
  cleanupRetryAttempts.delete(directory);
48421
48502
  } catch (error) {
@@ -48474,10 +48555,10 @@ function materializeBinaryResource(resource, scope) {
48474
48555
  session.bytes += decodedBytes;
48475
48556
  session.files += 1;
48476
48557
  try {
48477
- writeFileSync3(filePath, Buffer.from(resource.blob, "base64"), { flag: "wx", mode: 384 });
48558
+ writeFileSync4(filePath, Buffer.from(resource.blob, "base64"), { flag: "wx", mode: 384 });
48478
48559
  } catch {
48479
48560
  try {
48480
- rmSync2(filePath, { force: true });
48561
+ rmSync3(filePath, { force: true });
48481
48562
  session.bytes -= decodedBytes;
48482
48563
  session.files -= 1;
48483
48564
  } catch {
@@ -58746,7 +58827,7 @@ import {
58746
58827
  rename as rename3,
58747
58828
  unlink as unlink3
58748
58829
  } from "fs/promises";
58749
- import { existsSync as existsSync15, readFileSync as readFileSync6, readdirSync as readdirSync3 } from "fs";
58830
+ import { existsSync as existsSync15, readFileSync as readFileSync7, readdirSync as readdirSync3 } from "fs";
58750
58831
  import { join as join29 } from "path";
58751
58832
  var MAX_FAILED_RECORDS = 500;
58752
58833
  var FLUSH_DEBOUNCE_MS = 15e3;
@@ -58797,7 +58878,7 @@ var AnalyticsRecordBuffer = class {
58797
58878
  if (!existsSync15(ENGINE_DIR2)) return [];
58798
58879
  return readdirSync3(ENGINE_DIR2, { withFileTypes: true }).filter((entry) => entry.isFile() && this.storageNames.some(
58799
58880
  (storageName) => entry.name === `${storageName}.jsonl` || entry.name.startsWith(`${storageName}.`) && (entry.name.endsWith(".jsonl") || entry.name.endsWith(`.jsonl${UPLOADED_SUFFIX}`))
58800
- )).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync6(join29(ENGINE_DIR2, name), "utf-8"))).map((record3) => {
58881
+ )).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync7(join29(ENGINE_DIR2, name), "utf-8"))).map((record3) => {
58801
58882
  const recordId = this.options.getRecordId?.(record3);
58802
58883
  if (recordId) this.recordIds.add(recordId);
58803
58884
  return record3;
@@ -59626,6 +59707,10 @@ var KeepAliveService = class _KeepAliveService {
59626
59707
  setActivityCheck(check) {
59627
59708
  this.activityCheck = check;
59628
59709
  }
59710
+ stop() {
59711
+ if (this.interval) clearInterval(this.interval);
59712
+ this.interval = null;
59713
+ }
59629
59714
  noteActivity() {
59630
59715
  this.lastActivityMs = Date.now();
59631
59716
  if (this.interval) return;
@@ -61716,10 +61801,10 @@ import { extname as extname3 } from "path";
61716
61801
 
61717
61802
  // src/services/language-server-service.ts
61718
61803
  import { spawn as spawn6 } from "child_process";
61719
- import { existsSync as existsSync16, readFileSync as readFileSync7 } from "fs";
61804
+ import { existsSync as existsSync16, readFileSync as readFileSync8 } from "fs";
61720
61805
  import { createRequire as createRequire5 } from "module";
61721
61806
  import { delimiter as delimiter2, dirname as dirname17, join as join36, relative as relative2 } from "path";
61722
- import { setTimeout as setTimeout2 } from "timers/promises";
61807
+ import { setTimeout as setTimeout3 } from "timers/promises";
61723
61808
  import { fileURLToPath as fileURLToPath5, pathToFileURL } from "url";
61724
61809
  import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node.js";
61725
61810
  var require5 = createRequire5(import.meta.url);
@@ -61756,7 +61841,7 @@ var LANGUAGE_SERVERS = {
61756
61841
  };
61757
61842
  function packageBin(packageName, binName) {
61758
61843
  const packageJsonPath = require5.resolve(`${packageName}/package.json`);
61759
- const packageJson = JSON.parse(readFileSync7(packageJsonPath, "utf8"));
61844
+ const packageJson = JSON.parse(readFileSync8(packageJsonPath, "utf8"));
61760
61845
  const bin = typeof packageJson.bin === "string" ? packageJson.bin : packageJson.bin[binName];
61761
61846
  if (!bin) throw new Error(`Missing ${binName} binary`);
61762
61847
  return `${dirname17(packageJsonPath)}/${bin}`;
@@ -61816,7 +61901,7 @@ var LanguageServerClient = class {
61816
61901
  request(method, params) {
61817
61902
  return Promise.race([
61818
61903
  this.connection.sendRequest(method, params),
61819
- setTimeout2(SERVER_TIMEOUT_MS, void 0, { ref: false }).then(() => {
61904
+ setTimeout3(SERVER_TIMEOUT_MS, void 0, { ref: false }).then(() => {
61820
61905
  throw new Error(`Language server timed out: ${method}`);
61821
61906
  })
61822
61907
  ]);
@@ -61860,7 +61945,7 @@ var LanguageServerService = class {
61860
61945
  const absolutePath = fileURLToPath5(uri);
61861
61946
  const path7 = relative2(repoPath, absolutePath);
61862
61947
  if (path7.startsWith("..")) return [];
61863
- const preview = readFileSync7(absolutePath, "utf8").split("\n")[range.start.line]?.trim() ?? "";
61948
+ const preview = readFileSync8(absolutePath, "utf8").split("\n")[range.start.line]?.trim() ?? "";
61864
61949
  return [{ repoName, path: path7, line: range.start.line + 1, character: range.start.character, endCharacter: range.end.character, preview }];
61865
61950
  });
61866
61951
  return { symbol: "", detail: null, documentation: null, locations, provider: "language-server" };
@@ -63733,7 +63818,7 @@ var HeartbeatService = class _HeartbeatService {
63733
63818
  static HEARTBEAT_INTERVAL_MS = 15e3;
63734
63819
  static REQUEST_TIMEOUT_MS = 5e3;
63735
63820
  start(bootTimeMs2) {
63736
- if (IS_WARMING_MODE || !ENGINE_ENV.REPLICAS_WORKSPACE_ID || this.interval) return;
63821
+ if (!ENGINE_ENV.REPLICAS_WORKSPACE_ID || this.interval) return;
63737
63822
  this.bootTimeMs = bootTimeMs2;
63738
63823
  void this.ping();
63739
63824
  this.interval = setInterval(() => {
@@ -63741,6 +63826,10 @@ var HeartbeatService = class _HeartbeatService {
63741
63826
  }, _HeartbeatService.HEARTBEAT_INTERVAL_MS);
63742
63827
  unrefTimer(this.interval);
63743
63828
  }
63829
+ stop() {
63830
+ if (this.interval) clearInterval(this.interval);
63831
+ this.interval = null;
63832
+ }
63744
63833
  async ping() {
63745
63834
  if (this.inFlight || !this.bootTimeMs) return;
63746
63835
  this.inFlight = true;
@@ -63789,12 +63878,8 @@ async function installWorkspaceSdk() {
63789
63878
  // src/index.ts
63790
63879
  var startupStartedAt = performance.now();
63791
63880
  var startupTimings = {};
63792
- var ENGINE_INIT_GATE_TIMEOUT_MS = 35 * 60 * 1e3;
63793
- var resolveEngineReady = () => {
63794
- };
63795
- var engineReadyPromise = new Promise((resolve8) => {
63796
- resolveEngineReady = resolve8;
63797
- });
63881
+ var START_PARKED = process.argv.includes("--parked") || process.argv.includes("--warming");
63882
+ var PARKED_PATH_PREFIXES = ["/warm-hooks/", "/start-hooks/", "/environment/track"];
63798
63883
  async function timeStartupStep(name, fn) {
63799
63884
  const startedAt = performance.now();
63800
63885
  try {
@@ -63806,16 +63891,6 @@ async function timeStartupStep(name, fn) {
63806
63891
  };
63807
63892
  }
63808
63893
  }
63809
- async function waitForInitializationGate() {
63810
- if (!ENGINE_ENV.REPLICAS_ENGINE_DEFER_INITIALIZATION) return;
63811
- const deadline = Date.now() + ENGINE_INIT_GATE_TIMEOUT_MS;
63812
- while (!existsSync19(SANDBOX_PATHS.ENGINE_INIT_GATE)) {
63813
- if (Date.now() >= deadline) {
63814
- throw new Error("Timed out waiting for deferred engine initialization gate");
63815
- }
63816
- await new Promise((resolve8) => setTimeout(resolve8, 25));
63817
- }
63818
- }
63819
63894
  await timeStartupStep("engine_logger_initialize", () => engineLogger.initialize());
63820
63895
  process.on("uncaughtException", (error) => {
63821
63896
  console.error("[FATAL] Uncaught exception:", error);
@@ -63858,18 +63933,18 @@ function checkDesktopReady() {
63858
63933
  }
63859
63934
  var app = new Hono2();
63860
63935
  var bootTimeMs = Date.now();
63861
- var engineReady = false;
63862
63936
  var authMiddleware = async (c, next) => {
63863
63937
  const secret = c.req.header("X-Replicas-Engine-Secret");
63864
- const expectedSecret = ENGINE_ENV.REPLICAS_ENGINE_SECRET;
63865
63938
  if (!secret) {
63866
63939
  return c.json({ error: "Unauthorized: X-Replicas-Engine-Secret header required" }, 401);
63867
63940
  }
63868
- if (secret !== expectedSecret) {
63941
+ const activating = c.req.path === ENGINE_ACTIVATE_PATH;
63942
+ const accepted = secret === ENGINE_ENV.REPLICAS_ENGINE_SECRET || activating && lifecycle.state === "parked" && secret === readRuntimeEnvFile()?.REPLICAS_ENGINE_SECRET;
63943
+ if (!accepted) {
63869
63944
  return c.json({ error: "Unauthorized: Invalid secret" }, 401);
63870
63945
  }
63871
- if (!engineReady) {
63872
- return c.json({ error: "Engine is initializing" }, 503);
63946
+ if (!lifecycle.active && !activating && c.req.path !== ENGINE_SLEEP_PATH && !PARKED_PATH_PREFIXES.some((prefix) => c.req.path.startsWith(prefix))) {
63947
+ return c.json({ error: `Engine is ${lifecycle.state}` }, 503);
63873
63948
  }
63874
63949
  await next();
63875
63950
  };
@@ -63883,27 +63958,29 @@ var chatService = new ChatService(
63883
63958
  app.get("/health", async (c) => {
63884
63959
  const requestedWaitMs = Number(c.req.query(ENGINE_HEALTH_WAIT_QUERY_PARAM));
63885
63960
  const waitMs = Number.isFinite(requestedWaitMs) ? Math.min(Math.max(requestedWaitMs, 0), ENGINE_HEALTH_MAX_WAIT_MS) : 0;
63886
- if (!engineReady && waitMs > 0) {
63887
- await Promise.race([
63888
- engineReadyPromise,
63889
- new Promise((resolve8) => setTimeout(resolve8, waitMs))
63890
- ]);
63961
+ if (!lifecycle.active && waitMs > 0) {
63962
+ await lifecycle.waitForActive(waitMs);
63891
63963
  }
63892
63964
  c.header(ENGINE_HEALTH_WAIT_HEADER, "1");
63893
63965
  const response = {
63894
- status: engineReady ? "active" : "initializing",
63966
+ status: lifecycle.active ? "active" : "initializing",
63967
+ state: lifecycle.state,
63895
63968
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
63896
63969
  startup: {
63897
63970
  elapsedMs: performance.now() - startupStartedAt,
63898
63971
  steps: startupTimings
63899
63972
  }
63900
63973
  };
63901
- if (!engineReady) {
63902
- return c.json(response, 503);
63903
- }
63904
- return c.json(response);
63974
+ return c.json(response, lifecycle.active ? 200 : 503);
63905
63975
  });
63906
63976
  app.use("*", authMiddleware);
63977
+ var lifecycleResponse = (c, result) => result.ok ? c.json(result.data) : c.json({ error: result.error.message }, result.error.code);
63978
+ app.post(ENGINE_ACTIVATE_PATH, async (c) => {
63979
+ const body = await c.req.json().catch(() => null);
63980
+ const workspaceId = isRecord(body) && typeof body.workspaceId === "string" ? body.workspaceId : void 0;
63981
+ return lifecycleResponse(c, await lifecycle.transition(() => activate(workspaceId === void 0 ? void 0 : { workspaceId })));
63982
+ });
63983
+ app.post(ENGINE_SLEEP_PATH, async (c) => lifecycleResponse(c, await lifecycle.transition(sleep2)));
63907
63984
  app.get("/status", async (c) => {
63908
63985
  try {
63909
63986
  const [repos, hasActiveSSHSessions, desktopReady] = await Promise.all([
@@ -63961,14 +64038,23 @@ app.post(GITLAB_CREDENTIAL_REFRESH_PATH, async (c) => {
63961
64038
  var repoFileService = new RepoFileService(gitService);
63962
64039
  app.route("/", createV1Routes({ chatService, repoFileService, canvasService }));
63963
64040
  var port = ENGINE_ENV.REPLICAS_ENGINE_PORT;
64041
+ var broadcastTimer = null;
64042
+ var broadcastGeneration = 0;
64043
+ function stopStatusBroadcaster() {
64044
+ broadcastGeneration += 1;
64045
+ if (broadcastTimer) clearTimeout(broadcastTimer);
64046
+ broadcastTimer = null;
64047
+ }
63964
64048
  function startStatusBroadcaster() {
64049
+ if (broadcastTimer) return;
64050
+ const generation = broadcastGeneration;
63965
64051
  let previousRepoStatus = "";
63966
64052
  let previousHookStatus = "";
63967
64053
  let previousEngineStatus = "";
63968
64054
  let lastHooksRunning = replicasConfigService.areHooksRunning();
63969
64055
  const BROADCAST_INTERVAL_MS = 2e3;
63970
64056
  const scheduleNext = () => {
63971
- setTimeout(tick, BROADCAST_INTERVAL_MS);
64057
+ if (generation === broadcastGeneration) broadcastTimer = setTimeout(tick, BROADCAST_INTERVAL_MS);
63972
64058
  };
63973
64059
  const tick = async () => {
63974
64060
  try {
@@ -63977,6 +64063,7 @@ function startStatusBroadcaster() {
63977
64063
  checkActiveSSHSessions(),
63978
64064
  checkDesktopReady()
63979
64065
  ]);
64066
+ if (generation !== broadcastGeneration) return;
63980
64067
  const serialized = JSON.stringify(repos);
63981
64068
  if (serialized !== previousRepoStatus) {
63982
64069
  previousRepoStatus = serialized;
@@ -64072,7 +64159,98 @@ function startStatusBroadcaster() {
64072
64159
  scheduleNext();
64073
64160
  }
64074
64161
  };
64075
- scheduleNext();
64162
+ broadcastTimer = setTimeout(tick, BROADCAST_INTERVAL_MS);
64163
+ }
64164
+ var engineBooted = Promise.withResolvers();
64165
+ var tokenManagers = [githubTokenManager, gitlabTokenManager, claudeTokenManager, codexTokenManager, infisicalTokenManager];
64166
+ var backgroundController;
64167
+ var backgroundServices;
64168
+ var identityProxyStarted = false;
64169
+ async function stopWorkspaceServices() {
64170
+ backgroundController?.abort();
64171
+ stopStatusBroadcaster();
64172
+ heartbeatService.stop();
64173
+ keepAliveService.stop();
64174
+ await backgroundServices;
64175
+ await Promise.all(tokenManagers.map((manager) => manager.stop()));
64176
+ }
64177
+ async function activate(requested) {
64178
+ await engineBooted.promise;
64179
+ const values = readRuntimeEnvFile();
64180
+ const workspaceId = values && readReplicasRuntimeEnv((name) => values[name], REPLICAS_RUNTIME_ENV_ALIASES.workspaceId);
64181
+ if (!values || !workspaceId) {
64182
+ return createErrorResult({ message: "Settings file has no workspace id", code: 400 });
64183
+ }
64184
+ if (requested && requested.workspaceId !== workspaceId) {
64185
+ return createErrorResult({ message: `Settings file names workspace ${workspaceId}, not ${requested.workspaceId}`, code: 409 });
64186
+ }
64187
+ if (lifecycle.workspaceId && lifecycle.workspaceId !== workspaceId) {
64188
+ return createErrorResult({ message: `Engine already belongs to workspace ${lifecycle.workspaceId}`, code: 409 });
64189
+ }
64190
+ lifecycle.claim(workspaceId);
64191
+ await stopWorkspaceServices();
64192
+ reloadEngineEnv(values);
64193
+ startupStartedAt = performance.now();
64194
+ if (!replicasConfigService.areHooksRunning()) {
64195
+ await timeStartupStep("replicas_config_initialize", () => replicasConfigService.initialize());
64196
+ }
64197
+ await timeStartupStep(
64198
+ "git_credential_helper_initialize",
64199
+ () => configureManagedGitCredentialHelper(ENGINE_ENV.HOME_DIR)
64200
+ );
64201
+ await Promise.all([
64202
+ timeStartupStep("github_token_initialize", () => githubTokenManager.start()),
64203
+ // A parked or paused engine started before the hooks that added tools to the login profile.
64204
+ timeStartupStep("login_path_reload", async () => {
64205
+ const { stdout } = await execAsync(`bash -lc 'printf "\\n%s" "$PATH"'`, { timeout: 1e4 }).catch(() => ({ stdout: "" }));
64206
+ const loginPath = stdout.split("\n").pop() ?? "";
64207
+ process.env.PATH = [...new Set([...loginPath.split(":"), ...(process.env.PATH ?? "").split(":")].filter(Boolean))].join(":");
64208
+ })
64209
+ ]);
64210
+ lifecycle.set("active");
64211
+ backgroundController = new AbortController();
64212
+ const signal = backgroundController.signal;
64213
+ backgroundServices = Promise.allSettled([
64214
+ registerDesktopPreview(signal),
64215
+ startBackgroundServices(signal)
64216
+ ]).then((results) => {
64217
+ for (const result of results) {
64218
+ if (!signal.aborted && result.status === "rejected") console.error("Engine background startup failed:", result.reason);
64219
+ }
64220
+ });
64221
+ return createSuccessResult({ state: lifecycle.state, workspaceId });
64222
+ }
64223
+ async function startBackgroundServices(signal) {
64224
+ heartbeatService.start(bootTimeMs);
64225
+ if (!identityProxyStarted) {
64226
+ identityProxyStarted = true;
64227
+ createIdentityProxy(workspaceIdentityTokens).on("error", (error) => console.error("[identity-proxy] failed to listen:", error)).listen(IDENTITY_PROXY_PORT, "127.0.0.1");
64228
+ }
64229
+ for (const manager of tokenManagers.slice(1)) {
64230
+ if (signal.aborted) return;
64231
+ await manager.start();
64232
+ }
64233
+ if (signal.aborted) return;
64234
+ const repos = await gitService.listRepos();
64235
+ for (const event of [
64236
+ { type: "repo.discovered", payload: { repos } },
64237
+ { type: "repo.status.changed", payload: { repos } },
64238
+ { type: "engine.ready", payload: { version: "v1" } }
64239
+ ]) {
64240
+ if (signal.aborted) return;
64241
+ await eventService.publish({ id: randomUUID13(), ts: (/* @__PURE__ */ new Date()).toISOString(), ...event });
64242
+ }
64243
+ if (!signal.aborted) startStatusBroadcaster();
64244
+ }
64245
+ async function sleep2() {
64246
+ if (lifecycle.state === "parked") {
64247
+ return createErrorResult({ message: "A parked engine has no workspace to sleep", code: 409 });
64248
+ }
64249
+ lifecycle.set("sleeping");
64250
+ lifecycle.releaseClaim();
64251
+ await stopWorkspaceServices();
64252
+ await engineLogger.flush();
64253
+ return createSuccessResult({ state: lifecycle.state, workspaceId: lifecycle.workspaceId });
64076
64254
  }
64077
64255
  serve(
64078
64256
  {
@@ -64080,57 +64258,17 @@ serve(
64080
64258
  port
64081
64259
  },
64082
64260
  async (info) => {
64083
- if (IS_WARMING_MODE) {
64084
- console.log(`Replicas Engine running on port ${info.port} (warming mode)`);
64085
- } else {
64086
- console.log(`Replicas Engine running on port ${info.port}`);
64087
- }
64088
- await timeStartupStep("wait_for_initialization_gate", waitForInitializationGate);
64261
+ console.log(`Replicas Engine running on port ${info.port}${START_PARKED ? " (parked)" : ""}`);
64089
64262
  await timeStartupStep("workspace_sdk_install", installWorkspaceSdk);
64090
- if (!IS_WARMING_MODE) {
64091
- await timeStartupStep("replicas_config_initialize", () => replicasConfigService.initialize());
64092
- }
64093
64263
  await timeStartupStep("chat_initialize", () => chatService.initialize());
64094
64264
  await timeStartupStep("preview_initialize", () => previewService.initialize());
64095
- if (!IS_WARMING_MODE) {
64096
- await timeStartupStep(
64097
- "git_credential_helper_initialize",
64098
- () => configureManagedGitCredentialHelper(ENGINE_ENV.HOME_DIR)
64099
- );
64100
- await timeStartupStep("github_token_initialize", () => githubTokenManager.start());
64101
- }
64102
- engineReady = true;
64103
- resolveEngineReady();
64104
- void registerDesktopPreview();
64105
- heartbeatService.start(bootTimeMs);
64106
- if (!IS_WARMING_MODE) {
64107
- await gitlabTokenManager.start();
64108
- await claudeTokenManager.start();
64109
- await codexTokenManager.start();
64110
- await infisicalTokenManager.start();
64111
- createIdentityProxy(workspaceIdentityTokens).on("error", (error) => console.error("[identity-proxy] failed to listen:", error)).listen(IDENTITY_PROXY_PORT, "127.0.0.1");
64112
- }
64113
- const repos = await gitService.listRepos();
64114
- await eventService.publish({
64115
- id: randomUUID13(),
64116
- ts: (/* @__PURE__ */ new Date()).toISOString(),
64117
- type: "repo.discovered",
64118
- payload: { repos }
64119
- });
64120
- const repoStatuses = await gitService.listRepos();
64121
- await eventService.publish({
64122
- id: randomUUID13(),
64123
- ts: (/* @__PURE__ */ new Date()).toISOString(),
64124
- type: "repo.status.changed",
64125
- payload: { repos: repoStatuses }
64126
- });
64127
- await eventService.publish({
64128
- id: randomUUID13(),
64129
- ts: (/* @__PURE__ */ new Date()).toISOString(),
64130
- type: "engine.ready",
64131
- payload: { version: "v1" }
64132
- });
64133
- startStatusBroadcaster();
64265
+ engineBooted.resolve();
64266
+ const claimedWorkspaceId = START_PARKED ? lifecycle.claimedWorkspaceId : null;
64267
+ if (START_PARKED && !claimedWorkspaceId) return;
64268
+ const result = await lifecycle.transition(() => activate(claimedWorkspaceId ? { workspaceId: claimedWorkspaceId } : void 0));
64269
+ if (!result.ok) {
64270
+ console.error(`Engine stays parked: ${result.error.message}`);
64271
+ }
64134
64272
  }
64135
64273
  );
64136
64274
  /*! Bundled license information: