@nodetool-ai/app-export 0.0.0-stage → 0.8.3

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,51 @@
1
- # Temporary Holding Version
1
+ # @nodetool-ai/app-export
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
+ Exports a NodeTool mini app as a standalone JavaScript project. The project
4
+ runs the app without a NodeTool server: `npm install && npm run dev`.
5
+
6
+ The CLI (`nodetool apps export-project`), the server
7
+ (`GET /api/applications/:id/export-project`) and the web command menu
8
+ ("Export App as Standalone Project") all build the project here.
9
+
10
+ ## What the project contains
11
+
12
+ | Path | Role |
13
+ | --- | --- |
14
+ | `app.bundle.json` | The app's `ApplicationBundle`: the UI document and every workflow graph and JS script it runs |
15
+ | `src/` | A Vite + React UI that renders the document. Bindings, run policies, conditions and the message fold come from `@nodetool-ai/app-runtime`, so the app behaves as it does in NodeTool |
16
+ | `server/index.mjs` | One Node process: the UI (Vite middleware with `--dev`, `dist/` otherwise) plus `POST /api/run`, `POST /api/upload`, `GET /api/storage/*`, `GET /api/models` and `GET /api/package-assets/*` |
17
+ | `server/runner.mjs` | Runs a bundled graph by its key through `ExecutionSession` from `@nodetool-ai/execution`, and a bundled JS script through `runCodeBody` from `@nodetool-ai/agents`. The browser cannot send code of its own |
18
+ | `server/store.mjs` | The model interfaces a run calls for persistence, kept in files: generated assets, timelines, scripts, storyboards and sketches. No database is needed |
19
+ | `server/models.mjs` | The catalog behind `ModelSelect`: the models of every provider with a key in `.env` |
20
+ | `server/media.mjs` | Turns run outputs into URLs the browser loads, and uploaded files back into URIs a node reads |
21
+ | `assets/` | Copies of the `package://` sample files the app references |
22
+ | `.env.example` | The credentials the graphs need, read by the server and never sent to the browser |
23
+
24
+ The project depends on the published `@nodetool-ai/*` packages at the
25
+ exporter's own version.
26
+
27
+ ## What it does not do
28
+
29
+ `exportWarnings` names each of these for the app being exported, and the
30
+ project's README repeats them.
31
+
32
+ - Resource bindings, `ResourcePicker`, `ResourceGallery` and the storyboard
33
+ editors need NodeTool documents and render a note.
34
+ - `Sketch`, `Timeline` and `Storyboard` widgets render a note instead of the
35
+ editor.
36
+ - Nodes that read the entity library, job history or asset folders, and
37
+ nodes that need the Python bridge, fail at run time. Storyboard recasts
38
+ derive a fresh copy on every run.
39
+
40
+ ## The template
41
+
42
+ `template/` is the project the exporter writes, kept as real files so it can
43
+ be typechecked (`npm run lint` checks it with `template/tsconfig.json`). The
44
+ exporter reads it from `src/template-files.generated.ts`. After editing a
45
+ template file, run:
46
+
47
+ ```bash
48
+ npm run embed-template --workspace=packages/app-export
49
+ ```
50
+
51
+ A test fails when the generated module is stale.
@@ -0,0 +1 @@
1
+ 2026-10-12T12:16:56.599Z
@@ -0,0 +1,61 @@
1
+ import { type ApplicationBundle } from "@nodetool-ai/app-runtime";
2
+ import { type PackageAssetFile } from "./package-assets.js";
3
+ export { packageAssetPath, packageAssetUris, readPackageAssets, type PackageAssetFile } from "./package-assets.js";
4
+ export interface StandaloneProjectFile {
5
+ /** POSIX path relative to the project root. */
6
+ path: string;
7
+ /** Text, or the bytes of a copied sample file. */
8
+ content: string | Uint8Array;
9
+ }
10
+ export interface StandaloneProjectOptions {
11
+ /**
12
+ * Version of the `@nodetool-ai/*` packages the project depends on.
13
+ * Defaults to this package's own version.
14
+ */
15
+ nodetoolVersion?: string;
16
+ /** Credential names the app's graphs need; listed in `.env.example`. */
17
+ secrets?: ReadonlyArray<string>;
18
+ /**
19
+ * Every provider's credential name. Listed commented out in `.env.example`
20
+ * when a graph leaves a model unset, since the person picks the provider.
21
+ */
22
+ providerSecrets?: ReadonlyArray<string>;
23
+ /**
24
+ * The bytes of the `package://` files the bundle references (see
25
+ * `packageAssetUris` and `readPackageAssets`). Copied under `assets/`.
26
+ */
27
+ packageAssets?: ReadonlyArray<PackageAssetFile>;
28
+ }
29
+ export interface StandaloneProject {
30
+ /** npm-safe project name, also a sensible folder name. */
31
+ name: string;
32
+ files: StandaloneProjectFile[];
33
+ /** What the exported app cannot do that it does inside NodeTool. */
34
+ warnings: string[];
35
+ }
36
+ /**
37
+ * This package's version, read from its manifest (one level above both `src/`
38
+ * and `dist/`). A bundled host that flattens the paths gets `"latest"`.
39
+ */
40
+ export declare function exporterVersion(): string;
41
+ /** Lowercase, dash-separated, npm-safe; never empty. */
42
+ export declare function projectSlug(name: string): string;
43
+ interface RegistryLike {
44
+ has: (nodeType: string) => boolean;
45
+ getMetadata: (nodeType: string) => {
46
+ required_settings?: string[];
47
+ } | null | undefined;
48
+ }
49
+ /**
50
+ * The credential names an app's graphs need: every `required_settings` entry
51
+ * of the node types they use, plus the key of every provider a model
52
+ * reference names. The caller supplies the registry and the provider lookup,
53
+ * so this package needs neither.
54
+ */
55
+ export declare function requiredSecretNames(bundle: ApplicationBundle, registry: RegistryLike, providerSecretKey: (provider: string) => string | null): string[];
56
+ /** True when a graph carries a model reference with no model chosen. */
57
+ export declare function hasUnsetModel(bundle: ApplicationBundle): boolean;
58
+ /** Limitations worth telling the person exporting, before they find them. */
59
+ export declare function exportWarnings(bundle: ApplicationBundle): string[];
60
+ export declare function buildStandaloneProject(bundle: ApplicationBundle, options?: StandaloneProjectOptions): StandaloneProject;
61
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAcA,OAAO,EAIL,KAAK,iBAAiB,EACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAsC,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAGhG,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEnH,MAAM,WAAW,qBAAqB;IACpC,+CAA+C;IAC/C,IAAI,EAAE,MAAM,CAAC;IACb,kDAAkD;IAClD,OAAO,EA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AiB,EACzB,OAAO,GAAE,wBAA6B,GACrC,iBAAiB,CAmCnB"}
package/dist/index.js ADDED
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Export a mini app as a standalone JavaScript project.
3
+ *
4
+ * The project is the app's bundle (document plus every workflow graph it
5
+ * runs) inside a fixed template: a Vite + React UI that renders the document
6
+ * with the shared `@nodetool-ai/app-runtime` semantics, and a small Node
7
+ * server that runs the graphs in process through `@nodetool-ai/execution`.
8
+ * It needs no NodeTool server: `npm install && npm run dev` runs the app,
9
+ * with provider keys read from `.env`.
10
+ *
11
+ * Everything here is pure. Writing the files to disk or into a zip is the
12
+ * caller's business (the CLI writes a folder, the server streams a zip).
13
+ */
14
+ import { readFileSync } from "node:fs";
15
+ import { operationTarget, serializeApplicationBundle, WIDGET_CATALOG } from "@nodetool-ai/app-runtime";
16
+ import { packageAssetPath, packageAssetUris } from "./package-assets.js";
17
+ import { TEMPLATE_FILES } from "./template-files.generated.js";
18
+ export { packageAssetPath, packageAssetUris, readPackageAssets } from "./package-assets.js";
19
+ /** Template files the exporter writes itself or leaves out. */
20
+ const GENERATED_PATHS = new Set(["app.bundle.json"]);
21
+ const RENAMED_PATHS = { gitignore: ".gitignore" };
22
+ /** Widgets the exported UI renders as a pointer back to NodeTool. */
23
+ const NODETOOL_ONLY_WIDGETS = new Set([
24
+ "Sketch",
25
+ "Timeline",
26
+ "Storyboard",
27
+ "StoryboardPreview",
28
+ "SketchPad",
29
+ "ResourcePicker",
30
+ "ResourceGallery",
31
+ "StoryboardSceneList"
32
+ ]);
33
+ const REACT_VERSION = "^19.2.0";
34
+ const VITE_VERSION = "^8.0.0";
35
+ const VITE_REACT_VERSION = "^6.0.0";
36
+ const TYPESCRIPT_VERSION = "^5.9.0";
37
+ /**
38
+ * This package's version, read from its manifest (one level above both `src/`
39
+ * and `dist/`). A bundled host that flattens the paths gets `"latest"`.
40
+ */
41
+ export function exporterVersion() {
42
+ try {
43
+ const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
44
+ return typeof manifest.version === "string" && manifest.version ? manifest.version : "latest";
45
+ }
46
+ catch {
47
+ return "latest";
48
+ }
49
+ }
50
+ /** Lowercase, dash-separated, npm-safe; never empty. */
51
+ export function projectSlug(name) {
52
+ const slug = name
53
+ .normalize("NFKD")
54
+ .replace(/[^\w\s-]/g, "")
55
+ .trim()
56
+ .toLowerCase()
57
+ .replace(/[\s_]+/g, "-")
58
+ .replace(/-+/g, "-")
59
+ .replace(/^[-.]+|-+$/g, "")
60
+ .slice(0, 64);
61
+ return slug || "nodetool-app";
62
+ }
63
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
64
+ /**
65
+ * The credential names an app's graphs need: every `required_settings` entry
66
+ * of the node types they use, plus the key of every provider a model
67
+ * reference names. The caller supplies the registry and the provider lookup,
68
+ * so this package needs neither.
69
+ */
70
+ export function requiredSecretNames(bundle, registry, providerSecretKey) {
71
+ const names = new Set();
72
+ const visitValue = (value, depth) => {
73
+ if (depth > 8)
74
+ return;
75
+ if (Array.isArray(value)) {
76
+ for (const item of value)
77
+ visitValue(item, depth + 1);
78
+ return;
79
+ }
80
+ if (!isRecord(value))
81
+ return;
82
+ if (typeof value.type === "string" &&
83
+ value.type.endsWith("_model") &&
84
+ typeof value.provider === "string" &&
85
+ value.provider !== "") {
86
+ const key = providerSecretKey(value.provider);
87
+ if (key)
88
+ names.add(key);
89
+ }
90
+ for (const entry of Object.values(value))
91
+ visitValue(entry, depth + 1);
92
+ };
93
+ for (const workflow of bundle.workflows) {
94
+ for (const node of workflow.graph.nodes) {
95
+ if (!isRecord(node))
96
+ continue;
97
+ const type = typeof node.type === "string" ? node.type : "";
98
+ if (type && registry.has(type)) {
99
+ for (const key of registry.getMetadata(type)?.required_settings ?? []) {
100
+ if (key)
101
+ names.add(key);
102
+ }
103
+ }
104
+ visitValue(node.data ?? node.properties, 0);
105
+ }
106
+ }
107
+ // A script reads only the secrets its document declares.
108
+ for (const script of bundle.scripts) {
109
+ const declared = script.document.secrets;
110
+ if (!Array.isArray(declared))
111
+ continue;
112
+ for (const key of declared) {
113
+ if (typeof key === "string" && key)
114
+ names.add(key);
115
+ }
116
+ }
117
+ return [...names].sort();
118
+ }
119
+ /** True when a graph carries a model reference with no model chosen. */
120
+ export function hasUnsetModel(bundle) {
121
+ const visit = (value, depth) => {
122
+ if (depth > 8)
123
+ return false;
124
+ if (Array.isArray(value))
125
+ return value.some((item) => visit(item, depth + 1));
126
+ if (!isRecord(value))
127
+ return false;
128
+ if (typeof value.type === "string" && value.type.endsWith("_model") && "id" in value) {
129
+ return typeof value.id !== "string" || value.id === "";
130
+ }
131
+ return Object.values(value).some((entry) => visit(entry, depth + 1));
132
+ };
133
+ return bundle.workflows.some((workflow) => visit(workflow.graph.nodes, 0));
134
+ }
135
+ function collectWidgetTypes(value, into, depth = 0) {
136
+ if (depth > 64)
137
+ return;
138
+ if (Array.isArray(value)) {
139
+ for (const item of value)
140
+ collectWidgetTypes(item, into, depth + 1);
141
+ return;
142
+ }
143
+ if (!isRecord(value))
144
+ return;
145
+ if (typeof value.type === "string" && isRecord(value.props))
146
+ into.add(value.type);
147
+ for (const entry of Object.values(isRecord(value.props) ? value.props : value)) {
148
+ collectWidgetTypes(entry, into, depth + 1);
149
+ }
150
+ }
151
+ /** Limitations worth telling the person exporting, before they find them. */
152
+ export function exportWarnings(bundle) {
153
+ const warnings = [];
154
+ const workflowKeys = new Set(bundle.workflows.map((workflow) => workflow.key));
155
+ const scriptKeys = new Set(bundle.scripts.map((script) => script.key));
156
+ for (const operation of bundle.app.operations) {
157
+ const target = operationTarget(operation);
158
+ if (target.kind === "script" ? !scriptKeys.has(target.scriptId) : !workflowKeys.has(target.workflowId)) {
159
+ warnings.push(`Operation "${operation.name}" names a ${target.kind} the bundle does not carry.`);
160
+ }
161
+ }
162
+ if (bundle.app.resources.length > 0) {
163
+ warnings.push("Resource bindings read NodeTool documents, which the exported app has no database for.");
164
+ }
165
+ const types = new Set();
166
+ collectWidgetTypes(bundle.app.ui.content, types);
167
+ for (const type of [...types].sort()) {
168
+ if (NODETOOL_ONLY_WIDGETS.has(type)) {
169
+ warnings.push(`${WIDGET_CATALOG[type]?.label ?? type} widgets show a note instead of the NodeTool editor.`);
170
+ }
171
+ else if (!(type in WIDGET_CATALOG)) {
172
+ warnings.push(`Widget type "${type}" is unknown and renders as a note.`);
173
+ }
174
+ }
175
+ return warnings;
176
+ }
177
+ function packageJson(name, version) {
178
+ const nodetool = version === "latest" ? version : `^${version}`;
179
+ return `${JSON.stringify({
180
+ name,
181
+ private: true,
182
+ version: "0.1.0",
183
+ type: "module",
184
+ engines: { node: ">=22.0.0" },
185
+ scripts: {
186
+ dev: "node server/index.mjs --dev",
187
+ build: "vite build",
188
+ start: "node server/index.mjs",
189
+ typecheck: "tsc --noEmit"
190
+ },
191
+ dependencies: {
192
+ "@nodetool-ai/agents": nodetool,
193
+ "@nodetool-ai/app-runtime": nodetool,
194
+ "@nodetool-ai/base-nodes": nodetool,
195
+ "@nodetool-ai/execution": nodetool,
196
+ "@nodetool-ai/node-sdk": nodetool,
197
+ "@nodetool-ai/runtime": nodetool,
198
+ "@nodetool-ai/storage": nodetool,
199
+ react: REACT_VERSION,
200
+ "react-dom": REACT_VERSION
201
+ },
202
+ devDependencies: {
203
+ "@types/react": REACT_VERSION,
204
+ "@types/react-dom": REACT_VERSION,
205
+ "@vitejs/plugin-react": VITE_REACT_VERSION,
206
+ typescript: TYPESCRIPT_VERSION,
207
+ vite: VITE_VERSION
208
+ }
209
+ }, null, 2)}\n`;
210
+ }
211
+ function envExample(secrets, providerSecrets) {
212
+ const optional = providerSecrets.filter((name) => !secrets.includes(name));
213
+ const lines = [
214
+ "# Provider keys this app's workflows use. Copy to .env and fill in.",
215
+ "# The server reads .env at startup; keys never reach the browser.",
216
+ ...(secrets.length > 0 ? secrets.map((name) => `${name}=`) : optional.length > 0 ? [] : ["# (none detected)"]),
217
+ ...(optional.length > 0
218
+ ? [
219
+ "",
220
+ "# The app lets you pick a model. Set the key of each provider you want",
221
+ "# to offer; the model menus list what those providers serve.",
222
+ ...optional.map((name) => `# ${name}=`)
223
+ ]
224
+ : []),
225
+ "",
226
+ "# Server options",
227
+ "# PORT=5180",
228
+ "# HOST=127.0.0.1",
229
+ ""
230
+ ];
231
+ return lines.join("\n");
232
+ }
233
+ function readme(bundle, warnings) {
234
+ const description = bundle.description.trim();
235
+ return [
236
+ `# ${bundle.name}`,
237
+ "",
238
+ ...(description ? [description, ""] : []),
239
+ "A NodeTool mini app exported as a standalone project. The UI is a Vite +",
240
+ "React app; `server/` runs the app's workflows and JS scripts in this",
241
+ "process, so no NodeTool server is needed.",
242
+ "",
243
+ "## Run it",
244
+ "",
245
+ "```bash",
246
+ "npm install",
247
+ "cp .env.example .env # then add your provider keys",
248
+ "npm run dev # http://127.0.0.1:5180",
249
+ "```",
250
+ "",
251
+ "For a production build, run `npm run build` once, then `npm start`.",
252
+ "",
253
+ "## How it works",
254
+ "",
255
+ "- `app.bundle.json` is the whole app: the UI document and every workflow",
256
+ " graph and JS script it runs. Re-export from NodeTool to update it.",
257
+ "- `server/index.mjs` serves the UI and four endpoints: `POST /api/run`",
258
+ " streams a workflow or script run as Server-Sent Events, `POST /api/upload`",
259
+ " stores a picked file, `GET /api/storage/<key>` serves uploads and outputs,",
260
+ " and `GET /api/models` lists the models of the providers with a key in",
261
+ " `.env`.",
262
+ "- `server/runner.mjs` runs a graph or script from the bundle by its key.",
263
+ " The browser cannot send code of its own.",
264
+ "- `server/store.mjs` keeps what NodeTool keeps in its database (generated",
265
+ " assets, timelines, scripts, storyboards, sketches) as files. Everything",
266
+ " lives in `.nodetool-data/`.",
267
+ "- `src/` renders the document. Bindings, run policies, conditions and the",
268
+ " message fold come from `@nodetool-ai/app-runtime`, the same package the",
269
+ " NodeTool app uses, so the app behaves as it does there.",
270
+ "",
271
+ "The server listens on 127.0.0.1. Every run spends the keys in `.env`, so",
272
+ "put authentication in front of it before setting `HOST=0.0.0.0`.",
273
+ ...(warnings.length > 0
274
+ ? ["", "## Differences from NodeTool", "", ...warnings.map((warning) => `- ${warning}`)]
275
+ : []),
276
+ ""
277
+ ].join("\n");
278
+ }
279
+ export function buildStandaloneProject(bundle, options = {}) {
280
+ const name = projectSlug(bundle.name);
281
+ const warnings = exportWarnings(bundle);
282
+ const files = [];
283
+ const copied = new Set();
284
+ for (const asset of options.packageAssets ?? []) {
285
+ const path = packageAssetPath(asset.uri);
286
+ if (!path || copied.has(path))
287
+ continue;
288
+ copied.add(path);
289
+ files.push({ path: `assets/${path}`, content: asset.bytes });
290
+ }
291
+ const missing = packageAssetUris(bundle).filter((uri) => !copied.has(packageAssetPath(uri) ?? ""));
292
+ if (missing.length > 0) {
293
+ warnings.push(`${missing.length} sample file(s) from NodeTool's packages were not found and load as empty: ${missing.join(", ")}`);
294
+ }
295
+ for (const [path, content] of Object.entries(TEMPLATE_FILES)) {
296
+ if (GENERATED_PATHS.has(path))
297
+ continue;
298
+ files.push({ path: RENAMED_PATHS[path] ?? path, content });
299
+ }
300
+ files.push({ path: "package.json", content: packageJson(name, options.nodetoolVersion ?? exporterVersion()) }, { path: "app.bundle.json", content: serializeApplicationBundle(bundle) }, {
301
+ path: ".env.example",
302
+ content: envExample(options.secrets ?? [], hasUnsetModel(bundle) ? [...new Set(options.providerSecrets ?? [])].sort() : [])
303
+ }, { path: "README.md", content: readme(bundle, warnings) });
304
+ files.sort((a, b) => a.path.localeCompare(b.path));
305
+ return { name, files, warnings };
306
+ }
307
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EACL,eAAe,EACf,0BAA0B,EAC1B,cAAc,EAEf,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAyB,MAAM,q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e,CAAC,GAAG,CAAC,IAAI,CAAC;YAAE,SAAS;QACxC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,CAAC,IAAI,CAAC,IAAI,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,KAAK,CAAC,IAAI,CACR,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,eAAe,IAAI,eAAe,EAAE,CAAC,EAAE,EAClG,EAAE,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE,0BAA0B,CAAC,MAAM,CAAC,EAAE,EACxE;QACE,IAAI,EAAE,cAAc;QACpB,OAAO,EAAE,UAAU,CACjB,OAAO,CAAC,OAAO,IAAI,EAAE,EACrB,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,eAAe,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAChF;KACF,EACD,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,CACzD,CAAC;IACF,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IACnD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC;AACnC,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { ApplicationBundle } from "@nodetool-ai/app-runtime";
2
+ export interface PackageAssetFile {
3
+ uri: string;
4
+ bytes: Uint8Array;
5
+ }
6
+ /** `<package>/<path>` for a well-formed URI that stays inside its package. */
7
+ export declare function packageAssetPath(uri: string): string | null;
8
+ /** Every distinct `package://` URI in the app document and its graphs. */
9
+ export declare function packageAssetUris(bundle: ApplicationBundle): string[];
10
+ /**
11
+ * Read each URI from the first root holding `<root>/<package>/<path>`. URIs
12
+ * no root holds are left out; the exporter warns about them.
13
+ */
14
+ export declare function readPackageAssets(uris: ReadonlyArray<string>, roots: ReadonlyArray<string>): PackageAssetFile[];
15
+ //# sourceMappingURL=package-assets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package-assets.d.ts","sourceRoot":"","sources":["../src/package-assets.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAIlE,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,UAAU,CAAC;CACnB;AAED,8EAA8E;AAC9E,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAO3D;AAED,0EAA0E;AAC1E,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,iBAAiB,GAAG,MAAM,EAAE,CAmBpE;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,gBAAgB,EAAE,CAkB/G"}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Sample files a bundle references as `package://<package>/<path>`.
3
+ *
4
+ * Example apps seed inputs with files that ship inside NodeTool's node
5
+ * packages. Those files are not on npm, so the exported project carries a copy
6
+ * under `assets/<package>/<path>` and its server resolves the URIs from there.
7
+ */
8
+ import { readFileSync } from "node:fs";
9
+ import { join, relative, resolve } from "node:path";
10
+ const SCHEME = "package://";
11
+ /** `<package>/<path>` for a well-formed URI that stays inside its package. */
12
+ export function packageAssetPath(uri) {
13
+ if (!uri.startsWith(SCHEME))
14
+ return null;
15
+ const segments = uri.slice(SCHEME.length).split("/").filter((segment) => segment !== "" && segment !== ".");
16
+ if (segments.length < 2 || segments.some((segment) => segment === ".." || segment.includes("\\"))) {
17
+ return null;
18
+ }
19
+ return segments.join("/");
20
+ }
21
+ /** Every distinct `package://` URI in the app document and its graphs. */
22
+ export function packageAssetUris(bundle) {
23
+ const found = new Set();
24
+ const visit = (value, depth) => {
25
+ if (depth > 64)
26
+ return;
27
+ if (typeof value === "string") {
28
+ if (packageAssetPath(value))
29
+ found.add(value);
30
+ return;
31
+ }
32
+ if (Array.isArray(value)) {
33
+ for (const item of value)
34
+ visit(item, depth + 1);
35
+ return;
36
+ }
37
+ if (typeof value === "object" && value !== null) {
38
+ for (const entry of Object.values(value))
39
+ visit(entry, depth + 1);
40
+ }
41
+ };
42
+ visit(bundle.app, 0);
43
+ for (const workflow of bundle.workflows)
44
+ visit(workflow.graph, 0);
45
+ return [...found].sort();
46
+ }
47
+ /**
48
+ * Read each URI from the first root holding `<root>/<package>/<path>`. URIs
49
+ * no root holds are left out; the exporter warns about them.
50
+ */
51
+ export function readPackageAssets(uris, roots) {
52
+ const files = [];
53
+ for (const uri of uris) {
54
+ const path = packageAssetPath(uri);
55
+ if (!path)
56
+ continue;
57
+ for (const root of roots) {
58
+ const base = resolve(root);
59
+ const target = resolve(join(base, ...path.split("/")));
60
+ if (relative(base, target).startsWith(".."))
61
+ continue;
62
+ try {
63
+ files.push({ uri, bytes: new Uint8Array(readFileSync(target)) });
64
+ break;
65
+ }
66
+ catch {
67
+ // Not under this root; try the next one.
68
+ }
69
+ }
70
+ }
71
+ return files;
72
+ }
73
+ //# sourceMappingURL=package-assets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package-assets.js","sourceRoot":"","sources":["../src/package-assets.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpD,MAAM,MAAM,GAAG,YAAY,CAAC;AAO5B,8EAA8E;AAC9E,MAAM,UAAU,gBAAgB,CAAC,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ATE_FILES: Readonly<Record<string, string>>;
2
+ //# sourceMappingURL=template-files.generated.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"template-files.generated.d.ts","sourceRoot":"","sources":["../src/template-files.generated.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,cAAc,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAyB3D,CAAC"}
@@ -0,0 +1,28 @@
1
+ // Generated by scripts/embed-template.mjs from template/. Do not edit.
2
+ export const TEMPLATE_FILES = {
3
+ "gitignore": "node_modules\ndist\n.env\n.nodetool-data\n",
4
+ "index.html": "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <link rel=\"icon\" href=\"data:,\" />\n <title>NodeTool app</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/src/main.tsx\"></script>\n </body>\n</html>\n",
5
+ "server/index.mjs": "/**\n * The app's server: one process, one port.\n *\n * POST /api/run run one of the app's workflows or JS scripts,\n * streamed as SSE\n * POST /api/upload store a file the user picked, answer its URL\n * GET /api/models models the configured providers offer, by kind\n * GET /api/storage/<key> serve stored uploads and run outputs\n * GET /api/package-assets/<package>/<path>\n * serve the sample files copied under assets/\n * everything else the UI (Vite in dev, `dist/` after `npm run build`)\n *\n * It listens on 127.0.0.1 unless HOST says otherwise. Every run spends the\n * provider keys in `.env`, so think before exposing it to a network.\n */\nimport { createReadStream, existsSync } from \"node:fs\";\nimport { mkdir, readFile, stat } from \"node:fs/promises\";\nimport { createServer } from \"node:http\";\nimport { dirname, extname, join, normalize, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { randomUUID } from \"node:crypto\";\n\nconst ROOT = resolve(dirname(fileURLToPath(import.meta.url)), \"..\");\nif (existsSync(join(ROOT, \".env\"))) {\n process.loadEnvFile(join(ROOT, \".env\"));\n}\n\nconst DEV = process.argv.includes(\"--dev\");\nconst PORT = Number(process.env.PORT ?? 5180);\nconst HOST = process.env.HOST ?? \"127.0.0.1\";\nconst DATA_DIR = resolve(ROOT, process.env.NODETOOL_DATA_DIR ?? \".nodetool-data\");\nconst MAX_UPLOAD_BYTES = Number(process.env.MAX_UPLOAD_MB ?? 200) * 1024 * 1024;\n\nconst CONTENT_TYPES = {\n \".html\": \"text/html; charset=utf-8\",\n \".js\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".webp\": \"image/webp\",\n \".gif\": \"image/gif\",\n \".mp3\": \"audio/mpeg\",\n \".wav\": \"audio/wav\",\n \".ogg\": \"audio/ogg\",\n \".mp4\": \"video/mp4\",\n \".webm\": \"video/webm\",\n \".pdf\": \"application/pdf\",\n \".glb\": \"model/gltf-binary\",\n \".txt\": \"text/plain; charset=utf-8\"\n};\n\nawait mkdir(DATA_DIR, { recursive: true });\nconst { createRunner } = await import(\"./runner.mjs\");\nconst runner = createRunner({ root: ROOT, dataDir: DATA_DIR });\nconst { createModelCatalog } = await import(\"./models.mjs\");\nconst models = createModelCatalog();\n\nfunction sendJson(res, status, body) {\n res.writeHead(status, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(body));\n}\n\nasync function readBody(req, limit) {\n const chunks = [];\n let size = 0;\n for await (const chunk of req) {\n size += chunk.length;\n if (size > limit) {\n throw new Error(`Body exceeds ${Math.round(limit / 1024 / 1024)} MB`);\n }\n chunks.push(chunk);\n }\n return Buffer.concat(chunks);\n}\n\n/** A path under `base`, or null when the request tries to leave it. */\nfunction safeJoin(base, requested) {\n const target = normalize(join(base, requested));\n return target === base || target.startsWith(base + sep) ? target : null;\n}\n\nasync function serveFile(res, path, fallback) {\n try {\n const info = await stat(path);\n if (!info.isFile()) throw new Error(\"not a file\");\n res.writeHead(200, {\n \"content-type\": CONTENT_TYPES[extname(path).toLowerCase()] ?? \"application/octet-stream\",\n \"content-length\": info.size\n });\n createReadStream(path).pipe(res);\n } catch {\n if (fallback) {\n await serveFile(res, fallback, null);\n return;\n }\n sendJson(res, 404, { error: \"not_found\" });\n }\n}\n\nasync function handleRun(req, res) {\n let body;\n try {\n body = JSON.parse((await readBody(req, MAX_UPLOAD_BYTES)).toString(\"utf8\"));\n } catch {\n sendJson(res, 400, { error: \"invalid_json\" });\n return;\n }\n const workflow = typeof body?.workflow === \"string\" ? body.workflow : null;\n const script = typeof body?.script === \"string\" ? body.script : null;\n if (!workflow && !script) {\n sendJson(res, 400, { error: \"missing_workflow\" });\n return;\n }\n const jobId = typeof body.job_id === \"string\" ? body.job_id : randomUUID();\n const abort = new AbortController();\n res.on(\"close\", () => {\n if (!res.writableEnded) abort.abort();\n });\n res.writeHead(200, {\n \"content-type\": \"text/event-stream; charset=utf-8\",\n \"cache-control\": \"no-cache, no-transform\",\n connection: \"keep-alive\"\n });\n const send = (message) => {\n if (!res.writableEnded) res.write(`data: ${JSON.stringify(message)}\\n\\n`);\n };\n try {\n const request = { params: body.params, jobId, signal: abort.signal, send };\n if (script) await runner.runScript({ ...request, scriptKey: script });\n else await runner.run({ ...request, workflowKey: workflow });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`[run ${jobId}] ${message}`);\n send({ type: \"job_update\", status: \"failed\", job_id: jobId, error: message });\n } finally {\n res.end();\n }\n}\n\nasync function handleUpload(req, res, url) {\n const name = (url.searchParams.get(\"name\") ?? \"upload\").replace(/[^A-Za-z0-9._-]+/g, \"_\");\n const contentType = req.headers[\"content-type\"] ?? \"application/octet-stream\";\n try {\n const bytes = await readBody(req, MAX_UPLOAD_BYTES);\n const key = `uploads/${randomUUID()}-${name}`;\n await runner.storage.store(key, bytes, contentType);\n sendJson(res, 200, { uri: `/api/storage/${key}`, content_type: contentType });\n } catch (error) {\n sendJson(res, 413, { error: error instanceof Error ? error.message : String(error) });\n }\n}\n\nlet vite = null;\nif (DEV) {\n const { createServer: createViteServer } = await import(\"vite\");\n vite = await createViteServer({\n root: ROOT,\n server: { middlewareMode: true },\n appType: \"spa\"\n });\n}\n\nconst DIST = join(ROOT, \"dist\");\n\nconst server = createServer(async (req, res) => {\n const url = new URL(req.url ?? \"/\", \"http://localhost\");\n try {\n if (url.pathname === \"/api/run\" && req.method === \"POST\") {\n await handleRun(req, res);\n return;\n }\n if (url.pathname === \"/api/upload\" && req.method === \"POST\") {\n await handleUpload(req, res, url);\n return;\n }\n if (url.pathname === \"/api/models\" && req.method === \"GET\") {\n const kind = url.searchParams.get(\"kind\") ?? \"\";\n const task = url.searchParams.get(\"task\") || undefined;\n sendJson(res, 200, { models: await models.list(kind, task) });\n return;\n }\n if (url.pathname.startsWith(\"/api/storage/\") && req.method === \"GET\") {\n const key = decodeURIComponent(url.pathname.slice(\"/api/storage/\".length));\n const path = safeJoin(runner.storage.rootDir, key);\n if (!path) {\n sendJson(res, 400, { error: \"invalid_path\" });\n return;\n }\n await serveFile(res, path, null);\n return;\n }\n if (url.pathname.startsWith(\"/api/package-assets/\") && req.method === \"GET\") {\n const rel = decodeURIComponent(url.pathname.slice(\"/api/package-assets/\".length));\n const path = safeJoin(join(ROOT, \"assets\"), rel);\n if (!path) {\n sendJson(res, 400, { error: \"invalid_path\" });\n return;\n }\n await serveFile(res, path, null);\n return;\n }\n if (url.pathname.startsWith(\"/api/\")) {\n sendJson(res, 404, { error: \"not_found\" });\n return;\n }\n if (vite) {\n vite.middlewares(req, res);\n return;\n }\n const path = safeJoin(DIST, url.pathname === \"/\" ? \"index.html\" : url.pathname);\n await serveFile(res, path ?? join(DIST, \"index.html\"), join(DIST, \"index.html\"));\n } catch (error) {\n console.error(error);\n if (!res.headersSent) sendJson(res, 500, { error: \"internal_error\" });\n else res.end();\n }\n});\n\nserver.listen(PORT, HOST, async () => {\n console.log(`App running at http://${HOST}:${PORT}`);\n if (!DEV && !existsSync(join(DIST, \"index.html\"))) {\n console.log(\"No UI build found. Run `npm run build` first, or `npm run dev`.\");\n }\n const example = join(ROOT, \".env.example\");\n if (existsSync(example)) {\n const names = (await readFile(example, \"utf8\"))\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => /^[A-Z0-9_]+=/.test(line))\n .map((line) => line.split(\"=\")[0]);\n const missing = names.filter((name) => !process.env[name]);\n if (missing.length > 0) {\n console.log(`Not set (see .env.example): ${missing.join(\", \")}`);\n }\n }\n});\n",
6
+ "server/media.mjs": "/**\n * Rewrites the media inside a run message into URLs the browser can load.\n *\n * A node emits a media ref in one of four shapes: inline bytes (`data`), a\n * `file://` URI inside this server's storage folder, an `asset://` reference\n * to a file the local store saved, or a URL some provider already hosts. The\n * first three mean nothing to a browser, so inline bytes are written to\n * storage and all three become `/api/storage/<key>`. Provider URLs and\n * `data:` URIs pass through unchanged.\n *\n * Run params go the other way: a file the browser uploaded arrives as\n * `/api/storage/<key>` and becomes the `file://` URI of the stored file.\n */\nimport { randomUUID } from \"node:crypto\";\nimport { join, normalize as normalizePath, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nconst MEDIA_TYPES = new Set([\"image\", \"audio\", \"video\", \"document\", \"model_3d\", \"model3d\"]);\n\nconst EXTENSIONS = {\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpg\",\n \"image/webp\": \"webp\",\n \"image/gif\": \"gif\",\n \"audio/mpeg\": \"mp3\",\n \"audio/wav\": \"wav\",\n \"audio/x-wav\": \"wav\",\n \"audio/ogg\": \"ogg\",\n \"video/mp4\": \"mp4\",\n \"video/webm\": \"webm\",\n \"application/pdf\": \"pdf\",\n \"model/gltf-binary\": \"glb\"\n};\n\nconst DEFAULT_EXTENSIONS = {\n image: \"png\",\n audio: \"mp3\",\n video: \"mp4\",\n document: \"bin\",\n model_3d: \"glb\",\n model3d: \"glb\"\n};\n\nconst isRecord = (value) =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** Inline bytes as a Uint8Array, or null when `data` holds none. */\nconst bytesOf = (data) => {\n if (data instanceof Uint8Array) return data.length > 0 ? data : null;\n if (typeof data === \"string\" && data.length > 0) {\n // Raw base64 (never a data: URI) is the protocol's other inline form.\n return Buffer.from(data, \"base64\");\n }\n if (isRecord(data) && data.type === \"Buffer\" && Array.isArray(data.data)) {\n return Uint8Array.from(data.data);\n }\n return null;\n};\n\nexport function createMediaNormalizer(storage, assetKey = () => null) {\n const storagePrefix = `${pathToFileURL(storage.rootDir).toString()}/`;\n\n const storageUrl = (key) =>\n `/api/storage/${key.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n\n async function normalizeRef(ref) {\n const next = { ...ref };\n const bytes = bytesOf(ref.data);\n if (bytes) {\n const contentType = ref.content_type ?? ref.mime_type ?? undefined;\n const ext = EXTENSIONS[contentType] ?? DEFAULT_EXTENSIONS[ref.type] ?? \"bin\";\n const key = `outputs/${randomUUID()}.${ext}`;\n await storage.store(key, bytes, contentType);\n next.uri = storageUrl(key);\n delete next.data;\n } else if (typeof ref.uri === \"string\" && ref.uri.startsWith(storagePrefix)) {\n next.uri = storageUrl(decodeURIComponent(ref.uri.slice(storagePrefix.length)));\n } else if (typeof ref.uri === \"string\" && ref.uri.startsWith(\"asset://\")) {\n const key = assetKey(ref.uri);\n if (key) next.uri = storageUrl(key);\n } else if (!ref.uri && typeof ref.asset_id === \"string\") {\n const key = assetKey(`asset://${ref.asset_id}`);\n if (key) next.uri = storageUrl(key);\n }\n return next;\n }\n\n async function normalize(value, depth = 0) {\n if (depth > 32 || value == null) return value;\n if (Array.isArray(value)) {\n return Promise.all(value.map((item) => normalize(item, depth + 1)));\n }\n if (value instanceof Uint8Array) {\n return Buffer.from(value).toString(\"base64\");\n }\n if (!isRecord(value)) return value;\n const record =\n typeof value.type === \"string\" && MEDIA_TYPES.has(value.type)\n ? await normalizeRef(value)\n : value;\n const out = {};\n for (const [key, entry] of Object.entries(record)) {\n out[key] = await normalize(entry, depth + 1);\n }\n return out;\n }\n\n return normalize;\n}\n\n/**\n * Turns the `/api/storage/<key>` URIs of uploaded files inside run params back\n * into `file://` URIs a node can read. A key that leaves the storage folder is\n * dropped rather than resolved.\n */\nexport function createInputResolver(storage) {\n const root = normalizePath(storage.rootDir);\n const PREFIX = \"/api/storage/\";\n\n const resolveUri = (uri) => {\n const key = uri.slice(PREFIX.length).split(\"/\").map(decodeURIComponent).join(\"/\");\n const path = normalizePath(join(root, key));\n return path.startsWith(root + sep) ? pathToFileURL(path).toString() : \"\";\n };\n\n function resolve(value, depth = 0) {\n if (depth > 32 || value == null) return value;\n if (Array.isArray(value)) return value.map((item) => resolve(item, depth + 1));\n if (!isRecord(value)) return value;\n const out = {};\n for (const [key, entry] of Object.entries(value)) {\n out[key] =\n key === \"uri\" && typeof entry === \"string\" && entry.startsWith(PREFIX)\n ? resolveUri(entry)\n : resolve(entry, depth + 1);\n }\n return out;\n }\n\n return resolve;\n}\n",
7
+ "server/models.mjs": "/**\n * The model catalog behind `ModelSelect`: every model the providers with a key\n * in `.env` can list, as model references a graph property accepts.\n *\n * Listing asks each configured provider once per model kind and keeps the\n * answer for the life of the process. Restart the server after changing keys.\n */\nimport {\n getProvider,\n isProviderConfigured,\n listRegisteredProviderIds\n} from \"@nodetool-ai/runtime\";\n\n/** Model reference type → the provider method that lists that kind. */\nconst LISTERS = {\n language_model: \"getAvailableLanguageModels\",\n image_model: \"getAvailableImageModels\",\n video_model: \"getAvailableVideoModels\",\n tts_model: \"getAvailableTTSModels\",\n asr_model: \"getAvailableASRModels\",\n music_model: \"getAvailableMusicModels\",\n embedding_model: \"getAvailableEmbeddingModels\",\n audio_to_audio_model: \"getAvailableAudioToAudioModels\"\n};\n\nexport const MODEL_KINDS = Object.keys(LISTERS);\n\nconst getSecret = (key) => Promise.resolve(process.env[key] ?? null);\n\nexport function createModelCatalog() {\n const cache = new Map();\n\n async function listKind(kind) {\n const method = LISTERS[kind];\n const out = [];\n for (const providerId of listRegisteredProviderIds()) {\n try {\n if (!(await isProviderConfigured(providerId, getSecret))) continue;\n const provider = await getProvider(providerId, getSecret);\n if (typeof provider[method] !== \"function\") continue;\n for (const model of await provider[method]()) {\n out.push({\n type: kind,\n provider: model.provider ?? providerId,\n id: model.id,\n name: model.name ?? model.id,\n ...(Array.isArray(model.supportedTasks) ? { supported_tasks: model.supportedTasks } : {})\n });\n }\n } catch (error) {\n console.warn(`[models] ${providerId} could not list ${kind}: ${error instanceof Error ? error.message : error}`);\n }\n }\n return out;\n }\n\n /** Models of one kind, narrowed to a task (`image_to_image`, ...) when given. */\n async function list(kind, task) {\n if (!LISTERS[kind]) return [];\n if (!cache.has(kind)) {\n const pending = listKind(kind);\n cache.set(kind, pending);\n pending.catch(() => cache.delete(kind));\n }\n const models = await cache.get(kind);\n return task\n ? models.filter((model) => !model.supported_tasks || model.supported_tasks.length === 0 || model.supported_tasks.includes(task))\n : models;\n }\n\n return { list };\n}\n",
8
+ "server/runner.mjs": "/**\n * Runs the app's workflows and JS scripts in this process.\n *\n * The graphs and script bodies come from `app.bundle.json`, never from the\n * request: the browser names a workflow or script by its bundle key and sends\n * the params, so nobody who can reach this server can make it run code the\n * app does not ship.\n *\n * What NodeTool keeps in its database (generated assets, timelines, scripts,\n * storyboards, sketches) is kept in files under the data folder instead, see\n * `store.mjs`.\n *\n * Provider keys (OPENAI_API_KEY, FAL_API_KEY, ...) are read from the process\n * environment, which `server/index.mjs` fills from `.env`. They never reach\n * the browser.\n */\nimport { randomUUID } from \"node:crypto\";\nimport { mkdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { runCodeBody } from \"@nodetool-ai/agents\";\nimport { scriptRunMessages, scriptStreamMessages } from \"@nodetool-ai/app-runtime\";\nimport { registerBuiltinPacks } from \"@nodetool-ai/base-nodes/builtin-packs\";\nimport {\n ExecutionSession,\n isExecutionPreflightError,\n toRawGraphInput\n} from \"@nodetool-ai/execution\";\nimport {\n parseCarriedScriptDocument,\n scriptOperationInvocation\n} from \"@nodetool-ai/execution/app-debug\";\nimport {\n emptyDeclaredJsScriptOutputsError,\n missingDeclaredJsScriptOutputs\n} from \"@nodetool-ai/execution/js-script-debug\";\nimport {\n NodeRegistry,\n createGraphNodeTypeResolver\n} from \"@nodetool-ai/node-sdk\";\nimport {\n PERMISSION_GATE_CONTEXT_KEY,\n ProcessingContext,\n headlessGate\n} from \"@nodetool-ai/runtime\";\nimport { FileStorageAdapter } from \"@nodetool-ai/storage\";\nimport { createInputResolver, createMediaNormalizer } from \"./media.mjs\";\nimport { createLocalStore } from \"./store.mjs\";\n\n/** Run messages a script relays while it runs: agent text, tool calls, progress. */\nconst RELAYED_MESSAGES = new Set([\n \"chunk\",\n \"tool_call_update\",\n \"tool_result_update\",\n \"planning_update\",\n \"task_update\",\n \"node_progress\"\n]);\n\n/** The workflows and scripts the app ships, by bundle key. */\nexport function loadBundleWorkflows(root) {\n const bundle = JSON.parse(readFileSync(join(root, \"app.bundle.json\"), \"utf8\"));\n const workflows = new Map();\n for (const workflow of bundle.workflows ?? []) {\n workflows.set(workflow.key, workflow);\n }\n const scripts = new Map();\n for (const script of bundle.scripts ?? []) {\n scripts.set(script.key, script);\n }\n return { bundle, workflows, scripts };\n}\n\nexport function createRunner({ root, dataDir }) {\n const { workflows, scripts } = loadBundleWorkflows(root);\n // `package://<package>/<path>` sample inputs resolve from the copies the\n // export put under assets/.\n process.env.NODETOOL_PACKAGE_ASSETS_DIR ??= join(root, \"assets\");\n const registry = new NodeRegistry();\n registerBuiltinPacks(registry, { includeOptionalPacks: true });\n const { resolveNodeType } = createGraphNodeTypeResolver(registry);\n const storage = new FileStorageAdapter(join(dataDir, \"storage\"));\n const store = createLocalStore({ dataDir, storage });\n const normalize = createMediaNormalizer(storage, store.assetKey);\n const resolveInputs = createInputResolver(storage);\n const workspaceDir = join(dataDir, \"workspace\");\n mkdirSync(workspaceDir, { recursive: true });\n\n const createContext = (jobId, workflowId, onMessage) =>\n new ProcessingContext({\n jobId,\n workflowId,\n userId: \"1\",\n secretResolver: (key) => Promise.resolve(process.env[key] ?? null),\n storage,\n assetStorage: storage,\n workspaceDir,\n modelInterfaces: store.interfaces,\n // Output nodes would save every result a second time; outputs are\n // served from storage by URL instead.\n persistOutputAssets: false,\n ...(onMessage && { onMessage })\n });\n\n /**\n * Run one workflow and hand every message to `send`, media already rewritten\n * to URLs the browser can load. Resolves when the run has settled.\n */\n async function run({ workflowKey, params, jobId, signal, send }) {\n const workflow = workflows.get(workflowKey);\n if (!workflow) {\n throw new Error(`This app has no workflow \"${workflowKey}\"`);\n }\n const id = jobId || randomUUID();\n const context = createContext(id, workflowKey);\n let session;\n try {\n session = await ExecutionSession.create({\n graph: toRawGraphInput(workflow.graph),\n registry,\n resolveNodeType,\n jobId: id,\n workflowId: workflowKey,\n params: resolveInputs(params ?? {}),\n context,\n captureMessages: true,\n recordCosts: false\n });\n } catch (error) {\n // A graph this runtime cannot run (an unset model, a missing node\n // type) is the run's failure, said in the UI, not a server error.\n if (!isExecutionPreflightError(error)) throw error;\n send({ type: \"job_update\", status: \"failed\", job_id: id, error: error.message });\n return null;\n }\n const cancel = () => session.cancel(\"cancelled\");\n signal?.addEventListener(\"abort\", cancel, { once: true });\n try {\n for await (const message of session.messages) {\n // Node-level messages carry no job id; the browser routes by it.\n const normalized = await normalize(message);\n send(normalized.job_id ? normalized : { ...normalized, job_id: id });\n }\n const result = await session.result;\n return result;\n } finally {\n signal?.removeEventListener(\"abort\", cancel);\n }\n }\n\n /**\n * Run one JS script and hand `send` the messages the browser folds: what\n * the script relays while it runs, each `emit`, then its outputs and the\n * job's end, the same stream NodeTool's own app runtime builds from a\n * script run.\n */\n async function runScript({ scriptKey, params, jobId, signal, send }) {\n const script = scripts.get(scriptKey);\n if (!script) {\n throw new Error(`This app has no script \"${scriptKey}\"`);\n }\n // Parsing fills the defaults NodeTool applies, the timeout among them.\n const document = parseCarriedScriptDocument(script.document);\n if (!document) {\n throw new Error(`Script \"${script.name}\" is not a valid script document`);\n }\n const id = jobId || randomUUID();\n // Normalizing media is async; the chain keeps lines in the order they came.\n let relayed = Promise.resolve();\n const relay = (line) => {\n for (const message of scriptStreamMessages(line, id)) {\n relayed = relayed.then(async () => send(await normalize(message)));\n }\n };\n const context = createContext(id, null, (message) => {\n if (RELAYED_MESSAGES.has(message.type)) relay({ type: \"message\", message: { ...message } });\n });\n // Nobody is there to approve a guarded step, so the gate answers for them.\n context.set(PERMISSION_GATE_CONTEXT_KEY, headlessGate(\"JS script run\"));\n if (signal) context.signal = signal;\n\n const resolved = resolveInputs(params ?? {});\n const values = {};\n for (const port of document.inputs) {\n if (port.name in resolved) values[port.name] = resolved[port.name];\n }\n const { inputs, inputStreams } = scriptOperationInvocation(document, values);\n let result;\n try {\n result = await runCodeBody(context, {\n code: document.code,\n inputs,\n ...(inputStreams && { inputStreams }),\n secrets: document.secrets,\n timeoutSeconds: document.timeoutSeconds,\n withToolbelt: true,\n onEmit: (name, value) => relay({ type: \"emit\", name, value })\n });\n } catch (error) {\n result = { ok: false, logs: [], error: error instanceof Error ? error.message : String(error), duration_ms: 0 };\n }\n for (const line of result.logs ?? []) console.log(`[script ${scriptKey}] ${line}`);\n // Declaring outputs and setting none of them is a failed run.\n const missing = result.ok ? missingDeclaredJsScriptOutputs(document.outputs, result.outputs) : [];\n const settled = {\n ok: result.ok && missing.length === 0,\n outputs: result.outputs ?? {},\n // Emits already went out as they happened.\n streamed: [],\n logs: [],\n duration_ms: result.duration_ms ?? 0,\n ...(missing.length > 0\n ? { error: emptyDeclaredJsScriptOutputsError(missing) }\n : result.error !== undefined && { error: result.error })\n };\n await relayed;\n for (const message of scriptRunMessages(settled, id)) {\n send(await normalize(message));\n }\n return settled;\n }\n\n return { run, runScript, storage };\n}\n",
9
+ "server/store.mjs": "/**\n * The records NodeTool keeps in its database, kept in files instead.\n *\n * Generative nodes save what they make as assets, and timeline, script,\n * storyboard and sketch nodes save documents they read back by id. Inside\n * NodeTool those land in the database. Here an asset is a file in storage at\n * `<userId>/<id>.<ext>`, the key `asset://<id>.<ext>` resolves to, with its\n * name and metadata in `assets.json`. A document is one JSON file under\n * `documents/<kind>/`.\n */\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nconst EXTENSIONS = {\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpg\",\n \"image/webp\": \"webp\",\n \"image/gif\": \"gif\",\n \"image/svg+xml\": \"svg\",\n \"audio/mpeg\": \"mp3\",\n \"audio/wav\": \"wav\",\n \"audio/x-wav\": \"wav\",\n \"audio/ogg\": \"ogg\",\n \"video/mp4\": \"mp4\",\n \"video/webm\": \"webm\",\n \"application/pdf\": \"pdf\",\n \"application/json\": \"json\",\n \"text/plain\": \"txt\",\n \"text/markdown\": \"md\",\n \"model/gltf-binary\": \"glb\"\n};\n\n/** A generated resource id: 32 lowercase hex characters. */\nconst newId = () => randomUUID().replaceAll(\"-\", \"\");\n\nconst now = () => new Date().toISOString();\n\nconst extensionFor = (name, contentType) => {\n const dot = name.lastIndexOf(\".\");\n if (dot > 0 && dot < name.length - 1) return name.slice(dot + 1).toLowerCase();\n return EXTENSIONS[contentType] ?? \"bin\";\n};\n\nfunction readJson(path, fallback) {\n try {\n return JSON.parse(readFileSync(path, \"utf8\"));\n } catch {\n return fallback;\n }\n}\n\n/** One JSON file per record, for a kind of document. */\nfunction documentFolder(dir) {\n mkdirSync(dir, { recursive: true });\n const pathOf = (id) => (/^[0-9a-f]{32}$/.test(id) ? join(dir, `${id}.json`) : null);\n return {\n get(id) {\n const path = pathOf(id);\n return path && existsSync(path) ? readJson(path, null) : null;\n },\n put(record) {\n writeFileSync(join(dir, `${record.id}.json`), JSON.stringify(record));\n return record;\n },\n list() {\n return readdirSync(dir)\n .filter((file) => file.endsWith(\".json\"))\n .map((file) => readJson(join(dir, file), null))\n .filter(Boolean);\n }\n };\n}\n\n/** Merge new fields into a stored document record, or null when it is missing. */\nfunction updateRecord(folder, id, fields) {\n const existing = folder.get(id);\n if (!existing) return null;\n const next = { ...existing, updatedAt: now() };\n for (const [key, value] of Object.entries(fields)) {\n if (value !== undefined) next[key] = value;\n }\n return folder.put(next);\n}\n\n/**\n * The model interfaces a ProcessingContext calls for persistence, backed by\n * files under `dataDir` and the run storage.\n */\nexport function createLocalStore({ dataDir, storage }) {\n const indexPath = join(dataDir, \"assets.json\");\n const assets = readJson(indexPath, {});\n const saveIndex = () => writeFileSync(indexPath, JSON.stringify(assets, null, 2));\n const timelines = documentFolder(join(dataDir, \"documents\", \"timelines\"));\n const scripts = documentFolder(join(dataDir, \"documents\", \"scripts\"));\n const storyboards = documentFolder(join(dataDir, \"documents\", \"storyboards\"));\n const sketches = documentFolder(join(dataDir, \"documents\", \"sketches\"));\n\n const assetInfo = (entry) =>\n entry\n ? {\n id: entry.id,\n name: entry.name,\n content_type: entry.content_type,\n metadata: entry.metadata ?? null\n }\n : null;\n\n const document = (fields) => ({\n id: newId(),\n projectId: fields.projectId ?? \"default\",\n name: fields.name,\n document: fields.document,\n createdAt: now(),\n updatedAt: now()\n });\n\n /**\n * The asset a full id or its 12-character short form names. Agents and\n * scripts see the short form; it resolves only when one asset has it.\n */\n const findAsset = (id) => {\n if (assets[id]) return assets[id];\n if (!/^[0-9a-f]{12}$/.test(id)) return null;\n const matches = Object.keys(assets).filter((key) => key.startsWith(id));\n return matches.length === 1 ? assets[matches[0]] : null;\n };\n\n /** The storage key of an `asset://<id>[.ext]` URI, or null when unknown. */\n const assetKey = (uri) => {\n const id = uri.slice(\"asset://\".length).split(/[?#]/)[0].replace(/\\.[^./]+$/, \"\");\n return findAsset(id)?.key ?? null;\n };\n\n const interfaces = {\n createAsset: async (args) => {\n const id = newId();\n const ext = extensionFor(args.name, args.contentType);\n const key = `${args.userId}/${id}.${ext}`;\n await storage.store(key, args.content, args.contentType);\n const entry = {\n id,\n key,\n name: args.name,\n content_type: args.contentType,\n parent_id: args.parentId ?? null,\n node_id: args.nodeId ?? null,\n job_id: args.jobId,\n workflow_id: args.workflowId,\n metadata: args.metadata ?? null,\n created_at: now()\n };\n assets[id] = entry;\n saveIndex();\n return { ...assetInfo(entry), uri: `asset://${id}.${ext}` };\n },\n updateAssetBytes: async ({ assetId, content, contentType, name }) => {\n const entry = findAsset(assetId);\n if (!entry) return null;\n if (contentType) entry.content_type = contentType;\n if (name) entry.name = name;\n await storage.store(entry.key, content, entry.content_type);\n saveIndex();\n return assetInfo(entry);\n },\n getAssetInfo: async ({ assetId }) => assetInfo(findAsset(assetId)),\n // No folders here: every asset is a file of its own.\n listFolderAssets: async () => null,\n getJob: async () => null,\n\n getTimelineSequence: async ({ id }) => timelines.get(id),\n createTimelineSequence: async ({ sequence }) => timelines.put({ ...sequence, id: newId() }),\n updateTimelineSequence: async ({ id, sequence }) =>\n timelines.get(id) ? timelines.put({ ...sequence, id }) : null,\n\n getScript: async ({ id }) => scripts.get(id),\n createScript: async ({ name, projectId, document: body }) =>\n scripts.put(document({ name: name ?? \"Untitled script\", projectId, document: body })),\n updateScript: async ({ id, document: body, timelineId }) =>\n updateRecord(scripts, id, { document: body, timelineId: timelineId ?? undefined }),\n\n getStoryboard: async ({ id }) => storyboards.get(id),\n listStoryboards: async ({ limit }) =>\n storyboards\n .list()\n .sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)))\n .slice(0, limit ?? 50),\n // Recast copies are not tracked, so a recast derives a fresh copy each run.\n findRecastStoryboard: async () => null,\n createStoryboard: async ({ name, projectId, document: body }) =>\n storyboards.put(document({ name: name ?? \"Untitled storyboard\", projectId, document: body })),\n updateStoryboard: async ({ id, document: body, timelineId }) =>\n updateRecord(storyboards, id, { document: body, timelineId: timelineId ?? undefined }),\n\n getImageDocument: async ({ id }) => sketches.get(id),\n createImageDocument: async ({ name, projectId, width, height, document: body }) =>\n sketches.put({ ...document({ name, projectId, document: body }), width, height })\n };\n\n return { interfaces, assetKey };\n}\n",
10
+ "src/App.tsx": "/**\n * The app: parses the bundled document, starts the runtime, renders the UI\n * tree. Everything the app does is described by `app.bundle.json`.\n */\nimport type { ReactNode } from \"react\";\nimport { parseApplicationBundle } from \"@nodetool-ai/app-runtime\";\nimport rawBundle from \"../app.bundle.json\";\nimport { AppRuntimeContext } from \"./runtime/context\";\nimport { useAppRuntime } from \"./runtime/useAppRuntime\";\nimport { ComponentList, slotNodes } from \"./widgets/tree\";\n\nconst bundle = parseApplicationBundle(rawBundle);\n\nfunction RunningApp({ bundle: loaded }: { bundle: NonNullable<typeof bundle> }): ReactNode {\n const runtime = useAppRuntime(loaded, loaded.name);\n return (\n <AppRuntimeContext.Provider value={runtime}>\n <main className=\"nt-app\">\n <ComponentList nodes={slotNodes(loaded.app.ui.content)} />\n </main>\n </AppRuntimeContext.Provider>\n );\n}\n\nexport function App(): ReactNode {\n if (!bundle) {\n return (\n <main className=\"nt-app\">\n <div className=\"nt-alert nt-alert-error\">app.bundle.json is not a NodeTool app bundle.</div>\n </main>\n );\n }\n document.title = bundle.name;\n return <RunningApp bundle={bundle} />;\n}\n",
11
+ "src/main.tsx": "import { StrictMode } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { App } from \"./App\";\nimport \"./styles.css\";\n\nconst root = document.getElementById(\"root\");\nif (root) {\n createRoot(root).render(\n <StrictMode>\n <App />\n </StrictMode>\n );\n}\n",
12
+ "src/runtime/context.ts": "/**\n * What widgets read from the running app. A widget hands over its binding\n * string exactly as stored; resolution against the graph happens here, which\n * is why renaming a node in NodeTool never broke the app.\n */\nimport { createContext, useCallback, useContext, useEffect, useMemo, useRef } from \"react\";\nimport {\n eventToAction,\n evaluateCondition,\n formatTemplate,\n isOperationRunning,\n operationActivity,\n operationProgress,\n parseCondition,\n readRef,\n resolveBinding,\n stateKey,\n type AppEvent,\n type AppInstanceState,\n type BindingMode,\n type BindingRef,\n type ConditionProps,\n type EventTrigger\n} from \"@nodetool-ai/app-runtime\";\nimport { useStoreSelector } from \"./store\";\nimport type { AppRuntime } from \"./useAppRuntime\";\n\nexport const AppRuntimeContext = createContext<AppRuntime | null>(null);\n\nexport function useAppRuntimeContext(): AppRuntime {\n const runtime = useContext(AppRuntimeContext);\n if (!runtime) throw new Error(\"Widgets must render inside AppRuntimeContext\");\n return runtime;\n}\n\nexport function useRuntimeSelector<T>(selector: (state: AppInstanceState) => T): T {\n return useStoreSelector(useAppRuntimeContext().store, selector);\n}\n\nexport function useBindingRef(binding: string | undefined, mode: BindingMode): BindingRef | null {\n const { scope } = useAppRuntimeContext();\n return useMemo(() => resolveBinding(binding, scope, mode), [binding, mode, scope]);\n}\n\nexport function useBindingValue(ref: BindingRef | null): unknown {\n return useRuntimeSelector((state) => {\n if (!ref) return undefined;\n const key = stateKey(ref);\n switch (ref.kind) {\n case \"output\":\n return state.outputs[key]?.value;\n case \"variable\":\n return state.variables[key];\n case \"view\":\n return state.view[key];\n case \"execution\":\n return readRef(state, {\n source: \"execution\",\n operationId: ref.operationId,\n field: ref.field\n });\n default:\n return state.inputs[key]?.value;\n }\n });\n}\n\n/** An unset or unresolvable condition yields `fallback`: it never hides a widget by accident. */\nexport function useCondition(props: ConditionProps | undefined, fallback: boolean): boolean {\n const { scope } = useAppRuntimeContext();\n const condition = useMemo(() => parseCondition(props, scope), [props, scope]);\n return useRuntimeSelector((state) => (condition ? evaluateCondition(state, condition) : fallback));\n}\n\nexport function useFormatted(template: string | undefined): string | null {\n const { scope } = useAppRuntimeContext();\n return useRuntimeSelector((state) => (template ? formatTemplate(template, state, scope) : null));\n}\n\n/** \"change\" is a live adjustment, \"commit\" the settled value (blur, release). */\nexport type EmitPhase = \"change\" | \"commit\";\n\nconst DEBOUNCE_MS = 500;\n\nexport interface WidgetRuntime {\n value: unknown;\n setValue: (value: unknown) => void;\n emit: (trigger: EventTrigger, phase?: EmitPhase) => void;\n running: boolean;\n progress: number | undefined;\n activity: string | undefined;\n}\n\nexport function useWidgetRuntime(params: {\n id: string;\n bindingMode: BindingMode;\n binding?: string;\n events?: AppEvent[];\n}): WidgetRuntime {\n const { id, bindingMode, binding, events } = params;\n const { dispatch, write, scope } = useAppRuntimeContext();\n const bound = useBindingRef(binding, bindingMode);\n // An unbound input still needs somewhere to hold its value: widget-local\n // view state, which cannot collide with a workflow input.\n const ref = useMemo<BindingRef | null>(\n () =>\n bound ?? (bindingMode === \"write\" ? { kind: \"view\", componentId: id, prop: \"value\" } : null),\n [bound, bindingMode, id]\n );\n const value = useBindingValue(ref);\n\n const operationId =\n events?.find((event) => event.operationId)?.operationId ?? scope.defaultOperationId;\n const running = useRuntimeSelector((s) => isOperationRunning(s, operationId));\n const progress = useRuntimeSelector((s) => operationProgress(s, operationId));\n const activity = useRuntimeSelector((s) => operationActivity(s, operationId));\n\n const setValue = useCallback(\n (next: unknown) => {\n if (ref) write(ref, next);\n },\n [ref, write]\n );\n\n const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(\n () => () => {\n if (timer.current) clearTimeout(timer.current);\n },\n []\n );\n\n const emit = useCallback(\n (trigger: EventTrigger, phase: EmitPhase = \"change\") => {\n const matching = (events ?? []).filter((event) => event.trigger === trigger);\n if (matching.length === 0) return;\n const ctx = {\n defaultOperationId: scope.defaultOperationId,\n resolveVariableId: (key: string | undefined) => {\n const variable = resolveBinding(key, scope, \"read\");\n return variable?.kind === \"variable\" ? variable.variableId : null;\n }\n };\n const fire = (event: AppEvent) => {\n const action = eventToAction(event, ctx);\n if (action) dispatch(action);\n };\n const debounced: AppEvent[] = [];\n for (const event of matching) {\n const pace = event.pace ?? \"live\";\n if (pace === \"release\") {\n if (phase === \"commit\") fire(event);\n } else if (pace === \"debounce\") {\n debounced.push(event);\n } else if (phase === \"change\") {\n fire(event);\n }\n }\n if (debounced.length === 0) return;\n if (timer.current) clearTimeout(timer.current);\n timer.current = null;\n if (phase === \"commit\") {\n debounced.forEach(fire);\n return;\n }\n timer.current = setTimeout(() => {\n timer.current = null;\n debounced.forEach(fire);\n }, DEBOUNCE_MS);\n },\n [dispatch, events, scope]\n );\n\n return { value, setValue, emit, running, progress, activity };\n}\n",
13
+ "src/runtime/models.ts": "/**\n * The model choices a `ModelSelect` offers. An exported app has no provider\n * catalog to ask, so it offers every model reference its own graphs already\n * use, grouped by kind (`language_model`, `image_model`, ...).\n */\nimport type { ApplicationBundle } from \"@nodetool-ai/app-runtime\";\n\nexport interface ModelRef {\n type: string;\n id: string;\n provider?: string;\n name?: string;\n [key: string]: unknown;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isModelRef = (value: unknown): value is ModelRef =>\n isRecord(value) &&\n typeof value.type === \"string\" &&\n value.type.endsWith(\"_model\") &&\n typeof value.id === \"string\" &&\n value.id !== \"\";\n\nexport function collectModelRefs(bundle: ApplicationBundle): Record<string, ModelRef[]> {\n const byKind: Record<string, ModelRef[]> = {};\n const seen = new Set<string>();\n const visit = (value: unknown, depth: number): void => {\n if (depth > 8) return;\n if (Array.isArray(value)) {\n for (const item of value) visit(item, depth + 1);\n return;\n }\n if (!isRecord(value)) return;\n if (isModelRef(value)) {\n const key = `${value.type}:${value.provider ?? \"\"}:${value.id}`;\n if (!seen.has(key)) {\n seen.add(key);\n (byKind[value.type] ??= []).push(value);\n }\n return;\n }\n for (const entry of Object.values(value)) visit(entry, depth + 1);\n };\n for (const workflow of bundle.workflows) visit(workflow.graph.nodes, 0);\n return byKind;\n}\n",
14
+ "src/runtime/persistence.ts": "/**\n * `localStorage` for the variables a document declares `scope: \"user\"` with\n * `persist: true`. Everything else lives only as long as the page.\n */\nimport type { VariableDeclaration } from \"@nodetool-ai/app-runtime\";\n\nconst storageKey = (instanceKey: string): string => `nodetool-app:${instanceKey}:variables`;\n\nconst persistedIds = (variables: ReadonlyArray<VariableDeclaration>): Set<string> =>\n new Set(variables.filter((v) => v.scope === \"user\" && v.persist).map((v) => v.id));\n\nexport function loadPersistedVariables(\n instanceKey: string,\n variables: ReadonlyArray<VariableDeclaration>\n): Record<string, unknown> {\n const ids = persistedIds(variables);\n if (ids.size === 0) return {};\n try {\n const raw = window.localStorage.getItem(storageKey(instanceKey));\n const stored: unknown = raw ? JSON.parse(raw) : {};\n if (typeof stored !== \"object\" || stored === null) return {};\n return Object.fromEntries(\n Object.entries(stored as Record<string, unknown>).filter(([id]) => ids.has(id))\n );\n } catch {\n // Storage blocked or the entry is corrupt: start from the defaults.\n return {};\n }\n}\n\nexport function savePersistedVariables(\n instanceKey: string,\n variables: ReadonlyArray<VariableDeclaration>,\n values: Record<string, unknown>\n): void {\n const ids = persistedIds(variables);\n if (ids.size === 0) return;\n const kept = Object.fromEntries(Object.entries(values).filter(([id]) => ids.has(id)));\n try {\n window.localStorage.setItem(storageKey(instanceKey), JSON.stringify(kept));\n } catch {\n // Storage blocked or full: the value simply does not outlive the page.\n }\n}\n",
15
+ "src/runtime/server.ts": "/**\n * The calls the UI makes to its own server: run a workflow or script (streamed as\n * Server-Sent Events), upload a file a widget picked, and list the models the\n * configured providers offer.\n */\n\nexport type RunMessage = Record<string, unknown>;\n\nexport interface RunRequest {\n /** What to run: a workflow's or a script's key in `app.bundle.json`. */\n target: { workflow: string } | { script: string };\n params: Record<string, unknown>;\n jobId: string;\n signal: AbortSignal;\n onMessage: (message: RunMessage) => void;\n}\n\n/** Resolves when the server closes the stream; rejects on a transport error. */\nexport async function runOperation(request: RunRequest): Promise<void> {\n const response = await fetch(\"/api/run\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n ...request.target,\n params: request.params,\n job_id: request.jobId\n }),\n signal: request.signal\n });\n if (!response.ok || !response.body) {\n const detail = await response.text().catch(() => \"\");\n throw new Error(detail || `Run failed (${response.status})`);\n }\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n let buffer = \"\";\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += value;\n let boundary = buffer.indexOf(\"\\n\\n\");\n while (boundary >= 0) {\n const event = buffer.slice(0, boundary);\n buffer = buffer.slice(boundary + 2);\n const data = event\n .split(\"\\n\")\n .filter((line) => line.startsWith(\"data:\"))\n .map((line) => line.slice(5).trimStart())\n .join(\"\\n\");\n if (data) request.onMessage(JSON.parse(data) as RunMessage);\n boundary = buffer.indexOf(\"\\n\\n\");\n }\n }\n}\n\nexport type MediaKind = \"image\" | \"audio\" | \"video\" | \"document\" | \"model_3d\";\n\nexport interface MediaValue {\n type: MediaKind;\n uri: string;\n content_type?: string;\n}\n\n/** Store a file on the app's server and return the ref a workflow input reads. */\nexport async function uploadFile(kind: MediaKind, file: File): Promise<MediaValue> {\n const response = await fetch(`/api/upload?name=${encodeURIComponent(file.name)}`, {\n method: \"POST\",\n headers: { \"content-type\": file.type || \"application/octet-stream\" },\n body: file\n });\n if (!response.ok) {\n throw new Error((await response.text().catch(() => \"\")) || \"Upload failed\");\n }\n const body = (await response.json()) as { uri: string; content_type?: string };\n return { type: kind, uri: body.uri, content_type: body.content_type };\n}\n\nexport interface ModelOption {\n type: string;\n provider?: string;\n id: string;\n name?: string;\n [key: string]: unknown;\n}\n\nconst modelLists = new Map<string, Promise<ModelOption[]>>();\n\n/** Models of one kind the server's providers offer; cached for the page's life. */\nexport function listModels(kind: string, task?: string): Promise<ModelOption[]> {\n const key = `${kind}:${task ?? \"\"}`;\n let pending = modelLists.get(key);\n if (!pending) {\n const query = new URLSearchParams({ kind, ...(task ? { task } : {}) });\n pending = fetch(`/api/models?${query.toString()}`)\n .then((response) => (response.ok ? (response.json() as Promise<{ models?: ModelOption[] }>) : { models: [] }))\n .then((body) => (Array.isArray(body.models) ? body.models : []))\n .catch(() => {\n modelLists.delete(key);\n return [];\n });\n modelLists.set(key, pending);\n }\n return pending;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * The URL a media value can be loaded from in this browser, or null. Refs that\n * point into a NodeTool install (`asset://`, `file://`, `memory://`) have no\n * meaning here, so they render as empty rather than as a broken element.\n * `package://` samples are served from the copies under assets/.\n */\nexport function mediaUrl(value: unknown): string | null {\n const raw =\n typeof value === \"string\"\n ? value\n : isRecord(value)\n ? (value.uri ?? value.url)\n : null;\n if (typeof raw !== \"string\" || raw === \"\") return null;\n if (/^(https?:|data:|blob:)/.test(raw) || raw.startsWith(\"/api/storage/\")) {\n return raw;\n }\n // Sample files the export copied under assets/.\n if (raw.startsWith(\"package://\")) {\n return `/api/package-assets/${raw.slice(\"package://\".length)}`;\n }\n return null;\n}\n",
16
+ "src/runtime/store.ts": "/**\n * The app instance's state: the shared reducer from `@nodetool-ai/app-runtime`\n * behind a subscribe/getState pair React reads with `useSyncExternalStore`.\n */\nimport { useCallback, useRef, useSyncExternalStore } from \"react\";\nimport {\n applyEvent,\n createInstanceState,\n type AppInstanceState,\n type AppStateEvent\n} from \"@nodetool-ai/app-runtime\";\n\nexport interface RuntimeStore {\n getState: () => AppInstanceState;\n dispatch: (event: AppStateEvent) => void;\n subscribe: (listener: () => void) => () => void;\n}\n\nexport function createRuntimeStore(): RuntimeStore {\n let state = createInstanceState();\n const listeners = new Set<() => void>();\n return {\n getState: () => state,\n dispatch: (event) => {\n const next = applyEvent(state, event);\n if (next === state) return;\n state = next;\n for (const listener of listeners) listener();\n },\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n }\n };\n}\n\n/**\n * Read one slice of state. The result is cached per state object, so a\n * selector that builds a fresh array still hands React a stable snapshot.\n */\nexport function useStoreSelector<T>(\n store: RuntimeStore,\n selector: (state: AppInstanceState) => T\n): T {\n const cache = useRef<{ state: AppInstanceState; selector: unknown; value: T } | null>(null);\n const getSnapshot = useCallback(() => {\n const state = store.getState();\n const cached = cache.current;\n if (cached && cached.state === state && cached.selector === selector) {\n return cached.value;\n }\n const value = selector(state);\n if (cached && cached.state !== state && Object.is(cached.value, value)) {\n cache.current = { state, selector, value: cached.value };\n return cached.value;\n }\n cache.current = { state, selector, value };\n return value;\n }, [selector, store]);\n return useSyncExternalStore(store.subscribe, getSnapshot);\n}\n",
17
+ "src/runtime/useAppRuntime.ts": "/**\n * The reactive engine: turns widget actions into runs on the app's server and\n * folds each run's streamed messages into instance state.\n *\n * Every semantic decision — what a message does to a slot, which invocation\n * owns it, what a run policy means — comes from `@nodetool-ai/app-runtime`,\n * the same module the NodeTool web and mobile runtimes use. This hook only\n * wires those pieces to `fetch`.\n *\n * Run identity: the job id is minted here and sent with the request, and the\n * server stamps it on every message. A message for any other job is dropped,\n * so two overlapping runs never write into each other's slots.\n */\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport {\n decideRun,\n implicitOperation,\n initialVariableValues,\n isLiveInvocation,\n mergeVariables,\n messageToEvents,\n operationTarget,\n outputVariableTargets,\n resolveOperationParams,\n stateKey,\n type AppAction,\n type ApplicationBundle,\n type BindingRef,\n type BindingScope,\n type InvocationState,\n type OperationBinding\n} from \"@nodetool-ai/app-runtime\";\nimport { createRuntimeStore, type RuntimeStore } from \"./store\";\nimport { runOperation, type RunMessage, type RunRequest } from \"./server\";\nimport { extractScriptIO, extractWorkflowIO, seedInputValue, type WorkflowIO } from \"./workflowIO\";\nimport { loadPersistedVariables, savePersistedVariables } from \"./persistence\";\nimport { collectModelRefs, type ModelRef } from \"./models\";\n\nexport interface AppRuntime {\n store: RuntimeStore;\n scope: BindingScope;\n operations: OperationBinding[];\n /** The bindable surface of the workflow an operation runs. */\n ioFor: (operationId: string) => WorkflowIO;\n dispatch: (action: AppAction) => void;\n write: (ref: BindingRef, value: unknown) => void;\n /** Model references a `ModelSelect` can offer, by kind. */\n modelChoices: Record<string, ModelRef[]>;\n}\n\ninterface StartedRun {\n operationId: string;\n invocationId: string;\n controller: AbortController;\n timer?: ReturnType<typeof setTimeout>;\n}\n\nconst PERSIST_DEBOUNCE_MS = 300;\n\nexport function useAppRuntime(bundle: ApplicationBundle, instanceKey: string): AppRuntime {\n const document = bundle.app;\n\n const ioByWorkflow = useMemo(() => {\n const map = new Map<string, WorkflowIO>();\n for (const workflow of bundle.workflows) {\n map.set(workflow.key, extractWorkflowIO(workflow.graph));\n }\n return map;\n }, [bundle.workflows]);\n\n const ioByScript = useMemo(() => {\n const map = new Map<string, WorkflowIO>();\n for (const script of bundle.scripts) {\n map.set(script.key, extractScriptIO(script.document));\n }\n return map;\n }, [bundle.scripts]);\n\n const operations = useMemo<OperationBinding[]>(\n () =>\n document.operations.length > 0\n ? document.operations\n : [implicitOperation(bundle.workflows[0]?.key ?? \"\")],\n [bundle.workflows, document.operations]\n );\n\n const ioFor = useCallback(\n (operationId: string): WorkflowIO => {\n const operation = operations.find((op) => op.id === operationId);\n const target = operation ? operationTarget(operation) : null;\n const io =\n target?.kind === \"script\"\n ? ioByScript.get(target.scriptId)\n : target\n ? ioByWorkflow.get(target.workflowId)\n : undefined;\n return io ?? { inputs: [], outputs: [], nodeIds: [], variableNames: [] };\n },\n [ioByScript, ioByWorkflow, operations]\n );\n\n const variables = useMemo(\n () =>\n mergeVariables(\n document.variables,\n [...ioByWorkflow.values()].flatMap((io) => io.variableNames)\n ),\n [document.variables, ioByWorkflow]\n );\n\n const scope = useMemo<BindingScope>(\n () => ({\n defaultOperationId: operations[0]?.id ?? \"main\",\n operations: operations.map((op) => {\n const io = ioFor(op.id);\n return {\n operationId: op.id,\n inputs: io.inputs.map(({ nodeId, name }) => ({ nodeId, name })),\n outputs: io.outputs.map(({ nodeId, name }) => ({ nodeId, name })),\n nodeIds: io.nodeIds,\n variableNames: io.variableNames\n };\n }),\n variables\n }),\n [ioFor, operations, variables]\n );\n\n const store = useMemo(() => createRuntimeStore(), []);\n const modelChoices = useMemo(() => collectModelRefs(bundle), [bundle]);\n\n // Seed every input slot with the value its control shows, so a form the user\n // never touched runs with exactly what is on screen.\n useEffect(() => {\n const values: Record<string, unknown> = {};\n for (const op of operations) {\n for (const input of ioFor(op.id).inputs) {\n const seed = seedInputValue(input);\n if (seed !== undefined) {\n values[stateKey({ kind: \"input\", operationId: op.id, nodeId: input.nodeId })] = seed;\n }\n }\n }\n store.dispatch({ type: \"seedInputs\", values });\n }, [ioFor, operations, store]);\n\n // Restore persisted variables first: seeding never clobbers, so last\n // session's value outranks the declared default.\n useEffect(() => {\n store.dispatch({ type: \"seedVariables\", values: loadPersistedVariables(instanceKey, variables) });\n store.dispatch({ type: \"seedVariables\", values: initialVariableValues(variables) });\n }, [instanceKey, store, variables]);\n\n useEffect(() => {\n let timer: ReturnType<typeof setTimeout> | null = null;\n const unsubscribe = store.subscribe(() => {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = null;\n savePersistedVariables(instanceKey, variables, store.getState().variables);\n }, PERSIST_DEBOUNCE_MS);\n });\n return () => {\n unsubscribe();\n if (timer) clearTimeout(timer);\n };\n }, [instanceKey, store, variables]);\n\n const owned = useRef(new Map<string, InvocationState>());\n const started = useRef(new Map<string, StartedRun>());\n\n const outputVariables = useMemo(() => {\n const byOperation = new Map<string, Map<string, string>>();\n for (const op of operations) {\n byOperation.set(\n op.id,\n new Map(outputVariableTargets(op).map(({ nodeId, variableId }) => [nodeId, variableId]))\n );\n }\n return byOperation;\n }, [operations]);\n\n const fold = useCallback(\n (message: RunMessage) => {\n const events = messageToEvents(message, {\n resolveInvocation: (jobId) => (jobId ? (owned.current.get(jobId) ?? null) : null),\n outputKey: (operationId, nodeId) =>\n ioFor(operationId).outputs.some((output) => output.nodeId === nodeId)\n ? stateKey({ kind: \"output\", operationId, nodeId })\n : null,\n outputVariable: (operationId, nodeId) =>\n outputVariables.get(operationId)?.get(nodeId) ?? null\n });\n for (const event of events) {\n store.dispatch(event);\n if (event.type === \"invocationStatus\") {\n const invocation = owned.current.get(event.invocationId);\n if (invocation) invocation.status = event.status;\n if (event.status !== \"pending\" && event.status !== \"running\") {\n const run = started.current.get(event.invocationId);\n if (run?.timer) clearTimeout(run.timer);\n started.current.delete(event.invocationId);\n }\n }\n }\n },\n [ioFor, outputVariables, store]\n );\n\n const settle = useCallback(\n (invocationId: string, status: \"failed\" | \"cancelled\" | \"completed\", error?: string) => {\n const invocation = owned.current.get(invocationId);\n if (!invocation || !isLiveInvocation(invocation)) return;\n invocation.status = status;\n const run = started.current.get(invocationId);\n if (run?.timer) clearTimeout(run.timer);\n started.current.delete(invocationId);\n store.dispatch({\n type: \"invocationStatus\",\n invocationId,\n status,\n ...(error ? { error } : {})\n });\n },\n [store]\n );\n\n const failToStart = useCallback(\n (operationId: string, error: string) => {\n const invocation: InvocationState = {\n id: `failed-${operationId}-${Date.now()}`,\n operationId,\n status: \"failed\",\n error,\n startedAt: Date.now()\n };\n owned.current.set(invocation.id, invocation);\n store.dispatch({ type: \"runStarted\", invocation, outputKeys: [] });\n },\n [store]\n );\n\n const cancelInvocations = useCallback(\n (ids: ReadonlyArray<string>, error?: string) => {\n for (const id of ids) {\n started.current.get(id)?.controller.abort();\n settle(id, error ? \"failed\" : \"cancelled\", error);\n }\n },\n [settle]\n );\n\n const waitForSettled = useCallback(\n (ids: ReadonlyArray<string>) =>\n new Promise<void>((resolve) => {\n const done = () =>\n ids.every((id) => {\n const invocation = store.getState().invocations[id];\n return !invocation || !isLiveInvocation(invocation);\n });\n if (done()) {\n resolve();\n return;\n }\n const unsubscribe = store.subscribe(() => {\n if (!done()) return;\n unsubscribe();\n resolve();\n });\n }),\n [store]\n );\n\n const run = useCallback(\n async (operationId: string) => {\n const operation = operations.find((op) => op.id === operationId);\n if (!operation) {\n failToStart(operations[0]?.id ?? \"main\", `This app has no operation \"${operationId}\".`);\n return;\n }\n const decision = decideRun(store.getState(), operation);\n if (decision.kind === \"replace\") cancelInvocations(decision.cancel);\n else if (decision.kind === \"queue\") await waitForSettled(decision.after);\n\n const io = ioFor(operation.id);\n const params = resolveOperationParams({\n operation,\n state: store.getState(),\n inputNodeIds: io.inputs.map((input) => input.nodeId),\n inputName: (nodeId) => io.inputs.find((input) => input.nodeId === nodeId)?.name\n });\n\n const invocationId = crypto.randomUUID();\n const runState: StartedRun = {\n operationId: operation.id,\n invocationId,\n controller: new AbortController()\n };\n const invocation: InvocationState = {\n id: invocationId,\n operationId: operation.id,\n status: \"running\",\n startedAt: Date.now()\n };\n owned.current.set(invocationId, invocation);\n started.current.set(invocationId, runState);\n store.dispatch({\n type: \"runStarted\",\n invocation,\n outputKeys: io.outputs.map((output) =>\n stateKey({ kind: \"output\", operationId: operation.id, nodeId: output.nodeId })\n )\n });\n if (operation.timeoutMs && operation.timeoutMs > 0) {\n const limit = operation.timeoutMs;\n runState.timer = setTimeout(\n () => cancelInvocations([invocationId], `Run timed out after ${limit}ms`),\n limit\n );\n }\n\n try {\n const target = operationTarget(operation);\n const runTarget: RunRequest[\"target\"] =\n target.kind === \"script\" ? { script: target.scriptId } : { workflow: target.workflowId };\n await runOperation({\n target: runTarget,\n params,\n jobId: invocationId,\n signal: runState.controller.signal,\n onMessage: fold\n });\n // A stream that closed without a terminal status still has to end.\n settle(invocationId, \"failed\", \"The server closed the run without a result.\");\n } catch (error) {\n if (runState.controller.signal.aborted) return;\n settle(invocationId, \"failed\", error instanceof Error ? error.message : \"Run failed\");\n }\n },\n [cancelInvocations, failToStart, fold, ioFor, operations, settle, store, waitForSettled]\n );\n\n const cancel = useCallback(\n (operationId: string, invocationId?: string) => {\n if (invocationId) {\n cancelInvocations([invocationId]);\n return;\n }\n cancelInvocations(\n Object.values(store.getState().invocations)\n .filter((i) => i.operationId === operationId && isLiveInvocation(i))\n .map((i) => i.id)\n );\n },\n [cancelInvocations, store]\n );\n\n useEffect(\n () => () => {\n for (const runState of started.current.values()) {\n runState.controller.abort();\n if (runState.timer) clearTimeout(runState.timer);\n }\n },\n []\n );\n\n const write = useCallback(\n (ref: BindingRef, value: unknown) => {\n const key = stateKey(ref);\n switch (ref.kind) {\n case \"variable\":\n store.dispatch({ type: \"setVariable\", variableId: ref.variableId, value });\n break;\n case \"view\":\n store.dispatch({ type: \"setView\", key, value });\n break;\n default:\n store.dispatch({ type: \"setInput\", key, value });\n }\n },\n [store]\n );\n\n const dispatch = useCallback(\n (action: AppAction) => {\n switch (action.kind) {\n case \"run\":\n void run(action.operationId);\n break;\n case \"cancel\":\n cancel(action.operationId ?? scope.defaultOperationId, action.invocationId);\n break;\n case \"setVariable\":\n store.dispatch({ type: \"setVariable\", variableId: action.variableId, value: action.value });\n break;\n case \"toggleVariable\":\n store.dispatch({ type: \"toggleVariable\", variableId: action.variableId });\n break;\n default:\n // Resource commands read and write NodeTool documents, which an\n // exported app has no database for.\n console.warn(`\"${action.kind}\" needs a NodeTool server and is ignored here.`);\n }\n },\n [cancel, run, scope.defaultOperationId, store]\n );\n\n return useMemo(\n () => ({ store, scope, operations, ioFor, dispatch, write, modelChoices }),\n [dispatch, ioFor, modelChoices, operations, scope, store, write]\n );\n}\n",
18
+ "src/runtime/workflowIO.ts": "/**\n * The bindable surface of a workflow graph: the Input nodes an app writes, the\n * Output nodes it displays, and the SetVariable channels it can read. Mirrors\n * the web and mobile readers, so a document binds the same way here.\n */\nimport type { BundleGraph, BundleJsScriptDocument } from \"@nodetool-ai/app-runtime\";\n\nexport type WorkflowInputKind =\n | \"string\"\n | \"integer\"\n | \"float\"\n | \"boolean\"\n | \"color\"\n | \"image\"\n | \"video\"\n | \"audio\"\n | \"document\"\n | \"dataframe\"\n | \"file_path\"\n | \"folder_path\"\n | \"folder\"\n | \"select\"\n | \"language_model\"\n | \"image_model\"\n | \"video_model\"\n | \"tts_model\"\n | \"asr_model\"\n | \"music_model\"\n | \"embedding_model\"\n | \"image_list\"\n | \"video_list\"\n | \"audio_list\"\n | \"text_list\"\n | \"model3d\"\n | \"image_size\"\n | \"huggingface_model\";\n\nconst KIND_BY_NODE_TYPE: Readonly<Record<string, WorkflowInputKind>> = {\n \"nodetool.input.StringInput\": \"string\",\n \"nodetool.input.TextInput\": \"string\",\n \"nodetool.input.MessageInput\": \"string\",\n \"nodetool.input.BooleanInput\": \"boolean\",\n \"nodetool.input.IntegerInput\": \"integer\",\n \"nodetool.input.FloatInput\": \"float\",\n \"nodetool.input.ColorInput\": \"color\",\n \"nodetool.input.ImageInput\": \"image\",\n \"nodetool.input.VideoInput\": \"video\",\n \"nodetool.input.AudioInput\": \"audio\",\n \"nodetool.input.RealtimeAudioInput\": \"audio\",\n \"nodetool.input.DocumentInput\": \"document\",\n \"nodetool.input.DataFrameInput\": \"dataframe\",\n \"nodetool.input.DataframeInput\": \"dataframe\",\n \"nodetool.input.Model3DInput\": \"model3d\",\n \"nodetool.input.ImageSizeInput\": \"image_size\",\n \"nodetool.input.HuggingFaceModelInput\": \"huggingface_model\",\n \"nodetool.input.FilePathInput\": \"file_path\",\n \"nodetool.input.FolderPathInput\": \"folder_path\",\n \"nodetool.input.Folder\": \"folder\",\n \"nodetool.input.SelectInput\": \"select\",\n \"nodetool.input.LanguageModelInput\": \"language_model\",\n \"nodetool.input.ImageModelInput\": \"image_model\",\n \"nodetool.input.VideoModelInput\": \"video_model\",\n \"nodetool.input.TTSModelInput\": \"tts_model\",\n \"nodetool.input.ASRModelInput\": \"asr_model\",\n \"nodetool.input.MusicModelInput\": \"music_model\",\n \"nodetool.input.EmbeddingModelInput\": \"embedding_model\",\n \"nodetool.input.ImageListInput\": \"image_list\",\n \"nodetool.input.VideoListInput\": \"video_list\",\n \"nodetool.input.AudioListInput\": \"audio_list\",\n \"nodetool.input.TextListInput\": \"text_list\",\n \"nodetool.input.StringListInput\": \"text_list\"\n};\n\nexport interface WorkflowInputIO {\n nodeId: string;\n nodeType: string;\n name: string;\n label: string;\n kind: WorkflowInputKind;\n description?: string;\n min?: number;\n max?: number;\n multiline?: boolean;\n options?: string[];\n defaultValue?: unknown;\n}\n\nexport interface WorkflowOutputIO {\n nodeId: string;\n nodeType: string;\n name: string;\n label: string;\n}\n\nexport interface WorkflowIO {\n inputs: WorkflowInputIO[];\n outputs: WorkflowOutputIO[];\n nodeIds: string[];\n variableNames: string[];\n}\n\nexport const EMPTY_IO: WorkflowIO = { inputs: [], outputs: [], nodeIds: [], variableNames: [] };\n\nconst SET_VARIABLE_NODE_TYPE = \"nodetool.workflows.base_node.SetVariable\";\n\ninterface GraphNode {\n id: string;\n type: string;\n data?: Record<string, unknown>;\n properties?: Record<string, unknown>;\n ui_properties?: Record<string, unknown>;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst nonEmpty = (value: unknown): value is string =>\n typeof value === \"string\" && value.trim().length > 0;\n\nconst asNode = (value: unknown): GraphNode | null =>\n isRecord(value) && typeof value.id === \"string\" && typeof value.type === \"string\"\n ? (value as unknown as GraphNode)\n : null;\n\nconst nodeData = (node: GraphNode): Record<string, unknown> =>\n (isRecord(node.data) ? node.data : isRecord(node.properties) ? node.properties : {});\n\nconst isOutputNode = (type: string): boolean =>\n type.includes(\".output.\") || type === \"nodetool.workflows.base_node.Preview\";\n\nexport const getWorkflowInputKind = (nodeType: string): WorkflowInputKind | null =>\n KIND_BY_NODE_TYPE[nodeType] ?? null;\n\nexport function extractWorkflowIO(graph: BundleGraph | undefined): WorkflowIO {\n if (!graph) return EMPTY_IO;\n const inputs: WorkflowInputIO[] = [];\n const outputs: WorkflowOutputIO[] = [];\n const nodeIds: string[] = [];\n const variableNames = new Set<string>();\n\n for (const raw of graph.nodes) {\n const node = asNode(raw);\n if (!node) continue;\n nodeIds.push(node.id);\n if (isRecord(node.ui_properties) && node.ui_properties.bypassed === true) continue;\n const data = nodeData(node);\n const name = nonEmpty(data.name) ? data.name : node.id;\n const label = nonEmpty(data.label) ? data.label : name;\n\n if (node.type === SET_VARIABLE_NODE_TYPE && nonEmpty(data.name)) {\n variableNames.add(data.name.trim());\n continue;\n }\n\n const kind = getWorkflowInputKind(node.type);\n if (kind) {\n inputs.push({\n nodeId: node.id,\n nodeType: node.type,\n name,\n label,\n kind,\n description: nonEmpty(data.description) ? data.description : undefined,\n min: typeof data.min === \"number\" ? data.min : undefined,\n max: typeof data.max === \"number\" ? data.max : undefined,\n multiline:\n data.line_mode === \"multi_line\" ||\n data.line_mode === \"multiline\" ||\n data.multiline === true\n ? true\n : undefined,\n options: Array.isArray(data.options)\n ? data.options.filter((option): option is string => typeof option === \"string\")\n : undefined,\n defaultValue: data.value\n });\n continue;\n }\n if (isOutputNode(node.type)) {\n outputs.push({ nodeId: node.id, nodeType: node.type, name, label });\n }\n }\n\n return {\n inputs,\n outputs,\n nodeIds,\n variableNames: [...variableNames].sort((a, b) => a.localeCompare(b))\n };\n}\n\n/** Script port types (TypeMetadata names) a widget can edit, by the kind it edits. */\nconst KIND_BY_PORT_TYPE: Readonly<Record<string, WorkflowInputKind>> = {\n str: \"string\",\n text: \"string\",\n int: \"integer\",\n float: \"float\",\n bool: \"boolean\",\n color: \"color\",\n image: \"image\",\n video: \"video\",\n audio: \"audio\",\n document: \"document\",\n dataframe: \"dataframe\",\n model_3d: \"model3d\",\n language_model: \"language_model\",\n image_model: \"image_model\",\n video_model: \"video_model\",\n tts_model: \"tts_model\",\n asr_model: \"asr_model\",\n music_model: \"music_model\",\n embedding_model: \"embedding_model\",\n \"list[image]\": \"image_list\",\n \"list[video]\": \"video_list\",\n \"list[audio]\": \"audio_list\",\n \"list[str]\": \"text_list\"\n};\n\n/**\n * The bindable surface of a JS script: its declared ports. A script has no\n * nodes, so each port's name stands in for a node id, the way NodeTool binds\n * script operations. A port type no widget edits is offered as text.\n */\nexport function extractScriptIO(document: BundleJsScriptDocument | undefined): WorkflowIO {\n if (!document) return EMPTY_IO;\n return {\n inputs: document.inputs.map((port) => ({\n nodeId: port.name,\n nodeType: `jsscript.input.${port.type}`,\n name: port.name,\n label: port.name,\n kind: KIND_BY_PORT_TYPE[port.type] ?? \"string\"\n })),\n outputs: document.outputs.map((port) => ({\n nodeId: port.name,\n nodeType: `jsscript.output.${port.type}`,\n name: port.name,\n label: port.name\n })),\n nodeIds: [...document.inputs, ...document.outputs].map((port) => port.name),\n variableNames: []\n };\n}\n\n/**\n * The value an untouched input runs with: the node's saved default, else the\n * fallback its control displays, so an untouched form runs with what it shows.\n */\nexport function seedInputValue(input: WorkflowInputIO): unknown {\n if (input.defaultValue !== undefined && input.defaultValue !== null) {\n return input.defaultValue;\n }\n switch (input.kind) {\n case \"boolean\":\n return false;\n case \"integer\":\n case \"float\":\n return input.min ?? 0;\n case \"select\":\n return input.options?.[0];\n default:\n return undefined;\n }\n}\n",
19
+ "src/styles.css": ":root {\n --nt-bg: #f7f7f8;\n --nt-surface: #ffffff;\n --nt-surface-2: #f0f0f2;\n --nt-text: #18181b;\n --nt-text-2: #52525b;\n --nt-text-3: #8a8a93;\n --nt-border: #e2e2e6;\n --nt-primary: #3b5bdb;\n --nt-on-primary: #ffffff;\n --nt-success: #2f9e44;\n --nt-warning: #e67700;\n --nt-error: #e03131;\n --nt-radius: 10px;\n --nt-gap: 16px;\n color-scheme: light dark;\n font-family: Inter, system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n font-size: 15px;\n line-height: 1.5;\n color: var(--nt-text);\n background: var(--nt-bg);\n}\n\n@media (prefers-color-scheme: dark) {\n :root {\n --nt-bg: #111113;\n --nt-surface: #1a1a1d;\n --nt-surface-2: #232327;\n --nt-text: #ececef;\n --nt-text-2: #b4b4bb;\n --nt-text-3: #7c7c85;\n --nt-border: #2e2e33;\n --nt-primary: #748ffc;\n --nt-on-primary: #0b0b0c;\n }\n}\n\n* { box-sizing: border-box; }\nbody { margin: 0; }\nimg, video, audio, iframe { max-width: 100%; }\n\n.nt-app { max-width: 1100px; margin: 0 auto; padding: 32px 20px 64px; }\n.nt-stack { display: flex; flex-direction: column; gap: var(--nt-gap); min-width: 0; }\n.nt-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; border: 0; padding: 0; margin: 0; }\n.nt-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; }\n.nt-columns { display: grid; align-items: start; }\n@media (max-width: 720px) { .nt-columns { grid-template-columns: 1fr !important; } }\n\n.nt-heading h1, .nt-heading h2, .nt-heading h3, .nt-heading h4 { margin: 0; line-height: 1.2; }\n.nt-heading h1 { font-size: 30px; font-weight: 600; }\n.nt-subtitle { margin: 6px 0 0; color: var(--nt-text-2); }\n.nt-text { margin: 0; white-space: pre-wrap; }\n.nt-tone-hint, .nt-tone-muted, .nt-tone-secondary { color: var(--nt-text-3); font-size: 13px; }\n.nt-label { font-weight: 500; font-size: 13px; color: var(--nt-text-2); padding: 0; }\n.nt-hint { font-size: 13px; color: var(--nt-text-3); }\n.nt-clamp { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }\n.nt-placeholder { padding: 20px; border: 1px dashed var(--nt-border); border-radius: var(--nt-radius); color: var(--nt-text-3); text-align: center; font-size: 13px; }\n\n.nt-panel { background: var(--nt-surface); border: 1px solid var(--nt-border); border-radius: var(--nt-radius); padding: 18px; display: flex; flex-direction: column; gap: var(--nt-gap); }\n.nt-panel-outlined { background: transparent; }\n.nt-panel-plain, .nt-panel-flat { background: transparent; border: 0; padding: 0; }\n.nt-panel-title { margin: 0; font-size: 16px; font-weight: 600; cursor: default; }\ndetails.nt-panel > summary { cursor: pointer; }\n.nt-divider { border: 0; border-top: 1px solid var(--nt-border); margin: 4px 0; width: 100%; }\n\n.nt-input { width: 100%; font: inherit; color: var(--nt-text); background: var(--nt-surface); border: 1px solid var(--nt-border); border-radius: 8px; padding: 9px 11px; }\n.nt-input:focus { outline: 2px solid var(--nt-primary); outline-offset: -1px; }\ntextarea.nt-input { resize: vertical; }\n.nt-mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; }\ninput[type=\"range\"] { width: 100%; accent-color: var(--nt-primary); }\n.nt-switch { display: flex; align-items: center; gap: 10px; }\n.nt-switch input { width: 18px; height: 18px; accent-color: var(--nt-primary); }\n.nt-choices { flex-direction: row; flex-wrap: wrap; }\n.nt-choices legend { width: 100%; margin-bottom: 6px; }\n.nt-chip { display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border: 1px solid var(--nt-border); border-radius: 999px; background: var(--nt-surface); font: inherit; color: var(--nt-text); cursor: pointer; }\n.nt-chip.nt-selected { background: var(--nt-primary); border-color: var(--nt-primary); color: var(--nt-on-primary); }\n.nt-chip:disabled { opacity: .5; cursor: default; }\n\n.nt-button-row { display: flex; }\n.nt-button { display: inline-flex; align-items: center; justify-content: center; gap: 8px; font: inherit; font-weight: 500; padding: 9px 18px; border-radius: 8px; border: 1px solid var(--nt-primary); background: var(--nt-primary); color: var(--nt-on-primary); cursor: pointer; text-decoration: none; }\n.nt-button:disabled { opacity: .55; cursor: default; }\n.nt-button-outlined { background: transparent; color: var(--nt-primary); }\n.nt-button-text { background: transparent; border-color: transparent; color: var(--nt-primary); }\n.nt-color-warning { --nt-primary: var(--nt-warning); }\n.nt-color-error { --nt-primary: var(--nt-error); }\n.nt-color-success { --nt-primary: var(--nt-success); }\n.nt-full { width: 100%; }\n.nt-spinner { width: 14px; height: 14px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: nt-spin .8s linear infinite; }\n@keyframes nt-spin { to { transform: rotate(360deg); } }\n\n.nt-progress { height: 6px; background: var(--nt-surface-2); border-radius: 999px; overflow: hidden; }\n.nt-progress > div { height: 100%; background: var(--nt-primary); transition: width .2s; }\n.nt-progress-indeterminate > div { width: 30%; animation: nt-slide 1.2s ease-in-out infinite; }\n@keyframes nt-slide { from { transform: translateX(-100%); } to { transform: translateX(340%); } }\n\n.nt-alert { padding: 12px 14px; border-radius: var(--nt-radius); border: 1px solid; display: flex; flex-direction: column; gap: 4px; white-space: pre-wrap; }\n.nt-alert-info { border-color: var(--nt-primary); }\n.nt-alert-success { border-color: var(--nt-success); }\n.nt-alert-warning { border-color: var(--nt-warning); }\n.nt-alert-error { border-color: var(--nt-error); }\n.nt-status-done { color: var(--nt-success); }\n.nt-status-error { color: var(--nt-error); }\n\n.nt-figure { margin: 0; display: flex; flex-direction: column; gap: 8px; }\n.nt-figure figcaption { font-size: 13px; color: var(--nt-text-3); }\n.nt-image { width: 100%; border-radius: var(--nt-radius); background: var(--nt-surface-2); display: block; }\n.nt-video { width: 100%; border-radius: var(--nt-radius); background: #000; }\n.nt-audio { width: 100%; }\n.nt-pdf { width: 100%; border: 1px solid var(--nt-border); border-radius: var(--nt-radius); }\n.nt-gallery { display: grid; gap: 10px; }\n.nt-tile { padding: 0; border: 2px solid transparent; border-radius: var(--nt-radius); overflow: hidden; background: var(--nt-surface-2); cursor: pointer; aspect-ratio: 1; }\n.nt-tile img { width: 100%; height: 100%; object-fit: cover; display: block; }\n.nt-tile.nt-selected { border-color: var(--nt-primary); }\n.nt-lightbox { position: fixed; inset: 0; background: rgba(0,0,0,.85); display: flex; align-items: center; justify-content: center; padding: 24px; z-index: 10; cursor: zoom-out; }\n.nt-lightbox img { max-height: 100%; }\n.nt-compare { position: relative; border-radius: var(--nt-radius); overflow: hidden; background: var(--nt-surface-2); }\n.nt-compare img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; }\n\n.nt-cards { display: grid; gap: 10px; }\n.nt-card { display: flex; flex-direction: column; gap: 6px; text-align: left; font: inherit; color: var(--nt-text); padding: 12px; border: 1px solid var(--nt-border); border-radius: var(--nt-radius); background: var(--nt-surface); cursor: pointer; }\n.nt-card img { width: 100%; height: 96px; object-fit: cover; border-radius: 6px; }\n.nt-card.nt-selected { border-color: var(--nt-primary); box-shadow: 0 0 0 1px var(--nt-primary); }\n.nt-card:disabled { opacity: .5; cursor: default; }\n.nt-steps { display: flex; flex-wrap: wrap; gap: 8px; list-style: none; padding: 0; margin: 0; }\n.nt-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--nt-border); }\n.nt-tab { font: inherit; padding: 8px 14px; border: 0; border-bottom: 2px solid transparent; background: none; color: var(--nt-text-2); cursor: pointer; }\n.nt-tab.nt-selected { color: var(--nt-text); border-bottom-color: var(--nt-primary); }\n\n.nt-table-wrap { overflow-x: auto; border: 1px solid var(--nt-border); border-radius: var(--nt-radius); }\n.nt-table { width: 100%; border-collapse: collapse; font-size: 14px; }\n.nt-table th, .nt-table td { padding: 8px 10px; text-align: left; border-bottom: 1px solid var(--nt-border); vertical-align: top; }\n.nt-table th { background: var(--nt-surface-2); font-weight: 500; }\n.nt-kv { margin: 0; display: flex; flex-direction: column; }\n.nt-kv > div { display: flex; gap: 12px; padding: 6px 0; border-bottom: 1px solid var(--nt-border); }\n.nt-kv dt { color: var(--nt-text-3); min-width: 120px; }\n.nt-kv dd { margin: 0; overflow-wrap: anywhere; }\n.nt-stat { font-size: 28px; font-weight: 600; }\n.nt-list { margin: 0; padding-left: 20px; }\n.nt-list .nt-markdown > p { margin: 0; }\n\n.nt-code { margin: 0; padding: 12px; background: var(--nt-surface-2); border-radius: 8px; overflow: auto; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; white-space: pre-wrap; }\n.nt-markdown > :first-child { margin-top: 0; }\n.nt-markdown > :last-child { margin-bottom: 0; }\n.nt-markdown code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; background: var(--nt-surface-2); padding: 1px 4px; border-radius: 4px; }\n.nt-markdown pre code { background: none; padding: 0; }\n.nt-markdown blockquote { margin: 0; padding-left: 12px; border-left: 3px solid var(--nt-border); color: var(--nt-text-2); }\n.nt-markdown a { color: var(--nt-primary); }\n\n.nt-activity { display: flex; flex-direction: column; gap: 8px; overflow: auto; }\n.nt-activity-tool { padding: 8px 10px; border-radius: 8px; background: var(--nt-surface-2); display: flex; flex-direction: column; gap: 4px; }\n.nt-thread { display: flex; flex-direction: column; gap: 10px; overflow: auto; }\n.nt-bubble { max-width: 85%; padding: 10px 12px; border-radius: 12px; border: 1px solid var(--nt-border); }\n.nt-bubble-user { align-self: flex-end; background: var(--nt-surface-2); }\n.nt-bubble-assistant { align-self: flex-start; background: var(--nt-surface); }\n",
20
+ "src/widgets/Markdown.tsx": "/**\n * A small Markdown renderer for model output: headings, paragraphs, lists,\n * quotes, fenced code, inline code, bold, italic and links. It builds React\n * elements, never HTML strings, so text a model wrote cannot inject markup.\n */\nimport type { ReactNode } from \"react\";\n\nconst SAFE_LINK = /^(https?:|mailto:)/i;\n\nfunction renderInline(text: string, keyPrefix: string): ReactNode[] {\n const nodes: ReactNode[] = [];\n const pattern = /(`[^`]+`)|(\\*\\*[^*]+\\*\\*)|(__[^_]+__)|(\\*[^*\\s][^*]*\\*)|(_[^_\\s][^_]*_)|(\\[[^\\]]+\\]\\([^)\\s]+\\))/g;\n let last = 0;\n let index = 0;\n for (const match of text.matchAll(pattern)) {\n const at = match.index ?? 0;\n if (at > last) nodes.push(text.slice(last, at));\n const token = match[0];\n const key = `${keyPrefix}-${index++}`;\n if (token.startsWith(\"`\")) {\n nodes.push(<code key={key}>{token.slice(1, -1)}</code>);\n } else if (token.startsWith(\"**\") || token.startsWith(\"__\")) {\n nodes.push(<strong key={key}>{renderInline(token.slice(2, -2), key)}</strong>);\n } else if (token.startsWith(\"[\")) {\n const close = token.indexOf(\"](\");\n const label = token.slice(1, close);\n const href = token.slice(close + 2, -1);\n nodes.push(\n SAFE_LINK.test(href) ? (\n <a key={key} href={href} target=\"_blank\" rel=\"noreferrer\">\n {label}\n </a>\n ) : (\n label\n )\n );\n } else {\n nodes.push(<em key={key}>{renderInline(token.slice(1, -1), key)}</em>);\n }\n last = at + token.length;\n }\n if (last < text.length) nodes.push(text.slice(last));\n return nodes;\n}\n\nexport function Markdown({ text }: { text: string }): ReactNode {\n const lines = text.replace(/\\r\\n/g, \"\\n\").split(\"\\n\");\n const blocks: ReactNode[] = [];\n let i = 0;\n let key = 0;\n while (i < lines.length) {\n const line = lines[i];\n if (line.trim() === \"\") {\n i++;\n continue;\n }\n if (line.startsWith(\"```\")) {\n const code: string[] = [];\n i++;\n while (i < lines.length && !lines[i].startsWith(\"```\")) code.push(lines[i++]);\n i++;\n blocks.push(\n <pre key={key++} className=\"nt-code\">\n <code>{code.join(\"\\n\")}</code>\n </pre>\n );\n continue;\n }\n const heading = /^(#{1,6})\\s+(.*)$/.exec(line);\n if (heading) {\n const level = Math.min(heading[1].length + 1, 6);\n const Tag = `h${level}` as \"h2\";\n blocks.push(<Tag key={key}>{renderInline(heading[2], `h${key++}`)}</Tag>);\n i++;\n continue;\n }\n if (/^\\s*([-*+]|\\d+[.)])\\s+/.test(line)) {\n const ordered = /^\\s*\\d+[.)]\\s+/.test(line);\n const items: string[] = [];\n while (i < lines.length && /^\\s*([-*+]|\\d+[.)])\\s+/.test(lines[i])) {\n items.push(lines[i].replace(/^\\s*([-*+]|\\d+[.)])\\s+/, \"\"));\n i++;\n }\n const List = ordered ? \"ol\" : \"ul\";\n const listKey = key++;\n blocks.push(\n <List key={listKey}>\n {items.map((item, at) => (\n <li key={at}>{renderInline(item, `l${listKey}-${at}`)}</li>\n ))}\n </List>\n );\n continue;\n }\n if (line.startsWith(\">\")) {\n const quote: string[] = [];\n while (i < lines.length && lines[i].startsWith(\">\")) quote.push(lines[i++].replace(/^>\\s?/, \"\"));\n blocks.push(<blockquote key={key++}>{renderInline(quote.join(\" \"), `q${key}`)}</blockquote>);\n continue;\n }\n const paragraph: string[] = [];\n while (\n i < lines.length &&\n lines[i].trim() !== \"\" &&\n !/^(#{1,6}\\s|```|>|\\s*([-*+]|\\d+[.)])\\s+)/.test(lines[i])\n ) {\n paragraph.push(lines[i++]);\n }\n const paragraphKey = key++;\n blocks.push(\n <p key={paragraphKey}>\n {paragraph.flatMap((part, at) => [\n ...(at > 0 ? [<br key={`br${at}`} />] : []),\n ...renderInline(part, `p${paragraphKey}-${at}`)\n ])}\n </p>\n );\n }\n return <div className=\"nt-markdown\">{blocks}</div>;\n}\n",
21
+ "src/widgets/display.tsx": "/** Display widgets: they read a bound value and render it. */\nimport { useMemo, useState, type ReactNode } from \"react\";\nimport {\n isOperationRunning,\n operationTranscript,\n parseBinding,\n type ActivityEntry\n} from \"@nodetool-ai/app-runtime\";\nimport {\n useAppRuntimeContext,\n useBindingRef,\n useBindingValue,\n useRuntimeSelector,\n useWidgetRuntime\n} from \"../runtime/context\";\nimport { mediaUrl } from \"../runtime/server\";\nimport { Markdown } from \"./Markdown\";\nimport {\n FieldLabel,\n Placeholder,\n asItems,\n cellText,\n isRecord,\n numOr,\n str,\n type WidgetProps\n} from \"./shared\";\n\nconst NO_ACTIVITY: ReadonlyArray<ActivityEntry> = [];\n\nconst MEDIA_TYPES = new Set([\"image\", \"audio\", \"video\", \"document\", \"model_3d\", \"model3d\"]);\n\n/** Any value a workflow can emit, rendered by its shape. */\nexport function ValueView({ value }: { value: unknown }): ReactNode {\n if (value == null || value === \"\") return null;\n if (typeof value === \"string\") return <Markdown text={value} />;\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return <div className=\"nt-text\">{String(value)}</div>;\n }\n if (Array.isArray(value)) {\n return (\n <div className=\"nt-stack\">\n {value.map((item, index) => (\n <ValueView key={index} value={item} />\n ))}\n </div>\n );\n }\n if (isRecord(value) && typeof value.type === \"string\" && MEDIA_TYPES.has(value.type)) {\n return <MediaView value={value} />;\n }\n if (isRecord(value) && value.type === \"dataframe\") {\n return <DataTable value={value} />;\n }\n return <pre className=\"nt-code\">{JSON.stringify(value, null, 2)}</pre>;\n}\n\nfunction MediaView({ value }: { value: Record<string, unknown> }): ReactNode {\n const url = mediaUrl(value);\n if (!url) return <Placeholder text={`${str(value.type)} (not available outside NodeTool)`} />;\n switch (value.type) {\n case \"image\":\n return <img className=\"nt-image\" src={url} alt=\"\" />;\n case \"audio\":\n return <audio className=\"nt-audio\" src={url} controls />;\n case \"video\":\n return <video className=\"nt-video\" src={url} controls />;\n default:\n return (\n <a className=\"nt-button nt-button-outlined\" href={url} download target=\"_blank\" rel=\"noreferrer\">\n Open {value.type === \"document\" ? \"document\" : \"file\"}\n </a>\n );\n }\n}\n\nconst tableColumns = (rows: ReadonlyArray<unknown>): string[] => {\n const columns: string[] = [];\n for (const row of rows) {\n if (!isRecord(row)) continue;\n for (const key of Object.keys(row)) if (!columns.includes(key)) columns.push(key);\n }\n return columns;\n};\n\nfunction DataTable({ value }: { value: unknown }): ReactNode {\n let columns: string[];\n let rows: string[][];\n if (isRecord(value) && Array.isArray(value.data)) {\n const declared = Array.isArray(value.columns) ? value.columns : [];\n columns = declared.map((column) => (isRecord(column) ? str(column.name) : str(column)));\n rows = value.data.map((row) => (Array.isArray(row) ? row.map(cellText) : [cellText(row)]));\n } else {\n const items = asItems(value);\n columns = tableColumns(items);\n rows = items.map((row) =>\n columns.length === 0 ? [cellText(row)] : columns.map((column) => (isRecord(row) ? cellText(row[column]) : \"\"))\n );\n }\n return (\n <div className=\"nt-table-wrap\">\n <table className=\"nt-table\">\n {columns.length > 0 ? (\n <thead>\n <tr>\n {columns.map((column) => (\n <th key={column}>{column}</th>\n ))}\n </tr>\n </thead>\n ) : null}\n <tbody>\n {rows.map((cells, index) => (\n <tr key={index}>\n {cells.map((cell, at) => (\n <td key={at}>{cell}</td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}\n\nexport function HeadingWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const text = widget.formattedValue ?? (str(value) || str(widget.props.text));\n const subtitle = str(widget.props.subtitle);\n if (!text && !subtitle) return null;\n const level = Math.min(Math.max(Number(widget.props.level) || 1, 1), 4);\n const Tag = `h${level}` as \"h1\";\n return (\n <header className=\"nt-heading\">\n {text ? <Tag>{text}</Tag> : null}\n {subtitle ? <p className=\"nt-subtitle\">{subtitle}</p> : null}\n </header>\n );\n}\n\nexport function TextWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const text = widget.formattedValue ?? (str(value) || str(widget.props.text));\n if (!text) return null;\n const tone = str(widget.props.tone);\n return <p className={`nt-text${tone ? ` nt-tone-${tone}` : \"\"}`}>{text}</p>;\n}\n\nexport function MarkdownWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const text =\n widget.formattedValue ?? (asItems(value).map(cellText).join(\"\") || str(widget.props.text));\n return text ? <Markdown text={text} /> : null;\n}\n\nfunction DownloadLink({ url, label, filename }: { url: string; label: string; filename?: string }): ReactNode {\n return (\n <a className=\"nt-button nt-button-outlined\" href={url} download={filename || true} target=\"_blank\" rel=\"noreferrer\">\n {label}\n </a>\n );\n}\n\nexport function ImageWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const urls = asItems(value).map(mediaUrl).filter((url): url is string => url !== null);\n if (urls.length === 0) return <Placeholder text={str(widget.props.placeholder) || \"No image yet\"} />;\n const height = numOr(widget.props.height, 0);\n const caption = str(widget.props.caption);\n return (\n <figure className=\"nt-figure\">\n {urls.map((url, index) => (\n <img\n key={`${url}-${index}`}\n className=\"nt-image\"\n src={url}\n alt={caption}\n style={{\n objectFit: widget.props.fit === \"cover\" ? \"cover\" : \"contain\",\n ...(height > 0 ? { height } : {}),\n ...(str(widget.props.aspectRatio) ? { aspectRatio: str(widget.props.aspectRatio) } : {})\n }}\n />\n ))}\n {caption ? <figcaption>{caption}</figcaption> : null}\n {widget.props.download === true || widget.props.download === \"yes\" ? (\n <DownloadLink url={urls[0]} label=\"Download\" filename={str(widget.props.filename)} />\n ) : null}\n </figure>\n );\n}\n\n/** Audio, Video, JSON and Output: whatever the value is, in its natural form. */\nexport function OutputWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n if (widget.formattedValue) return <Markdown text={widget.formattedValue} />;\n const items = asItems(value);\n if (items.length === 0) return <Placeholder text={str(widget.props.placeholder)} />;\n const shown = items.every((item) => typeof item === \"string\") ? items.join(\"\") : value;\n const url = mediaUrl(items[0]);\n return (\n <div className=\"nt-stack\">\n <ValueView value={shown} />\n {url && (widget.props.download === true || widget.props.download === \"yes\") ? (\n <DownloadLink url={url} label=\"Download\" filename={str(widget.props.filename)} />\n ) : null}\n </div>\n );\n}\n\nexport function JsonWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n if (widget.formattedValue) return <pre className=\"nt-code\">{widget.formattedValue}</pre>;\n if (value === undefined) return null;\n return <pre className=\"nt-code\">{JSON.stringify(value, null, 2)}</pre>;\n}\n\nexport function TableWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const empty =\n value == null || (Array.isArray(value) && value.length === 0) || (isRecord(value) && Array.isArray(value.data) && value.data.length === 0);\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} />\n {empty ? <Placeholder text={str(widget.props.placeholder) || \"No rows\"} /> : <DataTable value={value} />}\n </div>\n );\n}\n\nexport function ProgressWidget(widget: WidgetProps): ReactNode {\n const { value, running, progress, activity } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const ratio = typeof value === \"number\" ? value : progress;\n const label = (running ? activity : undefined) ?? str(widget.props.label);\n if (!running && ratio === undefined) return null;\n return (\n <div className=\"nt-field\" role=\"status\">\n {label ? <div className=\"nt-hint\">{label}</div> : null}\n {ratio === undefined ? (\n <div className=\"nt-progress nt-progress-indeterminate\">\n <div />\n </div>\n ) : (\n <div className=\"nt-progress\">\n <div style={{ width: `${Math.round(Math.min(Math.max(ratio, 0), 1) * 100)}%` }} />\n </div>\n )}\n </div>\n );\n}\n\nconst TOOL_STATUS: Record<string, string> = { running: \"Running\", done: \"Done\", error: \"Failed\" };\n\nexport function AgentActivityWidget(widget: WidgetProps): ReactNode {\n const ref = parseBinding(str(widget.props.binding));\n const operationId = ref?.kind === \"execution\" ? ref.operationId : null;\n const entries = useRuntimeSelector((state) =>\n operationId ? operationTranscript(state, operationId) : NO_ACTIVITY\n );\n const running = useRuntimeSelector((state) =>\n operationId ? isOperationRunning(state, operationId) : false\n );\n if (!running && entries.length === 0) return <Placeholder text={str(widget.props.placeholder)} />;\n const label = str(widget.props.label);\n return (\n <div className=\"nt-field\">\n {label ? <div className=\"nt-label\">{label}{running ? \" · Working\" : \"\"}</div> : null}\n <div className=\"nt-activity\" style={{ maxHeight: numOr(widget.props.height, 360) }}>\n {entries.map((entry, index) =>\n entry.kind === \"tool\" ? (\n <div key={entry.id} className=\"nt-activity-tool\">\n <div className=\"nt-row\">\n <span>{entry.label}</span>\n <span className={`nt-hint nt-status-${entry.status}`}>{TOOL_STATUS[entry.status]}</span>\n </div>\n {entry.result ? <div className=\"nt-hint nt-clamp\">{entry.result}</div> : null}\n </div>\n ) : (\n <Markdown key={`text-${index}`} text={entry.text} />\n )\n )}\n </div>\n </div>\n );\n}\n\nexport function AlertWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const text = widget.formattedValue ?? (cellText(value) || str(widget.props.text));\n if (!text) return null;\n const severity = str(widget.props.severity) || \"info\";\n const title = str(widget.props.title);\n return (\n <div className={`nt-alert nt-alert-${severity}`} role={severity === \"error\" ? \"alert\" : \"status\"}>\n {title ? <strong>{title}</strong> : null}\n <div>{text}</div>\n </div>\n );\n}\n\nexport function CodeBlockWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const text =\n widget.formattedValue ?? (value != null ? asItems(value).map(cellText).join(\"\\n\") : str(widget.props.text));\n if (!text) return null;\n const maxHeight = numOr(widget.props.maxHeight, 0);\n return (\n <pre className=\"nt-code\" style={maxHeight > 0 ? { maxHeight } : undefined}>\n <code>{text}</code>\n </pre>\n );\n}\n\nexport function ListWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const items = (widget.formattedValue ? [widget.formattedValue] : asItems(value)).filter(\n (item) => item != null && item !== \"\"\n );\n if (items.length === 0) return <Placeholder text={str(widget.props.placeholder)} />;\n const List = widget.props.ordered === true || widget.props.ordered === \"yes\" ? \"ol\" : \"ul\";\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} />\n <List className=\"nt-list\">\n {items.map((item, index) => (\n <li key={index}>{typeof item === \"string\" ? <Markdown text={item} /> : cellText(item)}</li>\n ))}\n </List>\n </div>\n );\n}\n\nexport function KeyValueWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const entries: Array<[string, unknown]> = isRecord(value)\n ? Object.entries(value)\n : value == null || value === \"\"\n ? []\n : [[\"value\", value]];\n if (entries.length === 0) return <Placeholder text={str(widget.props.placeholder)} />;\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} />\n <dl className=\"nt-kv\">\n {entries.map(([key, entry]) => (\n <div key={key}>\n <dt>{key}</dt>\n <dd>{cellText(entry)}</dd>\n </div>\n ))}\n </dl>\n </div>\n );\n}\n\nexport function StatWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const shown = widget.formattedValue ?? (value != null && value !== \"\" ? cellText(value) : \"\");\n const caption = str(widget.props.caption);\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} />\n <div className=\"nt-stat\">{shown || str(widget.props.placeholder) || \"—\"}</div>\n {caption ? <div className=\"nt-hint\">{caption}</div> : null}\n </div>\n );\n}\n\nexport function DownloadWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const url = mediaUrl(asItems(value)[0]);\n if (!url) return <Placeholder text={str(widget.props.placeholder)} />;\n return (\n <DownloadLink url={url} label={str(widget.props.label) || \"Download\"} filename={str(widget.props.filename)} />\n );\n}\n\n/** Model3D, Chart and PDF: shown as a file the browser can open. */\nexport function FileWidget(widget: WidgetProps & { title: string }): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const item = asItems(value)[0];\n if (item == null) return <Placeholder text={str(widget.props.placeholder) || `No ${widget.title} yet`} />;\n const url = mediaUrl(item);\n if (url && widget.title === \"PDF\") {\n return <iframe className=\"nt-pdf\" src={url} title=\"PDF\" style={{ height: numOr(widget.props.height, 480) }} />;\n }\n if (!url) return <ValueView value={value} />;\n return <DownloadLink url={url} label={`Open ${widget.title}`} />;\n}\n\nexport function ChartWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n if (value == null) return <Placeholder text={str(widget.props.placeholder) || \"No data yet\"} />;\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} />\n <DataTable value={value} />\n </div>\n );\n}\n\nconst sameItem = (a: unknown, b: unknown): boolean => {\n if (a === b) return true;\n const left = mediaUrl(a);\n const right = mediaUrl(b);\n if (left !== null && right !== null) return left === right;\n return isRecord(a) && isRecord(b) && JSON.stringify(a) === JSON.stringify(b);\n};\n\nexport function GalleryWidget(widget: WidgetProps): ReactNode {\n const { write } = useAppRuntimeContext();\n const { value, emit } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const selectionRef = useBindingRef(\n typeof widget.props.selectionBinding === \"string\" ? widget.props.selectionBinding : undefined,\n \"write\"\n );\n const selected = useBindingValue(selectionRef);\n const [open, setOpen] = useState<string | null>(null);\n const tiles = useMemo(\n () =>\n asItems(value)\n .map((item) => ({ item, url: mediaUrl(item) }))\n .filter((tile): tile is { item: unknown; url: string } => tile.url !== null),\n [value]\n );\n if (tiles.length === 0) return <Placeholder text={str(widget.props.placeholder) || \"No images yet\"} />;\n const size = numOr(widget.props.tileSize, 160);\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} />\n <div className=\"nt-gallery\" style={{ gridTemplateColumns: `repeat(auto-fill, minmax(${size}px, 1fr))` }}>\n {tiles.map(({ item, url }, index) => {\n const isSelected = selectionRef !== null && sameItem(selected, item);\n return (\n <button\n key={`${url}-${index}`}\n type=\"button\"\n className={`nt-tile${isSelected ? \" nt-selected\" : \"\"}`}\n aria-pressed={selectionRef ? isSelected : undefined}\n disabled={widget.disabled}\n onClick={() => {\n if (!selectionRef) {\n setOpen(url);\n return;\n }\n write(selectionRef, item);\n emit(\"change\");\n }}\n >\n <img src={url} alt={`Image ${index + 1} of ${tiles.length}`} />\n </button>\n );\n })}\n </div>\n {open ? (\n <div className=\"nt-lightbox\" role=\"dialog\" onClick={() => setOpen(null)}>\n <img src={open} alt=\"\" />\n </div>\n ) : null}\n </div>\n );\n}\n\nexport function ImageCompareWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const compare = useBindingValue(\n useBindingRef(typeof widget.props.compareBinding === \"string\" ? widget.props.compareBinding : undefined, \"read\")\n );\n const [position, setPosition] = useState(50);\n const before = mediaUrl(asItems(value)[0]);\n const after = mediaUrl(asItems(compare)[0]);\n if (!before && !after) return <Placeholder text={str(widget.props.placeholder) || \"Nothing to compare yet\"} />;\n if (!before || !after) return <img className=\"nt-image\" src={(before ?? after) as string} alt=\"\" />;\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} />\n <div className=\"nt-compare\" style={{ height: numOr(widget.props.height, 360) }}>\n <img src={after} alt=\"After\" />\n <img src={before} alt=\"Before\" style={{ clipPath: `inset(0 ${100 - position}% 0 0)` }} />\n </div>\n <input\n type=\"range\"\n min={0}\n max={100}\n value={position}\n aria-label=\"Compare position\"\n onChange={(event) => setPosition(Number(event.target.value))}\n />\n </div>\n );\n}\n\n/** Widgets that show a NodeTool document (sketch, timeline, storyboard). */\nexport function DocumentOnlyWidget(widget: WidgetProps & { title: string }): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n if (value == null || value === \"\") return <Placeholder text={str(widget.props.placeholder)} />;\n return <Placeholder text={`${widget.title} results open in NodeTool.`} />;\n}\n",
22
+ "src/widgets/inputs.tsx": "/** Input widgets: they write a bound value and fire the widget's events. */\nimport { useEffect, useId, useMemo, useState, type ReactNode } from \"react\";\nimport {\n composeUserMessage,\n encodeBinding,\n messageText,\n messagesFrom,\n parseChoiceCardOptions\n} from \"@nodetool-ai/app-runtime\";\nimport {\n useAppRuntimeContext,\n useBindingRef,\n useBindingValue,\n useWidgetRuntime\n} from \"../runtime/context\";\nimport { listModels, mediaUrl, uploadFile, type MediaKind, type ModelOption } from \"../runtime/server\";\nimport type { WorkflowInputIO } from \"../runtime/workflowIO\";\nimport { Markdown } from \"./Markdown\";\nimport { ValueView } from \"./display\";\nimport { FieldLabel, Placeholder, isRecord, numOr, str, type WidgetProps } from \"./shared\";\n\nconst clamp = (value: number, min?: number, max?: number): number =>\n Math.min(max ?? Infinity, Math.max(min ?? -Infinity, value));\n\nconst optionValues = (raw: unknown): Array<{ value: string; label: string }> =>\n Array.isArray(raw)\n ? raw\n .map((option) =>\n typeof option === \"string\"\n ? { value: option, label: option }\n : isRecord(option)\n ? { value: str(option.value), label: str(option.label) || str(option.value) }\n : { value: \"\", label: \"\" }\n )\n .filter((option) => option.value !== \"\")\n : [];\n\nexport function TextInputWidget(widget: WidgetProps): ReactNode {\n const id = useId();\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const multiline = widget.props.multiline === true || widget.props.multiline === \"yes\";\n const common = {\n id,\n className: \"nt-input\",\n value: str(value),\n placeholder: str(widget.props.placeholder),\n disabled: widget.disabled,\n onBlur: () => emit(\"change\", \"commit\")\n };\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} htmlFor={id} />\n {multiline ? (\n <textarea\n {...common}\n rows={4}\n onChange={(event) => {\n setValue(event.target.value);\n emit(\"change\");\n }}\n />\n ) : (\n <input\n {...common}\n type=\"text\"\n onChange={(event) => {\n setValue(event.target.value);\n emit(\"change\");\n }}\n />\n )}\n {str(widget.props.hint) ? <div className=\"nt-hint\">{str(widget.props.hint)}</div> : null}\n </div>\n );\n}\n\nexport function NumberInputWidget(widget: WidgetProps): ReactNode {\n const id = useId();\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const min = typeof widget.props.min === \"number\" ? widget.props.min : undefined;\n const max = typeof widget.props.max === \"number\" ? widget.props.max : undefined;\n const [text, setText] = useState(() => (value == null ? \"\" : String(value)));\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} htmlFor={id} />\n <input\n id={id}\n className=\"nt-input\"\n type=\"number\"\n min={min}\n max={max}\n step={typeof widget.props.step === \"number\" ? widget.props.step : undefined}\n value={text}\n disabled={widget.disabled}\n onChange={(event) => {\n setText(event.target.value);\n const parsed = Number(event.target.value);\n if (event.target.value === \"\" || Number.isNaN(parsed)) return;\n setValue(clamp(parsed, min, max));\n emit(\"change\");\n }}\n onBlur={() => emit(\"change\", \"commit\")}\n />\n </div>\n );\n}\n\nexport function SliderWidget(widget: WidgetProps): ReactNode {\n const id = useId();\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const min = numOr(widget.props.min, 0);\n const max = numOr(widget.props.max, 100);\n const step = numOr(widget.props.step, 1);\n const current = typeof value === \"number\" ? value : min;\n return (\n <div className=\"nt-field\">\n <div className=\"nt-row\">\n <FieldLabel text={str(widget.props.label)} htmlFor={id} />\n <span className=\"nt-hint\">{current}</span>\n </div>\n <input\n id={id}\n type=\"range\"\n min={min}\n max={max}\n step={step}\n value={current}\n disabled={widget.disabled}\n onChange={(event) => {\n setValue(Number(event.target.value));\n emit(\"change\");\n }}\n onPointerUp={() => emit(\"change\", \"commit\")}\n onKeyUp={() => emit(\"change\", \"commit\")}\n />\n </div>\n );\n}\n\nexport function SwitchWidget(widget: WidgetProps): ReactNode {\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n return (\n <label className=\"nt-switch\">\n <input\n type=\"checkbox\"\n checked={value === true}\n disabled={widget.disabled}\n onChange={(event) => {\n setValue(event.target.checked);\n emit(\"change\");\n }}\n />\n <span>{str(widget.props.label)}</span>\n </label>\n );\n}\n\nexport function SelectWidget(widget: WidgetProps): ReactNode {\n const id = useId();\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const options = optionValues(widget.props.options);\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} htmlFor={id} />\n <select\n id={id}\n className=\"nt-input\"\n value={str(value)}\n disabled={widget.disabled}\n onChange={(event) => {\n setValue(event.target.value);\n emit(\"change\");\n }}\n >\n {value == null || value === \"\" ? <option value=\"\">Choose…</option> : null}\n {options.map((option, index) => (\n <option key={`${option.value}-${index}`} value={option.value}>\n {option.label}\n </option>\n ))}\n </select>\n </div>\n );\n}\n\nexport function RadioGroupWidget(widget: WidgetProps): ReactNode {\n const name = useId();\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n return (\n <fieldset className=\"nt-field nt-choices\">\n <legend className=\"nt-label\">{str(widget.props.label)}</legend>\n {optionValues(widget.props.options).map((option, index) => (\n <label key={`${option.value}-${index}`} className=\"nt-chip\">\n <input\n type=\"radio\"\n name={name}\n checked={str(value) === option.value}\n disabled={widget.disabled}\n onChange={() => {\n setValue(option.value);\n emit(\"change\");\n }}\n />\n {option.label}\n </label>\n ))}\n </fieldset>\n );\n}\n\nexport function CheckboxGroupWidget(widget: WidgetProps): ReactNode {\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const options = optionValues(widget.props.options);\n const checked = Array.isArray(value) ? value.map(str) : [];\n return (\n <fieldset className=\"nt-field nt-choices\">\n <legend className=\"nt-label\">{str(widget.props.label)}</legend>\n {options.map((option, index) => (\n <label key={`${option.value}-${index}`} className=\"nt-chip\">\n <input\n type=\"checkbox\"\n checked={checked.includes(option.value)}\n disabled={widget.disabled}\n onChange={() => {\n const on = checked.includes(option.value);\n setValue(\n options\n .map((o) => o.value)\n .filter((v) => (v === option.value ? !on : checked.includes(v)))\n );\n emit(\"change\");\n }}\n />\n {option.label}\n </label>\n ))}\n </fieldset>\n );\n}\n\nexport function DateInputWidget(widget: WidgetProps): ReactNode {\n const id = useId();\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const withTime = widget.props.withTime === true || widget.props.withTime === \"yes\";\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} htmlFor={id} />\n <input\n id={id}\n className=\"nt-input\"\n type={withTime ? \"datetime-local\" : \"date\"}\n value={str(value)}\n disabled={widget.disabled}\n onChange={(event) => {\n setValue(event.target.value === \"\" ? null : event.target.value);\n emit(\"change\");\n }}\n onBlur={() => emit(\"change\", \"commit\")}\n />\n </div>\n );\n}\n\n/** Color inputs carry either a hex string or a `{type: \"color\", value}` ref. */\nexport function ColorInputWidget(widget: WidgetProps): ReactNode {\n const id = useId();\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const asRef = isRecord(value) && value.type === \"color\";\n const hex = asRef ? str(value.value) : str(value);\n const write = (next: string) => {\n setValue(asRef ? { ...value, value: next } : next);\n emit(\"change\");\n };\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label) || \"Color\"} htmlFor={id} />\n <div className=\"nt-row\">\n <input\n type=\"color\"\n value={/^#[0-9a-fA-F]{6}$/.test(hex) ? hex : \"#000000\"}\n disabled={widget.disabled}\n onChange={(event) => write(event.target.value)}\n aria-label=\"Pick color\"\n />\n <input\n id={id}\n className=\"nt-input\"\n value={hex}\n placeholder=\"#RRGGBB\"\n disabled={widget.disabled}\n onChange={(event) => write(event.target.value)}\n />\n </div>\n </div>\n );\n}\n\nconst ACCEPT: Record<MediaKind, string> = {\n image: \"image/*\",\n audio: \"audio/*\",\n video: \"video/*\",\n document: \".pdf,.txt,.md,.doc,.docx,.csv,.json,.html,.xlsx\",\n model_3d: \".glb,.gltf,.obj,.fbx,.stl\"\n};\n\nconst MEDIA_LABEL: Record<MediaKind, string> = {\n image: \"image\",\n audio: \"audio\",\n video: \"video\",\n document: \"document\",\n model_3d: \"3D model\"\n};\n\n/** Upload a file, then write the ref the workflow input reads. */\nexport function MediaInputWidget(\n widget: WidgetProps & { kind: MediaKind; capture?: boolean; note?: string }\n): ReactNode {\n const id = useId();\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const url = mediaUrl(value);\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label) || `${MEDIA_LABEL[widget.kind]} input`} htmlFor={id} />\n {url ? <ValueView value={isRecord(value) ? value : { type: widget.kind, uri: url }} /> : null}\n <input\n id={id}\n type=\"file\"\n accept={ACCEPT[widget.kind]}\n {...(widget.capture ? { capture: \"user\" as const } : {})}\n disabled={widget.disabled || busy}\n onChange={async (event) => {\n const file = event.target.files?.[0];\n if (!file) return;\n setBusy(true);\n setError(null);\n try {\n setValue(await uploadFile(widget.kind, file));\n emit(\"change\");\n } catch (uploadError) {\n setError(uploadError instanceof Error ? uploadError.message : \"Upload failed\");\n } finally {\n setBusy(false);\n }\n }}\n />\n {busy ? <div className=\"nt-hint\">Uploading…</div> : null}\n {error ? <div className=\"nt-hint nt-status-error\">{error}</div> : null}\n {widget.note ? <div className=\"nt-hint\">{widget.note}</div> : null}\n </div>\n );\n}\n\n/** The four list inputs: several files, or several lines of text. */\nexport function MediaListInputWidget(widget: WidgetProps): ReactNode {\n const id = useId();\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const kind = str(widget.props.listKind) || \"image\";\n const items = Array.isArray(value) ? value : [];\n const [busy, setBusy] = useState(false);\n if (kind === \"text\") {\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} htmlFor={id} />\n <textarea\n id={id}\n className=\"nt-input\"\n rows={4}\n placeholder=\"One item per line\"\n value={items.map(str).join(\"\\n\")}\n disabled={widget.disabled}\n onChange={(event) => {\n setValue(event.target.value.split(\"\\n\").filter((line) => line.trim() !== \"\"));\n emit(\"change\");\n }}\n />\n </div>\n );\n }\n const mediaKind = (kind === \"audio\" || kind === \"video\" ? kind : \"image\") as MediaKind;\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} htmlFor={id} />\n {items.length > 0 ? <ValueView value={items} /> : null}\n <input\n id={id}\n type=\"file\"\n multiple\n accept={ACCEPT[mediaKind]}\n disabled={widget.disabled || busy}\n onChange={async (event) => {\n const files = [...(event.target.files ?? [])];\n if (files.length === 0) return;\n setBusy(true);\n try {\n setValue(await Promise.all(files.map((file) => uploadFile(mediaKind, file))));\n emit(\"change\");\n } finally {\n setBusy(false);\n }\n }}\n />\n </div>\n );\n}\n\nexport function PathInputWidget(widget: WidgetProps & { kind: \"file\" | \"folder\" }): ReactNode {\n const id = useId();\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const raw = isRecord(value) ? str(value.path) : str(value);\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label) || (widget.kind === \"file\" ? \"File path\" : \"Folder path\")} htmlFor={id} />\n <input\n id={id}\n className=\"nt-input\"\n value={raw}\n placeholder={str(widget.props.placeholder) || (widget.kind === \"file\" ? \"/path/to/file\" : \"/path/to/folder\")}\n disabled={widget.disabled}\n onChange={(event) => {\n setValue(isRecord(value) ? { ...value, path: event.target.value } : event.target.value);\n emit(\"change\");\n }}\n onBlur={() => emit(\"change\", \"commit\")}\n />\n <div className=\"nt-hint\">A path on the machine running this app's server.</div>\n </div>\n );\n}\n\nexport function ImageSizeInputWidget(widget: WidgetProps): ReactNode {\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const size = isRecord(value) ? value : {};\n const field = (key: \"width\" | \"height\") => (\n <input\n className=\"nt-input\"\n type=\"number\"\n aria-label={key}\n placeholder={key}\n value={typeof size[key] === \"number\" ? String(size[key]) : \"\"}\n disabled={widget.disabled}\n onChange={(event) => {\n const parsed = Number(event.target.value);\n setValue({ ...size, [key]: event.target.value === \"\" || Number.isNaN(parsed) ? undefined : parsed });\n emit(\"change\");\n }}\n />\n );\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label) || \"Image size\"} />\n <div className=\"nt-row\">\n {field(\"width\")}\n <span className=\"nt-hint\">×</span>\n {field(\"height\")}\n </div>\n </div>\n );\n}\n\n/** A dataframe edited as JSON rows: `[{\"column\": value}, ...]`. */\nexport function DataFrameInputWidget(widget: WidgetProps): ReactNode {\n const id = useId();\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const rows = useMemo(() => {\n if (!isRecord(value) || !Array.isArray(value.data)) return [];\n const columns = (Array.isArray(value.columns) ? value.columns : []).map((c) => (isRecord(c) ? str(c.name) : str(c)));\n return value.data.map((row) =>\n Object.fromEntries(columns.map((column, at) => [column, Array.isArray(row) ? row[at] : undefined]))\n );\n }, [value]);\n const [text, setText] = useState(() => JSON.stringify(rows, null, 2));\n const [error, setError] = useState<string | null>(null);\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} htmlFor={id} />\n <textarea\n id={id}\n className=\"nt-input nt-mono\"\n rows={8}\n value={text}\n disabled={widget.disabled}\n onChange={(event) => {\n setText(event.target.value);\n try {\n const parsed: unknown = JSON.parse(event.target.value);\n if (!Array.isArray(parsed)) throw new Error(\"Expected a JSON array of rows\");\n const columns = [...new Set(parsed.flatMap((row) => (isRecord(row) ? Object.keys(row) : [])))];\n setValue({\n type: \"dataframe\",\n columns: columns.map((name) => ({ name, data_type: \"object\" })),\n data: parsed.map((row) => columns.map((column) => (isRecord(row) ? row[column] : null)))\n });\n setError(null);\n emit(\"change\");\n } catch (parseError) {\n setError(parseError instanceof Error ? parseError.message : \"Invalid JSON\");\n }\n }}\n />\n {error ? <div className=\"nt-hint nt-status-error\">{error}</div> : null}\n </div>\n );\n}\n\n/** Model choices come from the models the app's own graphs already use. */\nexport function ModelSelectWidget(widget: WidgetProps): ReactNode {\n const id = useId();\n const { modelChoices } = useAppRuntimeContext();\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const kind = str(widget.props.modelKind) || (isRecord(value) ? str(value.type) : \"\") || \"language_model\";\n const task = str(widget.props.task) || undefined;\n const [offered, setOffered] = useState<ModelOption[]>([]);\n useEffect(() => {\n let live = true;\n void listModels(kind, task).then((models) => {\n if (live) setOffered(models);\n });\n return () => {\n live = false;\n };\n }, [kind, task]);\n const choices = useMemo(() => {\n // The graphs' own models first, then whatever the providers in .env offer.\n const list = [...(modelChoices[kind] ?? [])];\n for (const model of offered) {\n if (!list.some((m) => m.id === model.id && m.provider === model.provider)) list.push(model);\n }\n if (isRecord(value) && typeof value.id === \"string\" && value.id !== \"\" && !list.some((m) => m.id === value.id && m.provider === value.provider)) {\n list.unshift({ ...value, type: str(value.type) || kind, id: value.id });\n }\n return list;\n }, [kind, modelChoices, offered, value]);\n const keyOf = (model: { provider?: unknown; id: string }) => `${str(model.provider)}::${model.id}`;\n const current = isRecord(value) && typeof value.id === \"string\" && value.id !== \"\" ? keyOf({ provider: value.provider, id: value.id }) : \"\";\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label) || \"Model\"} htmlFor={id} />\n <select\n id={id}\n className=\"nt-input\"\n value={current}\n disabled={widget.disabled || choices.length === 0}\n onChange={(event) => {\n const picked = choices.find((model) => keyOf(model) === event.target.value);\n if (!picked) return;\n setValue(picked);\n emit(\"change\");\n }}\n >\n {current === \"\" ? <option value=\"\">Choose a model…</option> : null}\n {choices.map((model) => (\n <option key={keyOf(model)} value={keyOf(model)}>\n {str(model.name) || model.id}\n {model.provider ? ` (${str(model.provider)})` : \"\"}\n </option>\n ))}\n </select>\n </div>\n );\n}\n\nexport function ChoiceCardsWidget(widget: WidgetProps): ReactNode {\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const { value: bound } = useWidgetRuntime({\n id: `${widget.id}-options`,\n bindingMode: \"read\",\n binding: str(widget.props.optionsBinding) || undefined\n });\n const options = parseChoiceCardOptions(widget.props.optionsBinding ? bound : widget.props.options);\n const columns = numOr(widget.props.columns, 2);\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} />\n <div className=\"nt-cards\" style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }} role=\"radiogroup\">\n {options.map((option, index) => {\n const selected = str(value) === option.value;\n const image = option.image ? mediaUrl(option.image) : null;\n return (\n <button\n key={`${option.value}-${index}`}\n type=\"button\"\n role=\"radio\"\n aria-checked={selected}\n className={`nt-card${selected ? \" nt-selected\" : \"\"}`}\n disabled={widget.disabled || option.disabled === true}\n onClick={() => {\n setValue(option.value);\n emit(\"change\");\n }}\n >\n {image ? <img src={image} alt=\"\" /> : null}\n <strong>{option.title || option.value}</strong>\n {option.description ? <span className=\"nt-hint\">{option.description}</span> : null}\n </button>\n );\n })}\n </div>\n </div>\n );\n}\n\nexport function StepperWidget(widget: WidgetProps): ReactNode {\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const steps = Array.isArray(widget.props.steps) ? widget.props.steps.filter(isRecord) : [];\n const found = steps.findIndex((step) => str(step.value) === str(value));\n const current = found >= 0 ? found : 0;\n const allowBack = widget.props.allowBack !== false && widget.props.allowBack !== \"no\";\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} />\n <ol className=\"nt-steps\">\n {steps.map((step, index) => {\n const disabled = widget.disabled || step.disabled === true || (index < current && !allowBack);\n return (\n <li key={str(step.value) || index}>\n <button\n type=\"button\"\n className={`nt-chip${index === current ? \" nt-selected\" : \"\"}`}\n aria-current={index === current ? \"step\" : undefined}\n disabled={disabled}\n onClick={() => {\n setValue(str(step.value));\n emit(\"change\");\n }}\n >\n {step.completed === true ? \"✓ \" : \"\"}\n {str(step.title) || str(step.value)}\n </button>\n </li>\n );\n })}\n </ol>\n {steps[current] && str(steps[current].description) ? (\n <div className=\"nt-hint\">{str(steps[current].description)}</div>\n ) : null}\n </div>\n );\n}\n\nexport function ApprovalWidget(widget: WidgetProps): ReactNode {\n const { value, setValue, emit } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const choose = (next: \"approved\" | \"rejected\") => {\n setValue(next);\n emit(\"change\");\n };\n return (\n <div className=\"nt-panel\">\n <FieldLabel text={str(widget.props.label)} />\n {str(widget.props.description) ? <div className=\"nt-hint\">{str(widget.props.description)}</div> : null}\n <div className=\"nt-row\">\n <button\n type=\"button\"\n className={`nt-button${value === \"approved\" ? \"\" : \" nt-button-outlined\"}`}\n disabled={widget.disabled}\n onClick={() => choose(\"approved\")}\n >\n {str(widget.props.approveLabel) || \"Approve\"}\n </button>\n <button\n type=\"button\"\n className={`nt-button${value === \"rejected\" ? \"\" : \" nt-button-outlined\"}`}\n disabled={widget.disabled}\n onClick={() => choose(\"rejected\")}\n >\n {str(widget.props.rejectLabel) || \"Needs changes\"}\n </button>\n </div>\n </div>\n );\n}\n\nexport function ChatThreadWidget(widget: WidgetProps): ReactNode {\n const { value } = useWidgetRuntime({ ...widget, bindingMode: \"read\" });\n const stream = useBindingValue(useBindingRef(str(widget.props.streamBinding) || undefined, \"read\"));\n const messages = useMemo(\n () => [...messagesFrom(value), ...messagesFrom(stream).map((m) => ({ ...m, role: \"assistant\" }))],\n [stream, value]\n );\n if (messages.length === 0) return <Placeholder text={str(widget.props.placeholder) || \"No messages yet\"} />;\n return (\n <div className=\"nt-field\">\n <FieldLabel text={str(widget.props.label)} />\n <div className=\"nt-thread\" style={{ maxHeight: numOr(widget.props.maxHeight, 480) }}>\n {messages.map((message, index) => (\n <div key={index} className={`nt-bubble nt-bubble-${message.role === \"user\" ? \"user\" : \"assistant\"}`}>\n <Markdown text={messageText(message.content)} />\n </div>\n ))}\n </div>\n </div>\n );\n}\n\nexport function ChatComposerWidget(widget: WidgetProps): ReactNode {\n const { write } = useAppRuntimeContext();\n const { setValue, emit, running } = useWidgetRuntime({ ...widget, bindingMode: \"write\" });\n const historyRef = useBindingRef(str(widget.props.historyBinding) || undefined, \"read\");\n const history = useBindingValue(historyRef);\n const [draft, setDraft] = useState(\"\");\n const format = str(widget.props.valueFormat) || \"text\";\n const canSend = draft.trim() !== \"\" && !running && !widget.disabled;\n const send = () => {\n const text = draft.trim();\n if (!text) return;\n const message = composeUserMessage(text);\n const next = [...messagesFrom(history), message];\n if (historyRef) write(historyRef, next);\n setValue(format === \"history\" ? next : format === \"message\" ? message : text);\n setDraft(\"\");\n emit(\"click\");\n };\n return (\n <form\n className=\"nt-field\"\n onSubmit={(event) => {\n event.preventDefault();\n if (canSend) send();\n }}\n >\n <FieldLabel text={str(widget.props.label)} />\n <textarea\n className=\"nt-input\"\n rows={3}\n value={draft}\n placeholder={str(widget.props.placeholder) || \"Write a message…\"}\n disabled={widget.disabled}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === \"Enter\" && !event.shiftKey) {\n event.preventDefault();\n if (canSend) send();\n }\n }}\n />\n <button type=\"submit\" className=\"nt-button\" disabled={!canSend}>\n {running ? \"Working…\" : str(widget.props.sendLabel) || \"Send\"}\n </button>\n </form>\n );\n}\n\n/** The control one Input node needs, picked by the node's kind. */\nexport function WorkflowInputControl({ input, ...widget }: WidgetProps & { input: WorkflowInputIO }): ReactNode {\n const props: WidgetProps = {\n ...widget,\n props: {\n ...widget.props,\n label: input.label,\n min: input.min,\n max: input.max,\n options: input.options,\n multiline: input.multiline ?? true\n }\n };\n switch (input.kind) {\n case \"boolean\":\n return <SwitchWidget {...props} />;\n case \"integer\":\n case \"float\":\n return input.min !== undefined && input.max !== undefined ? (\n <SliderWidget {...props} props={{ ...props.props, step: input.kind === \"integer\" ? 1 : 0.01 }} />\n ) : (\n <NumberInputWidget {...props} />\n );\n case \"select\":\n return <SelectWidget {...props} />;\n case \"color\":\n return <ColorInputWidget {...props} />;\n case \"image\":\n case \"audio\":\n case \"video\":\n case \"document\":\n return <MediaInputWidget {...props} kind={input.kind} />;\n case \"model3d\":\n return <MediaInputWidget {...props} kind=\"model_3d\" />;\n case \"image_size\":\n return <ImageSizeInputWidget {...props} />;\n case \"dataframe\":\n return <DataFrameInputWidget {...props} />;\n case \"file_path\":\n return <PathInputWidget {...props} kind=\"file\" />;\n case \"folder_path\":\n case \"folder\":\n return <PathInputWidget {...props} kind=\"folder\" />;\n case \"image_list\":\n case \"video_list\":\n case \"audio_list\":\n case \"text_list\":\n return <MediaListInputWidget {...props} props={{ ...props.props, listKind: input.kind.replace(\"_list\", \"\") }} />;\n case \"language_model\":\n case \"image_model\":\n case \"video_model\":\n case \"tts_model\":\n case \"asr_model\":\n case \"music_model\":\n case \"embedding_model\":\n return <ModelSelectWidget {...props} props={{ ...props.props, modelKind: input.kind }} />;\n default:\n return <TextInputWidget {...props} />;\n }\n}\n\nexport function WorkflowInputWidget(widget: WidgetProps): ReactNode {\n const { ioFor } = useAppRuntimeContext();\n const ref = useBindingRef(widget.binding, \"write\");\n const input =\n ref?.kind === \"input\" ? ioFor(ref.operationId).inputs.find((i) => i.nodeId === ref.nodeId) : undefined;\n if (!input) {\n return <Placeholder text={`Unbound input: ${widget.binding ?? \"\"}`} />;\n }\n return <WorkflowInputControl {...widget} input={input} />;\n}\n\nexport function WorkflowFormWidget(widget: WidgetProps): ReactNode {\n const { ioFor, scope } = useAppRuntimeContext();\n const operationId = str(widget.props.operationId) || scope.defaultOperationId;\n const inputs = ioFor(operationId).inputs;\n const showDescriptions = widget.props.showDescriptions !== \"no\" && widget.props.showDescriptions !== false;\n return (\n <div className=\"nt-stack\">\n <FieldLabel text={str(widget.props.label)} />\n {inputs.length === 0 ? <div className=\"nt-hint\">This operation has no inputs.</div> : null}\n {inputs.map((input) => (\n <div key={input.nodeId} className=\"nt-field\">\n <WorkflowInputControl\n id={`${widget.id}:${input.nodeId}`}\n binding={encodeBinding({ kind: \"input\", operationId, nodeId: input.nodeId })}\n events={widget.events}\n disabled={widget.disabled}\n props={{}}\n input={input}\n />\n {showDescriptions && input.description ? <div className=\"nt-hint\">{input.description}</div> : null}\n </div>\n ))}\n </div>\n );\n}\n",
23
+ "src/widgets/shared.tsx": "/** Props and helpers every widget renderer shares. */\nimport type { ReactNode } from \"react\";\nimport type { AppEvent } from \"@nodetool-ai/app-runtime\";\n\n/** A placed widget in the UI document. Slots are arrays nested in props. */\nexport interface ComponentNode {\n type: string;\n props: Record<string, unknown>;\n}\n\nexport interface WidgetProps {\n id: string;\n binding?: string;\n events?: AppEvent[];\n /** The rendered `format` template; display widgets show it in place of the value. */\n formattedValue?: string;\n disabled?: boolean;\n props: Record<string, unknown>;\n}\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const str = (value: unknown): string =>\n typeof value === \"string\" ? value : value == null ? \"\" : String(value);\n\nexport const numOr = (value: unknown, fallback: number): number =>\n typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n\n/** A bound output holds one value or an accumulated list of streamed items. */\nexport const asItems = (value: unknown): unknown[] =>\n Array.isArray(value) ? value : value == null || value === \"\" ? [] : [value];\n\n/** Text for a value shown in a cell or a list item. */\nexport const cellText = (value: unknown): string => {\n if (value == null) return \"\";\n if (typeof value === \"object\") {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n }\n return String(value);\n};\n\nexport function Placeholder({ text }: { text: string }): ReactNode {\n return text ? <div className=\"nt-placeholder\">{text}</div> : null;\n}\n\nexport function FieldLabel({ text, htmlFor }: { text: string; htmlFor?: string }): ReactNode {\n return text ? (\n <label className=\"nt-label\" htmlFor={htmlFor}>\n {text}\n </label>\n ) : null;\n}\n",
24
+ "src/widgets/tree.tsx": "/**\n * The widget tree: one renderer per entry in the app-runtime widget catalog,\n * the layout widgets that nest children, and the node wrapper that applies\n * `visibleWhen`, `disabledWhen` and `format` in one place.\n */\nimport { useState, type ComponentType, type ReactNode } from \"react\";\nimport { WIDGET_CATALOG, type AppEvent, type ConditionProps } from \"@nodetool-ai/app-runtime\";\nimport { useCondition, useFormatted, useWidgetRuntime } from \"../runtime/context\";\nimport {\n AgentActivityWidget,\n AlertWidget,\n ChartWidget,\n CodeBlockWidget,\n DocumentOnlyWidget,\n DownloadWidget,\n FileWidget,\n GalleryWidget,\n HeadingWidget,\n ImageCompareWidget,\n ImageWidget,\n JsonWidget,\n KeyValueWidget,\n ListWidget,\n MarkdownWidget,\n OutputWidget,\n ProgressWidget,\n StatWidget,\n TableWidget,\n TextWidget\n} from \"./display\";\nimport {\n ApprovalWidget,\n ChatComposerWidget,\n ChatThreadWidget,\n CheckboxGroupWidget,\n ChoiceCardsWidget,\n ColorInputWidget,\n DataFrameInputWidget,\n DateInputWidget,\n ImageSizeInputWidget,\n MediaInputWidget,\n MediaListInputWidget,\n ModelSelectWidget,\n NumberInputWidget,\n PathInputWidget,\n RadioGroupWidget,\n SelectWidget,\n SliderWidget,\n StepperWidget,\n SwitchWidget,\n TextInputWidget,\n WorkflowFormWidget,\n WorkflowInputWidget\n} from \"./inputs\";\nimport { Placeholder, isRecord, numOr, str, type ComponentNode, type WidgetProps } from \"./shared\";\n\nfunction ButtonWidget(widget: WidgetProps): ReactNode {\n const { emit, running } = useWidgetRuntime({ ...widget, bindingMode: \"none\" });\n const variant = str(widget.props.variant);\n const color = str(widget.props.color);\n const runs = (widget.events ?? []).some((event) => !event.kind || event.kind === \"run\");\n const classes = [\n \"nt-button\",\n variant === \"outlined\" ? \"nt-button-outlined\" : variant === \"text\" ? \"nt-button-text\" : \"\",\n color ? `nt-color-${color}` : \"\",\n widget.props.fullWidth === true || widget.props.fullWidth === \"yes\" ? \"nt-full\" : \"\"\n ]\n .filter(Boolean)\n .join(\" \");\n const align = str(widget.props.align);\n return (\n <div className=\"nt-button-row\" style={align ? { justifyContent: align === \"center\" ? \"center\" : align === \"right\" ? \"flex-end\" : \"flex-start\" } : undefined}>\n <button\n type=\"button\"\n className={classes}\n disabled={widget.disabled || (runs && running)}\n aria-busy={running}\n onClick={() => emit(\"click\")}\n >\n {running && runs ? <span className=\"nt-spinner\" aria-hidden /> : null}\n {str(widget.props.label) || \"Run\"}\n </button>\n </div>\n );\n}\n\nfunction ContainerWidget(widget: WidgetProps): ReactNode {\n const title = str(widget.props.title);\n const columns = numOr(widget.props.columns, 1);\n return (\n <section className={`nt-panel nt-panel-${str(widget.props.variant) || \"default\"}`}>\n {title ? <h3 className=\"nt-panel-title\">{title}</h3> : null}\n <ComponentList\n nodes={slotNodes(widget.props.content)}\n style={columns > 1 ? { display: \"grid\", gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` } : undefined}\n />\n </section>\n );\n}\n\nconst COLUMN_LAYOUTS: Record<string, string> = {\n \"50-50\": \"1fr 1fr\",\n \"33-67\": \"1fr 2fr\",\n \"67-33\": \"2fr 1fr\",\n \"25-75\": \"1fr 3fr\",\n \"75-25\": \"3fr 1fr\",\n \"40-60\": \"2fr 3fr\",\n \"60-40\": \"3fr 2fr\"\n};\n\nfunction ColumnsWidget(widget: WidgetProps): ReactNode {\n const template = COLUMN_LAYOUTS[str(widget.props.layout)] ?? \"1fr 1fr\";\n return (\n <div className=\"nt-columns\" style={{ gridTemplateColumns: template, gap: numOr(widget.props.gap, 24) }}>\n <ComponentList nodes={slotNodes(widget.props.left)} />\n <ComponentList nodes={slotNodes(widget.props.right)} />\n </div>\n );\n}\n\nfunction TabsWidget(widget: WidgetProps): ReactNode {\n const panes = ([\"tab1\", \"tab2\", \"tab3\"] as const)\n .map((key) => ({ key, label: str(widget.props[`${key}Label`]), nodes: slotNodes(widget.props[key]) }))\n .filter((pane) => pane.label.trim() !== \"\");\n const [active, setActive] = useState<string>(\"tab1\");\n const current = panes.some((pane) => pane.key === active) ? active : panes[0]?.key;\n if (panes.length === 0) return null;\n return (\n <div className=\"nt-field\">\n <div className=\"nt-tabs\" role=\"tablist\">\n {panes.map((pane) => (\n <button\n key={pane.key}\n type=\"button\"\n role=\"tab\"\n aria-selected={pane.key === current}\n className={`nt-tab${pane.key === current ? \" nt-selected\" : \"\"}`}\n onClick={() => setActive(pane.key)}\n >\n {pane.label}\n </button>\n ))}\n </div>\n {panes.map((pane) => (\n // Hidden rather than unmounted, so a pane's state survives switching.\n <div key={pane.key} role=\"tabpanel\" hidden={pane.key !== current}>\n <ComponentList nodes={pane.nodes} />\n </div>\n ))}\n </div>\n );\n}\n\nfunction AccordionWidget(widget: WidgetProps): ReactNode {\n const open = widget.props.defaultOpen !== false && widget.props.defaultOpen !== \"no\";\n return (\n <details className=\"nt-panel\" open={open}>\n <summary className=\"nt-panel-title\">{str(widget.props.title) || \"Section\"}</summary>\n <ComponentList nodes={slotNodes(widget.props.content)} />\n </details>\n );\n}\n\nconst NeedsNodeTool = ({ label }: { label: string }): ReactNode => (\n <Placeholder text={`${label} works inside NodeTool only.`} />\n);\n\nconst RENDERERS: Record<string, ComponentType<WidgetProps>> = {\n Heading: HeadingWidget,\n Text: TextWidget,\n Markdown: MarkdownWidget,\n Image: ImageWidget,\n Audio: OutputWidget,\n Video: OutputWidget,\n Json: JsonWidget,\n Output: OutputWidget,\n Sketch: (props) => <DocumentOnlyWidget {...props} title=\"Sketch\" />,\n Timeline: (props) => <DocumentOnlyWidget {...props} title=\"Timeline\" />,\n Storyboard: (props) => <DocumentOnlyWidget {...props} title=\"Storyboard\" />,\n StoryboardPreview: (props) => <DocumentOnlyWidget {...props} title=\"Storyboard\" />,\n Table: TableWidget,\n Progress: ProgressWidget,\n AgentActivity: AgentActivityWidget,\n Alert: AlertWidget,\n CodeBlock: CodeBlockWidget,\n List: ListWidget,\n KeyValue: KeyValueWidget,\n Stat: StatWidget,\n Download: DownloadWidget,\n Model3D: (props) => <FileWidget {...props} title=\"3D model\" />,\n Chart: ChartWidget,\n PDF: (props) => <FileWidget {...props} title=\"PDF\" />,\n Gallery: GalleryWidget,\n ImageCompare: ImageCompareWidget,\n ChoiceCards: ChoiceCardsWidget,\n Stepper: StepperWidget,\n Approval: ApprovalWidget,\n WorkflowForm: WorkflowFormWidget,\n WorkflowInput: WorkflowInputWidget,\n TextInput: TextInputWidget,\n NumberInput: NumberInputWidget,\n Slider: SliderWidget,\n Switch: SwitchWidget,\n Select: SelectWidget,\n RadioGroup: RadioGroupWidget,\n CheckboxGroup: CheckboxGroupWidget,\n DateInput: DateInputWidget,\n ImageInput: (props) => <MediaInputWidget {...props} kind=\"image\" />,\n SketchPad: (props) => (\n <MediaInputWidget {...props} kind=\"image\" note=\"Drawing works inside NodeTool. Pick an image instead.\" />\n ),\n AudioInput: (props) => <MediaInputWidget {...props} kind=\"audio\" />,\n VideoInput: (props) => <MediaInputWidget {...props} kind=\"video\" />,\n AudioRecorder: (props) => <MediaInputWidget {...props} kind=\"audio\" capture />,\n CameraCapture: (props) => <MediaInputWidget {...props} kind=\"video\" capture />,\n DocumentInput: (props) => <MediaInputWidget {...props} kind=\"document\" />,\n ColorInput: ColorInputWidget,\n DataFrameInput: DataFrameInputWidget,\n FilePathInput: (props) => <PathInputWidget {...props} kind=\"file\" />,\n FolderPathInput: (props) => <PathInputWidget {...props} kind=\"folder\" />,\n Model3DInput: (props) => <MediaInputWidget {...props} kind=\"model_3d\" />,\n ImageSizeInput: ImageSizeInputWidget,\n MediaListInput: MediaListInputWidget,\n ResourcePicker: () => <NeedsNodeTool label=\"Picking a NodeTool document\" />,\n ResourceGallery: () => <NeedsNodeTool label=\"Browsing NodeTool documents\" />,\n StoryboardSceneList: () => <NeedsNodeTool label=\"Editing storyboard scenes\" />,\n ChatThread: ChatThreadWidget,\n ChatComposer: ChatComposerWidget,\n ModelSelect: ModelSelectWidget,\n Button: ButtonWidget,\n Container: ContainerWidget,\n Columns: ColumnsWidget,\n Tabs: TabsWidget,\n Accordion: AccordionWidget,\n Spacer: (widget) => <div style={{ height: numOr(widget.props.height, 24) }} />,\n Divider: () => <hr className=\"nt-divider\" />\n};\n\n/** Every catalog type this project can render; the exporter checks it. */\nexport const RENDERED_WIDGET_TYPES: ReadonlyArray<string> = Object.keys(RENDERERS);\n\nexport const slotNodes = (value: unknown): ComponentNode[] =>\n Array.isArray(value)\n ? value.filter(\n (node): node is ComponentNode => isRecord(node) && typeof node.type === \"string\" && isRecord(node.props)\n )\n : [];\n\nfunction WidgetNode({ node }: { node: ComponentNode }): ReactNode {\n const props = node.props;\n const visible = useCondition(props.visibleWhen as ConditionProps | undefined, true);\n const disabled = useCondition(props.disabledWhen as ConditionProps | undefined, false);\n const formatted = useFormatted(typeof props.format === \"string\" ? props.format : undefined);\n const Renderer = RENDERERS[node.type];\n if (!Renderer) {\n const label = WIDGET_CATALOG[node.type]?.label ?? node.type;\n return <NeedsNodeTool label={label} />;\n }\n if (!visible) return null;\n return (\n <Renderer\n id={str(props.id)}\n binding={typeof props.binding === \"string\" ? props.binding : undefined}\n events={Array.isArray(props.events) ? (props.events as AppEvent[]) : undefined}\n {...(formatted !== null ? { formattedValue: formatted } : {})}\n disabled={disabled}\n props={props}\n />\n );\n}\n\nexport function ComponentList({\n nodes,\n style\n}: {\n nodes: ComponentNode[];\n style?: React.CSSProperties;\n}): ReactNode {\n return (\n <div className=\"nt-stack\" style={style}>\n {nodes.map((node, index) => (\n <WidgetNode key={str(node.props.id) || `${node.type}-${index}`} node={node} />\n ))}\n </div>\n );\n}\n",
25
+ "tsconfig.json": "{\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Bundler\",\n \"jsx\": \"react-jsx\",\n \"strict\": true,\n \"noEmit\": true,\n \"skipLibCheck\": true,\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"types\": [\"vite/client\"]\n },\n \"include\": [\"src\"]\n}\n",
26
+ "vite.config.ts": "import { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\nexport default defineConfig({\n plugins: [react()]\n});\n"
27
+ };
28
+ //# sourceMappingURL=template-files.generated.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"template-files.generated.js","sourceRoot":"","sources":["../src/template-files.generated.ts"],"names":[],"mappings":"AAAA,uEAAuE;AAEvE,MAAM,CAAC,MAAM,cAAc,GAAqC;IAC9D,WAAW,EAAE,4CAA4C;IACzD,YAAY,EAAE,kXAAkX;IAChY,kBAAkB,EAAE,wnRAAwnR;IAC5oR,kBAAkB,EAAE,shKAAshK;IAC1iK,mBAAmB,EAAE,6hFAA6hF;IACljF,mBAAmB,EAAE,4lRAA4lR;IACjnR,kBAAkB,EAAE,s5OAAs5O;IAC16O,aAAa,EAAE,ytCAAytC;IACxuC,cAAc,EAAE,8SAA8S;IAC9T,wBAAwB,EAAE,u7LAAu7L;IACj9L,uBAAuB,EAAE,8lDAA8lD;IACvnD,4BAA4B,EAAE,kpDAAkpD;IAChrD,uBAAuB,EAAE,4jJAA4jJ;IACrlJ,sBAAsB,EAAE,s/DAAs/D;IAC9gE,8BAA8B,EAAE,kkcAAkkc;IAClmc,2BAA2B,EAAE,g+QAAg+Q;IAC7/Q,gBAAgB,EAAE,+1TAA+1T;IACj3T,0BAA0B,EAAE,qjIAAqjI;IACjlI,yBAAyB,EAAE,0zmBAA0zmB;IACr1mB,wBAAwB,EAAE,m09BAAm09B;IAC719B,wBAAwB,EAAE,i5DAAi5D;IAC36D,sBAAsB,EAAE,+xUAA+xU;IACvzU,eAAe,EAAE,uaAAua;IACxb,gBAAgB,EAAE,mJAAmJ;CACtK,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@nodetool-ai/app-export",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.8.3",
4
+ "description": "Export a NodeTool mini app as a standalone JavaScript project: a Vite UI plus a local Node server that runs the app's workflows in process",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=22.0.0"
8
+ },
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts",
11
+ "dependencies": {
12
+ "@nodetool-ai/app-runtime": "0.8.3"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "nodetool-dev": "./src/index.ts",
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "license": "MIT",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/nodetool-ai/nodetool.git",
26
+ "directory": "packages/app-export"
27
+ },
28
+ "homepage": "https://nodetool.ai",
29
+ "bugs": {
30
+ "url": "https://github.com/nodetool-ai/nodetool/issues"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "README.md"
38
+ ],
39
+ "keywords": [
40
+ "nodetool",
41
+ "ai",
42
+ "workflow",
43
+ "mini-app",
44
+ "export",
45
+ "typescript"
46
+ ]
47
+ }