comfy-ts 2.10.0 → 2.12.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 (110) hide show
  1. package/README.md +1 -0
  2. package/dist/{LogsSt-DFxzQfDc.js → LogsSt-U1H0mP1m.js} +35 -5
  3. package/dist/LogsSt-U1H0mP1m.js.map +1 -0
  4. package/dist/cli.js +4 -4
  5. package/dist/index.cjs +565 -62
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +210 -31
  8. package/dist/index.d.ts +210 -31
  9. package/dist/index.js +561 -63
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-serve-_nrvJYyt.js → run-serve-BeAznay5.js} +549 -43
  12. package/dist/run-serve-BeAznay5.js.map +1 -0
  13. package/dist/{run-tui-Atvf9vb3.js → run-tui-BTGjvnKk.js} +75 -18
  14. package/dist/run-tui-BTGjvnKk.js.map +1 -0
  15. package/dist/{DefinedWorkflow-BatWaZO1.js → schemaDrift-Cg39vs53.js} +644 -60
  16. package/dist/schemaDrift-Cg39vs53.js.map +1 -0
  17. package/dist/serve-web.js +523 -133
  18. package/dist/{state-6RFDIQwJ.js → state-C7REnHan.js} +18 -3
  19. package/dist/{state-6RFDIQwJ.js.map → state-C7REnHan.js.map} +1 -1
  20. package/dist/web.d.ts +210 -31
  21. package/dist/web.js +561 -63
  22. package/dist/web.js.map +1 -1
  23. package/examples/comfy-cloud/capybara-i2v.cflow.ts +2 -0
  24. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +2 -0
  25. package/examples/comfy-cloud/wan22-i2v.cflow.ts +2 -0
  26. package/examples/comfy-cloud/wan22-t2v.cflow.ts +2 -0
  27. package/examples/rvion/06-qwen-image-edit.cflow.ts +3 -2
  28. package/examples/rvion/07-local-llm-text-gen.cflow.ts +2 -2
  29. package/examples/rvion/10-anima-t2i.cflow.ts +229 -0
  30. package/extra/README.md +4 -0
  31. package/extra/comfyui-fresh-model-lists/README.md +25 -0
  32. package/extra/comfyui-fresh-model-lists/__init__.py +36 -0
  33. package/extra/comfyui-fresh-model-lists/test_fresh_model_lists.py +97 -0
  34. package/package.json +17 -7
  35. package/src/cli/draftMeta.ts +39 -0
  36. package/src/cli/serve/ServeApp.ts +242 -12
  37. package/src/cli/serve/applyVarPayload.ts +50 -22
  38. package/src/cli/serve/describeVar.ts +49 -6
  39. package/src/cli/serve/favicon.ts +3 -0
  40. package/src/cli/serve/llmConfigShape.ts +51 -0
  41. package/src/cli/serve/llmConfigs.ts +52 -0
  42. package/src/cli/serve/tagList.ts +92 -0
  43. package/src/cli/serve/tagSource.ts +69 -0
  44. package/src/cli/serve/web/api.ts +60 -0
  45. package/src/cli/serve/web/components/App.tsx +336 -44
  46. package/src/cli/serve/web/components/Gallery.tsx +105 -28
  47. package/src/cli/serve/web/components/HistoryPicker.tsx +149 -0
  48. package/src/cli/serve/web/components/Icon.tsx +18 -2
  49. package/src/cli/serve/web/components/MenuButton.tsx +53 -0
  50. package/src/cli/serve/web/components/Omnibox.tsx +85 -0
  51. package/src/cli/serve/web/components/PromptEnhancer.tsx +476 -180
  52. package/src/cli/serve/web/components/TooltipLayer.tsx +45 -0
  53. package/src/cli/serve/web/components/VarIcon.tsx +24 -0
  54. package/src/cli/serve/web/components/VarsForm.tsx +341 -177
  55. package/src/cli/serve/web/components/controls/BasicControls.tsx +57 -32
  56. package/src/cli/serve/web/components/controls/LorasControl.tsx +708 -285
  57. package/src/cli/serve/web/components/controls/PresetPicker.tsx +1 -1
  58. package/src/cli/serve/web/components/controls/PromptControl.tsx +279 -0
  59. package/src/cli/serve/web/components/controls/PromptEditor.tsx +113 -0
  60. package/src/cli/serve/web/components/controls/SeedControl.tsx +17 -10
  61. package/src/cli/serve/web/components/controls/SizeControl.tsx +111 -18
  62. package/src/cli/serve/web/components/modKey.ts +2 -0
  63. package/src/cli/serve/web/llm.ts +23 -12
  64. package/src/cli/serve/web/promptEditor/promptExtensions.ts +281 -0
  65. package/src/cli/serve/web/state/EnhancerSt.ts +415 -100
  66. package/src/cli/serve/web/state/FormSt.ts +193 -29
  67. package/src/cli/serve/web/state/OmniboxSt.ts +57 -0
  68. package/src/cli/serve/web/state/WebSt.ts +281 -57
  69. package/src/cli/serve/web/state/choiceButtons.ts +61 -0
  70. package/src/cli/serve/web/state/generateButton.ts +16 -0
  71. package/src/cli/serve/web/state/history.ts +54 -0
  72. package/src/cli/serve/web/state/host.ts +5 -2
  73. package/src/cli/serve/web/state/keptLines.ts +53 -0
  74. package/src/cli/serve/web/state/latentMode.ts +20 -0
  75. package/src/cli/serve/web/state/loraSort.ts +57 -0
  76. package/src/cli/serve/web/state/moduleTree.ts +2 -2
  77. package/src/cli/serve/web/state/omnibox.ts +69 -0
  78. package/src/cli/serve/web/state/payload.ts +38 -58
  79. package/src/cli/serve/web/state/shortcuts.ts +54 -0
  80. package/src/cli/serve/web/state/sizeStars.ts +31 -0
  81. package/src/cli/serve/web/state/stableSlots.ts +21 -0
  82. package/src/cli/serve/web/state/varGroups.ts +24 -0
  83. package/src/cli/serve/web/styles.ts +472 -118
  84. package/src/cli/serve/webBundle.ts +54 -10
  85. package/src/cli/tui/components/Header.tsx +2 -0
  86. package/src/cli/tui/components/PickerOverlays.tsx +9 -2
  87. package/src/cli/tui/imagePicker/ImagePickerSt.ts +1 -1
  88. package/src/cli/tui/state/DraftsSt.ts +18 -2
  89. package/src/cli/tui/state/EditorSt.ts +1 -1
  90. package/src/cli/tui/state/HostSt.ts +34 -0
  91. package/src/cli/tui/state/LorasSt.ts +1 -1
  92. package/src/cli/tui/state/PickerSt.ts +25 -7
  93. package/src/cli/tui/state/SettingsSt.ts +1 -1
  94. package/src/cli/tui/state/TuiSt.ts +10 -0
  95. package/src/coreExports.ts +20 -0
  96. package/src/host/ComfyHost.ts +15 -0
  97. package/src/host/loraInfoCache.ts +70 -0
  98. package/src/host/loraManagerApi.ts +27 -0
  99. package/src/host/schemaDrift.ts +87 -0
  100. package/src/state.ts +5 -0
  101. package/src/vars/ComfyVars.ts +337 -67
  102. package/src/vars/DefinedWorkflow.ts +40 -19
  103. package/src/vars/lanes.ts +238 -0
  104. package/src/vars/loraEntry.ts +101 -0
  105. package/src/vars/promptSyntax.ts +382 -0
  106. package/dist/DefinedWorkflow-BatWaZO1.js.map +0 -1
  107. package/dist/LogsSt-DFxzQfDc.js.map +0 -1
  108. package/dist/run-serve-_nrvJYyt.js.map +0 -1
  109. package/dist/run-tui-Atvf9vb3.js.map +0 -1
  110. package/src/cli/serve/web/components/Sidebar.tsx +0 -66
