comfy-ts 0.3.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +349 -255
  2. package/dist/DefinedWorkflow-O3ynII3Y.js +598 -0
  3. package/dist/DefinedWorkflow-O3ynII3Y.js.map +1 -0
  4. package/dist/cli.js +3969 -128
  5. package/dist/cli.js.map +1 -1
  6. package/dist/index.cjs +1208 -170
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +449 -115
  9. package/dist/index.d.ts +449 -115
  10. package/dist/index.js +1200 -171
  11. package/dist/index.js.map +1 -1
  12. package/dist/{run-tui-Io8Xea0L.js → run-tui-BFhba_oG.js} +744 -665
  13. package/dist/run-tui-BFhba_oG.js.map +1 -0
  14. package/examples/01-txt2img.cflow.ts +50 -0
  15. package/examples/02-img2img-upload.cflow.ts +66 -0
  16. package/examples/03-export-workflow-json.cflow.ts +56 -0
  17. package/examples/04-krea2-turbo-t2i.cflow.ts +125 -0
  18. package/examples/05-comfy-cloud.cflow.ts +67 -0
  19. package/examples/comfy-cloud/sdk.d.ts +122674 -0
  20. package/guide-for-agents.md +166 -0
  21. package/package.json +7 -3
  22. package/src/cli/comfy-ts-cli.ts +19 -2
  23. package/src/cli/gen.ts +21 -12
  24. package/src/cli/tui/components/Header.tsx +5 -0
  25. package/src/cli/tui/components/LogsPanel.tsx +23 -0
  26. package/src/cli/tui/components/PreviewPanel.tsx +52 -7
  27. package/src/cli/tui/components/StatusBar.tsx +10 -4
  28. package/src/cli/tui/components/TreePanel.tsx +15 -2
  29. package/src/cli/tui/components/TuiApp.tsx +26 -3
  30. package/src/cli/tui/discoverWorkflows.ts +79 -0
  31. package/src/cli/tui/protocolImagePainter.ts +54 -18
  32. package/src/cli/tui/run-tui.tsx +55 -24
  33. package/src/cli/tui/state/ExecSt.ts +4 -1
  34. package/src/cli/tui/state/HostSt.ts +123 -1
  35. package/src/cli/tui/state/LogsSt.ts +107 -0
  36. package/src/cli/tui/state/PreviewSt.ts +173 -23
  37. package/src/cli/tui/state/SettingsSt.ts +48 -21
  38. package/src/cli/tui/state/TreeSt.ts +30 -6
  39. package/src/cli/tui/state/TuiSt.ts +27 -3
  40. package/src/cli/tui/state/WorkflowsSt.ts +16 -1
  41. package/src/host/ComfyHost.ts +241 -71
  42. package/src/host/ComfyManager.ts +10 -9
  43. package/src/host/ComfyUploader.ts +1 -2
  44. package/src/host/ResilientWebsocket.ts +3 -1
  45. package/src/host/hostUrl.ts +59 -0
  46. package/src/host/loraManagerApi.ts +5 -4
  47. package/src/index.ts +20 -1
  48. package/src/litegraph/CanonicalWorkflow.ts +77 -0
  49. package/src/litegraph/LiteGraphGroup.ts +9 -7
  50. package/src/litegraph/LiteGraphJSON.ts +34 -13
  51. package/src/litegraph/LiteGraphLink.ts +32 -2
  52. package/src/litegraph/LiteGraphNode.ts +18 -33
  53. package/src/litegraph/LiteGraphNodeInput.ts +10 -8
  54. package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
  55. package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
  56. package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
  57. package/src/litegraph/expandSubgraphs.ts +352 -0
  58. package/src/litegraph/normalizeWorkflow.ts +141 -0
  59. package/src/runner/ComfyExecution.ts +4 -5
  60. package/src/runner/ComfyWorkflow.ts +2 -2
  61. package/src/runner/ComfyWsApi.ts +12 -1
  62. package/src/runner/wsBinaryFrame.ts +48 -0
  63. package/src/sdk-generator/Primitives.ts +6 -24
  64. package/src/sdk-generator/comfy-api-json.ts +3 -1
  65. package/src/sdk-generator/inputWidgetKind.ts +179 -0
  66. package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
  67. package/src/ssh-host-manager/ssh-manager.ts +0 -15
  68. package/src/state.ts +13 -2
  69. package/src/utils/ansi.ts +7 -0
  70. package/src/utils/mojibake.ts +60 -0
  71. package/dist/log-CdfgILde.js +0 -10
  72. package/dist/log-CdfgILde.js.map +0 -1
  73. package/dist/run-tui-Io8Xea0L.js.map +0 -1
