@moikapy/origen-zero 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,115 @@
1
+ import {
2
+ ZeroHTTPError,
3
+ ZeroTimeoutError,
4
+ parseCheckOutput,
5
+ parseFixOutput,
6
+ parseGraphOutput,
7
+ parseSizeOutput
8
+ } from "./chunk-6RAZN3WM.js";
9
+
10
+ // src/http-compiler.ts
11
+ var DEFAULT_TIMEOUT = 3e4;
12
+ var ZeroHTTPCompiler = class {
13
+ endpoint;
14
+ apiKey;
15
+ headers;
16
+ timeout;
17
+ fetchFn;
18
+ constructor(config) {
19
+ this.endpoint = config.endpoint.replace(/\/+$/, "");
20
+ this.apiKey = config.apiKey;
21
+ this.headers = config.headers ?? {};
22
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
23
+ this.fetchFn = config.fetch ?? globalThis.fetch;
24
+ }
25
+ // ── Public API ──────────────────────────────────────────────────────
26
+ async check(source) {
27
+ const raw = await this.post("/check", source);
28
+ return parseCheckOutput(raw);
29
+ }
30
+ async graph(source) {
31
+ const raw = await this.post("/graph", source);
32
+ return parseGraphOutput(raw);
33
+ }
34
+ async size(source) {
35
+ const raw = await this.post("/size", source);
36
+ return parseSizeOutput(raw);
37
+ }
38
+ async fix(source) {
39
+ const raw = await this.post("/fix", source);
40
+ return parseFixOutput(raw);
41
+ }
42
+ async build(source, options) {
43
+ const body = this.sourceToBody(source);
44
+ if (options) body.options = options;
45
+ const json = await this.postJson("/build", body);
46
+ return {
47
+ ok: json.ok ?? false,
48
+ outputPath: json.output ?? json.outputPath,
49
+ diagnostics: json.diagnostics ?? []
50
+ };
51
+ }
52
+ async explain(diagnosticCode) {
53
+ const url = `${this.endpoint}/explain/${encodeURIComponent(diagnosticCode)}`;
54
+ const res = await this.fetchWithTimeout(url, { method: "GET" });
55
+ if (!res.ok) {
56
+ throw new ZeroHTTPError(res.status, url, await res.text());
57
+ }
58
+ return (await res.text()).trim();
59
+ }
60
+ // ── Internal ────────────────────────────────────────────────────────
61
+ sourceToBody(source) {
62
+ if (typeof source === "string") {
63
+ return { source };
64
+ }
65
+ return { source: source.content, path: source.path };
66
+ }
67
+ async post(path, source) {
68
+ const body = this.sourceToBody(source);
69
+ return this.postRaw(path, body);
70
+ }
71
+ async postJson(path, body) {
72
+ const raw = await this.postRaw(path, body);
73
+ return JSON.parse(raw);
74
+ }
75
+ async postRaw(path, body) {
76
+ const url = `${this.endpoint}${path}`;
77
+ const headers = {
78
+ "Content-Type": "application/json",
79
+ ...this.headers
80
+ };
81
+ if (this.apiKey) {
82
+ headers["Authorization"] = this.apiKey;
83
+ }
84
+ const res = await this.fetchWithTimeout(url, {
85
+ method: "POST",
86
+ headers,
87
+ body: JSON.stringify(body)
88
+ });
89
+ if (!res.ok) {
90
+ throw new ZeroHTTPError(res.status, url, await res.text());
91
+ }
92
+ return await res.text();
93
+ }
94
+ /** fetch with timeout. */
95
+ async fetchWithTimeout(url, init) {
96
+ const controller = new AbortController();
97
+ const timer = setTimeout(() => controller.abort(), this.timeout);
98
+ try {
99
+ const res = await this.fetchFn(url, { ...init, signal: controller.signal });
100
+ return res;
101
+ } catch (err) {
102
+ if (err.name === "AbortError") {
103
+ throw new ZeroTimeoutError(`HTTP ${init.method} ${url}`, this.timeout);
104
+ }
105
+ throw err;
106
+ } finally {
107
+ clearTimeout(timer);
108
+ }
109
+ }
110
+ };
111
+
112
+ export {
113
+ ZeroHTTPCompiler
114
+ };
115
+ //# sourceMappingURL=chunk-J5UPC5XT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/http-compiler.ts"],"sourcesContent":["/**\n * @moikapy/origen-zero — ZeroHTTPCompiler\n *\n * HTTP-based Zero compiler client that works in Cloudflare Workers\n * (and any environment with fetch). Calls a Zero compiler service\n * instead of spawning a subprocess.\n *\n * The Zero compiler service must implement these endpoints:\n * POST /check { source, path? } → ZeroCheckResult\n * POST /graph { source, path? } → ZeroGraphResult\n * POST /size { source, path? } → ZeroSizeResult\n * POST /fix { source, path? } → ZeroFixResult\n * POST /build { source, path?, options? } → ZeroBuildResult\n * GET /explain/:code → string\n */\n\nimport type {\n ZeroHTTPCompilerConfig,\n ZeroCompilerLike,\n ZeroSourceFile,\n ZeroCheckResult,\n ZeroGraphResult,\n ZeroSizeResult,\n ZeroFixResult,\n ZeroBuildResult,\n ZeroBuildOptions,\n ZeroDiagnostic,\n} from \"./types.js\";\nimport {\n parseCheckOutput,\n parseGraphOutput,\n parseSizeOutput,\n parseFixOutput,\n} from \"./parser.js\";\nimport { ZeroHTTPError, ZeroTimeoutError } from \"./errors.js\";\n\n// ── Defaults ────────────────────────────────────────────────────────────\n\nconst DEFAULT_TIMEOUT = 30_000;\n\n// ── ZeroHTTPCompiler ─────────────────────────────────────────────────────\n\nexport class ZeroHTTPCompiler implements ZeroCompilerLike {\n private readonly endpoint: string;\n private readonly apiKey: string | undefined;\n private readonly headers: Record<string, string>;\n private readonly timeout: number;\n private readonly fetchFn: typeof globalThis.fetch;\n\n constructor(config: ZeroHTTPCompilerConfig) {\n // Strip trailing slash\n this.endpoint = config.endpoint.replace(/\\/+$/, \"\");\n this.apiKey = config.apiKey;\n this.headers = config.headers ?? {};\n this.timeout = config.timeout ?? DEFAULT_TIMEOUT;\n this.fetchFn = config.fetch ?? globalThis.fetch;\n }\n\n // ── Public API ──────────────────────────────────────────────────────\n\n async check(source: string | ZeroSourceFile): Promise<ZeroCheckResult> {\n const raw = await this.post(\"/check\", source);\n return parseCheckOutput(raw);\n }\n\n async graph(source: string | ZeroSourceFile): Promise<ZeroGraphResult> {\n const raw = await this.post(\"/graph\", source);\n return parseGraphOutput(raw);\n }\n\n async size(source: string | ZeroSourceFile): Promise<ZeroSizeResult> {\n const raw = await this.post(\"/size\", source);\n return parseSizeOutput(raw);\n }\n\n async fix(source: string | ZeroSourceFile): Promise<ZeroFixResult> {\n const raw = await this.post(\"/fix\", source);\n return parseFixOutput(raw);\n }\n\n async build(\n source: string | ZeroSourceFile,\n options?: ZeroBuildOptions,\n ): Promise<ZeroBuildResult> {\n const body = this.sourceToBody(source);\n if (options) body.options = options;\n const json = await this.postJson(\"/build\", body) as {\n ok?: boolean;\n output?: string;\n outputPath?: string;\n diagnostics?: ZeroDiagnostic[];\n };\n return {\n ok: json.ok ?? false,\n outputPath: json.output ?? json.outputPath,\n diagnostics: json.diagnostics ?? [],\n };\n }\n\n async explain(diagnosticCode: string): Promise<string> {\n const url = `${this.endpoint}/explain/${encodeURIComponent(diagnosticCode)}`;\n const res = await this.fetchWithTimeout(url, { method: \"GET\" });\n if (!res.ok) {\n throw new ZeroHTTPError(res.status, url, await res.text());\n }\n return (await res.text()).trim();\n }\n\n // ── Internal ────────────────────────────────────────────────────────\n\n private sourceToBody(\n source: string | ZeroSourceFile,\n ): Record<string, unknown> {\n if (typeof source === \"string\") {\n return { source };\n }\n return { source: source.content, path: source.path };\n }\n\n private async post(\n path: string,\n source: string | ZeroSourceFile,\n ): Promise<string> {\n const body = this.sourceToBody(source);\n return this.postRaw(path, body);\n }\n\n private async postJson(\n path: string,\n body: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const raw = await this.postRaw(path, body);\n return JSON.parse(raw);\n }\n\n private async postRaw(\n path: string,\n body: Record<string, unknown>,\n ): Promise<string> {\n const url = `${this.endpoint}${path}`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...this.headers,\n };\n if (this.apiKey) {\n headers[\"Authorization\"] = this.apiKey;\n }\n\n const res = await this.fetchWithTimeout(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n });\n\n if (!res.ok) {\n throw new ZeroHTTPError(res.status, url, await res.text());\n }\n\n return await res.text();\n }\n\n /** fetch with timeout. */\n private async fetchWithTimeout(\n url: string,\n init: RequestInit,\n ): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n try {\n const res = await this.fetchFn(url, { ...init, signal: controller.signal });\n return res;\n } catch (err) {\n if ((err as Error).name === \"AbortError\") {\n throw new ZeroTimeoutError(`HTTP ${init.method} ${url}`, this.timeout);\n }\n throw err;\n } finally {\n clearTimeout(timer);\n }\n }\n}"],"mappings":";;;;;;;;;;AAsCA,IAAM,kBAAkB;AAIjB,IAAM,mBAAN,MAAmD;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,QAAgC;AAE1C,SAAK,WAAW,OAAO,SAAS,QAAQ,QAAQ,EAAE;AAClD,SAAK,SAAS,OAAO;AACrB,SAAK,UAAU,OAAO,WAAW,CAAC;AAClC,SAAK,UAAU,OAAO,WAAW;AACjC,SAAK,UAAU,OAAO,SAAS,WAAW;AAAA,EAC5C;AAAA;AAAA,EAIA,MAAM,MAAM,QAA2D;AACrE,UAAM,MAAM,MAAM,KAAK,KAAK,UAAU,MAAM;AAC5C,WAAO,iBAAiB,GAAG;AAAA,EAC7B;AAAA,EAEA,MAAM,MAAM,QAA2D;AACrE,UAAM,MAAM,MAAM,KAAK,KAAK,UAAU,MAAM;AAC5C,WAAO,iBAAiB,GAAG;AAAA,EAC7B;AAAA,EAEA,MAAM,KAAK,QAA0D;AACnE,UAAM,MAAM,MAAM,KAAK,KAAK,SAAS,MAAM;AAC3C,WAAO,gBAAgB,GAAG;AAAA,EAC5B;AAAA,EAEA,MAAM,IAAI,QAAyD;AACjE,UAAM,MAAM,MAAM,KAAK,KAAK,QAAQ,MAAM;AAC1C,WAAO,eAAe,GAAG;AAAA,EAC3B;AAAA,EAEA,MAAM,MACJ,QACA,SAC0B;AAC1B,UAAM,OAAO,KAAK,aAAa,MAAM;AACrC,QAAI,QAAS,MAAK,UAAU;AAC5B,UAAM,OAAO,MAAM,KAAK,SAAS,UAAU,IAAI;AAM/C,WAAO;AAAA,MACL,IAAI,KAAK,MAAM;AAAA,MACf,YAAY,KAAK,UAAU,KAAK;AAAA,MAChC,aAAa,KAAK,eAAe,CAAC;AAAA,IACpC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AAM,IAAI,KAAK;AAAA,EACxB;AAAA;AAAA,EAGA,MAAc,iBACZ,KACA,MACmB;AACnB,UAAM,aAAa,IAAI,gBAAgB;AACvC,UAAM,QAAQ,WAAW,MAAM,WAAW,MAAM,GAAG,KAAK,OAAO;AAC/D,QAAI;AACF,YAAM,MAAM,MAAM,KAAK,QAAQ,KAAK,EAAE,GAAG,MAAM,QAAQ,WAAW,OAAO,CAAC;AAC1E,aAAO;AAAA,IACT,SAAS,KAAK;AACZ,UAAK,IAAc,SAAS,cAAc;AACxC,cAAM,IAAI,iBAAiB,QAAQ,KAAK,MAAM,IAAI,GAAG,IAAI,KAAK,OAAO;AAAA,MACvE;AACA,YAAM;AAAA,IACR,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,65 @@
1
+ import {
2
+ createZeroWASIRuntime
3
+ } from "./chunk-QUQPQFU6.js";
4
+
5
+ // src/wasm-tool.ts
6
+ var moduleCache = /* @__PURE__ */ new WeakMap();
7
+ async function getModule(wasmBytes, precompiled) {
8
+ if (wasmBytes instanceof WebAssembly.Module) return wasmBytes;
9
+ if (precompiled) return precompiled;
10
+ const cached = moduleCache.get(wasmBytes);
11
+ if (cached) return cached;
12
+ const compiled = await WebAssembly.compile(wasmBytes);
13
+ moduleCache.set(wasmBytes, compiled);
14
+ return compiled;
15
+ }
16
+ function createZeroWASMTool(config) {
17
+ return {
18
+ name: config.functionName,
19
+ description: config.description,
20
+ parameters: config.parameters ?? {
21
+ type: "object",
22
+ properties: {},
23
+ required: []
24
+ },
25
+ async execute(args, _getD1) {
26
+ const module = await getModule(config.wasmBytes, config.module);
27
+ const wasiArgs = ["zero", JSON.stringify(args)];
28
+ const runtime = createZeroWASIRuntime({
29
+ ...config.runtimeConfig,
30
+ args: wasiArgs
31
+ });
32
+ const instance = await WebAssembly.instantiate(module, runtime.imports);
33
+ runtime.setInstance(instance);
34
+ if (!config.module && config.wasmBytes instanceof ArrayBuffer) {
35
+ config.module = module;
36
+ }
37
+ const exitCode = instance.exports.main();
38
+ if (exitCode !== 0) {
39
+ const errOutput = runtime.getStderr();
40
+ const stdOutput = runtime.getStdout();
41
+ return `Error: Zero program exited with code ${exitCode}${errOutput ? `: ${errOutput}` : ""}${stdOutput ? `
42
+ ${stdOutput}` : ""}`;
43
+ }
44
+ return runtime.getStdout();
45
+ }
46
+ };
47
+ }
48
+ function createZeroWASMTools(wasmBytes, options) {
49
+ const description = options?.descriptions?.["main"] ?? "Zero program entry point";
50
+ const parameters = options?.parameters?.["main"];
51
+ return [
52
+ createZeroWASMTool({
53
+ functionName: "main",
54
+ description,
55
+ wasmBytes,
56
+ parameters
57
+ })
58
+ ];
59
+ }
60
+
61
+ export {
62
+ createZeroWASMTool,
63
+ createZeroWASMTools
64
+ };
65
+ //# sourceMappingURL=chunk-PJFVSOEI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wasm-tool.ts"],"sourcesContent":["/**\n * @moikapy/origen-zero — WASM tool execution\n *\n * Executes compiled Zero WASM modules in-process via WebAssembly.instantiate().\n * Works in Cloudflare Workers, browsers, and Node.js — no subprocess needed.\n *\n * WASM modules compiled from Zero export:\n * - `memory`: WebAssembly.Memory (1+ pages, 64KB each)\n * - `main()`: Program entry point (returns i32, 0 = success)\n * They import WASI snapshot preview 1 functions for I/O.\n *\n * For Origen tool invocation, args are passed via WASI (args_get/args_sizes_get)\n * for wasm32-wasi targets, or encoded to memory for wasm32-web targets that\n * read from environ.\n */\n\nimport type { OrigenTool } from \"@moikapy/origen\";\nimport { createZeroWASIRuntime, type ZeroWASIRuntimeConfig } from \"./wasi-runtime.js\";\n\n// ── Types ─────────────────────────────────────────────────────────────────\n\nexport interface ZeroWASMToolConfig {\n /** Tool function name. */\n functionName: string;\n /** Human-readable description for the LLM. */\n description: string;\n /** Compiled WASM module bytes. */\n wasmBytes: ArrayBuffer | WebAssembly.Module;\n /** Optional pre-instantiated module cache (for Workers global scope). */\n module?: WebAssembly.Module;\n /** WASI runtime config (args, env, files, dirs). */\n runtimeConfig?: ZeroWASIRuntimeConfig;\n /** Custom parameter schema for the OrigenTool. */\n parameters?: Record<string, unknown>;\n}\n\n// ── Module cache ──────────────────────────────────────────────────────────\n// Per-tool module cache. Each tool config can hold its own compiled module,\n// avoiding global cache thrashing when multiple WASM tools are active.\n// The config.module field is populated on first compile and reused thereafter.\n\nconst moduleCache = new WeakMap<ArrayBuffer, WebAssembly.Module>();\n\nasync function getModule(\n wasmBytes: ArrayBuffer | WebAssembly.Module,\n precompiled?: WebAssembly.Module,\n): Promise<WebAssembly.Module> {\n if (wasmBytes instanceof WebAssembly.Module) return wasmBytes;\n if (precompiled) return precompiled;\n // Check per-bytes cache (same ArrayBuffer reference = same module)\n const cached = moduleCache.get(wasmBytes);\n if (cached) return cached;\n const compiled = await WebAssembly.compile(wasmBytes);\n moduleCache.set(wasmBytes, compiled);\n return compiled;\n}\n\n// ── createZeroWASMTool ───────────────────────────────────────────────────\n\n/**\n * Create an OrigenTool that executes a compiled Zero WASM module in-process.\n *\n * The tool instantiates the WASM module with a full WASI runtime,\n * passes args via WASI args_get, calls the exported main() function,\n * and returns the stdout output.\n *\n * Works in Cloudflare Workers, browsers, and Node.js.\n */\nexport function createZeroWASMTool(config: ZeroWASMToolConfig): OrigenTool {\n return {\n name: config.functionName,\n description: config.description,\n parameters: config.parameters ?? {\n type: \"object\",\n properties: {},\n required: [],\n },\n async execute(args: Record<string, unknown>, _getD1: any): Promise<string> {\n const module = await getModule(config.wasmBytes, config.module);\n\n // Pass args as WASI command-line args (JSON-serialized)\n const wasiArgs = [\"zero\", JSON.stringify(args)];\n const runtime = createZeroWASIRuntime({\n ...config.runtimeConfig,\n args: wasiArgs,\n });\n\n const instance = await WebAssembly.instantiate(module, runtime.imports);\n runtime.setInstance(instance);\n\n // Execute the Zero program\n // Cache the compiled module for subsequent invocations\n if (!config.module && config.wasmBytes instanceof ArrayBuffer) {\n (config as ZeroWASMToolConfig).module = module;\n }\n\n const exitCode = (instance.exports.main as () => number)();\n\n if (exitCode !== 0) {\n const errOutput = runtime.getStderr();\n const stdOutput = runtime.getStdout();\n return `Error: Zero program exited with code ${exitCode}${errOutput ? `: ${errOutput}` : \"\"}${stdOutput ? `\\n${stdOutput}` : \"\"}`;\n }\n\n return runtime.getStdout();\n },\n };\n}\n\n/**\n * Create multiple tools from a single Zero WASM module.\n * If the module exports a single main(), creates one tool.\n * Future: parse module exports to discover multiple functions.\n */\nexport function createZeroWASMTools(\n wasmBytes: ArrayBuffer | WebAssembly.Module,\n options?: { descriptions?: Record<string, string>; parameters?: Record<string, Record<string, unknown>> },\n): OrigenTool[] {\n const description = options?.descriptions?.[\"main\"] ?? \"Zero program entry point\";\n const parameters = options?.parameters?.[\"main\"];\n\n return [\n createZeroWASMTool({\n functionName: \"main\",\n description,\n wasmBytes,\n parameters,\n }),\n ];\n}"],"mappings":";;;;;AAyCA,IAAM,cAAc,oBAAI,QAAyC;AAEjE,eAAe,UACb,WACA,aAC6B;AAC7B,MAAI,qBAAqB,YAAY,OAAQ,QAAO;AACpD,MAAI,YAAa,QAAO;AAExB,QAAM,SAAS,YAAY,IAAI,SAAS;AACxC,MAAI,OAAQ,QAAO;AACnB,QAAM,WAAW,MAAM,YAAY,QAAQ,SAAS;AACpD,cAAY,IAAI,WAAW,QAAQ;AACnC,SAAO;AACT;AAaO,SAAS,mBAAmB,QAAwC;AACzE,SAAO;AAAA,IACL,MAAM,OAAO;AAAA,IACb,aAAa,OAAO;AAAA,IACpB,YAAY,OAAO,cAAc;AAAA,MAC/B,MAAM;AAAA,MACN,YAAY,CAAC;AAAA,MACb,UAAU,CAAC;AAAA,IACb;AAAA,IACA,MAAM,QAAQ,MAA+B,QAA8B;AACzE,YAAM,SAAS,MAAM,UAAU,OAAO,WAAW,OAAO,MAAM;AAG9D,YAAM,WAAW,CAAC,QAAQ,KAAK,UAAU,IAAI,CAAC;AAC9C,YAAM,UAAU,sBAAsB;AAAA,QACpC,GAAG,OAAO;AAAA,QACV,MAAM;AAAA,MACR,CAAC;AAED,YAAM,WAAW,MAAM,YAAY,YAAY,QAAQ,QAAQ,OAAO;AACtE,cAAQ,YAAY,QAAQ;AAI5B,UAAI,CAAC,OAAO,UAAU,OAAO,qBAAqB,aAAa;AAC7D,QAAC,OAA8B,SAAS;AAAA,MAC1C;AAEA,YAAM,WAAY,SAAS,QAAQ,KAAsB;AAEzD,UAAI,aAAa,GAAG;AAClB,cAAM,YAAY,QAAQ,UAAU;AACpC,cAAM,YAAY,QAAQ,UAAU;AACpC,eAAO,wCAAwC,QAAQ,GAAG,YAAY,KAAK,SAAS,KAAK,EAAE,GAAG,YAAY;AAAA,EAAK,SAAS,KAAK,EAAE;AAAA,MACjI;AAEA,aAAO,QAAQ,UAAU;AAAA,IAC3B;AAAA,EACF;AACF;AAOO,SAAS,oBACd,WACA,SACc;AACd,QAAM,cAAc,SAAS,eAAe,MAAM,KAAK;AACvD,QAAM,aAAa,SAAS,aAAa,MAAM;AAE/C,SAAO;AAAA,IACL,mBAAmB;AAAA,MACjB,cAAc;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -0,0 +1,223 @@
1
+ // src/wasi-runtime.ts
2
+ var encoder = new TextEncoder();
3
+ var decoder = new TextDecoder();
4
+ function concatUint8(arrays) {
5
+ const total = arrays.reduce((sum, a) => sum + a.length, 0);
6
+ const result = new Uint8Array(total);
7
+ let offset = 0;
8
+ for (const a of arrays) {
9
+ result.set(a, offset);
10
+ offset += a.length;
11
+ }
12
+ return result;
13
+ }
14
+ function createZeroWASIRuntime(config) {
15
+ const args = config?.args ?? ["zero"];
16
+ const env = config?.env ?? [];
17
+ const files = config?.files ?? /* @__PURE__ */ new Map();
18
+ const dirs = config?.dirs ?? /* @__PURE__ */ new Set(["."]);
19
+ let instance;
20
+ let stdout = "";
21
+ let stderr = "";
22
+ const fds = /* @__PURE__ */ new Map();
23
+ let nextFd = 4;
24
+ function view() {
25
+ const memory = instance.exports.memory;
26
+ return new DataView(memory.buffer);
27
+ }
28
+ function mem() {
29
+ const memory = instance.exports.memory;
30
+ return new Uint8Array(memory.buffer);
31
+ }
32
+ function readI32(ptr) {
33
+ return view().getUint32(ptr, true);
34
+ }
35
+ function writeI32(ptr, value) {
36
+ view().setUint32(ptr, value >>> 0, true);
37
+ }
38
+ function writeU64(ptr, value) {
39
+ view().setBigUint64(ptr, BigInt(value), true);
40
+ }
41
+ function readString(ptr, len) {
42
+ return decoder.decode(mem().subarray(ptr, ptr + len));
43
+ }
44
+ function byteLength(items) {
45
+ return items.reduce((total, item) => total + encoder.encode(item).length + 1, 0);
46
+ }
47
+ function writeStrings(ptrArray, ptrBytes, items) {
48
+ let offset = ptrBytes;
49
+ for (let i = 0; i < items.length; i++) {
50
+ const bytes = encoder.encode(items[i]);
51
+ writeI32(ptrArray + i * 4, offset);
52
+ mem().set(bytes, offset);
53
+ mem()[offset + bytes.length] = 0;
54
+ offset += bytes.length + 1;
55
+ }
56
+ }
57
+ function writeFileAt(entry, chunks) {
58
+ const incoming = concatUint8(chunks);
59
+ const current = files.get(entry.path) || new Uint8Array(0);
60
+ const end = entry.pos + incoming.length;
61
+ const next = new Uint8Array(Math.max(current.length, end));
62
+ next.set(current, 0);
63
+ next.set(incoming, entry.pos);
64
+ files.set(entry.path, next);
65
+ entry.pos = end;
66
+ }
67
+ const imports = {
68
+ wasi_snapshot_preview1: {
69
+ args_sizes_get(argcPtr, argvBufSizePtr) {
70
+ writeI32(argcPtr, args.length);
71
+ writeI32(argvBufSizePtr, byteLength(args));
72
+ return 0;
73
+ },
74
+ args_get(argvPtr, argvBufPtr) {
75
+ writeStrings(argvPtr, argvBufPtr, args);
76
+ return 0;
77
+ },
78
+ environ_sizes_get(countPtr, envBufSizePtr) {
79
+ writeI32(countPtr, env.length);
80
+ writeI32(envBufSizePtr, byteLength(env));
81
+ return 0;
82
+ },
83
+ environ_get(envPtr, envBufPtr) {
84
+ writeStrings(envPtr, envBufPtr, env);
85
+ return 0;
86
+ },
87
+ path_open(fd, dirflags, pathPtr, pathLen, oflags, rightsBase, rightsInheriting, fdflags, openedFdPtr) {
88
+ const path = readString(pathPtr, pathLen);
89
+ const directory = (oflags & 2) !== 0;
90
+ const write = (oflags & 9) !== 0 || (rightsBase & 64n) !== 0n;
91
+ if (directory) {
92
+ if (!dirs.has(path)) return 44;
93
+ const opened2 = nextFd++;
94
+ fds.set(opened2, { type: "dir", path, pos: 0 });
95
+ writeI32(openedFdPtr, opened2);
96
+ return 0;
97
+ }
98
+ if (write) files.set(path, new Uint8Array(0));
99
+ if (!files.has(path)) return 44;
100
+ const opened = nextFd++;
101
+ fds.set(opened, { type: "file", path, pos: 0 });
102
+ writeI32(openedFdPtr, opened);
103
+ return 0;
104
+ },
105
+ fd_read(fd, iovs, iovsLen, nread) {
106
+ const entry = fds.get(fd);
107
+ if (!entry || entry.type !== "file") return 8;
108
+ const source = files.get(entry.path) || new Uint8Array(0);
109
+ let total = 0;
110
+ for (let i = 0; i < iovsLen; i++) {
111
+ const ptr = readI32(iovs + i * 8);
112
+ const len = readI32(iovs + i * 8 + 4);
113
+ const chunk = source.subarray(entry.pos, entry.pos + len);
114
+ mem().set(chunk, ptr);
115
+ entry.pos += chunk.length;
116
+ total += chunk.length;
117
+ }
118
+ writeI32(nread, total);
119
+ return 0;
120
+ },
121
+ fd_write(fd, iovs, iovsLen, nwritten) {
122
+ let total = 0;
123
+ const chunks = [];
124
+ for (let i = 0; i < iovsLen; i++) {
125
+ const ptr = readI32(iovs + i * 8);
126
+ const len = readI32(iovs + i * 8 + 4);
127
+ chunks.push(mem().slice(ptr, ptr + len));
128
+ total += len;
129
+ }
130
+ if (fd === 1) {
131
+ stdout += decoder.decode(concatUint8(chunks));
132
+ } else if (fd === 2) {
133
+ stderr += decoder.decode(concatUint8(chunks));
134
+ } else {
135
+ const entry = fds.get(fd);
136
+ if (!entry || entry.type !== "file") return 8;
137
+ writeFileAt(entry, chunks);
138
+ }
139
+ writeI32(nwritten, total);
140
+ return 0;
141
+ },
142
+ fd_close(fd) {
143
+ fds.delete(fd);
144
+ return 0;
145
+ },
146
+ fd_filestat_get(fd, buf) {
147
+ const entry = fds.get(fd);
148
+ if (!entry || entry.type !== "file") return 8;
149
+ writeU64(buf + 32, (files.get(entry.path) || new Uint8Array(0)).length);
150
+ return 0;
151
+ },
152
+ fd_readdir(fd, buf, bufLen, cookie, nread) {
153
+ const entry = fds.get(fd);
154
+ if (!entry || entry.type !== "dir") return 8;
155
+ writeI32(nread, 0);
156
+ return 0;
157
+ },
158
+ path_create_directory(fd, pathPtr, pathLen) {
159
+ dirs.add(readString(pathPtr, pathLen));
160
+ return 0;
161
+ },
162
+ path_remove_directory(fd, pathPtr, pathLen) {
163
+ const path = readString(pathPtr, pathLen);
164
+ if (!dirs.has(path)) return 44;
165
+ dirs.delete(path);
166
+ return 0;
167
+ },
168
+ path_unlink_file(fd, pathPtr, pathLen) {
169
+ const path = readString(pathPtr, pathLen);
170
+ if (!files.has(path)) return 44;
171
+ files.delete(path);
172
+ return 0;
173
+ },
174
+ path_rename(oldFd, oldPtr, oldLen, newFd, newPtr, newLen) {
175
+ const oldPath = readString(oldPtr, oldLen);
176
+ const newPath = readString(newPtr, newLen);
177
+ if (!files.has(oldPath)) return 44;
178
+ files.set(newPath, files.get(oldPath));
179
+ files.delete(oldPath);
180
+ return 0;
181
+ },
182
+ // Stubs for WASI functions Zero doesn't use but may import
183
+ proc_exit(code) {
184
+ throw new Error(`Zero program exited with code ${code}`);
185
+ },
186
+ clock_time_get(clockId, precision, timePtr) {
187
+ if (clockId === 0) {
188
+ const ns = BigInt(Date.now()) * 1000000n;
189
+ view().setBigUint64(timePtr, ns, true);
190
+ return 0;
191
+ }
192
+ return 0;
193
+ },
194
+ random_get(buf, bufLen) {
195
+ const bytes = crypto.getRandomValues(new Uint8Array(bufLen));
196
+ mem().set(bytes, buf);
197
+ return 0;
198
+ },
199
+ sched_yield() {
200
+ return 0;
201
+ },
202
+ poll_oneoff(inPtr, outPtr, nsubscriptions, nevents) {
203
+ writeI32(nevents, 0);
204
+ return 0;
205
+ }
206
+ }
207
+ };
208
+ return {
209
+ imports,
210
+ getStdout: () => stdout,
211
+ getStderr: () => stderr,
212
+ getFiles: () => files,
213
+ getDirs: () => dirs,
214
+ setInstance(i) {
215
+ instance = i;
216
+ }
217
+ };
218
+ }
219
+
220
+ export {
221
+ createZeroWASIRuntime
222
+ };
223
+ //# sourceMappingURL=chunk-QUQPQFU6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wasi-runtime.ts"],"sourcesContent":["/**\n * @moikapy/origen-zero — WASI runtime for Zero WASM modules\n *\n * Full WASI snapshot preview 1 implementation matching the Zero CLI's\n * wasm-runtime-smoke.mjs. Supports: args, env, fd_read, fd_write,\n * path_open, fd_close, fd_filestat_get, fd_readdir, path_mkdir,\n * path_remove_directory, path_unlink_file, path_rename.\n *\n * Zero programs that use World (stdout/stderr), std.args, std.env,\n * or std.fs (Fs resource) all route through these WASI imports.\n *\n * Uses only Uint8Array/TextEncoder/TextDecoder — no Node.js Buffer.\n * Works in Cloudflare Workers, browsers, and Node.js.\n */\n\n// ── Portable byte utilities (Workers-compatible, no Buffer) ────────────\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\nfunction concatUint8(arrays: Uint8Array[]): Uint8Array {\n const total = arrays.reduce((sum, a) => sum + a.length, 0);\n const result = new Uint8Array(total);\n let offset = 0;\n for (const a of arrays) {\n result.set(a, offset);\n offset += a.length;\n }\n return result;\n}\n\n// ── Types ─────────────────────────────────────────────────────────────────\n\nexport interface ZeroWASIRuntimeConfig {\n /** Command-line args (default: [\"zero\"]). */\n args?: string[];\n /** Environment variables (default: []). Format: \"KEY=VALUE\". */\n env?: string[];\n /** Pre-populated files: Map<path, Uint8Array>. */\n files?: Map<string, Uint8Array>;\n /** Pre-populated directories. */\n dirs?: Set<string>;\n}\n\nexport interface ZeroWASIRuntime {\n /** WASI imports to pass to WebAssembly.instantiate(). */\n imports: Record<string, Record<string, WebAssembly.ImportValue>>;\n /** Get all captured stdout output. */\n getStdout(): string;\n /** Get all captured stderr output. */\n getStderr(): string;\n /** Get the virtual filesystem state. */\n getFiles(): Map<string, Uint8Array>;\n /** Get the virtual directory set. */\n getDirs(): Set<string>;\n /** Set the instance reference (called after instantiation). */\n setInstance(instance: WebAssembly.Instance): void;\n}\n\n// ── Implementation ────────────────────────────────────────────────────────\n\nexport function createZeroWASIRuntime(config?: ZeroWASIRuntimeConfig): ZeroWASIRuntime {\n const args = config?.args ?? [\"zero\"];\n const env = config?.env ?? [];\n const files = config?.files ?? new Map<string, Uint8Array>();\n const dirs = config?.dirs ?? new Set([\".\"]);\n\n let instance: WebAssembly.Instance;\n let stdout = \"\";\n let stderr = \"\";\n const fds = new Map<number, { type: \"file\" | \"dir\"; path: string; pos: number }>();\n let nextFd = 4; // 0=stdin, 1=stdout, 2=stderr, 3+ available\n\n // ── Helpers ──────────────────────────────────────────────────────────\n\n function view(): DataView {\n const memory = instance.exports.memory as WebAssembly.Memory;\n return new DataView(memory.buffer);\n }\n\n function mem(): Uint8Array {\n const memory = instance.exports.memory as WebAssembly.Memory;\n return new Uint8Array(memory.buffer);\n }\n\n function readI32(ptr: number): number {\n return view().getUint32(ptr, true);\n }\n\n function writeI32(ptr: number, value: number): void {\n view().setUint32(ptr, value >>> 0, true);\n }\n\n function writeU64(ptr: number, value: number): void {\n view().setBigUint64(ptr, BigInt(value), true);\n }\n\n function readString(ptr: number, len: number): string {\n return decoder.decode(mem().subarray(ptr, ptr + len));\n }\n\n function byteLength(items: string[]): number {\n return items.reduce((total, item) => total + encoder.encode(item).length + 1, 0);\n }\n\n function writeStrings(ptrArray: number, ptrBytes: number, items: string[]): void {\n let offset = ptrBytes;\n for (let i = 0; i < items.length; i++) {\n const bytes = encoder.encode(items[i]!);\n writeI32(ptrArray + i * 4, offset);\n mem().set(bytes, offset);\n mem()[offset + bytes.length] = 0; // null terminator\n offset += bytes.length + 1;\n }\n }\n\n function writeFileAt(entry: { path: string; pos: number }, chunks: Uint8Array[]): void {\n const incoming = concatUint8(chunks);\n const current = files.get(entry.path) || new Uint8Array(0);\n const end = entry.pos + incoming.length;\n const next = new Uint8Array(Math.max(current.length, end));\n next.set(current, 0);\n next.set(incoming, entry.pos);\n files.set(entry.path, next);\n entry.pos = end;\n }\n\n // ── WASI Imports ─────────────────────────────────────────────────────\n\n const imports: Record<string, Record<string, WebAssembly.ImportValue>> = {\n wasi_snapshot_preview1: {\n args_sizes_get(argcPtr: number, argvBufSizePtr: number): number {\n writeI32(argcPtr, args.length);\n writeI32(argvBufSizePtr, byteLength(args));\n return 0;\n },\n\n args_get(argvPtr: number, argvBufPtr: number): number {\n writeStrings(argvPtr, argvBufPtr, args);\n return 0;\n },\n\n environ_sizes_get(countPtr: number, envBufSizePtr: number): number {\n writeI32(countPtr, env.length);\n writeI32(envBufSizePtr, byteLength(env));\n return 0;\n },\n\n environ_get(envPtr: number, envBufPtr: number): number {\n writeStrings(envPtr, envBufPtr, env);\n return 0;\n },\n\n path_open(\n fd: number, dirflags: number, pathPtr: number, pathLen: number,\n oflags: number, rightsBase: bigint, rightsInheriting: bigint,\n fdflags: number, openedFdPtr: number,\n ): number {\n const path = readString(pathPtr, pathLen);\n const directory = (oflags & 2) !== 0;\n const write = (oflags & 9) !== 0 || (rightsBase & 64n) !== 0n;\n\n if (directory) {\n if (!dirs.has(path)) return 44; // ENOENT\n const opened = nextFd++;\n fds.set(opened, { type: \"dir\", path, pos: 0 });\n writeI32(openedFdPtr, opened);\n return 0;\n }\n\n if (write) files.set(path, new Uint8Array(0));\n if (!files.has(path)) return 44; // ENOENT\n const opened = nextFd++;\n fds.set(opened, { type: \"file\", path, pos: 0 });\n writeI32(openedFdPtr, opened);\n return 0;\n },\n\n fd_read(fd: number, iovs: number, iovsLen: number, nread: number): number {\n const entry = fds.get(fd);\n if (!entry || entry.type !== \"file\") return 8; // EBADF\n const source = files.get(entry.path) || new Uint8Array(0);\n let total = 0;\n for (let i = 0; i < iovsLen; i++) {\n const ptr = readI32(iovs + i * 8);\n const len = readI32(iovs + i * 8 + 4);\n const chunk = source.subarray(entry.pos, entry.pos + len);\n mem().set(chunk, ptr);\n entry.pos += chunk.length;\n total += chunk.length;\n }\n writeI32(nread, total);\n return 0;\n },\n\n fd_write(fd: number, iovs: number, iovsLen: number, nwritten: number): number {\n let total = 0;\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < iovsLen; i++) {\n const ptr = readI32(iovs + i * 8);\n const len = readI32(iovs + i * 8 + 4);\n chunks.push(mem().slice(ptr, ptr + len));\n total += len;\n }\n if (fd === 1) {\n stdout += decoder.decode(concatUint8(chunks));\n } else if (fd === 2) {\n stderr += decoder.decode(concatUint8(chunks));\n } else {\n const entry = fds.get(fd);\n if (!entry || entry.type !== \"file\") return 8; // EBADF\n writeFileAt(entry, chunks);\n }\n writeI32(nwritten, total);\n return 0;\n },\n\n fd_close(fd: number): number {\n fds.delete(fd);\n return 0;\n },\n\n fd_filestat_get(fd: number, buf: number): number {\n const entry = fds.get(fd);\n if (!entry || entry.type !== \"file\") return 8; // EBADF\n writeU64(buf + 32, (files.get(entry.path) || new Uint8Array(0)).length);\n return 0;\n },\n\n fd_readdir(fd: number, buf: number, bufLen: number, cookie: number, nread: number): number {\n const entry = fds.get(fd);\n if (!entry || entry.type !== \"dir\") return 8; // EBADF\n writeI32(nread, 0);\n return 0;\n },\n\n path_create_directory(fd: number, pathPtr: number, pathLen: number): number {\n dirs.add(readString(pathPtr, pathLen));\n return 0;\n },\n\n path_remove_directory(fd: number, pathPtr: number, pathLen: number): number {\n const path = readString(pathPtr, pathLen);\n if (!dirs.has(path)) return 44; // ENOENT\n dirs.delete(path);\n return 0;\n },\n\n path_unlink_file(fd: number, pathPtr: number, pathLen: number): number {\n const path = readString(pathPtr, pathLen);\n if (!files.has(path)) return 44; // ENOENT\n files.delete(path);\n return 0;\n },\n\n path_rename(\n oldFd: number, oldPtr: number, oldLen: number,\n newFd: number, newPtr: number, newLen: number,\n ): number {\n const oldPath = readString(oldPtr, oldLen);\n const newPath = readString(newPtr, newLen);\n if (!files.has(oldPath)) return 44; // ENOENT\n files.set(newPath, files.get(oldPath)!);\n files.delete(oldPath);\n return 0;\n },\n\n // Stubs for WASI functions Zero doesn't use but may import\n proc_exit(code: number): void {\n throw new Error(`Zero program exited with code ${code}`);\n },\n\n clock_time_get(clockId: number, precision: bigint, timePtr: number): number {\n // Return current time as nanoseconds for realtime clock\n if (clockId === 0) {\n const ns = BigInt(Date.now()) * 1_000_000n;\n view().setBigUint64(timePtr, ns, true);\n return 0;\n }\n return 0;\n },\n\n random_get(buf: number, bufLen: number): number {\n const bytes = crypto.getRandomValues(new Uint8Array(bufLen));\n mem().set(bytes, buf);\n return 0;\n },\n\n sched_yield(): number { return 0; },\n poll_oneoff(inPtr: number, outPtr: number, nsubscriptions: number, nevents: number): number {\n writeI32(nevents, 0);\n return 0;\n },\n },\n };\n\n return {\n imports,\n getStdout: () => stdout,\n getStderr: () => stderr,\n getFiles: () => files,\n getDirs: () => dirs,\n setInstance(i: WebAssembly.Instance) { instance = i; },\n };\n}"],"mappings":";AAiBA,IAAM,UAAU,IAAI,YAAY;AAChC,IAAM,UAAU,IAAI,YAAY;AAEhC,SAAS,YAAY,QAAkC;AACrD,QAAM,QAAQ,OAAO,OAAO,CAAC,KAAK,MAAM,MAAM,EAAE,QAAQ,CAAC;AACzD,QAAM,SAAS,IAAI,WAAW,KAAK;AACnC,MAAI,SAAS;AACb,aAAW,KAAK,QAAQ;AACtB,WAAO,IAAI,GAAG,MAAM;AACpB,cAAU,EAAE;AAAA,EACd;AACA,SAAO;AACT;AAgCO,SAAS,sBAAsB,QAAiD;AACrF,QAAM,OAAO,QAAQ,QAAQ,CAAC,MAAM;AACpC,QAAM,MAAM,QAAQ,OAAO,CAAC;AAC5B,QAAM,QAAQ,QAAQ,SAAS,oBAAI,IAAwB;AAC3D,QAAM,OAA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WAAW,QAAQ,MAAM;AACzC,YAAI,CAAC,MAAM,IAAI,OAAO,EAAG,QAAO;AAChC,cAAM,IAAI,SAAS,MAAM,IAAI,OAAO,CAAE;AACtC,cAAM,OAAO,OAAO;AACpB,eAAO;AAAA,MACT;AAAA;AAAA,MAGA,UAAU,MAAoB;AAC5B,cAAM,IAAI,MAAM,iCAAiC,IAAI,EAAE;AAAA,MACzD;AAAA,MAEA,eAAe,SAAiB,WAAmB,SAAyB;AAE1E,YAAI,YAAY,GAAG;AACjB,gBAAM,KAAK,OAAO,KAAK,IAAI,CAAC,IAAI;AAChC,eAAK,EAAE,aAAa,SAAS,IAAI,IAAI;AACrC,iBAAO;AAAA,QACT;AACA,eAAO;AAAA,MACT;AAAA,MAEA,WAAW,KAAa,QAAwB;AAC9C,cAAM,QAAQ,OAAO,gBAAgB,IAAI,WAAW,MAAM,CAAC;AAC3D,YAAI,EAAE,IAAI,OAAO,GAAG;AACpB,eAAO;AAAA,MACT;AAAA,MAEA,cAAsB;AAAE,eAAO;AAAA,MAAG;AAAA,MAClC,YAAY,OAAe,QAAgB,gBAAwB,SAAyB;AAC1F,iBAAS,SAAS,CAAC;AACnB,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,WAAW,MAAM;AAAA,IACjB,WAAW,MAAM;AAAA,IACjB,UAAU,MAAM;AAAA,IAChB,SAAS,MAAM;AAAA,IACf,YAAY,GAAyB;AAAE,iBAAW;AAAA,IAAG;AAAA,EACvD;AACF;","names":["opened"]}
@@ -0,0 +1,161 @@
1
+ import {
2
+ ZeroCompiler
3
+ } from "./chunk-DE5JDJKT.js";
4
+ import {
5
+ ZeroExecutionError,
6
+ ZeroHTTPError
7
+ } from "./chunk-6RAZN3WM.js";
8
+
9
+ // src/tools.ts
10
+ function createZeroTool(config) {
11
+ return {
12
+ name: config.functionName,
13
+ description: config.description,
14
+ parameters: config.parameters ?? {
15
+ type: "object",
16
+ properties: {},
17
+ required: []
18
+ },
19
+ inputSchema: config.inputSchema,
20
+ async execute(args) {
21
+ return executeTool(config.execution, args);
22
+ }
23
+ };
24
+ }
25
+ async function createZeroToolsFromProgram(execution, options) {
26
+ const compiler = resolveCompiler(options?.compiler);
27
+ const source = execution.mode === "subprocess" ? { path: execution.executablePath } : { path: "program.0" };
28
+ const graphResult = await compiler.graph(source);
29
+ const functionNames = graphResult.functions.map((f) => f.name);
30
+ return functionNames.map(
31
+ (fn) => createZeroTool({
32
+ functionName: fn,
33
+ description: `Zero function: ${fn}`,
34
+ execution,
35
+ compiler,
36
+ verify: options?.verify
37
+ })
38
+ );
39
+ }
40
+ async function compileAndRegister(source, options) {
41
+ const compiler = resolveCompiler(options?.compiler);
42
+ const execution = options?.execution ?? {
43
+ mode: "subprocess",
44
+ executablePath: source.path.replace(/\.0$/, "")
45
+ };
46
+ const checkResult = await compiler.check(source);
47
+ if (!checkResult.ok) {
48
+ return { errors: checkResult.diagnostics };
49
+ }
50
+ if (execution.mode === "subprocess" && compiler instanceof ZeroCompiler) {
51
+ const buildResult = await compiler.build(source, {
52
+ ...options?.build,
53
+ out: options?.build?.out ?? execution.executablePath
54
+ });
55
+ if (!buildResult.ok || !buildResult.outputPath) {
56
+ return {
57
+ errors: buildResult.diagnostics.length > 0 ? buildResult.diagnostics : [
58
+ {
59
+ code: "ZERO_BUILD_FAILED",
60
+ severity: "error",
61
+ message: "Build produced no output",
62
+ line: 0
63
+ }
64
+ ]
65
+ };
66
+ }
67
+ execution.executablePath = buildResult.outputPath;
68
+ }
69
+ const graphResult = await compiler.graph(source);
70
+ const tools = graphResult.functions.map(
71
+ (f) => createZeroTool({
72
+ functionName: f.name,
73
+ description: `Zero function: ${f.name}`,
74
+ execution,
75
+ compiler
76
+ })
77
+ );
78
+ return { tools };
79
+ }
80
+ async function executeTool(execution, args) {
81
+ switch (execution.mode) {
82
+ case "subprocess":
83
+ return executeBinary(execution.executablePath, args);
84
+ case "http":
85
+ return executeHTTP(execution, args);
86
+ case "wasm": {
87
+ const { createZeroWASMTool } = await import("./wasm-tool.js");
88
+ const tool = createZeroWASMTool({
89
+ functionName: "main",
90
+ description: "Zero WASM tool",
91
+ wasmBytes: execution.wasmBytes
92
+ });
93
+ return tool.execute(args, async () => null);
94
+ }
95
+ }
96
+ }
97
+ async function executeBinary(executablePath, args) {
98
+ const { execFile } = await import("child_process");
99
+ const stdin = JSON.stringify(args);
100
+ return new Promise((resolve, reject) => {
101
+ const child = execFile(
102
+ executablePath,
103
+ [],
104
+ {
105
+ maxBuffer: 1024 * 1024
106
+ // 1MB
107
+ },
108
+ (error, stdout, stderr) => {
109
+ if (error) {
110
+ reject(
111
+ new ZeroExecutionError(
112
+ error.code ?? 1,
113
+ stderr || error.message
114
+ )
115
+ );
116
+ return;
117
+ }
118
+ resolve(stdout);
119
+ }
120
+ );
121
+ if (child.stdin) {
122
+ child.stdin.write(stdin, () => {
123
+ child.stdin?.end();
124
+ });
125
+ }
126
+ });
127
+ }
128
+ async function executeHTTP(execution, args) {
129
+ const headers = {
130
+ "Content-Type": "application/json",
131
+ ...execution.headers
132
+ };
133
+ if (execution.apiKey) {
134
+ headers["Authorization"] = execution.apiKey;
135
+ }
136
+ const fetchFn = execution.fetch ?? globalThis.fetch;
137
+ const url = `${execution.endpoint.replace(/\/+$/, "")}/execute`;
138
+ const res = await fetchFn(url, {
139
+ method: "POST",
140
+ headers,
141
+ body: JSON.stringify(args)
142
+ });
143
+ if (!res.ok) {
144
+ throw new ZeroHTTPError(res.status, url, await res.text());
145
+ }
146
+ return await res.text();
147
+ }
148
+ function resolveCompiler(compiler) {
149
+ if (!compiler) return new ZeroCompiler();
150
+ if ("check" in compiler && typeof compiler.check === "function") {
151
+ return compiler;
152
+ }
153
+ return new ZeroCompiler(compiler);
154
+ }
155
+
156
+ export {
157
+ createZeroTool,
158
+ createZeroToolsFromProgram,
159
+ compileAndRegister
160
+ };
161
+ //# sourceMappingURL=chunk-SDOZC7ZI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tools.ts"],"sourcesContent":["/**\n * @moikapy/origen-zero — Tool registration\n *\n * Registers compiled Zero programs as OrigenTools and provides\n * compileAndRegister for write-compile-verify-register in one call.\n *\n * Supports two execution modes:\n * - \"subprocess\": Spawns compiled binary (Node/Bun only)\n * - \"http\": Calls a Zero execution service via fetch (Workers-compatible)\n */\n\nimport type { OrigenTool } from \"@moikapy/origen\";\nimport { ZeroCompiler, TEMP_DIR } from \"./compiler.js\";\nimport type {\n ZeroCompilerLike,\n ZeroToolConfig,\n ZeroToolExecution,\n ZeroSourceFile,\n ZeroToolRegistrationSuccess,\n ZeroToolRegistrationFailure,\n ZeroBuildOptions,\n ZeroCompilerConfig,\n} from \"./types.js\";\nimport { ZeroExecutionError, ZeroHTTPError } from \"./errors.js\";\n\nconst DEFAULT_VERIFY = true;\n\n// ── createZeroTool ───────────────────────────────────────────────────────\n\n/**\n * Register a compiled Zero program's function as an OrigenTool.\n *\n * In \"subprocess\" mode, executes the compiled binary via execFile.\n * In \"http\" mode, calls a Zero execution service via fetch.\n */\nexport function createZeroTool(config: ZeroToolConfig): OrigenTool {\n return {\n name: config.functionName,\n description: config.description,\n parameters: config.parameters ?? {\n type: \"object\",\n properties: {},\n required: [],\n },\n inputSchema: config.inputSchema,\n async execute(args: Record<string, unknown>): Promise<string> {\n return executeTool(config.execution, args);\n },\n } as OrigenTool;\n}\n\n// ── createZeroToolsFromProgram ──────────────────────────────────────────\n\n/**\n * Register all exported functions from a Zero program as OrigenTools.\n * Uses the compiler's graph() to discover public functions,\n * then creates one OrigenTool per function.\n */\nexport async function createZeroToolsFromProgram(\n execution: ZeroToolExecution,\n options?: {\n compiler?: ZeroCompilerLike | ZeroCompilerConfig;\n verify?: boolean;\n },\n): Promise<OrigenTool[]> {\n const compiler = resolveCompiler(options?.compiler);\n\n // Use graph to discover public functions\n const source: ZeroSourceFile =\n execution.mode === \"subprocess\"\n ? { path: execution.executablePath }\n : { path: \"program.0\" }; // HTTP mode — path is a hint\n\n const graphResult = await compiler.graph(source);\n const functionNames = graphResult.functions.map(f => f.name);\n\n return functionNames.map((fn) =>\n createZeroTool({\n functionName: fn,\n description: `Zero function: ${fn}`,\n execution,\n compiler,\n verify: options?.verify,\n }),\n );\n}\n\n// ── compileAndRegister ──────────────────────────────────────────────────\n\n/**\n * Write a Zero source file, compile it, verify it, and register\n * its public functions as OrigenTools — all in one call.\n *\n * If the source has errors, returns them without registering tools.\n *\n * Note: build() only works with ZeroCompiler (subprocess), not ZeroHTTPCompiler.\n * HTTP mode requires pre-compiled binaries or a build service.\n */\nexport async function compileAndRegister(\n source: ZeroSourceFile,\n options?: {\n compiler?: ZeroCompilerLike | ZeroCompilerConfig;\n execution?: ZeroToolExecution;\n build?: ZeroBuildOptions;\n },\n): Promise<ZeroToolRegistrationSuccess | ZeroToolRegistrationFailure> {\n const compiler = resolveCompiler(options?.compiler);\n const execution: ZeroToolExecution = options?.execution ?? {\n mode: \"subprocess\",\n executablePath: source.path.replace(/\\.0$/, \"\"),\n };\n\n // Step 1: Check the source for errors\n const checkResult = await compiler.check(source);\n\n if (!checkResult.ok) {\n return { errors: checkResult.diagnostics };\n }\n\n // Step 2: Build (only with subprocess compiler)\n if (execution.mode === \"subprocess\" && compiler instanceof ZeroCompiler) {\n const buildResult = await compiler.build(source, {\n ...options?.build,\n out: options?.build?.out ?? execution.executablePath,\n });\n\n if (!buildResult.ok || !buildResult.outputPath) {\n return {\n errors: buildResult.diagnostics.length > 0\n ? buildResult.diagnostics\n : [\n {\n code: \"ZERO_BUILD_FAILED\",\n severity: \"error\",\n message: \"Build produced no output\",\n line: 0,\n },\n ],\n };\n }\n\n // Update execution path to the built binary\n execution.executablePath = buildResult.outputPath;\n }\n\n // Step 3: Discover functions via graph\n const graphResult = await compiler.graph(source);\n\n // Step 4: Register each function\n const tools: OrigenTool[] = graphResult.functions.map((f) =>\n createZeroTool({\n functionName: f.name,\n description: `Zero function: ${f.name}`,\n execution,\n compiler,\n }),\n );\n\n return { tools };\n}\n\n// ── Tool execution ───────────────────────────────────────────────────────\n\n/** Execute a tool based on the execution mode. */\nasync function executeTool(\n execution: ZeroToolExecution,\n args: Record<string, unknown>,\n): Promise<string> {\n switch (execution.mode) {\n case \"subprocess\":\n return executeBinary(execution.executablePath, args);\n case \"http\":\n return executeHTTP(execution, args);\n case \"wasm\": {\n const { createZeroWASMTool } = await import(\"./wasm-tool.js\");\n const tool = createZeroWASMTool({\n functionName: \"main\",\n description: \"Zero WASM tool\",\n wasmBytes: execution.wasmBytes,\n });\n return tool.execute(args, async () => null as any);\n }\n }\n}\n\n/** Execute a compiled Zero binary with JSON args via stdin. */\nasync function executeBinary(\n executablePath: string,\n args: Record<string, unknown>,\n): Promise<string> {\n const { execFile } = await import(\"node:child_process\");\n const stdin = JSON.stringify(args);\n\n return new Promise((resolve, reject) => {\n const child = execFile(\n executablePath,\n [],\n {\n maxBuffer: 1024 * 1024, // 1MB\n },\n (error, stdout, stderr) => {\n if (error) {\n reject(\n new ZeroExecutionError(\n ((error as any).code as number) ?? 1,\n stderr || error.message,\n ),\n );\n return;\n }\n resolve(stdout);\n },\n );\n\n // Pipe input via stdin\n if (child.stdin) {\n child.stdin.write(stdin, () => {\n child.stdin?.end();\n });\n }\n });\n}\n\n/** Execute a Zero function via HTTP. */\nasync function executeHTTP(\n execution: ZeroToolExecution & { mode: \"http\" },\n args: Record<string, unknown>,\n): Promise<string> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...execution.headers,\n };\n if (execution.apiKey) {\n headers[\"Authorization\"] = execution.apiKey;\n }\n\n const fetchFn = execution.fetch ?? globalThis.fetch;\n const url = `${execution.endpoint.replace(/\\/+$/, \"\")}/execute`;\n\n const res = await fetchFn(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(args),\n });\n\n if (!res.ok) {\n throw new ZeroHTTPError(res.status, url, await res.text());\n }\n\n return await res.text();\n}\n\n// ── Compiler resolution ──────────────────────────────────────────────────\n\n/** Resolve a compiler config or instance to a ZeroCompilerLike. */\nfunction resolveCompiler(\n compiler?: ZeroCompilerLike | ZeroCompilerConfig,\n): ZeroCompilerLike {\n if (!compiler) return new ZeroCompiler();\n if (\"check\" in compiler && typeof compiler.check === \"function\") {\n return compiler as ZeroCompilerLike;\n }\n return new ZeroCompiler(compiler as ZeroCompilerConfig);\n}"],"mappings":";;;;;;;;;AAmCO,SAAS,eAAe,QAAoC;AACjE,SAAO;AAAA,IACL,MAAM,OAAO;AAAA,IACb,aAAa,OAAO;AAAA,IACpB,YAAY,OAAO,cAAc;AAAA,MAC/B,MAAM;AAAA,MACN,YAAY,CAAC;AAAA,MACb,UAAU,CAAC;AAAA,IACb;AAAA,IACA,aAAa,OAAO;AAAA,IACpB,MAAM,QAAQ,MAAgD;AAC5D,aAAO,YAAY,OAAO,WAAW,IAAI;AAAA,IAC3C;AAAA,EACF;AACF;AASA,eAAsB,2BACpB,WACA,SAIuB;AACvB,QAAM,WAAW,gBAAgB,SAAS,QAAQ;AAGlD,QAAM,SACJ,UAAU,SAAS,eACf,EAAE,MAAM,UAAU,eAAe,IACjC,EAAE,MAAM,YAAY;AAE1B,QAAM,cAAc,MAAM,SAAS,MAAM,MAAM;AAC/C,QAAM,gBAAgB,YAAY,UAAU,IAAI,OAAK,EAAE,IAAI;AAE3D,SAAO,cAAc;AAAA,IAAI,CAAC,OACxB,eAAe;AAAA,MACb,cAAc;AAAA,MACd,aAAa,kBAAkB,EAAE;AAAA,MACjC;AAAA,MACA;AAAA,MACA,QAAQ,SAAS;AAAA,IACnB,CAAC;AAAA,EACH;AACF;AAaA,eAAsB,mBACpB,QACA,SAKoE;AACpE,QAAM,WAAW,gBAAgB,SAAS,QAAQ;AAClD,QAAM,YAA+B,SAAS,aAAa;AAAA,IACzD,MAAM;AAAA,IACN,gBAAgB,OAAO,KAAK,QAAQ,QAAQ,EAAE;AAAA,EAChD;AAGA,QAAM,cAAc,MAAM,SAAS,MAAM,MAAM;AAE/C,MAAI,CAAC,YAA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