@@ -1,11 +1,11 @@
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 { $ as stripAnsi, A as refreshLoraInfoCacheIfChanged, B as lmFilePath, C as getLoraTriggerWords, D as lorasMissingFromMirror, E as loraMirrorEntries, F as fetchLoraExampleImages, G as lmSha256, H as lmFolder, I as fetchLoraList, K as lmTags, L as fetchLoraPreviewBytes, M as writeLoraMirror, N as fetchLoraCivitai, P as fetchLoraDescription, Q as colorsAvailable, R as lmBaseModel, S as getLoraPreviewUrl, V as lmFileSize, W as lmNotes, X as loraPreviewMapFrom, Y as loraKey, Z as ansi, b as getLoraDisplayName, d as isPromptInput, dt as sha1HexOfString, et as extractErrorMessage, f as isLoraStrength, i as summarizeDrift, j as reloadLoraInfoCache, k as recordCivitaiMiss, l as isLoraLanes, lt as statelessRegex, m as getLoraKeyword, nt as bang, o as DEFAULT_IMAGE_EXTENSIONS, r as driftChanged, u as isLorasInput, v as buildLoraMirror, w as getLoraTriggers, x as getLoraInfo, y as getLoraAddedAt, z as lmCivitai } from "./schemaDrift-Cg39vs53.js";
2
+ import { a as draftsDirForFile, c as isDraftMetaKey, f as findDefinedWorkflow, i as draftKeyForFile, m as scanCflowFiles, n as assembleLogChunks, o as listDraftsForFile, s as ENHANCE_KEY } from "./LogsSt-U1H0mP1m.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
- import { basename, dirname, extname, join, resolve } from "pathe";
5
+ import { basename, dirname, extname, isAbsolute, join, resolve } from "pathe";
6
6
  import { nanoid } from "nanoid";
7
7
  import { createServer } from "node:http";
8
- import { networkInterfaces } from "node:os";
8
+ import { homedir, networkInterfaces } from "node:os";
9
9
  //#region src/cli/serve/describeVar.ts
10
10
  /** an empty list is absent from the json: every var without presets would otherwise carry `[]` */