@@ -1,139 +1,426 @@
1
- import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
2
- import type { LiteGraphLink } from 'src/litegraph/LiteGraphLink.ts'
1
+ import type {
2
+ CanonicalInput,
3
+ CanonicalLink,
4
+ CanonicalNode,
5
+ CanonicalWorkflow,
6
+ } from 'src/litegraph/CanonicalWorkflow.ts'
3
7
  import type { LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'
4
- import type { LiteGraphNode } from 'src/litegraph/LiteGraphNode.ts'
5
- import type { LiteGraphNodeInput } from 'src/litegraph/LiteGraphNodeInput.ts'
6
8
  import type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
7
9
  import type { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'
8
10
  import type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
9
11
  import type { NodeInputExt } from 'src/sdk-generator/comfyui-types.ts'
12
+ import { howManyWidgetValuesForThisInputType } from 'src/sdk-generator/Primitives.ts'
10
13
  import {
11
- howManyWidgetValuesForThisInputType,
12
- howManyWidgetValuesForThisSchemaType,
13
- UnknownCustomNode,
14
- } from 'src/sdk-generator/Primitives.ts'
15
- import type { Maybe } from 'src/types/index.ts'
14
+ classifySchemaInput,
15
+ classifyWidgetInput,
16
+ defaultValueForWidget,
17
+ isRecord,
18
+ type DynamicComboOption,
19
+ type RawInputSpecEntry,
20
+ } from 'src/sdk-generator/inputWidgetKind.ts'
21
+
22
+ type PromptInputValue = ComfyApiNodeJson['inputs'][string]
23
+
24
+ export type WorkflowConvertErrorCode =
25
+ | 'unknown-node'
26
+ | 'missing-widget-value'
27
+ | 'invalid-widget-value'
28
+ | 'unknown-dynamic-combo-option'
29
+ | 'dangling-link'
30
+ | 'missing-required-input'
31
+ | 'unsupported-feature'
32
+
33
+ /** a canonical workflow the converter cannot turn into a prompt — the code NAMES the feature that failed */
34
+ export class WorkflowConvertError extends Error {
35
+ constructor(
36
+ public code: WorkflowConvertErrorCode,
37
+ message: string,
38
+ public node?: { id: number; type: string },
39
+ ) {
40
+ super(`[workflow ${code}] ${message}`)
41
+ this.name = 'WorkflowConvertError'
42
+ }
43
+ }
44
+
45
+ /**
46
+ * closed set: frontend-only node types that NEVER execute. PrimitiveString /
47
+ * PrimitiveInt / PrimitiveBoolean etc are REAL backend nodes — do not add them.
48
+ */
49
+ const VIRTUAL_NODE_TYPES: ReadonlySet<string> = new Set(['Note', 'MarkdownNote', 'Reroute', 'PrimitiveNode'])
50
+
51
+ const isNeverExecuted = (node: CanonicalNode): boolean => node.isVirtualNode || VIRTUAL_NODE_TYPES.has(node.type)
52
+
53
+ /** exact match, or `*` wildcard on either side (Reroute-style slots) */
54
+ /** frontend isValidConnection parity: exact, `*` wildcard, or any member of a comma-separated multi-type */
55
+ const linkTypeMatches = (a: string, b: string): boolean => {
56
+ if (a === b || a === '*' || b === '*') return true
57
+ if (!a.includes(',') && !b.includes(',')) return false
58
+ const as = a.split(',')
59
+ const bs = b.split(',')
60
+ return as.some((x) => bs.includes(x))
61
+ }
62
+
63
+ /** what an inlined PrimitiveNode may contribute: scalar widget values only */
64
+ const isPromptScalar = (v: unknown): v is string | number | boolean | null =>
65
+ v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'
16
66
 
17
67
  /**
18
- * convert a saved ComfyUI workflow.json (litegraph format) into the api.json
19
- * (prompt format) ComfyUI's POST /prompt takes.
20
- * Handles: muted nodes, Note/Reroute/PrimitiveNode virtual nodes (reroutes
21
- * unwrapped, primitives inlined into their consumers), widget-value offsets
22
- * (incl. the phantom `control_after_generate` value after seeds).
68
+ * convert a normalized workflow (CanonicalWorkflow — see parseWorkflowJson)
69
+ * into the api.json (prompt format) ComfyUI's POST /prompt takes.
70
+ * Handles: muted nodes (skipped, consumers resolve unconnected), bypassed
71
+ * nodes (mode 4: link resolution walks through to the first type-matching
72
+ * input), Note/MarkdownNote/Reroute/PrimitiveNode virtual nodes (reroutes
73
+ * unwrapped, primitives inlined into their consumers), widget values both
74
+ * positional (with the phantom `control_after_generate` offset after seeds)
75
+ * and named (object-form widgets_values + subgraph promotion overrides —
76
+ * named wins, but a live link wins over both). Widget-ness is decided from
77
+ * the input CONFIG (inputWidgetKind.ts): V3 string-spelled widget types
78
+ * (COMBO options, dynamic combos, autogrow containers, socketless customs)
79
+ * and 2024-era enums go through ONE classifier; a positional array shorter
80
+ * than the schema's widget list fills schema defaults, never throws
81
+ * (agent/architecture.md owns both decisions).
23
82
  */
24
83
  export const convertLiteGraphToPrompt = (
25
84
  /** the ComfySchema object (to look for references/definitions) */
26
85
  schema: ComfySchema,
27
- /** the litegraph */
28
- workflow: LiteGraphJSON,
86
+ /** the normalized litegraph document */
87
+ workflow: CanonicalWorkflow,
29
88
  opts: { verbose?: boolean } = {},
30
89
  ): ComfyApiJson => {
31
90
  const prompt: ComfyApiJson = {}
32
91
  const LOG = opts.verbose ? (...args: unknown[]): void => console.log('[🔥] converter:', ...args) : (): void => {}
33
92
 
34
- // 1. cache primitive node values so links from PrimitiveNode inline as values
93
+ // 1. cache primitive node values so links from PrimitiveNode inline as values.
94
+ // A PrimitiveNode may serialize WITHOUT a value (real corpus case): its
95
+ // consumers then resolve unconnected and fall back to their OWN serialized
96
+ // widget values — the primitive only mirrors the consumer's widget.
35
97
  const PRIMITIVE_VALUES: { [nodeId: string]: unknown } = {}
36
98
  for (const node of workflow.nodes) {
37
- if (node.type === 'PrimitiveNode') {
38
- const widgetValues = node.widgets_values
39
- if (widgetValues == null || widgetValues.length === 0) {
40
- throw new Error(`PrimitiveNode#${node.id} has no widget values`)
41
- }
42
- PRIMITIVE_VALUES[node.id] = widgetValues[0]
43
- }
99
+ if (node.type !== 'PrimitiveNode') continue
100
+ if (node.widgets.positional.length > 0) PRIMITIVE_VALUES[node.id] = node.widgets.positional[0]
101
+ else if (Object.hasOwn(node.widgets.named, 'value')) PRIMITIVE_VALUES[node.id] = node.widgets.named['value']
44
102
  }
45
103
 
46
104
  // 2. every executable node
47
105
  for (const node of workflow.nodes) {
48
- if (node.isVirtualNode) continue // frontend-only nodes
49
- if (node.mode === 2) continue // muted
50
- if (node.type === 'Reroute') continue // unwrapped below
51
- if (node.type === 'Note') continue // comments
52
- if (node.type === 'PrimitiveNode') continue // inlined into consumers
106
+ if (isNeverExecuted(node)) continue // frontend-only nodes (reroutes/primitives unwrapped below)
107
+ if (node.mode !== 'normal') continue // muted skipped, bypassed passthrough'd at link resolution
53
108
 
54
109
  const inputs: ComfyApiNodeJson['inputs'] = {}
55
- const fieldNamesWithLinks = new Set((node.inputs ?? []).map((i) => i.name))
110
+ const fieldNamesPresent = new Set(node.inputs.map((i) => i.name))
56
111
  const nodeSchema_ = schema.nodesByNameInComfy[node.type]
57
- if (nodeSchema_ == null) throw new UnknownCustomNode(node)
112
+ if (nodeSchema_ == null)
113
+ throw new WorkflowConvertError(
114
+ 'unknown-node',
115
+ `node ${node.id}(${node.type}) has no schema on this host; a custom node is missing`,
116
+ node,
117
+ )
58
118
  const nodeSchema: ComfyNodeSchema = nodeSchema_
59
119
 
60
- // 2.a widget values, consumed in schema order
120
+ // 2.a widget values, walked in schema order. Widget-ness comes from the
121
+ // input CONFIG (classifySchemaInput — agent/architecture.md): named wins,
122
+ // else positional cursor, else SCHEMA-DEFAULT FILL (what the frontend
123
+ // does when an old file meets a grown schema — a throw would reject files
124
+ // ComfyUI runs fine). The offset advances past named-shadowed slots
125
+ // whenever a positional array exists (promotion case). A LIVE LINK on
126
+ // the field wins over both — the widget value is kept as the fallback
127
+ // for dead-end link resolution (muted/bypassed parents).
61
128
  let offset = 0
62
- const inputsInNodeJSON: LiteGraphNodeInput[] = node.inputs ?? []
129
+ const positional = node.widgets.positional
130
+ const named = node.widgets.named
131
+ const widgetFallback = new Map<string, PromptInputValue>()
132
+ const inputsInNodeJSON: CanonicalInput[] = node.inputs
63
133
  const inputsInNodeSchema: NodeInputExt[] = nodeSchema.inputs
134
+
135
+ /** arrays ride wrapped (a bare 2-list is a link server-side); objects pass only in lax (custom-widget) domains */
136
+ const toPromptValue = (value: unknown, p: { promptName: string; strict: boolean }): PromptInputValue => {
137
+ if (value == null) return null
138
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value
139
+ if (Array.isArray(value)) return { __value__: value }
140
+ if (!p.strict && isRecord(value)) return value
141
+ throw new WorkflowConvertError(
142
+ 'invalid-widget-value',
143
+ `node ${node.id}(${node.type}) has an invalid widget value for "${p.promptName}": ${JSON.stringify(value)}`,
144
+ node,
145
+ )
146
+ }
147
+
148
+ /** named wins, then positional cursor; filled=true when both miss (caller falls back to the schema default) */
149
+ const resolveWidgetValue = (p: { promptName: string; consumes: number }): { value: unknown; filled: boolean } => {
150
+ let value: unknown
151
+ let has = false
152
+ if (Object.hasOwn(named, p.promptName)) {
153
+ value = named[p.promptName]
154
+ has = true
155
+ } else if (offset < positional.length) {
156
+ value = positional[offset]
157
+ has = true
158
+ }
159
+ if (positional.length > 0) offset += p.consumes // named-shadow still advances (promotion case)
160
+ return { value, filled: !has }
161
+ }
162
+
163
+ const consumePlainWidget = (p: {
164
+ promptName: string
165
+ typeName: string
166
+ opts: unknown
167
+ consumes: number
168
+ strict: boolean
169
+ enumValues?: readonly (string | boolean | number)[]
170
+ linkedInput: CanonicalInput | undefined
171
+ }): void => {
172
+ const r = resolveWidgetValue({ promptName: p.promptName, consumes: p.consumes })
173
+ const raw = r.filled
174
+ ? defaultValueForWidget({
175
+ type: p.typeName,
176
+ opts: p.opts,
177
+ enumValues: p.enumValues ?? schema.knownUnionByName.get(p.typeName)?.values,
178
+ })
179
+ : r.value
180
+ const value = toPromptValue(raw, { promptName: p.promptName, strict: p.strict })
181
+ if (r.filled) LOG(`${node.type}#${node.id}.${p.promptName} = ${JSON.stringify(value)} (schema-default fill)`)
182
+ if (p.linkedInput?.link != null) widgetFallback.set(p.promptName, value)
183
+ else inputs[p.promptName] = value
184
+ }
185
+
186
+ /** key consumed first, then the SELECTED branch inline, recursively (backend get_finalized_class_inputs) */
187
+ const consumeDynamicCombo = (p: { path: string; options: DynamicComboOption[]; defaultKey: string }): void => {
188
+ const r = resolveWidgetValue({ promptName: p.path, consumes: 1 })
189
+ const key = r.filled ? p.defaultKey : r.value
190
+ if (typeof key !== 'string')
191
+ throw new WorkflowConvertError(
192
+ 'invalid-widget-value',
193
+ `node ${node.id}(${node.type}): dynamic combo "${p.path}" key is not a string: ${JSON.stringify(key)}`,
194
+ node,
195
+ )
196
+ const opt = p.options.find((o) => o.key === key)
197
+ // own code: usually the template is NEWER than this host's node
198
+ // (version drift, same class as unknown-node), not a garbage value
199
+ if (opt == null)
200
+ throw new WorkflowConvertError(
201
+ 'unknown-dynamic-combo-option',
202
+ `node ${node.id}(${node.type}): "${key}" is not an option of dynamic combo "${p.path}" (options: ${p.options.map((o) => o.key).join(', ')})`,
203
+ node,
204
+ )
205
+ if (r.filled) LOG(`${node.type}#${node.id}.${p.path} = ${key} (schema-default fill)`)
206
+ inputs[p.path] = key
207
+ for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub)
208
+ }
209
+
210
+ const consumeBranchInput = (subPath: string, sub: RawInputSpecEntry): void => {
211
+ const kind = classifyWidgetInput({ name: sub.name, type: sub.type, opts: sub.opts })
212
+ // slots and containers materialize as dotted serialized inputs, resolved as links in 2.b
213
+ if (kind.kind === 'slot' || kind.kind === 'dynamic-container') return
214
+ if (kind.kind === 'dynamic-combo')
215
+ return consumeDynamicCombo({ path: subPath, options: kind.options, defaultKey: kind.defaultKey })
216
+ const inlineEnum = Array.isArray(sub.type)
217
+ ? sub.type.filter(
218
+ (v): v is string | number | boolean =>
219
+ typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean',
220
+ )
221
+ : undefined
222
+ consumePlainWidget({
223
+ promptName: subPath,
224
+ typeName: typeof sub.type === 'string' ? sub.type : 'COMBO',
225
+ opts: sub.opts,
226
+ consumes: kind.consumes,
227
+ strict: kind.strictValues,
228
+ enumValues: inlineEnum,
229
+ linkedInput: inputsInNodeJSON.find((i) => i.name === subPath),
230
+ })
231
+ }
232
+
64
233
  for (const field of inputsInNodeSchema) {
65
234
  const input = inputsInNodeJSON.find((i) => i.name === field.nameInComfy)
66
- const MUST_CONSUME = input?.type
67
- ? howManyWidgetValuesForThisInputType(input.type, field.nameInComfy)
68
- : howManyWidgetValuesForThisSchemaType(field)
69
-
70
- if (MUST_CONSUME > 0) {
71
- if (node.widgets_values == null)
72
- throw new Error(
73
- `node ${node.id}(${node.type}) has no widgets_values but "${field.nameInComfy}" needs one`,
74
- )
75
- if (node.widgets_values.length < offset + 1)
76
- throw new Error(`node ${node.id}(${node.type}) has not enough widgets_values for "${field.nameInComfy}"`)
77
- const _value = node.widgets_values[offset]
78
- LOG(`${node.type}#${node.id}.${field.nameInComfy} = ${_value} (widget, consumes ${MUST_CONSUME})`)
79
- if (!isValidValue(_value))
80
- throw new Error(
81
- `node ${node.id}(${node.type}) has an invalid widget value for "${field.nameInComfy}": ${JSON.stringify(_value)}`,
82
- )
83
- inputs[field.nameInComfy] = _value
84
- offset += MUST_CONSUME
85
- } else if (!fieldNamesWithLinks.has(field.nameInComfy)) {
235
+ let kind = classifySchemaInput(field)
236
+ // era drift: the file serialized this input widget-backed while the
237
+ // schema now says slot (e.g. forceInput added later) — the file
238
+ // proves a widget value was written, so consume per the file's era
239
+ if (kind.kind === 'slot' && input?.widgetName != null) {
240
+ const legacyConsumes = howManyWidgetValuesForThisInputType(input.type, field.nameInComfy)
241
+ kind = { kind: 'widget', consumes: legacyConsumes === 2 ? 2 : 1, strictValues: true }
242
+ }
243
+
244
+ if (kind.kind === 'widget') {
245
+ consumePlainWidget({
246
+ promptName: field.nameInComfy,
247
+ typeName: field.typeName,
248
+ opts: field.opts,
249
+ consumes: kind.consumes,
250
+ strict: kind.strictValues,
251
+ linkedInput: input,
252
+ })
253
+ } else if (kind.kind === 'dynamic-combo') {
254
+ consumeDynamicCombo({ path: field.nameInComfy, options: kind.options, defaultKey: kind.defaultKey })
255
+ } else if (kind.kind === 'dynamic-container') {
256
+ // the declaration itself never appears; the first template.min
257
+ // instances must be connected (backend requires them by name)
258
+ for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
259
+ const iname = `${field.nameInComfy}.${instName}`
260
+ const inst = inputsInNodeJSON.find((i) => i.name === iname)
261
+ if (inst?.link == null)
262
+ throw new WorkflowConvertError(
263
+ 'missing-required-input',
264
+ `node ${node.id}(${node.type}): autogrow "${field.nameInComfy}" requires instance "${iname}" connected (template.min = ${kind.requiredCount})`,
265
+ node,
266
+ )
267
+ }
268
+ } else if (!fieldNamesPresent.has(field.nameInComfy)) {
86
269
  if (field.required)
87
- throw new Error(
270
+ throw new WorkflowConvertError(
271
+ 'missing-required-input',
88
272
  `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`,
273
+ node,
89
274
  )
90
275
  }
91
276
  }
92
277
 
93
278
  // 2.b links
94
- type ParentInfo = { node: LiteGraphNode; link: LiteGraphLink }
279
+ type ParentInfo = { node: CanonicalNode; link: CanonicalLink }
95
280
  const getParentNode = (linkId: LiteGraphLinkID): ParentInfo => {
96
- const link = workflow.links.find((link) => link[0] === linkId)
281
+ const link = workflow.links.find((link) => link.id === linkId)
97
282
  if (link == null)
98
- throw new Error(`Node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`)
99
- const parentId = link[1]
100
- const parentNode = workflow.nodes.find((n) => n.id === parentId)
101
- if (parentNode == null) throw new Error(`link ${linkId} references a non-existent parent node ${parentId}`)
283
+ throw new WorkflowConvertError(
284
+ 'dangling-link',
285
+ `node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`,
286
+ node,
287
+ )
288
+ const parentNode = workflow.nodes.find((n) => n.id === link.originId)
289
+ if (parentNode == null)
290
+ throw new WorkflowConvertError(
291
+ 'dangling-link',
292
+ `link ${linkId} references a non-existent parent node ${link.originId}`,
293
+ node,
294
+ )
102
295
  return { node: parentNode, link }
103
296
  }
104
297
 
105
- INPT: for (const ipt of node.inputs ?? []) {
106
- const isPrimitive = howManyWidgetValuesForThisInputType(ipt.type, ipt.name) > 0
107
- if (isPrimitive) continue
298
+ // mirrors frontend ExecutableNodeDTO._getBypassSlotIndex (verified
299
+ // 2026-07-29, agent/architecture.md "Bypass passthrough"): wildcard
300
+ // consumer type short-circuits to the same-slot input; else same-slot
301
+ // preferred when connection-valid against output AND consumer type; else
302
+ // first EXACT consumer-type match; else first wildcard-tolerant match.
303
+ // The pick ignores link-state on purpose — an unlinked winner resolves
304
+ // unconnected, like the frontend's null link.
305
+ const pickBypassInput = (p: {
306
+ inputs: CanonicalInput[]
307
+ outSlot: number
308
+ outputType: string
309
+ consumerType: string
310
+ }): CanonicalInput | null => {
311
+ const sameSlot = p.inputs[p.outSlot]
312
+ if (p.consumerType === '*' || p.consumerType === '') return sameSlot ?? p.inputs[0] ?? null
313
+ if (
314
+ sameSlot != null &&
315
+ linkTypeMatches(sameSlot.type, p.outputType) &&
316
+ linkTypeMatches(sameSlot.type, p.consumerType)
317
+ )
318
+ return sameSlot
319
+ const exact = p.inputs.find((i) => i.type === p.consumerType)
320
+ if (exact != null) return exact
321
+ return (
322
+ p.inputs.find((i) => linkTypeMatches(i.type, p.outputType) && linkTypeMatches(i.type, p.consumerType)) ??
323
+ null
324
+ )
325
+ }
326
+
327
+ // walk through follow-through parents: Reroute unwraps, bypassed nodes
328
+ // redirect per pickBypassInput above. The match type is RE-DERIVED at
329
+ // each bypass hop from the picked input (frontend resolveOutput calls
330
+ // resolveInput WITHOUT the type param, so the next hop matches on that
331
+ // input's own type); muted parents and dead-end bypasses resolve
332
+ // UNCONNECTED. Visited-set guards link cycles.
333
+ type LinkResolution =
334
+ | { kind: 'link'; nodeId: number; slot: number }
335
+ | { kind: 'primitive'; nodeId: number }
336
+ | { kind: 'unconnected'; reason: string }
337
+ const resolveThroughParents = (startLink: LiteGraphLinkID, consumerType: string): LinkResolution => {
338
+ const visited = new Set<number>()
339
+ let linkId = startLink
340
+ let effectiveType = consumerType
341
+ while (true) {
342
+ const parent: ParentInfo = getParentNode(linkId)
343
+ if (visited.has(parent.node.id))
344
+ throw new WorkflowConvertError(
345
+ 'dangling-link',
346
+ `node ${node.id}(${node.type}): link resolution loops through node ${parent.node.id}`,
347
+ node,
348
+ )
349
+ visited.add(parent.node.id)
350
+ if (parent.node.type === 'Reroute') {
351
+ const rerouteIn = parent.node.inputs[0]?.link
352
+ if (rerouteIn == null) return { kind: 'unconnected', reason: 'reroute chain ends on an empty slot' }
353
+ linkId = rerouteIn
354
+ continue
355
+ }
356
+ if (parent.node.mode === 'muted')
357
+ return { kind: 'unconnected', reason: `parent ${parent.node.id}(${parent.node.type}) is muted` }
358
+ if (parent.node.mode === 'bypassed') {
359
+ const outputType = parent.node.outputs[parent.link.originSlot]?.type ?? parent.link.type
360
+ const through = pickBypassInput({
361
+ inputs: parent.node.inputs,
362
+ outSlot: parent.link.originSlot,
363
+ outputType,
364
+ consumerType: effectiveType,
365
+ })
366
+ if (through?.link == null)
367
+ return {
368
+ kind: 'unconnected',
369
+ reason: `bypassed parent ${parent.node.id}(${parent.node.type}) has no connected ${effectiveType} input to pass through`,
370
+ }
371
+ linkId = through.link
372
+ effectiveType = through.type
373
+ continue
374
+ }
375
+ if (parent.node.type === 'PrimitiveNode') {
376
+ if (!(parent.node.id in PRIMITIVE_VALUES))
377
+ return { kind: 'unconnected', reason: `PrimitiveNode#${parent.node.id} has no widget value` }
378
+ return { kind: 'primitive', nodeId: parent.node.id }
379
+ }
380
+ return { kind: 'link', nodeId: parent.node.id, slot: parent.link.originSlot }
381
+ }
382
+ }
108
383
 
109
- // not a primitive => we assume it's a link
384
+ for (const ipt of node.inputs) {
110
385
  if (ipt.link == null) {
111
- LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (fine when optional)`)
386
+ LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (widget-backed or optional)`)
112
387
  continue
113
388
  }
114
- let parent: Maybe<ParentInfo> = getParentNode(ipt.link)
115
-
116
- // unwrap reroute chains
117
- let max = 100
118
- while (parent != null && parent.node.type === 'Reroute' && max-- > 0) {
119
- const firstParentInput = parent.node.inputs?.[0]
120
- if (firstParentInput?.link == null) {
121
- LOG(`${node.type}#${node.id}.${ipt.name}: reroute chain ends on an empty slot`)
122
- continue INPT
123
- }
124
- parent = getParentNode(firstParentInput.link)
389
+ const resolved = resolveThroughParents(ipt.link, ipt.type)
390
+ if (resolved.kind === 'primitive') {
391
+ // inline primitive nodes as plain values — GUARDED: primitives are
392
+ // scalar widgets, a non-scalar value would cast garbage (or a
393
+ // fake link 2-array) into the prompt
394
+ const pv: unknown = PRIMITIVE_VALUES[resolved.nodeId]
395
+ if (!isPromptScalar(pv))
396
+ throw new WorkflowConvertError(
397
+ 'invalid-widget-value',
398
+ `node ${node.id}(${node.type}): PrimitiveNode#${resolved.nodeId} value is not a scalar: ${JSON.stringify(pv)}`,
399
+ node,
400
+ )
401
+ inputs[ipt.name] = pv
402
+ LOG(`${node.type}#${node.id}.${ipt.name} = ${pv} (inlined primitive)`)
403
+ continue
125
404
  }
126
- if (parent == null) throw new Error(`no parent found for ${node.id}.${ipt.name}`)
127
-
128
- // inline primitive nodes as plain values
129
- if (parent.node.type === 'PrimitiveNode') {
130
- inputs[ipt.name] = PRIMITIVE_VALUES[parent.node.id] as ComfyApiNodeJson['inputs'][string]
131
- LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (inlined primitive)`)
405
+ if (resolved.kind === 'link') {
406
+ LOG(`${node.type}#${node.id}.${ipt.name} = [${resolved.nodeId}, ${resolved.slot}] (link)`)
407
+ inputs[ipt.name] = [String(resolved.nodeId), resolved.slot]
132
408
  continue
133
409
  }
134
-
135
- LOG(`${node.type}#${node.id}.${ipt.name} = [${parent.node.id}, ${parent.link[2]}] (link)`)
136
- inputs[ipt.name] = [String(parent.node.id), parent.link[2]]
410
+ // unconnected: the serialized widget value covers it, else loud when required
411
+ if (widgetFallback.has(ipt.name)) {
412
+ inputs[ipt.name] = widgetFallback.get(ipt.name) ?? null
413
+ LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (widget fallback, ${resolved.reason})`)
414
+ continue
415
+ }
416
+ const field = inputsInNodeSchema.find((f) => f.nameInComfy === ipt.name)
417
+ if (field?.required)
418
+ throw new WorkflowConvertError(
419
+ 'missing-required-input',
420
+ `node ${node.id}(${node.type}): required input "${ipt.name}" resolves unconnected (${resolved.reason}) and no widget value covers it`,
421
+ node,
422
+ )
423
+ LOG(`${node.type}#${node.id}.${ipt.name}: resolves unconnected (${resolved.reason})`)
137
424
  }
138
425
 
139
426
  prompt[String(node.id)] = { inputs, class_type: node.type }
@@ -144,14 +431,3 @@ export const convertLiteGraphToPrompt = (
144
431
 
145
432
  /** alias cause I keep forgetting about this */
146
433
  export const convertWorkflowToPrompt = convertLiteGraphToPrompt
147
-
148
- type ValidValue = string | number | boolean | [string, number] | null
149
- function isValidValue(value: unknown): value is ValidValue {
150
- if (value == null) return true // null is valid
151
- if (typeof value === 'string') return true
152
- if (typeof value === 'number') return true
153
- if (typeof value === 'boolean') return true
154
- if (Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number')
155
- return true
156
- return false
157
- }
@@ -12,21 +12,6 @@ export class SSHHost {
12
12
  this.activeProcesses = new Set()
13
13
  }
14
14
 
15
- async ensurePortForward(port: number): Promise<void> {
16
- try {
17
- // Check if master connection exists
18
- await execAsync(`ssh -O check ${this.host} 2>/dev/null`)
19
- console.log('✅ SSH connection already active')
20
- } catch {
21
- // Establish master connection
22
- console.log('🔌 Establishing SSH connection...')
23
- // reverse tunnel form: ssh -fN -R 8084:localhost:8084 <ssh-host>
24
- // https://explainshell.com/explain?cmd=ssh+-fN+-L
25
- await execAsync(`ssh -fN -L ${port}:127.0.0.1:${port} ${this.host}`)
26
- console.log('✅ SSH connection established')
27
- }
28
- }
29
-
30
15
  async executeCommand(command: string): Promise<string> {
31
16
  const { stdout, stderr } = await execAsync(`ssh ${this.host} "${command}"`)
32
17
  if (stderr) console.error('SSH Error:', stderr)
package/src/state.ts CHANGED
@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from 'node:fs'
2
2
  import { join } from 'pathe'
3
3
  import pkgJson from '../package.json' with { type: 'json' }
4
4
  import { ComfyHost, type ComfyHostData } from 'src/host/ComfyHost.ts'
5
+ import { parseHostBase, renderHttpBase } from 'src/host/hostUrl.ts'
5
6
  import { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
6
7
  import { type AbsolutePath, asAbsolutePath, type RelativePath } from 'src/types/index.ts'
7
8
 
@@ -42,9 +43,19 @@ export class ComfyTS {
42
43
  host<const ID extends string>(data: ComfyHostData & { id: ID }): ComfyHost<ID> {
43
44
  const existing = this.hosts.get(data.id)
44
45
  if (existing != null) {
45
- if (existing.data.host !== data.host || existing.data.port !== data.port || existing.data.https !== data.https)
46
+ // identity = the parsed base quad + apiKey PRESENCE (equivalent url and
47
+ // host/port spellings unify; the key VALUE never appears in the error)
48
+ const incoming = parseHostBase(data)
49
+ const cur = existing.base
50
+ const sameBase =
51
+ cur.scheme === incoming.scheme &&
52
+ cur.host === incoming.host &&
53
+ cur.port === incoming.port &&
54
+ cur.basePath === incoming.basePath
55
+ const sameAuth = (existing.data.apiKey == null) === (data.apiKey == null)
56
+ if (!sameBase || !sameAuth)
46
57
  throw new Error(
47
- `host id '${data.id}' already registered at ${existing.data.host}:${existing.data.port} — refusing ${data.host}:${data.port}`,
58
+ `host id '${data.id}' already registered at ${renderHttpBase(cur)}${existing.data.apiKey != null ? ' (authed)' : ''} — refusing ${renderHttpBase(incoming)}${data.apiKey != null ? ' (authed)' : ''}`,
48
59
  )
49
60
  // cast: whitelist item 7 (agent/coding.md) — id equality checked just above
50
61
  return existing as ComfyHost<ID>
package/src/utils/ansi.ts CHANGED
@@ -24,3 +24,10 @@ function styler(open: string = '', close: string = ''): Styler {
24
24
  }
25
25
 
26
26
  export const ansi: Styler = styler()
27
+
28
+ // CSI sequences + lone ESC-letter escapes (server logs re-rendered inside ink)
29
+ const ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]|\x1b[A-Za-z]/g
30
+
31
+ export function stripAnsi(s: string): string {
32
+ return s.replace(ANSI_RE, '')
33
+ }
@@ -0,0 +1,60 @@
1
+ // cp1252's 0x80-0x9F specials, unicode → original byte (the rest is latin1: code = byte)
2
+ const CP1252_REVERSE: Record<string, number> = {
3
+ '€': 0x80,
4
+ '‚': 0x82,
5
+ ƒ: 0x83,
6
+ '„': 0x84,
7
+ '…': 0x85,
8
+ '†': 0x86,
9
+ '‡': 0x87,
10
+ ˆ: 0x88,
11
+ '‰': 0x89,
12
+ Š: 0x8a,
13
+ '‹': 0x8b,
14
+ Œ: 0x8c,
15
+ Ž: 0x8e,
16
+ '‘': 0x91,
17
+ '’': 0x92,
18
+ '“': 0x93,
19
+ '”': 0x94,
20
+ '•': 0x95,
21
+ '–': 0x96,
22
+ '—': 0x97,
23
+ '˜': 0x98,
24
+ '™': 0x99,
25
+ š: 0x9a,
26
+ '›': 0x9b,
27
+ œ: 0x9c,
28
+ ž: 0x9e,
29
+ Ÿ: 0x9f,
30
+ }
31
+
32
+ /**
33
+ * repair UTF-8 that was decoded as cp1252 (a Windows server re-reading its own
34
+ * output: `█` E2 96 88 arrives as `â–ˆ`). Reverses the cp1252 map back to
35
+ * bytes and re-decodes as UTF-8; any unmappable char or invalid byte sequence
36
+ * means the text was NOT mojibake — the original is returned untouched.
37
+ */
38
+ export function repairMojibake(s: string): string {
39
+ let suspicious = false
40
+ for (let i = 0; i < s.length; i++) {
41
+ if (s.charCodeAt(i) > 0x7f) {
42
+ suspicious = true
43
+ break
44
+ }
45
+ }
46
+ if (!suspicious) return s
47
+ const bytes = new Uint8Array(s.length)
48
+ for (let i = 0; i < s.length; i++) {
49
+ const code = s.charCodeAt(i)
50
+ if (code <= 0xff) {
51
+ bytes[i] = code
52
+ continue
53
+ }
54
+ const mapped = CP1252_REVERSE[s[i] ?? '']
55
+ if (mapped == null) return s
56
+ bytes[i] = mapped
57
+ }
58
+ const decoded = Buffer.from(bytes).toString('utf8')
59
+ return decoded.includes('�') ? s : decoded
60
+ }