build: separate runtime artifacts and supervise command ownership
This commit is contained in:
@@ -4,7 +4,4 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
await Promise.all([
|
||||
rm(join(root, "dist"), { recursive: true, force: true }),
|
||||
rm(join(root, ".cache", "tsconfig.build.tsbuildinfo"), { force: true }),
|
||||
]);
|
||||
await rm(join(root, "dist"), { recursive: true, force: true });
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { formatGeneratedFile } from "./lib/format-generated-file.mjs";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../dist/contracts/managed/managedWorkflowToolContracts.js";
|
||||
import { auxiliaryAnalysisProviderDeclarations } from "../dist/composition/auxiliaryAnalysisProviders.js";
|
||||
import { toolRegistrationOptions } from "../dist/server/toolRegistrationOptions.js";
|
||||
import { ensureGeneratedFile } from "./lib/generated-file.mjs";
|
||||
|
||||
@@ -17,10 +16,9 @@ for (const argument of arguments_)
|
||||
throw new Error(`Unknown MCP tool catalog option: ${argument}`);
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
// This build-generated source supports schema and provider conformance tests;
|
||||
// This generated metadata supports schema conformance tests;
|
||||
// production MCP tools are registered from their canonical contracts directly.
|
||||
// Keep the test metadata portable and regenerate it with `npm run build`.
|
||||
const CATALOG_PLATFORM = "darwin";
|
||||
// Keep the test metadata portable and regenerate it with `npm run mcp-catalog:generate`.
|
||||
const sessionToolNames = new Set([
|
||||
...TOOL_CONTRACTS.filter(({ kind }) => kind === "session").map(
|
||||
({ name }) => name,
|
||||
@@ -87,10 +85,6 @@ async function sdkToolCatalog() {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
}
|
||||
const auxiliaryProviders = auxiliaryAnalysisProviderDeclarations(
|
||||
CATALOG_PLATFORM,
|
||||
).map(({ identity, capabilities }) => ({ identity, capabilities }));
|
||||
|
||||
const canonicalizeJson = (value) => {
|
||||
if (Array.isArray(value)) return value.map(canonicalizeJson);
|
||||
if (value === null || typeof value !== "object") return value;
|
||||
@@ -101,101 +95,13 @@ const canonicalizeJson = (value) => {
|
||||
);
|
||||
};
|
||||
|
||||
const payloadJson = JSON.stringify(
|
||||
canonicalizeJson({ catalog, auxiliaryProviders }),
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const source = await formatGeneratedFile(
|
||||
"src/generatedMcpToolCatalog.ts",
|
||||
`import type { ToolAnnotations } from "@modelcontextprotocol/server";
|
||||
import type {
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "./application/AnalysisProvider.js";
|
||||
import type { ToolKind } from "./contracts/toolContractTypes.js";
|
||||
import type { ToolEffects } from "./contracts/toolEffects.js";
|
||||
|
||||
interface GeneratedTool {
|
||||
readonly name: string;
|
||||
readonly analysisOperation: CapabilityDescriptor["operation"] | null;
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
readonly kind: ToolKind;
|
||||
readonly requiresSession: boolean;
|
||||
readonly inputSchema: Readonly<Record<string, unknown>>;
|
||||
readonly outputSchema: Readonly<Record<string, unknown>>;
|
||||
readonly annotations: ToolAnnotations;
|
||||
readonly effects: ToolEffects;
|
||||
}
|
||||
|
||||
interface GeneratedProvider {
|
||||
readonly identity: ProviderIdentity;
|
||||
readonly capabilities: readonly CapabilityDescriptor[];
|
||||
}
|
||||
|
||||
interface GeneratedPayload {
|
||||
readonly catalog: readonly GeneratedTool[];
|
||||
readonly auxiliaryProviders: readonly GeneratedProvider[];
|
||||
}
|
||||
|
||||
const GENERATED_PAYLOAD_JSON = ${JSON.stringify(payloadJson)};
|
||||
const generatedPayload: unknown = JSON.parse(GENERATED_PAYLOAD_JSON);
|
||||
if (!isGeneratedPayload(generatedPayload))
|
||||
throw new TypeError("Generated MCP catalog payload is invalid");
|
||||
|
||||
/** Generated from TOOL_CONTRACTS; do not edit. */
|
||||
export const GENERATED_MCP_TOOL_CATALOG = generatedPayload.catalog;
|
||||
|
||||
/** Generated lightweight metadata for lazily loaded auxiliary providers. */
|
||||
export const GENERATED_AUXILIARY_PROVIDERS = generatedPayload.auxiliaryProviders;
|
||||
|
||||
function isGeneratedPayload(value: unknown): value is GeneratedPayload {
|
||||
return (
|
||||
isRecord(value) &&
|
||||
Array.isArray(value.catalog) &&
|
||||
value.catalog.every(isGeneratedTool) &&
|
||||
Array.isArray(value.auxiliaryProviders) &&
|
||||
value.auxiliaryProviders.every(isGeneratedProvider)
|
||||
);
|
||||
}
|
||||
|
||||
function isGeneratedTool(value: unknown): value is GeneratedTool {
|
||||
return (
|
||||
isRecord(value) &&
|
||||
typeof value.name === "string" &&
|
||||
(typeof value.analysisOperation === "string" ||
|
||||
value.analysisOperation === null) &&
|
||||
typeof value.title === "string" &&
|
||||
typeof value.description === "string" &&
|
||||
typeof value.kind === "string" &&
|
||||
typeof value.requiresSession === "boolean" &&
|
||||
isRecord(value.inputSchema) &&
|
||||
isRecord(value.outputSchema) &&
|
||||
isRecord(value.annotations) &&
|
||||
isRecord(value.effects)
|
||||
);
|
||||
}
|
||||
|
||||
function isGeneratedProvider(value: unknown): value is GeneratedProvider {
|
||||
return (
|
||||
isRecord(value) &&
|
||||
isRecord(value.identity) &&
|
||||
Array.isArray(value.capabilities)
|
||||
);
|
||||
}
|
||||
|
||||
function isRecord(
|
||||
value: unknown,
|
||||
): value is Readonly<Record<string, unknown>> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
const payloadJson = JSON.stringify(canonicalizeJson({ catalog }), null, 2);
|
||||
const outputPath = join(root, ".cache/mcp-tool-catalog.json");
|
||||
if (!arguments_.has("--check"))
|
||||
await mkdir(dirname(outputPath), { recursive: true });
|
||||
await ensureGeneratedFile({
|
||||
path: join(root, "src/generatedMcpToolCatalog.ts"),
|
||||
source,
|
||||
path: outputPath,
|
||||
source: `${payloadJson}\n`,
|
||||
check: arguments_.has("--check"),
|
||||
generateCommand: "npm run mcp-catalog:generate",
|
||||
});
|
||||
|
||||
@@ -200,7 +200,7 @@ export const providerCatalog = (sources) => {
|
||||
sources.webNetworkCaptureContracts.WEB_NETWORK_CAPTURE_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.browserProvider.CDP_BROWSER_PROVIDER_IDENTITY,
|
||||
identity: sources.browserIdentities.CDP_BROWSER_PROVIDER_IDENTITY,
|
||||
contracts: [
|
||||
...sources.browserContracts.BROWSER_TOOL_CONTRACTS,
|
||||
...sources.webRuntimeContracts.WEB_RUNTIME_TOOL_CONTRACTS,
|
||||
@@ -208,19 +208,17 @@ export const providerCatalog = (sources) => {
|
||||
},
|
||||
{
|
||||
identity:
|
||||
sources.browserScenarioProvider
|
||||
.PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY,
|
||||
sources.browserIdentities.PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY,
|
||||
contracts:
|
||||
sources.browserScenarioContracts.BROWSER_SCENARIO_TOOL_CONTRACTS,
|
||||
},
|
||||
{
|
||||
identity: sources.electronProvider.CDP_ELECTRON_PROVIDER_IDENTITY,
|
||||
identity: sources.browserIdentities.CDP_ELECTRON_PROVIDER_IDENTITY,
|
||||
contracts: observationContracts,
|
||||
},
|
||||
{
|
||||
identity:
|
||||
sources.electronActiveProvider
|
||||
.PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY,
|
||||
sources.browserIdentities.PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY,
|
||||
contracts: activeContracts,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -75,10 +75,7 @@ const SOURCE_PATHS = {
|
||||
idaProvider: "dist/ida/IdaProviderCapabilities.js",
|
||||
nativeProvider: "dist/native/NativeMacOSProviderMetadata.js",
|
||||
artifactProviders: "dist/application/InvestigationProviders.js",
|
||||
browserProvider: "dist/browser/CdpBrowserProvider.js",
|
||||
browserScenarioProvider: "dist/browser/PlaywrightBrowserScenarioProvider.js",
|
||||
electronProvider: "dist/browser/CdpElectronProvider.js",
|
||||
electronActiveProvider: "dist/browser/PlaywrightElectronActiveProvider.js",
|
||||
browserIdentities: "dist/browser/providerIdentities.js",
|
||||
v8InspectorProvider: "dist/inspector/V8InspectorProvider.js",
|
||||
evidence: "dist/domain/evidence.js",
|
||||
evidenceBundle: "dist/domain/evidenceBundle.js",
|
||||
|
||||
@@ -11,11 +11,12 @@ export function parseDevelopmentTestRequest(
|
||||
arguments_: readonly string[],
|
||||
): DevelopmentTestRequest;
|
||||
|
||||
/** Plan source feedback or a strict explicit run with its build prerequisite. */
|
||||
/** Plan source feedback or explicit tests with runtime/artifact prerequisites. */
|
||||
export function developmentTestPlan(
|
||||
request: DevelopmentTestRequest,
|
||||
baseCommit?: string,
|
||||
): {
|
||||
readonly needsBuild: boolean;
|
||||
readonly artifactTasks: readonly string[];
|
||||
readonly vitestArguments: readonly string[];
|
||||
};
|
||||
|
||||
@@ -49,7 +49,20 @@ export const parseDevelopmentTestRequest = (mode, arguments_) => {
|
||||
return { mode, paths: [...new Set(paths)], base, dryRun };
|
||||
};
|
||||
|
||||
/** Plan source feedback or a strict explicit run with its build prerequisite. */
|
||||
// Test-only outputs are declared beside the test planner rather than becoming
|
||||
// runtime or typecheck prerequisites. Add a consumer here when it reads one.
|
||||
const artifactConsumers = {
|
||||
"artifacts:mcp-catalog": [
|
||||
"tests/boundary/mcp/contractPresentation.test.ts",
|
||||
"tests/boundary/mcp/toolSchemaValidity.test.ts",
|
||||
],
|
||||
"artifacts:product-catalog": ["tests/boundary/cli/productCatalog.test.ts"],
|
||||
"artifacts:managed-evidence": [
|
||||
"tests/boundary/filesystem/setupSkill.test.ts",
|
||||
],
|
||||
};
|
||||
|
||||
/** Plan source feedback or explicit tests with their runtime/artifact prerequisites. */
|
||||
export const developmentTestPlan = (request, baseCommit) => {
|
||||
const explicit = request.paths.length > 0;
|
||||
if (
|
||||
@@ -60,6 +73,10 @@ export const developmentTestPlan = (request, baseCommit) => {
|
||||
const projects = request.mode === "focused" ? [] : sourceProjects;
|
||||
return {
|
||||
needsBuild: request.paths.some((path) => !sourceTest(path)),
|
||||
artifactTasks: Object.entries(artifactConsumers).flatMap(
|
||||
([task, consumers]) =>
|
||||
request.paths.some((path) => consumers.includes(path)) ? [task] : [],
|
||||
),
|
||||
vitestArguments: [
|
||||
"run",
|
||||
...projects.flatMap((project) => ["--project", project]),
|
||||
|
||||
@@ -14,14 +14,6 @@ const MIGRATED_PROVIDER_ROOTS = new Set([
|
||||
"inspector",
|
||||
"javascript",
|
||||
]);
|
||||
const PROVIDER_ROOTS = new Set([
|
||||
...MIGRATED_PROVIDER_ROOTS,
|
||||
"artifacts",
|
||||
"browser",
|
||||
"dotnet",
|
||||
"native",
|
||||
]);
|
||||
|
||||
const repositoryPath = (root, path) =>
|
||||
relative(root, path).replaceAll("\\", "/");
|
||||
|
||||
@@ -88,11 +80,6 @@ const failedBoundary = (file, target) => {
|
||||
/^src\/(?:cli|main)\./u.test(target))
|
||||
)
|
||||
return "artifact-acquisition";
|
||||
if (
|
||||
PROVIDER_ROOTS.has(layer) &&
|
||||
/^src\/generatedMcpToolCatalog\.(?:js|ts)$/u.test(target)
|
||||
)
|
||||
return "provider-generated-catalog";
|
||||
if (PURE_LAYERS.has(layer)) {
|
||||
if (
|
||||
(/^src\/[^/]+\//u.test(target) && !PURE_LAYERS.has(targetLayer)) ||
|
||||
|
||||
+3
-6
@@ -44,7 +44,6 @@ if (!(await compiledRuntimeExists(runtimeFiles))) {
|
||||
const {
|
||||
renderCliOutputArgumentError,
|
||||
renderEmptyFilteredCliOutput,
|
||||
sanitizeCliOutput,
|
||||
validateCliOutputArguments,
|
||||
} = await import("../dist/cliOutput.js");
|
||||
const outputArguments = validateCliOutputArguments(args);
|
||||
@@ -57,13 +56,11 @@ if (!(await compiledRuntimeExists(runtimeFiles))) {
|
||||
await createCli(process.env, resultOutput).serve(args, {
|
||||
stdout: (output) => {
|
||||
if (resultOutput?.handled) {
|
||||
if (resultOutput.failed)
|
||||
process.stderr.write(sanitizeCliOutput(output));
|
||||
if (resultOutput.failed) process.stderr.write(output);
|
||||
return;
|
||||
}
|
||||
const sanitized = sanitizeCliOutput(output);
|
||||
if (sanitized.length > 0) wroteOutput = true;
|
||||
process.stdout.write(sanitized);
|
||||
if (output.length > 0) wroteOutput = true;
|
||||
process.stdout.write(output);
|
||||
},
|
||||
});
|
||||
if (!wroteOutput && !resultOutput?.handled)
|
||||
|
||||
@@ -47,15 +47,24 @@ try {
|
||||
? `Focused tests: ${request.paths.join(", ")}`
|
||||
: `Source-test feedback${baseCommit ? ` from merge base ${baseCommit}` : ""}; compiled boundaries and real providers need explicit verification.`,
|
||||
);
|
||||
if (plan.needsBuild) {
|
||||
if (!process.env.npm_execpath)
|
||||
throw new Error("Run compiled tests through npm run test:focused");
|
||||
const built = await run(process.execPath, [
|
||||
process.env.npm_execpath,
|
||||
"run",
|
||||
"build:cached",
|
||||
if (plan.needsBuild || plan.artifactTasks.length > 0) {
|
||||
const dependencies = await run(process.execPath, [
|
||||
"scripts/check-dependency-install.mjs",
|
||||
]);
|
||||
if (built.code !== 0) process.exitCode = built.code;
|
||||
if (dependencies.code !== 0)
|
||||
throw new Error(
|
||||
"Test prerequisites require the locked dependency installation",
|
||||
);
|
||||
const prepared = await run(process.execPath, [
|
||||
"scripts/run-exclusive.mjs",
|
||||
"artifacts",
|
||||
process.execPath,
|
||||
resolve("node_modules/turbo/bin/turbo"),
|
||||
"run",
|
||||
...(plan.needsBuild ? ["artifacts:skills"] : []),
|
||||
...plan.artifactTasks,
|
||||
]);
|
||||
if (prepared.code !== 0) process.exitCode = prepared.code;
|
||||
}
|
||||
if (!process.exitCode && !shutdownSignal) {
|
||||
const tested = await run(process.execPath, [
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
|
||||
const [, , lockName, ...command] = process.argv;
|
||||
const lockRoot = resolve(process.cwd(), ".cache", "rea-command-locks");
|
||||
const signalExitCodes = { SIGINT: 130, SIGTERM: 143 };
|
||||
|
||||
let database;
|
||||
let child;
|
||||
let forceTimer;
|
||||
let shutdownSignal;
|
||||
|
||||
process.on("SIGINT", () => handleSignal("SIGINT"));
|
||||
process.on("SIGTERM", () => handleSignal("SIGTERM"));
|
||||
process.on("disconnect", handleDisconnect);
|
||||
process.on("message", (message) => {
|
||||
if (message === "SIGINT" || message === "SIGTERM") handleSignal(message);
|
||||
});
|
||||
|
||||
if (!process.connected) {
|
||||
// The public wrapper can disappear before ESM startup installs listeners.
|
||||
// A disconnected supervisor has no authority to start a new command.
|
||||
process.exitCode = signalExitCodes.SIGTERM;
|
||||
} else if (
|
||||
typeof lockName !== "string" ||
|
||||
!/^[a-z][a-z0-9-]*$/u.test(lockName) ||
|
||||
command.length === 0
|
||||
) {
|
||||
console.error("Usage: run-exclusive.mjs <lock-name> <command> [args...]");
|
||||
process.exitCode = 64;
|
||||
disconnectParent();
|
||||
} else {
|
||||
await run();
|
||||
}
|
||||
|
||||
async function run() {
|
||||
try {
|
||||
await mkdir(lockRoot, { recursive: true });
|
||||
// SQLite owns acquisition and OS-backed lock release, including process
|
||||
// death. Keep the database pathname stable; deleting it would split owners.
|
||||
database = new DatabaseSync(join(lockRoot, `${lockName}.sqlite`));
|
||||
try {
|
||||
database.exec("BEGIN EXCLUSIVE");
|
||||
} catch (cause) {
|
||||
if (isBusyError(cause))
|
||||
throw new Error(
|
||||
`Another ${lockName} command is already running. Wait for it to finish.`,
|
||||
{ cause },
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
if (shutdownSignal === undefined) {
|
||||
const result = await runCommand();
|
||||
process.exitCode = result.code ?? 1;
|
||||
}
|
||||
} catch (cause) {
|
||||
console.error(cause instanceof Error ? cause.message : String(cause));
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
database?.close();
|
||||
clearTimeout(forceTimer);
|
||||
if (shutdownSignal !== undefined)
|
||||
process.exitCode = signalExitCodes[shutdownSignal];
|
||||
disconnectParent();
|
||||
}
|
||||
}
|
||||
|
||||
function runCommand() {
|
||||
return new Promise((resolveResult, reject) => {
|
||||
child = spawn(command[0], command.slice(1), {
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
shell: process.platform === "win32",
|
||||
stdio: "inherit",
|
||||
});
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) => {
|
||||
// During POSIX cancellation the group leader must stay alive, retaining
|
||||
// both its group identity and SQLite ownership until the entire group is
|
||||
// killed. A completed command can still have uncooperative descendants.
|
||||
if (shutdownSignal === undefined || process.platform === "win32")
|
||||
resolveResult({ code });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function disconnectParent() {
|
||||
process.off("disconnect", handleDisconnect);
|
||||
if (process.connected) process.disconnect();
|
||||
}
|
||||
|
||||
function handleDisconnect() {
|
||||
handleSignal("SIGTERM");
|
||||
}
|
||||
|
||||
function handleSignal(signal) {
|
||||
if (shutdownSignal !== undefined) return;
|
||||
shutdownSignal = signal;
|
||||
if (child === undefined || process.platform === "win32") return;
|
||||
// Establish cancellation before signalling the group. This supervisor is
|
||||
// its live leader, so the group identifier cannot be reused during cleanup.
|
||||
process.kill(-process.pid, signal);
|
||||
forceTimer = setTimeout(() => process.kill(-process.pid, "SIGKILL"), 1_000);
|
||||
}
|
||||
|
||||
function isBusyError(cause) {
|
||||
return (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
cause.code === "ERR_SQLITE_ERROR" &&
|
||||
"errcode" in cause &&
|
||||
(cause.errcode === 5 || cause.errcode === 6)
|
||||
);
|
||||
}
|
||||
+31
-146
@@ -1,155 +1,40 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const [, , lockName, ...command] = process.argv;
|
||||
const lockRoot = resolve(process.cwd(), ".cache", "rea-command-locks");
|
||||
const lockPath = join(lockRoot, `${lockName ?? "invalid"}.lock`);
|
||||
const ownerPath = join(lockPath, "owner.json");
|
||||
const signalExitCodes = { SIGINT: 130, SIGTERM: 143 };
|
||||
|
||||
let lockHeld = false;
|
||||
let child;
|
||||
let forceTimer;
|
||||
let shutdownSignal;
|
||||
const supervisor = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
fileURLToPath(new URL("./run-exclusive-command.mjs", import.meta.url)),
|
||||
...process.argv.slice(2),
|
||||
],
|
||||
{
|
||||
detached: process.platform !== "win32",
|
||||
stdio: ["inherit", "inherit", "inherit", "ipc"],
|
||||
},
|
||||
);
|
||||
|
||||
process.on("SIGINT", () => handleSignal("SIGINT"));
|
||||
process.on("SIGTERM", () => handleSignal("SIGTERM"));
|
||||
|
||||
if (
|
||||
typeof lockName !== "string" ||
|
||||
!/^[a-z][a-z0-9-]*$/u.test(lockName) ||
|
||||
command.length === 0
|
||||
) {
|
||||
console.error("Usage: run-exclusive.mjs <lock-name> <command> [args...]");
|
||||
process.exitCode = 64;
|
||||
} else {
|
||||
await run();
|
||||
}
|
||||
|
||||
async function run() {
|
||||
try {
|
||||
await acquireLock();
|
||||
const result = await runCommand();
|
||||
process.exitCode =
|
||||
shutdownSignal === undefined
|
||||
? (result.code ?? 1)
|
||||
: signalExitCodes[shutdownSignal];
|
||||
} catch (cause) {
|
||||
console.error(cause instanceof Error ? cause.message : String(cause));
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
async function acquireLock() {
|
||||
await mkdir(lockRoot, { recursive: true });
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
try {
|
||||
await mkdir(lockPath);
|
||||
await writeFile(
|
||||
ownerPath,
|
||||
JSON.stringify({
|
||||
pid: process.pid,
|
||||
command: command.join(" "),
|
||||
started_at: new Date().toISOString(),
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
lockHeld = true;
|
||||
return;
|
||||
} catch (cause) {
|
||||
if (!isAlreadyExistsError(cause)) throw cause;
|
||||
const owner = await readOwner();
|
||||
if (owner === null || isProcessAlive(owner.pid))
|
||||
throw new Error(
|
||||
`Another ${lockName} command is already running (pid ${String(owner?.pid ?? "unknown")}). Wait for it to finish or inspect ${lockPath}.`,
|
||||
);
|
||||
await rm(lockPath, { force: true, recursive: true });
|
||||
}
|
||||
}
|
||||
throw new Error(`Could not acquire the ${lockName} command lock`);
|
||||
}
|
||||
|
||||
async function releaseLock() {
|
||||
if (!lockHeld) return;
|
||||
lockHeld = false;
|
||||
try {
|
||||
const owner = await readOwner();
|
||||
if (owner?.pid === process.pid)
|
||||
await rm(lockPath, { force: true, recursive: true });
|
||||
} catch (cause) {
|
||||
console.error(
|
||||
`Could not remove the ${lockName} command lock: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function runCommand() {
|
||||
return new Promise((resolveResult, reject) => {
|
||||
child = spawn(command[0], command.slice(1), {
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
shell: process.platform === "win32",
|
||||
stdio: "inherit",
|
||||
});
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(forceTimer);
|
||||
resolveResult({ code });
|
||||
});
|
||||
for (const signal of Object.keys(signalExitCodes))
|
||||
process.on(signal, () => {
|
||||
if (shutdownSignal !== undefined) return;
|
||||
shutdownSignal = signal;
|
||||
if (supervisor.connected)
|
||||
supervisor.send(signal, (cause) => {
|
||||
if (cause !== null)
|
||||
console.error(`Could not forward cancellation: ${cause.message}`);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function handleSignal(signal) {
|
||||
if (shutdownSignal !== undefined) return;
|
||||
shutdownSignal = signal;
|
||||
if (child !== undefined && child.exitCode === null) {
|
||||
child.kill(signal);
|
||||
forceTimer = setTimeout(() => child?.kill("SIGKILL"), 1_000);
|
||||
forceTimer.unref?.();
|
||||
}
|
||||
}
|
||||
|
||||
async function readOwner() {
|
||||
try {
|
||||
const parsed = JSON.parse(await readFile(ownerPath, "utf8"));
|
||||
const pid =
|
||||
typeof parsed === "object" && parsed !== null
|
||||
? Reflect.get(parsed, "pid")
|
||||
: undefined;
|
||||
if (typeof pid !== "number" || !Number.isInteger(pid)) return null;
|
||||
return { pid };
|
||||
} catch (cause) {
|
||||
if (isMissingFileError(cause)) return null;
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
|
||||
function isProcessAlive(pid) {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
return !isMissingProcessError(cause);
|
||||
}
|
||||
}
|
||||
|
||||
function isAlreadyExistsError(cause) {
|
||||
return isNodeError(cause) && cause.code === "EEXIST";
|
||||
}
|
||||
|
||||
function isMissingFileError(cause) {
|
||||
return isNodeError(cause) && cause.code === "ENOENT";
|
||||
}
|
||||
|
||||
function isMissingProcessError(cause) {
|
||||
return isNodeError(cause) && cause.code === "ESRCH";
|
||||
}
|
||||
|
||||
function isNodeError(cause) {
|
||||
return typeof cause === "object" && cause !== null && "code" in cause;
|
||||
}
|
||||
supervisor.once("error", (cause) => {
|
||||
console.error(cause.message);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
supervisor.once("close", (code) => {
|
||||
process.exitCode =
|
||||
shutdownSignal === undefined
|
||||
? (code ?? 1)
|
||||
: signalExitCodes[shutdownSignal];
|
||||
});
|
||||
|
||||
@@ -42,12 +42,8 @@ export async function verifyPackagePack({ root, workspace }) {
|
||||
throw new Error(
|
||||
"package included authored skill sources instead of only the generated bundle",
|
||||
);
|
||||
if (
|
||||
packedFiles.some((path) =>
|
||||
/^package\/(?:dist|src)\/generatedMcpToolCatalog\./u.test(path),
|
||||
)
|
||||
)
|
||||
throw new Error("package included the test-only generated MCP catalog");
|
||||
if (packedFiles.some((path) => path.startsWith("package/.cache/")))
|
||||
throw new Error("package included development cache or test metadata");
|
||||
const skill = (
|
||||
await exec("tar", [
|
||||
"-xOf",
|
||||
|
||||
Reference in New Issue
Block a user