Files
wehub-resource-sync 426e9eeabd
Voice Workbench / headless workbench (mocked backends) (push) Has been cancelled
Voice Workbench / real acoustic lane (nightly, provisioned only) (push) Has been cancelled
ci / test (push) Has been cancelled
ci / lint-and-format (push) Has been cancelled
ci / build (push) Has been cancelled
ci / dev-startup (push) Has been cancelled
gitleaks / gitleaks (push) Has been cancelled
Markdown Links / Relative Markdown Links (push) Has been cancelled
Quality (Extended) / Homepage Build (PR smoke) (push) Has been cancelled
Quality (Extended) / Comment-only diff guard (push) Has been cancelled
Quality (Extended) / Format + Type Safety Ratchet (push) Has been cancelled
Quality (Extended) / Develop Gate (secret scan + UI determinism) (push) Has been cancelled
Quality (Extended) / Develop Gate (lint) (push) Has been cancelled
Chat shell gestures / Chat shell gesture + parity e2e (push) Has been cancelled
Cloud Gateway Discord / Test (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx @biomejs/biome check packages/lifeops-bench/src, benchmark-lint) (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx vitest run --config packages/lifeops-bench/vitest.config.ts --root packages/lifeops-bench --passWithNoTests, benchmark-tests) (push) Has been cancelled
Build Agent Image / build-and-push (push) Has been cancelled
Dev Smoke / bun run dev onboarding chat (push) Has been cancelled
Dev Smoke / Vite HMR dependency-level smoke (push) Has been cancelled
Electrobun Submodule Guard / electrobun gitlink is fetchable (push) Has been cancelled
Publish @elizaos/example-code / check_npm (push) Has been cancelled
Publish @elizaos/example-code / publish_npm (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / verify_version (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / publish_npm (push) Has been cancelled
Sandbox Live Smoke / Sandbox live smoke (push) Has been cancelled
Snap Build & Test / Build Snap (amd64) (push) Has been cancelled
Snap Build & Test / Build Snap (arm64) (push) Has been cancelled
Test Packaging / elizaos CLI global-install smoke (node + bun) (push) Has been cancelled
Cloud Gateway Webhook / Test (push) Has been cancelled
Cloud Tests / lint-and-types (push) Has been cancelled
Cloud Tests / unit-tests (push) Has been cancelled
Cloud Tests / integration-tests (push) Has been cancelled
Cloud Tests / e2e-tests (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Apps Worker (Product 2) / Determine environment (push) Has been cancelled
Deploy Apps Worker (Product 2) / Deploy apps worker to apps-control host (${{ needs.determine-env.outputs.environment }}) (push) Has been cancelled
Deploy Eliza Provisioning Worker / Determine environment (push) Has been cancelled
Deploy Eliza Provisioning Worker / Deploy worker to Hetzner host (${{ needs.determine-env.outputs.environment }} @ ${{ needs.determine-env.outputs.deployment_sha }}) (push) Has been cancelled
Dev Smoke / Classify changed paths (push) Has been cancelled
supply-chain / sbom (push) Has been cancelled
supply-chain / vulnerability-scan (push) Has been cancelled
Build, Push & Deploy to Phala Cloud / build-and-push (push) Has been cancelled
Test Packaging / Validate Packaging Configs (push) Has been cancelled
Test Packaging / Build & Test PyPI Package (push) Has been cancelled
Test Packaging / PyPI on Python ${{ matrix.python }} (push) Has been cancelled
Test Packaging / Pack & Test JS Tarballs (push) Has been cancelled
UI Fixture E2E / ui-fixture-e2e (push) Has been cancelled
UI Fixture E2E / fixture-e2e (push) Has been cancelled
UI Story Gate / story-gate (push) Has been cancelled
vault-ci / test (macos-latest) (push) Has been cancelled
vault-ci / test (ubuntu-latest) (push) Has been cancelled
vault-ci / test (windows-latest) (push) Has been cancelled
vault-ci / app-core wiring tests (push) Has been cancelled
verify-patches / verify patches/CHECKSUMS.sha256 (push) Has been cancelled
Voice Benchmark Smoke / voice-emotion fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voiceagentbench fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench-quality unit smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench TypeScript unit (no audio) (push) Has been cancelled
Voice Benchmark Smoke / voice bench smoke summary (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/app-core test bun run --cwd packages/elizaos test bun run --cwd packages/cloud/shared test], app-and-cli) (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/scenario-runner test bun run --cwd packages/vault test bun run --cwd packages/security test bun run --cwd plugins/plugin-coding-tools test], framework-packages) (push) Has been cancelled
Windows CI / windows ([bun run --cwd plugins/plugin-elizacloud test bun run --cwd plugins/plugin-discord test bun run --cwd plugins/plugin-anthropic test bun run --cwd plugins/plugin-openai test bun run --cwd plugins/plugin-app-control test bun run --cwd plugins/pl… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run build --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/agent --concurrency=4 node packages/scripts/run-bash-linux-only.mjs scripts/verify-riscv64-buildpaths.sh node packages/scripts/run… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run typecheck --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/cloud-shared --concurrency=4 bun run --cwd packages/core test bun run --cwd packages/shared test], core-runtime, 75) (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:43:05 +08:00

278 lines
7.4 KiB
JavaScript

#!/usr/bin/env node
import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
export const DEFAULT_UI_PORT_BASE = 2100;
export const DEFAULT_UI_PORT_SPAN = 900;
export const DEFAULT_API_PORT_OFFSET = 10_000;
export const REGISTRY_VERSION = 1;
export function defaultRegistryPath(env = process.env) {
return (
env.ELIZA_DEV_SERVER_REGISTRY ??
path.join(os.homedir(), ".eliza", "dev-server-registry.json")
);
}
export function normalizeWorktreePath(worktreePath) {
return path.resolve(worktreePath).replace(/\\/g, "/");
}
export function hashString(input) {
let hash = 0x811c9dc5;
for (let i = 0; i < input.length; i += 1) {
hash ^= input.charCodeAt(i);
hash = Math.imul(hash, 0x01000193) >>> 0;
}
return hash >>> 0;
}
export function preferredUiPortForWorktree(
worktreePath,
{ base = DEFAULT_UI_PORT_BASE, span = DEFAULT_UI_PORT_SPAN } = {},
) {
return base + (hashString(normalizeWorktreePath(worktreePath)) % span);
}
export function portsForUiPort(uiPort) {
return {
uiPort,
apiPort: uiPort + DEFAULT_API_PORT_OFFSET,
};
}
export function createEmptyRegistry() {
return { version: REGISTRY_VERSION, entries: [] };
}
export function readRegistry(registryPath = defaultRegistryPath()) {
try {
const parsed = JSON.parse(fs.readFileSync(registryPath, "utf8"));
if (
!parsed ||
typeof parsed !== "object" ||
!Array.isArray(parsed.entries)
) {
return createEmptyRegistry();
}
return {
version: REGISTRY_VERSION,
entries: parsed.entries.filter(
(entry) => entry && typeof entry === "object",
),
};
} catch (error) {
if (error && error.code === "ENOENT") return createEmptyRegistry();
throw error;
}
}
export function writeRegistry(registry, registryPath = defaultRegistryPath()) {
fs.mkdirSync(path.dirname(registryPath), { recursive: true });
const tmp = `${registryPath}.${process.pid}.tmp`;
fs.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}\n`);
fs.renameSync(tmp, registryPath);
}
export function isPidAlive(pid) {
if (!Number.isInteger(pid) || pid <= 0) return false;
try {
process.kill(pid, 0);
return true;
} catch (error) {
return error && error.code === "EPERM";
}
}
export async function isPortOpen(port, host = "127.0.0.1", timeoutMs = 250) {
return await new Promise((resolve) => {
const socket = net.createConnection({ host, port });
const done = (value) => {
socket.removeAllListeners();
socket.destroy();
resolve(value);
};
socket.setTimeout(timeoutMs);
socket.once("connect", () => done(true));
socket.once("timeout", () => done(false));
socket.once("error", () => done(false));
});
}
export async function getEntryRuntime(entry) {
const pidAlive = isPidAlive(entry.pid);
const portOpen = Number.isInteger(entry.uiPort)
? await isPortOpen(entry.uiPort)
: false;
return {
pidAlive,
portOpen,
running: pidAlive || portOpen,
};
}
export async function listRegistryEntries({
registryPath = defaultRegistryPath(),
includeStopped = false,
} = {}) {
const registry = readRegistry(registryPath);
const rows = [];
for (const entry of registry.entries) {
const runtime = await getEntryRuntime(entry);
if (!includeStopped && !runtime.running) continue;
rows.push({ ...entry, ...runtime });
}
rows.sort((a, b) => (a.uiPort ?? 0) - (b.uiPort ?? 0));
return rows;
}
function pruneDeadEntries(entries, currentWorktree) {
return entries.filter((entry) => {
if (entry.worktree === currentWorktree) return false;
if (entry.stoppedAt) return false;
if (entry.pid === null || entry.pid === undefined) return true;
return isPidAlive(entry.pid);
});
}
export function allocatePortsForWorktree(
worktreePath,
{
registry = createEmptyRegistry(),
base = DEFAULT_UI_PORT_BASE,
span = DEFAULT_UI_PORT_SPAN,
now = new Date().toISOString(),
blockedUiPorts = [],
} = {},
) {
const worktree = normalizeWorktreePath(worktreePath);
const preferredUiPort = preferredUiPortForWorktree(worktree, { base, span });
const entries = pruneDeadEntries(registry.entries ?? [], worktree);
const usedUiPorts = new Set([
...entries.map((entry) => entry.uiPort),
...blockedUiPorts,
]);
let uiPort = preferredUiPort;
let probeCount = 0;
while (usedUiPorts.has(uiPort) && probeCount < span) {
probeCount += 1;
uiPort = base + ((preferredUiPort - base + probeCount) % span);
}
if (probeCount >= span) {
throw new Error(
`No free deterministic UI ports in ${base}-${base + span - 1}`,
);
}
const ports = portsForUiPort(uiPort);
const entry = {
worktree,
packageDir: path.join(worktree, "packages", "app"),
uiPort: ports.uiPort,
apiPort: ports.apiPort,
preferredUiPort,
pid: null,
startedAt: null,
updatedAt: now,
lastRebuildAt: null,
};
return {
entry,
registry: { version: REGISTRY_VERSION, entries: [...entries, entry] },
};
}
export async function withRegistryLock(
callback,
{ registryPath = defaultRegistryPath(), staleMs = 30_000 } = {},
) {
const lockPath = `${registryPath}.lock`;
fs.mkdirSync(path.dirname(registryPath), { recursive: true });
const start = Date.now();
while (true) {
try {
fs.mkdirSync(lockPath);
fs.writeFileSync(path.join(lockPath, "pid"), String(process.pid));
break;
} catch (error) {
if (error && error.code !== "EEXIST") throw error;
let stale = false;
try {
const stat = fs.statSync(lockPath);
stale = Date.now() - stat.mtimeMs > staleMs;
} catch {
stale = true;
}
if (stale) {
fs.rmSync(lockPath, { recursive: true, force: true });
continue;
}
if (Date.now() - start > staleMs) {
throw new Error(`Timed out waiting for registry lock ${lockPath}`);
}
await new Promise((resolve) => setTimeout(resolve, 50));
}
}
try {
return await callback();
} finally {
fs.rmSync(lockPath, { recursive: true, force: true });
}
}
export async function reservePortsForWorktree(
worktreePath,
{ registryPath = defaultRegistryPath(), base, span } = {},
) {
return await withRegistryLock(
async () => {
const current = readRegistry(registryPath);
const blockedUiPorts = new Set();
while (true) {
const allocated = allocatePortsForWorktree(worktreePath, {
registry: current,
base,
span,
blockedUiPorts,
});
if (!(await isPortOpen(allocated.entry.uiPort))) {
writeRegistry(allocated.registry, registryPath);
return allocated.entry;
}
blockedUiPorts.add(allocated.entry.uiPort);
}
},
{ registryPath },
);
}
export async function updateRegistryEntry(
worktreePath,
patch,
{ registryPath = defaultRegistryPath() } = {},
) {
const worktree = normalizeWorktreePath(worktreePath);
return await withRegistryLock(
async () => {
const registry = readRegistry(registryPath);
const entries = registry.entries ?? [];
const index = entries.findIndex((entry) => entry.worktree === worktree);
if (index === -1) return null;
const updated = {
...entries[index],
...patch,
updatedAt: new Date().toISOString(),
};
entries[index] = updated;
writeRegistry({ version: REGISTRY_VERSION, entries }, registryPath);
return updated;
},
{ registryPath },
);
}