wishforge-ide/scripts/local-services.mjs
eust-w 13ceca5c8f
Some checks failed
CI / Format, types and tests (pull_request) Has been cancelled
CI / PostgreSQL migrations and integration tests (pull_request) Has been cancelled
🔀 Merge review/overhaul into feat/wiki-copilot-diagnostics
Brings the branch up to the current base (executor settings, project
skills, Chinese run messages, cloud IDE removal, wish attachments) and
resolves the ten conflicted files, keeping both sides:

- wish-refiner: the tenant's executor settings pick the models first,
  then the Copilot model setting; the tenant credential still goes
  before the operator's login
- worker providers: executor settings apply, and a run with its own
  credential still gets an empty home
- main.ts: Copilot screenshot uploads and wish attachments each keep
  their own body limit
- contracts, http, web types: default budget and skill auto-activation,
  Copilot and attachment entity kinds, ./text and ./attachments exports
- globals.css: Copilot styles and attachment styles, one after the other
- tests: the canceled-release reason is Chinese; the refiner's default
  models have no [1m] suffix, as this branch names them

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 00:39:05 +08:00

219 lines
8.0 KiB
JavaScript

// Starts local development processes, reuses ones that are already running and
// stops everything it started when one of them exits.
import { spawn } from 'node:child_process';
import { setTimeout as delay } from 'node:timers/promises';
/**
* Loads the private settings: .env.local on the operator's machine, or the file a container is
* given (WF_LOCAL_ENV_FILE), which holds only what that container's services need.
*/
export function loadLocalEnvironment(file = process.env.WF_LOCAL_ENV_FILE || '.env.local') {
try {
process.loadEnvFile(file);
} catch {
throw new Error(`${file} is missing; run npm run setup:local first`);
}
if (process.env.WF_DEPLOYMENT_MODE !== 'development')
throw new Error('Local services need WF_DEPLOYMENT_MODE=development in .env.local; run npm run setup:local');
}
const LOOPBACK = ['127.0.0.1', 'localhost', '::1'];
/**
* Where the web console listens, and the address its readiness is checked at. Only the production
* build may listen beyond loopback, and only with local sign-in: the development server hands any
* visitor its source maps and hot-reload channel.
*/
export function webListener(env = process.env) {
const host = env.WF_WEB_HOST || '127.0.0.1';
const port = Number(env.WF_WEB_PORT || 3000);
if (!Number.isSafeInteger(port) || port < 1 || port > 65535) throw new Error('WF_WEB_PORT must be a TCP port.');
if (!LOOPBACK.includes(host)) {
if (env.WF_LOCAL_ACCESS !== 'true')
throw new Error('A web listener beyond loopback requires local sign-in (WF_LOCAL_ACCESS=true).');
if (env.WF_WEB_SERVE_MODE !== 'production')
throw new Error(
'Only the production web build may listen beyond loopback: run npm run local:build and set WF_WEB_SERVE_MODE=production.',
);
}
// A wildcard listener answers on loopback; one bound to a single address only there.
const probe = ['0.0.0.0', '::'].includes(host) ? '127.0.0.1' : host.includes(':') ? `[${host}]` : host;
return { host, port, probe };
}
const inherited = () =>
Object.fromEntries(
// Proxy variables in both spellings: macOS proxy tools usually export the lowercase ones.
[
'PATH',
'HOME',
'TMPDIR',
'LANG',
'TERM',
'HTTP_PROXY',
'HTTPS_PROXY',
'NO_PROXY',
'http_proxy',
'https_proxy',
'no_proxy',
]
.filter(key => process.env[key])
.map(key => [key, process.env[key]]),
);
/**
* The ports of this machine's WishForge services, from their configured addresses: sandboxed host
* checks may never reach them, even when they may use loopback (WF_HOST_CHECK_BLOCKED_PORTS).
* Temporal's web interface (8233) is included; it can stop workflows like Temporal itself.
*/
export function platformPorts(env = process.env) {
const ports = new Set([8233, Number(env.WF_WEB_PORT || 3000), Number(env.WF_GIT_PORT || 4504)]);
const addresses = [
env.WF_API_URL,
env.WF_CONTROL_PLANE_URL,
env.DATABASE_URL,
env.S3_ENDPOINT,
env.WF_PROVISIONER_URL,
env.WF_GIT_SERVICE_URL,
env.TEMPORAL_ADDRESS && `grpc://${env.TEMPORAL_ADDRESS}`,
];
for (const address of addresses.filter(Boolean)) {
try {
const url = new URL(address.trim());
const port = Number(url.port || { 'http:': 80, 'https:': 443 }[url.protocol]);
if (port) ports.add(port);
} catch {
// Not an address; nothing to block.
}
}
for (const port of (env.WF_HOST_CHECK_BLOCKED_PORTS ?? '').split(',')) if (port.trim()) ports.add(Number(port));
return [...ports].filter(port => Number.isInteger(port) && port > 0 && port < 65536).sort((a, b) => a - b);
}
/**
* The services this process starts: all of them, or those WF_LOCAL_SERVICES names (separated by
* commas), where they run in separate containers of one Pod. An unknown name is an error.
*/
export function selectServices(services, env = process.env) {
const wanted = (env.WF_LOCAL_SERVICES ?? '')
.split(',')
.map(name => name.trim())
.filter(Boolean);
if (!wanted.length) return services;
const known = new Set(services.map(service => service.name));
const unknown = wanted.filter(name => !known.has(name));
if (unknown.length) throw new Error(`WF_LOCAL_SERVICES names unknown services: ${unknown.join(', ')}`);
return services.filter(service => wanted.includes(service.name));
}
/** Each process sees only the settings matching its patterns, plus the deployment mode. */
export function environment(patterns, extra = {}) {
return {
...inherited(),
...Object.fromEntries(Object.entries(process.env).filter(([key]) => patterns.some(pattern => pattern.test(key)))),
WF_DEPLOYMENT_MODE: 'development',
NODE_ENV: 'development',
...extra,
};
}
async function healthy(service) {
try {
const response = await fetch(service.url, { signal: AbortSignal.timeout(1000) });
if (!response.ok) return false;
if (!service.identity) return true;
return (await response.json()).service === service.identity;
} catch {
return false;
}
}
/**
* SIGTERM to a service's process group, so whatever it spawned stops with it; SIGKILL to what
* remains of the group once the service exits or `graceMs` passes.
*/
function stopGroup(child, graceMs) {
const signal = name => {
try {
process.kill(-child.pid, name);
} catch {
/* The group has no processes left. */
}
};
return new Promise(resolve => {
const done = () => {
clearTimeout(timer);
signal('SIGKILL');
resolve();
};
const timer = setTimeout(done, graceMs);
if (child.exitCode !== null || child.signalCode !== null) return done();
child.once('exit', done);
signal('SIGTERM');
});
}
/**
* `url` is a readiness check; a service that answers there already is reused, unless `reuse`
* is false, as under the LaunchAgent supervisor, where it may be a leftover running old code.
* Services without one (Temporal workers) count as ready once they stay up for a moment. Each
* service runs in its own process group; stopping waits until every group is gone, within the
* supervisor's 20 seconds.
*/
export async function startServices(services, banner, { reuse = true, graceMs = 10_000 } = {}) {
const children = [];
let stopping;
const stop = (code = 0) =>
(stopping ??= (async () => {
process.exitCode = code;
await Promise.all(children.map(child => stopGroup(child, graceMs)));
})());
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => void stop());
for (const service of services) {
if (stopping) return { stop };
if (service.url && (await healthy(service))) {
if (!reuse) {
await stop(1);
throw new Error(
`${service.name}: ${service.url} already answers; stop that process before starting these services.`,
);
}
console.log(`${service.name}: reusing the service already running at ${service.url}`);
continue;
}
const child = spawn(process.execPath, service.args, {
cwd: service.cwd,
env: service.env,
stdio: ['ignore', 'pipe', 'pipe'],
detached: true,
});
children.push(child);
for (const output of [child.stdout, child.stderr])
output.on('data', bytes =>
String(bytes)
.split('\n')
.filter(Boolean)
.forEach(line => console.log(`[${service.name}] ${line}`)),
);
child.once('exit', code => {
if (!stopping) {
console.error(`${service.name} exited (${code}); stopping the services this command started.`);
void stop(code || 1);
}
});
let ready = false;
for (let attempt = 0; attempt < (service.url ? 90 : 2) && !stopping; attempt++) {
if (service.url && (await healthy(service))) {
ready = true;
break;
}
await delay(1000);
}
if (!service.url && !stopping) ready = true;
if (!ready) {
await stop(1);
throw new Error(`${service.name} did not become ready; check its output above.`);
}
}
console.log(banner);
if (!children.length) console.log('Every service was already running; nothing was started.');
return { stop };
}