@melite/estate-queue 0.0.0-stage → 0.1.5-pre-alpha

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 (131) hide show
  1. package/LICENSE +557 -0
  2. package/README.md +54 -2
  3. package/lib/bakeParams.d.ts +17 -0
  4. package/lib/bakeParams.js +182 -0
  5. package/lib/bench.d.ts +32 -0
  6. package/lib/bench.js +111 -0
  7. package/lib/cardsArmError.d.ts +61 -0
  8. package/lib/cardsArmError.js +57 -0
  9. package/lib/cardsCompose.d.ts +53 -0
  10. package/lib/cardsCompose.js +295 -0
  11. package/lib/cardsDangling.d.ts +16 -0
  12. package/lib/cardsDangling.js +213 -0
  13. package/lib/cardsFacts.d.ts +87 -0
  14. package/lib/cardsFacts.js +78 -0
  15. package/lib/cardsLanes.d.ts +43 -0
  16. package/lib/cardsLanes.js +178 -0
  17. package/lib/cardsRegistry.d.ts +404 -0
  18. package/lib/cardsRegistry.js +1543 -0
  19. package/lib/cardsVariant.d.ts +37 -0
  20. package/lib/cardsVariant.js +243 -0
  21. package/lib/discloseRegistry.d.ts +95 -0
  22. package/lib/discloseRegistry.js +156 -0
  23. package/lib/filmLead.d.ts +4 -0
  24. package/lib/filmLead.js +17 -0
  25. package/lib/filmMemoryWarn.d.ts +27 -0
  26. package/lib/filmMemoryWarn.js +99 -0
  27. package/lib/flowsData.d.ts +234 -0
  28. package/lib/flowsData.js +673 -0
  29. package/lib/flowsFamilyCompose.d.ts +45 -0
  30. package/lib/flowsFamilyCompose.js +191 -0
  31. package/lib/flowsParamsOverlay.d.ts +55 -0
  32. package/lib/flowsParamsOverlay.js +197 -0
  33. package/lib/flowsRegistryRows.d.ts +12 -0
  34. package/lib/flowsRegistryRows.js +520 -0
  35. package/lib/index.d.ts +47 -0
  36. package/lib/index.js +75 -0
  37. package/lib/ledgerTail.d.ts +20 -0
  38. package/lib/ledgerTail.js +123 -0
  39. package/lib/lifecycleLatch.d.ts +16 -0
  40. package/lib/lifecycleLatch.js +42 -0
  41. package/lib/loadPlane.d.ts +94 -0
  42. package/lib/loadPlane.js +570 -0
  43. package/lib/loadRegistry.d.ts +22 -0
  44. package/lib/loadRegistry.js +55 -0
  45. package/lib/manageOps.d.ts +27 -0
  46. package/lib/manageOps.js +162 -0
  47. package/lib/managePlane.d.ts +151 -0
  48. package/lib/managePlane.js +1790 -0
  49. package/lib/manageProbe.d.ts +48 -0
  50. package/lib/manageProbe.js +165 -0
  51. package/lib/manageRegistry.d.ts +66 -0
  52. package/lib/manageRegistry.js +113 -0
  53. package/lib/managerRail.d.ts +33 -0
  54. package/lib/managerRail.js +91 -0
  55. package/lib/mediaKinds.d.ts +3 -0
  56. package/lib/mediaKinds.js +2 -0
  57. package/lib/queue.d.ts +9 -0
  58. package/lib/queue.js +80 -0
  59. package/lib/queueCore.d.ts +72 -0
  60. package/lib/queueCore.js +128 -0
  61. package/lib/queueLifecycle.d.ts +2 -0
  62. package/lib/queueLifecycle.js +11 -0
  63. package/lib/queueLock.d.ts +60 -0
  64. package/lib/queueLock.js +198 -0
  65. package/lib/queueResurrect.d.ts +59 -0
  66. package/lib/queueResurrect.js +249 -0
  67. package/lib/queueRetry.d.ts +36 -0
  68. package/lib/queueRetry.js +24 -0
  69. package/lib/queueSidecar.d.ts +149 -0
  70. package/lib/queueSidecar.js +183 -0
  71. package/lib/queueSubmit.d.ts +82 -0
  72. package/lib/queueSubmit.js +191 -0
  73. package/lib/queueSweep.d.ts +30 -0
  74. package/lib/queueSweep.js +132 -0
  75. package/lib/resurrect.d.ts +6 -0
  76. package/lib/resurrect.js +18 -0
  77. package/lib/rootsManifest.d.ts +11 -0
  78. package/lib/rootsManifest.js +11 -0
  79. package/lib/runsChange.d.ts +61 -0
  80. package/lib/runsChange.js +79 -0
  81. package/lib/runsErrorCodes.d.ts +2 -0
  82. package/lib/runsErrorCodes.js +48 -0
  83. package/lib/runsExecute.d.ts +52 -0
  84. package/lib/runsExecute.js +494 -0
  85. package/lib/runsGates.d.ts +161 -0
  86. package/lib/runsGates.js +307 -0
  87. package/lib/runsList.d.ts +78 -0
  88. package/lib/runsList.js +574 -0
  89. package/lib/runsRefusalVoices.d.ts +9 -0
  90. package/lib/runsRefusalVoices.js +96 -0
  91. package/lib/runsRegistry.d.ts +351 -0
  92. package/lib/runsRegistry.js +2394 -0
  93. package/lib/runsSourceEcho.d.ts +81 -0
  94. package/lib/runsSourceEcho.js +341 -0
  95. package/lib/runsStart.d.ts +163 -0
  96. package/lib/runsStart.js +667 -0
  97. package/lib/runsTypes.d.ts +218 -0
  98. package/lib/runsTypes.js +289 -0
  99. package/lib/runsValidate.d.ts +5 -0
  100. package/lib/runsValidate.js +31 -0
  101. package/lib/runsValidateArms.d.ts +7 -0
  102. package/lib/runsValidateArms.js +339 -0
  103. package/lib/runsValidateInline.d.ts +6 -0
  104. package/lib/runsValidateInline.js +82 -0
  105. package/lib/runsValidateRefusals.d.ts +7 -0
  106. package/lib/runsValidateRefusals.js +18 -0
  107. package/lib/runsValidateServe.d.ts +15 -0
  108. package/lib/runsValidateServe.js +276 -0
  109. package/lib/runsValidateShared.d.ts +84 -0
  110. package/lib/runsValidateShared.js +88 -0
  111. package/lib/runsValidateStages.d.ts +32 -0
  112. package/lib/runsValidateStages.js +511 -0
  113. package/lib/runsValidateSweeps.d.ts +6 -0
  114. package/lib/runsValidateSweeps.js +143 -0
  115. package/lib/service.d.ts +63 -0
  116. package/lib/service.js +89 -0
  117. package/lib/skillFrontmatter.d.ts +11 -0
  118. package/lib/skillFrontmatter.js +46 -0
  119. package/lib/skillFs.d.ts +24 -0
  120. package/lib/skillFs.js +78 -0
  121. package/lib/skillPlane.d.ts +99 -0
  122. package/lib/skillPlane.js +269 -0
  123. package/lib/skillRegistry.d.ts +23 -0
  124. package/lib/skillRegistry.js +55 -0
  125. package/lib/skillRows.d.ts +127 -0
  126. package/lib/skillRows.js +468 -0
  127. package/lib/toolProjection.d.ts +30 -0
  128. package/lib/toolProjection.js +142 -0
  129. package/lib/vocab.d.ts +6 -0
  130. package/lib/vocab.js +18 -0
  131. package/package.json +48 -4
