@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
119 lines • 6 kB
JavaScript
/**
* Headless loader for the Windows socket-secret bridge (`crates/senpi-socket-secret`, sisyphuslabs/omo-desktop-app#4199).
* There is no optional fallback: a Windows public-secret mutation that cannot load the bridge must fail, never fall
* back to a direct final-path write. Nothing here runs at import time.
*/
import { randomUUID } from "node:crypto";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { getPackageDir } from "../../config.js";
export { publishSocketSecretNoReplace, SocketSecretPublishError } from "./socket-secret-publish.js";
/** ABI of the bridge's exports, not the package CalVer. Keep aligned with crates/senpi-socket-secret. */
const NATIVE_SOCKET_SECRET_ABI_VERSION = "1";
const SOCKET_SECRET_NATIVE_PATH_ENV = "SENPI_SOCKET_SECRET_NATIVE_PATH";
/** POSIX endpoints have no public-secret presence contract. Do not load a Windows bridge there. */
export function loadSocketSecretPresence(options = {}, native) {
if ((options.platform ?? process.platform) !== "win32") {
return { status: "unavailable", reason: "unsupported_platform" };
}
const binding = native ?? loadSocketSecretNative(options);
assertPresenceBinding(binding);
return {
status: "available",
guard: {
acquire: (id, path) => binding.presenceAcquire(id, path),
probe: (request) => binding.presenceProbe(request),
probeRetained: (request) => binding.presenceProbeRetained(request),
preActionCheck: (id) => binding.presencePreActionCheck(id),
releaseAfterQuiescence: (receipt) => binding.presenceReleaseAfterQuiescence(receipt),
async waitAndAcquire(id, path, signal) {
if (signal?.aborted)
return { status: "cancelled" };
// The native call registers its cancellation token synchronously before queuing work.
const waitId = randomUUID();
const waiting = binding.presenceWaitAndAcquire(id, path, waitId);
const cancel = () => binding.presenceCancelWait(waitId);
signal?.addEventListener("abort", cancel, { once: true });
try {
return await waiting;
}
finally {
signal?.removeEventListener("abort", cancel);
}
},
},
};
}
function assertPresenceBinding(value) {
const exports = value;
if (![
"presenceAcquire",
"presenceProbe",
"presenceProbeRetained",
"presencePreActionCheck",
"presenceWaitAndAcquire",
"presenceCancelWait",
"presenceReleaseAfterQuiescence",
].every((name) => typeof exports[name] === "function")) {
throw new SocketSecretNativeAbiMismatchError("presence registry");
}
}
export class SocketSecretNativeUnavailableError extends Error {
constructor(host, attemptedPaths, causes) {
super(`The Windows socket-secret bridge for ${host} could not be loaded: ${causes.join("; ")}`);
this.code = "socket-secret-native-unavailable";
this.name = "SocketSecretNativeUnavailableError";
this.attemptedPaths = attemptedPaths;
}
}
export class SocketSecretNativeAbiMismatchError extends Error {
constructor(modulePath) {
super(`Socket-secret bridge ABI mismatch in ${modulePath}: expected __senpiSocketSecretAbi1() === "${NATIVE_SOCKET_SECRET_ABI_VERSION}" and every export`);
this.code = "socket-secret-native-abi-mismatch";
this.name = "SocketSecretNativeAbiMismatchError";
this.modulePath = modulePath;
}
}
export function socketSecretNativeCandidatePaths(options = {}) {
const env = options.env ?? process.env;
// An explicit override is authoritative, including when it cannot be loaded.
const override = env[SOCKET_SECRET_NATIVE_PATH_ENV];
if (override)
return [override];
const host = `${options.platform ?? process.platform}-${options.arch ?? process.arch}`;
const relative = join("native", "socket-secret", "prebuilds", host, `senpi_socket_secret.${host}.node`);
const packageDir = options.packageDir ?? (env.SENPI_PACKAGE_DIR || getPackageDir());
const moduleDir = options.moduleDir ?? dirname(fileURLToPath(import.meta.url));
const execPath = options.execPath ?? process.execPath;
return [join(packageDir, relative), join(moduleDir, "../../..", relative), join(dirname(execPath), relative)];
}
/** Loads the bridge or throws; a sentinel mismatch stops at once instead of trying the next candidate. */
export function loadSocketSecretNative(options = {}) {
const attemptedPaths = socketSecretNativeCandidatePaths(options);
const requireBinding = options.requireBinding ?? createRequire(import.meta.url);
const causes = [];
for (const modulePath of attemptedPaths) {
let binding;
try {
binding = requireBinding(modulePath);
}
catch (error) {
causes.push(`${modulePath}: ${error instanceof Error ? error.message : String(error)}`);
continue;
}
assertBinding(binding, modulePath);
return binding;
}
throw new SocketSecretNativeUnavailableError(`${options.platform ?? process.platform}-${options.arch ?? process.arch}`, attemptedPaths, causes);
}
function assertBinding(value, modulePath) {
if (typeof value !== "object" || value === null)
throw new SocketSecretNativeAbiMismatchError(modulePath);
const exports = value;
const complete = ["__senpiSocketSecretAbi1", "publishNoReplace", "kernelSessionIdentity", "classifyVolume"].every((name) => typeof exports[name] === "function");
if (!complete || exports.__senpiSocketSecretAbi1() !== NATIVE_SOCKET_SECRET_ABI_VERSION) {
throw new SocketSecretNativeAbiMismatchError(modulePath);
}
}
//# sourceMappingURL=socket-secret-native.js.map