nanoodle 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nanoodle contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,150 @@
1
+ # nanoodle
2
+
3
+ **Run [nanoodle](https://nanoodle.io) visual AI workflows from JavaScript.** nanoodle is a
4
+ no-server, bring-your-own-key editor where you wire AI nodes (LLMs, image, video, audio) into a
5
+ graph and download it as `noodle-graph.json`. This package is the zero-dependency executor for
6
+ those files: load a saved workflow, feed it inputs, get its outputs — same execution semantics
7
+ as the app (topological order, concurrent lanes, wired-field overrides), against the same
8
+ [NanoGPT](https://nano-gpt.com) API. Build and test workflows visually at
9
+ [nanoodle.io](https://nanoodle.io); automate them here.
10
+
11
+ - Zero runtime dependencies — Node >= 20, built-in `fetch`
12
+ - Text, image, video (submit + poll), audio (sync + async poll), vision, transcription
13
+ - Cost tracking per node and per run
14
+ - Library and CLI in one install
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ npm install nanoodle # library + CLI
20
+ npx nanoodle --help # or run the CLI without installing
21
+ ```
22
+
23
+ ## Quickstart (library)
24
+
25
+ ```js
26
+ import { Workflow } from "nanoodle";
27
+
28
+ const wf = await Workflow.load("noodle-graph.json"); // key from NANOGPT_API_KEY
29
+ const result = await wf.run({ Text: "a cozy ramen shop on a rainy night" });
30
+ await result.get("Image").save("ramen.png"); // media outputs: MediaRef (url + bytes()/save())
31
+ console.log(result.costUsd, result.remainingBalance);
32
+ ```
33
+
34
+ With the starter graph from the app (text → LLM prompt-writer → image), that's the whole program.
35
+
36
+ ## Quickstart (CLI)
37
+
38
+ Inspect first — it's offline and shows the workflow's inputs, outputs, and settings:
39
+
40
+ ```bash
41
+ npx nanoodle inspect graph.json
42
+ ```
43
+
44
+ Then run (this calls the NanoGPT API and spends from your balance):
45
+
46
+ ```bash
47
+ export NANOGPT_API_KEY=... # or --key K, or --env-file .env
48
+ npx nanoodle run graph.json --input Text="a cozy ramen shop" --out ./out
49
+ npx nanoodle run graph.json --input n2.system=@style.txt --set n3.size=1k --json
50
+ ```
51
+
52
+ `--env-file path` reads `NANOGPT_API_KEY` from a `.env`-style file (`--key` wins if both are
53
+ given). `--input k=@path` reads a file — media files ride as media, `.txt`/`.md`/`.json` as
54
+ text. `--out dir` saves media outputs to disk; `--json` prints a machine-readable result.
55
+
56
+ ## Inputs, outputs, settings
57
+
58
+ ```js
59
+ wf.inputs // [{ key: "Text", nodeId: "n1", field: "text", kind: "textarea", optional: false, def: "..." }]
60
+ wf.outputs // [{ key: "Image", nodeId: "n3", type: "image", ports: [{ name: "image", type: "image" }] }]
61
+ wf.settings // [{ key: "n3.model", kind: "model", def: "nano-banana-2-lite" }, ...]
62
+ ```
63
+
64
+ Input keys resolve flexibly (case-insensitive): the node's custom name (`"Text"`),
65
+ `nodeId.field` (`"n2.system"`), a bare node id, or the input's label. Output keys are the sink
66
+ node's custom name (or its type name). A workflow with exactly one required input also accepts
67
+ a bare value: `wf.run("hello")`. Settings use `nodeId.field` keys (`"n3.model"`).
68
+
69
+ ### Media inputs
70
+
71
+ ```js
72
+ import { mediaFromFile } from "nanoodle";
73
+
74
+ await wf.run({ Image: await mediaFromFile("photo.jpg") }); // local file
75
+ await wf.run({ Image: "https://example.com/photo.jpg" }); // hosted URL
76
+ await wf.run({ Image: bytesUint8Array }); // raw bytes (MIME sniffed)
77
+ ```
78
+
79
+ Media is sent inline as base64 (NanoGPT has no upload endpoint); files over ~4.4 MB
80
+ (~3.5 MB for transcription) are refused locally with a clear error before any paid call.
81
+
82
+ ### Progress and errors
83
+
84
+ ```js
85
+ const result = await wf.run(
86
+ { Text: "sunset harbor" },
87
+ {
88
+ settings: { "n3.model": "flux-dev", "n3.size": "1024x1024" },
89
+ timeoutMs: 300000,
90
+ onProgress: (e) => console.error(e.type, e.name ?? "", e.status ?? ""),
91
+ },
92
+ );
93
+ ```
94
+
95
+ `run()` rejects with `RunError` when an output (sink) node failed — `err.result` still carries
96
+ the partial results, per-node statuses, and cost so far. Failures in lanes no output depends on
97
+ only surface in `result.errors`. Unknown/unsupported node types, missing required inputs, bad
98
+ keys, and a missing API key all fail **before** anything is spent.
99
+
100
+ ## Supported nodes
101
+
102
+ | runs | node types |
103
+ |---|---|
104
+ | local | text, upload (image/audio/video), choice, join, comment |
105
+ | NanoGPT | llm (incl. vision + audio input), image, draw, edit, inpaint*, vision, tvideo, ivideo, vedit, lipsync, music, remix, tts, transcribe |
106
+ | **not supported** (browser-only media processing) | resize, vframes, combine, soundtrack, trim, extractaudio |
107
+
108
+ Workflows containing unsupported node types load with a warning and fail fast at `run()` with
109
+ `UnsupportedNodeError` — before any network call.
110
+
111
+ \* inpaint caveat: the browser app composites the mask onto black at the source's pixel size;
112
+ this library passes your mask through verbatim, so supply a black/white mask matching the
113
+ source dimensions.
114
+
115
+ ## Use it as an agent skill
116
+
117
+ A saved workflow plus a short `SKILL.md` playbook makes a skill any coding agent can run —
118
+ Claude Code (`.claude/skills/<name>/SKILL.md`) or anything that reads markdown and runs shell.
119
+ Recipe + copy-pasteable template: [docs/agent-skills.md](docs/agent-skills.md); complete
120
+ example: [examples/agent-skill/poster-generator/](examples/agent-skill/poster-generator/).
121
+
122
+ ## API key and cost
123
+
124
+ This is bring-your-own-key: you need a [nano-gpt.com](https://nano-gpt.com) API key (or OAuth
125
+ access token) with balance, and **every `run()` spends real money** — NanoGPT bills per
126
+ generation. The library reports what each run cost: `result.costUsd` totals the prices NanoGPT
127
+ returned, `result.costExact` turns false when any call omitted a price (the total is then a
128
+ floor), and `result.remainingBalance` is the freshest balance the API reported. A price of 0
129
+ means known-included (subscription), not unknown. `inspect` and loading/validating workflows
130
+ never call the API.
131
+
132
+ ## Specs and testing
133
+
134
+ The format and execution semantics are specified in [docs/](docs/):
135
+ [DESIGN.md](docs/DESIGN.md), [SPEC-format.md](docs/SPEC-format.md),
136
+ [SPEC-engine.md](docs/SPEC-engine.md), [SPEC-io.md](docs/SPEC-io.md).
137
+
138
+ Tests run fully offline against a mock NanoGPT server (`tests/harness/`):
139
+
140
+ ```bash
141
+ npm test
142
+ ```
143
+
144
+ An opt-in live probe (spends a fraction of a cent) exists for hand-verification:
145
+ `node scripts/live-spot-check.mjs` (add `--image` to also run the starter graph's image step).
146
+
147
+ ## License
148
+
149
+ MIT — see [LICENSE](LICENSE). Not affiliated with NanoGPT. Build workflows at
150
+ [nanoodle.io](https://nanoodle.io).
@@ -0,0 +1,195 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * nanoodle CLI — run and inspect noodle-graph.json workflows.
4
+ *
5
+ * nanoodle run graph.json --input Text="a cozy ramen shop" --input n2.system=@file.txt \
6
+ * --set n3.size=1k --out ./out [--json]
7
+ * nanoodle inspect graph.json
8
+ *
9
+ * API key: NANOGPT_API_KEY env var, --key <key>, or --env-file <path> (.env-style file).
10
+ * Precedence: --key > --env-file > NANOGPT_API_KEY. NANOGPT_BASE_URL overrides the API host.
11
+ */
12
+ import { mkdir, readFile } from "node:fs/promises";
13
+ import { join, extname } from "node:path";
14
+ import process from "node:process";
15
+ import { Workflow, RunError, mediaFromFile } from "../src/index.mjs";
16
+ import { MediaRef, extForMime } from "../src/media.mjs";
17
+
18
+ function usage(code = 1) {
19
+ console.error(`usage:
20
+ nanoodle run <graph.json> [--input k=v]... [--set k=v]... [--out dir] [--json] [--key K] [--env-file path] [--timeout ms]
21
+ nanoodle inspect <graph.json> [--key K] [--env-file path]
22
+ nanoodle --version
23
+
24
+ --input k=v set a workflow input ("Text=hello", "n2.system=@notes.txt"; @path reads a file —
25
+ media files ride as media, .txt/.md/.json as text)
26
+ --set k=v override a setting ("n3.model=flux-pro", "n3.size=1k")
27
+ --out dir save media outputs into dir (text outputs are printed)
28
+ --json print a machine-readable result
29
+ --key K NanoGPT API key (defaults to NANOGPT_API_KEY)
30
+ --env-file p read NANOGPT_API_KEY from a .env-style file (--key wins if both given)
31
+ --timeout ms overall run timeout`);
32
+ process.exit(code);
33
+ }
34
+
35
+ function parseKv(arg, flag) {
36
+ const eq = arg.indexOf("=");
37
+ if (eq < 1) { console.error(`${flag} expects key=value, got: ${arg}`); process.exit(1); }
38
+ return [arg.slice(0, eq), arg.slice(eq + 1)];
39
+ }
40
+
41
+ const TEXT_EXT = new Set([".txt", ".md", ".json", ".csv", ".html", ".xml"]);
42
+
43
+ async function resolveValue(v) {
44
+ if (!v.startsWith("@")) return v;
45
+ const path = v.slice(1);
46
+ if (TEXT_EXT.has(extname(path).toLowerCase())) return await readFile(path, "utf8");
47
+ return mediaFromFile(path);
48
+ }
49
+
50
+ async function main() {
51
+ const argv = process.argv.slice(2);
52
+ const cmd = argv.shift();
53
+ if (cmd === "--version") {
54
+ const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
55
+ console.log(`nanoodle ${pkg.version}`);
56
+ process.exit(0);
57
+ }
58
+ if (!cmd || cmd === "--help" || cmd === "-h") usage(cmd ? 0 : 1);
59
+ if (cmd !== "run" && cmd !== "inspect") usage();
60
+
61
+ let graphPath = null, outDir = null, asJson = false, keyFlag = null, envFile = null, timeoutMs;
62
+ const inputArgs = [], setArgs = [];
63
+ let i = 0;
64
+ const val = (flag) => { // a value-taking flag at end of argv is a usage error, not a TypeError
65
+ const v = argv[++i];
66
+ if (v === undefined) { console.error(`${flag} expects a value`); usage(); }
67
+ return v;
68
+ };
69
+ for (; i < argv.length; i++) {
70
+ const a = argv[i];
71
+ if (a === "--input") inputArgs.push(val("--input"));
72
+ else if (a === "--set") setArgs.push(val("--set"));
73
+ else if (a === "--out") outDir = val("--out");
74
+ else if (a === "--json") asJson = true;
75
+ else if (a === "--key") keyFlag = val("--key");
76
+ else if (a === "--env-file") envFile = val("--env-file");
77
+ else if (a === "--timeout") timeoutMs = +val("--timeout");
78
+ else if (a.startsWith("-")) { console.error("unknown flag: " + a); usage(); }
79
+ else if (!graphPath) graphPath = a;
80
+ else { console.error("unexpected argument: " + a); usage(); }
81
+ }
82
+ if (!graphPath) usage();
83
+
84
+ // key precedence: --key > --env-file > NANOGPT_API_KEY (same .env parsing as scripts/live-spot-check.mjs)
85
+ let apiKey = keyFlag ?? process.env.NANOGPT_API_KEY;
86
+ if (envFile && keyFlag == null) {
87
+ let envText;
88
+ try { envText = await readFile(envFile, "utf8"); }
89
+ catch (e) { console.error(`--env-file: cannot read ${envFile}: ${e.message}`); process.exit(1); }
90
+ const m = envText.match(/^NANOGPT_API_KEY\s*=\s*"?([^"\n]+)"?/m);
91
+ if (!m) { console.error(`--env-file: no NANOGPT_API_KEY entry in ${envFile}`); process.exit(1); }
92
+ apiKey = m[1].trim();
93
+ }
94
+
95
+ const wf = await Workflow.load(graphPath, { apiKey, baseUrl: process.env.NANOGPT_BASE_URL || undefined });
96
+
97
+ if (cmd === "inspect") {
98
+ const pad = (s, n) => String(s).padEnd(n);
99
+ console.log("Inputs:");
100
+ for (const i of wf.inputs) {
101
+ const extras = [i.optional ? "optional" : "required", i.def != null ? `default: ${JSON.stringify(i.def)}` : null,
102
+ i.options ? `options: ${i.options.join(" | ")}` : null].filter(Boolean).join(", ");
103
+ console.log(` ${pad('"' + i.key + '"', 26)} ${pad(i.nodeId + "." + i.field, 16)} ${pad(i.kind, 9)} ${extras}`);
104
+ }
105
+ if (!wf.inputs.length) console.log(" (none)");
106
+ console.log("Outputs:");
107
+ for (const o of wf.outputs) {
108
+ console.log(` ${pad('"' + o.key + '"', 26)} ${pad(o.nodeId, 16)} ${o.type} → ${o.ports.map((p) => p.name + ":" + p.type).join(", ")}`);
109
+ }
110
+ if (!wf.outputs.length) console.log(" (none)");
111
+ console.log("Settings:");
112
+ for (const s of wf.settings) {
113
+ const extras = [s.def != null && s.def !== "" ? `current: ${JSON.stringify(s.def)}` : null,
114
+ s.options ? `options: ${s.options.join(" | ")}` : null].filter(Boolean).join(", ");
115
+ console.log(` ${pad(s.key, 26)} ${pad(s.kind, 9)} ${extras}`);
116
+ }
117
+ if (!wf.settings.length) console.log(" (none)");
118
+ console.log("Nodes:");
119
+ for (const n of wf.graph.nodes) {
120
+ console.log(` ${pad(n.id, 5)} ${pad(n.type, 13)} ${n.name ? '"' + n.name + '"' : ""}`);
121
+ }
122
+ for (const w of wf.warnings) console.log("warning: " + w);
123
+ return;
124
+ }
125
+
126
+ // ---- run ----
127
+ const inputs = {};
128
+ for (const arg of inputArgs) {
129
+ const [k, v] = parseKv(arg, "--input");
130
+ inputs[k] = await resolveValue(v);
131
+ }
132
+ const settings = {};
133
+ for (const arg of setArgs) {
134
+ const [k, v] = parseKv(arg, "--set");
135
+ settings[k] = v;
136
+ }
137
+
138
+ let result;
139
+ try {
140
+ result = await wf.run(inputs, {
141
+ settings, timeoutMs,
142
+ onProgress: asJson ? undefined : (e) => {
143
+ if (e.type === "node-start") console.error(`▶ ${e.name} (${e.nodeId})`);
144
+ if (e.type === "node-done") console.error(`✔ ${e.name} (${e.nodeId}) ${e.ms}ms${e.costUsd != null ? ` $${e.costUsd}` : ""}`);
145
+ if (e.type === "node-error") console.error(`✖ ${e.name} (${e.nodeId}): ${e.error}`);
146
+ },
147
+ });
148
+ } catch (e) {
149
+ if (e instanceof RunError && e.result) {
150
+ console.error("run failed: " + e.message);
151
+ result = e.result;
152
+ process.exitCode = 1;
153
+ } else {
154
+ console.error("error: " + e.message);
155
+ process.exit(1);
156
+ }
157
+ }
158
+
159
+ if (outDir) await mkdir(outDir, { recursive: true });
160
+ const printable = {};
161
+ for (const o of wf.outputs) {
162
+ const value = result.outputs[o.key];
163
+ if (value === undefined) { printable[o.key] = null; continue; }
164
+ if (value instanceof MediaRef) {
165
+ if (outDir) {
166
+ const safe = o.key.replace(/[^\w.-]+/g, "_");
167
+ const path = join(outDir, safe + "." + extForMime(value.mime || ""));
168
+ await value.save(path);
169
+ printable[o.key] = path;
170
+ if (!asJson) console.log(`${o.key}: saved ${path}`);
171
+ } else {
172
+ printable[o.key] = value.url.length > 200 ? value.url.slice(0, 80) + `… (${value.url.length} chars — use --out to save)` : value.url;
173
+ if (!asJson) console.log(`${o.key}: ${printable[o.key]}`);
174
+ }
175
+ } else {
176
+ printable[o.key] = value;
177
+ if (!asJson) console.log(`${o.key}: ${value}`);
178
+ }
179
+ }
180
+ if (asJson) {
181
+ console.log(JSON.stringify({
182
+ outputs: printable,
183
+ costUsd: result.costUsd,
184
+ costExact: result.costExact,
185
+ remainingBalance: result.remainingBalance,
186
+ errors: result.errors,
187
+ nodes: Object.fromEntries(Object.entries(result.nodes).map(([id, r]) => [id, { status: r.status, ms: r.ms, costUsd: r.costUsd, error: r.error }])),
188
+ }, null, 2));
189
+ } else {
190
+ const approx = result.costExact ? "" : "≥ ";
191
+ console.error(`cost: ${approx}$${result.costUsd}${result.remainingBalance != null ? ` · balance: $${result.remainingBalance}` : ""}`);
192
+ }
193
+ }
194
+
195
+ main().catch((e) => { console.error("error: " + (e && e.message || e)); process.exit(1); });
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "nanoodle",
3
+ "version": "0.1.0",
4
+ "description": "Run nanoodle visual AI workflows from JavaScript — zero-dependency executor for saved noodle-graph.json files",
5
+ "type": "module",
6
+ "main": "./src/index.mjs",
7
+ "exports": {
8
+ ".": "./src/index.mjs",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "sideEffects": false,
12
+ "bin": {
13
+ "nanoodle": "./bin/nanoodle.mjs"
14
+ },
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "scripts": {
19
+ "test": "node --test \"tests/**/*.test.mjs\""
20
+ },
21
+ "files": [
22
+ "src",
23
+ "bin",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "keywords": [
28
+ "nanoodle",
29
+ "workflow",
30
+ "ai",
31
+ "nanogpt",
32
+ "image-generation",
33
+ "video-generation",
34
+ "llm",
35
+ "agent",
36
+ "automation",
37
+ "tts",
38
+ "transcription",
39
+ "byok",
40
+ "no-deps",
41
+ "zero-dependencies"
42
+ ],
43
+ "license": "MIT",
44
+ "homepage": "https://nanoodle.io",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/255BITS/nanoodle-js.git"
48
+ },
49
+ "bugs": {
50
+ "url": "https://github.com/255BITS/nanoodle-js/issues"
51
+ }
52
+ }