@@ -0,0 +1,1790 @@
1
+ // managePlane.ts — the management plane, RE-HOMED (REBUILD-15,
2
+
3
+ // gateway app) ports here BESIDE the runs/disclose seats — the
4
+ // vocabulary (ACTIONS, HANDLERS rows, LIFECYCLE_GUARDED) stays the
5
+ // SSOT the walls scan. Wire contract unchanged: the envelope is
6
+ // always {action, ok, detail, data}.
7
+ //
8
+ // This module is the PURE plane (dispatchManage + ManageCtx); the
9
+ // seat (manageRegistry.ts) assembles the ctx from the estate's own
10
+ // seats and answers the tools' /v1/manage lane.
11
+ //
12
+ // Erasable-syntax TS only (node --experimental-strip-types).
13
+ import { execFile } from "node:child_process";
14
+ import { promisify } from "node:util";
15
+ import { readFileSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { ComfyError, endpointConfigPath, invalidateObjectInfo, liveObjectInfo, loadEndpointConfig, resolveEngineBaseUrl, } from "@melite/comfyui-cordis";
18
+ import { writeJsonAtomic } from "./queueLock.js";
19
+ import { installUserLora, installUserLoraBytes, loraNamesFromObjectInfo, readUserLoraRows, resolveEngineLorasDir, unboardedRows, userLorasPath, } from "@melite/comfyui-cordis/user-loras";
20
+ import { AcquireBusyError } from "@melite/estate-provisioning";
21
+ import { ManagerApiError, managerGet, managerPost, planeUnavailable } from "./managerRail.js";
22
+ import { probeEndpoint, activeRuns, managerSecurity, engineQueueView } from "./manageProbe.js";
23
+ import { base, mapManagerRefused, mapRail, railMs, estateOnly, awaitQueueDrained, systemctl, guardLifecycle } from "./manageOps.js";
24
+ import { holdLifecycle } from "./lifecycleLatch.js";
25
+ import { deadline as deadlineOf, timeoutOf } from "@deepseek-ai/dsh-timeout";
26
+ import { segmentConfined } from "@melite/contracts/mediaKinds";
27
+ import { artifactFileName } from "@melite/contracts/benchResult";
28
+ const execFileAsync = promisify(execFile);
29
+ // ── SSOT vocabulary ─────────────────────────────────────────────────
30
+ // Closed vocabulary — a typo is a 422, not a silent miss.
31
+ export const ACTIONS = [
32
+ "status",
33
+ "endpoint_set",
34
+ "logs",
35
+ "search_models",
36
+ "list_extensions",
37
+ "snapshot_list",
38
+ "install_extension",
39
+ "install_extension_url",
40
+ "download_model",
41
+ "provision_model",
42
+ "acquire_weight",
43
+ "restart",
44
+ "stop",
45
+ "launch",
46
+ "update",
47
+ "switch_version",
48
+ "free",
49
+ "snapshot_save",
50
+ "snapshot_restore",
51
+ "lora_list",
52
+ "lora_install",
53
+ ];
54
+ /** The status reconcile bound (the wall law — see hStatus): status
55
+ * answers inside the plane's 5s wall; the digest-verifying
56
+ * reconcile cannot, so it rides this bound and reports partial.
57
+ * 1.5s (not 3s): the wall's 5s covers bundle-mount + seat settle
58
+ * too — under battery load the settle alone eats ~2s, so the
59
+ * reconcile must leave headroom (the flake law). */
60
+ const STATUS_RECONCILE_MS = 1_500;
61
+ // Lifecycle actions that would kill a live GPU job — guarded
62
+ // (INFERENCE LAW: management never manufactures zombie runs; the stop
63
+ // DOOR is the sanctioned way a run dies).
64
+ export const LIFECYCLE_GUARDED = new Set([
65
+ "restart",
66
+ "stop",
67
+ "switch_version",
68
+ "update",
69
+ "snapshot_restore",
70
+ "free",
71
+ ]);
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+ export function provisioningOf(ctx) {
86
+ const seat = ctx.provisioning;
87
+ if (seat === undefined || typeof seat.reconcile !== "function") {
88
+ throw new Refused(503, "the provisioning seat is not mounted on this lane (absent, not broken) — the estate's provisioning composition row is what mounts it; nothing can be installed, updated or reconciled without it");
89
+ }
90
+ return seat;
91
+ }
92
+ export function provisioningOrAbsent(ctx) {
93
+ const seat = ctx.provisioning;
94
+ return seat === undefined || typeof seat.reconcile !== "function" ? undefined : seat;
95
+ }
96
+ // ── errors (the dispatch maps classes to codes, as before) ─────────
97
+ export class Refused extends Error {
98
+ data;
99
+ constructor(code, message, data) {
100
+ super(message);
101
+ this.code = code;
102
+ this.data = data;
103
+ }
104
+ code;
105
+ }
106
+ export const badRequest = (m) => new Refused(422, m);
107
+ const notFound = (m) => new Refused(404, m);
108
+ const unavailable = (m) => new Refused(503, m);
109
+ function abortReason(signal) {
110
+ return signal?.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
111
+ }
112
+ function signalIsAborted(signal) {
113
+ return signal?.aborted === true;
114
+ }
115
+ function throwIfAborted(signal) {
116
+ if (signal?.aborted === true)
117
+ throw abortReason(signal);
118
+ }
119
+ function awaitWithAbort(work, signal) {
120
+ if (signal.aborted)
121
+ return Promise.reject(abortReason(signal));
122
+ return new Promise((resolvePromise, rejectPromise) => {
123
+ let settled = false;
124
+ const finish = (fn) => {
125
+ if (settled)
126
+ return;
127
+ settled = true;
128
+ signal.removeEventListener("abort", onAbort);
129
+ fn();
130
+ };
131
+ const onAbort = () => finish(() => rejectPromise(abortReason(signal)));
132
+ signal.addEventListener("abort", onAbort, { once: true });
133
+ work.then((value) => finish(() => resolvePromise(value)), (error) => finish(() => rejectPromise(error)));
134
+ });
135
+ }
136
+ function linkCallerSignal(ctx, signal) {
137
+ if (signal === undefined)
138
+ return ctx;
139
+ return {
140
+ ...ctx,
141
+ signal,
142
+ // The timer keeps its own abort listener (an in-flight wait
143
+ // fires early when the caller aborts). A timer SCHEDULED while
144
+ // already aborted cannot occur: every ctx.timeout caller
145
+ // (waitForQueuePoll, the registry seat) rejects at entry on the
146
+ // same tick it would schedule on — the pre-aborted leg the
147
+ // wrapper once carried was unreachable and is gone (the same
148
+ // judgment waitForQueuePoll's own comment records).
149
+ timeout: (callback, delay) => {
150
+ const clear = ctx.timeout(callback, delay);
151
+ const onAbort = () => callback();
152
+ signal.addEventListener("abort", onAbort, { once: true });
153
+ return () => {
154
+ signal.removeEventListener("abort", onAbort);
155
+ clear();
156
+ };
157
+ },
158
+ };
159
+ }
160
+ export function parseReq(doc) {
161
+ if (doc === null || typeof doc !== "object" || Array.isArray(doc)) {
162
+ throw badRequest("Input should be a valid dictionary");
163
+ }
164
+ const d = doc;
165
+ const action = String(d["action"] ?? "");
166
+ if (action === "")
167
+ throw badRequest("Field required: action");
168
+ if (!ACTIONS.includes(action)) {
169
+ throw badRequest("Input should be one of: " + ACTIONS.join(", "));
170
+ }
171
+ const str = (k) => (typeof d[k] === "string" ? d[k] : "");
172
+ const num = (k, def) => {
173
+ const v = d[k];
174
+ if (typeof v !== "number" || !Number.isFinite(v))
175
+ return def;
176
+ return v;
177
+ };
178
+ return {
179
+ action: action,
180
+ nodes: Array.isArray(d["nodes"]) ? d["nodes"].map(String).filter((s) => s !== "") : [],
181
+ url: str("url"),
182
+ ref: str("ref"),
183
+ relative_path: str("relative_path"),
184
+ wait: typeof d["wait"] === "boolean" ? d["wait"] : null,
185
+ timeout_seconds: num("timeout_seconds", 300),
186
+ model: str("model"),
187
+ variant: str("variant"),
188
+ quant: str("quant"),
189
+ tail: num("tail", 200),
190
+ query: str("query"),
191
+ version: str("version"),
192
+ target: str("target") || "comfy",
193
+ extra_args: Array.isArray(d["extra_args"]) ? d["extra_args"].map(String) : [],
194
+ force: d["force"] === true,
195
+ operator_confirmed: d["operator_confirmed"] === true,
196
+ snapshot: str("snapshot"),
197
+
198
+ // ENGINE will accept (its own combo) plus the user's own rows;
199
+ // `lora_install` copies a LoRA the operator already has into the
200
+ // engine's loras dir — never a fetch (the no-loras-remote law).
201
+ path: str("path"),
202
+
203
+ // Cloudflare + a per-account key, and the standing law forbids a
204
+ // loras remote — so the USER'S BROWSER downloads it and hands the
205
+ // bytes over as the uploads rail's own data-URL spelling.
206
+ data: str("data"),
207
+ filename: str("filename") || str("file"),
208
+ families: Array.isArray(d["families"]) ? d["families"].map(String).filter((s) => s !== "") : [],
209
+ operation_id: str("operation_id"),
210
+ };
211
+ }
212
+ function need(req, ...fields) {
213
+ const missing = fields.filter((f) => {
214
+ const v = req[f];
215
+ // (no caller gates an array field today — all needs are strings)
216
+ return Array.isArray(v) ? /* v8 ignore next */ v.length === 0 : v === "";
217
+ });
218
+ if (missing.length > 0)
219
+ throw badRequest(req.action + " requires: " + missing.join(", "));
220
+ }
221
+ function ok(action, detail, data) {
222
+ const value = typeof data === "object" && data !== null && !Array.isArray(data)
223
+ ? data
224
+ : undefined;
225
+ const envelope = {
226
+ action,
227
+ ok: true,
228
+ detail,
229
+ data,
230
+ ...(Array.isArray(data) ? { rows: data } : {}),
231
+ };
232
+ if (typeof value?.state === "string")
233
+ envelope.state = value.state;
234
+ if (typeof value?.next_action === "string")
235
+ envelope.next_action = value.next_action;
236
+ if (typeof value?.operation_id === "string")
237
+ envelope.operation_id = value.operation_id;
238
+ if (Array.isArray(value?.operations))
239
+ envelope.operations = value.operations;
240
+ return [200, envelope];
241
+ }
242
+ function withNextAction(response, nextAction) {
243
+ response[1].next_action = nextAction;
244
+ return response;
245
+ }
246
+ // ── handlers ────────────────────────────────────────────────────────
247
+ function engineBootReceiptPath(ctx) {
248
+ return join(ctx.repoRoot, "data", "runtime", "comfyui", ".estate-engine-boot.json");
249
+ }
250
+ async function recordEngineBoot(ctx, source) {
251
+ try {
252
+ // J6: the receipt rides the package's atomic writer — a bare
253
+ // writeFileSync could tear the file across a crash, and a torn
254
+ // receipt is a FALSE blindness signal for the status reader.
255
+ await writeJsonAtomic(engineBootReceiptPath(ctx), { boot_at: Date.now(), source });
256
+ }
257
+ catch {
258
+ // Swallowed with reason: the engine IS rebooting regardless; a
259
+ // failed receipt write must never fail the restart answer — with
260
+ // ONE exception (MP-R2, round 19): the caller's own abort. An
261
+ // abort surfacing inside this write must propagate (the hRestart
262
+ // finally still drops the cache for the issued reboot) instead of
263
+ // being laundered into a success the caller cancelled.
264
+ if (signalIsAborted(ctx.signal))
265
+ throw abortReason(ctx.signal);
266
+ return;
267
+ }
268
+ }
269
+ function engineBootRow(ctx) {
270
+ try {
271
+ const raw = JSON.parse(readFileSync(engineBootReceiptPath(ctx), "utf8"));
272
+ const bootAt = typeof raw.boot_at === "number" ? raw.boot_at : NaN;
273
+ if (!Number.isFinite(bootAt))
274
+ throw new Error("malformed receipt");
275
+ return {
276
+ known: true,
277
+ boot_at: new Date(bootAt).toISOString(),
278
+ age_seconds: Math.max(0, Math.round((Date.now() - bootAt) / 1000)),
279
+ source: typeof raw.source === "string" ? raw.source : "estate",
280
+ };
281
+ }
282
+ catch {
283
+ return { known: false, note: "engine booted outside the estate's restart door — age unknown" };
284
+ }
285
+ }
286
+ function statusOutcome(state) {
287
+ return state;
288
+ }
289
+ function safeStatusItems(items) {
290
+ return items.map((item) => ({
291
+ key: item.key,
292
+ kind: item.kind,
293
+ state: item.state,
294
+ ...(item.path === undefined ? {} : { path: item.path }),
295
+ ...(item.sha256 === undefined ? {} : { sha256: item.sha256 }),
296
+ ...(item.integrity === undefined ? {} : { integrity: item.integrity }),
297
+ ...(item.errorCode === undefined ? {} : { errorCode: item.errorCode }),
298
+ ...(item.detail === undefined ? {} : { detail: item.detail }),
299
+ }));
300
+ }
301
+ async function normalizedResources(resources, provisioning) {
302
+ const rows = [];
303
+ for (const resource of resources) {
304
+ rows.push(await normalizeResource(resource, provisioning));
305
+ }
306
+ return rows;
307
+ }
308
+
309
+
310
+
311
+
312
+
313
+
314
+
315
+
316
+
317
+ async function normalizeResource(resource, provisioning) {
318
+ const row = (operationId, state, items, detail) => ({
319
+ ...resource,
320
+ state,
321
+ items,
322
+ ...(operationId === undefined ? {} : { operationId }),
323
+ ...(detail === undefined ? {} : { detail }),
324
+ });
325
+ if (provisioning === undefined) {
326
+
327
+
328
+
329
+
330
+
331
+
332
+ return row(resource.operationId, resource.state, resource.items, resource.detail);
333
+ }
334
+ try {
335
+ const operation = provisioning.operationOf(resource.ref);
336
+ if (operation === undefined) {
337
+ return row(resource.operationId, resource.state, resource.items, resource.detail);
338
+ }
339
+ const verified = provisioning.verifyOperation === undefined
340
+ ? operation
341
+ : await provisioning.verifyOperation(operation);
342
+ if (verified.state !== operation.state) {
343
+ return row(verified.operationId, verified.state, verified.items, verified.items[0]?.detail ?? resource.detail);
344
+ }
345
+ return row(operation.operationId, operation.state, operation.items, resource.detail ?? operation.detail);
346
+ }
347
+ catch {
348
+ return row(resource.operationId, resource.state, resource.items, resource.detail);
349
+ }
350
+ }
351
+ function operationRows(resources) {
352
+ return resources.flatMap((resource) => {
353
+ const operationId = resource.operationId;
354
+ const first = resource.items[0];
355
+ return operationId === undefined ? [] : [{
356
+ operation_id: operationId,
357
+ name: resource.ref.id,
358
+ ref: resource.ref,
359
+ ...(first?.path === undefined ? {} : { path: first.path }),
360
+ state: resource.state,
361
+ outcome: statusOutcome(resource.state),
362
+ items: safeStatusItems(resource.items),
363
+ next_action: resource.state === "restart_required" || resource.state === "installed" ? "restart" : "status",
364
+ }];
365
+ });
366
+ }
367
+ function nextActionFor(endpointReachable, resources, managed) {
368
+ if (!endpointReachable)
369
+ return managed ? "launch" : "endpoint_set";
370
+ if (resources.some((resource) => resource.state === "restart_required" || resource.state === "installed"))
371
+ return "restart";
372
+ return "status";
373
+ }
374
+ function modelOptions(models) {
375
+ if (typeof models.allDecls !== "function")
376
+ return { options: [], detail: "model catalog unavailable" };
377
+ try {
378
+ const options = models.allDecls()
379
+ .filter((decl) => !decl.unoffered && (decl.engine === undefined || decl.engine === "" || decl.engine === "comfyui"))
380
+ .map((decl) => ({
381
+ id: decl.id,
382
+ label: decl.label || decl.id,
383
+ ...(decl.description === undefined ? {} : { description: decl.description }),
384
+ ...(decl.genre === undefined ? {} : { genre: decl.genre }),
385
+ variants: (decl.variants ?? []).filter((variant) => variant.hide_from_dropdown !== true && (variant.cells ?? []).some((cell) => cell.quant !== "" && cell.hide_from_dropdown !== true)).map((variant) => ({
386
+ id: variant.id,
387
+ label: variant.label || variant.id,
388
+ ...(variant.description === undefined ? {} : { description: variant.description }),
389
+ quants: variant.cells
390
+ .filter((cell) => cell.quant !== "" && cell.hide_from_dropdown !== true)
391
+ .map((cell) => ({
392
+ id: cell.quant,
393
+ label: cell.label || cell.quant,
394
+ ...(cell.description === undefined ? {} : { description: cell.description }),
395
+ })),
396
+ })),
397
+ }));
398
+ return { options };
399
+ }
400
+ catch (error) {
401
+ return { options: [], detail: error instanceof Error ? error.message : String(error) };
402
+ }
403
+ }
404
+ function versionOptions(doc) {
405
+ const values = Array.isArray(doc)
406
+ ? doc
407
+ : typeof doc === "object" && doc !== null
408
+ ? (() => {
409
+ const record = doc;
410
+ if (Array.isArray(record["versions"]))
411
+ return record["versions"];
412
+ if (Array.isArray(record["tags"]))
413
+ return record["tags"];
414
+ if (Array.isArray(record["data"]))
415
+ return record["data"];
416
+ return Object.entries(record).map(([tag, version]) => ({ tag, version }));
417
+ })()
418
+ : [];
419
+ const seen = new Set();
420
+ const options = [];
421
+ for (const value of values) {
422
+ if (typeof value === "string" || typeof value === "number") {
423
+ const id = String(value);
424
+ if (id === "" || seen.has(id))
425
+ continue;
426
+ seen.add(id);
427
+ options.push({ id, label: id });
428
+ continue;
429
+ }
430
+ if (typeof value !== "object" || value === null)
431
+ continue;
432
+ const record = value;
433
+ const version = typeof record["version"] === "string" ? record["version"] : undefined;
434
+ const tag = typeof record["tag"] === "string" ? record["tag"] : undefined;
435
+ const commit = typeof record["commit"] === "string" ? record["commit"] : undefined;
436
+ const id = version ?? tag ?? commit ?? (typeof record["id"] === "string" ? record["id"] : undefined);
437
+ if (id === undefined || id === "" || seen.has(id))
438
+ continue;
439
+ seen.add(id);
440
+ const label = version !== undefined && tag !== undefined && version !== tag
441
+ ? version + " — " + tag
442
+ : version ?? tag ?? commit ?? id;
443
+ options.push({ id, label, ...(version === undefined ? {} : { version }), ...(tag === undefined ? {} : { tag }), ...(commit === undefined ? {} : { commit }) });
444
+ }
445
+ return options;
446
+ }
447
+ async function hStatus(req, ctx) {
448
+ const cfg = ctx.endpoint();
449
+ const endpoint = await probeEndpoint(ctx);
450
+ const active = activeRuns(ctx.stateRoots);
451
+
452
+ // law (unreadable ⇒ active — guardLifecycle refuses restarts on
453
+ // it), but the STATUS view was asserting every unsettled sidecar
454
+ // as a concurrent active run: 60+ `active_runs` against the flow
455
+ // door's one-active-run-machine-wide contract. The engine's own
456
+ // queue corroborates: ComfyUI executes serially, so a reachable
457
+ // engine reporting an empty queue cannot be executing ANY claim —
458
+ // those rows are historical (dead-process sidecars that never
459
+ // settled). The guard keeps the raw census; only the view splits.
460
+ const engineQueue = await engineQueueView(ctx);
461
+ const engineIdle = engineQueue !== null && engineQueue.running === 0 && engineQueue.pending === 0;
462
+ const activeView = engineIdle ? [] : active;
463
+ const staleClaims = engineIdle
464
+ ? active.map((name) => name + " (claimed live; engine queue empty — historical: the sidecar never settled; the boot sweep retires its own root at restart)")
465
+ : [];
466
+ const routing = { mode: cfg["provision"] === "managed" ? "managed" : "byo" };
467
+ let manager = {};
468
+ let comfyuiVersions = [];
469
+ let comfyuiVersionsDetail;
470
+ if (endpoint.reachable) {
471
+ const [versionResult, queueResult, versionsResult] = await Promise.allSettled([
472
+ managerGet(base(ctx), "/manager/version", { ctx, timeoutMs: 1500 }),
473
+ managerGet(base(ctx), "/manager/queue/status", { ctx, timeoutMs: 1500 }),
474
+ managerGet(base(ctx), "/comfyui_manager/comfyui_versions", { ctx, timeoutMs: 1500 }),
475
+ ]);
476
+ if (signalIsAborted(ctx.signal))
477
+ throw abortReason(ctx.signal);
478
+ const managerFailure = [versionResult, queueResult].find((result) => result.status === "rejected");
479
+ if (managerFailure?.status === "rejected") {
480
+ manager = { reachable: false, reason: managerFailure.reason.message.slice(0, 160) };
481
+ }
482
+ else {
483
+ const version = versionResult;
484
+ const queue = queueResult;
485
+ manager = { reachable: true, version: version.value, queue: queue.value };
486
+ }
487
+ if (versionsResult.status === "fulfilled") {
488
+ comfyuiVersions = versionOptions(versionsResult.value);
489
+ }
490
+ else {
491
+ comfyuiVersionsDetail = versionsResult.reason.message;
492
+ }
493
+ }
494
+ else {
495
+ manager = { reachable: false, reason: "endpoint not reachable" };
496
+ }
497
+ let resources = [];
498
+ let resourcesDetail;
499
+
500
+ // reported IN WORDS and the rest of the status still answers. Before,
501
+ // this line was `ctx.provisioning.reconcile(...)` behind a try/catch,
502
+ // so an absent seat produced the TypeError text
503
+ // "Cannot read properties of undefined (reading 'reconcile')" as a
504
+ // status FIELD — a crash wearing a data costume, on the one door an
505
+ // operator reads to decide what the estate is doing.
506
+ const provisionSeat = provisioningOrAbsent(ctx);
507
+ if (provisionSeat === undefined) {
508
+ resourcesDetail = "the provisioning seat is not mounted on this lane (absent, not broken): no resource reconciliation — everything else in this status is live";
509
+ }
510
+ else {
511
+ try {
512
+ resources = await withManageTimeout(req, ctx, (signal) => provisionSeat.reconcile(undefined, signal), STATUS_RECONCILE_MS);
513
+ }
514
+ catch (error) {
515
+ if (signalIsAborted(ctx.signal))
516
+ throw abortReason(ctx.signal);
517
+ resourcesDetail = error instanceof Error ? error.message : String(error);
518
+ }
519
+ }
520
+ const normalized = await normalizedResources(resources, provisionSeat);
521
+ const operations = operationRows(normalized);
522
+ const resourceRows = normalized.map((resource) => ({
523
+ ...resource,
524
+ ...(resource.operationId === undefined ? {} : { operation_id: resource.operationId }),
525
+ }));
526
+ const state = endpoint.reachable ? "up" : "down";
527
+ const nextAction = nextActionFor(endpoint.reachable, normalized, routing.mode === "managed");
528
+ const catalog = modelOptions(ctx.models);
529
+ const data = {
530
+ state,
531
+ next_action: nextAction,
532
+ endpoint,
533
+ manager: {
534
+ ...manager,
535
+ security: managerSecurity(ctx.repoRoot),
536
+ unit: ctx.comfyUnit,
537
+ operations,
538
+ },
539
+ comfyui_versions: comfyuiVersions,
540
+ ...(comfyuiVersionsDetail === undefined ? {} : { comfyui_versions_detail: comfyuiVersionsDetail }),
541
+ model_options: catalog.options,
542
+ ...(catalog.detail === undefined ? {} : { model_options_detail: catalog.detail }),
543
+ active_runs: activeView,
544
+ ...(engineQueue === null ? {} : { engine_queue: engineQueue }),
545
+ ...(staleClaims.length > 0 ? { stale_claims: staleClaims } : {}),
546
+ ...(active.length > 1 && !engineIdle
547
+ ? { active_runs_note: active.length + " claims; the one-run law bounds machine-wide actives at 1 — the surplus is unsettled sidecars (historical); the engine queue corroborates only when empty" }
548
+ : {}),
549
+ engine_boot: engineBootRow(ctx),
550
+ routing,
551
+ auto_provision: ctx.autoProvision,
552
+ resources: resourceRows,
553
+ operations,
554
+ ...(resourcesDetail === undefined ? {} : { resources_detail: resourcesDetail }),
555
+ };
556
+ return ok(req.action, endpoint.reachable ? "server up" : "server not reachable", data);
557
+ }
558
+ async function hLogs(req, ctx) {
559
+ throwIfAborted(ctx.signal);
560
+ const tail = Math.max(1, Math.min(Math.trunc(req.tail), 2000));
561
+ let stdout;
562
+ try {
563
+ const out = await execFileAsync("journalctl", ["--user", "-u", ctx.comfyUnit, "-n", String(tail), "--no-pager", "-o", "cat"], {
564
+ timeout: 15 * 1000,
565
+ encoding: "utf8",
566
+ signal: ctx.signal,
567
+ });
568
+ stdout = out.stdout;
569
+ }
570
+ catch (error) {
571
+ if (signalIsAborted(ctx.signal))
572
+ throw abortReason(ctx.signal);
573
+ throw unavailable("logs need the estate deployment's journal (unit " + ctx.comfyUnit + "): " +
574
+ error.message.slice(0, 120));
575
+ }
576
+ throwIfAborted(ctx.signal);
577
+ const lines = stdout.split("\n").filter((ln) => ln !== "");
578
+ return ok(req.action, lines.length + " log line(s) from " + ctx.comfyUnit, lines);
579
+ }
580
+ async function hSearch(req, ctx) {
581
+ need(req, "query");
582
+ const cfg = ctx.endpoint();
583
+ estateOnly(req, cfg);
584
+ let doc;
585
+ try {
586
+ doc = await managerGet(base(ctx), "/externalmodel/getlist?mode=cache", { ctx, timeoutMs: railMs(req) });
587
+ }
588
+ catch (e) {
589
+ throw mapRail(e, req.action);
590
+ }
591
+ const models = doc["models"] ?? [];
592
+ const q = req.query.toLowerCase();
593
+ const hits = models.filter((m) => {
594
+ const hay = [m["name"], m["type"], m["base"], m["filename"]].map((v) => String(v ?? "").toLowerCase()).join(" ");
595
+ return hay.includes(q);
596
+ }).slice(0, 50);
597
+ return ok(req.action, hits.length + " hit(s) from Manager external catalog for '" + req.query + "'", hits);
598
+ }
599
+ async function withManageTimeout(req, ctx, work, boundMs = railMs(req)) {
600
+ throwIfAborted(ctx.signal);
601
+ // The fuse is dsh-timeout's deadline (the caller signal and the
602
+ // timer fuse into one signal; TimeoutReason carries the win); the
603
+ // 504 voice and its state payload are ours.
604
+ const dl = deadlineOf(ctx.signal, boundMs, "MANAGE_OP");
605
+ const boundAt = Date.now() + boundMs;
606
+ const timedOut = () => timeoutOf(dl.signal, "MANAGE_OP") !== undefined;
607
+ try {
608
+ const value = await work(dl.signal);
609
+
610
+ // RESOLVED, its value is real — reporting 504 for a result the
611
+ // caller could have used (the old Date.now arm fired on work that
612
+ // landed one tick past boundAt) serves nobody. An unresolved work
613
+ // still dies at the deadline below (the abort arm).
614
+ if (signalIsAborted(ctx.signal))
615
+ throw abortReason(ctx.signal);
616
+ return value;
617
+ }
618
+ catch (error) {
619
+ if (signalIsAborted(ctx.signal))
620
+ throw abortReason(ctx.signal);
621
+ if (timedOut() || dl.signal.aborted) {
622
+ throw new Refused(504, "manage operation timed out", {
623
+ state: "timeout",
624
+ next_action: "status",
625
+ });
626
+ }
627
+ throw error;
628
+ }
629
+ finally {
630
+ dl[Symbol.dispose]();
631
+ }
632
+ }
633
+ function externalModelPath(req) {
634
+ const rawFolder = req.relative_path.startsWith("models/")
635
+ ? req.relative_path.slice("models/".length)
636
+ : req.relative_path === "" ? "checkpoints" : req.relative_path;
637
+ const folder = rawFolder === "models" ? "" : rawFolder;
638
+ if (folder.includes("..") || folder.startsWith("/")) {
639
+ throw badRequest("relative_path must stay under the models root: " + req.relative_path);
640
+ }
641
+ // THE NO-LORAS-REMOTE LAW, enforced at the one fetch door: the
642
+ // operator's rule ("THERE SHOULD NOT BE A LORAS REMOTE / IT'S
643
+ // ALL BUILT IN") — a LoRA arrives by COPY through lora_install
644
+ // or the user rows file, never by url. Before this arm the door
645
+ // could fetch into models/loras and contradict the stated law.
646
+ if (folder === "loras" || folder.startsWith("loras/")) {
647
+ throw badRequest("download_model refuses the loras dir — LoRAs arrive by copy or upload (lora_install), never by url");
648
+ }
649
+
650
+ // rides the SSOT the cell artifacts ride — a URL's query and
651
+ // fragment are never the file's name ("...safetensors?download=1"
652
+ // landed bytes under a name the engine never listed), a trailing
653
+ // slash names a directory (the empty name refuses by the bare-name
654
+ // fence below), and %XX escapes decode to the true name.
655
+ const filename = req.filename !== "" ? req.filename : artifactFileName(req.url);
656
+ // The bare-name fence rides the SSOT (the dry-sweep's N5):
657
+ // segmentConfined owns the bytes of a legal segment — inner dots
658
+ // are legal ("model..ckpt" stays under the root; the traversal
659
+ // fence is the slash arm, since the SSOT judges one segment) and
660
+ // the NUL arm is its behavioral wall. The old hand-roll refused
661
+ // every inner ".." and had drifted from the grammar every other
662
+ // door rides.
663
+ if (filename.includes("/") || !segmentConfined(filename)) {
664
+ throw badRequest("filename must be a bare name under the models root");
665
+ }
666
+ return { relativePath: folder, filename };
667
+ }
668
+ function safeProvisionItems(result, plan) {
669
+ const plans = new Map((plan?.items ?? []).map((item) => [item.key, item]));
670
+ return result.items.map((item) => {
671
+ const declaration = plans.get(item.key);
672
+ const name = declaration === undefined
673
+ ? undefined
674
+ : declaration.kind === "model" ? declaration.name : declaration.id;
675
+ return {
676
+ key: item.key,
677
+ kind: item.kind,
678
+ state: item.state,
679
+ outcome: item.outcome,
680
+ ...(name === undefined ? {} : { name }),
681
+ ...(item.path === undefined ? {} : { path: item.path }),
682
+ ...(item.sha256 === undefined ? {} : { sha256: item.sha256 }),
683
+ ...(item.integrity === undefined ? {} : { integrity: item.integrity }),
684
+ ...(item.errorCode === undefined ? {} : { errorCode: item.errorCode }),
685
+ ...(item.detail === undefined ? {} : { detail: item.detail }),
686
+ };
687
+ });
688
+ }
689
+ function operationRow(name, result, ref, plan) {
690
+ const first = result.items[0];
691
+ return {
692
+ operation_id: result.operationId,
693
+ name,
694
+ ref,
695
+ ...(first?.path === undefined ? {} : { path: first.path }),
696
+ state: result.state,
697
+ outcome: result.outcome,
698
+ items: safeProvisionItems(result, plan),
699
+ restart_required: result.restartRequired,
700
+ next_action: result.restartRequired || result.state === "restart_required" ? "restart" : "status",
701
+ };
702
+ }
703
+ function provisionEnvelope(action, result, extra = {}, operations = []) {
704
+ const success = result.state === "active" || result.state === "restart_required";
705
+ const code = success ? 200 : result.state === "blocked" || result.state === "cancelled" ? 409 : 500;
706
+ const detail = result.detail ?? `${result.state} (${result.items.length} item(s))`;
707
+ const errors = result.items
708
+ .filter((item) => item.errorCode !== undefined)
709
+ .map((item) => ({ file: item.key, error: item.detail ?? item.errorCode }));
710
+ const rows = operations.length === 0
711
+ ? [operationRow(result.ref.id, result, result.ref)]
712
+ : operations;
713
+ const nextAction = result.restartRequired || result.state === "restart_required"
714
+ ? "restart"
715
+ : result.state === "partial" || result.state === "failed" || result.state === "cancelled"
716
+ ? action
717
+ : "status";
718
+ const items = operations.length === 0
719
+ ? safeProvisionItems(result)
720
+ : operations.flatMap((row) => row["items"]);
721
+ const data = {
722
+ ...extra,
723
+ operation_id: result.operationId,
724
+ state: result.state,
725
+ items,
726
+ operations: rows,
727
+ restart_required: result.restartRequired,
728
+ partial: result.state === "partial",
729
+ next_action: nextAction,
730
+ ...(errors.length === 0 ? {} : { errors }),
731
+ };
732
+ return [
733
+ code,
734
+ {
735
+ action,
736
+ ok: success,
737
+ detail,
738
+ status: code,
739
+ state: result.state,
740
+ next_action: nextAction,
741
+ operation_id: result.operationId,
742
+ operations: rows,
743
+ items,
744
+ partial: result.state === "partial",
745
+ restart_required: result.restartRequired,
746
+ ...(Array.isArray(extra["requested"]) ? { requested: extra["requested"] } : {}),
747
+ ...(Array.isArray(extra["succeeded"]) ? { succeeded: extra["succeeded"] } : {}),
748
+ ...(Array.isArray(extra["missed"]) ? { missed: extra["missed"] } : {}),
749
+ ...(Array.isArray(extra["misses"]) ? { misses: extra["misses"] } : {}),
750
+ data,
751
+ },
752
+ ];
753
+ }
754
+ function failedProvisionResult(ref, plan, detail, index) {
755
+ return {
756
+ operationId: "failed-" + ref.kind + "-" + String(index),
757
+ ref,
758
+ state: "failed",
759
+ outcome: "failed",
760
+ operationState: "failed",
761
+ items: plan.items.map((item) => ({
762
+ key: item.key,
763
+ kind: item.kind,
764
+ state: "failed",
765
+ outcome: "failed",
766
+ errorCode: "manage/provision-failed",
767
+ detail,
768
+ })),
769
+ restartRequired: false,
770
+ detail,
771
+ };
772
+ }
773
+ function mergeProvisionResults(results) {
774
+ const items = results.flatMap((result) => result.items);
775
+ const hasSuccess = results.some((result) => result.state === "active" || result.state === "restart_required");
776
+ const hasFailure = results.some((result) => result.state !== "active" && result.state !== "restart_required");
777
+ const state = hasFailure
778
+ ? hasSuccess
779
+ ? "partial"
780
+ : results.every((result) => result.state === "blocked")
781
+ ? "blocked"
782
+ : results.some((result) => result.state === "cancelled")
783
+ ? "cancelled"
784
+ : "failed"
785
+ : results.some((result) => result.state === "restart_required")
786
+ ? "restart_required"
787
+ : "active";
788
+ return {
789
+ state,
790
+ operationId: results.length === 1
791
+ ? results[0].operationId
792
+ : "aggregate:" + results.map((result) => result.operationId).join("+"),
793
+ items,
794
+ restartRequired: results.some((result) => result.restartRequired),
795
+ ...(state === "partial" ? { detail: "partial provisioning result" } : {}),
796
+ };
797
+ }
798
+ async function hInstallExtension(req, ctx) {
799
+ if (req.nodes.length === 0)
800
+ throw badRequest("install_extension requires: nodes");
801
+ estateOnly(req, ctx.endpoint());
802
+
803
+ // below turns any plan/ensure throw into a "missed" row, so a
804
+ // seatless lane answered "extension is not declared" — blaming the
805
+ // DECLARATION for a missing provisioner. Ask once, up front, so the
806
+ // refusal is the true one and no node is attempted at all.
807
+ const provisioner = provisioningOf(ctx);
808
+ return await withManageTimeout(req, ctx, async (signal) => {
809
+ const results = [];
810
+ const misses = [];
811
+ const missed = [];
812
+ for (const [index, node] of req.nodes.entries()) {
813
+ throwIfAborted(ctx.signal);
814
+ throwIfAborted(signal);
815
+ const ref = { kind: "extension", id: node };
816
+ let plan;
817
+ try {
818
+ plan = await awaitWithAbort(provisioner.plan(ref), signal);
819
+ throwIfAborted(signal);
820
+ const result = await provisioner.ensure(ref, undefined, signal);
821
+ results.push({ node, ref, plan, result });
822
+ if (result.state !== "active" && result.state !== "restart_required") {
823
+ missed.push(node);
824
+ misses.push(node + ": " + (result.detail ?? result.state));
825
+ }
826
+ }
827
+ catch (error) {
828
+ if (signalIsAborted(ctx.signal))
829
+ throw abortReason(ctx.signal);
830
+ if (signal.aborted)
831
+ throw abortReason(signal);
832
+ const detail = error instanceof Error ? error.message : String(error);
833
+ if (plan !== undefined)
834
+ results.push({ node, ref, plan, result: failedProvisionResult(ref, plan, detail, index) });
835
+ missed.push(node);
836
+ misses.push(node + ": " + detail);
837
+ }
838
+ }
839
+ const requested = [...req.nodes];
840
+ const succeeded = results
841
+ .filter(({ result }) => result.state === "active" || result.state === "restart_required")
842
+ .map(({ node }) => node);
843
+ const operations = results.map(({ node, ref, plan, result }) => operationRow(node, result, ref, plan));
844
+ if (results.length === 0) {
845
+ throw new Refused(404, "extension is not declared: " + misses.join(", "), {
846
+ state: "failed",
847
+ requested,
848
+ succeeded,
849
+ missed,
850
+ misses,
851
+ partial: false,
852
+ items: [],
853
+ operations: [],
854
+ next_action: "install_extension",
855
+ });
856
+ }
857
+ const merged = mergeProvisionResults(results.map(({ result }) => result));
858
+ const state = missed.length > 0 && succeeded.length > 0
859
+ ? "partial"
860
+ : merged.state;
861
+ const result = {
862
+ operationId: merged.operationId,
863
+ ref: { kind: "extension", id: req.nodes.join(",") },
864
+ state,
865
+ outcome: state,
866
+ operationState: state === "partial"
867
+ ? "installed"
868
+ : state === "cancelled"
869
+ ? "failed"
870
+ : state,
871
+ items: merged.items,
872
+ restartRequired: merged.restartRequired,
873
+ ...(state === "partial" ? { detail: `partial (${succeeded.length}/${requested.length} extension(s) succeeded)` } : {}),
874
+ };
875
+ return provisionEnvelope(req.action, result, {
876
+ requested,
877
+ succeeded,
878
+ missed,
879
+ misses,
880
+ queued: merged.items.filter((item) => item.state === "restart_required" || item.state === "active").map((item) => item.key),
881
+ partial: state === "partial",
882
+ }, operations);
883
+ });
884
+ }
885
+
886
+
887
+
888
+
889
+
890
+
891
+
892
+ function operatorConfirmGate(req, door) {
893
+ if (req.operator_confirmed === true)
894
+ return null;
895
+ return [
896
+ 409,
897
+ {
898
+ action: door,
899
+ ok: false,
900
+ state: "conflict",
901
+ detail: door + ": external acquisitions land bytes from a caller-named URL — pass operator_confirmed=true " +
902
+ "(the human's approval) to proceed. The flag is recorded with the operation.",
903
+ next_action: "operator_confirmed",
904
+ },
905
+ ];
906
+ }
907
+ async function hInstallExtensionUrl(req, ctx) {
908
+ need(req, "url");
909
+ estateOnly(req, ctx.endpoint());
910
+ // THE SEAT ASKS FIRST (the hProvisionModel order law): a seatless
911
+ // lane names its own 503 before any human flag is demanded
912
+ const provisioner = provisioningOf(ctx);
913
+ const confirmed = operatorConfirmGate(req, "install_extension_url");
914
+ if (confirmed !== null)
915
+ return confirmed;
916
+ const result = await withManageTimeout(req, ctx, (signal) => provisioner.acquireExternal({ kind: "extension", url: req.url, ...(req.ref === "" ? {} : { ref: req.ref }) }, { operatorConfirmed: req.operator_confirmed }, signal));
917
+ return provisionEnvelope(req.action, result);
918
+ }
919
+ async function hDownloadModel(req, ctx) {
920
+ need(req, "url");
921
+ estateOnly(req, ctx.endpoint());
922
+ const path = externalModelPath(req);
923
+ // THE SEAT ASKS FIRST (the hProvisionModel order law), then the
924
+ // gate below the shape guards: a request refused on its own merits
925
+ // never needs the human's flag
926
+ const provisioner = provisioningOf(ctx);
927
+ const confirmed = operatorConfirmGate(req, "download_model");
928
+ if (confirmed !== null)
929
+ return confirmed;
930
+ const result = await withManageTimeout(req, ctx, (signal) => provisioner.acquireExternal({
931
+ kind: "model",
932
+ url: req.url,
933
+ relativePath: path.relativePath,
934
+ filename: path.filename,
935
+ }, { operatorConfirmed: req.operator_confirmed }, signal));
936
+
937
+ // living process must not leave the boot-time /object_info doc
938
+ // serving. The old restartRequired guard was dead — the service
939
+ // answers models "active" on every path (only extension installs
940
+ // arm restart_required), so model landings never dropped and the
941
+ // census stayed boot-stale until a reboot.
942
+ invalidateLiveObjectInfo(ctx);
943
+ ctx.rearmWeights?.();
944
+ return provisionEnvelope(req.action, result);
945
+ }
946
+ function familyModelDeclared(ctx, id) {
947
+ return ctx.models.allDecls().some((decl) => decl.id === id || decl.variants.some((variant) => variant.route === id || variant.cells.some((cell) => cell.route === id)));
948
+ }
949
+ async function hProvisionModel(req, ctx) {
950
+ need(req, "model");
951
+ estateOnly(req, ctx.endpoint());
952
+
953
+ // attempts sit inside catches that end in notFound(...), so a
954
+
955
+ // was perfectly well declared — the missing provisioner wearing the
956
+ // wrong refusal. Ask once, first; then the family→card fallback keeps
957
+ // its meaning.
958
+ const provisioner = provisioningOf(ctx);
959
+ return await withManageTimeout(req, ctx, async (signal) => {
960
+ const family = {
961
+ kind: "model",
962
+ owner: "family",
963
+ id: req.model,
964
+ ...(req.variant === "" ? {} : { variant: req.variant }),
965
+ ...(req.quant === "" ? {} : { quant: req.quant }),
966
+ };
967
+ let ref = family;
968
+ let plan;
969
+ try {
970
+ plan = await awaitWithAbort(provisioner.plan(family), signal);
971
+ }
972
+ catch (error) {
973
+ if (signalIsAborted(ctx.signal))
974
+ throw abortReason(ctx.signal);
975
+ if (signal.aborted)
976
+ throw abortReason(signal);
977
+ if (familyModelDeclared(ctx, req.model)) {
978
+ throw notFound(error instanceof Error ? error.message : String(error));
979
+ }
980
+ ref = {
981
+ kind: "model",
982
+ owner: "card",
983
+ id: req.model,
984
+ ...(req.variant === "" ? {} : { variant: req.variant }),
985
+ ...(req.quant === "" ? {} : { quant: req.quant }),
986
+ };
987
+ try {
988
+ plan = await awaitWithAbort(provisioner.plan(ref), signal);
989
+ }
990
+ catch (error) {
991
+ if (signalIsAborted(ctx.signal))
992
+ throw abortReason(ctx.signal);
993
+ if (signal.aborted)
994
+ throw abortReason(signal);
995
+ throw notFound(error instanceof Error ? error.message : String(error));
996
+ }
997
+ }
998
+ throwIfAborted(signal);
999
+ const result = await provisioner.ensure(ref, undefined, signal);
1000
+ // THE WEIGHTS LANDED UNDER A LIVING PROCESS (cold-drive run 6,
1001
+
1002
+
1003
+ // boot-time /object_info doc — the next compose read an empty combo
1004
+ // ("unet_name allows 0 values"). The engine's own folder scan is
1005
+ // mtime-live, so dropping the cached doc makes the landing visible
1006
+ // without a reboot (same door law as loraInstalled below).
1007
+
1008
+ // dead guard — model items never arm it (service answers "active";
1009
+ // only extensions yield restart_required), so the drop must not
1010
+ // wait on a flag that never fires.
1011
+ invalidateLiveObjectInfo(ctx);
1012
+ ctx.rearmWeights?.();
1013
+ return provisionEnvelope(req.action, result, {
1014
+ model: req.model,
1015
+ files: result.items.filter((item) => item.state === "active").map((item) => item.key),
1016
+ present: result.items.filter((item) => item.state === "active").map((item) => item.key),
1017
+ }, [operationRow(req.model, result, ref, plan)]);
1018
+ });
1019
+ }
1020
+ /** THE F9 ACQUISITION DOOR (run-press acquisition — ONE door, TWO
1021
+ * callers): the bench popup's Download button and the agent's
1022
+ * comfy_manage acquire_weight seat both land here. It starts the
1023
+ * fetch WITHOUT awaiting the landing (the progress ledger counts
1024
+ * real landed bytes) and returns the operation id at once; the
1025
+ * tracker polls this SAME action with {operation_id} for
1026
+ * bytes/total. The fetch itself rides provisioner.ensure (the
1027
+ * existing fetcher — never a second fetcher). */
1028
+ async function hAcquireWeight(req, ctx) {
1029
+ const provisioner = provisioningOf(ctx);
1030
+ // THE POLL (the tracker's read): same action, operation id only —
1031
+ // no model, no fetch, no wait. Unknown ids 404 (never a fake
1032
+ // zero — the tracker must render the truth).
1033
+ if (req.operation_id !== "") {
1034
+ if (typeof provisioner.progressOf !== "function") {
1035
+ throw unavailable("acquire_weight progress is not configured on this lane");
1036
+ }
1037
+ const progress = provisioner.progressOf(req.operation_id);
1038
+ if (progress === null || progress === undefined) {
1039
+ throw notFound("unknown acquire_weight operation: " + req.operation_id);
1040
+ }
1041
+
1042
+ // the files (same door law as hProvisionModel); the next read
1043
+ // re-fetches once and sees the landed weights
1044
+ if (progress.state === "installed" ||
1045
+ progress.state === "restart_required" ||
1046
+ progress.state === "active") {
1047
+ invalidateLiveObjectInfo(ctx);
1048
+ // the presence face re-arms with the doc: the files the engine
1049
+ // will serve are the files the board's present flags claim
1050
+ ctx.rearmWeights?.();
1051
+ }
1052
+ return ok(req.action, "acquire_weight " + progress.operationId + ": " + String(progress.bytes) + "/" + String(progress.total)
1053
+ + " bytes (" + progress.state + ")", {
1054
+ operation_id: progress.operationId,
1055
+ state: progress.state,
1056
+ bytes: progress.bytes,
1057
+ total: progress.total,
1058
+ next_action: "acquire_weight",
1059
+ ...(progress.detail === undefined ? {} : { detail: progress.detail }),
1060
+ });
1061
+ }
1062
+ // THE START (the Download press): model required, the missing file
1063
+ // rides filename for DISPLAY only (the DECL owns the fetch source —
1064
+ // the names-only law). Returns the operation id at once; the fetch
1065
+ // lands in the background and the tracker polls it above.
1066
+ need(req, "model");
1067
+ estateOnly(req, ctx.endpoint());
1068
+ if (typeof provisioner.startWeightAcquire !== "function" || typeof provisioner.progressOf !== "function") {
1069
+ throw unavailable("acquire_weight is not configured on this lane");
1070
+ }
1071
+ const startAcquire = provisioner.startWeightAcquire;
1072
+ const family = {
1073
+ kind: "model",
1074
+ owner: "family",
1075
+ id: req.model,
1076
+ ...(req.variant === "" ? {} : { variant: req.variant }),
1077
+ ...(req.quant === "" ? {} : { quant: req.quant }),
1078
+ };
1079
+ // The provisioner hops ride the same deadline fuse as every
1080
+ // sibling arm (audit N-E2): a stalled provisioner answers 504
1081
+ // inside the request's own railMs, never hangs the door.
1082
+ let ref = family;
1083
+ let plan = null;
1084
+ try {
1085
+ plan = await withManageTimeout(req, ctx, async () => await provisioner.plan(family));
1086
+ }
1087
+ catch (error) {
1088
+ // the fuse's own refusal keeps its voice (audit F1): a deadline
1089
+ // maps to 504 here, never into the unknown-model 404 below
1090
+ if (error instanceof Refused)
1091
+ throw error;
1092
+ if (familyModelDeclared(ctx, req.model)) {
1093
+ throw notFound(error instanceof Error ? error.message : String(error));
1094
+ }
1095
+ ref = {
1096
+ kind: "model",
1097
+ owner: "card",
1098
+ id: req.model,
1099
+ ...(req.variant === "" ? {} : { variant: req.variant }),
1100
+ ...(req.quant === "" ? {} : { quant: req.quant }),
1101
+ };
1102
+ try {
1103
+ plan = await withManageTimeout(req, ctx, async () => await provisioner.plan(ref));
1104
+ }
1105
+ catch (nested) {
1106
+ if (nested instanceof Refused)
1107
+ throw nested;
1108
+ throw notFound(nested instanceof Error ? nested.message : String(nested));
1109
+ }
1110
+ }
1111
+
1112
+
1113
+ // downloads every row of a multi-GB family. The name maps to plan
1114
+ // item keys exactly as the provisioner's own options.items filter
1115
+ // keys them (kind model → name, else id); an unknown filename is
1116
+ // the item-not-found refusal, never a whole-family fetch.
1117
+ let acquireOptions;
1118
+ if (req.filename !== "" && plan !== null) {
1119
+ const wanted = plan.items
1120
+ .filter((item) => (item.kind === "model" ? item.name : item.id) === req.filename)
1121
+ .map((item) => (item.kind === "model" ? item.name : item.id));
1122
+ if (wanted.length === 0) {
1123
+ throw badRequest(`acquire_weight file '${req.filename}' matches no provision row of '${req.model}' (item-not-found) — refusing to fetch the whole family for a one-file miss`);
1124
+ }
1125
+ acquireOptions = { items: wanted };
1126
+ }
1127
+ // THE BUSY MAP (audit I-S4): a plane at its concurrency cap is a
1128
+ // wait, not a failure — the 429 carries retry_after_ms and points
1129
+ // the caller back at the poll arm
1130
+ let operationId;
1131
+ try {
1132
+ operationId = await withManageTimeout(req, ctx, async () => await startAcquire.call(provisioner, ref, acquireOptions));
1133
+ }
1134
+ catch (error) {
1135
+ if (error instanceof AcquireBusyError) {
1136
+ return [429, {
1137
+ action: req.action,
1138
+ ok: false,
1139
+ state: "busy",
1140
+ status: 429,
1141
+ detail: error.message,
1142
+ next_action: "acquire_weight",
1143
+ retry_after_ms: error.retryAfterMs,
1144
+ }];
1145
+ }
1146
+ throw error;
1147
+ }
1148
+ const progress = provisioner.progressOf(operationId);
1149
+ const bytes = progress?.bytes ?? 0;
1150
+ const total = progress?.total ?? 0;
1151
+ const state = progress?.state ?? "acquiring";
1152
+ const file = req.filename !== "" ? " (" + req.filename + ")" : "";
1153
+ return ok(req.action, "acquiring " + req.model + file + " — " + String(bytes) + "/" + String(total)
1154
+ + " bytes (poll acquire_weight operation_id=" + operationId + ")", {
1155
+ operation_id: operationId,
1156
+ operationId,
1157
+ state,
1158
+ bytes,
1159
+ total,
1160
+ model: req.model,
1161
+ ...(req.filename === "" ? {} : { file: req.filename, filename: req.filename }),
1162
+ ...(req.variant === "" ? {} : { variant: req.variant }),
1163
+ ...(req.quant === "" ? {} : { quant: req.quant }),
1164
+ next_action: "acquire_weight",
1165
+ });
1166
+ }
1167
+ async function hRestart(req, ctx) {
1168
+ guardLifecycle(req, ctx);
1169
+ const cfg = ctx.endpoint();
1170
+ estateOnly(req, cfg);
1171
+
1172
+ // call so a run pressed mid-reboot refuses instead of tearing.
1173
+ const releaseLifecycle = holdLifecycle(req.action);
1174
+ try {
1175
+ await managerPost(base(ctx), "/manager/reboot", {}, { ctx, timeoutMs: 10_000 });
1176
+
1177
+ // await — the cached /object_info doc must not outlive it. The
1178
+ // drop rides a finally so an abort inside the receipt write
1179
+ // cannot skip it (the abort still propagates after the drop).
1180
+ try {
1181
+ await recordEngineBoot(ctx, "estate restart");
1182
+ }
1183
+ finally {
1184
+
1185
+ // the cached /object_info doc must not outlive it (the refresh
1186
+
1187
+ invalidateLiveObjectInfo(ctx);
1188
+ }
1189
+ return ok(req.action, "reboot issued (systemd re-spawns the engine)", { next_action: "status" });
1190
+ }
1191
+ catch (e) {
1192
+ if (e instanceof ManagerApiError && e.status === 503) {
1193
+ // The vendor reboots by exiting: the connection can drop after
1194
+ // the 200 is sent — same honest answer.
1195
+ if (/fetch failed|ECONNRESET|socket/i.test(e.text)) {
1196
+ try {
1197
+ await recordEngineBoot(ctx, "estate restart (connection dropped mid-answer)");
1198
+ }
1199
+ finally {
1200
+ invalidateLiveObjectInfo(ctx);
1201
+ }
1202
+ return ok(req.action, "reboot issued (connection closed by restart)", { next_action: "status" });
1203
+ }
1204
+ throw mapManagerRefused(e, req.action);
1205
+ }
1206
+ throw mapRail(e, req.action);
1207
+ }
1208
+ finally {
1209
+ releaseLifecycle();
1210
+ }
1211
+ }
1212
+ async function hStop(req, ctx) {
1213
+ guardLifecycle(req, ctx);
1214
+ estateOnly(req, ctx.endpoint());
1215
+
1216
+ // systemctl call so a run pressed mid-stop refuses.
1217
+ const releaseLifecycle = holdLifecycle(req.action);
1218
+ try {
1219
+ return await systemctl(req, "stop", ctx.comfyUnit, ctx.signal);
1220
+ }
1221
+ finally {
1222
+ releaseLifecycle();
1223
+ }
1224
+ }
1225
+ async function hLaunch(req, ctx) {
1226
+ estateOnly(req, ctx.endpoint());
1227
+ return await systemctl(req, "start", ctx.comfyUnit, ctx.signal);
1228
+ }
1229
+ async function hUpdate(req, ctx) {
1230
+ if (req.target !== "comfy") {
1231
+ throw badRequest("update target must be comfy — comfy-cli is retired (the built-in manager updates ComfyUI)");
1232
+ }
1233
+ guardLifecycle(req, ctx);
1234
+ const cfg = ctx.endpoint();
1235
+ estateOnly(req, cfg);
1236
+
1237
+ // calls so a run pressed mid-update refuses instead of tearing.
1238
+ const releaseLifecycle = holdLifecycle(req.action);
1239
+ try {
1240
+ await managerPost(base(ctx), "/manager/queue/update_comfyui", {}, { ctx, timeoutMs: 10_000 });
1241
+ await managerPost(base(ctx), "/manager/queue/start", {}, { ctx, timeoutMs: 10_000 });
1242
+ const queue = await awaitQueueDrained(ctx, req);
1243
+ if (queue["timed_out"] === true) {
1244
+ throw new Refused(504, "update(comfy) queue did not drain before the deadline", {
1245
+ state: "timeout",
1246
+ queue,
1247
+ next_action: "status",
1248
+ });
1249
+ }
1250
+ return ok(req.action, "update(comfy) queued through the manager", {
1251
+ state: "completed",
1252
+ queue,
1253
+ next_action: "status",
1254
+ });
1255
+ }
1256
+ catch (e) {
1257
+ if (signalIsAborted(ctx.signal))
1258
+ throw abortReason(ctx.signal);
1259
+ if (e instanceof Refused)
1260
+ throw e;
1261
+ throw mapRail(e, req.action);
1262
+ }
1263
+ finally {
1264
+ releaseLifecycle();
1265
+ }
1266
+ }
1267
+ async function hSwitchVersion(req, ctx) {
1268
+ need(req, "version");
1269
+ guardLifecycle(req, ctx);
1270
+ const cfg = ctx.endpoint();
1271
+ estateOnly(req, cfg);
1272
+
1273
+ // switch so a run pressed mid-switch refuses instead of tearing.
1274
+ const releaseLifecycle = holdLifecycle(req.action);
1275
+ try {
1276
+ const doc = await managerGet(base(ctx), "/comfyui_manager/comfyui_versions", {
1277
+ ctx, timeoutMs: 30_000,
1278
+ });
1279
+ const versions = versionOptions(doc).map((option) => option.id);
1280
+ if (!versions.includes(req.version)) {
1281
+ throw notFound("version " + req.version + " not available (have: " + versions.slice(0, 6).join(", ") + "…)");
1282
+ }
1283
+ await managerPost(base(ctx), "/comfyui_manager/comfyui_switch_version", { ver: req.version }, {
1284
+ ctx, timeoutMs: railMs(req),
1285
+ });
1286
+ }
1287
+ catch (e) {
1288
+ throw mapRail(e, req.action);
1289
+ }
1290
+ finally {
1291
+ releaseLifecycle();
1292
+ }
1293
+ return ok(req.action, "switch to " + req.version + " issued (restart required)", {
1294
+ state: "restart_required",
1295
+ restart_required: true,
1296
+ next_action: "restart",
1297
+ });
1298
+ }
1299
+ async function hFree(req, ctx) {
1300
+ guardLifecycle(req, ctx);
1301
+ const b = base(ctx);
1302
+ if (b === "")
1303
+ throw planeUnavailable(b, "no endpoint url");
1304
+
1305
+ // call so a run pressed mid-free refuses instead of tearing.
1306
+ const releaseLifecycle = holdLifecycle(req.action);
1307
+ try {
1308
+ await managerPost(b, "/free", { unload_models: true, free_memory: true }, { ctx, timeoutMs: 30_000 });
1309
+ }
1310
+ catch (e) {
1311
+ throw mapRail(e, req.action);
1312
+ }
1313
+ finally {
1314
+ releaseLifecycle();
1315
+ }
1316
+ return ok(req.action, "free issued (next worker iteration)", { next_action: "status" });
1317
+ }
1318
+ // ── endpoint_set: the operator's server URL change ────────────────
1319
+ // Validates FIRST (a live /system_stats probe — an unreachable URL
1320
+ // is refused, never written), then rewrites ONLY `url` in the
1321
+ // endpoint config, preserving every other field. Works in managed
1322
+ // AND byo modes (pointing elsewhere is not provisioning).
1323
+ async function hEndpointSet(req, ctx) {
1324
+ need(req, "url");
1325
+ const url = req.url.trim().replace(/\/+$/, "");
1326
+ if (!/^https?:\/\/[A-Za-z0-9.\-]+(:\d+)?(\/.*)?$/.test(url)) {
1327
+ throw new Refused(400, "endpoint_set: url must be http(s)://host[:port] — got '" + url + "'");
1328
+ }
1329
+ // Probe the candidate BEFORE writing (no unreachable URL ever
1330
+ // lands in the config; the old URL keeps serving on refusal).
1331
+ // THE ENV FENCE (audit I-S2, the KEY LAW divergence enforced):
1332
+ // resolveEngineBaseUrl reads COMFYUI_URL FIRST, so with the env
1333
+ // set, this file write lands on a plane no reader keys off —
1334
+ // the census, lora doors, and live docs keep answering the env
1335
+ // server while the UI reports the file's. Refuse instead of
1336
+ // warning: the operator unsets COMFYUI_URL (or points it at the
1337
+ // same server) and the write becomes real.
1338
+ const envUrl = (process.env["COMFYUI_URL"] ?? "").trim().replace(/\/+$/, "");
1339
+ if (envUrl !== "" && envUrl !== url) {
1340
+ throw new Refused(409, "endpoint_set: COMFYUI_URL='" + envUrl + "' overrides the config file — " +
1341
+ "every reader keys off the env while this write lands on the file, " +
1342
+ "so the door would silently change nothing. Unset COMFYUI_URL or point it at '" + url + "' first.", { state: "conflict", next_action: "endpoint_set" });
1343
+ }
1344
+ const dl = deadlineOf(ctx.signal, 5000, "ENDPOINT_SET_PROBE");
1345
+ let stats;
1346
+ try {
1347
+ const r = await fetch(url + "/system_stats", { signal: dl.signal });
1348
+ if (!r.ok)
1349
+ throw new Error("HTTP " + String(r.status));
1350
+ stats = (await r.json());
1351
+ }
1352
+ catch (e) {
1353
+ if (signalIsAborted(ctx.signal))
1354
+ throw abortReason(ctx.signal);
1355
+ if (timeoutOf(dl.signal, "ENDPOINT_SET_PROBE")) {
1356
+ throw new Refused(504, "endpoint_set probe timed out — the endpoint is unchanged", {
1357
+ state: "timeout",
1358
+ next_action: "endpoint_set",
1359
+ });
1360
+ }
1361
+ throw new Refused(502, "endpoint_set: '" + url + "' did not answer /system_stats (" +
1362
+ (e instanceof Error ? e.message : String(e)) + ") — the endpoint is unchanged");
1363
+ }
1364
+ finally {
1365
+ dl[Symbol.dispose]();
1366
+ }
1367
+ throwIfAborted(ctx.signal);
1368
+ const cfgPath = endpointConfigPath();
1369
+ const cfg = { ...loadEndpointConfig() };
1370
+ // Captured BEFORE the mutation below: priorUrl must read the
1371
+ // PRE-write config url. Reading cfg["url"] after `cfg["url"] = url`
1372
+ // returns the new url twice and the old server's doc never drops
1373
+ // (found by the MP-R2 wall — the drop loop read [url, url]).
1374
+ const priorUrl = (() => {
1375
+ const raw = cfg["url"];
1376
+ return typeof raw === "string" && raw.trim() !== "" ? raw.trim().replace(/\/+$/, "") : url;
1377
+ })();
1378
+ cfg["url"] = url;
1379
+ try {
1380
+ // J6: the endpoint config rides the atomic writer — a torn
1381
+ // comfyui_endpoint.json would brick every later config read on
1382
+ // this estate. The writer rejects with Error only (fs/promises),
1383
+ // so the Refused narrow still holds.
1384
+ await writeJsonAtomic(cfgPath, cfg);
1385
+ }
1386
+ catch (e) {
1387
+ throw new Refused(500, "endpoint_set: config write failed (" + e.message + ") — the endpoint is unchanged");
1388
+ }
1389
+
1390
+ // server's ~3.5MB census doc forever (oiCache is unbounded) — drop
1391
+ // the pre-write config url AND the new one, so neither seat serves
1392
+
1393
+
1394
+ // abort check — the write above already landed, so an abort
1395
+ // delivered between the write and the drop still drops (the old
1396
+ // server's doc must not be served indefinitely). A write that did
1397
+ // NOT land throws above and never reaches this drop.
1398
+ for (const stale of [priorUrl, url]) {
1399
+ try {
1400
+ invalidateObjectInfo(stale);
1401
+ }
1402
+ catch (e) {
1403
+ // no endpoint configured under this spelling — no key was
1404
+ // cached under it. The LIVE key failing is different (audit
1405
+ // N-S6): the stale doc survives and the next census serves the
1406
+ // old server's node set — that failure is voiced, not folded.
1407
+ if (stale === url) {
1408
+ console.log("[estate-queue] endpoint_set: the oiCache drop failed on the LIVE key — the next census may serve the previous server's node set:", e instanceof Error ? e.message : String(e));
1409
+ }
1410
+ }
1411
+ }
1412
+ throwIfAborted(ctx.signal);
1413
+ const sys = (stats["system"] ?? {});
1414
+ return ok(req.action, "endpoint set to " + url + " (ComfyUI " + String(sys["comfyui_version"] ?? "?") + " answered)", { url, comfyui_version: sys["comfyui_version"] ?? null });
1415
+ }
1416
+ async function hListExtensions(req, ctx) {
1417
+ const cfg = ctx.endpoint();
1418
+ estateOnly(req, cfg);
1419
+ let doc;
1420
+ try {
1421
+ doc = await managerGet(base(ctx), "/customnode/installed", { ctx, timeoutMs: 30_000 });
1422
+ }
1423
+ catch (e) {
1424
+ throw mapRail(e, req.action);
1425
+ }
1426
+ const packs = (doc ?? {});
1427
+ const rows = Object.entries(packs).map(([name, v]) => ({
1428
+ name,
1429
+ version: v["version"] ?? v["ver"] ?? "?",
1430
+ }));
1431
+ return withNextAction(ok(req.action, rows.length + " installed pack(s)", rows), "install_extension");
1432
+ }
1433
+ function snapshotItem(value) {
1434
+ if (typeof value === "string")
1435
+ return value;
1436
+ if (typeof value === "object" && value !== null) {
1437
+ const row = value;
1438
+ for (const key of ["snapshot", "name", "filename", "file"]) {
1439
+ if (typeof row[key] === "string")
1440
+ return row[key];
1441
+ }
1442
+ }
1443
+ return String(value);
1444
+ }
1445
+ function snapshotItems(doc) {
1446
+ if (Array.isArray(doc))
1447
+ return doc.map(snapshotItem);
1448
+ if (typeof doc !== "object" || doc === null)
1449
+ return [];
1450
+ const value = doc;
1451
+ for (const key of ["items", "snapshots"]) {
1452
+ if (Array.isArray(value[key]))
1453
+ return value[key].map(snapshotItem);
1454
+ }
1455
+ if (value["data"] !== undefined)
1456
+ return snapshotItems(value["data"]);
1457
+ return [];
1458
+ }
1459
+ function snapshotName(doc) {
1460
+ if (typeof doc === "string" && doc.trim() !== "" && doc !== "?")
1461
+ return doc;
1462
+ if (typeof doc !== "object" || doc === null)
1463
+ return undefined;
1464
+ const value = doc;
1465
+ for (const key of ["snapshot", "name", "filename", "file"]) {
1466
+ const candidate = value[key];
1467
+ if (typeof candidate === "string" && candidate.trim() !== "" && candidate !== "?")
1468
+ return candidate;
1469
+ }
1470
+ if (value["data"] !== undefined)
1471
+ return snapshotName(value["data"]);
1472
+ return undefined;
1473
+ }
1474
+ async function hSnapshotList(req, ctx) {
1475
+ const cfg = ctx.endpoint();
1476
+ estateOnly(req, cfg);
1477
+ let doc;
1478
+ try {
1479
+ doc = await managerGet(base(ctx), "/snapshot/getlist", { ctx, timeoutMs: 30_000 });
1480
+ }
1481
+ catch (e) {
1482
+ throw mapRail(e, req.action);
1483
+ }
1484
+ const items = snapshotItems(doc);
1485
+ return withNextAction(ok(req.action, items.length + " snapshot(s)", items), "snapshot_save");
1486
+ }
1487
+ async function hSnapshotSave(req, ctx) {
1488
+ const cfg = ctx.endpoint();
1489
+ estateOnly(req, cfg);
1490
+ return await withManageTimeout(req, ctx, async (signal) => {
1491
+ const scoped = { ...ctx, signal };
1492
+ const before = snapshotItems(await managerGet(base(ctx), "/snapshot/getlist", { ctx: scoped, timeoutMs: 15_000 }));
1493
+ const response = await managerPost(base(ctx), "/snapshot/save", {}, { ctx: scoped, timeoutMs: railMs(req) });
1494
+ const after = snapshotItems(await managerGet(base(ctx), "/snapshot/getlist", { ctx: scoped, timeoutMs: 15_000 }));
1495
+ const added = after.filter((item) => !before.includes(item));
1496
+ const addedName = added.length === 1 && added[0].trim() !== "" && added[0] !== "?" ? added[0] : undefined;
1497
+ const name = addedName ?? snapshotName(response);
1498
+ if (name === undefined) {
1499
+ throw new Refused(502, "snapshot save completed without a verifiable snapshot name", {
1500
+ state: "unknown",
1501
+ snapshots: after,
1502
+ next_action: "snapshot_list",
1503
+ });
1504
+ }
1505
+ return ok(req.action, "snapshot saved: " + name, {
1506
+ state: "saved",
1507
+ snapshot: name,
1508
+ snapshots: after,
1509
+ next_action: "snapshot_restore",
1510
+ });
1511
+ }).catch((error) => {
1512
+ if (signalIsAborted(ctx.signal))
1513
+ throw abortReason(ctx.signal);
1514
+ if (error instanceof Refused)
1515
+ throw error;
1516
+ throw mapRail(error, req.action);
1517
+ });
1518
+ }
1519
+ async function hSnapshotRestore(req, ctx) {
1520
+ need(req, "snapshot");
1521
+ guardLifecycle(req, ctx);
1522
+ const cfg = ctx.endpoint();
1523
+ estateOnly(req, cfg);
1524
+
1525
+ // call so a run pressed mid-restore refuses instead of tearing.
1526
+ const releaseLifecycle = holdLifecycle(req.action);
1527
+ try {
1528
+ await managerPost(base(ctx), "/snapshot/restore", { target: req.snapshot }, { ctx, timeoutMs: 30_000 });
1529
+ }
1530
+ catch (e) {
1531
+ throw mapRail(e, req.action);
1532
+ }
1533
+ finally {
1534
+ releaseLifecycle();
1535
+ }
1536
+ return ok(req.action, "restore of " + req.snapshot + " scheduled (restart required)", {
1537
+ state: "restart_required",
1538
+ restart_required: true,
1539
+ next_action: "restart",
1540
+ });
1541
+ }
1542
+
1543
+ // belong in the ComfyUI Manager sidebar, not a dev-only drop-in).
1544
+ /** The engine's loras dir, resolved by the ONE shared spelling
1545
+ * (`resolveEngineLorasDir` in comfyui-cordis — env override, else
1546
+ * the endpoint's model root + `loras`, null when undeclared). The
1547
+ * uploads door's binary arm reads the same function, so the two
1548
+ * doors can never disagree about where a LoRA lands. */
1549
+ const engineLorasDir = resolveEngineLorasDir;
1550
+ /** The refusal text for an undeclared loras dir — one spelling. */
1551
+ const LORAS_DIR_UNDECLARED = 'the loras install dir is undeclared — set MELITE_COMFYUI_LORAS_DIR or the endpoint model_base_path (never guessed)';
1552
+ /** `lora_list` — THE FACT + THE ROWS. The engine's own
1553
+ * LoraLoaderModelOnly combo is the only truth about what /prompt will
1554
+ * accept (a name outside it is a 400 after the money is spent), and
1555
+ * the user's rows file says which of those names are OFFERED, with a
1556
+ * label and a strength default. */
1557
+ async function hLoraList(req, ctx) {
1558
+ const cfg = ctx.endpoint();
1559
+ estateOnly(req, cfg);
1560
+ const combo = loraNamesFromObjectInfo(await objectInfoDoc(ctx, railMs(req)));
1561
+ const file = readUserLoraRows(userLorasPath());
1562
+ const unboarded = unboardedRows(file.rows, combo);
1563
+ return ok(req.action, combo.length + ' LoRA name(s) the engine accepts; ' + file.rows.length + ' user row(s) offered', {
1564
+ engine_loras: combo,
1565
+ user_rows: file.rows,
1566
+ user_rows_path: file.path,
1567
+ user_rows_present: !file.absent,
1568
+ user_row_problems: file.problems,
1569
+ // rows the engine does NOT have: named here, not at /prompt
1570
+ unboarded,
1571
+ install_dir: engineLorasDir(cfg) ?? LORAS_DIR_UNDECLARED,
1572
+ // a file copied in is only seen by the combo after a reboot —
1573
+ // core enumerates folder_paths at import, and a reboot is the
1574
+ // only refresh primitive this repo owns
1575
+ next_action_after_install: 'restart',
1576
+ });
1577
+ }
1578
+
1579
+
1580
+
1581
+ async function hLoraInstall(req, ctx) {
1582
+ const cfg = ctx.endpoint();
1583
+ estateOnly(req, cfg);
1584
+ const dir = engineLorasDir(cfg);
1585
+ // a copy needs a REAL target — an undeclared dir refuses loud
1586
+ // (never a guessed path on someone else's machine)
1587
+ if (dir === null)
1588
+ throw new Refused(502, LORAS_DIR_UNDECLARED);
1589
+ // THE BYTES ARM: a browser upload (the civit flow) needs no path
1590
+ if (req.data !== '') {
1591
+ if (req.filename === '')
1592
+ throw new Refused(422, 'lora_install with bytes requires filename');
1593
+ // the declared length rides along so the door answers the cap
1594
+ // BEFORE decoding a 500MB base64 string (the transport knows the
1595
+ // length; a copy must not have to measure by decoding)
1596
+ const landed = installUserLoraBytes(req.filename, req.data, dir, req.data.length);
1597
+ if (!landed.ok)
1598
+ throw new Refused(422, landed.reason, { filename: req.filename, install_dir: dir });
1599
+ return loraInstalled(req, ctx, dir, landed, 'uploaded');
1600
+ }
1601
+ need(req, 'path');
1602
+ const result = installUserLora(req.path, dir);
1603
+ if (!result.ok) {
1604
+ // the plane's own refusal path (Refused → the envelope's detail +
1605
+ // data), so the sidebar reads it like every other refusal
1606
+ throw new Refused(422, result.reason, { path: req.path, install_dir: dir });
1607
+ }
1608
+ return loraInstalled(req, ctx, dir, result, 'copied');
1609
+ }
1610
+ /** THE ANSWER both arms share: the name, the bytes, whether the
1611
+ * engine already lists it, and the restart it needs. The pinned
1612
+ * core's folder listing is mtime-live (cached_filename_list_
1613
+ * re-stats each folder per read — data/runtime/comfyui/
1614
+ * folder_paths.py:499), so a landed file shows in the next census
1615
+ * WITHOUT a reboot; the harness's own cached /object_info doc is
1616
+ * the stale layer, and the acquisition doors drop it (1a6f773c).
1617
+ * A restart stays required for custom_nodes (import-time), never
1618
+ * for a weight file. The row suggestion rides along so the
1619
+ * operator's next step is a paste, not a hunt. */
1620
+ async function loraInstalled(req, ctx, dir, result, verb) {
1621
+ // truth at answer time: the engine may have rebooted since the
1622
+ // cache filled (an out-of-band restart), so the combo read below
1623
+ // must not serve the pre-restart doc — one fresh fetch per install
1624
+ invalidateLiveObjectInfo(ctx);
1625
+ const combo = loraNamesFromObjectInfo(await objectInfoDoc(ctx, railMs(req)));
1626
+ const visible = combo.includes(result.filename);
1627
+ return ok(req.action, verb + ' ' + result.filename + ' (' + result.bytes + ' bytes) into ' + dir
1628
+ + (visible ? ' — already in the engine\'s list' : ' — restart the engine to enter its list'), {
1629
+ filename: result.filename,
1630
+ bytes: result.bytes,
1631
+ install_dir: dir,
1632
+ in_combo_now: visible,
1633
+ next_action: 'restart',
1634
+ restart_required: !visible,
1635
+ // the row the operator adds next, ready to paste
1636
+ row_suggestion: {
1637
+ id: result.filename.replace(/\.[^.]+$/, '').replace(/[^a-zA-Z0-9]+/g, '_'),
1638
+ filename: result.filename,
1639
+ families: req.families,
1640
+ default_strength: 1,
1641
+ },
1642
+ });
1643
+ }
1644
+ /** The engine's node declaration, or null when the engine is
1645
+ * unreachable (the cross-check then proves nothing and refuses
1646
+ * nothing — never a throw across the sidebar). ONE reader, the
1647
+ * estate's own: `liveObjectInfo` is cached per engine for the
1648
+ * process life and refuses closed on a malformed body — a second
1649
+ * spelling here would be a second truth about the engine. */
1650
+ /** The engine's WHOLE node-definitions doc, or null when the engine
1651
+ * is unreachable. It is the doc (not one node) because the reader
1652
+ * that turns it into the LoRA list is the reader's own job, and a
1653
+ * per-node hop here would make the two spellings drift. */
1654
+ async function objectInfoDoc(ctx, boundMs) {
1655
+
1656
+
1657
+ // same railMs bound every other manage hop rides. The deadline
1658
+ // refusal is LOUD — a hung engine refuses the door (504), it
1659
+ // never reads as an empty lora combo; only an engine that cannot
1660
+ // be reached at all folds to the null-doc contract.
1661
+ throwIfAborted(ctx.signal);
1662
+ if (ctx.objectInfo !== undefined) {
1663
+ try {
1664
+ return await ctx.objectInfo();
1665
+ }
1666
+ catch {
1667
+ return null;
1668
+ }
1669
+ }
1670
+ try {
1671
+ return await liveObjectInfo(resolveEngineBaseUrl(), ctx.signal, boundMs);
1672
+ }
1673
+ catch (error) {
1674
+ // only the deadline goes loud; an unreachable or endpoint-less
1675
+ // engine keeps the settled null-doc contract (not-visible), and
1676
+ // an aborted door needs no refusal past its own teardown
1677
+ if (error instanceof ComfyError && error.code === 'deadline') {
1678
+ throw new Refused(504, error.message);
1679
+ }
1680
+ return null;
1681
+ }
1682
+ }
1683
+ /** Drop the live /object_info cache entry for the engine this
1684
+ * process serves — the same key objectInfoDoc's live arm reads.
1685
+ * A ctx carrying its own objectInfo seam never touches the global
1686
+ * cache, so there is nothing to drop; and an endpoint-less
1687
+ * resolveEngineBaseUrl refusal means no key was ever cached.
1688
+ * KEY LAW: the drop keys off resolveEngineBaseUrl() (env/config),
1689
+ * never ctx.endpoint() — matching the reader. A lane seating a
1690
+ * ctx.endpoint() that differs from the resolved base must point
1691
+ * COMFYUI_URL at the same server, or the drop lands on a key no
1692
+ * census reads and the stale doc survives. */
1693
+ function invalidateLiveObjectInfo(ctx) {
1694
+ if (ctx.objectInfo !== undefined)
1695
+ return;
1696
+ try {
1697
+ invalidateObjectInfo(resolveEngineBaseUrl());
1698
+ }
1699
+ catch (e) {
1700
+ // no endpoint configured — nothing was ever cached under a key
1701
+ void e;
1702
+ }
1703
+ }
1704
+ // ── handler table (wall-scanned rows) ───────────────────────────────
1705
+ const HANDLERS = {
1706
+ status: hStatus,
1707
+ logs: hLogs,
1708
+ search_models: hSearch,
1709
+ endpoint_set: hEndpointSet,
1710
+ list_extensions: hListExtensions,
1711
+ snapshot_list: hSnapshotList,
1712
+ install_extension: hInstallExtension,
1713
+ install_extension_url: hInstallExtensionUrl,
1714
+ download_model: hDownloadModel,
1715
+ provision_model: hProvisionModel,
1716
+ acquire_weight: hAcquireWeight,
1717
+ restart: hRestart,
1718
+ stop: hStop,
1719
+ launch: hLaunch,
1720
+ update: hUpdate,
1721
+ switch_version: hSwitchVersion,
1722
+ free: hFree,
1723
+ snapshot_save: hSnapshotSave,
1724
+ snapshot_restore: hSnapshotRestore,
1725
+ lora_list: hLoraList,
1726
+ lora_install: hLoraInstall,
1727
+ };
1728
+ function refusalDataFields(data) {
1729
+ if (typeof data !== "object" || data === null)
1730
+ return {};
1731
+ const value = data;
1732
+ return {
1733
+ ...(typeof value["state"] === "string" ? { state: value["state"] } : {}),
1734
+ ...(typeof value["next_action"] === "string" ? { next_action: value["next_action"] } : {}),
1735
+ ...(typeof value["operation_id"] === "string" ? { operation_id: value["operation_id"] } : {}),
1736
+ ...(Array.isArray(value["operations"]) ? { operations: value["operations"] } : {}),
1737
+ ...(Array.isArray(value["items"]) ? { items: value["items"] } : {}),
1738
+ ...(Array.isArray(value["requested"]) ? { requested: value["requested"] } : {}),
1739
+ ...(Array.isArray(value["succeeded"]) ? { succeeded: value["succeeded"] } : {}),
1740
+ ...(Array.isArray(value["missed"]) ? { missed: value["missed"] } : {}),
1741
+ ...(Array.isArray(value["misses"]) ? { misses: value["misses"] } : {}),
1742
+ ...(typeof value["partial"] === "boolean" ? { partial: value["partial"] } : {}),
1743
+ ...(typeof value["restart_required"] === "boolean" ? { restart_required: value["restart_required"] } : {}),
1744
+ };
1745
+ }
1746
+ function refusalEnvelope(action, status, detail, data) {
1747
+ return {
1748
+ action,
1749
+ ok: false,
1750
+ detail,
1751
+ status,
1752
+ code: "manage/refused",
1753
+ data,
1754
+ ...refusalDataFields(data),
1755
+ };
1756
+ }
1757
+ export async function dispatchManage(doc, ctx, signal) {
1758
+ const activeCtx = linkCallerSignal(ctx, signal ?? ctx.signal);
1759
+ throwIfAborted(activeCtx.signal);
1760
+ let req;
1761
+ try {
1762
+ req = parseReq(doc);
1763
+ }
1764
+ catch (e) {
1765
+ const r = e;
1766
+ const action = doc !== null && typeof doc === "object" && !Array.isArray(doc)
1767
+ ? String(doc["action"] ?? "?")
1768
+ : "?";
1769
+ return [r.code, refusalEnvelope(action, r.code, r.message, r.data)];
1770
+ }
1771
+ try {
1772
+ const response = await HANDLERS[req.action](req, activeCtx);
1773
+ throwIfAborted(activeCtx.signal);
1774
+ return response;
1775
+ }
1776
+ catch (e) {
1777
+ if (activeCtx.signal?.aborted === true)
1778
+ throw abortReason(activeCtx.signal);
1779
+ if (e instanceof Refused) {
1780
+ return [e.code, refusalEnvelope(req.action, e.code, e.message, e.data)];
1781
+ }
1782
+ if (e instanceof ManagerApiError) {
1783
+ const refused = mapManagerRefused(e, req.action);
1784
+ return [refused.code, refusalEnvelope(req.action, refused.code, refused.message, refused.data)];
1785
+ }
1786
+ const msg = e instanceof Error ? e.constructor.name + ": " + e.message : String(e);
1787
+ return [500, refusalEnvelope(req.action, 500, msg.slice(0, 300))];
1788
+ }
1789
+ }
1790
+ //# sourceMappingURL=managePlane.js.map