@nodetool-ai/app-export 0.8.3 → 0.8.4-a24.2

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.
@@ -1,28 +1,32 @@
1
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
- };
2
+ export const TEMPLATE_FILES = new Map([
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\";\nimport { storageResponseHeaders } from \"./storage-policy.mjs\";\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, untrusted = false) {\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 ...(untrusted && storageResponseHeaders(path))\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, propertyOverrides: body.property_overrides, operationId: body.operation_id, 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, true);\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/input-boundary.mjs", "import { lstat, readlink, realpath } from \"node:fs/promises\";\nimport { dirname, extname, isAbsolute, resolve, sep } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nconst PATH_PROPERTIES = new Set([\"path\", \"file_path\", \"folder_path\", \"folder\", \"directory\", \"input_path\", \"output_path\"]);\nconst MEDIA_TYPES = new Set([\"image\", \"audio\", \"video\", \"document\", \"folder\", \"model3d\", \"model_3d\"]);\nconst NAME_WRITERS = new Set([\"nodetool.text.SaveTextFile\", \"nodetool.text.SaveText\", \"nodetool.image.SaveImage\", \"nodetool.audio.SaveAudio\", \"nodetool.video.SaveVideo\", \"nodetool.model3d.SaveModel3D\"]);\nconst FILENAME_WRITERS = new Set([\"nodetool.document.SaveDocumentFile\", \"nodetool.image.SaveImageFile\", \"nodetool.audio.SaveAudioFile\", \"nodetool.video.SaveVideoFile\", \"nodetool.model3d.SaveModel3DFile\"]);\nconst FALLBACK_FILENAMES = {\n \"nodetool.document.SaveDocumentFile\": \"document.txt\",\n \"nodetool.audio.SaveAudioFile\": \"audio.wav\",\n \"nodetool.video.SaveVideoFile\": \"video.mp4\",\n \"nodetool.image.SaveImageFile\": \"image_%Y-%m-%d_%H-%M-%S\",\n \"nodetool.model3d.SaveModel3DFile\": \"model_%Y-%m-%d_%H-%M-%S\"\n};\n\nfunction datedName(name) {\n const now = new Date();\n const fields = { Y: now.getFullYear(), m: now.getMonth() + 1, d: now.getDate(), H: now.getHours(), M: now.getMinutes(), S: now.getSeconds() };\n return name.replace(/%([YmdHMS])/g, (_, field) => String(fields[field]).padStart(field === \"Y\" ? 4 : 2, \"0\"));\n}\n\nasync function existingPath(path) {\n try {\n return await realpath(path);\n } catch (error) {\n if (error.code !== \"ENOENT\") throw error;\n try {\n if ((await lstat(path)).isSymbolicLink()) return existingPath(resolve(dirname(path), await readlink(path)));\n } catch (missing) {\n if (missing.code !== \"ENOENT\") throw missing;\n }\n const parent = dirname(path);\n if (parent === path) throw error;\n return resolve(await existingPath(parent), path.slice(parent.length + 1));\n }\n}\n\nexport function createNodeInputBoundary(roots) {\n const base = resolve(roots[0]);\n async function localPath(value) {\n if (value === null || value === undefined || value === \"\") return base;\n if (typeof value !== \"string\") {\n if (typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Invalid node input path\");\n const result = { ...value };\n if (Object.hasOwn(result, \"path\")) result.path = await localPath(result.path);\n result.uri = typeof result.uri === \"string\" && result.uri !== \"\" ? result.uri : pathToFileURL(base).href;\n return result;\n }\n const path = /^file:/i.test(value) ? fileURLToPath(value) : isAbsolute(value) ? value : resolve(base, value);\n const actual = await existingPath(path);\n const allowed = await Promise.all(roots.map(existingPath));\n if (!allowed.some((root) => actual === root || actual.startsWith(root + sep))) {\n throw new Error(\"Node input path leaves this application's storage\");\n }\n return actual;\n }\n async function media(value) {\n if (Array.isArray(value)) return Promise.all(value.map(media));\n if (value === null || typeof value !== \"object\" || value instanceof Uint8Array) return value;\n const entries = await Promise.all(Object.entries(value).map(async ([key, entry]) => [key,\n key === \"uri\" && typeof entry === \"string\" && !/^(https?:|data:|asset:|package:|memory:)/i.test(entry)\n ? entry === \"\" ? \"\" : pathToFileURL(await localPath(entry)).href\n : await media(entry)\n ]));\n return Object.fromEntries(entries);\n }\n return async (inputs, metadata) => {\n const writer = NAME_WRITERS.has(metadata?.node_type) || FILENAME_WRITERS.has(metadata?.node_type);\n const defaults = Object.fromEntries((metadata?.properties ?? []).filter((property) => property.default !== undefined && (PATH_PROPERTIES.has(property.name) || MEDIA_TYPES.has(property.type?.type) || writer && [\"name\", \"filename\", \"save_to_workspace\"].includes(property.name))).map((property) => [property.name, property.default]));\n const result = await media({ ...defaults, ...inputs });\n async function typed(value, type) {\n if (type?.type === \"list\" && Array.isArray(value)) return Promise.all(value.map((item) => typed(item, type.type_args?.[0])));\n if (type?.type === \"folder\") return localPath(value);\n if (MEDIA_TYPES.has(type?.type) && typeof value === \"string\" && !/^(https?:|data:|asset:|package:|memory:)/i.test(value)) return value === \"\" ? \"\" : pathToFileURL(await localPath(value)).href;\n return value;\n }\n for (const property of metadata?.properties ?? []) {\n if (!Object.hasOwn(result, property.name)) continue;\n if (writer && property.name === \"folder\" && result.save_to_workspace === true) {\n result.folder = base;\n continue;\n }\n if (PATH_PROPERTIES.has(property.name) || [\"file_path\", \"folder_path\"].includes(property.json_schema_extra?.type)) {\n result[property.name] = await localPath(result[property.name]);\n } else result[property.name] = await typed(result[property.name], property.type);\n }\n if (writer) {\n const folder = result.save_to_workspace === true ? base : typeof result.folder === \"string\" ? result.folder : result.folder?.path ?? result.folder?.uri ?? base;\n const destination = /^file:/i.test(folder) ? fileURLToPath(folder) : folder;\n const key = NAME_WRITERS.has(metadata.node_type) ? \"name\" : \"filename\";\n const rawName = (result[key] == null ? \"\" : String(result[key])).trim() || FALLBACK_FILENAMES[metadata.node_type] || \"\";\n const name = datedName(rawName);\n if (name.trim() !== \"\") {\n const writableRoot = await existingPath(base);\n const names = [...new Set([rawName, name])];\n if (!extname(name) && metadata.node_type === \"nodetool.image.SaveImageFile\") names.push(...[\"png\", \"jpg\", \"webp\", \"gif\", \"bmp\"].map((extension) => `${name}.${extension}`));\n if (!extname(name) && metadata.node_type === \"nodetool.model3d.SaveModel3DFile\") names.push(`${name}.${String(result.model?.format || extname(result.model?.uri ?? \"\").slice(1) || \"glb\").toLowerCase()}`);\n for (const filename of names) {\n const target = await localPath(resolve(destination || base, filename));\n if (target !== writableRoot && !target.startsWith(writableRoot + sep)) throw new Error(\"Node output path leaves this application's storage\");\n }\n }\n if (metadata.node_type === \"nodetool.document.SaveDocumentFile\" && result.path) {\n result.path = await localPath(result.path);\n const writableRoot = await existingPath(base);\n if (typeof result.path !== \"string\" || result.path !== writableRoot && !result.path.startsWith(writableRoot + sep)) throw new Error(\"Node output path leaves this application's storage\");\n }\n }\n return result;\n };\n}\n\nexport function guardExecutor(executor, metadata, boundary, properties = {}) {\n return new Proxy(executor, {\n get(target, key) {\n const method = Reflect.get(target, key);\n if (key === \"initialize\") return async () => {\n const guarded = await boundary(properties, metadata);\n target.applyProperties?.(guarded);\n await method?.call(target);\n };\n if (typeof method !== \"function\") return method;\n if (key === \"process\") return async (inputs, ...args) => method.call(target, await boundary(inputs, metadata), ...args);\n if (key === \"genProcess\") return async function* (inputs, ...args) {\n yield* method.call(target, await boundary(inputs, metadata), ...args);\n };\n return method.bind(target);\n }\n });\n}\n"],
7
+ ["server/lifecycle.mjs", "export function observeSessionCancellation(session, signal) {\n const cancel = () => session.cancel(\"cancelled\");\n signal?.addEventListener(\"abort\", cancel, { once: true });\n if (signal?.aborted) cancel();\n return () => signal?.removeEventListener(\"abort\", cancel);\n}\n"],
8
+ ["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, { workspaceRelative = false } = {}) {\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 if (!path.startsWith(root + sep)) throw new Error(\"Input storage handle leaves the storage directory\");\n return workspaceRelative ? path.slice(root.length + 1) : pathToFileURL(path).toString();\n };\n\n function resolve(value, depth = 0) {\n if (depth > 32) throw new Error(\"Input media exceeds the supported nesting depth\");\n if (value == null) return value;\n if (typeof value === \"string\" && value.startsWith(PREFIX)) return resolveUri(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 if (key === \"uri\" && typeof entry === \"string\") {\n if (entry.startsWith(PREFIX)) out[key] = resolveUri(entry);\n else if (/^(https?:|data:|asset:|package:)/i.test(entry)) out[key] = entry;\n else throw new Error(\"Input media must use an uploaded storage handle or a supported media URI\");\n } else out[key] = resolve(entry, depth + 1);\n }\n return out;\n }\n\n return resolve;\n}\n"],
9
+ ["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"],
10
+ ["server/properties.mjs", "import { operationTarget, parseBinding } from \"@nodetool-ai/app-runtime\";\n\nexport function applyPropertyOverrides(bundle, workflow, operationId, overrides = {}) {\n if (Object.keys(overrides).length === 0) return workflow.graph;\n const operation = bundle.app.operations.find((entry) => entry.id === operationId);\n const target = operation && operationTarget(operation);\n if (!target || target.kind !== \"workflow\" || target.workflowId !== workflow.key) throw new Error(\"Invalid property override operation\");\n const allowed = new Set();\n function visit(value) {\n if (typeof value === \"string\") {\n const ref = parseBinding(value);\n if (ref?.kind === \"nodeProperty\" && (ref.operationId === operationId || ref.operationId === \"\")) allowed.add(`${ref.nodeId}#${ref.property}`);\n } else if (value && typeof value === \"object\") {\n for (const entry of Object.values(value)) visit(entry);\n }\n }\n visit(bundle.app.ui);\n const byNode = new Map();\n for (const [key, value] of Object.entries(overrides)) {\n if (!allowed.has(key) || value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Property override is not exposed by this application\");\n if (Object.keys(value).length !== 1 || !Object.hasOwn(value, \"value\")) throw new Error(\"Invalid property override\");\n const separator = key.lastIndexOf(\"#\");\n const nodeId = key.slice(0, separator);\n const properties = byNode.get(nodeId) ?? new Map();\n properties.set(key.slice(separator + 1), value.value);\n byNode.set(nodeId, properties);\n }\n return {\n ...workflow.graph,\n nodes: workflow.graph.nodes.map((node) => {\n const data = { ...(node.properties ?? node.data ?? {}), ...Object.fromEntries(byNode.get(node.id) ?? []) };\n return { ...node, ...(node.properties ? { properties: data } : { data }) };\n })\n };\n}\n"],
11
+ ["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\";\nimport { createNodeInputBoundary, guardExecutor } from \"./input-boundary.mjs\";\nimport { applyPropertyOverrides } from \"./properties.mjs\";\nimport { observeSessionCancellation } from \"./lifecycle.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 { bundle, 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 resolveScriptInputs = createInputResolver(storage, { workspaceRelative: true });\n const workspaceDir = storage.rootDir;\n mkdirSync(workspaceDir, { recursive: true });\n const inputBoundary = createNodeInputBoundary([workspaceDir, join(root, \"assets\")]);\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 nodeExecutorGuard: (executor, type, inputs) => {\n const metadata = registry.resolveMetadata(type);\n if (!metadata) throw new Error(`Standalone app cannot enforce filesystem inputs for unregistered node: ${type}`);\n return guardExecutor(executor, metadata, inputBoundary, inputs);\n },\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, propertyOverrides, operationId, jobId, signal, send }) {\n signal?.throwIfAborted();\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(applyPropertyOverrides(bundle, workflow, operationId, propertyOverrides)),\n registry,\n resolveNodeType,\n resolveExecutor: (node) => {\n if (!registry.has(node.type)) throw new Error(`Standalone app cannot enforce filesystem inputs for unregistered node: ${node.type}`);\n return context.nodeExecutorGuard(registry.resolve(node), node.type, node.properties ?? {});\n },\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 stopObserving = observeSessionCancellation(session, signal);\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 stopObserving();\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 = resolveScriptInputs(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"],
12
+ ["server/storage-policy.mjs", "import { extname } from \"node:path\";\n\nexport function storageResponseHeaders(path) {\n return {\n \"content-security-policy\": \"sandbox; default-src 'none'\",\n \"x-content-type-options\": \"nosniff\",\n ...([\".html\", \".htm\", \".svg\", \".xml\", \".xhtml\"].includes(extname(path).toLowerCase()) && { \"content-disposition\": \"attachment\" })\n };\n}\n"],
13
+ ["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\";\nimport { getAssetFileName } from \"@nodetool-ai/protocol\";\n\n/** A generated resource id: 32 lowercase hex characters. */\nconst newId = () => randomUUID().replaceAll(\"-\", \"\");\n\nconst now = () => new Date().toISOString();\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 filename = getAssetFileName(id, args.contentType);\n const key = `${args.userId}/${filename}`;\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://${filename}` };\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 const previousKey = entry.key;\n entry.key = `${previousKey.slice(0, previousKey.lastIndexOf(\"/\"))}/${getAssetFileName(entry.id, entry.content_type)}`;\n await storage.store(entry.key, content, entry.content_type);\n if (previousKey !== entry.key) await storage.delete(previousKey);\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"],
14
+ ["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"],
15
+ ["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"],
16
+ ["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"],
17
+ ["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"],
18
+ ["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"],
19
+ ["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 operationId: string;\n propertyOverrides: Record<string, { value: 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 operation_id: request.operationId,\n property_overrides: request.propertyOverrides,\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"],
20
+ ["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"],
21
+ ["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 parseInputStateKey,\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 const propertyOverrides: Record<string, { value: unknown }> = {};\n for (const [key, value] of Object.entries(store.getState().inputs)) {\n const ref = parseInputStateKey(key);\n if (ref?.operationId === operation.id && ref.property !== undefined) {\n propertyOverrides[`${ref.nodeId}#${ref.property}`] = { value };\n }\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 operationId: operation.id,\n propertyOverrides,\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"],
22
+ ["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"],
23
+ ["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"],
24
+ ["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"],
25
+ ["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"],
26
+ ["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"],
27
+ ["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"],
28
+ ["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"],
29
+ ["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"],
30
+ ["vite.config.ts", "import { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\nexport default defineConfig({\n plugins: [react()]\n});\n"]
31
+ ]);
28
32
  //# sourceMappingURL=template-files.generated.js.map