clicodemode 0.0.0-stage → 0.6.1

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.
package/README.md CHANGED
@@ -1,3 +1,151 @@
1
- # Temporary Holding Version
1
+ # clicodemode (experimental)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Code Mode for JavaScript and TypeScript CLIs. Register the commands your CLI
4
+ already has as operations; an agent then writes one small JavaScript-like
5
+ program that calls and composes them, instead of many separate tool calls.
6
+
7
+ This package is a **thin wrapper around the Go engine compiled to WebAssembly**.
8
+ It is not a native TypeScript interpreter. The Go engine owns parsing,
9
+ language semantics and validation (diagnostics with file:line:col); this
10
+ package only loads it, passes your handlers in and returns its results.
11
+ Status: **experimental**, version 0.6.1. The Go project is the reference.
12
+
13
+ ## Install (no npm registry needed)
14
+
15
+ The package is not published to the npm registry. Pick one:
16
+
17
+ **a) From a GitHub release asset** (the URL is valid once the v0.6.1 release
18
+ exists; the release workflow attaches the tarball produced by `npm pack`
19
+ after the WASM is built):
20
+
21
+ ```sh
22
+ npm install https://github.com/muthuishere/clicodemode/releases/download/v0.6.1/clicodemode-0.6.1.tgz
23
+ ```
24
+
25
+ **b) From source** (needs Go and Node >= 20):
26
+
27
+ ```sh
28
+ git clone https://github.com/muthuishere/clicodemode && cd clicodemode
29
+ bash scripts/build-wasm.sh
30
+ cd npm && npm ci && npm run build
31
+ npm pack # -> clicodemode-0.6.1.tgz, install it anywhere with npm install <path>
32
+ ```
33
+
34
+ `npm run verify-pack` packs the tarball, installs it into a fresh directory
35
+ and runs the two quickstarts below (JS executed, TS type-checked and executed).
36
+
37
+ ## Quickstart (TypeScript)
38
+
39
+ <!-- quickstart-ts -->
40
+ ```ts
41
+ import { createCodeMode } from "clicodemode";
42
+
43
+ const cm = createCodeMode({ version: "1.0.0" });
44
+ cm.register({
45
+ name: "health.check",
46
+ description: "Report service health",
47
+ sideEffects: "none",
48
+ idempotent: true,
49
+ inputSchema: { type: "object", properties: { verbose: { type: "boolean" } } },
50
+ handler: async ({ verbose }) => ({ ok: true, verbose: !!verbose }),
51
+ });
52
+
53
+ const caps = await cm.capabilities(); // cache by caps.fingerprint
54
+ const bad = await cm.check("class A {}"); // diagnostics carry file:line:col
55
+ console.log("fingerprint:", caps.fingerprint.length > 0, "check ok:", bad.ok);
56
+
57
+ const r = await cm.run(
58
+ "const h = await ops.health.check({verbose: input.v}); h.ok",
59
+ { input: { v: true }, timeoutMs: 5000 },
60
+ );
61
+ console.log("run:", r.ok, r.value);
62
+ ```
63
+
64
+ ## Quickstart (JavaScript, ESM)
65
+
66
+ <!-- quickstart-js -->
67
+ ```js
68
+ import { createCodeMode } from "clicodemode";
69
+
70
+ const cm = createCodeMode({ version: "1.0.0" });
71
+ cm.register({
72
+ name: "health.check",
73
+ description: "Report service health",
74
+ sideEffects: "none",
75
+ idempotent: true,
76
+ inputSchema: { type: "object", properties: { verbose: { type: "boolean" } } },
77
+ handler: async ({ verbose }) => ({ ok: true, verbose: !!verbose }),
78
+ });
79
+
80
+ const caps = await cm.capabilities(); // cache by caps.fingerprint
81
+ const bad = await cm.check("class A {}"); // diagnostics carry file:line:col
82
+ console.log("fingerprint:", caps.fingerprint.length > 0, "check ok:", bad.ok);
83
+
84
+ const r = await cm.run(
85
+ "const h = await ops.health.check({verbose: input.v}); h.ok",
86
+ { input: { v: true }, timeoutMs: 5000 },
87
+ );
88
+ console.log("run:", r.ok, r.value);
89
+ ```
90
+
91
+ ## API
92
+
93
+ `register`, `operations`, `describe`, `capabilities`, `docs`, `skill`,
94
+ `check`, `compile`, `run(src, {file, input, timeoutMs, signal})`,
95
+ `eval(expr, {input, timeoutMs, signal})`. `run`/`eval` return
96
+ `{ok, value, error, diagnostics, ms, stdout}`.
97
+
98
+ - Handlers that throw or reject make the program's call reject; the program can `try/catch` it.
99
+ - Object results from handlers keep key order as the program sees it.
100
+ - Operations may be registered before the WASM loads; it loads lazily on the
101
+ first call. Registering after the first call rebuilds the engine with the full op set.
102
+
103
+ ### Timeouts and cancellation
104
+
105
+ `timeoutMs` defaults to **30000** ms per call (`0` = no per-call timeout).
106
+ `signal` is an `AbortSignal`. On timeout or abort the call resolves with
107
+ `ok: false` and any host handler promise still pending is abandoned (a
108
+ handler that never resolves cannot hang the call or keep the process alive).
109
+ The engine stays usable afterwards, and other concurrent calls are unaffected.
110
+
111
+ Limit: WASM has no preemption. Timeout and abort take effect when the program
112
+ is waiting on a host operation (or between calls into one); they cannot
113
+ interrupt a pure CPU loop that never awaits. CPU-bound loops are stopped by
114
+ `limits.max_steps` (engine default 10,000,000 steps, an error, not a hang).
115
+ Set `limits.max_steps` for untrusted programs. `limits.timeout_ms` is also
116
+ available but, being a Go-side timer, can keep the Node process alive until it
117
+ expires.
118
+
119
+ ## Security model
120
+
121
+ - The engine owns language validation: unsupported syntax, unknown operations
122
+ and bad `exec` argv are rejected before anything runs.
123
+ - **The host (your handlers) owns authorization, path and exec security.**
124
+ A program can call exactly the operations you registered, with arguments it
125
+ chooses; validate arguments and enforce permissions inside each handler.
126
+ - `exec` / `shell` are **denied** in this build: the program gets a diagnostic
127
+ such as `running "echo" is not permitted: this host allows no external
128
+ programs`. Run commands, if you need them, from your own handlers.
129
+
130
+ ## Size, startup, and reuse
131
+
132
+ - `dist/codemode.wasm` is about 7.8 MB raw, 2.1 MB gzipped (the npm tarball is
133
+ compressed). Node memory after loading the engine is roughly 120 MB RSS.
134
+ - Cold start (load WASM and run one program) measured about 55 ms on an Apple
135
+ Silicon laptop with Node 24. Treat this as indicative only.
136
+ - **Reuse one engine (`createCodeMode`) per process.** Each engine instance is
137
+ cheap, but program runs are the unit of work; do not create one per call.
138
+ The WASM module itself is loaded once per process.
139
+
140
+ ## Not supported
141
+
142
+ The program language is a JavaScript subset: no `class`, `new`, `this`,
143
+ generators, `switch`, regex, dynamic `import()`. See
144
+ [docs/SPEC.md](../docs/SPEC.md) for the full language and semantics. The
145
+ `policy` option of the Go API is not exposed here.
146
+
147
+ ## Other runtimes
148
+
149
+ The Node loader lives in `src/wasm.ts`; `loadWasm(bytes)` boots the engine from
150
+ bytes once `wasm_exec.js` has defined `globalThis.Go`. A browser or bundler
151
+ entry can fetch the wasm and call it; not shipped yet.
Binary file
@@ -0,0 +1,45 @@
1
+ import type { Capabilities, CheckResult, CodeModeOptions, Operation, OperationSpec, Result } from "./types.js";
2
+ export * from "./types.js";
3
+ export { loadWasm, type Bridge } from "./wasm.js";
4
+ /** Structural subset of the standard AbortSignal (no DOM or @types/node needed). */
5
+ export interface AbortSignalLike {
6
+ readonly aborted: boolean;
7
+ addEventListener(type: "abort", fn: () => void, opts?: {
8
+ once?: boolean;
9
+ }): void;
10
+ removeEventListener(type: "abort", fn: () => void): void;
11
+ }
12
+ /** Default wall-clock bound for one run/eval call, in milliseconds. */
13
+ export declare const DEFAULT_TIMEOUT_MS = 30000;
14
+ export interface CallOptions {
15
+ /** Program input, visible to the program as `input`. */
16
+ input?: unknown;
17
+ /**
18
+ * Bound for this call in ms (default DEFAULT_TIMEOUT_MS = 30000; 0 = none
19
+ * beyond the engine's own limits.timeout_ms). On expiry the call resolves
20
+ * with ok:false and pending host handlers are abandoned. Caveat: WASM has
21
+ * no preemption, so the timeout cannot interrupt a CPU-bound loop that
22
+ * never awaits a host operation; that is bounded by limits.max_steps.
23
+ */
24
+ timeoutMs?: number;
25
+ /** Aborting resolves the call with ok:false and abandons pending host handlers. Like timeoutMs it takes effect when the program awaits a host operation, not inside a pure CPU loop. */
26
+ signal?: AbortSignalLike;
27
+ }
28
+ export interface RunOptions extends CallOptions {
29
+ file?: string;
30
+ }
31
+ export interface EvalOptions extends CallOptions {
32
+ }
33
+ export interface CodeMode {
34
+ register(op: OperationSpec): void;
35
+ operations(): Promise<Operation[]>;
36
+ describe(name: string): Promise<Operation>;
37
+ capabilities(): Promise<Capabilities>;
38
+ docs(): Promise<string>;
39
+ skill(): Promise<string>;
40
+ check(src: string, file?: string): Promise<CheckResult>;
41
+ compile(src: string, file?: string): Promise<CheckResult>;
42
+ run(src: string, opts?: RunOptions): Promise<Result>;
43
+ eval(expr: string, opts?: EvalOptions): Promise<Result>;
44
+ }
45
+ export declare function createCodeMode(options: CodeModeOptions): CodeMode;
package/dist/index.js ADDED
@@ -0,0 +1,119 @@
1
+ import { getBridge } from "./wasm.js";
2
+ export * from "./types.js";
3
+ export { loadWasm } from "./wasm.js";
4
+ /** Default wall-clock bound for one run/eval call, in milliseconds. */
5
+ export const DEFAULT_TIMEOUT_MS = 30_000;
6
+ let callSeq = 0;
7
+ const NAME_RE = /^[a-z][a-z0-9_-]*(\.[a-z][a-z0-9_-]*)*$/;
8
+ function parse(s) {
9
+ const v = JSON.parse(s);
10
+ if (v && typeof v === "object" && !Array.isArray(v) && typeof v.error === "string" && Object.keys(v).length === 1) {
11
+ throw new Error("clicodemode: " + v.error); // bridge reports bad id / unknown op as {"error":...}
12
+ }
13
+ return v;
14
+ }
15
+ function withOk(r) {
16
+ const ds = r.diagnostics ?? [];
17
+ return { ...r, diagnostics: ds, ok: !ds.some((d) => d.severity === "error") };
18
+ }
19
+ /** Parse bridge output; a non-JSON string (docs/skill text) is returned as is. */
20
+ function text(s) {
21
+ return s;
22
+ }
23
+ export function createCodeMode(options) {
24
+ const specs = new Map();
25
+ let id;
26
+ let bridgeP;
27
+ const invoke = async (name, argsJson) => {
28
+ const spec = specs.get(name);
29
+ if (!spec)
30
+ throw new Error(`unknown operation ${name}`);
31
+ const args = argsJson ? JSON.parse(argsJson) : {};
32
+ const out = await spec.handler(args ?? {});
33
+ return JSON.stringify(out === undefined ? null : out);
34
+ };
35
+ const config = () => ({
36
+ version: options.version,
37
+ operations: [...specs.values()].map((s) => ({
38
+ name: s.name,
39
+ description: s.description,
40
+ input_schema: s.inputSchema,
41
+ output_schema: s.outputSchema,
42
+ side_effects: s.sideEffects ?? "local",
43
+ idempotent: s.idempotent ?? false,
44
+ authorization: s.authorization,
45
+ examples: s.examples,
46
+ })),
47
+ limits: options.limits,
48
+ moduleRoot: options.moduleRoot,
49
+ });
50
+ // Engine is created lazily on first call, with every op registered so far.
51
+ async function ready() {
52
+ bridgeP ??= getBridge();
53
+ const b = await bridgeP;
54
+ if (id === undefined) {
55
+ const made = b.create(JSON.stringify(config()), invoke);
56
+ if (typeof made !== "number") {
57
+ throw new Error("clicodemode: engine creation failed: " + (made?.error ?? String(made)));
58
+ }
59
+ id = made;
60
+ }
61
+ return { b, id };
62
+ }
63
+ // Runs one call under a callId so signal/timeout can cancel it in the engine.
64
+ async function call(opts, start) {
65
+ const { signal } = opts;
66
+ const aborted = () => ({ ok: false, value: null, error: "aborted", ms: 0 });
67
+ if (signal?.aborted)
68
+ return aborted();
69
+ const { b, id } = await ready();
70
+ if (signal?.aborted)
71
+ return aborted();
72
+ const callId = `c${++callSeq}`;
73
+ const t = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
74
+ if (!(t >= 0))
75
+ throw new Error("clicodemode: timeoutMs must be >= 0");
76
+ const onAbort = () => { b.cancel(callId); };
77
+ signal?.addEventListener("abort", onAbort, { once: true });
78
+ // The timer lives on the JS side: a Go-side timer would keep the Node
79
+ // process alive until it expires even after the call finished.
80
+ let timedOut = false;
81
+ const timer = t > 0 ? setTimeout(() => { timedOut = true; b.cancel(callId); }, t) : undefined;
82
+ try {
83
+ const r = parse(await start(b, id, callId));
84
+ if (timedOut && !r.ok)
85
+ r.error = `timed out after ${t}ms (${r.error ?? "cancelled"})`;
86
+ return r;
87
+ }
88
+ finally {
89
+ if (timer !== undefined)
90
+ clearTimeout(timer);
91
+ signal?.removeEventListener("abort", onAbort);
92
+ }
93
+ }
94
+ return {
95
+ register(op) {
96
+ if (!NAME_RE.test(op.name))
97
+ throw new Error(`clicodemode: invalid operation name "${op.name}" (want dotted lower-case, e.g. health.check)`);
98
+ if (typeof op.handler !== "function")
99
+ throw new Error(`clicodemode: operation "${op.name}" has no handler`);
100
+ if (specs.has(op.name))
101
+ throw new Error(`clicodemode: operation "${op.name}" already registered`);
102
+ specs.set(op.name, op);
103
+ id = undefined; // engine is rebuilt with the new op set on the next call
104
+ },
105
+ async operations() { const { b, id } = await ready(); return parse(b.operations(id)); },
106
+ async describe(name) { const { b, id } = await ready(); return parse(b.describe(id, name)); },
107
+ async capabilities() { const { b, id } = await ready(); return parse(b.capabilities(id)); },
108
+ async docs() { const { b, id } = await ready(); return text(b.docs(id)); },
109
+ async skill() { const { b, id } = await ready(); return text(b.skill(id)); },
110
+ async check(src, file = "<program>") { const { b, id } = await ready(); return withOk(parse(b.check(id, src, file))); },
111
+ async compile(src, file = "<program>") { const { b, id } = await ready(); return withOk(parse(b.compile(id, src, file))); },
112
+ run(src, opts = {}) {
113
+ return call(opts, (b, id, callId) => b.run(id, src, opts.file ?? "<program>", JSON.stringify(opts.input ?? null), callId));
114
+ },
115
+ eval(expr, opts = {}) {
116
+ return call(opts, (b, id, callId) => b.eval(id, expr, JSON.stringify(opts.input ?? null), callId));
117
+ },
118
+ };
119
+ }
@@ -0,0 +1,85 @@
1
+ export type SideEffect = "none" | "local" | "external";
2
+ export interface Example {
3
+ description?: string;
4
+ args?: Record<string, unknown>;
5
+ result?: unknown;
6
+ }
7
+ export type Handler = (args: Record<string, any>) => unknown | Promise<unknown>;
8
+ /** What you pass to register(). Mirrors Go codemode.Operation. */
9
+ export interface OperationSpec {
10
+ name: string;
11
+ description: string;
12
+ inputSchema?: unknown;
13
+ outputSchema?: unknown;
14
+ sideEffects?: SideEffect;
15
+ idempotent?: boolean;
16
+ authorization?: string;
17
+ examples?: Example[];
18
+ handler: Handler;
19
+ }
20
+ /** Operation as the engine reports it (Go JSON, snake_case). */
21
+ export interface Operation {
22
+ name: string;
23
+ description: string;
24
+ input_schema?: unknown;
25
+ output_schema?: unknown;
26
+ side_effects: SideEffect;
27
+ idempotent: boolean;
28
+ authorization?: string;
29
+ examples?: Example[];
30
+ }
31
+ export interface Diagnostic {
32
+ severity: "error" | "warning";
33
+ file: string;
34
+ line: number;
35
+ col: number;
36
+ message: string;
37
+ hint?: string;
38
+ }
39
+ export interface LanguageInfo {
40
+ name: string;
41
+ features: string[];
42
+ unsupported: string[];
43
+ globals: string[];
44
+ }
45
+ export interface Capabilities {
46
+ spec: string;
47
+ version: string;
48
+ fingerprint: string;
49
+ language: LanguageInfo;
50
+ operations: Operation[];
51
+ }
52
+ export interface Result {
53
+ ok: boolean;
54
+ value: unknown;
55
+ error?: string;
56
+ diagnostics?: Diagnostic[];
57
+ ms: number;
58
+ /** print/console.log output of the program. */
59
+ stdout?: string;
60
+ }
61
+ /** Result of check(): diagnostics plus the operations the program uses. */
62
+ export interface CheckResult {
63
+ ok: boolean;
64
+ diagnostics?: Diagnostic[];
65
+ /** compile() only: program metadata (null on a parse error). */
66
+ program?: {
67
+ file: string;
68
+ hash: string;
69
+ imports: string[] | null;
70
+ operations: string[] | null;
71
+ cache_key: string;
72
+ } | null;
73
+ [k: string]: unknown;
74
+ }
75
+ export interface Limits {
76
+ max_steps?: number;
77
+ max_call_depth?: number;
78
+ max_concurrency?: number;
79
+ timeout_ms?: number;
80
+ }
81
+ export interface CodeModeOptions {
82
+ version: string;
83
+ limits?: Limits;
84
+ moduleRoot?: string;
85
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/wasm.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ /** The string-in/string-out bridge the Go side installs on globalThis.__codemode. */
2
+ export interface Bridge {
3
+ create(configJson: string, invoke: (name: string, argsJson: string) => Promise<string>): number | string;
4
+ operations(id: number | string): string;
5
+ describe(id: number | string, name: string): string;
6
+ capabilities(id: number | string): string;
7
+ check(id: number | string, src: string, file: string): string;
8
+ compile(id: number | string, src: string, file: string): string;
9
+ docs(id: number | string): string;
10
+ skill(id: number | string): string;
11
+ version(): string;
12
+ run(id: number | string, src: string, file: string, inputJson: string, callId?: string, timeoutMs?: string): Promise<string>;
13
+ eval(id: number | string, expr: string, inputJson: string, callId?: string, timeoutMs?: string): Promise<string>;
14
+ /** Abort the running call named callId; true if one was running. */
15
+ cancel(callId: string): boolean;
16
+ }
17
+ /**
18
+ * Seam for other runtimes: give it the wasm bytes and it boots the Go runtime.
19
+ * A browser/bundler entry can fetch() the bytes and import wasm_exec.js itself,
20
+ * then call this.
21
+ */
22
+ export declare function loadWasm(bytes: Uint8Array | ArrayBuffer): Promise<Bridge>;
23
+ /** Node ESM loader; one wasm module per process. */
24
+ export declare function getBridge(): Promise<Bridge>;
package/dist/wasm.js ADDED
@@ -0,0 +1,33 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ let bridge;
4
+ /**
5
+ * Seam for other runtimes: give it the wasm bytes and it boots the Go runtime.
6
+ * A browser/bundler entry can fetch() the bytes and import wasm_exec.js itself,
7
+ * then call this.
8
+ */
9
+ export async function loadWasm(bytes) {
10
+ const g = globalThis;
11
+ if (!g.Go)
12
+ throw new Error("clicodemode: wasm_exec.js has not defined globalThis.Go");
13
+ const go = new g.Go();
14
+ const { instance } = await WebAssembly.instantiate(bytes, go.importObject);
15
+ void go.run(instance); // never resolves while the bridge is alive
16
+ for (let i = 0; i < 2000 && !g.__codemode; i++)
17
+ await new Promise((r) => setTimeout(r, 5));
18
+ if (!g.__codemode)
19
+ throw new Error("clicodemode: wasm started but globalThis.__codemode never appeared");
20
+ return g.__codemode;
21
+ }
22
+ /** Node ESM loader; one wasm module per process. */
23
+ export function getBridge() {
24
+ bridge ??= (async () => {
25
+ if (globalThis.__codemode)
26
+ return globalThis.__codemode;
27
+ await import("./wasm_exec.js");
28
+ const wasmPath = fileURLToPath(new URL("./codemode.wasm", import.meta.url));
29
+ return loadWasm(readFileSync(wasmPath));
30
+ })();
31
+ bridge.catch(() => { bridge = undefined; });
32
+ return bridge;
33
+ }
@@ -0,0 +1,575 @@
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ "use strict";
6
+
7
+ (() => {
8
+ const enosys = () => {
9
+ const err = new Error("not implemented");
10
+ err.code = "ENOSYS";
11
+ return err;
12
+ };
13
+
14
+ if (!globalThis.fs) {
15
+ let outputBuf = "";
16
+ globalThis.fs = {
17
+ constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused
18
+ writeSync(fd, buf) {
19
+ outputBuf += decoder.decode(buf);
20
+ const nl = outputBuf.lastIndexOf("\n");
21
+ if (nl != -1) {
22
+ console.log(outputBuf.substring(0, nl));
23
+ outputBuf = outputBuf.substring(nl + 1);
24
+ }
25
+ return buf.length;
26
+ },
27
+ write(fd, buf, offset, length, position, callback) {
28
+ if (offset !== 0 || length !== buf.length || position !== null) {
29
+ callback(enosys());
30
+ return;
31
+ }
32
+ const n = this.writeSync(fd, buf);
33
+ callback(null, n);
34
+ },
35
+ chmod(path, mode, callback) { callback(enosys()); },
36
+ chown(path, uid, gid, callback) { callback(enosys()); },
37
+ close(fd, callback) { callback(enosys()); },
38
+ fchmod(fd, mode, callback) { callback(enosys()); },
39
+ fchown(fd, uid, gid, callback) { callback(enosys()); },
40
+ fstat(fd, callback) { callback(enosys()); },
41
+ fsync(fd, callback) { callback(null); },
42
+ ftruncate(fd, length, callback) { callback(enosys()); },
43
+ lchown(path, uid, gid, callback) { callback(enosys()); },
44
+ link(path, link, callback) { callback(enosys()); },
45
+ lstat(path, callback) { callback(enosys()); },
46
+ mkdir(path, perm, callback) { callback(enosys()); },
47
+ open(path, flags, mode, callback) { callback(enosys()); },
48
+ read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
49
+ readdir(path, callback) { callback(enosys()); },
50
+ readlink(path, callback) { callback(enosys()); },
51
+ rename(from, to, callback) { callback(enosys()); },
52
+ rmdir(path, callback) { callback(enosys()); },
53
+ stat(path, callback) { callback(enosys()); },
54
+ symlink(path, link, callback) { callback(enosys()); },
55
+ truncate(path, length, callback) { callback(enosys()); },
56
+ unlink(path, callback) { callback(enosys()); },
57
+ utimes(path, atime, mtime, callback) { callback(enosys()); },
58
+ };
59
+ }
60
+
61
+ if (!globalThis.process) {
62
+ globalThis.process = {
63
+ getuid() { return -1; },
64
+ getgid() { return -1; },
65
+ geteuid() { return -1; },
66
+ getegid() { return -1; },
67
+ getgroups() { throw enosys(); },
68
+ pid: -1,
69
+ ppid: -1,
70
+ umask() { throw enosys(); },
71
+ cwd() { throw enosys(); },
72
+ chdir() { throw enosys(); },
73
+ }
74
+ }
75
+
76
+ if (!globalThis.path) {
77
+ globalThis.path = {
78
+ resolve(...pathSegments) {
79
+ return pathSegments.join("/");
80
+ }
81
+ }
82
+ }
83
+
84
+ if (!globalThis.crypto) {
85
+ throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
86
+ }
87
+
88
+ if (!globalThis.performance) {
89
+ throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
90
+ }
91
+
92
+ if (!globalThis.TextEncoder) {
93
+ throw new Error("globalThis.TextEncoder is not available, polyfill required");
94
+ }
95
+
96
+ if (!globalThis.TextDecoder) {
97
+ throw new Error("globalThis.TextDecoder is not available, polyfill required");
98
+ }
99
+
100
+ const encoder = new TextEncoder("utf-8");
101
+ const decoder = new TextDecoder("utf-8");
102
+
103
+ globalThis.Go = class {
104
+ constructor() {
105
+ this.argv = ["js"];
106
+ this.env = {};
107
+ this.exit = (code) => {
108
+ if (code !== 0) {
109
+ console.warn("exit code:", code);
110
+ }
111
+ };
112
+ this._exitPromise = new Promise((resolve) => {
113
+ this._resolveExitPromise = resolve;
114
+ });
115
+ this._pendingEvent = null;
116
+ this._scheduledTimeouts = new Map();
117
+ this._nextCallbackTimeoutID = 1;
118
+
119
+ const setInt64 = (addr, v) => {
120
+ this.mem.setUint32(addr + 0, v, true);
121
+ this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
122
+ }
123
+
124
+ const setInt32 = (addr, v) => {
125
+ this.mem.setUint32(addr + 0, v, true);
126
+ }
127
+
128
+ const getInt64 = (addr) => {
129
+ const low = this.mem.getUint32(addr + 0, true);
130
+ const high = this.mem.getInt32(addr + 4, true);
131
+ return low + high * 4294967296;
132
+ }
133
+
134
+ const loadValue = (addr) => {
135
+ const f = this.mem.getFloat64(addr, true);
136
+ if (f === 0) {
137
+ return undefined;
138
+ }
139
+ if (!isNaN(f)) {
140
+ return f;
141
+ }
142
+
143
+ const id = this.mem.getUint32(addr, true);
144
+ return this._values[id];
145
+ }
146
+
147
+ const storeValue = (addr, v) => {
148
+ const nanHead = 0x7FF80000;
149
+
150
+ if (typeof v === "number" && v !== 0) {
151
+ if (isNaN(v)) {
152
+ this.mem.setUint32(addr + 4, nanHead, true);
153
+ this.mem.setUint32(addr, 0, true);
154
+ return;
155
+ }
156
+ this.mem.setFloat64(addr, v, true);
157
+ return;
158
+ }
159
+
160
+ if (v === undefined) {
161
+ this.mem.setFloat64(addr, 0, true);
162
+ return;
163
+ }
164
+
165
+ let id = this._ids.get(v);
166
+ if (id === undefined) {
167
+ id = this._idPool.pop();
168
+ if (id === undefined) {
169
+ id = this._values.length;
170
+ }
171
+ this._values[id] = v;
172
+ this._goRefCounts[id] = 0;
173
+ this._ids.set(v, id);
174
+ }
175
+ this._goRefCounts[id]++;
176
+ let typeFlag = 0;
177
+ switch (typeof v) {
178
+ case "object":
179
+ if (v !== null) {
180
+ typeFlag = 1;
181
+ }
182
+ break;
183
+ case "string":
184
+ typeFlag = 2;
185
+ break;
186
+ case "symbol":
187
+ typeFlag = 3;
188
+ break;
189
+ case "function":
190
+ typeFlag = 4;
191
+ break;
192
+ }
193
+ this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
194
+ this.mem.setUint32(addr, id, true);
195
+ }
196
+
197
+ const loadSlice = (addr) => {
198
+ const array = getInt64(addr + 0);
199
+ const len = getInt64(addr + 8);
200
+ return new Uint8Array(this._inst.exports.mem.buffer, array, len);
201
+ }
202
+
203
+ const loadSliceOfValues = (addr) => {
204
+ const array = getInt64(addr + 0);
205
+ const len = getInt64(addr + 8);
206
+ const a = new Array(len);
207
+ for (let i = 0; i < len; i++) {
208
+ a[i] = loadValue(array + i * 8);
209
+ }
210
+ return a;
211
+ }
212
+
213
+ const loadString = (addr) => {
214
+ const saddr = getInt64(addr + 0);
215
+ const len = getInt64(addr + 8);
216
+ return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
217
+ }
218
+
219
+ const testCallExport = (a, b) => {
220
+ this._inst.exports.testExport0();
221
+ return this._inst.exports.testExport(a, b);
222
+ }
223
+
224
+ const timeOrigin = Date.now() - performance.now();
225
+ this.importObject = {
226
+ _gotest: {
227
+ add: (a, b) => a + b,
228
+ callExport: testCallExport,
229
+ },
230
+ gojs: {
231
+ // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
232
+ // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
233
+ // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
234
+ // This changes the SP, thus we have to update the SP used by the imported function.
235
+
236
+ // func wasmExit(code int32)
237
+ "runtime.wasmExit": (sp) => {
238
+ sp >>>= 0;
239
+ const code = this.mem.getInt32(sp + 8, true);
240
+ this.exited = true;
241
+ delete this._inst;
242
+ delete this._values;
243
+ delete this._goRefCounts;
244
+ delete this._ids;
245
+ delete this._idPool;
246
+ this.exit(code);
247
+ },
248
+
249
+ // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
250
+ "runtime.wasmWrite": (sp) => {
251
+ sp >>>= 0;
252
+ const fd = getInt64(sp + 8);
253
+ const p = getInt64(sp + 16);
254
+ const n = this.mem.getInt32(sp + 24, true);
255
+ fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
256
+ },
257
+
258
+ // func resetMemoryDataView()
259
+ "runtime.resetMemoryDataView": (sp) => {
260
+ sp >>>= 0;
261
+ this.mem = new DataView(this._inst.exports.mem.buffer);
262
+ },
263
+
264
+ // func nanotime1() int64
265
+ "runtime.nanotime1": (sp) => {
266
+ sp >>>= 0;
267
+ setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
268
+ },
269
+
270
+ // func walltime() (sec int64, nsec int32)
271
+ "runtime.walltime": (sp) => {
272
+ sp >>>= 0;
273
+ const msec = (new Date).getTime();
274
+ setInt64(sp + 8, msec / 1000);
275
+ this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
276
+ },
277
+
278
+ // func scheduleTimeoutEvent(delay int64) int32
279
+ "runtime.scheduleTimeoutEvent": (sp) => {
280
+ sp >>>= 0;
281
+ const id = this._nextCallbackTimeoutID;
282
+ this._nextCallbackTimeoutID++;
283
+ this._scheduledTimeouts.set(id, setTimeout(
284
+ () => {
285
+ this._resume();
286
+ while (this._scheduledTimeouts.has(id)) {
287
+ // for some reason Go failed to register the timeout event, log and try again
288
+ // (temporary workaround for https://github.com/golang/go/issues/28975)
289
+ console.warn("scheduleTimeoutEvent: missed timeout event");
290
+ this._resume();
291
+ }
292
+ },
293
+ getInt64(sp + 8),
294
+ ));
295
+ this.mem.setInt32(sp + 16, id, true);
296
+ },
297
+
298
+ // func clearTimeoutEvent(id int32)
299
+ "runtime.clearTimeoutEvent": (sp) => {
300
+ sp >>>= 0;
301
+ const id = this.mem.getInt32(sp + 8, true);
302
+ clearTimeout(this._scheduledTimeouts.get(id));
303
+ this._scheduledTimeouts.delete(id);
304
+ },
305
+
306
+ // func getRandomData(r []byte)
307
+ "runtime.getRandomData": (sp) => {
308
+ sp >>>= 0;
309
+ crypto.getRandomValues(loadSlice(sp + 8));
310
+ },
311
+
312
+ // func finalizeRef(v ref)
313
+ "syscall/js.finalizeRef": (sp) => {
314
+ sp >>>= 0;
315
+ const id = this.mem.getUint32(sp + 8, true);
316
+ this._goRefCounts[id]--;
317
+ if (this._goRefCounts[id] === 0) {
318
+ const v = this._values[id];
319
+ this._values[id] = null;
320
+ this._ids.delete(v);
321
+ this._idPool.push(id);
322
+ }
323
+ },
324
+
325
+ // func stringVal(value string) ref
326
+ "syscall/js.stringVal": (sp) => {
327
+ sp >>>= 0;
328
+ storeValue(sp + 24, loadString(sp + 8));
329
+ },
330
+
331
+ // func valueGet(v ref, p string) ref
332
+ "syscall/js.valueGet": (sp) => {
333
+ sp >>>= 0;
334
+ const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
335
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
336
+ storeValue(sp + 32, result);
337
+ },
338
+
339
+ // func valueSet(v ref, p string, x ref)
340
+ "syscall/js.valueSet": (sp) => {
341
+ sp >>>= 0;
342
+ Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
343
+ },
344
+
345
+ // func valueDelete(v ref, p string)
346
+ "syscall/js.valueDelete": (sp) => {
347
+ sp >>>= 0;
348
+ Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
349
+ },
350
+
351
+ // func valueIndex(v ref, i int) ref
352
+ "syscall/js.valueIndex": (sp) => {
353
+ sp >>>= 0;
354
+ storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
355
+ },
356
+
357
+ // valueSetIndex(v ref, i int, x ref)
358
+ "syscall/js.valueSetIndex": (sp) => {
359
+ sp >>>= 0;
360
+ Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
361
+ },
362
+
363
+ // func valueCall(v ref, m string, args []ref) (ref, bool)
364
+ "syscall/js.valueCall": (sp) => {
365
+ sp >>>= 0;
366
+ try {
367
+ const v = loadValue(sp + 8);
368
+ const m = Reflect.get(v, loadString(sp + 16));
369
+ const args = loadSliceOfValues(sp + 32);
370
+ const result = Reflect.apply(m, v, args);
371
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
372
+ storeValue(sp + 56, result);
373
+ this.mem.setUint8(sp + 64, 1);
374
+ } catch (err) {
375
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
376
+ storeValue(sp + 56, err);
377
+ this.mem.setUint8(sp + 64, 0);
378
+ }
379
+ },
380
+
381
+ // func valueInvoke(v ref, args []ref) (ref, bool)
382
+ "syscall/js.valueInvoke": (sp) => {
383
+ sp >>>= 0;
384
+ try {
385
+ const v = loadValue(sp + 8);
386
+ const args = loadSliceOfValues(sp + 16);
387
+ const result = Reflect.apply(v, undefined, args);
388
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
389
+ storeValue(sp + 40, result);
390
+ this.mem.setUint8(sp + 48, 1);
391
+ } catch (err) {
392
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
393
+ storeValue(sp + 40, err);
394
+ this.mem.setUint8(sp + 48, 0);
395
+ }
396
+ },
397
+
398
+ // func valueNew(v ref, args []ref) (ref, bool)
399
+ "syscall/js.valueNew": (sp) => {
400
+ sp >>>= 0;
401
+ try {
402
+ const v = loadValue(sp + 8);
403
+ const args = loadSliceOfValues(sp + 16);
404
+ const result = Reflect.construct(v, args);
405
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
406
+ storeValue(sp + 40, result);
407
+ this.mem.setUint8(sp + 48, 1);
408
+ } catch (err) {
409
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
410
+ storeValue(sp + 40, err);
411
+ this.mem.setUint8(sp + 48, 0);
412
+ }
413
+ },
414
+
415
+ // func valueLength(v ref) int
416
+ "syscall/js.valueLength": (sp) => {
417
+ sp >>>= 0;
418
+ setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
419
+ },
420
+
421
+ // valuePrepareString(v ref) (ref, int)
422
+ "syscall/js.valuePrepareString": (sp) => {
423
+ sp >>>= 0;
424
+ const str = encoder.encode(String(loadValue(sp + 8)));
425
+ storeValue(sp + 16, str);
426
+ setInt64(sp + 24, str.length);
427
+ },
428
+
429
+ // valueLoadString(v ref, b []byte)
430
+ "syscall/js.valueLoadString": (sp) => {
431
+ sp >>>= 0;
432
+ const str = loadValue(sp + 8);
433
+ loadSlice(sp + 16).set(str);
434
+ },
435
+
436
+ // func valueInstanceOf(v ref, t ref) bool
437
+ "syscall/js.valueInstanceOf": (sp) => {
438
+ sp >>>= 0;
439
+ this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
440
+ },
441
+
442
+ // func copyBytesToGo(dst []byte, src ref) (int, bool)
443
+ "syscall/js.copyBytesToGo": (sp) => {
444
+ sp >>>= 0;
445
+ const dst = loadSlice(sp + 8);
446
+ const src = loadValue(sp + 32);
447
+ if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
448
+ this.mem.setUint8(sp + 48, 0);
449
+ return;
450
+ }
451
+ const toCopy = src.subarray(0, dst.length);
452
+ dst.set(toCopy);
453
+ setInt64(sp + 40, toCopy.length);
454
+ this.mem.setUint8(sp + 48, 1);
455
+ },
456
+
457
+ // func copyBytesToJS(dst ref, src []byte) (int, bool)
458
+ "syscall/js.copyBytesToJS": (sp) => {
459
+ sp >>>= 0;
460
+ const dst = loadValue(sp + 8);
461
+ const src = loadSlice(sp + 16);
462
+ if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
463
+ this.mem.setUint8(sp + 48, 0);
464
+ return;
465
+ }
466
+ const toCopy = src.subarray(0, dst.length);
467
+ dst.set(toCopy);
468
+ setInt64(sp + 40, toCopy.length);
469
+ this.mem.setUint8(sp + 48, 1);
470
+ },
471
+
472
+ "debug": (value) => {
473
+ console.log(value);
474
+ },
475
+ }
476
+ };
477
+ }
478
+
479
+ async run(instance) {
480
+ if (!(instance instanceof WebAssembly.Instance)) {
481
+ throw new Error("Go.run: WebAssembly.Instance expected");
482
+ }
483
+ this._inst = instance;
484
+ this.mem = new DataView(this._inst.exports.mem.buffer);
485
+ this._values = [ // JS values that Go currently has references to, indexed by reference id
486
+ NaN,
487
+ 0,
488
+ null,
489
+ true,
490
+ false,
491
+ globalThis,
492
+ this,
493
+ ];
494
+ this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
495
+ this._ids = new Map([ // mapping from JS values to reference ids
496
+ [0, 1],
497
+ [null, 2],
498
+ [true, 3],
499
+ [false, 4],
500
+ [globalThis, 5],
501
+ [this, 6],
502
+ ]);
503
+ this._idPool = []; // unused ids that have been garbage collected
504
+ this.exited = false; // whether the Go program has exited
505
+
506
+ // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
507
+ let offset = 4096;
508
+
509
+ const strPtr = (str) => {
510
+ const ptr = offset;
511
+ const bytes = encoder.encode(str + "\0");
512
+ new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
513
+ offset += bytes.length;
514
+ if (offset % 8 !== 0) {
515
+ offset += 8 - (offset % 8);
516
+ }
517
+ return ptr;
518
+ };
519
+
520
+ const argc = this.argv.length;
521
+
522
+ const argvPtrs = [];
523
+ this.argv.forEach((arg) => {
524
+ argvPtrs.push(strPtr(arg));
525
+ });
526
+ argvPtrs.push(0);
527
+
528
+ const keys = Object.keys(this.env).sort();
529
+ keys.forEach((key) => {
530
+ argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
531
+ });
532
+ argvPtrs.push(0);
533
+
534
+ const argv = offset;
535
+ argvPtrs.forEach((ptr) => {
536
+ this.mem.setUint32(offset, ptr, true);
537
+ this.mem.setUint32(offset + 4, 0, true);
538
+ offset += 8;
539
+ });
540
+
541
+ // The linker guarantees global data starts from at least wasmMinDataAddr.
542
+ // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
543
+ const wasmMinDataAddr = 4096 + 8192;
544
+ if (offset >= wasmMinDataAddr) {
545
+ throw new Error("total length of command line and environment variables exceeds limit");
546
+ }
547
+
548
+ this._inst.exports.run(argc, argv);
549
+ if (this.exited) {
550
+ this._resolveExitPromise();
551
+ }
552
+ await this._exitPromise;
553
+ }
554
+
555
+ _resume() {
556
+ if (this.exited) {
557
+ throw new Error("Go program has already exited");
558
+ }
559
+ this._inst.exports.resume();
560
+ if (this.exited) {
561
+ this._resolveExitPromise();
562
+ }
563
+ }
564
+
565
+ _makeFuncWrapper(id) {
566
+ const go = this;
567
+ return function () {
568
+ const event = { id: id, this: this, args: arguments };
569
+ go._pendingEvent = event;
570
+ go._resume();
571
+ return event.result;
572
+ };
573
+ }
574
+ }
575
+ })();
@@ -0,0 +1,17 @@
1
+ import { createCodeMode } from "../dist/index.js";
2
+
3
+ const cm = createCodeMode({ version: "1.0.0" });
4
+ cm.register({
5
+ name: "demo.add",
6
+ description: "Add two numbers",
7
+ sideEffects: "none",
8
+ idempotent: true,
9
+ handler: async ({ a, b }) => ({ sum: a + b }),
10
+ });
11
+
12
+ console.log((await cm.capabilities()).fingerprint);
13
+ const r = await cm.run(`
14
+ const rs = await pmap([1, 2, 3], (n) => ops.demo.add({ a: n, b: input.offset }), { concurrency: 2 });
15
+ rs.map((x) => x.sum)
16
+ `, { input: { offset: 10 } });
17
+ console.log(r.ok, r.value);
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "clicodemode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.1",
4
+ "description": "Code Mode for JS and TS CLIs: register your commands as operations, agents run a small JavaScript-like program that calls them. Engine is Go compiled to WASM.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./codemode.wasm": "./dist/codemode.wasm",
14
+ "./package.json": "./package.json"
15
+ },
16
+ "files": [
17
+ "dist/*.js",
18
+ "dist/*.d.ts",
19
+ "dist/codemode.wasm",
20
+ "README.md",
21
+ "examples"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.json",
28
+ "build:wasm": "bash ../scripts/build-wasm.sh",
29
+ "test": "npm run build && node --test test/*.test.mjs",
30
+ "verify-pack": "node scripts/verify-pack.mjs"
31
+ },
32
+ "devDependencies": {
33
+ "typescript": "^5.6.0"
34
+ },
35
+ "license": "MIT",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/muthuishere/clicodemode.git",
39
+ "directory": "npm"
40
+ },
41
+ "homepage": "https://muthuishere.github.io/clicodemode/",
42
+ "bugs": {
43
+ "url": "https://github.com/muthuishere/clicodemode/issues"
44
+ }
45
+ }