11
11
  function presetsOrUndefined(presets) {
@@ -19,15 +19,21 @@ function describeVar(varDef) {
19
19
  const base = {
20
20
  kind: varDef.kind,
21
21
  label: varDef.label,
22
- default: varDef.defaultValue
22
+ default: varDef.defaultValue,
23
+ ...Object.keys(varDef.uiOpts).length > 0 ? { ui: varDef.uiOpts } : {}
23
24
  };
24
25
  switch (varDef.kind) {
25
26
  case "prompt": {
26
27
  const v = varDef;
27
28
  return {
28
29
  ...base,
29
- payload: "string (\"//\" lines = comments, \"- \" lines = negative)",
30
- textPresets: presetsOrUndefined(v.presets)
30
+ payload: "string (\"//\" starts a comment, \"- \" lines = negative)",
31
+ textPresets: presetsOrUndefined(v.presets),
32
+ tags: v.tags == null ? void 0 : {
33
+ underscores: v.tags.underscores === true,
34
+ artistPrefix: v.tags.artistPrefix
35
+ },
36
+ weights: v.promptOpts.weights === false ? false : void 0
31
37
  };
32
38
  }
33
39
  case "text": {
@@ -74,10 +80,13 @@ function describeVar(varDef) {
74
80
  };
75
81
  case "choice": {
76
82
  const v = varDef;
83
+ const list = v.choices.join(" | ");
84
+ const payload = v.select === "many" ? `a list of: ${list}` : v.select === "zero-or-one" ? `null or one of: ${list}` : `one of: ${list}`;
77
85
  return {
78
86
  ...base,
79
- payload: `one of: ${v.choices.join(" | ")}`,
80
- choices: v.choices
87
+ payload,
88
+ choices: v.choices,
89
+ select: v.select
81
90
  };
82
91
  }
83
92
  case "loras": {
@@ -94,7 +103,8 @@ function describeVar(varDef) {
94
103
  return {
95
104
  ...base,
96
105
  payload: "{\"width\":W,\"height\":H} or \"WxH\" or a preset label",
97
- presets: v.presets
106
+ presets: v.presets,
107
+ starredPresets: [...v.starred]
98
108
  };
99
109
  }
100
110
  case "image": {
@@ -134,11 +144,6 @@ function truncate(s, n) {
134
144
  function isFiniteNumber(x) {
135
145
  return typeof x === "number" && Number.isFinite(x);
136
146
  }
137
- function isLoraStrength(x) {
138
- if (typeof x === "boolean") return true;
139
- if (isFiniteNumber(x)) return true;
140
- return Array.isArray(x) && x.length === 2 && isFiniteNumber(x[0]) && isFiniteNumber(x[1]);
141
- }
142
147
  /** cap long option lists in error messages */
143
148
  function listSome(items, cap = 20) {
144
149
  if (items.length <= cap) return items.join(", ");
@@ -151,10 +156,13 @@ function applyVarPayload(varDef, raw, opts = {}) {
151
156
  const name = varDef.name ?? varDef.label ?? varDef.kind;
152
157
  switch (varDef.kind) {
153
158
  case "text":
154
- case "prompt":
155
159
  if (typeof raw !== "string") return `var '${name}' expects a string`;
156
160
  varDef.set(raw);
157
161
  return null;
162
+ case "prompt":
163
+ if (!isPromptInput(raw)) return `var '${name}' expects a string or {"lanes": [{"name": string, "prompt": string, "active": boolean}]}`;
164
+ varDef.set(raw);
165
+ return null;
158
166
  case "int":
159
167
  case "float": {
160
168
  const v = varDef;
@@ -191,18 +199,44 @@ function applyVarPayload(varDef, raw, opts = {}) {
191
199
  return null;
192
200
  case "choice": {
193
201
  const v = varDef;
194
- if (typeof raw === "string" && v.parse(raw)) return null;
202
+ const known = (x) => typeof x === "string" && v.choices.includes(x);
203
+ if (v.select === "many") {
204
+ if (known(raw)) {
205
+ v.set([raw]);
206
+ return null;
207
+ }
208
+ if (Array.isArray(raw) && raw.every(known)) {
209
+ v.set(v.choices.filter((c) => raw.includes(c)));
210
+ return null;
211
+ }
212
+ return `var '${name}' expects a list of: ${listSome(v.choices)}`;
213
+ }
214
+ if (v.select === "zero-or-one") {
215
+ if (raw === null || known(raw)) {
216
+ v.set(raw);
217
+ return null;
218
+ }
219
+ return `var '${name}' expects null or one of: ${listSome(v.choices)}`;
220
+ }
221
+ if (known(raw)) {
222
+ v.set(raw);
223
+ return null;
224
+ }
195
225
  return `var '${name}' expects one of: ${listSome(v.choices)}`;
196
226
  }
197
227
  case "loras": {
198
228
  const v = varDef;
199
- if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return `var '${name}' expects {"<lora name>": false | true | strength | [model, clip]}`;
200
- const record = raw;
229
+ const SHAPE = `{"<lora name>": false | true | strength | [model, clip] | {strength, off?, mute?}} or {"lanes": [{"name", "active", "loras": {…}}]}`;
230
+ if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return `var '${name}' expects ${SHAPE}`;
231
+ const records = isLoraLanes(raw) ? raw.lanes.map((l) => l.loras) : [raw];
201
232
  const known = /* @__PURE__ */ new Set([...v.options, ...opts.extraLoraOptions ?? []]);
202
- const unknownNames = Object.keys(record).filter((k) => !known.has(k));
203
- if (unknownNames.length > 0) return `var '${name}': unknown lora(s) ${unknownNames.join(", ")} — available: ${listSome([...known])}`;
204
- for (const [k, st] of Object.entries(record)) if (!isLoraStrength(st)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`;
205
- v.set(record);
233
+ for (const record of records) {
234
+ const unknownNames = Object.keys(record).filter((k) => !known.has(k));
235
+ if (unknownNames.length > 0) return `var '${name}': unknown lora(s) ${unknownNames.join(", ")} — available: ${listSome([...known])}`;
236
+ for (const [k, st] of Object.entries(record)) if (!isLoraStrength(st)) return `var '${name}': '${k}' must be false | true | number | [model, clip] | { strength: [model, clip], off?, mute? }`;
237
+ }
238
+ if (!isLorasInput(raw)) return `var '${name}' expects ${SHAPE}`;
239
+ v.set(raw);
206
240
  return null;
207
241
  }
208
242
  case "size": {
@@ -252,13 +286,13 @@ function validSavePrefix(raw) {
252
286
  }
253
287
  //#endregion
254
288
  //#region src/promptEnhancers.ts
255
- const EXT = ".md";
289
+ const EXT$1 = ".md";
256
290
  function promptEnhancersDir() {
257
291
  return comfyts.resolveFromPromptEnhancers("");
258
292
  }
259
293
  function promptEnhancerPath(name) {
260
294
  const safe = validStoreName(name);
261
- return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT}`);
295
+ return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT$1}`);
262
296
  }
263
297
  /** the shipped starting point. It is a FILE from the first read on, so it can be edited
264
298
  * on disk like everything else, the browser ships no copy of this text */
@@ -294,7 +328,7 @@ function readPromptEnhancers() {
294
328
  if (!existsSync(dir)) return [];
295
329
  const out = [];
296
330
  for (const file of readdirSync(dir).sort()) {
297
- if (!file.endsWith(EXT)) continue;
331
+ if (!file.endsWith(EXT$1)) continue;
298
332
  const name = file.slice(0, -3);
299
333
  if (validStoreName(name) == null) continue;
300
334
  try {
@@ -323,6 +357,85 @@ function deletePromptEnhancer(name) {
323
357
  return true;
324
358
  }
325
359
  //#endregion
360
+ //#region src/cli/serve/web/llm.ts
361
+ const OPENROUTER_BASE = "https://openrouter.ai/api/v1";
362
+ const OPENWEBUI_BASE = "http://localhost:3000";
363
+ const OPENAI_COMPAT_BASE = "http://localhost:8080/v1";
364
+ function defaultBaseUrl(provider) {
365
+ if (provider === "openrouter") return OPENROUTER_BASE;
366
+ return provider === "openwebui" ? OPENWEBUI_BASE : OPENAI_COMPAT_BASE;
367
+ }
368
+ //#endregion
369
+ //#region src/cli/serve/llmConfigShape.ts
370
+ function isProvider(raw) {
371
+ return raw === "openrouter" || raw === "openwebui" || raw === "openai";
372
+ }
373
+ function isEffort(raw) {
374
+ return raw === "off" || raw === "low" || raw === "medium" || raw === "high";
375
+ }
376
+ /** explicit model ids, never an alias: behaviour and cost stay reproducible */
377
+ const DEFAULT_MODEL = {
378
+ openrouter: "anthropic/claude-sonnet-5",
379
+ openwebui: "",
380
+ openai: ""
381
+ };
382
+ /** a stored file → a usable config: a half-written or hand-broken field degrades to its
383
+ * default, never breaks the modal */
384
+ function normalizeLlmConfig(raw) {
385
+ const o = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : {};
386
+ const provider = isProvider(o.provider) ? o.provider : "openrouter";
387
+ return {
388
+ provider,
389
+ baseUrl: typeof o.baseUrl === "string" && o.baseUrl.trim() !== "" ? o.baseUrl.trim() : defaultBaseUrl(provider),
390
+ model: typeof o.model === "string" ? o.model : DEFAULT_MODEL[provider],
391
+ effort: isEffort(o.effort) ? o.effort : "medium",
392
+ thinkingOnly: o.thinkingOnly !== false
393
+ };
394
+ }
395
+ //#endregion
396
+ //#region src/cli/serve/llmConfigs.ts
397
+ const EXT = ".json";
398
+ function llmConfigsDir() {
399
+ return comfyts.resolveFromLlmConfigs("");
400
+ }
401
+ function llmConfigPath(name) {
402
+ const safe = validStoreName(name);
403
+ return safe == null ? null : join(llmConfigsDir(), `${safe}${EXT}`);
404
+ }
405
+ function listLlmConfigs() {
406
+ const dir = llmConfigsDir();
407
+ if (!existsSync(dir)) return [];
408
+ const out = [];
409
+ for (const file of readdirSync(dir).sort()) {
410
+ if (!file.endsWith(EXT)) continue;
411
+ const name = file.slice(0, -5);
412
+ if (validStoreName(name) == null) continue;
413
+ try {
414
+ out.push({
415
+ name,
416
+ config: normalizeLlmConfig(JSON.parse(readFileSync(join(dir, file), "utf8")))
417
+ });
418
+ } catch (e) {
419
+ console.error(`[serve] llm config '${name}' unreadable, skipped:`, e);
420
+ }
421
+ }
422
+ return out;
423
+ }
424
+ function writeLlmConfig(name, config) {
425
+ const path = llmConfigPath(name);
426
+ if (path == null) return null;
427
+ mkdirSync(llmConfigsDir(), { recursive: true });
428
+ writeFileSync(path, `${JSON.stringify(normalizeLlmConfig(config), null, 3)}\n`);
429
+ return path;
430
+ }
431
+ /** a missing file is still a success: the caller asked for it to be gone, and it is */
432
+ function deleteLlmConfig(name) {
433
+ const path = llmConfigPath(name);
434
+ if (path == null) return false;
435
+ if (existsSync(path)) rmSync(path);
436
+ return true;
437
+ }
438
+ //#endregion
326
439
  //#region src/cli/serve/managerOnlyLoras.ts
327
440
  /**
328
441
  * `options` is the host enum for this var: it decides both what counts as already-known
@@ -336,6 +449,166 @@ function managerOnlyLoraOptions(p) {
336
449
  return loraMirrorEntries(p.hostId, { separator }).filter((e) => !known.has(e.key)).map((e) => e.serverName).filter((n) => filter == null || filter.test(n));
337
450
  }
338
451
  //#endregion
452
+ //#region src/cli/serve/tagList.ts
453
+ /** one csv line, double-quoted fields with `""` escapes */
454
+ function csvFields(line) {
455
+ const out = [];
456
+ let cur = "";
457
+ let quoted = false;
458
+ for (let i = 0; i < line.length; i++) {
459
+ const ch = line[i];
460
+ if (quoted) if (ch === "\"" && line[i + 1] === "\"") {
461
+ cur += "\"";
462
+ i++;
463
+ } else if (ch === "\"") quoted = false;
464
+ else cur += ch;
465
+ else if (ch === "\"") quoted = true;
466
+ else if (ch === ",") {
467
+ out.push(cur);
468
+ cur = "";
469
+ } else cur += ch;
470
+ }
471
+ out.push(cur);
472
+ return out;
473
+ }
474
+ const intOrNull = (s) => s != null && /^\d+$/.test(s.trim()) ? Number(s) : null;
475
+ function parseTagList(text) {
476
+ const out = [];
477
+ for (const raw of text.split(/\r?\n/)) {
478
+ const line = raw.trim();
479
+ if (line === "" || line.startsWith("#")) continue;
480
+ const f = csvFields(line);
481
+ const name = (f[0] ?? "").trim();
482
+ if (name === "") continue;
483
+ const twoCols = f.length === 2;
484
+ out.push({
485
+ name,
486
+ category: twoCols ? null : intOrNull(f[1]),
487
+ count: (twoCols ? intOrNull(f[1]) : intOrNull(f[2])) ?? 0,
488
+ aliases: (f[3] ?? "").split(",").map((a) => a.trim()).filter((a) => a !== "")
489
+ });
490
+ }
491
+ return out;
492
+ }
493
+ /** the searchable form: lowercase, spaces as underscores (the lists write `long_hair`) */
494
+ const key = (s) => s.trim().toLowerCase().replace(/\s+/g, "_");
495
+ var TagList = class TagList {
496
+ constructor(entries) {
497
+ this.entries = entries;
498
+ this.rows = entries.map((e) => ({
499
+ e,
500
+ name: key(e.name),
501
+ aliases: e.aliases.map(key)
502
+ }));
503
+ this.rows.sort((a, b) => b.e.count - a.e.count);
504
+ }
505
+ static parse(text) {
506
+ return new TagList(parseTagList(text));
507
+ }
508
+ /** prefix of the name first, then prefix of an alias (answered with the name it points to),
509
+ * then a word inside the name (`hair` finds `long_hair`), each by post count */
510
+ search(query, limit = 20) {
511
+ const q = key(query);
512
+ if (q === "") return [];
513
+ const hits = [];
514
+ const seen = /* @__PURE__ */ new Set();
515
+ const take = (e, alias) => {
516
+ if (seen.has(e.name)) return false;
517
+ seen.add(e.name);
518
+ hits.push(alias == null ? {
519
+ name: e.name,
520
+ category: e.category,
521
+ count: e.count
522
+ } : {
523
+ ...pick(e),
524
+ alias
525
+ });
526
+ return hits.length >= limit;
527
+ };
528
+ for (const r of this.rows) if (r.name.startsWith(q) && take(r.e)) return hits;
529
+ for (const r of this.rows) {
530
+ const a = r.aliases.find((x) => x.startsWith(q));
531
+ if (a != null && take(r.e, a)) return hits;
532
+ }
533
+ for (const r of this.rows) if (r.name.includes(`_${q}`) && take(r.e)) return hits;
534
+ return hits;
535
+ }
536
+ };
537
+ const pick = (e) => ({
538
+ name: e.name,
539
+ category: e.category,
540
+ count: e.count
541
+ });
542
+ //#endregion
543
+ //#region src/cli/serve/tagSource.ts
544
+ /** http(s) stays a url; `file://`, `~/`, absolute and relative (to the workflow file) become a path */
545
+ function resolveTagSource(url, moduleFile) {
546
+ if (/^https?:\/\//i.test(url)) return {
547
+ kind: "http",
548
+ url
549
+ };
550
+ if (url.startsWith("file://")) return {
551
+ kind: "file",
552
+ path: fileURLToPath(url)
553
+ };
554
+ if (url === "~" || url.startsWith("~/")) return {
555
+ kind: "file",
556
+ path: join(homedir(), url.slice(1))
557
+ };
558
+ if (isAbsolute(url)) return {
559
+ kind: "file",
560
+ path: url
561
+ };
562
+ return {
563
+ kind: "file",
564
+ path: resolve(dirname(moduleFile), url)
565
+ };
566
+ }
567
+ var TagSources = class {
568
+ constructor(p) {
569
+ this.p = p;
570
+ this.files = /* @__PURE__ */ new Map();
571
+ this.remote = /* @__PURE__ */ new Map();
572
+ }
573
+ async load(ref) {
574
+ if (ref.kind === "file") return this.loadFile(ref.path);
575
+ const hit = this.remote.get(ref.url);
576
+ if (hit != null) return hit;
577
+ const pending = this.loadRemote(ref.url);
578
+ this.remote.set(ref.url, pending);
579
+ pending.catch(() => this.remote.delete(ref.url));
580
+ return pending;
581
+ }
582
+ loadFile(path) {
583
+ if (!existsSync(path)) throw new Error(`tag list not found: ${path}`);
584
+ const mtimeMs = statSync(path).mtimeMs;
585
+ const cached = this.files.get(path);
586
+ if (cached != null && cached.mtimeMs === mtimeMs) return cached.list;
587
+ const list = TagList.parse(readFileSync(path, "utf8"));
588
+ if (list.entries.length === 0) throw new Error(`tag list is empty: ${path}`);
589
+ this.files.set(path, {
590
+ mtimeMs,
591
+ list
592
+ });
593
+ return list;
594
+ }
595
+ async loadRemote(url) {
596
+ const file = join(this.p.cacheDir(), `${sha1HexOfString(url)}.txt`);
597
+ if (existsSync(file)) return TagList.parse(readFileSync(file, "utf8"));
598
+ console.log(`[serve] fetching tag list ${url}`);
599
+ const text = await this.p.fetchText(url);
600
+ const list = TagList.parse(text);
601
+ if (list.entries.length === 0) throw new Error(`tag list is empty: ${url}`);
602
+ mkdirSync(dirname(file), { recursive: true });
603
+ writeFileSync(file, text);
604
+ console.log(`[serve] tag list ${url}: ${list.entries.length} tags, kept in ${file}`);
605
+ return list;
606
+ }
607
+ };
608
+ //#endregion
609
+ //#region src/cli/serve/favicon.ts
610
+ const FAVICON_DATA_URI = "data:image/png;base64,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";
611
+ //#endregion
339
612
  //#region src/utils/stringMap.ts
340
613
  function stringMap(raw) {
341
614
  const out = {};
@@ -463,6 +736,9 @@ var DownloadRefused = class extends Error {
463
736
  };
464
737
  const INPUT_DOWNLOAD_CAP = 5e7;
465
738
  const INPUT_DOWNLOAD_TIMEOUT_MS = 6e4;
739
+ /** the danbooru list is ~3.5 MB; ten times that is still a tag list, beyond is a wrong url */
740
+ const TAG_LIST_CAP = 4e7;
741
+ const TAG_LIST_TIMEOUT_MS = 12e4;
466
742
  /** read a reply STREAMING, aborting the moment it passes the cap. `arrayBuffer()` buffers the
467
743
  * whole body first, so a chunked reply with no content-length could exhaust the process before
468
744
  * anything checked its size, the cap then reported a number nobody survived to read. */
@@ -554,15 +830,21 @@ const USAGE = [
554
830
  "GET /drafts/<module>/<draft> — one draft with its stored values",
555
831
  "POST /generate/<module>/<draft> with { ...vars } — run, blocking",
556
832
  "POST /generate/<draft> — unqualified, when unambiguous",
833
+ "POST /preview/<module> with { ...draft values } — the workflow previews for those values, nothing is run",
557
834
  "PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft",
558
835
  "DELETE /drafts/<module>/<draft> — delete that draft file",
559
836
  "GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes",
560
837
  "POST /upload with {\"name\",\"dataBase64\"} — store a browser file for an image var",
838
+ "GET /tags/<module>/<var>?q=<text>&limit=<n> — tag completion from the list a prompt var declares (`tags`)",
839
+ "GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)",
561
840
  "GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)",
841
+ "POST /hosts/<hostId>/lora-civitai/<lora> — fetch its civitai metadata (trigger words) through the lora manager, then re-sync the mirror",
562
842
  "GET /lora-preview/<hostId>/<lora> — preview image bytes",
563
843
  "GET /lora-about/<hostId>/<lora> — civitai description + example images (live from the extension)",
564
844
  "GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)",
565
845
  "PUT /prompt-enhancers/<name> with {\"text\"} — write one · DELETE /prompt-enhancers/<name> — remove it",
846
+ "GET /llm-configs — the enhancer LLM configs (.comfy-ts/llm-configs/*.json)",
847
+ "PUT /llm-configs/<name> with {provider, baseUrl, model, effort, thinkingOnly} · DELETE /llm-configs/<name>",
566
848
  "GET /settings — { saveToDisk } · PUT /settings with {\"saveToDisk\"} — write outputs to disk, or keep them in memory",
567
849
  "GET /hosts — every host this process knows · PUT /hosts/<module> with {\"host\"} — run that workflow elsewhere",
568
850
  "POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host",
@@ -586,6 +868,7 @@ const WEB_SHELL = `<!doctype html>
586
868
  <meta charset="utf-8">
587
869
  <meta name="viewport" content="width=device-width, initial-scale=1">
588
870
  <title>comfy-ts serve</title>
871
+ <link rel="icon" type="image/png" href="${FAVICON_DATA_URI}">
589
872
  <style>html{background:#101217;color:#e8eaf0}</style>
590
873
  </head>
591
874
  <body>
@@ -607,10 +890,20 @@ var ServeApp = class {
607
890
  this.opts = opts;
608
891
  this.seedState = /* @__PURE__ */ new Map();
609
892
  this.chains = /* @__PURE__ */ new Map();
610
- this.webJsCache = null;
611
893
  this.settingsCache = null;
612
894
  this.memoryImages = /* @__PURE__ */ new Map();
613
895
  this.MEMORY_IMAGE_CAP = 60;
896
+ this.tagSources = new TagSources({
897
+ cacheDir: () => join(comfyts.baseFolder, "cache", "tags"),
898
+ fetchText: async (url) => {
899
+ const res = await fetch(url, {
900
+ redirect: "follow",
901
+ signal: AbortSignal.timeout(TAG_LIST_TIMEOUT_MS)
902
+ });
903
+ if (!res.ok) throw new Error(`tag list download failed (http ${res.status}): ${url}`);
904
+ return new TextDecoder().decode(await readCapped(res, TAG_LIST_CAP, url));
905
+ }
906
+ });
614
907
  this.liveRuns = /* @__PURE__ */ new Map();
615
908
  this.latentPreviews = /* @__PURE__ */ new Map();
616
909
  this.latentSeq = 0;
@@ -633,8 +926,7 @@ var ServeApp = class {
633
926
  }
634
927
  if (req.method === "GET") {
635
928
  if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes("text/html") === true) {
636
- this.webJsCache ??= this.opts.webJs();
637
- const js = await this.webJsCache;
929
+ const js = await this.opts.webJs();
638
930
  if (js != null) return {
639
931
  status: 200,
640
932
  contentType: "text/html; charset=utf-8",
@@ -651,10 +943,13 @@ var ServeApp = class {
651
943
  if (segs[0] === "lora-preview" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraPreview(segs[1], segs[2]);
652
944
  if (segs[0] === "lora-about" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraAbout(segs[1], segs[2]);
653
945
  if (segs[0] === "prompt-enhancers" && segs.length === 1) return this.replyPromptEnhancers();
946
+ if (segs[0] === "llm-configs" && segs.length === 1) return this.replyLlmConfigs();
947
+ if (segs[0] === "tags" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyTags(segs[1], segs[2], req.url);
654
948
  if (segs[0] === "settings" && segs.length === 1) return this.replySettings();
655
949
  if (segs[0] === "hosts" && segs.length === 1) return this.replyHosts();
656
950
  if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "logs") return await this.replyHostLogs(segs[1]);
657
951
  if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "ping") return await this.replyHostPing(segs[1]);
952
+ 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
953
  if (segs[0] === "images" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyMemoryImage(`${segs[1]}/${segs[2]}`);
659
954
  if (segs[0] === "outputs") return this.replyOutput(segs.slice(1));
660
955
  return json(404, {
@@ -667,14 +962,18 @@ var ServeApp = class {
667
962
  if ("error" in target) return json(target.status, { error: target.error });
668
963
  return await this.generate(target.mod, target.draft, req);
669
964
  }
965
+ if (req.method === "POST" && segs[0] === "preview" && segs.length === 2 && segs[1] != null) return await this.replyPreview(segs[1], req);
670
966
  if (req.method === "POST" && segs[0] === "upload" && segs.length === 1) return this.replyUpload(req);
671
967
  if (req.method === "PUT" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replySaveDraft(segs[1], segs[2], req);
672
968
  if (req.method === "DELETE" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyDeleteDraft(segs[1], segs[2]);
673
969
  if (req.method === "PUT" && segs[0] === "settings" && segs.length === 1) return this.replySaveSettings(req);
674
970
  if (req.method === "PUT" && segs[0] === "hosts" && segs.length === 2 && segs[1] != null) return this.replySetHost(segs[1], req);
675
971
  if (req.method === "POST" && segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyHostAction(segs[1], segs[2]);
972
+ 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
973
  if (req.method === "PUT" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replySavePromptEnhancer(segs[1], req);
677
974
  if (req.method === "DELETE" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replyDeletePromptEnhancer(segs[1]);
975
+ if (req.method === "PUT" && segs[0] === "llm-configs" && segs.length === 2 && segs[1] != null) return this.replySaveLlmConfig(segs[1], req);
976
+ if (req.method === "DELETE" && segs[0] === "llm-configs" && segs.length === 2 && segs[1] != null) return this.replyDeleteLlmConfig(segs[1]);
678
977
  return json(404, {
679
978
  error: `no route: ${req.method} ${path}`,
680
979
  usage: USAGE
@@ -786,6 +1085,18 @@ var ServeApp = class {
786
1085
  if (kw !== "") keywords[option] = kw;
787
1086
  }
788
1087
  if (Object.keys(keywords).length > 0) desc.optionKeywords = keywords;
1088
+ const addedAt = {};
1089
+ for (const option of desc.options) {
1090
+ const t = getLoraAddedAt(option, hostId);
1091
+ if (t != null) addedAt[option] = t;
1092
+ }
1093
+ if (Object.keys(addedAt).length > 0) desc.optionAddedAt = addedAt;
1094
+ const triggers = {};
1095
+ for (const option of desc.options) {
1096
+ const t = getLoraTriggers(option, hostId);
1097
+ if (t != null) triggers[option] = t;
1098
+ }
1099
+ if (Object.keys(triggers).length > 0) desc.optionTriggers = triggers;
789
1100
  }
790
1101
  vars[name] = desc;
791
1102
  }
@@ -803,7 +1114,8 @@ var ServeApp = class {
803
1114
  host: mod.dw.host.data.id,
804
1115
  drafts: this.draftsFor(mod),
805
1116
  routes: this.draftsFor(mod).map((d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),
806
- vars
1117
+ vars,
1118
+ previews: Object.keys(mod.dw.spec.previews ?? {})
807
1119
  };
808
1120
  }
809
1121
  replyIndex() {
@@ -824,6 +1136,31 @@ var ServeApp = class {
824
1136
  values: this.draftValues(mod, draft)
825
1137
  });
826
1138
  }
1139
+ /** the workflow's previews for the values the panel holds right now. The vars are SHARED
1140
+ * state (a run reads them), so this runs under the module lock: load the values, compute,
1141
+ * put the old values back. Nothing is queued, nothing is written */
1142
+ async replyPreview(key, req) {
1143
+ const mod = this.moduleByKey(key);
1144
+ if (mod == null) return json(404, { error: `unknown workflow '${key}'` });
1145
+ let values;
1146
+ try {
1147
+ values = JSON.parse(req.body ?? "{}");
1148
+ } catch (e) {
1149
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
1150
+ }
1151
+ if (values == null || typeof values !== "object" || Array.isArray(values)) return json(400, { error: "expects { \"<var>\": value, … }" });
1152
+ const incoming = values;
1153
+ return json(200, { previews: await this.exclusive(mod.key, () => {
1154
+ const saved = mod.dw.entries().map(([k, v]) => [k, v.toJSON()]);
1155
+ try {
1156
+ for (const [k, v] of mod.dw.entries()) if (k in incoming) v.loadJSON(incoming[k]);
1157
+ return Promise.resolve(mod.dw.computePreviews());
1158
+ } finally {
1159
+ const byName = new Map(mod.dw.entries());
1160
+ for (const [k, json] of saved) byName.get(k)?.loadJSON(json);
1161
+ }
1162
+ }) });
1163
+ }
827
1164
  /** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
828
1165
  draftValues(mod, draft) {
829
1166
  const path = this.draftPath(mod, draft);
@@ -844,8 +1181,7 @@ var ServeApp = class {
844
1181
  }
845
1182
  async replyWebJs() {
846
1183
  if (this.opts.webJs == null) return json(404, { error: "web ui not enabled on this server" });
847
- this.webJsCache ??= this.opts.webJs();
848
- const js = await this.webJsCache;
1184
+ const js = await this.opts.webJs();
849
1185
  if (js == null) return json(404, { error: "web ui bundle unavailable — see the server log" });
850
1186
  return {
851
1187
  status: 200,
@@ -891,7 +1227,11 @@ var ServeApp = class {
891
1227
  if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
892
1228
  const values = parsed;
893
1229
  const known = new Set(mod.dw.entries().map(([k]) => k));
894
- const unknown = Object.keys(values).filter((k) => !known.has(k));
1230
+ if ("$enhance" in values) {
1231
+ const raw = values[ENHANCE_KEY];
1232
+ if (!(raw != null && typeof raw === "object" && !Array.isArray(raw) && Object.values(raw).every((v) => typeof v === "string"))) return json(400, { error: `${ENHANCE_KEY} must be { "<prompt var>": "<intent>" }` });
1233
+ }
1234
+ const unknown = Object.keys(values).filter((k) => !known.has(k) && !isDraftMetaKey(k));
895
1235
  if (unknown.length > 0) return json(400, { error: `unknown var(s) ${unknown.join(", ")} — vars: ${[...known].join(", ")}` });
896
1236
  const path = bang(this.draftPath(mod, draft), "draft name validated just above");
897
1237
  await this.exclusive(mod.key, () => {
@@ -976,6 +1316,8 @@ var ServeApp = class {
976
1316
  if (action === "refresh-loras") return await this.refreshLoraMirror(hostId, host);
977
1317
  if (action === "refresh-schema") {
978
1318
  await host.fetchAndUpdateSchema();
1319
+ const unmirrored = lorasMissingFromMirror(host.schema.getLoras(), (n) => getLoraInfo(n, hostId) != null);
1320
+ const lorasNote = (await this.refreshLoraMirror(hostId, host)).status === 200 ? unmirrored.length > 0 ? `, lora list re-read (${unmirrored.length} new)` : ", lora list re-read" : ", the lora manager list could not be re-read";
979
1321
  const rebound = await this.rebindHostVars(hostId, host);
980
1322
  const nodes = host.schema.nodes.length;
981
1323
  const loras = host.schema.getLoras().length;
@@ -985,7 +1327,7 @@ var ServeApp = class {
985
1327
  host: hostId,
986
1328
  action,
987
1329
  stale: rebound.stale,
988
- note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}. no restart needed`
1330
+ note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}${lorasNote}`
989
1331
  });
990
1332
  }
991
1333
  if (action === "restart") {
@@ -1065,6 +1407,74 @@ var ServeApp = class {
1065
1407
  note: `${mirror.count} loras synced`
1066
1408
  });
1067
1409
  }
1410
+ /** fetch ONE lora's civitai metadata through the lora manager, then re-sync the mirror so its
1411
+ * trigger words reach every surface. The extension keys the request by the file path ON THE
1412
+ * HOST, which only the mirror knows, so a lora outside the mirror needs a sync first */
1413
+ async replyLoraCivitaiFetch(hostId, lora) {
1414
+ const host = comfyts.hosts.get(hostId);
1415
+ if (host == null) return json(404, { error: `unknown host '${hostId}'` });
1416
+ const info = getLoraInfo(lora, hostId);
1417
+ const filePath = info == null ? null : lmFilePath(info);
1418
+ if (filePath == null) return json(404, { error: `'${lora}' is not in the lora manager mirror of ${hostId}: sync the mirror first` });
1419
+ const fetched = await fetchLoraCivitai(host, filePath);
1420
+ const sha256 = info == null ? null : lmSha256(info);
1421
+ if (!fetched.ok && /no version data found/i.test(fetched.reason) && sha256 != null) {
1422
+ recordCivitaiMiss({
1423
+ hostId,
1424
+ sha256,
1425
+ miss: true
1426
+ });
1427
+ return json(200, {
1428
+ ok: true,
1429
+ host: hostId,
1430
+ lora,
1431
+ triggers: { state: "not-on-civitai" },
1432
+ note: `civitai does not know '${lora}' (a private or local lora): no trigger words to fetch`
1433
+ });
1434
+ }
1435
+ if (!fetched.ok) return json(502, { error: `civitai fetch failed for '${lora}': ${fetched.reason}` });
1436
+ if (sha256 != null) recordCivitaiMiss({
1437
+ hostId,
1438
+ sha256,
1439
+ miss: false
1440
+ });
1441
+ const synced = await this.refreshLoraMirror(hostId, host);
1442
+ if (synced.status !== 200) return synced;
1443
+ const t = getLoraTriggers(lora, hostId);
1444
+ return json(200, {
1445
+ ok: true,
1446
+ host: hostId,
1447
+ lora,
1448
+ triggers: t,
1449
+ 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}'`
1450
+ });
1451
+ }
1452
+ /** has the host changed since this process loaded its schema: new or removed model files (and
1453
+ * node types on a full check). A host whose catalog is COMMITTED rather than live-synced
1454
+ * (sdkAutoWrite: false, the cloud catalog) is not compared: its live list moves on purpose */
1455
+ async replyHostDrift(hostId, full) {
1456
+ const host = comfyts.hosts.get(hostId);
1457
+ if (host == null) return json(404, { error: `unknown host '${hostId}'` });
1458
+ if (host.data.sdkAutoWrite === false) return json(200, {
1459
+ host: hostId,
1460
+ checked: false,
1461
+ changed: false,
1462
+ summary: ""
1463
+ });
1464
+ try {
1465
+ const drift = await host.checkSchemaDrift({ full });
1466
+ return json(200, {
1467
+ host: hostId,
1468
+ checked: true,
1469
+ full,
1470
+ changed: driftChanged(drift),
1471
+ summary: summarizeDrift(drift),
1472
+ drift
1473
+ });
1474
+ } catch (e) {
1475
+ return json(502, { error: `${hostId} unreachable: ${extractErrorMessage(e)}` });
1476
+ }
1477
+ }
1068
1478
  /** is the host answering RIGHT NOW: what the panel polls while a restart is in flight, so
1069
1479
  * "restarting…" ends on a fact rather than on a guess */
1070
1480
  async replyHostPing(hostId) {
@@ -1229,7 +1639,22 @@ var ServeApp = class {
1229
1639
  effectivePrefix: Object.fromEntries(this.modules.map((m) => [m.key, this.savePrefixFor(m.key)]))
1230
1640
  });
1231
1641
  }
1232
- /** the folder is seeded on the first read, so `refine-krea2-prompt.md` exists to be edited */
1642
+ async replyTags(modKey, varName, url) {
1643
+ const mod = this.moduleByKey(modKey);
1644
+ if (mod == null) return json(404, { error: `unknown workflow '${modKey}'` });
1645
+ const found = mod.dw.entries().find(([k]) => k === varName)?.[1];
1646
+ if (found == null) return json(404, { error: `workflow '${modKey}' has no var '${varName}'` });
1647
+ const tags = found.kind === "prompt" ? found.tags : null;
1648
+ if (tags == null) return json(404, { error: `var '${varName}' declares no tag list (v.prompt(…, { tags }))` });
1649
+ const params = new URLSearchParams(url.split("?")[1] ?? "");
1650
+ const limit = Math.min(100, Math.max(1, Number(params.get("limit") ?? "20") || 20));
1651
+ try {
1652
+ return json(200, { hits: (await this.tagSources.load(resolveTagSource(tags.url, mod.file))).search(params.get("q") ?? "", limit) });
1653
+ } catch (e) {
1654
+ console.error(`[serve] 🔴 tag list for ${modKey}/${varName}: ${extractErrorMessage(e)}`);
1655
+ return json(502, { error: extractErrorMessage(e) });
1656
+ }
1657
+ }
1233
1658
  replyPromptEnhancers() {
1234
1659
  try {
1235
1660
  return json(200, { enhancers: listPromptEnhancers() });
@@ -1275,6 +1700,49 @@ var ServeApp = class {
1275
1700
  enhancers: listPromptEnhancers()
1276
1701
  });
1277
1702
  }
1703
+ replyLlmConfigs() {
1704
+ try {
1705
+ return json(200, { configs: listLlmConfigs() });
1706
+ } catch (e) {
1707
+ return json(500, { error: `llm-configs folder unreadable: ${extractErrorMessage(e)}` });
1708
+ }
1709
+ }
1710
+ replySaveLlmConfig(rawName, req) {
1711
+ const name = validStoreName(rawName);
1712
+ if (name == null) return json(400, { error: `invalid config name '${rawName}' — letters/digits then letters, digits, ". -_"` });
1713
+ let parsed;
1714
+ try {
1715
+ parsed = JSON.parse(req.body ?? "");
1716
+ } catch (e) {
1717
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
1718
+ }
1719
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be { provider, baseUrl, model, effort, thinkingOnly }" });
1720
+ try {
1721
+ writeLlmConfig(name, normalizeLlmConfig(parsed));
1722
+ } catch (e) {
1723
+ return json(500, { error: `could not write llm config '${name}': ${extractErrorMessage(e)}` });
1724
+ }
1725
+ return json(200, {
1726
+ ok: true,
1727
+ name,
1728
+ configs: listLlmConfigs()
1729
+ });
1730
+ }
1731
+ replyDeleteLlmConfig(rawName) {
1732
+ const name = validStoreName(rawName);
1733
+ if (name == null) return json(400, { error: `invalid config name '${rawName}'` });
1734
+ try {
1735
+ deleteLlmConfig(name);
1736
+ } catch (e) {
1737
+ return json(500, { error: `could not delete llm config '${name}': ${extractErrorMessage(e)}` });
1738
+ }
1739
+ console.log(`[serve] llm config deleted: ${name}`);
1740
+ return json(200, {
1741
+ ok: true,
1742
+ name,
1743
+ configs: listLlmConfigs()
1744
+ });
1745
+ }
1278
1746
  runningModules() {
1279
1747
  return [...this.liveRuns.entries()].filter(([, e]) => e.status !== "Success" && e.status !== "Failure").map(([key]) => key);
1280
1748
  }
@@ -1749,11 +2217,40 @@ async function buildWebJsText(pkgRoot) {
1749
2217
  if (!result.success || result.outputs[0] == null) throw new Error(`web ui bundle failed:\n${result.logs.map((l) => String(l)).join("\n")}`);
1750
2218
  return await result.outputs[0].text();
1751
2219
  }
1752
- /** the runtime resolution chain; every miss logs loud and degrades to api-only */
2220
+ /** changes whenever a file under `dir` is added, removed or rewritten. The web bundle reaches
2221
+ * outside web/ (vars, protocol types), so the whole src/ tree is the input: ~300 stats, a few ms */
2222
+ function sourceSignature(dir) {
2223
+ let count = 0;
2224
+ let newest = 0;
2225
+ let bytes = 0;
2226
+ const walk = (d) => {
2227
+ for (const entry of readdirSync(d, { withFileTypes: true })) {
2228
+ const abs = join(d, entry.name);
2229
+ if (entry.isDirectory()) walk(abs);
2230
+ else if (entry.isFile()) {
2231
+ const st = statSync(abs);
2232
+ count += 1;
2233
+ bytes += st.size;
2234
+ newest = Math.max(newest, st.mtimeMs);
2235
+ }
2236
+ }
2237
+ };
2238
+ walk(dir);
2239
+ return `${count}:${bytes}:${newest}`;
2240
+ }
2241
+ let prebuiltJs = null;
2242
+ let fromSource = null;
2243
+ /** the runtime resolution chain; every miss logs loud and degrades to api-only. Called on every
2244
+ * page load: a prebuilt file is read once, a source build is redone only when src/ changed, so
2245
+ * an edited panel shows on refresh under `bun --watch`, which never sees the bundled files */
1753
2246
  async function loadOrBuildWebJs() {
1754
2247
  const here = dirname(fileURLToPath(import.meta.url));
1755
2248
  const prebuilt = join(here, "serve-web.js");
1756
- if (existsSync(prebuilt)) return readFileSync(prebuilt, "utf8");
2249
+ if (prebuiltJs != null) return prebuiltJs;
2250
+ if (existsSync(prebuilt)) {
2251
+ prebuiltJs = readFileSync(prebuilt, "utf8");
2252
+ return prebuiltJs;
2253
+ }
1757
2254
  if (typeof Bun === "undefined") {
1758
2255
  console.error("[serve] 🔴 no serve-web.js next to the cli and not running under bun — api only, no web ui");
1759
2256
  return null;
@@ -1763,12 +2260,21 @@ async function loadOrBuildWebJs() {
1763
2260
  console.error(`[serve] 🔴 web ui source not found (looked for ${WEB_ENTRY} above ${here}) — api only, no web ui`);
1764
2261
  return null;
1765
2262
  }
1766
- try {
1767
- return await buildWebJsText(pkgRoot);
1768
- } catch (e) {
1769
- console.error("[serve] 🔴 web ui bundle failed — api only:", e);
1770
- return null;
2263
+ const signature = sourceSignature(join(pkgRoot, "src"));
2264
+ if (fromSource?.signature !== signature) {
2265
+ const rebuilt = fromSource != null;
2266
+ fromSource = {
2267
+ signature,
2268
+ js: buildWebJsText(pkgRoot).then((js) => {
2269
+ if (rebuilt) console.log("[serve] web ui rebuilt from source");
2270
+ return js;
2271
+ }, (e) => {
2272
+ console.error("[serve] 🔴 web ui bundle failed — api only until the next edit:", e);
2273
+ return null;
2274
+ })
2275
+ };
1771
2276
  }
2277
+ return await fromSource.js;
1772
2278
  }
1773
2279
  //#endregion
1774
2280
  //#region src/cli/serve/run-serve.ts
@@ -1945,4 +2451,4 @@ function printStartup(app, bind, port) {
1945
2451
  //#endregion
1946
2452
  export { runServe };
1947
2453
 
1948
- //# sourceMappingURL=run-serve-_nrvJYyt.js.map
2454
+ //# sourceMappingURL=run-serve-BeAznay5.js.map