@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,285 @@
1
+ import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
2
+ import { RUNS_ERROR_CODES } from "./runsErrorCodes.js";
3
+ import { getRegistryFlow, expandRegistryFlow, registryFlowToInline, registryInitialsError } from "./flowsData.js";
4
+ import { composeFamilyStages, liveFamilySeat } from "./flowsFamilyCompose.js";
5
+ import { resolveRepoRoot } from "@melite/comfyui-cordis";
6
+ import { inlineArm, strictBody } from "./runsValidate.js";
7
+ import { FLOW_ID_RE } from "./runsGates.js";
8
+ import { CardArmError } from "./cardsArmError.js";
9
+ import { prepareCardParams } from "./cardsCompose.js";
10
+ export async function validate(doc, signal, ctx) {
11
+ signal.throwIfAborted();
12
+ // the {flow:} shim may REPLACE the body (flow → flow_inline):
13
+ // the inline arm compiles the LIVE body, not the original doc.
14
+ let liveDoc = doc;
15
+ if (typeof doc === "object" && doc !== null && !Array.isArray(doc)) {
16
+ let body = doc;
17
+ if ("model" in body) {
18
+ const answer = await modelValidateArm(body, ctx);
19
+ if (answer.status === 200)
20
+ return answer.payload;
21
+ const p = answer.payload;
22
+ const mapped = RUNS_ERROR_CODES[p["code"]];
23
+ if (mapped === undefined) {
24
+ throw new Error("runs validate: unmapped answer code " + p["code"]);
25
+ }
26
+ // (no model-arm answer stamps loc today — the passthrough
27
+ // rides undefined, verbatim like the inline block below.)
28
+ throw new RemoteError(mapped, p["error"], {
29
+ loc: p["loc"],
30
+ });
31
+ }
32
+ if ("flow" in body && !("flow_inline" in body) &&
33
+ !("model" in body) && !("stages" in body)) {
34
+ // THE NAMED-FLOW SHIM at validate (REBUILD-13; the dead
35
+ // door's law): expand the registry flow live and compile it
36
+ // through the SAME inline arm — no second validator. Unknown
37
+ // names keep the door's own voice.
38
+ const raw = body["flow"];
39
+ const name = typeof raw === "string" ? raw : "";
40
+ // The start arm's order, verbatim: admission (the id's shape)
41
+ // before presence (is it registered). One voice for an
42
+ // illegal name, whichever door answers.
43
+ if (!FLOW_ID_RE.test(name)) {
44
+ throw new RemoteError("runs/invalid-request",
45
+ // The RAW value, named — the start arm's voice verbatim.
46
+ "flow id " + JSON.stringify(raw) + " is not a legal identifier", { loc: "flow" });
47
+ }
48
+ const decl = getRegistryFlow(name);
49
+ if (decl === undefined) {
50
+ throw new RemoteError("runs/invalid-request", "no flow named " + name + " in the registry", { loc: "flow" });
51
+ }
52
+ const expanded = expandRegistryFlow(decl);
53
+ // The same compile-time gate at validate (REBUILD-21).
54
+ const badInitial = registryInitialsError(expanded, body, {
55
+ repoRoot: resolveRepoRoot(),
56
+ stateRoot: ctx.queue.stateRoot,
57
+ });
58
+ if (badInitial !== null) {
59
+ throw new RemoteError("runs/invalid-request", badInitial, {
60
+ loc: "body",
61
+ });
62
+ }
63
+ // THE FAMILY-ACTION STAGES COMPOSE HERE TOO (the atom
64
+ // vocabulary, stroke 4): validate compiles the SAME composed
65
+ // envelope start registers — one admission law, both doors.
66
+ // The interpreter's refusals (unknown family/action,
67
+ // unadmitted param, contradicting hand-write) surface with
68
+ // the door's invalid-request voice.
69
+ let composedFlow;
70
+ try {
71
+ // The seat read rides ctx.get, the engines precedent in
72
+ // runsRegistry: an undeclared-inject property access
73
+ // would throw cordis's reflect voice instead of
74
+ // degrading to the booted singleton.
75
+ const seat = liveFamilySeat(ctx.get("models"));
76
+ composedFlow = composeFamilyStages(expanded, seat.decls, seat.state);
77
+ }
78
+ catch (e) {
79
+ throw new RemoteError("runs/invalid-request", e instanceof Error ? e.message : String(e), { loc: "stages" });
80
+ }
81
+ const inlineDoc = registryFlowToInline(composedFlow);
82
+ const rest = { ...body };
83
+ delete rest["flow"];
84
+ liveDoc = { ...rest, flow_inline: inlineDoc };
85
+ }
86
+ }
87
+ // The card-stage lattice reads through the primed registry (the
88
+ // cards stroke's CardRegistryService — ctx.cardRegistry, primed
89
+ // at boot). Passing null here refused EVERY card= stage with the
90
+ // LOUD miswire ("no CardRegistryService for cardGate") — the
91
+
92
+ // could run but never validate.
93
+ const answer = inlineArm(liveDoc, ctx.cardRegistry);
94
+ if (answer.status === 200) {
95
+ // THE ONE-ADMISSION LAW (commission 018's sharpest
96
+
97
+ // runnable promise — the start door composes card stages
98
+ // through phase1Card (overlay → admission → lane presence →
99
+ // spell pool → composeOnce) and that walk refused params the
100
+ // lattice's schema alone passed (attempt-018: the directory
101
+ // default died at the compose guard, validate said green).
102
+ // Validate now runs the SAME walk per card stage. One honest
103
+ // degradation: an unreachable engine keeps validate usable —
104
+ // the payload NAMES the skipped walk instead of refusing
105
+ // closed (the {model:} arm's composeValidateCard keeps its
106
+ // stricter closed voice; the bench seat must validate on
107
+ // engine-less boxes).
108
+ const note = await composeCardStagesAtValidate(liveDoc, ctx.cardRegistry);
109
+ if (typeof note === "string" && note.startsWith("REFUSED ")) {
110
+ throw new RemoteError("runs/invalid-request", note.slice(8), { loc: "stages" });
111
+ }
112
+ return note === null ? answer.payload : { ...answer.payload, note };
113
+ }
114
+ const p = answer.payload;
115
+ const mapped = RUNS_ERROR_CODES[p["code"]];
116
+
117
+
118
+ if (mapped === undefined) {
119
+ // An answer this table does not name is a bug — LOUD.
120
+ throw new Error("runs validate: unmapped answer code " + p["code"]);
121
+ }
122
+ // (inlineArm stamps loc on every 400 — the passthrough never
123
+ // yields undefined here.)
124
+ throw new RemoteError(mapped, p["error"], {
125
+ loc: p["loc"],
126
+ errors: p["errors"],
127
+ });
128
+ }
129
+ /** THE ONE-ADMISSION LAW's inline half: compose every card stage
130
+ * through the registry's phase1Card — the SAME walk the start
131
+ * door rides ($spell bodies skip the graph by their own law).
132
+ * null = composed clean, no note. A string starting "REFUSED "
133
+ * carries the refusal voice; any other string is a degradation
134
+ * note (engine unreachable — the schema-only verdict stands,
135
+ * named). */
136
+ async function composeCardStagesAtValidate(liveDoc, svc) {
137
+
138
+ // a non-object stage, a non-object params, an empty id and a
139
+ // missing model BEFORE this walk reads them — every stage here is
140
+ // an object with a non-empty id and an object params. The
141
+
142
+ // (a wall for an unreachable arm is a lie), so they are gone; a
143
+ // body that skipped the door now fails loud instead of quietly
144
+ // composing nothing.
145
+ // THE SUBJECT, THE WAY inlineArm FINDS IT (under the 200 only —
146
+
147
+ // carrying flow_inline is read through it and a body without one
148
+ // is its own subject (inlineArm's own envelope rule). Reading
149
+ // flow_inline.stages unconditionally assumed a key this walk's
150
+ // caller does not promise — the removed half-built-seat guard had
151
+ // been hiding it.
152
+
153
+ // comment above): validate reaches this walk only on a 200 from
154
+ // inlineArm, and flowFromBody — the door every subject passes —
155
+ // refuses a non-object body and a non-array (or empty) stages
156
+ // list before that 200 can exist. The non-object `: {}` and
157
+ // non-array `: []` fallbacks this walk carried were unreachable
158
+ // (a wall for an unreachable arm is a lie) and are gone; the
159
+ // casts state what the door already proved.
160
+ const liveRec = liveDoc;
161
+ const envelope = ("flow_inline" in liveRec ? liveRec["flow_inline"] : liveRec);
162
+ const stages = envelope.stages;
163
+ // a legal NON-card stage (a plain engine stage) is not this
164
+ // walk's business: it composes through the engine
165
+ const cardStages = stages.filter((st) => typeof st["card"] === "string" && st["card"] !== "");
166
+ if (cardStages.length === 0)
167
+ return null;
168
+ if (!(await svc.primeObjectInfo())) {
169
+ return "compose walk skipped: engine unreachable (schema-only verdict — the start door composes before queuing)";
170
+ }
171
+ for (const st of cardStages) {
172
+ const params = st["params"];
173
+ // a non-string model row (the door's card gate only demands
174
+ // presence) composes against the CARD name — the arm is live
175
+ const mid = typeof params["model"] === "string"
176
+ ? params["model"] : String(st["card"]);
177
+ // A MODEL-LESS CARD STAGE (stroke 3: the registry's rig hop)
178
+ // rides with NO model key at all: an injected one would hit
179
+ // the board check ("model 'rig' is not offered by card 'rig'",
180
+ // boards: none) before prepareCardParams ever resolved the
181
+ // familyless card-unit arm — which needs mid alone, not a
182
+ // body.model. admitStageModel passes an absent model; the
183
+ // compose names the family through the card's own selector
184
+ // (the rig card's mode knob).
185
+ const body = params["model"] === undefined
186
+ ? { ...params }
187
+ : { ...params, model: mid };
188
+ try {
189
+ await svc.phase1Card(body, mid);
190
+ }
191
+ catch (e) {
192
+ if (e instanceof CardArmError) {
193
+ return "REFUSED stage " + JSON.stringify(String(st["id"])) + ": " + e.message;
194
+ }
195
+ throw e;
196
+ }
197
+ }
198
+ return null;
199
+ }
200
+ /** Map a CardArmError onto the refusal envelope (door-verbatim:
201
+ * the error verbatim + code + loc/expected/got only when set). */
202
+ export async function modelValidateArm(body, ctx) {
203
+ const mid = String(body["model"] ?? "");
204
+ try {
205
+ strictBody(body);
206
+ }
207
+ catch (e) {
208
+ // (strictBody throws FlowError only — checkStrictBody is total
209
+ // string ops over the body's keys — so the cast folds every
210
+ // throw with the door-verbatim text.)
211
+ const flowErr = e;
212
+ return {
213
+ status: 400,
214
+ payload: { error: flowErr.message, code: "invalid_request" },
215
+ };
216
+ }
217
+ // resolve_request's door count: the {model} arm
218
+ // re-checks ambiguity — a body naming two doors refuses here,
219
+ // before the artifact sweep.
220
+ const doors = ["flow", "flow_inline", "model"]
221
+ .filter((k) => k in body);
222
+ if (doors.length > 1) {
223
+ return {
224
+ status: 400,
225
+ payload: {
226
+ error: "ambiguous request: names " +
227
+ JSON.stringify(doors) +
228
+ " — provide exactly one of flow, flow_inline, model",
229
+ code: "invalid_request",
230
+ },
231
+ };
232
+ }
233
+ const svc = ctx.cardRegistry;
234
+ // ONE PREPARE: this door owns no refusal voices of its own —
235
+ // prepareCardParams refuses (dangling, legality, resolves,
236
+ // unknown-unit, skew) and the arm folds its CardArmErrors
237
+ // into the validate answer. The facts degrade below is THIS
238
+ // door's pinned policy (the catalog answers alone when the
239
+ // facts file is absent), handed to prepare as an explicit
240
+ // resolve step.
241
+ let facts;
242
+ try {
243
+ facts = svc.modelFacts();
244
+ }
245
+ catch {
246
+ facts = {};
247
+ }
248
+ let prep;
249
+ try {
250
+ prep = prepareCardParams(svc, body, mid, "1", facts);
251
+ }
252
+ catch (e) {
253
+ if (e instanceof CardArmError) {
254
+ return { status: 400, payload: { error: e.message, code: e.code } };
255
+ }
256
+ throw e;
257
+ }
258
+ const params = prep.params;
259
+ // IN-PROCESS COMPOSE: the SAME registry compose pipeline the
260
+ // start arm rides composes for validate (one plane, both arms).
261
+ const refused =
262
+ // the body's OWN model address rides: the params are overlaid (the
263
+ // model key is consumed), so the arm must not lose the address the
264
+ // board check and the variant selection both judge
265
+ await svc.composeValidateCard(prep.card, prep.fam, params, mid, body);
266
+ if (refused !== null) {
267
+ return {
268
+ status: 400,
269
+ payload: { error: refused.message, code: refused.code },
270
+ };
271
+ }
272
+ // composed OK — 200 shape verbatim (ok/model/card/cost in
273
+ // wire order; engine medians unknown at validate time so the
274
+ // stages list is empty).
275
+ return {
276
+ status: 200,
277
+ payload: {
278
+ ok: true,
279
+ model: mid,
280
+ card: true,
281
+ cost: { queue_depth: 0, eta_queue_s: null, stages: [] },
282
+ },
283
+ };
284
+ }
285
+ //# sourceMappingURL=runsValidateArms.js.map
@@ -0,0 +1,6 @@
1
+ import type { Edge, StageSkip } from "./runsValidateShared.js";
2
+ export declare function edgeRef(e: Edge): string;
3
+ export declare function inlineKind(where: string, value: unknown): string;
4
+ export declare function inlineEdge(where: string, value: unknown): Edge;
5
+ export declare function inlineSkip(where: string, value: unknown): StageSkip | null;
6
+ //# sourceMappingURL=runsValidateInline.d.ts.map
@@ -0,0 +1,82 @@
1
+ // runsValidateInline.ts — inline edge/kind/branch validators split from
2
+ // runsValidate.ts (pure move, zero logic changes).
3
+ import { isRecord, isStringField } from "./runsGates.js";
4
+ import { FlowError, KIND_VOCAB, SKIP_VOCAB } from "./runsValidateShared.js";
5
+ // ── inline edges / kinds / branches ─────────────────────────────
6
+ export function edgeRef(e) {
7
+ return e.kind === "initial" ? "__initial__." + e.key : e.stage + "." + e.output;
8
+ }
9
+ export function inlineKind(where, value) {
10
+ // Leaf-type structure rides the admission gate (schemastery); the
11
+ // closed-vocab membership + FlowError prose stay here (voice).
12
+ if (!isStringField(value)) {
13
+ throw new FlowError(where + ": kind " + JSON.stringify(value) + " is not a string");
14
+ }
15
+ if (!KIND_VOCAB.includes(value)) {
16
+ throw new FlowError(where +
17
+ ": " +
18
+ JSON.stringify(value) +
19
+ " is not a Kind — the closed vocabulary is " +
20
+ JSON.stringify([...KIND_VOCAB]));
21
+ }
22
+ return value;
23
+ }
24
+ export function inlineEdge(where, value) {
25
+ if (!isRecord(value)) {
26
+ throw new FlowError(where +
27
+ ": edge " +
28
+ JSON.stringify(value) +
29
+ ' is not an object — use {"initial": key} ' +
30
+ 'or {"stage": id, "output": name}');
31
+ }
32
+ const keys = Object.keys(value);
33
+ if (keys.length === 1 && keys[0] === "initial") {
34
+ // str(value["initial"]) — mirrors FromInitial(key=str(...));
35
+ // the empty-string min_length refusal is faked byte-exact below.
36
+ return { kind: "initial", key: String(value["initial"] ?? "") };
37
+ }
38
+ if (keys.length === 2 && keys.includes("stage") && keys.includes("output")) {
39
+ const rec = value;
40
+ return { kind: "stage", stage: String(rec["stage"] ?? ""), output: String(rec["output"] ?? "") };
41
+ }
42
+ throw new FlowError(where +
43
+ ": edge keys " +
44
+ JSON.stringify(keys) +
45
+ ' are not an edge shape — exactly {"initial": key} ' +
46
+ 'or {"stage": id, "output": name}');
47
+ }
48
+ export function inlineSkip(where, value) {
49
+ if (value === null || value === undefined)
50
+ return null;
51
+ if (!isRecord(value)) {
52
+ throw new FlowError(where +
53
+ ": skip_when " +
54
+ JSON.stringify(value) +
55
+ ' is not an object — use {"initial": ' +
56
+ "key, \"when\": present|absent}");
57
+ }
58
+ const keys = Object.keys(value);
59
+ if (keys.length !== 2 || !keys.includes("initial") || !keys.includes("when")) {
60
+ throw new FlowError(where +
61
+ ": skip_when keys " +
62
+ JSON.stringify(keys) +
63
+ ' are not a branch shape — exactly {"initial": key, ' +
64
+ '"when": present|absent}');
65
+ }
66
+ const rec = value;
67
+ const when = rec["when"];
68
+ if (!isStringField(when) || !SKIP_VOCAB.includes(when)) {
69
+ throw new FlowError(where +
70
+ ": " +
71
+ JSON.stringify(when) +
72
+ " is not a branch condition — the closed vocabulary " +
73
+ "is " +
74
+ JSON.stringify([...SKIP_VOCAB]));
75
+ }
76
+ const initial = rec["initial"];
77
+ if (!isStringField(initial) || initial === "") {
78
+ throw new FlowError(where + ": skip initial " + JSON.stringify(initial) + " is not a non-empty string");
79
+ }
80
+ return { initial, when };
81
+ }
82
+ //# sourceMappingURL=runsValidateInline.js.map
@@ -0,0 +1,7 @@
1
+ export declare function minLengthRefusal(cls: string, field: string): string;
2
+ /** Record coercion for stage params: plain objects ride
3
+ * (falsy rides {}); anything else refuses loud. Pair-list
4
+ * params are refused — JSON params are objects, never pair
5
+ * lists. */
6
+ export declare function coerceRecord(v: unknown): Record<string, unknown>;
7
+ //# sourceMappingURL=runsValidateRefusals.d.ts.map
@@ -0,0 +1,18 @@
1
+ // runsValidateRefusals.ts — refusal builders: plain TS texts
2
+ // (the shape fakes and repr renders are deleted — the estate speaks
3
+ // TS). Record coercion for stage params.
4
+ export function minLengthRefusal(cls, field) {
5
+ return cls + " " + field + " must be a non-empty string";
6
+ }
7
+ /** Record coercion for stage params: plain objects ride
8
+ * (falsy rides {}); anything else refuses loud. Pair-list
9
+ * params are refused — JSON params are objects, never pair
10
+ * lists. */
11
+ export function coerceRecord(v) {
12
+ const src = v ? v : {};
13
+ if (typeof src === "object" && src !== null && !Array.isArray(src)) {
14
+ return { ...src };
15
+ }
16
+ throw new Error("stage params must be an object");
17
+ }
18
+ //# sourceMappingURL=runsValidateRefusals.js.map
@@ -0,0 +1,15 @@
1
+ import type { CardRegistryLike, Flow, FlowsValidateAnswer, GraphNode } from "./runsValidateShared.js";
2
+ export declare function prunedFor(flow: Flow, body: Record<string, unknown>, cards?: CardRegistryLike | null): {
3
+ flow: Flow;
4
+ pruned: string[];
5
+ };
6
+ export declare function toGraph(flow: Flow): GraphNode[];
7
+ export declare function dollarTokens(params: unknown): string[];
8
+ export declare function compileFlow(flow: Flow, body: Record<string, unknown>, cards?: CardRegistryLike | null): {
9
+ nodes: GraphNode[];
10
+ skipped: string[];
11
+ };
12
+ export declare function costPreview(engineTypes: string[]): Record<string, unknown>;
13
+ export declare function inlineArm(full: unknown, cards?: CardRegistryLike | null): FlowsValidateAnswer;
14
+ export declare function serveSubject(subject: unknown, fullRec: Record<string, unknown>, cards?: CardRegistryLike | null): FlowsValidateAnswer;
15
+ //# sourceMappingURL=runsValidateServe.d.ts.map
@@ -0,0 +1,254 @@
1
+ // runsValidateServe.ts — the shared compile-serve tail split from
2
+ // runsValidate.ts (pure move, zero logic changes): branch prune, to_graph,
3
+ // the $channel gate, cost preview, and the inline/named serve arms.
4
+ import { engineIdOk } from "@melite/engine-contract";
5
+ import { ENGINE_TABLE, FlowError } from "./runsValidateShared.js";
6
+ import { edgeRef } from "./runsValidateInline.js";
7
+ import { flowFromBody, kindsOk, wiresResolve } from "./runsValidateStages.js";
8
+ import { batchRows, sweepWorkflows } from "./runsValidateSweeps.js";
9
+ // ── branch prune (pruned_for — verbatim) ────────────
10
+ export function prunedFor(flow, body, cards) {
11
+ if (!flow.stages.some((st) => st.skipWhen !== null))
12
+ return { flow, pruned: [] };
13
+ const pruned = new Map();
14
+ const kept = [];
15
+ for (const st of flow.stages) {
16
+ const cond = st.skipWhen;
17
+ if (cond === null) {
18
+ kept.push(st);
19
+ continue;
20
+ }
21
+ const present = body[cond.initial] !== undefined && body[cond.initial] !== null;
22
+ const fire = cond.when === "present" ? present : !present;
23
+ if (fire)
24
+ pruned.set(st.id, cond);
25
+ else
26
+ kept.push(st);
27
+ }
28
+ if (kept.length === 0) {
29
+ throw new FlowError("flow " +
30
+ JSON.stringify(flow.id) +
31
+ ": the branch pruned every stage (fired: " +
32
+ JSON.stringify([...pruned.keys()].sort()) +
33
+ ") — a run with no stages never registers");
34
+ }
35
+ const merged = [];
36
+ for (const st of kept) {
37
+ const hitsPruned = st.inputs.some((i) => i.edge.kind === "stage" && pruned.has(i.edge.stage));
38
+ if (!hitsPruned) {
39
+ merged.push(st);
40
+ continue;
41
+ }
42
+ const newInputs = st.inputs.map((i) => ({ ...i }));
43
+ for (const inp of newInputs) {
44
+ if (inp.edge.kind !== "stage" || !pruned.has(inp.edge.stage))
45
+ continue;
46
+ const cond = pruned.get(inp.edge.stage);
47
+ if (cond.when !== "present") {
48
+ throw new FlowError("flow " +
49
+ JSON.stringify(flow.id) +
50
+ " stage " +
51
+ JSON.stringify(st.id) +
52
+ " input " +
53
+ JSON.stringify(inp.name) +
54
+ " wires FromStage(" +
55
+ JSON.stringify(edgeRef(inp.edge)) +
56
+ ") to pruned stage " +
57
+ " (branch " +
58
+ JSON.stringify(cond.initial) +
59
+ " fired) — no request key to merge (absent-trigger prunes " +
60
+ "carry nothing)");
61
+ }
62
+ inp.edge = { kind: "initial", key: cond.initial };
63
+ }
64
+ merged.push({ ...st, inputs: newInputs });
65
+ }
66
+ // RECONSTRUCTED — every construction validator re-runs (TS scope:
67
+ // wires + deferred kinds; card/tool/validators are no-ops here).
68
+ wiresResolve(flow.id, merged);
69
+ kindsOk(flow.id, merged, {}, cards);
70
+ return { flow: { id: flow.id, description: flow.description, stages: merged }, pruned: [...pruned.keys()] };
71
+ }
72
+ export function toGraph(flow) {
73
+ return flow.stages.map((st) => {
74
+ const outputs = [];
75
+ if (st.outputs.length > 0) {
76
+ for (const o of st.outputs)
77
+ outputs.push({ ...o });
78
+ }
79
+ else if (st.cardIo.length > 0) {
80
+ for (const o of st.cardIo)
81
+ outputs.push({ ...o });
82
+ }
83
+ else {
84
+ // validateEngines already refused unknown engines and the
85
+ // table carries a default for every known one — the
86
+ // try/except-unknown shape of to_graph collapses to the table.
87
+ // validateEngines refused unknown engines upstream — the hit is proven.
88
+ const row = st.engine.startsWith("mcp:") && engineIdOk(st.engine)
89
+ ? { plugin: "mcp-client", def: "image" }
90
+ : ENGINE_TABLE[st.engine];
91
+ outputs.push({ name: "default", kind: row.def });
92
+ }
93
+ return {
94
+ id: st.id,
95
+ engine: st.engine,
96
+ description: st.description,
97
+ inputFrom: st.inputs.map((i) => edgeRef(i.edge)),
98
+ inputNames: st.inputs.map((i) => i.name),
99
+ outputs,
100
+ params: st.params,
101
+ };
102
+ });
103
+ }
104
+ // dollarTokens (same file): whole-string $-tokens.
105
+ export function dollarTokens(params) {
106
+ const out = [];
107
+ const walk = (v) => {
108
+ if (typeof v === "string") {
109
+ if (v.startsWith("$") && v.length > 1)
110
+ out.push(v.slice(1));
111
+ }
112
+ else if (Array.isArray(v)) {
113
+ for (const item of v)
114
+ walk(item);
115
+ }
116
+ else if (typeof v === "object" && v !== null) {
117
+ for (const val of Object.values(v))
118
+ walk(val);
119
+ }
120
+ };
121
+ walk(params);
122
+ return out;
123
+ }
124
+ // compileFlow (same file): prune, then toGraph, then the unresolved $channel gate (per-node pool, ALL bad joined).
125
+ export function compileFlow(flow, body, cards) {
126
+ const { flow: built, pruned } = prunedFor(flow, body, cards);
127
+ const nodes = toGraph(built);
128
+ const bad = [];
129
+ for (const node of nodes) {
130
+ const pool = new Set(node.inputNames);
131
+ for (const ref of node.inputFrom) {
132
+ if (ref.startsWith("__initial__."))
133
+ pool.add(ref.split(".", 2)[1]); // the prefix guarantees [1]
134
+ else
135
+ pool.add(ref);
136
+ }
137
+ const sortedPool = [...pool].sort();
138
+ for (const token of dollarTokens(node.params)) {
139
+ if (!pool.has(token)) {
140
+ bad.push("stage " +
141
+ JSON.stringify(node.id) +
142
+ " references $" +
143
+ token +
144
+ " (available: " +
145
+ (sortedPool.length > 0 ? sortedPool.join(", ") : "nothing") +
146
+ ")");
147
+ }
148
+ }
149
+ }
150
+ if (bad.length > 0) {
151
+ throw new FlowError("unresolved $channel(s): " + bad.join("; "));
152
+ }
153
+ return { nodes, skipped: pruned };
154
+ }
155
+ // ── model facts + model-dir scan (resolve_model's TS mirror) ────
156
+ // (Stroke 2a: the facts/route/mids caches that lived here are
157
+ // CardRegistryLike state now — this door reads them through its
158
+ // injected service. The absent-facts degrade survives at the
159
+ // modelArm call site, which catches the service's strict read.)
160
+ // ── {model} arm (resolve_card_model, ported subset) ─
161
+ export function costPreview(engineTypes) {
162
+ // A fresh Gateway: depth 0, eta null, medians unknown
163
+ // (cost_preview — no engine stats).
164
+ return {
165
+ queue_depth: 0,
166
+ eta_queue_s: null,
167
+ stages: engineTypes.map((et) => ({ engine: et, median_s: null, samples: 0 })),
168
+ };
169
+ }
170
+ export function inlineArm(full, cards) {
171
+ const fullRec = typeof full === "object" && full !== null && !Array.isArray(full)
172
+ ? full
173
+ : {};
174
+ const hasInline = typeof full === "object" && full !== null && !Array.isArray(full) && "flow_inline" in fullRec;
175
+ const envelope = hasInline ? fullRec["flow_inline"] : undefined;
176
+ const subject = envelope !== undefined && envelope !== null ? envelope : full;
177
+ return serveSubject(subject, fullRec, cards);
178
+ }
179
+ // ── the shared compile-serve tail (flowFromBody -> compile ->
180
+ // pin sweep -> the 200 shape; the inline arm and the named arm
181
+ // both ride it — one validator, never two) ──────────────────────
182
+ export function serveSubject(subject, fullRec, cards) {
183
+ let flow;
184
+ try {
185
+ flow = flowFromBody(subject, cards);
186
+ }
187
+ catch (e) {
188
+ if (e instanceof FlowError) {
189
+ return {
190
+ status: 400,
191
+ payload: {
192
+ error: e.message,
193
+ code: "flow_compile",
194
+ loc: "flow",
195
+ errors: batchRows(subject, e.message, cards),
196
+ },
197
+ };
198
+ }
199
+ throw e;
200
+ }
201
+ let compiled;
202
+ try {
203
+ compiled = compileFlow(flow, fullRec, cards);
204
+ }
205
+ catch (e) {
206
+
207
+
208
+
209
+
210
+ if (e instanceof FlowError) {
211
+ return {
212
+ status: 400,
213
+ payload: {
214
+ error: e.message,
215
+ code: "flow_compile",
216
+ loc: "flow",
217
+ errors: batchRows(subject, e.message, cards),
218
+ },
219
+ };
220
+ }
221
+
222
+ throw e;
223
+ }
224
+ const wfRows = sweepWorkflows(subject, cards);
225
+ if (wfRows.length > 0) {
226
+ const first = wfRows[0];
227
+ return {
228
+ status: 400,
229
+ payload: {
230
+ error: first["error"],
231
+ code: "workflow_pin",
232
+ loc: first["stage"], // sweep rows always stamp stage
233
+ errors: wfRows,
234
+ },
235
+ };
236
+ }
237
+ return {
238
+ status: 200,
239
+ payload: {
240
+ ok: true,
241
+ skipped: compiled.skipped,
242
+ flow: flow.id,
243
+ cost: costPreview(compiled.nodes.map((n) => n.engine)),
244
+ stages: compiled.nodes.map((n) => ({
245
+ id: n.id,
246
+ engine: n.engine,
247
+ description: n.description,
248
+ inputs: n.inputFrom,
249
+ outputs: Object.fromEntries(n.outputs.map((o) => [o.name, o.kind])),
250
+ })),
251
+ },
252
+ };
253
+ }
254
+ //# sourceMappingURL=runsValidateServe.js.map