@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
84 lines • 3.2 kB
JavaScript
import { isMainThread, workerData } from "node:worker_threads";
const disposeAll = (grants) => {
for (const grant of grants)
grant.dispose?.();
};
export class SessionWorkerDataRegistry {
constructor(state = { providers: new Map(), sealed: false }) {
this.state = state;
}
provide(name, create) {
if (!isMainThread)
throw new Error("provideSessionWorkerData runs on the main thread only");
if (this.state.sealed)
throw new Error(`session worker data "${name}" was provided after the first session worker`);
if (this.state.providers.has(name))
throw new Error(`session worker data "${name}" is already provided`);
this.state.providers.set(name, create);
}
spawn(start) {
this.state.sealed = true;
const grants = [];
const extensionData = {};
try {
for (const [name, create] of this.state.providers) {
const grant = create();
grants.push(grant);
extensionData[name] = grant.value;
}
}
catch (cause) {
disposeAll(grants);
throw cause;
}
let disposed = false;
const issued = {
extensionData,
transfer: grants.flatMap((grant) => grant.transfer ?? []),
dispose: () => {
if (disposed)
return;
disposed = true;
disposeAll(grants);
},
};
try {
return { result: start(issued), issued };
}
catch (cause) {
issued.dispose();
throw cause;
}
}
}
// One registry per process even when an extension loader instantiates this module again (jiti).
const REGISTRY_KEY = Symbol.for("senpi.session-worker-data.registry");
function sharedState() {
const existing = Reflect.get(globalThis, REGISTRY_KEY);
if (isRegistryState(existing))
return existing;
const state = { providers: new Map(), sealed: false };
Reflect.set(globalThis, REGISTRY_KEY, state);
return state;
}
function isRegistryState(value) {
return (value !== null &&
typeof value === "object" &&
Reflect.get(value, "providers") instanceof Map &&
typeof Reflect.get(value, "sealed") === "boolean");
}
export const sessionWorkerDataRegistry = new SessionWorkerDataRegistry(sharedState());
export function provideSessionWorkerData(name, create) {
sessionWorkerDataRegistry.provide(name, create);
}
export function readSessionWorkerData(data, name) {
const extensionData = data !== null && typeof data === "object" ? Reflect.get(data, "extensionData") : undefined;
if (extensionData === null || typeof extensionData !== "object" || !Object.hasOwn(extensionData, name))
return undefined;
return Reflect.get(extensionData, name);
}
/** The value a provider issued to this session Worker; undefined when not provided or outside a session Worker. */
export function sessionWorkerData(name) {
return isMainThread ? undefined : readSessionWorkerData(workerData, name);
}
//# sourceMappingURL=session-worker-data.js.map