comfy-ts 2.10.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/{LogsSt-DFxzQfDc.js → LogsSt-qtFzOKpu.js} +2 -2
  2. package/dist/{LogsSt-DFxzQfDc.js.map → LogsSt-qtFzOKpu.js.map} +1 -1
  3. package/dist/cli.js +4 -4
  4. package/dist/index.cjs +93 -1
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +19 -0
  7. package/dist/index.d.ts +19 -0
  8. package/dist/index.js +93 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/{run-serve-_nrvJYyt.js → run-serve-BK7BA2dn.js} +91 -3
  11. package/dist/run-serve-BK7BA2dn.js.map +1 -0
  12. package/dist/{run-tui-Atvf9vb3.js → run-tui-CQyvMf0N.js} +36 -4
  13. package/dist/run-tui-CQyvMf0N.js.map +1 -0
  14. package/dist/{DefinedWorkflow-BatWaZO1.js → schemaDrift-DjjEtwfx.js} +176 -2
  15. package/dist/schemaDrift-DjjEtwfx.js.map +1 -0
  16. package/dist/serve-web.js +32 -16
  17. package/dist/{state-6RFDIQwJ.js → state--wrz0BQc.js} +14 -3
  18. package/dist/{state-6RFDIQwJ.js.map → state--wrz0BQc.js.map} +1 -1
  19. package/dist/web.d.ts +19 -0
  20. package/dist/web.js +93 -1
  21. package/dist/web.js.map +1 -1
  22. package/examples/comfy-cloud/capybara-i2v.cflow.ts +2 -0
  23. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +2 -0
  24. package/examples/comfy-cloud/wan22-i2v.cflow.ts +2 -0
  25. package/examples/comfy-cloud/wan22-t2v.cflow.ts +2 -0
  26. package/examples/rvion/07-local-llm-text-gen.cflow.ts +2 -2
  27. package/package.json +4 -2
  28. package/src/cli/serve/ServeApp.ts +94 -0
  29. package/src/cli/serve/describeVar.ts +7 -0
  30. package/src/cli/serve/favicon.ts +3 -0
  31. package/src/cli/serve/web/api.ts +12 -0
  32. package/src/cli/serve/web/components/VarsForm.tsx +18 -7
  33. package/src/cli/serve/web/components/controls/LorasControl.tsx +102 -6
  34. package/src/cli/serve/web/state/WebSt.ts +79 -0
  35. package/src/cli/serve/web/state/loraSort.ts +39 -0
  36. package/src/cli/serve/web/styles.ts +15 -0
  37. package/src/cli/tui/components/Header.tsx +2 -0
  38. package/src/cli/tui/state/HostSt.ts +34 -0
  39. package/src/host/ComfyHost.ts +15 -0
  40. package/src/host/loraInfoCache.ts +64 -0
  41. package/src/host/loraManagerApi.ts +27 -0
  42. package/src/host/schemaDrift.ts +87 -0
  43. package/dist/DefinedWorkflow-BatWaZO1.js.map +0 -1
  44. package/dist/run-serve-_nrvJYyt.js.map +0 -1
  45. package/dist/run-tui-Atvf9vb3.js.map +0 -1
@@ -1,5 +1,5 @@
1
- import { B as stripAnsi, C as fetchLoraList, D as lmFilePath, E as lmCivitai, I as loraKey, L as loraPreviewMapFrom, M as lmSha256, N as lmTags, O as lmFileSize, R as ansi, S as fetchLoraExampleImages, T as lmBaseModel, U as bang, V as extractErrorMessage, X as statelessRegex, b as writeLoraMirror, d as getLoraDisplayName, f as getLoraInfo, g as loraMirrorEntries, j as lmNotes, k as lmFolder, m as getLoraTriggerWords, n as DEFAULT_IMAGE_EXTENSIONS, o as getLoraKeyword, p as getLoraPreviewUrl, u as buildLoraMirror, v as refreshLoraInfoCacheIfChanged, w as fetchLoraPreviewBytes, x as fetchLoraDescription, y as reloadLoraInfoCache, z as colorsAvailable } from "./DefinedWorkflow-BatWaZO1.js";
2
- import { a as draftsDirForFile, f as scanCflowFiles, i as draftKeyForFile, n as assembleLogChunks, o as listDraftsForFile, u as findDefinedWorkflow } from "./LogsSt-DFxzQfDc.js";
1
+ import { A as fetchLoraExampleImages, B as lmSha256, D as writeLoraMirror, E as reloadLoraInfoCache, F as lmFilePath, G as loraPreviewMapFrom, I as lmFileSize, J as stripAnsi, K as ansi, L as lmFolder, M as fetchLoraPreviewBytes, N as lmBaseModel, O as fetchLoraCivitai, P as lmCivitai, S as loraMirrorEntries, T as refreshLoraInfoCacheIfChanged, V as lmTags, W as loraKey, Y as extractErrorMessage, Z as bang, _ as getLoraInfo, b as getLoraTriggers, g as getLoraDisplayName, h as getLoraAddedAt, i as summarizeDrift, it as statelessRegex, j as fetchLoraList, k as fetchLoraDescription, m as buildLoraMirror, o as DEFAULT_IMAGE_EXTENSIONS, q as colorsAvailable, r as driftChanged, u as getLoraKeyword, v as getLoraPreviewUrl, w as recordCivitaiMiss, y as getLoraTriggerWords, z as lmNotes } from "./schemaDrift-DjjEtwfx.js";
2
+ import { a as draftsDirForFile, f as scanCflowFiles, i as draftKeyForFile, n as assembleLogChunks, o as listDraftsForFile, u as findDefinedWorkflow } from "./LogsSt-qtFzOKpu.js";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
4
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
5
5
  import { basename, dirname, extname, join, resolve } from "pathe";
@@ -336,6 +336,9 @@ function managerOnlyLoraOptions(p) {
336
336
  return loraMirrorEntries(p.hostId, { separator }).filter((e) => !known.has(e.key)).map((e) => e.serverName).filter((n) => filter == null || filter.test(n));
337
337
  }
338
338
  //#endregion
339
+ //#region src/cli/serve/favicon.ts
340
+ const FAVICON_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAKUklEQVR42u1aaWxU1xW2DWEJZCENNgaK8iNRU5UAAYKBWW1ImwbaoqiuQkrUVlRdlDZSGpqAcTKrFyAoJRCRKmpRidKA98Sm0MQhRClOs7CIggiTtniZN4sZe8AeL/Puvef23LeMnwePQdWwhTnS9XvP8zzvft/5znfPfXJWViYykYlMZCITmchEJjKRiUxc4eCcj8ExFkfOzQg+23huvL5pwFNKf8wYexmvZ2m/H6cpQlHFV5IYIXvta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RKL/zlQKfSiEqCcaR/HnWzfWfZMX6snq1evtMZCITmchEJjKRiUxkIhM3ZfwPK9dyLD4coj4AAAAASUVORK5CYII=";
341
+ //#endregion
339
342
  //#region src/utils/stringMap.ts
