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