UNPKG

genaiscript

Version:

A CLI for GenAIScript, a generative AI scripting framework.

52 lines (51 loc) 1.69 kB
import { Worker } from "node:worker_threads"; import { fileURLToPath } from "node:url"; import { dirname, join } from "node:path"; import debug from "debug"; import { runtimeHost } from "../../core/src/host"; import { RESOURCE_CHANGE } from "../../core/src/constants"; const dbg = debug("genaiscript:api"); export async function run(scriptId, files, options) { if (!scriptId) throw new Error("scriptId is required"); dbg(`run ${scriptId}`); if (typeof files === "string") files = [files]; const { envVars, signal, ...rest } = options || {}; const workerData = { type: "run", scriptId, files: files || [], options: rest }; const filename = typeof __filename === "undefined" ? join(dirname(fileURLToPath(import.meta.url)), "genaiscript.cjs") : __filename; dbg(`start ${filename}`); let worker = new Worker(filename, { workerData, name: options?.label }); return new Promise((resolve, reject) => { const abort = () => { if (worker) { dbg(`abort`); reject(new Error("aborted")); worker.terminate(); } }; signal?.addEventListener("abort", abort); worker.on("message", async (res) => { const type = res?.type; dbg(type); if (type === "run") { signal?.removeEventListener("abort", abort); resolve(res.result); } else if (type === RESOURCE_CHANGE) { const resource = res; await runtimeHost.resources.upsetResource( resource.reference, resource.content ); } }); worker.on("error", (reason) => { dbg(`error ${reason}`); signal?.removeEventListener("abort", abort); reject(reason); }); }); }