340
343
  function stringMap(raw) {
341
344
  const out = {};
@@ -558,7 +561,9 @@ const USAGE = [
558
561
  "DELETE /drafts/<module>/<draft> — delete that draft file",
559
562
  "GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes",
560
563
  "POST /upload with {\"name\",\"dataBase64\"} — store a browser file for an image var",
564
+ "GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)",
561
565
  "GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)",
566
+ "POST /hosts/<hostId>/lora-civitai/<lora> — fetch its civitai metadata (trigger words) through the lora manager, then re-sync the mirror",
562
567
  "GET /lora-preview/<hostId>/<lora> — preview image bytes",
563
568
  "GET /lora-about/<hostId>/<lora> — civitai description + example images (live from the extension)",
564
569
  "GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)",
@@ -586,6 +591,7 @@ const WEB_SHELL = `<!doctype html>
586
591
  <meta charset="utf-8">
587
592
  <meta name="viewport" content="width=device-width, initial-scale=1">
588
593
  <title>comfy-ts serve</title>
594
+ <link rel="icon" type="image/png" href="${FAVICON_DATA_URI}">
589
595
  <style>html{background:#101217;color:#e8eaf0}</style>
590
596
  </head>
591
597
  <body>
@@ -655,6 +661,7 @@ var ServeApp = class {
655
661
  if (segs[0] === "hosts" && segs.length === 1) return this.replyHosts();
656
662
  if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "logs") return await this.replyHostLogs(segs[1]);
657
663
  if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "ping") return await this.replyHostPing(segs[1]);
664
+ if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "drift") return await this.replyHostDrift(segs[1], req.url.includes("full=1"));
658
665
  if (segs[0] === "images" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyMemoryImage(`${segs[1]}/${segs[2]}`);
659
666
  if (segs[0] === "outputs") return this.replyOutput(segs.slice(1));
660
667
  return json(404, {
@@ -673,6 +680,7 @@ var ServeApp = class {
673
680
  if (req.method === "PUT" && segs[0] === "settings" && segs.length === 1) return this.replySaveSettings(req);
674
681
  if (req.method === "PUT" && segs[0] === "hosts" && segs.length === 2 && segs[1] != null) return this.replySetHost(segs[1], req);
675
682
  if (req.method === "POST" && segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyHostAction(segs[1], segs[2]);
683
+ if (req.method === "POST" && segs[0] === "hosts" && segs.length === 4 && segs[1] != null && segs[2] === "lora-civitai" && segs[3] != null) return await this.replyLoraCivitaiFetch(segs[1], segs[3]);
676
684
  if (req.method === "PUT" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replySavePromptEnhancer(segs[1], req);
677
685
  if (req.method === "DELETE" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replyDeletePromptEnhancer(segs[1]);
678
686
  return json(404, {
@@ -786,6 +794,18 @@ var ServeApp = class {
786
794
  if (kw !== "") keywords[option] = kw;
787
795
  }
788
796
  if (Object.keys(keywords).length > 0) desc.optionKeywords = keywords;
797
+ const addedAt = {};
798
+ for (const option of desc.options) {
799
+ const t = getLoraAddedAt(option, hostId);
800
+ if (t != null) addedAt[option] = t;
801
+ }
802
+ if (Object.keys(addedAt).length > 0) desc.optionAddedAt = addedAt;
803
+ const triggers = {};
804
+ for (const option of desc.options) {
805
+ const t = getLoraTriggers(option, hostId);
806
+ if (t != null) triggers[option] = t;
807
+ }
808
+ if (Object.keys(triggers).length > 0) desc.optionTriggers = triggers;
789
809
  }
790
810
  vars[name] = desc;
791
811
  }
@@ -1065,6 +1085,74 @@ var ServeApp = class {
1065
1085
  note: `${mirror.count} loras synced`
1066
1086
  });
1067
1087
  }
1088
+ /** fetch ONE lora's civitai metadata through the lora manager, then re-sync the mirror so its
1089
+ * trigger words reach every surface. The extension keys the request by the file path ON THE
1090
+ * HOST, which only the mirror knows, so a lora outside the mirror needs a sync first */
1091
+ async replyLoraCivitaiFetch(hostId, lora) {
1092
+ const host = comfyts.hosts.get(hostId);
1093
+ if (host == null) return json(404, { error: `unknown host '${hostId}'` });
1094
+ const info = getLoraInfo(lora, hostId);
1095
+ const filePath = info == null ? null : lmFilePath(info);
1096
+ if (filePath == null) return json(404, { error: `'${lora}' is not in the lora manager mirror of ${hostId}: sync the mirror first` });
1097
+ const fetched = await fetchLoraCivitai(host, filePath);
1098
+ const sha256 = info == null ? null : lmSha256(info);
1099
+ if (!fetched.ok && /no version data found/i.test(fetched.reason) && sha256 != null) {
1100
+ recordCivitaiMiss({
1101
+ hostId,
1102
+ sha256,
1103
+ miss: true
1104
+ });
1105
+ return json(200, {
1106
+ ok: true,
1107
+ host: hostId,
1108
+ lora,
1109
+ triggers: { state: "not-on-civitai" },
1110
+ note: `civitai does not know '${lora}' (a private or local lora): no trigger words to fetch`
1111
+ });
1112
+ }
1113
+ if (!fetched.ok) return json(502, { error: `civitai fetch failed for '${lora}': ${fetched.reason}` });
1114
+ if (sha256 != null) recordCivitaiMiss({
1115
+ hostId,
1116
+ sha256,
1117
+ miss: false
1118
+ });
1119
+ const synced = await this.refreshLoraMirror(hostId, host);
1120
+ if (synced.status !== 200) return synced;
1121
+ const t = getLoraTriggers(lora, hostId);
1122
+ return json(200, {
1123
+ ok: true,
1124
+ host: hostId,
1125
+ lora,
1126
+ triggers: t,
1127
+ note: t?.state === "words" ? `trigger words: ${t.words.join(", ")}` : t?.state === "none" ? `civitai lists no trigger words for '${lora}'` : `civitai has no metadata for '${lora}'`
1128
+ });
1129
+ }
1130
+ /** has the host changed since this process loaded its schema: new or removed model files (and
1131
+ * node types on a full check). A host whose catalog is COMMITTED rather than live-synced
1132
+ * (sdkAutoWrite: false, the cloud catalog) is not compared: its live list moves on purpose */
1133
+ async replyHostDrift(hostId, full) {
1134
+ const host = comfyts.hosts.get(hostId);
1135
+ if (host == null) return json(404, { error: `unknown host '${hostId}'` });
1136
+ if (host.data.sdkAutoWrite === false) return json(200, {
1137
+ host: hostId,
1138
+ checked: false,
1139
+ changed: false,
1140
+ summary: ""
1141
+ });
1142
+ try {
1143
+ const drift = await host.checkSchemaDrift({ full });
1144
+ return json(200, {
1145
+ host: hostId,
1146
+ checked: true,
1147
+ full,
1148
+ changed: driftChanged(drift),
1149
+ summary: summarizeDrift(drift),
1150
+ drift
1151
+ });
1152
+ } catch (e) {
1153
+ return json(502, { error: `${hostId} unreachable: ${extractErrorMessage(e)}` });
1154
+ }
1155
+ }
1068
1156
  /** is the host answering RIGHT NOW: what the panel polls while a restart is in flight, so
1069
1157
  * "restarting…" ends on a fact rather than on a guess */
1070
1158
  async replyHostPing(hostId) {
@@ -1945,4 +2033,4 @@ function printStartup(app, bind, port) {
1945
2033
  //#endregion
1946
2034
  export { runServe };
1947
2035
 
1948
- //# sourceMappingURL=run-serve-_nrvJYyt.js.map
2036
+ //# sourceMappingURL=run-serve-BK7BA2dn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-serve-BK7BA2dn.js","names":["g"],"sources":["../src/cli/serve/describeVar.ts","../src/cli/serve/applyVarPayload.ts","../src/utils/safeName.ts","../src/promptEnhancers.ts","../src/cli/serve/managerOnlyLoras.ts","../src/cli/serve/favicon.ts","../src/utils/stringMap.ts","../src/cli/serve/serveSettings.ts","../src/cli/serve/ServeApp.ts","../src/cli/serve/startupPrint.ts","../src/cli/serve/webBundle.ts","../src/cli/serve/run-serve.ts"],"sourcesContent":["// PURE var → descriptor: ONE introspection pass feeds GET /drafts (json) AND\n// the startup print (renderDescriptorLine)\nimport { ansi } from 'src/utils/ansi.ts'\nimport type {\n AnyVar,\n ChoiceVar,\n FloatVar,\n ImageVar,\n IntVar,\n LorasVar,\n PromptVar,\n SeedVar,\n SizePreset,\n SizeVar,\n TextVar,\n VarKind,\n} from 'src/vars/ComfyVars.ts'\nimport type { VarPreset } from 'src/vars/presets.ts'\nimport type { LoraTriggers } from 'src/host/loraInfoCache.ts'\n\nexport type VarDescriptor = {\n kind: VarKind\n label?: string\n /** what a POST payload accepts for this var, human-readable */\n payload: string\n default: unknown\n choices?: readonly string[]\n /** loras: the resolved option list */\n options?: readonly string[]\n /** loras: human display names from the lora-manager mirror, keyed by option — entries only where the label differs (filled by ServeApp.describeModule, which knows the host) */\n optionLabels?: Record<string, string>\n /** prompt: the name of the loras var whose ACTIVE keywords prefix this prompt\n * (`v.prompt(…, { loraKeywordsFrom })`), filled by ServeApp.describeModule, which is the\n * only place that knows both vars by name. The panel previews the injection from it */\n keywordsFrom?: string\n /** loras: the regex the workflow narrowed the list with (`/krea-?2/i`), when it did */\n optionsFilter?: string\n /** loras: hand-assigned keyword (or trigger words) per option, entries only where one\n * exists, what a prompt with `loraKeywordsFrom` will prepend */\n optionKeywords?: Record<string, string>\n /** loras: names the lora-manager mirror knows and ComfyUI's enum does NOT (yet). Offered in\n * the picker with a warning, because a lora present on disk usually runs even when the\n * server has not rescanned its list, filled by ServeApp.describeModule */\n managerOnlyOptions?: readonly string[]\n /** loras: when each file landed on the host (epoch seconds, the lora manager's date), entries\n * only where the mirror has one. The popup's `date added` sort reads it */\n optionAddedAt?: Record<string, number>\n /** loras: trigger words per option as the mirror knows them (words, fetched and empty, or\n * civitai never asked). An option ABSENT from this record is not in the mirror at all */\n optionTriggers?: Record<string, LoraTriggers>\n /** text: this one wants a box, not a line (`v.text(…, { multiline: true })`) */\n multiline?: boolean\n /** text + prompt: named starting texts (`{ presets: { label: text } }`). NOT `presets`, which\n * a size var already owns with a different shape — one flat descriptor type, two kinds */\n textPresets?: VarPreset[]\n min?: number\n max?: number\n presets?: SizePreset[]\n extensions?: readonly string[]\n}\n\n/** an empty list is absent from the json: every var without presets would otherwise carry `[]` */\nfunction presetsOrUndefined(presets: VarPreset[]): VarPreset[] | undefined {\n return presets.length === 0 ? undefined : presets\n}\n\nfunction rangeText(opts: { min?: number; max?: number }): string {\n if (opts.min == null && opts.max == null) return ''\n return ` (${opts.min ?? '-∞'}..${opts.max ?? '∞'})`\n}\n\nexport function describeVar(varDef: AnyVar): VarDescriptor {\n const base = { kind: varDef.kind, label: varDef.label, default: varDef.defaultValue }\n // kind, never instanceof: the cli bundle and the consumer's `comfy-ts` import hold\n // different copies of every class (VarKind owns the WHY). Casts are the sanctioned\n // kind-narrowing family (agent/coding.md cast whitelist 6)\n switch (varDef.kind) {\n case 'prompt': {\n const v = varDef as PromptVar\n return {\n ...base,\n payload: 'string (\"//\" lines = comments, \"- \" lines = negative)',\n textPresets: presetsOrUndefined(v.presets),\n }\n }\n case 'text': {\n const v = varDef as TextVar\n return { ...base, payload: 'string', multiline: v.opts.multiline, textPresets: presetsOrUndefined(v.presets) }\n }\n case 'int': {\n const v = varDef as IntVar\n return { ...base, payload: `integer${rangeText(v.opts)}`, min: v.opts.min, max: v.opts.max }\n }\n case 'float': {\n const v = varDef as FloatVar\n return { ...base, payload: `number${rangeText(v.opts)}`, min: v.opts.min, max: v.opts.max }\n }\n case 'seed': {\n const v = varDef as SeedVar\n return {\n ...base,\n // defaultMode, never the LIVE mode: serve's vars are shared mutable state, so a\n // run under '?' would otherwise leak its mode into every fileless draft's defaults\n // (and the web ui autosaves those defaults straight back into the draft file)\n default: { mode: v.defaultMode, value: v.defaultValue },\n payload: 'number (fixed) or {\"mode\":\"=|+|-|?\",\"value\":number}',\n }\n }\n case 'toggle':\n return { ...base, payload: 'true or false' }\n case 'choice': {\n const v = varDef as ChoiceVar<string>\n return { ...base, payload: `one of: ${v.choices.join(' | ')}`, choices: v.choices }\n }\n case 'loras': {\n const v = varDef as LorasVar<string>\n return {\n ...base,\n payload: '{\"<lora name>\": false | true | strength | [model, clip]}',\n options: v.options,\n // the workflow's own narrowing, shown in the picker so the list is explainable\n optionsFilter: v.optionsFilter == null ? undefined : String(v.optionsFilter),\n }\n }\n case 'size': {\n const v = varDef as SizeVar\n return { ...base, payload: '{\"width\":W,\"height\":H} or \"WxH\" or a preset label', presets: v.presets }\n }\n case 'image': {\n const v = varDef as ImageVar\n return { ...base, payload: 'local file path or http(s) url', extensions: v.extensions }\n }\n default: {\n // an unknown kind CAN reach here: a globally installed cli against a project on a\n // newer comfy-ts (wire tolerance, agent/coding.md whitelist 4). The `never` binding\n // is the compile-time exhaustiveness check; the RUNTIME path must degrade, because\n // printStartup calls d.kind.padEnd() before the server ever listens\n const unknownKind: never = varDef.kind\n return { ...base, payload: `string (unrecognised kind '${String(unknownKind)}')` }\n }\n }\n}\n\n/** one aligned console line per var (startup print). Padding happens on the PLAIN text: colors are wrapped around the\n * already-padded cells, so a colored and an uncolored print line up identically */\nexport function renderDescriptorLine(name: string, d: VarDescriptor, nameWidth: number, color = false): string {\n const def = typeof d.default === 'string' ? JSON.stringify(truncate(d.default, 40)) : JSON.stringify(d.default)\n const cells = { name: name.padEnd(nameWidth), kind: d.kind.padEnd(6), value: truncate(def ?? 'null', 60) }\n if (!color) return ` ${cells.name} ${cells.kind} ${d.payload} · default: ${cells.value}`\n return ` ${ansi.bold(cells.name)} ${ansi.yellow(cells.kind)} ${ansi.gray(d.payload)} ${ansi.gray('· default:')} ${cells.value}`\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : s.slice(0, n - 1) + '…'\n}\n","// PURE payload → var application: one POST body value onto one var, per kind.\n// Returns an error message (nothing applied) or null. No fs here — ImageVar\n// url download + existence checks are ServeApp's job.\n//\n// Discrimination is by `kind`, NEVER instanceof: a consumer's `.cflow.ts` imports\n// `comfy-ts` (dist/index.js) while `comfy-ts serve` runs from the cli bundle, and the\n// two hold different copies of every class, so instanceof was false for EVERY var and\n// every payload override answered \"unsupported kind\". The casts\n// below are the sanctioned kind-narrowing family (agent/coding.md cast whitelist 6).\nimport type {\n AnyVar,\n ChoiceVar,\n FloatVar,\n ImageVar,\n IntVar,\n LoraStrength,\n LorasVar,\n PromptVar,\n SeedVar,\n SizeVar,\n TextVar,\n ToggleVar,\n} from 'src/vars/ComfyVars.ts'\n\nfunction isFiniteNumber(x: unknown): x is number {\n return typeof x === 'number' && Number.isFinite(x)\n}\n\nfunction isLoraStrength(x: unknown): x is LoraStrength {\n if (typeof x === 'boolean') return true\n if (isFiniteNumber(x)) return true\n return Array.isArray(x) && x.length === 2 && isFiniteNumber(x[0]) && isFiniteNumber(x[1])\n}\n\n/** cap long option lists in error messages */\nfunction listSome(items: readonly string[], cap: number = 20): string {\n if (items.length <= cap) return items.join(', ')\n return `${items.slice(0, cap).join(', ')} … +${items.length - cap} more`\n}\n\n/** `extraLoraOptions`: names the lora-manager mirror knows that ComfyUI's enum does not.\n * they are accepted like any option, the file is on disk, so the run usually works, but\n * ONLY those: an arbitrary name still fails, so a typo cannot reach the host */\nexport function applyVarPayload(\n varDef: AnyVar,\n raw: unknown,\n opts: { extraLoraOptions?: readonly string[] } = {},\n): string | null {\n const name = varDef.name ?? varDef.label ?? varDef.kind\n\n switch (varDef.kind) {\n case 'text':\n case 'prompt': {\n if (typeof raw !== 'string') return `var '${name}' expects a string`\n ;(varDef as TextVar | PromptVar).set(raw)\n return null\n }\n\n case 'int':\n case 'float': {\n const v = varDef as IntVar | FloatVar\n if (isFiniteNumber(raw)) {\n v.set(raw) // set() clamps to min/max\n return null\n }\n if (typeof raw === 'string' && v.parse(raw)) return null\n const o = v.opts\n const range = o.min == null && o.max == null ? '' : ` (${o.min ?? '-∞'}..${o.max ?? '∞'})`\n return `var '${name}' expects a number${range}`\n }\n\n case 'seed': {\n const v = varDef as SeedVar\n if (isFiniteNumber(raw)) {\n // an explicit payload seed is FIXED for this request\n v.setMode('=')\n v.set(raw)\n return null\n }\n if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {\n const o = raw as { mode?: unknown; value?: unknown }\n const mode = o.mode === '=' || o.mode === '+' || o.mode === '-' || o.mode === '?' ? o.mode : null\n if (o.mode !== undefined && mode == null) return `var '${name}': mode must be one of = + - ?`\n if (o.value !== undefined && !isFiniteNumber(o.value)) return `var '${name}': value must be a number`\n if (mode == null && o.value === undefined) return `var '${name}': give \"mode\" and/or \"value\"`\n if (mode != null) v.setMode(mode)\n if (isFiniteNumber(o.value)) v.set(o.value)\n return null\n }\n return `var '${name}' expects a number or {\"mode\":\"=|+|-|?\",\"value\":number}`\n }\n\n case 'toggle': {\n if (typeof raw !== 'boolean') return `var '${name}' expects true or false`\n ;(varDef as ToggleVar).set(raw)\n return null\n }\n\n case 'choice': {\n const v = varDef as ChoiceVar<string>\n if (typeof raw === 'string' && v.parse(raw)) return null\n return `var '${name}' expects one of: ${listSome(v.choices)}`\n }\n\n case 'loras': {\n const v = varDef as LorasVar<string>\n if (raw == null || typeof raw !== 'object' || Array.isArray(raw))\n return `var '${name}' expects {\"<lora name>\": false | true | strength | [model, clip]}`\n const record = raw as Record<string, unknown>\n const known = new Set<string>([...v.options, ...(opts.extraLoraOptions ?? [])])\n const unknownNames = Object.keys(record).filter((k) => !known.has(k))\n if (unknownNames.length > 0)\n return `var '${name}': unknown lora(s) ${unknownNames.join(', ')} — available: ${listSome([...known])}`\n for (const [k, st] of Object.entries(record))\n if (!isLoraStrength(st)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`\n v.set(record as Partial<Record<string, LoraStrength>>) // every entry validated just above\n return null\n }\n\n case 'size': {\n const v = varDef as SizeVar\n if (typeof raw === 'string' && v.parse(raw)) return null\n if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {\n const o = raw as { width?: unknown; height?: unknown }\n if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {\n v.set({ width: o.width, height: o.height })\n return null\n }\n }\n return `var '${name}' expects {\"width\":W,\"height\":H}, \"WxH\", or a preset label`\n }\n\n case 'image': {\n if (typeof raw !== 'string') return `var '${name}' expects a file path or http(s) url string`\n ;(varDef as ImageVar).set(raw)\n return null\n }\n\n default: {\n // same as describeVar: `never` is the compile-time check, the runtime path keeps\n // the message a caller can act on instead of answering a bare token\n const unknownKind: never = varDef.kind\n return `var '${name}' has unsupported kind '${String(unknownKind)}'`\n }\n }\n}\n","// THE name gate for every serve route that turns a url segment into a file path.\n// SECURITY-CRITICAL and deliberately shared: handle() decodes per segment, so\n// `%2F` arrives as a real `/` while the segment count still looks right. One\n// function, because a second regex somewhere else is a second traversal hole.\n\n/** the accepted name, or null. Rejects traversal, absolute paths, leading dots and empties */\nexport function validStoreName(raw: string): string | null {\n const name = raw.trim()\n // length cap: past it the fs answers ENAMETOOLONG as a raw 500\n if (name.length > 100) return null\n return /^[\\w][\\w .-]*$/.test(name) ? name : null\n}\n\n/** a save prefix becomes a PATH under outputs/, so every segment goes through the same gate:\n * it cannot climb out, and it cannot be absolute. Lives here, not on ServeApp, because the\n * settings READER validates it too, a hand-written settings file never met the PUT route. */\nexport function validSavePrefix(raw: string): string | null {\n const clean = raw.trim().replaceAll('\\\\', '/')\n if (clean === '') return ''\n // an ABSOLUTE path is refused, not quietly re-rooted: dropping the leading slash turned\n // '/etc' into 'etc' under outputs/, which is safe but is not what the writer asked for\n if (clean.startsWith('/') || /^[a-z]:/i.test(clean)) return null\n // the whole path is capped, not only each segment: 3000 valid two-char segments passed and\n // then broke that module's saving for good with an unopenable path\n if (clean.length > 200) return null\n const segments = clean.split('/').filter((s) => s !== '')\n if (segments.length === 0 || segments.some((s) => validStoreName(s) == null)) return null\n return segments.join('/')\n}\n","// the master prompts of the web ui's prompt enhancer, as FILES:\n// `.comfy-ts/prompt-enhancers/<name>.md`, the drafts model applied to prose.\n// markdown, not json: these are hand-edited paragraphs, and a json string field\n// would be one escaped line. The FILENAME is the identity (a rename is a write\n// plus a delete); validStoreName is the same gate the draft routes use.\n// NODE-ONLY (fs): the web entry never touches this folder, and a workflow reads\n// it through promptEnhancerPresets() to offer the same texts as var presets.\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { join } from 'pathe'\nimport { validStoreName } from 'src/utils/safeName.ts'\nimport type { VarPresetSpec } from 'src/vars/presets.ts'\n\nconst EXT = '.md'\n\nexport type PromptEnhancer = { name: string; text: string }\n\nexport function promptEnhancersDir(): string {\n return comfyts.resolveFromPromptEnhancers('')\n}\n\nfunction promptEnhancerPath(name: string): string | null {\n const safe = validStoreName(name)\n return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT}`)\n}\n\n/** the shipped starting point. It is a FILE from the first read on, so it can be edited\n * on disk like everything else, the browser ships no copy of this text */\nconst SEED: PromptEnhancer = {\n name: 'refine-krea2-prompt',\n text: `You rewrite image prompts for krea2 turbo, a distilled 8 step text to image model whose text encoder reads flowing natural language. Long detailed prompts give it the best images. Your job is to serve the VISION behind the user's line: take what they wrote and expand it into the picture they were already imagining but did not type.\n\nRewrite it into ONE paragraph a reader could picture with their eyes closed:\n\n- every subject, action, color and spatial relation the user wrote survives, in their own words wherever those words already work. Nothing is dropped, nothing is swapped for something easier.\n- expand the vision, never replace it. Add the visual facts a camera would have to resolve anyway: what each subject looks like, lighting, palette, material and texture, camera angle and distance, framing and composition, background, depth of field, mood, and the signature of the medium itself (visible brushstrokes, film grain, cel shading, stippling, halftone, airbrush gradients, paper texture).\n- choose the style before you write, and keep the choosing invisible. Weigh two or three mediums and lighting setups, pick the one that best serves the input, then write only the result. If they named a medium (photo of, illustration of, 3D render of, painting of, sketch of), that medium is fixed.\n- attach every attribute to its own subject, so nothing bleeds: one clause per figure carrying its features, clothes, pose and action. Spatial words stay grounded: left foreground, upper center, behind, resting on, knee deep in.\n- an input that is already dense gets polished and finished, not inflated. Keep its phrasing and its direction, add only what is genuinely missing.\n- plain descriptive english. Flowing sentences and comma separated descriptive clauses both read well; disconnected keyword soup does not. No praise words, never \"masterpiece\", \"8k\", \"highly detailed\", \"award winning\", \"trending on\". The model is steered by what you name, not by what you forbid.\n- text that must appear inside the image is spelled out in \"quotes\", exactly as it should be rendered.\n- roughly 60 to 150 words, one paragraph, no lists, no headings, no quotes around the result itself.\n- keep any \"// \" comment line and any \"- \" negative line from the input verbatim, each on its own line.\n\nAnswer with the rewritten prompt and nothing else: no preamble, no explanation.\n`,\n}\n\n/** seeds ONCE, on an absent folder, then lists. An emptied folder stays empty: the seed is a\n * starting point, not a file the store keeps restoring */\nexport function listPromptEnhancers(): PromptEnhancer[] {\n if (!existsSync(promptEnhancersDir())) writePromptEnhancer(SEED.name, SEED.text)\n return readPromptEnhancers()\n}\n\n/** the PURE read: no seeding, no writing. What a workflow calls at define time, since importing\n * a module must never create files in someone's project */\nexport function readPromptEnhancers(): PromptEnhancer[] {\n const dir = promptEnhancersDir()\n if (!existsSync(dir)) return []\n const out: PromptEnhancer[] = []\n for (const file of readdirSync(dir).sort()) {\n if (!file.endsWith(EXT)) continue\n const name = file.slice(0, -EXT.length)\n if (validStoreName(name) == null) continue\n // one unreadable entry (a DIRECTORY called *.md, a permission problem) must not take the\n // whole route down: it is skipped loudly, the rest still list\n try {\n out.push({ name, text: readFileSync(join(dir, file), 'utf8') })\n } catch (e) {\n console.error(`[serve] prompt enhancer '${name}' unreadable, skipped:`, e)\n }\n }\n return out\n}\n\n/**\n * the same master prompts, shaped for `v.text(x, { presets })` / `v.prompt`: file name → text.\n * The point is that ONE library of texts serves the ✨ enhancer and every var that wants them,\n * so a paragraph you tuned in the panel is offered by the workflow too, with no copy.\n * Empty when the folder is absent, so a var keeps whatever presets it declares inline.\n */\nexport function promptEnhancerPresets(): VarPresetSpec {\n const out: VarPresetSpec = {}\n for (const e of readPromptEnhancers()) out[e.name] = e.text\n return out\n}\n\nexport function writePromptEnhancer(name: string, text: string): string | null {\n const path = promptEnhancerPath(name)\n if (path == null) return null\n mkdirSync(promptEnhancersDir(), { recursive: true })\n writeFileSync(path, text)\n return path\n}\n\n/** a missing file is still a success: the caller asked for it to be gone, and it is */\nexport function deletePromptEnhancer(name: string): boolean {\n const path = promptEnhancerPath(name)\n if (path == null) return false\n if (existsSync(path)) rmSync(path)\n return true\n}\n","// the loras a host's lora-manager knows but its object_info enum does not yet list.\n// ONE function, because the picker and the payload validator must agree exactly: whatever\n// the ui offers, `applyVarPayload` compares by RAW STRING, so a name built with the wrong\n// separator is offered and then refused as an unknown lora.\nimport { loraMirrorEntries } from 'src/host/loraInfoCache.ts'\nimport { loraKey } from 'src/host/loraManagerApi.ts'\nimport { statelessRegex } from 'src/utils/matchesRegex.ts'\n\n/**\n * `options` is the host enum for this var: it decides both what counts as already-known\n * (compared by normalized key, never raw, the enum keeps case, extension and separators)\n * and which separator the rebuilt names must use.\n */\nexport function managerOnlyLoraOptions(p: {\n hostId: string\n options: readonly string[]\n /** the var's own narrowing, `v.loras(/krea-?2/i)`: it applies to the mirror too */\n filter?: RegExp | null\n}): string[] {\n const filter = p.filter == null ? null : statelessRegex(p.filter)\n const known = new Set(p.options.map((o) => loraKey(o)))\n const separator = p.options.some((o) => o.includes('\\\\')) ? '\\\\' : '/'\n return loraMirrorEntries(p.hostId, { separator })\n .filter((e) => !known.has(e.key))\n .map((e) => e.serverName)\n .filter((n) => filter == null || filter.test(n))\n}\n","// generated by scripts/gen-favicon.ts from .shipkit/identity/icon.png, never edited by hand\nexport const FAVICON_DATA_URI =\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAKUklEQVR42u1aaWxU1xW2DWEJZCENNgaK8iNRU5UAAYKBWW1ImwbaoqiuQkrUVlRdlDZSGpqAcTKrFyAoJRCRKmpRidKA98Sm0MQhRClOs7CIggiTtniZN4sZe8AeL/Puvef23LeMnwePQdWwhTnS9XvP8zzvft/5znfPfXJWViYykYlMZCITmchEJjKRiUxc4eCcj8ExFkfOzQg+23huvL5pwFNKf8wYexmvZ2m/H6cpQlHFV5IYIXvtaMEh4+CM83/hIS9ZGSOUSvYNnXUNyC3iGgA2KuAZ7+NqvI3jZ6iKp3GsIYQsw+sZOmFJZIy5Ec0uRzufhOMHjMGnGnAUAAdtJALUqxgwOIYs7UBCViFptycTekNkXcv4eMzsL/Hap2Pkw0MQQbTB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EbZiQAywKWuPwwDxWx2CnBT14Lw58+7IGT/kGQaQqZM5UQNnLNw/4T/cJ44cGN6PQI3uTyM3wes1Vg9j3S6qGu7yqGTkKhq3WdvaKbmcu7uXDjpS6JCV+we0NgcQVgYWkA5pZICimrXw1DxTtRaDwaA18wDtjAsCQlGI0PPjozwH7++jnMekBZ6qweobIANXk6qb0iys3O1t9eE/AJErQH2zz+5ejAPmFGZndQEEBMeMTdmDApEOWBZaKAmLtBggUvIBi8XrklwNYiwOf3RMBV2wU73zsPcTLU8D21qxPuX9cGdqx5QSZ+JzF7z4HVG6EWl/9XaW13/09TyNZJWFHRNsXqkjZbPKE+++YYt3g7ccIBQQQ1aUQIEnDJQkLw3BmEpQ4/PFTqR2n7YfZz7XjeAYGonNDAX1su4ArTgWQpqiK2ivPY6ESiZkf7qusAvFEKSIK2/FjdHfcVYjuKkz5vq8SlUkwagSMAWRAiDNPsEhmVQBwFIVbF1ERtS9Di60+URPOpPrbwhQ6KpLJCQaoz8LnV3f7ANZX9qMtk8dD20+bwzbS7pOfMLv8RYVjWTQgAuzU0TI51jCRgD+EOyiYPkuLCFxi4muAKQkUp6AQ0Hu2nC51daHTBHqsr8OJKh3Tr9Qk+qX0uLh6aoDBLe3lHgd3d4UEgLWaPFLOWR3jhSwNclIoNX1tZUSXWcjyWdfECp8T2fNyDBknJ02/G+JySYH3xjrPT9O92OG6Q/yxRiEh6ISE2V49U+mYWlUmrcLkstTtbd1md/ibcwX2EajiEBnrMVBbBDs8vF3oCAyYkBZe6NQqRDj4u6wb9X4FsoQjVsFIA4HrZ8LHY1TUXbiXcUtHHbeWRTpvj7D1XvsO7qspw5NhsH4wVYB3KuwYNmAZw5UvS3bh8brW4gvvRKL/zlQKfSiEqCcaR/HnWzfWfZMX6snq1evtMZCITmchEJjKRiUxkIhM3ZfwPK9dyLD4coj4AAAAASUVORK5CYII='\n","// unknown json → a plain record of strings. Every localStorage blob and every settings file\n// crossing into this process needs the same shape check; two copies of it drift.\nexport function stringMap(raw: unknown): Record<string, string> {\n const out: Record<string, string> = {}\n if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) {\n for (const [k, v] of Object.entries(raw)) if (typeof v === 'string') out[k] = v\n }\n return out\n}\n","// serve's own slice of `.comfy-ts/settings.json`, under a `serve` key.\n// MERGE, never rewrite: the TUI owns the rest of that file and a whole-blob write\n// from here would silently drop its preview mode, last draft and lora prefixes.\n// deliberately NOT the TUI's `saveToDisk`: that one governs TUI runs, this one\n// governs the api's, so the two surfaces cannot fight over one value.\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { stringMap } from 'src/utils/stringMap.ts'\nimport { validSavePrefix } from 'src/utils/safeName.ts'\nimport { dirname } from 'pathe'\n\nexport type ServeSettings = {\n /** false = generations stay in memory, streamed to the client, nothing written to outputs/ */\n saveToDisk: boolean\n /** module key → host id the runs go to, when it is not the one the module defined\n * (the TUI's host override, per module because serve holds many workflows at once) */\n hostOverride: Record<string, string>\n /** module key → subfolder under outputs/ its images land in. Empty/absent = the module key,\n * which is what serve always used before it was choosable */\n savePrefix: Record<string, string>\n}\n\nconst DEFAULT_SERVE_SETTINGS: ServeSettings = { saveToDisk: true, hostOverride: {}, savePrefix: {} }\n\n/** null when no comfyts is registered yet: a ServeApp can be constructed before the global\n * exists (tests do), and reading a setting must degrade to defaults, never throw */\nfunction settingsPath(): string | null {\n const g = globalThis as { comfyts?: { settingsPath?: string } }\n const path = g.comfyts?.settingsPath\n return typeof path === 'string' ? path : null\n}\n\n/** `readable: false` says the file EXISTS but could not be parsed — the one case where a write\n * must refuse. Merging onto `{}` there would rewrite the file from nothing and take the TUI's\n * keys with it, and these files are documented as hand-editable, so the user would lose the\n * chance to repair it. */\nfunction readBlob(): { blob: Record<string, unknown>; readable: boolean } {\n const path = settingsPath()\n if (path == null || !existsSync(path)) return { blob: {}, readable: true }\n try {\n const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))\n const ok = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)\n if (!ok) console.error(`[serve] settings is not an object (${path}), using defaults`)\n return { blob: ok ? (parsed as Record<string, unknown>) : {}, readable: ok }\n } catch (e) {\n // reading must not take the server down: log loud, use defaults, and refuse to WRITE\n console.error(`[serve] settings unreadable (${path}), using defaults:`, e)\n return { blob: {}, readable: false }\n }\n}\n\n/** keeps the CLEANED value, not the raw one: storing the raw form let the same input mean two\n * different directories depending on whether it arrived by PUT or by hand */\nfunction cleanValues(map: Record<string, string>, clean: (v: string) => string | null): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(map)) {\n const ok = clean(v)\n if (ok != null) out[k] = ok\n }\n return out\n}\n\nexport function readServeSettings(): ServeSettings {\n const serve = readBlob().blob.serve\n const o = typeof serve === 'object' && serve !== null ? (serve as Record<string, unknown>) : {}\n return {\n saveToDisk: typeof o.saveToDisk === 'boolean' ? o.saveToDisk : DEFAULT_SERVE_SETTINGS.saveToDisk,\n hostOverride: stringMap(o.hostOverride),\n // validated on the way IN as well as on the way out: PUT /settings gates it, but a\n // hand-written file did not go through that route, and this value becomes an output\n // directory. One gate on one side is not a gate\n savePrefix: cleanValues(stringMap(o.savePrefix), validSavePrefix),\n }\n}\n\nexport function writeServeSettings(next: ServeSettings): void {\n const path = settingsPath()\n // loud: the caller reports \"applied for this session but not saved\" rather than pretending\n if (path == null) throw new Error('no comfyts instance registered — cannot persist serve settings')\n const current = readBlob()\n if (!current.readable)\n throw new Error(\n `serve settings not saved: ${path} is not readable json. Fix or delete it — overwriting would drop the keys it still holds`,\n )\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify({ ...current.blob, serve: next }, null, 2))\n}\n","// `comfy-ts serve` request handling, transport-free: run-serve owns node:http,\n// tests call handle() directly with an injected starter. Full contract:\n// agent/architecture.md item 12.\nimport {\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n readSync,\n realpathSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs'\nimport { nanoid } from 'nanoid'\nimport { basename, dirname, extname, join, resolve } from 'pathe'\nimport { applyVarPayload } from 'src/cli/serve/applyVarPayload.ts'\nimport { describeVar, type VarDescriptor } from 'src/cli/serve/describeVar.ts'\nimport { deletePromptEnhancer, listPromptEnhancers, writePromptEnhancer } from 'src/promptEnhancers.ts'\nimport { managerOnlyLoraOptions } from 'src/cli/serve/managerOnlyLoras.ts'\nimport { FAVICON_DATA_URI } from 'src/cli/serve/favicon.ts'\nimport { driftChanged, summarizeDrift } from 'src/host/schemaDrift.ts'\nimport { validSavePrefix, validStoreName } from 'src/utils/safeName.ts'\nimport { readServeSettings, writeServeSettings, type ServeSettings } from 'src/cli/serve/serveSettings.ts'\nimport { assembleLogChunks } from 'src/cli/tui/state/LogsSt.ts'\nimport { draftsDirForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'\nimport {\n buildLoraMirror,\n getLoraAddedAt,\n getLoraTriggers,\n type LoraTriggers,\n recordCivitaiMiss,\n getLoraDisplayName,\n getLoraInfo,\n getLoraPreviewUrl,\n getLoraTriggerWords,\n refreshLoraInfoCacheIfChanged,\n reloadLoraInfoCache,\n writeLoraMirror,\n} from 'src/host/loraInfoCache.ts'\nimport {\n fetchLoraCivitai,\n fetchLoraDescription,\n fetchLoraExampleImages,\n fetchLoraList,\n fetchLoraPreviewBytes,\n lmBaseModel,\n lmCivitai,\n lmFilePath,\n lmFileSize,\n lmSha256,\n lmFolder,\n lmNotes,\n lmTags,\n loraKey,\n loraPreviewMapFrom,\n} from 'src/host/loraManagerApi.ts'\nimport { getLoraKeyword } from 'src/vars/loraKeywords.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport { DEFAULT_IMAGE_EXTENSIONS } from 'src/vars/ComfyVars.ts'\nimport type { ImageVar, LorasVar, PromptVar, SeedVar } from 'src/vars/ComfyVars.ts'\nimport type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\n\nexport type ServeModule = { key: string; file: string; dw: DefinedWorkflow }\n\n/** structural face of ComfyExecution — tests inject a fake starter.\n * absPath is null for in-memory images (a ws-saver run with saving off) */\nexport type ServeExecution = {\n done: Promise<unknown>\n status: string\n /** buffer is the ONLY copy for an in-memory image (saving off); reading it on a\n * SAVED image would hit the disk, so it is only touched when absPath is null */\n images: { absPath: string | null; filename: string; buffer?: Uint8Array }[]\n /** STRING outputs (PreviewAny, i.e. every llm graph). A text-only workflow has no images at\n * all, so without these its run reply is empty and the panel shows nothing */\n texts?: { nodeId: string; nodeKey: string | null; text: string }[]\n data: { id: string; error?: unknown }\n /** live global progress (ComfyExecution has it; fakes may omit) — the /run/<module> poll reads it */\n progressGlobal?: { percent: number }\n /** the executing node and ITS counter, in its own unit (sampler steps, generated tokens).\n * the only live signal a text node has: ComfyUI sends no partial text */\n progress?: {\n nodeName: string | null\n nodeProgress: { value: number; max: number } | null\n /** a node's live display text while it runs — a streaming generator's partial answer */\n progressText?: string | null\n }\n}\n\nexport type ServeStarter = (\n mod: ServeModule,\n opts: { saveToDisk: boolean; savePrefix: string; host?: ComfyHost },\n) => Promise<ServeExecution>\n\nexport type ServeRequest = { method: string; url: string; accept?: string; body?: string }\nexport type ServeReply = {\n status: number\n contentType: string\n body: string | Uint8Array\n /** extra response headers, lowercase keys — the transport writes them verbatim */\n headers?: Record<string, string>\n}\n\n/** what serve will read off the disk and upload. Wider than the picker default: ComfyUI's\n * LoadImage takes bmp and tiff too, and a var declaring one of those must not be refused */\nconst SERVE_IMAGE_FLOOR = new Set([\n ...DEFAULT_IMAGE_EXTENSIONS.map((e) => e.toLowerCase()),\n 'bmp',\n 'tif',\n 'tiff',\n 'avif',\n])\n\n/** the first bytes say what a file IS; the name only says what it claims. Cheap, and it stops\n * a .png that holds a key or a script from being read and uploaded to the host.\n * HONEST LIMIT: this is checked before the run, and the file is read again when the graph\n * builds, so a local writer who can swap the path in between still wins. Closing that needs\n * the upload to hold an fd, which is a bigger change than this gate. */\nfunction looksLikeImage(path: string): boolean {\n let fd: number | null = null\n try {\n fd = openSync(path, 'r')\n const head = new Uint8Array(16)\n const n = readSync(fd, head, 0, 16, 0)\n return isImageMagic(head.subarray(0, n))\n } catch {\n return false\n } finally {\n if (fd != null) closeSync(fd)\n }\n}\n\n/** what `POST /generate` will read off this machine and upload to a ComfyUI host. A var's own\n * `extensions` is documented as a PICKER filter that never affects the value, so it cannot be\n * the gate: a workflow author narrowing (or emptying) it for listing reasons must not be able\n * to widen what an unauthenticated request can make the server read. The var may narrow this\n * floor, never leave it. */\nfunction serveAcceptsImageExt(declared: readonly string[], ext: string): boolean {\n if (ext === '') return false\n if (!SERVE_IMAGE_FLOOR.has(ext)) return false\n // a declared list NARROWS the floor by its intersection. When that intersection is empty\n // the declaration says nothing this bridge can honour (a picker filter for a format serve\n // does not read), so the floor stands: narrowing to NOTHING would refuse every image,\n // including the ones the var was declared for\n const narrowed = declared.map((e) => e.toLowerCase().replace(/^\\./, '')).filter((e) => SERVE_IMAGE_FLOOR.has(e))\n return narrowed.length === 0 || narrowed.includes(ext)\n}\n\n/** an image var pointing at a url downloads it: capped, because the inbound BODY cap does not\n * apply to what serve fetches on your behalf, and one url at a big file would OOM the process */\nclass DownloadRefused extends Error {\n constructor(url: string) {\n super(`could not fetch ${url}`)\n this.name = 'DownloadRefused'\n }\n}\n\nconst INPUT_DOWNLOAD_CAP = 50_000_000\nconst INPUT_DOWNLOAD_TIMEOUT_MS = 60_000\n\n/** read a reply STREAMING, aborting the moment it passes the cap. `arrayBuffer()` buffers the\n * whole body first, so a chunked reply with no content-length could exhaust the process before\n * anything checked its size, the cap then reported a number nobody survived to read. */\nexport async function readCapped(res: Response, cap: number, what: string): Promise<Uint8Array> {\n const body = res.body\n if (body == null) return new Uint8Array(0)\n const reader = body.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n try {\n for (;;) {\n const step = await reader.read()\n if (step.done) break\n total += step.value.length\n if (total > cap) {\n await reader.cancel()\n throw new Error(`download too large (over ${cap} bytes): ${what}`)\n }\n chunks.push(step.value)\n }\n } finally {\n reader.releaseLock()\n }\n const out = new Uint8Array(total)\n let at = 0\n for (const c of chunks) {\n out.set(c, at)\n at += c.length\n }\n return out\n}\n\n/** the panel is REBUILT per serve process, so a cached copy is always the wrong one. With no\n * cache header at all a browser applies heuristic freshness and reuses app.js across reloads,\n * which makes every fix look like it never landed */\nconst NO_STORE = { 'cache-control': 'no-store, must-revalidate' }\n\n/** connect + fresh graph from current var values + send; done is awaited OUTSIDE the module mutex.\n * serve OPTS INTO local saving (library default is memory-only, architecture.md\n * item 14): the /outputs/ routes serve files, grouped per module */\nconst realStarter: ServeStarter = async (mod, opts) => {\n // the override substitutes the host the graph is BUILT against too (DefinedWorkflow.build's\n // own rule): a node missing there must surface as a workflow problem, not a silent run\n const host = opts.host ?? mod.dw.host\n await host.connect()\n const wf = await mod.dw.build({ advance: true, host })\n // saving is a SETTING now (GET/PUT /settings): off keeps outputs in memory and the\n // reply points at /images/<promptId>/<ix> instead of a file url\n return await wf.start({ save: opts.saveToDisk ? { prefix: opts.savePrefix } : false })\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.gif': 'image/gif',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n '.json': 'application/json',\n '.txt': 'text/plain',\n}\n\n/** magic-byte sniff for the preview proxy — fetchLoraPreviewBytes already guarantees an image */\nfunction sniffImageContentType(bytes: Uint8Array): string {\n if (bytes[0] === 0x89 && bytes[1] === 0x50) return 'image/png'\n if (bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg'\n if (bytes[0] === 0x47 && bytes[1] === 0x49) return 'image/gif'\n if (bytes[0] === 0x52 && bytes[1] === 0x49) return 'image/webp' // RIFF container\n return 'application/octet-stream'\n}\n\n/** the FULL signature, not the first two bytes: `RI` alone matched a wav renamed .webp, and a\n * two-byte file matched png. bmp/tiff/avif are here because the floor accepts them */\nexport function isImageMagic(b: Uint8Array): boolean {\n const at = (i: number, ...want: number[]): boolean => want.every((w, k) => b[i + k] === w)\n if (at(0, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)) return true // png\n if (at(0, 0xff, 0xd8, 0xff)) return true // jpeg\n if (at(0, 0x47, 0x49, 0x46, 0x38)) return true // gif87a/89a\n if (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x45, 0x42, 0x50)) return true // riff....webp\n if (at(0, 0x42, 0x4d)) return true // bmp\n if (at(0, 0x49, 0x49, 0x2a, 0x00) || at(0, 0x4d, 0x4d, 0x00, 0x2a)) return true // tiff le/be\n if (at(4, 0x66, 0x74, 0x79, 0x70)) return true // isobmff box: avif/heif\n return false\n}\n\nfunction json(status: number, payload: unknown): ServeReply {\n return { status, contentType: 'application/json', body: JSON.stringify(payload, null, 2) }\n}\n\nconst USAGE = [\n 'GET / in a browser — web control panel (every var as a form control)',\n 'GET /drafts — every served workflow, its drafts and var descriptors',\n 'GET /drafts/<module>/<draft> — one draft with its stored values',\n 'POST /generate/<module>/<draft> with { ...vars } — run, blocking',\n 'POST /generate/<draft> — unqualified, when unambiguous',\n 'PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft',\n 'DELETE /drafts/<module>/<draft> — delete that draft file',\n 'GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes',\n 'POST /upload with {\"name\",\"dataBase64\"} — store a browser file for an image var',\n 'GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)',\n 'GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)',\n 'POST /hosts/<hostId>/lora-civitai/<lora> — fetch its civitai metadata (trigger words) through the lora manager, then re-sync the mirror',\n 'GET /lora-preview/<hostId>/<lora> — preview image bytes',\n 'GET /lora-about/<hostId>/<lora> — civitai description + example images (live from the extension)',\n 'GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)',\n 'PUT /prompt-enhancers/<name> with {\"text\"} — write one · DELETE /prompt-enhancers/<name> — remove it',\n 'GET /settings — { saveToDisk } · PUT /settings with {\"saveToDisk\"} — write outputs to disk, or keep them in memory',\n 'GET /hosts — every host this process knows · PUT /hosts/<module> with {\"host\"} — run that workflow elsewhere',\n 'POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host',\n 'GET /hosts/<hostId>/ping — is that host answering right now (restart watch)',\n 'GET /hosts/<hostId>/logs — the last lines of that host console',\n 'GET /images/<promptId>/<ix> — an in-memory output (saving off), while the process lives',\n 'GET /outputs/<path> — generated files',\n]\n\n/** content hash of the bundle, so the script URL CHANGES whenever the code does. no-store\n * alone does not help a browser that already has app.js cached under a plain url, and a panel\n * running stale javascript is indistinguishable from a broken fix */\nfunction buildId(js: string): string {\n let h = 5381\n for (let i = 0; i < js.length; i++) h = ((h << 5) + h + js.charCodeAt(i)) | 0\n return (h >>> 0).toString(36)\n}\n\n/** the html shell; the app itself is ONE bundle at /web/app.js */\nconst WEB_SHELL = `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>comfy-ts serve</title>\n<link rel=\"icon\" type=\"image/png\" href=\"${FAVICON_DATA_URI}\">\n<style>html{background:#101217;color:#e8eaf0}</style>\n</head>\n<body>\n<div id=\"root\"></div>\n<script type=\"module\" src=\"/web/app.js?v=__BUILD__\"></script>\n</body>\n</html>\n`\n\nexport class ServeApp {\n private starter: ServeStarter\n /** last SERVED seed per `module/draft/var` — '+'/'-' modes continue from it.\n * draftBase remembers which DRAFT value the continuation grew from: when the\n * draft's seed changes (the web form autosaves a typed value), the typed\n * value wins and the continuation restarts there */\n private seedState = new Map<string, { last: number; draftBase: number }>()\n /** per-module promise chain: vars are shared mutable state, apply→send is exclusive */\n private chains = new Map<string, Promise<unknown>>()\n /** the bundle is built at most once per process, first browser hit pays it */\n private webJsCache: Promise<string | null> | null = null\n /** saving + host overrides are live settings (the web ui flips them). LAZY: a ServeApp can\n * be constructed before a comfyts instance is registered, and reading the file then would\n * throw at construction time */\n private settingsCache: ServeSettings | null = null\n private get settings(): ServeSettings {\n this.settingsCache ??= readServeSettings()\n return this.settingsCache\n }\n private set settings(next: ServeSettings) {\n this.settingsCache = next\n }\n /** in-memory outputs of runs made with saving OFF: the ONLY copy, so the gallery has\n * something to show. Capped and FIFO, a long session must not grow without bound */\n private memoryImages = new Map<string, { bytes: Uint8Array; contentType: string }>()\n\n constructor(\n public modules: ServeModule[],\n private opts: {\n starter?: ServeStarter\n outputRoot?: string\n loadErrors?: Record<string, string>\n /** web ui bundle provider (run-serve wires loadOrBuildWebJs); absent = api only */\n webJs?: () => Promise<string | null>\n } = {},\n ) {\n this.starter = opts.starter ?? realStarter\n }\n\n private get outputRoot(): string {\n return this.opts.outputRoot ?? comfyts.outputPath\n }\n\n // #region routing ----------------------------------------------------------\n async handle(req: ServeRequest): Promise<ServeReply> {\n try {\n const path = (req.url.split('?')[0] ?? '/').split('#')[0] ?? '/'\n let segs: string[]\n try {\n segs = path\n .split('/')\n .filter((s) => s !== '')\n .map(decodeURIComponent)\n } catch {\n return json(400, { error: `bad url encoding: ${path}` })\n }\n if (req.method === 'GET') {\n // a browser lands on the control panel; every other client keeps the json index.\n // the bundle resolves BEFORE the shell ships: a shell whose /web/app.js 404s is\n // a blank dark page, the json index is a usable answer\n if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes('text/html') === true) {\n this.webJsCache ??= this.opts.webJs()\n const js = await this.webJsCache\n if (js != null)\n return {\n status: 200,\n contentType: 'text/html; charset=utf-8',\n body: WEB_SHELL.replace('__BUILD__', buildId(js)),\n headers: NO_STORE,\n }\n }\n if (segs.length === 0 || (segs[0] === 'drafts' && segs.length === 1)) return this.replyIndex()\n if (segs[0] === 'web' && segs[1] === 'app.js' && segs.length === 2) return await this.replyWebJs()\n if (segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return this.replyDraft(segs[1], segs[2])\n if (segs[0] === 'run' && segs.length === 2 && segs[1] != null) return this.replyRunStatus(segs[1])\n if (segs[0] === 'run' && segs.length === 3 && segs[1] != null && segs[2] === 'preview')\n return this.replyRunPreview(segs[1])\n if (segs[0] === 'lora-info' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return this.replyLoraInfo(segs[1], segs[2])\n if (segs[0] === 'lora-preview' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return await this.replyLoraPreview(segs[1], segs[2])\n if (segs[0] === 'lora-about' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return await this.replyLoraAbout(segs[1], segs[2])\n if (segs[0] === 'prompt-enhancers' && segs.length === 1) return this.replyPromptEnhancers()\n if (segs[0] === 'settings' && segs.length === 1) return this.replySettings()\n if (segs[0] === 'hosts' && segs.length === 1) return this.replyHosts()\n if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'logs')\n return await this.replyHostLogs(segs[1])\n if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'ping')\n return await this.replyHostPing(segs[1])\n if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'drift')\n return await this.replyHostDrift(segs[1], req.url.includes('full=1'))\n if (segs[0] === 'images' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return this.replyMemoryImage(`${segs[1]}/${segs[2]}`)\n if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))\n return json(404, { error: `no route: GET ${path}`, usage: USAGE })\n }\n if (req.method === 'POST' && segs[0] === 'generate') {\n const target = this.resolveDraft(segs.slice(1))\n if ('error' in target) return json(target.status, { error: target.error })\n return await this.generate(target.mod, target.draft, req)\n }\n if (req.method === 'POST' && segs[0] === 'upload' && segs.length === 1) return this.replyUpload(req)\n if (req.method === 'PUT' && segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return await this.replySaveDraft(segs[1], segs[2], req)\n if (req.method === 'DELETE' && segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return await this.replyDeleteDraft(segs[1], segs[2])\n if (req.method === 'PUT' && segs[0] === 'settings' && segs.length === 1) return this.replySaveSettings(req)\n if (req.method === 'PUT' && segs[0] === 'hosts' && segs.length === 2 && segs[1] != null)\n return this.replySetHost(segs[1], req)\n if (req.method === 'POST' && segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return await this.replyHostAction(segs[1], segs[2])\n if (\n req.method === 'POST' &&\n segs[0] === 'hosts' &&\n segs.length === 4 &&\n segs[1] != null &&\n segs[2] === 'lora-civitai' &&\n segs[3] != null\n )\n return await this.replyLoraCivitaiFetch(segs[1], segs[3])\n if (req.method === 'PUT' && segs[0] === 'prompt-enhancers' && segs.length === 2 && segs[1] != null)\n return this.replySavePromptEnhancer(segs[1], req)\n if (req.method === 'DELETE' && segs[0] === 'prompt-enhancers' && segs.length === 2 && segs[1] != null)\n return this.replyDeletePromptEnhancer(segs[1])\n return json(404, { error: `no route: ${req.method} ${path}`, usage: USAGE })\n } catch (e) {\n console.error('[serve] request crashed:', e)\n return json(500, { error: extractErrorMessage(e) })\n }\n }\n\n moduleByKey(key: string): ServeModule | null {\n return this.modules.find((m) => m.key === key) ?? null\n }\n\n /** 'default' always exists (spec defaults); files under .comfy-ts/drafts/<module>/ add the rest */\n draftsFor(mod: ServeModule): string[] {\n const onDisk = listDraftsForFile(mod.file)\n return ['default', ...onDisk.filter((n) => n !== 'default')]\n }\n\n /** THE draft-name gate, shared by every route that turns a url segment into a path\n * (safeName.ts owns the rule, the prompt-enhancer routes call the same function) */\n private validDraftName(raw: string): string | null {\n return validStoreName(raw)\n }\n\n /** absolute path of a draft file, or null when the name is not one we accept */\n private draftPath(mod: ServeModule, draft: string): string | null {\n const name = this.validDraftName(draft)\n return name == null ? null : join(draftsDirForFile(mod.file), `${name}.json`)\n }\n\n private draftExists(mod: ServeModule, draft: string): boolean {\n const path = this.draftPath(mod, draft)\n if (path == null) return false\n return draft === 'default' || existsSync(path)\n }\n\n private resolveDraft(segs: string[]): { mod: ServeModule; draft: string } | { error: string; status: number } {\n if (segs.length === 2 && segs[0] != null && segs[1] != null) {\n const mod = this.moduleByKey(segs[0])\n if (mod == null)\n return {\n status: 404,\n error: `unknown module '${segs[0]}' — modules: ${this.modules.map((m) => m.key).join(', ')}`,\n }\n if (!this.draftExists(mod, segs[1]))\n return {\n status: 404,\n error: `module '${mod.key}' has no draft '${segs[1]}' — drafts: ${this.draftsFor(mod).join(', ')}`,\n }\n return { mod, draft: segs[1] }\n }\n if (segs.length === 1 && segs[0] != null) {\n const draft = segs[0]\n if (this.modules.length === 1 && this.modules[0] != null) {\n const mod = this.modules[0]\n if (!this.draftExists(mod, draft))\n return {\n status: 404,\n error: `no draft '${draft}' — drafts: ${this.draftsFor(mod).join(', ')}`,\n }\n return { mod, draft }\n }\n const hits = this.modules.filter((m) => this.draftExists(m, draft))\n if (hits.length === 1 && hits[0] != null) return { mod: hits[0], draft }\n if (hits.length === 0) return { status: 404, error: `no module has a draft '${draft}'` }\n return {\n status: 400,\n error: `draft '${draft}' is ambiguous — use: ${hits.map((m) => `/generate/${m.key}/${draft}`).join(' or ')}`,\n }\n }\n return { status: 400, error: 'use POST /generate/<module>/<draft> or /generate/<draft>' }\n }\n\n // #region introspection ----------------------------------------------------\n private describeModule(mod: ServeModule): Record<string, unknown> {\n refreshLoraInfoCacheIfChanged()\n const hostId = mod.dw.host.data.id\n const vars: Record<string, VarDescriptor> = {}\n for (const [name, varDef] of mod.dw.entries()) {\n const desc = describeVar(varDef)\n // the raw enum values stay the payload keys; the mirror's names are for humans\n if (desc.kind === 'loras' && desc.options != null) {\n const labels: Record<string, string> = {}\n for (const option of desc.options) {\n const label = getLoraDisplayName(option, hostId)\n if (label !== option) labels[option] = label\n }\n if (Object.keys(labels).length > 0) desc.optionLabels = labels\n // the UNION: a lora the manager mirror knows but ComfyUI's enum does not. It is on\n // disk, so it usually runs, the picker offers it, flagged, rather than hiding it\n // by normalized key, never raw: an enum value keeps its case, extension and\n // windows separators. the var's own regex narrows the mirror too\n const extras = managerOnlyLoraOptions({\n hostId,\n options: desc.options,\n filter: (varDef as LorasVar<string>).optionsFilter,\n })\n if (extras.length > 0) {\n desc.managerOnlyOptions = extras\n desc.options = [...desc.options, ...extras]\n for (const extra of extras) {\n const label = getLoraDisplayName(extra, hostId)\n if (label !== extra) (desc.optionLabels ??= {})[extra] = label\n }\n }\n // what a prompt with loraKeywordsFrom will PREPEND, per option: the panel shows\n // the injection instead of leaving you to discover it in the generated image\n const keywords: Record<string, string> = {}\n for (const option of desc.options) {\n const kw = getLoraKeyword(option, hostId)\n if (kw !== '') keywords[option] = kw\n }\n if (Object.keys(keywords).length > 0) desc.optionKeywords = keywords\n const addedAt: Record<string, number> = {}\n for (const option of desc.options) {\n const t = getLoraAddedAt(option, hostId)\n if (t != null) addedAt[option] = t\n }\n if (Object.keys(addedAt).length > 0) desc.optionAddedAt = addedAt\n const triggers: Record<string, LoraTriggers> = {}\n for (const option of desc.options) {\n const t = getLoraTriggers(option, hostId)\n if (t != null) triggers[option] = t\n }\n if (Object.keys(triggers).length > 0) desc.optionTriggers = triggers\n }\n vars[name] = desc\n }\n // a prompt knows its lora SOURCE by identity only; naming it needs both vars, which is\n // exactly what this loop has. Without it the panel cannot preview the keyword prefix\n for (const [name, varDef] of mod.dw.entries()) {\n if (varDef.kind !== 'prompt') continue\n const source = (varDef as PromptVar).promptOpts.loraKeywordsFrom\n if (source == null) continue\n // identity across two unrelated faces (AnyVar vs ActiveLoraSource): compare as unknown,\n // the LorasVar instance IS both\n const sourceName = mod.dw.entries().find(([, other]) => (other as unknown) === (source as unknown))?.[0]\n const desc = vars[name]\n if (sourceName != null && desc != null) desc.keywordsFrom = sourceName\n }\n return {\n module: mod.key,\n file: mod.file,\n host: mod.dw.host.data.id,\n drafts: this.draftsFor(mod),\n routes: this.draftsFor(mod).map(\n (d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`,\n ),\n vars,\n }\n }\n\n private replyIndex(): ServeReply {\n return json(200, {\n server: 'comfy-ts serve',\n usage: USAGE,\n workflows: this.modules.map((m) => this.describeModule(m)),\n ...(this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0\n ? { loadErrors: this.opts.loadErrors }\n : {}),\n })\n }\n\n private replyDraft(modKey: string, draft: string): ServeReply {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n if (!this.draftExists(mod, draft))\n return json(404, {\n error: `module '${modKey}' has no draft '${draft}' — drafts: ${this.draftsFor(mod).join(', ')}`,\n })\n return json(200, { ...this.describeModule(mod), draft, values: this.draftValues(mod, draft) })\n }\n\n /** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */\n private draftValues(mod: ServeModule, draft: string): Record<string, unknown> {\n const path = this.draftPath(mod, draft)\n if (path != null && existsSync(path)) return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default\n return out\n }\n\n // #region outputs ----------------------------------------------------------\n private replyOutput(segs: string[]): ServeReply {\n const abs = resolve(this.outputRoot, ...segs)\n // traversal guard: the resolved path must stay under the output root\n if (abs !== this.outputRoot && !abs.startsWith(this.outputRoot + '/'))\n return json(400, { error: 'path escapes the outputs root' })\n if (!existsSync(abs) || !statSync(abs).isFile())\n return json(404, { error: `no such output file: /${segs.join('/')}` })\n const contentType = CONTENT_TYPES[extname(abs).toLowerCase()] ?? 'application/octet-stream'\n return { status: 200, contentType, body: new Uint8Array(readFileSync(abs)) }\n }\n\n private async replyWebJs(): Promise<ServeReply> {\n if (this.opts.webJs == null) return json(404, { error: 'web ui not enabled on this server' })\n this.webJsCache ??= this.opts.webJs()\n const js = await this.webJsCache\n if (js == null) return json(404, { error: 'web ui bundle unavailable — see the server log' })\n return { status: 200, contentType: 'text/javascript; charset=utf-8', body: js, headers: NO_STORE }\n }\n\n /** browser file → local file an image var can point at (downloadInput family) */\n private replyUpload(req: ServeRequest): ServeReply {\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body ?? '')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n const o = (parsed ?? {}) as { name?: unknown; dataBase64?: unknown }\n if (typeof o.name !== 'string' || o.name === '' || typeof o.dataBase64 !== 'string' || o.dataBase64 === '')\n return json(400, { error: 'upload expects {\"name\":\"<filename>\",\"dataBase64\":\"<base64 bytes>\"}' })\n const bytes = Buffer.from(o.dataBase64, 'base64')\n if (bytes.length === 0) return json(400, { error: 'dataBase64 decoded to zero bytes' })\n // the same 100-char cap validStoreName carries: without it a long name reached the fs and\n // came back as a 500 quoting the absolute path\n const safe = (basename(o.name).replace(/[^\\w.-]+/g, '_') || 'upload').slice(0, 100)\n const abs = join(this.outputRoot, 'serve-inputs', `${nanoid(6)}-${safe}`)\n mkdirSync(dirname(abs), { recursive: true })\n writeFileSync(abs, bytes)\n console.log(`[serve] upload → ${abs} (${bytes.length} bytes)`)\n return json(200, { ok: true, path: abs, url: this.outputUrl(abs) })\n }\n\n // #region drafts write (the web ui's autosave + duplicate ride this) --------\n private async replySaveDraft(modKey: string, rawDraft: string, req: ServeRequest): Promise<ServeReply> {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n const draft = this.validDraftName(rawDraft)\n if (draft == null)\n return json(400, { error: `invalid draft name '${rawDraft}' — letters/digits then letters, digits, \". -_\"` })\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body ?? '')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))\n return json(400, { error: 'body must be a json object: { \"<var>\": value, … }' })\n const values = parsed as Record<string, unknown>\n const known = new Set(mod.dw.entries().map(([k]) => k))\n const unknown = Object.keys(values).filter((k) => !known.has(k))\n if (unknown.length > 0)\n return json(400, { error: `unknown var(s) ${unknown.join(', ')} — vars: ${[...known].join(', ')}` })\n // values are written VERBATIM (toJSON shapes, loadJSON re-validates on read) —\n // under the module mutex, so a save cannot interleave a generate's draft read\n const path = bang(this.draftPath(mod, draft), 'draft name validated just above')\n await this.exclusive(mod.key, () => {\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(values, null, 2))\n return Promise.resolve()\n })\n return json(200, { ok: true, module: mod.key, draft, drafts: this.draftsFor(mod) })\n }\n\n /** delete the draft FILE. `default` is deletable like any other: the implicit `default`\n * draft (spec values, no file) survives it, which is exactly the reset. Missing file is\n * still a 200, the caller asked for it to be gone, and it is */\n private async replyDeleteDraft(modKey: string, rawDraft: string): Promise<ServeReply> {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n const path = this.draftPath(mod, rawDraft)\n if (path == null) return json(400, { error: `invalid draft name '${rawDraft}'` })\n await this.exclusive(mod.key, () => {\n if (existsSync(path)) rmSync(path)\n return Promise.resolve()\n })\n console.log(`[serve] draft deleted: ${mod.key}/${rawDraft.trim()}`)\n return json(200, { ok: true, module: mod.key, draft: rawDraft.trim(), drafts: this.draftsFor(mod) })\n }\n\n // #region hosts (run a workflow somewhere else, the TUI's host override) ----\n /** every host this process registered: the modules' own, plus anything they created */\n private knownHosts(): { id: string; url: string; httpUrl: string; modules: string[] }[] {\n const byId = new Map<string, { id: string; url: string; httpUrl: string; modules: string[] }>()\n for (const [id, host] of comfyts.hosts)\n byId.set(id, {\n id,\n url: `${host.base.host}:${host.base.port}`,\n // the browser needs the REAL base to open the host's own pages (lora manager)\n httpUrl: host.getServerHostHTTP(),\n modules: [],\n })\n for (const mod of this.modules) {\n const entry = byId.get(mod.dw.host.data.id)\n if (entry != null) entry.modules.push(mod.key)\n }\n return [...byId.values()].sort((a, b) => a.id.localeCompare(b.id))\n }\n\n /** the host a run goes to: the override if it still exists, else the module's own.\n * A stale override (a host id that is gone) must never silently swallow the run */\n private runHostFor(mod: ServeModule): ComfyHost | null {\n const wanted = this.settings.hostOverride[mod.key]\n if (wanted == null || wanted === mod.dw.host.data.id) return null\n return comfyts.hosts.get(wanted) ?? null\n }\n\n /** the host actions the TUI's host panel has, minus re-codegen: regenerating the sdk\n * rewrites a .d.ts for your EDITOR, while the running modules keep the builder they were\n * imported with, a button that changes nothing in this process would be a lie */\n private async replyHostAction(hostId: string, action: string): Promise<ServeReply> {\n const host = comfyts.hosts.get(hostId)\n if (host == null)\n return json(404, { error: `unknown host '${hostId}' — known: ${[...comfyts.hosts.keys()].join(', ')}` })\n try {\n if (action === 'interrupt') {\n await host.interrupt()\n return json(200, { ok: true, host: hostId, action, note: 'interrupt requested' })\n }\n if (action === 'clear-queue') {\n await host.clearQueue()\n return json(200, { ok: true, host: hostId, action, note: 'pending prompts dropped' })\n }\n if (action === 'refresh-loras') return await this.refreshLoraMirror(hostId, host)\n if (action === 'refresh-schema') {\n await host.fetchAndUpdateSchema()\n // a lora var resolves its regex against the schema ONCE, at define time, so a\n // refetch alone left every var on the list it was born with and the panel kept\n // warning about a lora the host had just learned. rebinding re-runs that resolve\n const rebound = await this.rebindHostVars(hostId, host)\n const nodes = host.schema.nodes.length\n const loras = host.schema.getLoras().length\n const dropped =\n rebound.stale.length === 0\n ? ''\n : `. dropped ${rebound.stale.length} selection(s) this host no longer lists`\n return json(200, {\n ok: true,\n host: hostId,\n action,\n stale: rebound.stale,\n note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}. no restart needed`,\n })\n }\n if (action === 'restart') {\n // restartComfyUI already treats the mid-reboot disconnect as success, so what\n // reaches here is a host that REFUSED, swallowing it reported a reboot that\n // never happened, which is worse than saying nothing\n await host.manager.restartComfyUI()\n return json(200, { ok: true, host: hostId, action, note: 'reboot requested — it reconnects when back' })\n }\n return json(400, {\n error: `unknown host action '${action}' — interrupt | clear-queue | restart | refresh-loras | refresh-schema`,\n })\n } catch (e) {\n return json(502, { error: `host '${hostId}' refused '${action}': ${extractErrorMessage(e)}` })\n }\n }\n\n /** re-sweep ComfyUI-Lora-Manager and rewrite the mirror — what `comfy-ts loras` does, with\n * its refusals kept: a partial or unreachable sweep NEVER overwrites, because writing it\n * would delete loras from the mirror that are alive on the host */\n /** re-resolve the host-bound lora vars of the modules DEFINED on this host: LorasVar only\n * resolves its RegExp inside bindHost, so nothing else picks up a widened enum.\n *\n * the defining host, not the override: rebinding an overridden module against another box\n * rewrites its options AND its hostId (which picks the metadata mirror) with no way back,\n * since dropping the override cannot un-resolve them.\n *\n * runs under each module's mutex, so it cannot swap the options out from under a generate\n * that already validated its payload against the old list. */\n private async rebindHostVars(hostId: string, host: ComfyHost): Promise<{ widened: number; stale: string[] }> {\n let widened = 0\n const stale: string[] = []\n for (const mod of this.modules) {\n if (mod.dw.host.data.id !== hostId) continue\n await this.exclusive(mod.key, () => {\n for (const [name, varDef] of mod.dw.entries()) {\n if (varDef.kind !== 'loras') continue\n const lorasVar = varDef as LorasVar<string>\n if (lorasVar.optionsFilter == null) continue // a plain array never re-resolves\n const before = lorasVar.options.length\n lorasVar.bindHost(host)\n if (lorasVar.options.length !== before) widened++\n // a SELECTED lora the host no longer lists would still ride into the graph and\n // be refused there: it leaves the record, and the reply says which\n const known = new Set<string>(lorasVar.options)\n const value = lorasVar.value as Record<string, unknown>\n for (const picked of Object.keys(value)) {\n if (known.has(picked)) continue\n stale.push(`${mod.key}/${name}: ${picked}`)\n delete value[picked]\n }\n }\n return Promise.resolve()\n })\n }\n return { widened, stale }\n }\n\n private async refreshLoraMirror(hostId: string, host: ComfyHost): Promise<ServeReply> {\n const sweep = await fetchLoraList(host)\n if (sweep.status === 'absent')\n return json(400, {\n error: `${hostId} has no ComfyUI-Lora-Manager: the extension is not installed there. Mirror left untouched.`,\n })\n if (sweep.status === 'unreachable')\n return json(502, { error: `${hostId} unreachable — ${sweep.reason}. Mirror left untouched.` })\n if (sweep.status === 'partial')\n return json(502, {\n error: `the sweep broke off after ${sweep.items.length} loras (${sweep.reason}). Writing that would drop every lora past it, so the mirror is left untouched.`,\n })\n const mirror = buildLoraMirror({\n hostId,\n hostUrl: host.getServerHostHTTP(),\n fetchedAt: new Date().toISOString(),\n items: sweep.items,\n })\n writeLoraMirror(mirror)\n // the in-process cache reads the file by mtime, so every surface sees the new names\n reloadLoraInfoCache()\n console.log(`[serve] lora mirror refreshed for ${hostId}: ${mirror.count} loras`)\n return json(200, {\n ok: true,\n host: hostId,\n action: 'refresh-loras',\n count: mirror.count,\n note: `${mirror.count} loras synced`,\n })\n }\n\n /** fetch ONE lora's civitai metadata through the lora manager, then re-sync the mirror so its\n * trigger words reach every surface. The extension keys the request by the file path ON THE\n * HOST, which only the mirror knows, so a lora outside the mirror needs a sync first */\n private async replyLoraCivitaiFetch(hostId: string, lora: string): Promise<ServeReply> {\n const host = comfyts.hosts.get(hostId)\n if (host == null) return json(404, { error: `unknown host '${hostId}'` })\n const info = getLoraInfo(lora, hostId)\n const filePath = info == null ? null : lmFilePath(info)\n if (filePath == null)\n return json(404, { error: `'${lora}' is not in the lora manager mirror of ${hostId}: sync the mirror first` })\n const fetched = await fetchLoraCivitai(host, filePath)\n const sha256 = info == null ? null : lmSha256(info)\n // civitai ANSWERED that it has no version for this hash: a definite result, kept so the\n // card stops offering a fetch. Any other failure (network, the extension) stays an error\n if (!fetched.ok && /no version data found/i.test(fetched.reason) && sha256 != null) {\n recordCivitaiMiss({ hostId, sha256, miss: true })\n return json(200, {\n ok: true,\n host: hostId,\n lora,\n triggers: { state: 'not-on-civitai' },\n note: `civitai does not know '${lora}' (a private or local lora): no trigger words to fetch`,\n })\n }\n if (!fetched.ok) return json(502, { error: `civitai fetch failed for '${lora}': ${fetched.reason}` })\n if (sha256 != null) recordCivitaiMiss({ hostId, sha256, miss: false })\n const synced = await this.refreshLoraMirror(hostId, host)\n if (synced.status !== 200) return synced\n const t = getLoraTriggers(lora, hostId)\n const note =\n t?.state === 'words'\n ? `trigger words: ${t.words.join(', ')}`\n : t?.state === 'none'\n ? `civitai lists no trigger words for '${lora}'`\n : `civitai has no metadata for '${lora}'`\n return json(200, { ok: true, host: hostId, lora, triggers: t, note })\n }\n\n /** has the host changed since this process loaded its schema: new or removed model files (and\n * node types on a full check). A host whose catalog is COMMITTED rather than live-synced\n * (sdkAutoWrite: false, the cloud catalog) is not compared: its live list moves on purpose */\n private async replyHostDrift(hostId: string, full: boolean): Promise<ServeReply> {\n const host = comfyts.hosts.get(hostId)\n if (host == null) return json(404, { error: `unknown host '${hostId}'` })\n if (host.data.sdkAutoWrite === false)\n return json(200, { host: hostId, checked: false, changed: false, summary: '' })\n try {\n const drift = await host.checkSchemaDrift({ full })\n return json(200, {\n host: hostId,\n checked: true,\n full,\n changed: driftChanged(drift),\n summary: summarizeDrift(drift),\n drift,\n })\n } catch (e) {\n return json(502, { error: `${hostId} unreachable: ${extractErrorMessage(e)}` })\n }\n }\n\n /** is the host answering RIGHT NOW: what the panel polls while a restart is in flight, so\n * \"restarting…\" ends on a fact rather than on a guess */\n private async replyHostPing(hostId: string): Promise<ServeReply> {\n const host = comfyts.hosts.get(hostId)\n if (host == null) return json(404, { error: `unknown host '${hostId}'` })\n try {\n const res = await host.fetch('/system_stats', {})\n return json(200, { host: hostId, up: res.ok, status: res.status })\n } catch (e) {\n return json(200, { host: hostId, up: false, reason: extractErrorMessage(e) })\n }\n }\n\n /** the ComfyUI console, the TUI's logs panel over http — through the SAME assembly the TUI\n * uses (assembleLogChunks): entries are write CHUNKS, so lines are folded there, ANSI is\n * stripped, tqdm redraws collapse to their last state, and the cp1252 mojibake a windows\n * host emits is repaired. Re-implementing any of that here would drift from the TUI */\n private async replyHostLogs(hostId: string): Promise<ServeReply> {\n const host = comfyts.hosts.get(hostId)\n if (host == null) return json(404, { error: `unknown host '${hostId}'` })\n try {\n const raw = await host.fetchRawLogs()\n const lines: string[] = []\n const partial = assembleLogChunks({ lines, partial: '', entries: raw.entries })\n // the tail has no newline yet (a live progress bar): show it, it is the current state\n if (partial.trim() !== '') lines.push(partial)\n return json(200, { host: hostId, lines: lines.slice(-200) })\n } catch (e) {\n return json(502, { error: `could not read the logs of '${hostId}': ${extractErrorMessage(e)}` })\n }\n }\n\n private replyHosts(): ServeReply {\n return json(200, {\n hosts: this.knownHosts(),\n defaults: Object.fromEntries(this.modules.map((m) => [m.key, m.dw.host.data.id])),\n overrides: this.settings.hostOverride,\n })\n }\n\n private replySetHost(modKey: string, req: ServeRequest): ServeReply {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body ?? '')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n const wanted = parsed != null && typeof parsed === 'object' ? (parsed as { host?: unknown }).host : null\n if (wanted != null && typeof wanted !== 'string')\n return json(400, { error: 'body must be { \"host\": \"<host id>\" } or { \"host\": null } to reset' })\n const next = { ...this.settings.hostOverride }\n if (wanted == null || wanted === mod.dw.host.data.id) delete next[mod.key]\n else {\n if (!comfyts.hosts.has(wanted))\n return json(400, {\n error: `unknown host '${wanted}' — known: ${[...comfyts.hosts.keys()].join(', ')}`,\n })\n next[mod.key] = wanted\n }\n this.settings = { ...this.settings, hostOverride: next }\n try {\n writeServeSettings(this.settings)\n } catch (e) {\n return json(500, { error: `host applied for this session but not saved: ${extractErrorMessage(e)}` })\n }\n const target = next[mod.key] ?? mod.dw.host.data.id\n console.log(`[serve] ${mod.key} runs on ${target}${next[mod.key] != null ? ' (override)' : ''}`)\n return json(200, { ok: true, module: mod.key, host: target, overrides: this.settings.hostOverride })\n }\n\n // #region settings + in-memory outputs --------------------------------------\n /** the last N in-memory outputs stay reachable; older ones are dropped, because with\n * saving off these buffers are the only copy and nothing else will free them */\n private readonly MEMORY_IMAGE_CAP = 60\n\n private rememberMemoryImage(key: string, bytes: Uint8Array, filename: string): void {\n const contentType = CONTENT_TYPES[extname(filename).toLowerCase()] ?? sniffImageContentType(bytes)\n this.memoryImages.set(key, { bytes, contentType })\n while (this.memoryImages.size > this.MEMORY_IMAGE_CAP) {\n const oldest = this.memoryImages.keys().next()\n if (oldest.done === true) break\n this.memoryImages.delete(oldest.value)\n }\n }\n\n private replyMemoryImage(key: string): ServeReply {\n const hit = this.memoryImages.get(key)\n if (hit == null)\n return json(404, {\n error: `no in-memory image '${key}' — it expired (only the last ${this.MEMORY_IMAGE_CAP} are kept) or the server restarted. Turn saving on to keep outputs.`,\n })\n return { status: 200, contentType: hit.contentType, body: hit.bytes }\n }\n\n /** the subfolder under outputs/ a module's images land in. Falls back to the module key,\n * which is what every serve run used before the prefix was choosable */\n private savePrefixFor(modKey: string): string {\n const stored = this.settings.savePrefix[modKey]?.trim() ?? ''\n return stored === '' ? modKey : stored\n }\n\n private replySaveSettings(req: ServeRequest): ServeReply {\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body ?? '')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))\n return json(400, {\n error: 'body must be { \"saveToDisk\"?: true | false, \"savePrefix\"?: { \"<module>\": \"path\" } }',\n })\n const wanted = parsed as { saveToDisk?: unknown; savePrefix?: unknown }\n let next = this.settings\n if (wanted.saveToDisk != null) {\n if (typeof wanted.saveToDisk !== 'boolean') return json(400, { error: '\"saveToDisk\" must be true or false' })\n next = { ...next, saveToDisk: wanted.saveToDisk }\n }\n if (wanted.savePrefix != null) {\n if (typeof wanted.savePrefix !== 'object' || Array.isArray(wanted.savePrefix))\n return json(400, { error: '\"savePrefix\" must be { \"<module>\": \"path\" }' })\n const prefixes = { ...next.savePrefix }\n for (const [modKey, raw] of Object.entries(wanted.savePrefix as Record<string, unknown>)) {\n if (this.moduleByKey(modKey) == null) return json(404, { error: `unknown module '${modKey}'` })\n if (typeof raw !== 'string') return json(400, { error: `prefix for '${modKey}' must be a string` })\n const clean = validSavePrefix(raw)\n if (clean == null)\n return json(400, {\n error: `invalid prefix '${raw}' — folder names only, \"a/b\" allowed, no \"..\" and no absolute path`,\n })\n // empty means \"back to the default\", so the stored map keeps only real choices\n if (clean === '') delete prefixes[modKey]\n else prefixes[modKey] = clean\n }\n next = { ...next, savePrefix: prefixes }\n }\n const saveToDisk = next.saveToDisk\n this.settings = next\n try {\n writeServeSettings(this.settings)\n } catch (e) {\n // the live setting still applies; say the persistence failed rather than lying\n return json(500, { error: `setting applied for this session but not saved: ${extractErrorMessage(e)}` })\n }\n console.log(`[serve] outputs ${saveToDisk ? 'SAVE to disk' : 'stay in MEMORY'}`)\n return this.replySettings()\n }\n\n /** the stored settings PLUS the prefix each module actually uses, so the ui can show the\n * effective folder without re-deriving the fallback rule */\n private replySettings(): ServeReply {\n return json(200, {\n ...this.settings,\n effectivePrefix: Object.fromEntries(this.modules.map((m) => [m.key, this.savePrefixFor(m.key)])),\n })\n }\n\n // #region prompt enhancers (the web ui's master prompts, as .md files) ------\n /** the folder is seeded on the first read, so `refine-krea2-prompt.md` exists to be edited */\n private replyPromptEnhancers(): ServeReply {\n try {\n return json(200, { enhancers: listPromptEnhancers() })\n } catch (e) {\n return json(500, { error: `prompt-enhancers folder unreadable: ${extractErrorMessage(e)}` })\n }\n }\n\n private replySavePromptEnhancer(rawName: string, req: ServeRequest): ServeReply {\n const name = validStoreName(rawName)\n if (name == null)\n return json(400, { error: `invalid enhancer name '${rawName}' — letters/digits then letters, digits, \". -_\"` })\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body ?? '')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))\n return json(400, { error: 'body must be { \"text\": \"<master prompt>\" }' })\n const text = (parsed as Record<string, unknown>).text\n if (typeof text !== 'string') return json(400, { error: 'body must be { \"text\": \"<master prompt>\" }' })\n try {\n writePromptEnhancer(name, text)\n } catch (e) {\n return json(500, { error: `could not write enhancer '${name}': ${extractErrorMessage(e)}` })\n }\n return json(200, { ok: true, name, enhancers: listPromptEnhancers() })\n }\n\n private replyDeletePromptEnhancer(rawName: string): ServeReply {\n const name = validStoreName(rawName)\n if (name == null) return json(400, { error: `invalid enhancer name '${rawName}'` })\n try {\n deletePromptEnhancer(name)\n } catch (e) {\n return json(500, { error: `could not delete enhancer '${name}': ${extractErrorMessage(e)}` })\n }\n console.log(`[serve] prompt enhancer deleted: ${name}`)\n return json(200, { ok: true, name, enhancers: listPromptEnhancers() })\n }\n\n // #region live run state (web ui polling: progress + latent preview) --------\n private liveRuns = new Map<string, ServeExecution>()\n /** seq counts frames so the poller refetches only on a NEW one, not every tick */\n private latentPreviews = new Map<string, { bytes: Uint8Array; mime: string; seq: number }>()\n private latentSeq = 0\n /** promptId → module: `onLatentPreview` is ONE slot per host and two modules can share a\n * host, so frames are routed by the prompt they belong to, never by \"the last run started\" */\n private promptOwner = new Map<string, string>()\n private latentHosts = new Set<ComfyHost>()\n\n private runningModules(): string[] {\n return [...this.liveRuns.entries()]\n .filter(([, e]) => e.status !== 'Success' && e.status !== 'Failure')\n .map(([key]) => key)\n }\n\n /** one dispatcher per host, installed once and left in place (idempotent) */\n private wireLatents(host: ComfyHost): void {\n if (this.latentHosts.has(host)) return\n this.latentHosts.add(host)\n host.onLatentPreview = (p) => {\n const owner = p.promptID != null ? this.promptOwner.get(p.promptID) : undefined\n // an unattributable frame (no promptID yet, e.g. before start() returned) is only\n // safe to show when exactly ONE run is live; otherwise drop it rather than lie\n const running = this.runningModules()\n const key = owner ?? (running.length === 1 ? running[0] : undefined)\n if (key == null) return\n this.latentPreviews.set(key, { bytes: p.bytes, mime: p.mime, seq: ++this.latentSeq })\n }\n }\n\n private replyRunStatus(modKey: string): ServeReply {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n const exec = this.liveRuns.get(mod.key)\n const running = exec != null && exec.status !== 'Success' && exec.status !== 'Failure'\n return json(200, {\n running,\n status: exec?.status ?? 'idle',\n percent: running ? (exec.progressGlobal?.percent ?? null) : null,\n // the node and ITS counter: on a text graph this is the ONLY thing that moves, since\n // ComfyUI publishes no partial text (probed: 90 progress messages, then one `executed`)\n node: running ? (exec.progress?.nodeName ?? null) : null,\n // value/max ONLY: the raw ws progress message also carries prompt_id and node, and\n // echoing a whole wire message into our own api makes its extra fields look like ours\n nodeProgress:\n running && exec.progress?.nodeProgress != null\n ? { value: exec.progress.nodeProgress.value, max: exec.progress.nodeProgress.max }\n : null,\n // live text a node publishes WHILE it runs (send_progress_text): the only channel\n // on which a generator's partial answer can reach a client at all\n progressText: running ? (exec.progress?.progressText ?? null) : null,\n hasPreview: this.latentPreviews.has(mod.key),\n previewSeq: this.latentPreviews.get(mod.key)?.seq ?? null,\n })\n }\n\n private replyRunPreview(modKey: string): ServeReply {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n const preview = this.latentPreviews.get(mod.key)\n if (preview == null) return json(404, { error: 'no latent preview yet' })\n return {\n status: 200,\n contentType: preview.mime !== '' ? preview.mime : sniffImageContentType(preview.bytes),\n body: preview.bytes,\n }\n }\n\n // #region lora hover data ---------------------------------------------------\n private hostById(hostId: string): ComfyHost | null {\n return this.modules.map((m) => m.dw.host).find((h) => h.data.id === hostId) ?? null\n }\n\n private hostIds(): string {\n return [...new Set(this.modules.map((m) => m.dw.host.data.id))].join(', ')\n }\n\n /** mirror-backed text for the hover pane, no network */\n private replyLoraInfo(hostId: string, lora: string): ServeReply {\n if (this.hostById(hostId) == null)\n return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` })\n refreshLoraInfoCacheIfChanged()\n // everything the mirror holds that a human wants when they click a card. Read through the\n // lm* accessors, never off the raw json: the extension's field names are its business\n const item = getLoraInfo(lora, hostId)\n const civitai = item == null ? null : lmCivitai(item)\n return json(200, {\n name: lora,\n displayName: getLoraDisplayName(lora, hostId),\n triggerWords: getLoraTriggerWords(lora, hostId),\n known: item != null,\n baseModel: item == null ? null : lmBaseModel(item),\n folder: item == null ? null : lmFolder(item),\n filePath: item == null ? null : lmFilePath(item),\n fileSize: item == null ? null : lmFileSize(item),\n tags: item == null ? [] : lmTags(item),\n notes: item == null ? '' : lmNotes(item),\n civitaiUrl: civitai?.modelId == null ? null : `https://civitai.com/models/${civitai.modelId}`,\n civitaiVersion: civitai?.name ?? null,\n })\n }\n\n /** what the mirror does NOT hold: civitai's description and the example images, both live\n * from the extension. A SEPARATE route from /lora-info on purpose, that one is mirror-only\n * and instant, this one talks to the host and is fetched when a details panel opens */\n private async replyLoraAbout(hostId: string, lora: string): Promise<ServeReply> {\n const host = this.hostById(hostId)\n if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` })\n refreshLoraInfoCacheIfChanged()\n const item = getLoraInfo(lora, hostId)\n if (item == null) return json(200, { known: false, description: null, examples: [], examplesReason: null })\n const filePath = lmFilePath(item)\n const sha = lmSha256(item)\n const [description, examples] = await Promise.all([\n filePath == null ? Promise.resolve(null) : fetchLoraDescription(host, filePath),\n sha == null ? Promise.resolve({ files: [], reason: null }) : fetchLoraExampleImages(host, sha),\n ])\n return json(200, {\n known: true,\n description,\n examples: examples.files,\n examplesReason: examples.reason,\n })\n }\n\n /** preview url resolution misses per host, so an absent lora-manager costs ONE sweep, not one\n * per hover. An UNREACHABLE host evicts itself: the host coming back must not stay 404 forever */\n private previewSweeps = new Map<string, Promise<{ status: string; map: Map<string, string> | null }>>()\n\n private async replyLoraPreview(hostId: string, lora: string): Promise<ServeReply> {\n const host = this.hostById(hostId)\n if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` })\n refreshLoraInfoCacheIfChanged()\n let url = getLoraPreviewUrl(lora, hostId)\n if (url == null) {\n // the TUI's fallback: unsynced mirror (or a lora it never saw) → ask the live host once\n let sweep = this.previewSweeps.get(hostId)\n if (sweep == null) {\n sweep = fetchLoraList(host).then((r) => {\n if (r.status === 'unreachable') {\n this.previewSweeps.delete(hostId)\n return { status: r.status, map: null }\n }\n return { status: r.status, map: r.status === 'absent' ? null : loraPreviewMapFrom(r.items) }\n })\n this.previewSweeps.set(hostId, sweep)\n }\n const swept = await sweep\n url = swept.map?.get(loraKey(lora)) ?? null\n // each miss has its OWN cause (the LorasSt rule): the wrong advice sends the user hunting\n if (url == null && swept.status === 'unreachable')\n return json(404, { error: `host '${hostId}' is unreachable — no preview to fetch` })\n if (url == null && swept.status === 'absent')\n return json(404, { error: `lora-manager extension not detected on '${hostId}'` })\n }\n if (url == null)\n return json(404, { error: `no preview known for '${lora}' (run: comfy-ts loras --id ${hostId})` })\n const bytes = await fetchLoraPreviewBytes(host, url)\n // one 404 for two causes on purpose: unreachable host and no-image both mean \"nothing to show\"\n if (bytes == null)\n return json(404, { error: `no image preview for '${lora}' (host '${hostId}' unreachable, or not an image)` })\n return { status: 200, contentType: sniffImageContentType(bytes), body: bytes }\n }\n\n private outputUrl(absPath: string): string | null {\n if (!absPath.startsWith(this.outputRoot + '/')) return null\n const rel = absPath.slice(this.outputRoot.length + 1)\n return '/outputs/' + rel.split('/').map(encodeURIComponent).join('/')\n }\n\n // #region generate ---------------------------------------------------------\n private async generate(mod: ServeModule, draft: string, req: ServeRequest): Promise<ServeReply> {\n let payload: Record<string, unknown> = {}\n if (req.body != null && req.body.trim() !== '') {\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body)\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))\n return json(400, { error: 'body must be a json object: { \"<var>\": value, … }' })\n payload = parsed as Record<string, unknown>\n }\n\n const t0 = Date.now()\n const seeds: Record<string, number> = {}\n const started = await this.exclusive(mod.key, () => this.prepareAndStart(mod, draft, payload, seeds))\n if ('error' in started) return json(started.status, { error: started.error })\n\n const execution = started.execution\n this.liveRuns.set(mod.key, execution)\n this.promptOwner.set(execution.data.id, mod.key)\n console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`)\n try {\n await execution.done\n } finally {\n this.promptOwner.delete(execution.data.id)\n }\n const durationMs = Date.now() - t0\n\n if (execution.status === 'Failure') {\n console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms`)\n return json(500, {\n ok: false,\n module: mod.key,\n draft,\n promptId: execution.data.id,\n durationMs,\n error: execution.data.error ?? 'execution failed',\n })\n }\n\n const produced = [`${execution.images.length} image(s)`]\n if ((execution.texts ?? []).length > 0) produced.push(`${(execution.texts ?? []).length} text(s)`)\n console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1000).toFixed(1)}s · ${produced.join(' · ')}`)\n\n // saving off → the buffer is the only copy: keep it addressable so the gallery (and\n // curl) still get an image instead of a null url\n const memoryKeys = new Map<number, string>()\n for (const [ix, img] of execution.images.entries()) {\n if (img.absPath != null || img.buffer == null) continue\n const key = `${execution.data.id}/${ix}`\n this.rememberMemoryImage(key, img.buffer, img.filename)\n memoryKeys.set(ix, key)\n }\n\n // Accept: image/* → first image's bytes directly (curl -o, <img src>)\n const first = execution.images[0]\n if (req.accept?.includes('image/') && first != null) {\n if (first.absPath != null) {\n const contentType = CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? 'application/octet-stream'\n return { status: 200, contentType, body: new Uint8Array(readFileSync(first.absPath)) }\n }\n const inMemory = this.memoryImages.get(memoryKeys.get(0) ?? '')\n if (inMemory != null) return { status: 200, contentType: inMemory.contentType, body: inMemory.bytes }\n }\n\n return json(200, {\n ok: true,\n module: mod.key,\n draft,\n promptId: execution.data.id,\n durationMs,\n seeds,\n savedToDisk: this.settings.saveToDisk,\n texts: (execution.texts ?? []).map((t) => ({ nodeKey: t.nodeKey, text: t.text })),\n images: execution.images.map((img, ix) => ({\n filename: img.filename,\n url:\n img.absPath != null\n ? this.outputUrl(img.absPath)\n : memoryKeys.has(ix)\n ? // the KEY is raw (`<promptId>/<ix>`); the url encodes each segment, and\n // handle() decodes per segment, so the lookup gets the raw key back\n `/images/${(memoryKeys.get(ix) ?? '')\n .split('/')\n .map((seg) => encodeURIComponent(seg))\n .join('/')}`\n : null,\n absPath: img.absPath,\n })),\n })\n }\n\n /** everything that touches the module's SHARED vars, under the module mutex */\n private async prepareAndStart(\n mod: ServeModule,\n draft: string,\n payload: Record<string, unknown>,\n seeds: Record<string, number>,\n ): Promise<{ execution: ServeExecution } | { error: string; status: number }> {\n // 1. reset, then load the draft FRESH from disk (TUI edits between requests apply)\n for (const [, varDef] of mod.dw.entries()) varDef.reset()\n const draftPath = this.draftPath(mod, draft)\n if (draftPath == null) return { status: 404, error: `no draft '${draft}'` }\n if (existsSync(draftPath)) {\n try {\n const values = JSON.parse(readFileSync(draftPath, 'utf8')) as Record<string, unknown>\n for (const [k, varDef] of mod.dw.entries()) if (k in values) varDef.loadJSON(values[k])\n } catch (e) {\n return { status: 500, error: `draft file unreadable: ${draftPath} — ${extractErrorMessage(e)}` }\n }\n }\n\n // the DRAFT's seed values, before payload overrides: the +/- continuation\n // compares against what the draft file says, not what a payload injected\n const draftSeedValues = new Map<string, number>()\n for (const [k, varDef] of mod.dw.entries())\n if (varDef.kind === 'seed') draftSeedValues.set(k, (varDef as SeedVar).value)\n\n // 2. payload overrides (image urls download first, so the var gets a local path)\n const varMap = new Map(mod.dw.entries())\n for (const [k, rawValue] of Object.entries(payload)) {\n const varDef = varMap.get(k)\n if (varDef == null)\n return { status: 400, error: `unknown var '${k}' — vars: ${[...varMap.keys()].join(', ')}` }\n let value = rawValue\n // kind, never instanceof: consumer and cli hold different class copies (VarKind\n // owns the WHY); casts are the kind-narrowing family, agent/coding.md whitelist 6\n if (varDef.kind === 'image' && typeof rawValue === 'string' && /^https?:\\/\\//.test(rawValue)) {\n try {\n value = await this.downloadInput(rawValue)\n } catch (e) {\n return { status: 400, error: `var '${k}': ${extractErrorMessage(e)}` }\n }\n }\n // a lora the mirror knows but the enum does not is a legal choice here too, else the\n // picker would offer something the api then refuses\n const err = applyVarPayload(varDef, value, {\n // narrowed by the var's OWN filter, exactly like the picker: what the ui offers and\n // what the api accepts must be the same set, or one of them is lying\n // the SAME function the picker used: it derives the separator from this var's own\n // enum, so a backslash host cannot be offered `a/b` and then refused it\n extraLoraOptions:\n varDef.kind === 'loras'\n ? managerOnlyLoraOptions({\n hostId: mod.dw.host.data.id,\n options: (varDef as LorasVar<string>).options,\n filter: (varDef as LorasVar<string>).optionsFilter,\n })\n : undefined,\n })\n if (err != null) return { status: 400, error: err }\n }\n\n // 3. image vars must point at a real FILE of a declared type BEFORE anything is queued.\n // the path a request hands us is read off this box and uploaded to the ComfyUI host, so\n // the extension list the descriptor advertises is enforced here, not merely advertised:\n // a var that accepts .png must not be talked into reading a key or a config file\n for (const [k, varDef] of varMap) {\n if (varDef.kind !== 'image') continue\n const img = varDef as ImageVar\n if (!img.isSet()) continue\n const abs = img.absPath()\n // ONE message for every rejection below: distinct ones told an unauthenticated caller\n // whether any path exists, is a file, and what type it is\n const refuse = { status: 400, error: `image var '${k}': not a usable image file` }\n if (!existsSync(abs)) return refuse\n // the REAL path: statSync follows symlinks, so `pic.png -> id_rsa` passed a check made\n // on the link's name. Resolving first means the gate judges the file being read\n let real: string\n try {\n real = realpathSync(abs)\n } catch {\n return refuse\n }\n try {\n if (!statSync(real).isFile()) return refuse\n } catch {\n return refuse\n }\n if (!serveAcceptsImageExt(img.extensions, extname(real).toLowerCase().replace(/^\\./, ''))) return refuse\n if (!looksLikeImage(real)) return refuse\n }\n\n // 4. seed policy (architecture item 12): payload wins; '?' rerolls;\n // '+'/'-' continue from the last SERVED value; '=' keeps the draft value\n for (const [k, varDef] of varMap) {\n if (varDef.kind !== 'seed') continue\n const seedVar = varDef as SeedVar\n const stateKey = `${mod.key}/${draft}/${k}`\n const draftValue = draftSeedValues.get(k) ?? seedVar.value\n if (!(k in payload)) {\n if (seedVar.mode === '?') seedVar.randomize()\n else if (seedVar.mode === '+' || seedVar.mode === '-') {\n const prev = this.seedState.get(stateKey)\n // the draft holding the value we last SERVED is our own write-back, not the\n // human edit draftBase watches for\n const ours = prev != null && (prev.draftBase === draftValue || prev.last === draftValue)\n if (prev != null && ours) seedVar.set(prev.last + (seedVar.mode === '+' ? 1 : -1))\n }\n }\n this.seedState.set(stateKey, { last: seedVar.value, draftBase: draftValue })\n seeds[k] = seedVar.value\n }\n\n // 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex.\n // latent frames feed the web ui's /run/<module>/preview poll (ExecSt's pattern);\n // the previous run's preview must not linger over the new one\n this.latentPreviews.delete(mod.key)\n // the host the run ACTUALLY goes to: onLatentPreview is one slot per ComfyHost, so\n // wiring the defining host while running on an override left the override host with no\n // dispatcher, the panel simply never saw a frame, with nothing to say why\n const runHost = this.runHostFor(mod)\n this.wireLatents(runHost ?? mod.dw.host)\n try {\n return {\n execution: await this.starter(mod, {\n saveToDisk: this.settings.saveToDisk,\n savePrefix: this.savePrefixFor(mod.key),\n host: runHost ?? undefined,\n }),\n }\n } catch (e) {\n // name, not instanceof: same two-copies problem as the var classes\n if (e instanceof Error && e.name === 'ImageVarEmptyError') return { status: 400, error: e.message }\n // the ComfyUI host is upstream of this bridge: 502, not \"serve crashed\".\n // The connect deadline (ConnectOptions.timeoutMs) is what makes this\n // this runs inside the module mutex: a url that never answers would hold it\n if (e instanceof Error && e.name === 'ComfyHostUnreachableError') return { status: 502, error: e.message }\n return { status: 500, error: extractErrorMessage(e) }\n }\n }\n\n /** serialize fn per module key; the stored chain never rejects */\n private exclusive<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = this.chains.get(key) ?? Promise.resolve()\n const next = prev.then(fn)\n this.chains.set(\n key,\n next.catch(() => {}),\n )\n return next\n }\n\n /** payload image urls land as local files under outputs/serve-inputs/ */\n private async downloadInput(url: string): Promise<string> {\n // every failure below answers the SAME thing. Refused, DNS miss, 403 and 200-of-the-wrong\n // -type were four distinguishable replies, which is a port and host scanner for anything\n // this box can reach. The reason goes to the server log\n try {\n return await this.fetchInput(url)\n } catch (e) {\n if (!(e instanceof DownloadRefused)) console.error(`[serve] input download failed: ${url}:`, e)\n throw new DownloadRefused(url)\n }\n }\n\n private async fetchInput(url: string): Promise<string> {\n // a timeout, because this runs INSIDE the module mutex: a url that accepts the connection\n // and then trickles would wedge that workflow's queue for as long as it liked\n const res = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(INPUT_DOWNLOAD_TIMEOUT_MS) })\n // the upstream STATUS is not reported back: reflecting it turns an image var into a port\n // and route scanner for everything this box can reach (loopback, tailnet, metadata\n // endpoints). The caller learns the fetch failed, not what answered\n if (!res.ok) {\n console.error(`[serve] input download failed (http ${res.status}): ${url}`)\n throw new DownloadRefused(url)\n }\n const declared = Number(res.headers.get('content-length') ?? '0')\n if (declared > INPUT_DOWNLOAD_CAP) throw new Error(`download too large (${declared} bytes): ${url}`)\n const bytes = await readCapped(res, INPUT_DOWNLOAD_CAP, url)\n const name = basename(new URL(url).pathname) || 'input'\n const abs = join(this.outputRoot, 'serve-inputs', `${nanoid(6)}-${name}`)\n mkdirSync(dirname(abs), { recursive: true })\n writeFileSync(abs, bytes)\n return abs\n }\n}\n","// what `comfy-ts serve` prints on launch. PURE: takes the already-described\n// modules and gives back lines, so tests read the layout without a server and\n// without a tty. Colors are a parameter, never a probe done in here.\nimport { ansi, stripAnsi } from 'src/utils/ansi.ts'\n\nexport type StartupModule = {\n key: string\n hostId: string\n /** the POST routes, ready to print */\n routes: string[]\n /** one line per var (renderDescriptorLine) */\n varLines: string[]\n}\n\nexport type StartupInput = {\n modules: StartupModule[]\n bind: string\n port: number\n /** every address this bind answers on (reachableAddresses) */\n urls: string[]\n color: boolean\n}\n\nconst RULE_WIDTH = 64\n\n/** 100.64.0.0/10 is the CGNAT range tailscale hands out — worth naming, it is the one\n * you want when the phone is not on the same wifi */\nexport function addressNote(addr: string): string {\n const octets = addr.split('.').map(Number)\n const second = octets[1] ?? 0\n if (octets[0] === 100 && second >= 64 && second <= 127) return 'tailnet'\n if (addr === '127.0.0.1' || addr === 'localhost') return 'this machine'\n return ''\n}\n\nfunction paint(color: boolean): {\n title: (s: string) => string\n name: (s: string) => string\n dim: (s: string) => string\n url: (s: string) => string\n warn: (s: string) => string\n} {\n const id = (s: string): string => s\n if (!color) return { title: id, name: id, dim: id, url: id, warn: id }\n return {\n title: (s) => ansi.bold(s),\n name: (s) => ansi.bold.cyan(s),\n dim: (s) => ansi.gray(s),\n url: (s) => ansi.green(s),\n warn: (s) => ansi.yellow(s),\n }\n}\n\n/** a box that stays square whatever the colors do: padding measures the VISIBLE text */\nexport function boxed(lines: string[], p: { color: boolean } = { color: false }): string[] {\n const width = Math.max(...lines.map((l) => stripAnsi(l).length), 0)\n const edge = (l: string, r: string): string => `${l}${'─'.repeat(width + 2)}${r}`\n const border = (s: string): string => (p.color ? ansi.gray(s) : s)\n return [\n border(edge('┌', '┐')),\n ...lines.map((l) => `${border('│')} ${l}${' '.repeat(width - stripAnsi(l).length)} ${border('│')}`),\n border(edge('└', '┘')),\n ]\n}\n\nexport function renderStartupLines(p: StartupInput): string[] {\n const c = paint(p.color)\n const loopback = p.bind === '127.0.0.1' || p.bind === 'localhost' || p.bind === '::1'\n const primary = `http://${p.urls[0] ?? p.bind}:${p.port}/`\n const out: string[] = []\n\n const count = `${p.modules.length} workflow${p.modules.length === 1 ? '' : 's'}`\n out.push(c.title(`comfy-ts serve · ${count} · ${primary}`))\n // said on EVERY launch, loopback included: cross-origin is open, so the exposure is not\n // limited to who can reach the port. any page in your browser can reach 127.0.0.1 too\n out.push(\n c.warn(\n loopback\n ? '⚠️ no auth: this API runs workflows, and any page open in your browser can call it'\n : `⚠️ bound to ${p.bind}, no auth: anyone on this network can run workflows on your ComfyUI host`,\n ),\n )\n\n for (const mod of p.modules) {\n out.push('', c.dim('─'.repeat(RULE_WIDTH)))\n out.push(`${c.name(mod.key)} ${c.dim(`host: ${mod.hostId}`)}`)\n for (const route of mod.routes) out.push(c.dim(` POST ${route}`))\n out.push(...mod.varLines)\n }\n out.push(c.dim('─'.repeat(RULE_WIDTH)), '')\n\n // the box is the last thing on screen: where the ui is, and how to reach it elsewhere\n const box: string[] = [\n `${c.title('web ui')} ${c.url(primary)}`,\n `${c.dim('json api')} ${c.dim(`${primary}drafts`)}`,\n ]\n if (p.urls.length > 1) {\n box.push('', c.dim('also reachable at:'))\n for (const url of p.urls.slice(1)) {\n const note = addressNote(url)\n box.push(` ${c.url(`http://${url}:${p.port}/`)}${note === '' ? '' : c.dim(` (${note})`)}`)\n }\n }\n if (loopback) {\n box.push('', c.dim('to open it from your phone or another machine:'))\n box.push(c.dim(` comfy-ts serve --host 0.0.0.0 (--bind is the same flag)`))\n box.push(c.dim(' every reachable url gets printed here, tailnet included'))\n }\n out.push(...boxed(box, { color: p.color }))\n return out\n}\n","// web ui bundle resolution (architecture item 12, web ui): prebuilt\n// dist/serve-web.js next to the running module, else an in-memory Bun.build\n// from source (src/ ships in the npm tarball), else null — the api must serve\n// without a UI, never crash\nimport { existsSync, readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, join } from 'pathe'\n\nconst WEB_ENTRY = 'src/cli/serve/web/main.tsx'\n\n/** nearest dir upward holding a package.json — the comfy-ts package root, from dist/ and src/ alike */\nfunction packageRoot(fromDir: string): string | null {\n let dir = fromDir\n while (true) {\n if (existsSync(join(dir, 'package.json'))) return dir\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/** bundle the web app to one browser file. Bun.build reads no tsconfig, so the\n * house 'src/...' absolute imports resolve through the same plugin shape as\n * tests/web-bundle.test.ts */\nexport async function buildWebJsText(pkgRoot: string): Promise<string> {\n const result = await Bun.build({\n entrypoints: [join(pkgRoot, WEB_ENTRY)],\n target: 'browser',\n minify: true,\n throw: false,\n define: { 'process.env.NODE_ENV': '\"production\"' },\n plugins: [\n {\n name: 'repo-src-paths',\n setup(build) {\n build.onResolve({ filter: /^src\\// }, (args) => ({ path: join(pkgRoot, args.path) }))\n },\n },\n ],\n })\n if (!result.success || result.outputs[0] == null)\n throw new Error(`web ui bundle failed:\\n${result.logs.map((l) => String(l)).join('\\n')}`)\n return await result.outputs[0].text()\n}\n\n/** the runtime resolution chain; every miss logs loud and degrades to api-only */\nexport async function loadOrBuildWebJs(): Promise<string | null> {\n const here = dirname(fileURLToPath(import.meta.url))\n const prebuilt = join(here, 'serve-web.js')\n if (existsSync(prebuilt)) return readFileSync(prebuilt, 'utf8')\n if (typeof Bun === 'undefined') {\n console.error('[serve] 🔴 no serve-web.js next to the cli and not running under bun — api only, no web ui')\n return null\n }\n const pkgRoot = packageRoot(here)\n if (pkgRoot == null || !existsSync(join(pkgRoot, WEB_ENTRY))) {\n console.error(`[serve] 🔴 web ui source not found (looked for ${WEB_ENTRY} above ${here}) — api only, no web ui`)\n return null\n }\n try {\n return await buildWebJsText(pkgRoot)\n } catch (e) {\n console.error('[serve] 🔴 web ui bundle failed — api only:', e)\n return null\n }\n}\n","// `comfy-ts serve [dir | module.cflow.ts] [--port N] [--host ADDR]`\n// drafts as a local HTTP generation API — agent/architecture.md item 12\nimport { statSync } from 'node:fs'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport { networkInterfaces } from 'node:os'\nimport { pathToFileURL } from 'node:url'\nimport { resolve } from 'pathe'\nimport { scanCflowFiles } from 'src/cli/tui/discoverWorkflows.ts'\nimport { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'\nimport { draftKeyForFile } from 'src/cli/tui/state/DraftsSt.ts'\nimport { describeVar, renderDescriptorLine } from 'src/cli/serve/describeVar.ts'\nimport { ServeApp, type ServeModule } from 'src/cli/serve/ServeApp.ts'\nimport { renderStartupLines } from 'src/cli/serve/startupPrint.ts'\nimport { loadOrBuildWebJs } from 'src/cli/serve/webBundle.ts'\nimport { colorsAvailable } from 'src/utils/ansi.ts'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\n\nconst DEFAULT_PORT = 8288\nconst BODY_CAP = 10_000_000\n\nexport function parseArgs(args: string[]): { target?: string; port: number; bind: string } | { error: string } {\n let target: string | undefined\n let port = DEFAULT_PORT\n let bind = '127.0.0.1'\n for (let i = 0; i < args.length; i++) {\n const a = args[i]\n if (a === '--port') {\n const n = Number(args[++i])\n if (!Number.isInteger(n) || n <= 0 || n > 65535) return { error: `--port expects 1..65535, got '${args[i]}'` }\n port = n\n } else if (a === '--host' || a === '--bind') {\n // --host is the spelling; --bind stays an alias so an old command line keeps working\n const b = args[++i]\n if (b == null) return { error: `${a} expects an address (0.0.0.0 to reach it from another machine)` }\n bind = b\n } else if (a != null && a.startsWith('--')) return { error: `unknown flag '${a}'` }\n else if (a != null) {\n if (target != null) return { error: `one target only (got '${target}' and '${a}')` }\n target = a\n }\n }\n return { target, port, bind }\n}\n\n/** node:http glue around ServeApp.handle — exported so tests can drive a real socket */\n/** open CORS, because a browser page IS a first-class client here: the web entry runs the\n * library in a tab and rides serve as its bridge to hosts that send no CORS headers\n * (examples/web is on another port by construction). The cost is real and stated at launch:\n * with no auth, any page you visit can drive this api. That is the same trade as the port\n * being open at all, so it is said out loud rather than hidden behind a flag. */\nexport function makeRequestListener(app: ServeApp): (req: IncomingMessage, res: ServerResponse) => void {\n const cors = {\n 'access-control-allow-origin': '*',\n 'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'access-control-allow-headers': 'content-type, accept',\n }\n return (req, res) => {\n const chunks: Buffer[] = []\n let size = 0\n let overflow = false\n req.on('error', (e) => console.error(`[serve] request stream error: ${extractErrorMessage(e)}`))\n req.on('data', (c: Buffer) => {\n if (overflow) return\n size += c.length\n if (size > BODY_CAP) {\n // answer NOW: a destroyed request never emits 'end'\n overflow = true\n res.writeHead(413, { 'content-type': 'application/json', ...cors })\n res.end(JSON.stringify({ error: 'payload too large' }), () => req.destroy())\n } else chunks.push(c)\n })\n req.on('end', () => {\n if (overflow) return\n if (req.method === 'OPTIONS') {\n res.writeHead(204, cors)\n res.end()\n return\n }\n app.handle({\n method: req.method ?? 'GET',\n url: req.url ?? '/',\n accept: req.headers.accept,\n body: Buffer.concat(chunks).toString('utf8'),\n })\n .then((reply) => {\n res.writeHead(reply.status, { 'content-type': reply.contentType, ...reply.headers, ...cors })\n res.end(reply.body)\n })\n .catch((e: unknown) => {\n // handle() catches internally; this guards the response write itself\n console.error(`[serve] response write failed: ${extractErrorMessage(e)}`)\n res.destroy()\n })\n })\n }\n}\n\nexport async function runServe(args: string[]): Promise<number> {\n const parsed = parseArgs(args)\n if ('error' in parsed) {\n console.error(`[comfy-ts serve] ${parsed.error}`)\n return 1\n }\n\n // discovery: explicit file → that module only; dir/no-arg → scan, WITHOUT\n // the bundled examples (serve is for the user's tuned drafts)\n const target = resolve(parsed.target ?? '.')\n let files: string[]\n try {\n files = statSync(target).isDirectory() ? scanCflowFiles(target) : [target]\n } catch {\n console.error(`[comfy-ts serve] no such file or directory: ${target}`)\n return 1\n }\n if (files.length === 0) {\n console.error(`[comfy-ts serve] no *.cflow.ts modules under ${target}`)\n return 1\n }\n\n const modules: ServeModule[] = []\n const loadErrors: Record<string, string> = {}\n for (const file of files) {\n try {\n const mod: Record<string, unknown> = await import(pathToFileURL(file).href)\n const dw = findDefinedWorkflow(mod)\n if (dw == null) throw new Error('exports no DefinedWorkflow')\n const key = draftKeyForFile(file)\n const clash = modules.find((m) => m.key === key)\n if (clash != null) throw new Error(`module key '${key}' already taken by ${clash.file}`)\n modules.push({ key, file, dw })\n } catch (e) {\n loadErrors[file] = extractErrorMessage(e)\n console.error(`[comfy-ts serve] ✗ ${file}: ${loadErrors[file]}`)\n }\n }\n if (modules.length === 0) {\n console.error('[comfy-ts serve] every module failed to load — nothing to serve')\n return 1\n }\n\n const app = new ServeApp(modules, { loadErrors, webJs: loadOrBuildWebJs })\n printStartup(app, parsed.bind, parsed.port)\n\n const server = createServer(makeRequestListener(app))\n\n server.on('error', (e) => {\n console.error(`[comfy-ts serve] server error: ${extractErrorMessage(e)}`)\n process.exitCode = 1\n server.close()\n })\n server.listen(parsed.port, parsed.bind)\n\n // stays up until the process is interrupted or the server dies\n return new Promise<number>((resolveExit) => {\n server.on('close', () => resolveExit(typeof process.exitCode === 'number' ? process.exitCode : 0))\n })\n}\n\nexport type Nic = { address: string; family: string | number; internal: boolean }\n\n/** the addresses this bind actually answers on. `0.0.0.0` means every interface, so printing\n * only that back is useless: the LAN ip and the tailnet 100.x are the urls a phone can open */\nexport function reachableAddresses(bind: string, nics: Record<string, Nic[] | undefined>): string[] {\n if (bind !== '0.0.0.0' && bind !== '::') return [bind]\n const found: string[] = []\n for (const list of Object.values(nics)) {\n for (const nic of list ?? []) {\n // node reports family as 'IPv4' or 4 depending on the version\n if (nic.internal || (nic.family !== 'IPv4' && nic.family !== 4)) continue\n found.push(nic.address)\n }\n }\n return ['127.0.0.1', ...found]\n}\n\nfunction printStartup(app: ServeApp, bind: string, port: number): void {\n const base = `http://${bind}:${port}`\n const color = colorsAvailable()\n const lines = renderStartupLines({\n bind,\n port,\n urls: reachableAddresses(bind, networkInterfaces()),\n color,\n modules: app.modules.map((mod) => {\n const entries = mod.dw.entries()\n const nameWidth = Math.max(...entries.map(([n]) => n.length), 4)\n return {\n key: mod.key,\n hostId: mod.dw.host.data.id,\n routes: app\n .draftsFor(mod)\n .map((d) => `${base}/generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),\n varLines: entries.map(([name, varDef]) =>\n renderDescriptorLine(name, describeVar(varDef), nameWidth, color),\n ),\n }\n }),\n })\n for (const line of lines) console.log(line)\n}\n"],"mappings":";;;;;;;;;;AA8DA,SAAS,mBAAmB,SAA+C;CACxE,OAAO,QAAQ,WAAW,IAAI,KAAA,IAAY;AAC7C;AAEA,SAAS,UAAU,MAA8C;CAC9D,IAAI,KAAK,OAAO,QAAQ,KAAK,OAAO,MAAM,OAAO;CACjD,OAAO,KAAK,KAAK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