-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathpython-bridge-base.ts
More file actions
1767 lines (1641 loc) · 60.9 KB
/
Copy pathpython-bridge-base.ts
File metadata and controls
1767 lines (1641 loc) · 60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Transport-agnostic Python worker bridge base class.
*
* Holds all the protocol logic that is independent of how bytes move
* between the JS runtime and the Python worker — pending-request bookkeeping,
* message dispatch, discover/execute/cancel, provider RPC, and the shared
* connection lifecycle. Concrete transports (stdio, WebSocket) subclass this
* and implement the small set of transport hooks below.
*
* The wire protocol itself (msgpack-encoded `{type, request_id, data}` frames)
* is shared; only framing/transport differs per subclass.
*/
import { getNodeBuiltinSync, safeProcessEnv } from "@nodetool-ai/config";
// The base only needs crypto (request IDs) and events (EventEmitter).
// Lazy-load so the module *graph* loads off-Node; instantiating a concrete
// bridge there throws at construction. Notably the base does NOT require
// child_process — that belongs to the stdio subclass only.
const nodeCrypto = getNodeBuiltinSync<typeof import("node:crypto")>("node:crypto");
const nodeEvents = getNodeBuiltinSync<typeof import("node:events")>("node:events");
function notOnNode(api: string): never {
throw new Error(`${api} requires Node — PythonBridgeBase is Node-only`);
}
const randomUUID =
nodeCrypto?.randomUUID ?? ((): string => notOnNode("node:crypto.randomUUID"));
// Re-export the EventEmitter type/class — falls back to a no-op so the
// module evaluates off-Node; consumers that instantiate the bridge will
// fail at construction time, not at module load.
class FallbackEmitter {
on(_: string, __: (...args: unknown[]) => void): this {
notOnNode("node:events.EventEmitter");
}
emit(_: string, ...__: unknown[]): boolean {
notOnNode("node:events.EventEmitter");
}
removeAllListeners(): this {
notOnNode("node:events.EventEmitter");
}
}
// SAFETY: off-Node the fallback stands in for `EventEmitter` and throws from
// every member. It cannot implement the full class (`once`, `off`,
// `listenerCount`, the static helpers), which `PythonBridge extends
// EventEmitter` puts in the package's public contract.
const EventEmitter = (nodeEvents?.EventEmitter ??
FallbackEmitter) as unknown as typeof import("node:events").EventEmitter;
import { createLogger } from "@nodetool-ai/config";
import {
BRIDGE_PROTOCOL_VERSION,
MIN_BRIDGE_PROTOCOL_VERSION,
MIN_NODETOOL_CORE_VERSION
} from "@nodetool-ai/protocol/bridge-protocol";
import { validateBridgeFrame } from "@nodetool-ai/protocol";
import { isNumber } from "@nodetool-ai/protocol";
const log = createLogger("nodetool.runtime.python-bridge-base");
/**
* Inbound bridge-frame validation gate (task B3). Every frame
* `_handleMessage` dispatches is safe-parsed against its
* `@nodetool-ai/protocol` schema first when this returns true; a frame that
* fails gets a structured, non-fatal rejection (see
* {@link PythonBridgeBase._handleInvalidFrame}) instead of silently
* dispatching malformed data.
*
* Mirrors `shouldValidateOutboundWs` in
* `packages/websocket/src/websocket-client-session.ts`: set
* `NODETOOL_VALIDATE_BRIDGE_FRAMES=1`/`=0` to force on/off; unset, it
* defaults to on under `NODE_ENV=test`/Vitest and off otherwise, so a worker
* bug that emits a malformed frame fails the test that exercised it rather
* than risking a perf hit validating every frame in production before the
* mechanism has burned in.
*/
function shouldValidateBridgeFrames(): boolean {
const override = safeProcessEnv()["NODETOOL_VALIDATE_BRIDGE_FRAMES"]?.trim();
if (override === "1" || override === "true") return true;
if (override === "0" || override === "false") return false;
const env = safeProcessEnv();
return env["NODE_ENV"] === "test" || Boolean(env["VITEST"]);
}
import type {
PythonNodeMetadata,
ExecuteResult,
ExecuteInputBlobs,
ExecuteIdentity,
JobBoundary,
ModelEvictRequest,
ModelEvictResult,
ProgressEvent,
StreamCallback,
PythonProviderInfo,
PythonBridgeOptions,
PythonWorkerLoadError,
PythonWorkerStatus,
UnifiedModelLike,
ModelDownloadRequest,
ModelDownloadUpdate,
ComfyStatusInfo,
ComfyEvent,
ComfyExecuteOptions,
ComfyExecuteResult,
ComfyModelDownloadRequest,
ComfyModelDownloadUpdate,
ComfyModelInfo,
BlenderExecuteJob,
BlenderStatusInfo,
BlenderEvent,
BlenderExecuteOptions,
BlenderExecuteResult,
PythonBridge
} from "./python-bridge-types.js";
import {
comfyStatusInfoSchema,
workerStatusSchema
} from "./python-bridge-types.js";
interface PendingRequest {
resolve: (value: ExecuteResult) => void;
reject: (error: Error) => void;
onProgress?: (event: ProgressEvent) => void;
blobTransfers?: Map<string, BlobTransfer>;
completedBlobs?: Record<string, Uint8Array>;
}
interface BlobTransfer {
size: number;
received: number;
chunks: Uint8Array[];
}
interface PendingStreamRequest {
resolve: (value: Record<string, unknown>) => void;
reject: (error: Error) => void;
onChunk: StreamCallback;
}
const DEFAULT_EXECUTE_TIMEOUT_MS = Number(
safeProcessEnv()["NODETOOL_PYTHON_EXECUTE_TIMEOUT_MS"] ?? 12 * 60 * 1000
);
const DEFAULT_STATUS_TIMEOUT_MS = Number(
safeProcessEnv()["NODETOOL_PYTHON_STATUS_TIMEOUT_MS"] ?? 30000
);
const DEFAULT_DOWNLOAD_IDLE_TIMEOUT_MS = Number(
safeProcessEnv()["NODETOOL_PYTHON_DOWNLOAD_IDLE_TIMEOUT_MS"] ?? 5 * 60 * 1000
);
const MAX_RESULT_BLOB_BYTES = Number(
safeProcessEnv()["NODETOOL_PYTHON_MAX_RESULT_BLOB_BYTES"] ?? 2 * 1024 * 1024 * 1024
);
/**
* Transport-agnostic Python bridge. Subclasses provide the transport via
* {@link _openTransport} and {@link _send}, plus {@link close}. The optional
* {@link _assertCanConnect} hook lets a transport refuse to connect (e.g. in
* production).
*/
export abstract class PythonBridgeBase
extends EventEmitter
implements PythonBridge
{
protected _nodeMetadata: PythonNodeMetadata[] = [];
protected _loadErrors: PythonWorkerLoadError[] = [];
protected _workerStatus: PythonWorkerStatus | null = null;
protected _pending = new Map<string, PendingRequest>();
protected _pendingStream = new Map<string, PendingStreamRequest>();
/**
* `comfy.execute` event callbacks, keyed by request id. Separate from the
* pending maps because `comfy.event` frames are neither `progress` (wrong
* shape) nor terminal — they stream the ComfyUI lifecycle while the same
* request's terminal `result`/`error` settles via {@link _pendingStream}.
*/
protected _pendingComfyEvents = new Map<
string,
(event: ComfyEvent) => void
>();
/**
* `blender.execute` event callbacks, keyed by request id. Same shape as
* {@link _pendingComfyEvents}: `blender.event` frames stream progress while
* the same request's terminal `result`/`error` settles via
* {@link _pendingStream}.
*/
protected _pendingBlenderEvents = new Map<
string,
(event: BlenderEvent) => void
>();
protected _options: PythonBridgeOptions;
protected _connected = false;
private _connectPromise: Promise<void> | null = null;
constructor(options: PythonBridgeOptions = {}) {
super();
this._options = options;
}
/**
* Requests still awaiting a worker reply (plain, streaming, and Comfy event
* subscriptions). Exposed for leak accounting — a run that ended with
* pending requests left a promise nothing will ever settle.
*/
get pendingRequestCount(): number {
return (
this._pending.size +
this._pendingStream.size +
this._pendingComfyEvents.size +
this._pendingBlenderEvents.size
);
}
// ── Transport hooks (implemented by subclasses) ─────────────────────
/** Open the underlying transport and become connected. */
protected abstract _openTransport(): Promise<void>;
/** Encode + send a single protocol message over the transport. */
protected abstract _send(msg: Record<string, unknown>): void;
/** Tear down the transport and reject any pending requests. */
abstract close(): void;
/**
* Optional guard invoked at the start of connect(). Throw to refuse.
* Default is a no-op.
*/
protected _assertCanConnect(): void {}
// ── Connection lifecycle ───────────────────────────────────────────
async connect(): Promise<void> {
this._assertCanConnect();
await this._openTransport();
await this._discover();
try {
await this._getWorkerStatusWithTimeout();
} catch (err) {
log.warn(
"Failed to fetch initial Python worker status; load_errors will be unavailable until next status fetch",
err
);
}
}
ensureConnected(): Promise<void> {
if (this._connected) return Promise.resolve();
if (!this._connectPromise) {
this._connectPromise = this.connect().then(
() => {
this._connectPromise = null;
},
(err) => {
this._connectPromise = null;
throw err;
}
);
}
return this._connectPromise;
}
// ── Message dispatch ────────────────────────────────────────────────
protected _handleMessage(msg: Record<string, unknown>): void {
const type = msg.type as string;
const requestId = msg.request_id as string | null;
if (shouldValidateBridgeFrames()) {
const validation = validateBridgeFrame(msg);
if (!validation.success) {
this._handleInvalidFrame(type, requestId, validation.error);
return;
}
}
if (type === "discover" && requestId) {
const pending = this._pending.get(requestId);
if (pending) {
const data = msg.data as {
nodes: PythonNodeMetadata[];
protocol_version?: number;
load_errors?: PythonWorkerLoadError[];
};
// Reject the discover promise only if the worker's protocol is below
// the HARD FLOOR (a real wire break). Workers at or above the floor
// but below BRIDGE_PROTOCOL_VERSION still connect — newer, additive
// features are gated per-capability (e.g. supportsModelManagement),
// so an older worker keeps running everything it understands. Workers
// that pre-date the protocol_version field are treated as version 1
// (the initial release) — same wire format, they just don't announce.
const workerVersion =
isNumber(data.protocol_version) ? data.protocol_version : 1;
if (workerVersion < MIN_BRIDGE_PROTOCOL_VERSION) {
this._pending.delete(requestId);
pending.reject(
new Error(
`The installed nodetool-core speaks bridge protocol v${workerVersion}, ` +
`but this Nodetool build requires at least v${MIN_BRIDGE_PROTOCOL_VERSION}. ` +
`Please reinstall the Python environment from Settings → Packages ` +
`(Reinstall environment) — it will fetch nodetool-core>=${MIN_NODETOOL_CORE_VERSION}.`
)
);
return;
}
if (workerVersion > BRIDGE_PROTOCOL_VERSION) {
// Forward-compat: a newer worker is expected to keep speaking
// older protocols, so we proceed with a warning.
this.emit(
"stderr",
`[python-bridge] Worker protocol v${workerVersion} is newer than ` +
`JS runtime v${BRIDGE_PROTOCOL_VERSION}; assuming backward compatibility.\n`
);
}
this._nodeMetadata = data.nodes;
this._loadErrors = data.load_errors ?? [];
pending.resolve({ outputs: {}, blobs: {} });
}
} else if (type === "result" && requestId) {
const streamReq = this._pendingStream.get(requestId);
if (streamReq) {
this._pendingStream.delete(requestId);
streamReq.resolve(msg.data as Record<string, unknown>);
return;
}
const pending = this._pending.get(requestId);
if (pending) {
this._pending.delete(requestId);
if (pending.blobTransfers?.size) {
pending.reject(
new Error("Python worker ended the result before all blob transfers completed")
);
return;
}
const data = msg.data as {
outputs: Record<string, unknown>;
blobs: Record<string, Uint8Array>;
};
pending.resolve({
outputs: data.outputs,
blobs: { ...(data.blobs ?? {}), ...(pending.completedBlobs ?? {}) }
});
}
} else if (type === "error" && requestId) {
const streamReq = this._pendingStream.get(requestId);
if (streamReq) {
this._pendingStream.delete(requestId);
const data = msg.data as { error: string; traceback?: string };
const err = new Error(data.error);
Reflect.set(err, "traceback", data.traceback);
streamReq.reject(err);
return;
}
const pending = this._pending.get(requestId);
if (pending) {
this._pending.delete(requestId);
const data = msg.data as { error: string; traceback?: string };
const err = new Error(data.error);
Reflect.set(err, "traceback", data.traceback);
pending.reject(err);
}
} else if (type === "chunk" && requestId) {
const streamReq = this._pendingStream.get(requestId);
if (streamReq) {
streamReq.onChunk(msg.data as Record<string, unknown>);
}
} else if (type === "blob.start" && requestId) {
this._startBlobTransfer(requestId, msg.data as Record<string, unknown>);
} else if (type === "blob.chunk" && requestId) {
this._appendBlobChunk(requestId, msg.data as Record<string, unknown>);
} else if (type === "blob.end" && requestId) {
this._finishBlobTransfer(requestId, msg.data as Record<string, unknown>);
} else if (type === "progress" && requestId) {
const pending = this._pending.get(requestId);
if (pending?.onProgress) {
const data = msg.data as { progress: number; total: number };
pending.onProgress({ request_id: requestId, ...data });
}
this.emit("progress", msg.data);
} else if (type === "comfy.event" && requestId) {
// Dedicated `comfy.execute` lifecycle frame. Distinct from `progress`
// because ComfyUI's events don't fit `{progress,total,message}`. Without
// this explicit case the frames would fall through and vanish silently.
const onEvent = this._pendingComfyEvents.get(requestId);
if (onEvent) {
onEvent(msg.data as ComfyEvent);
}
} else if (type === "blender.event" && requestId) {
// Dedicated `blender.execute` progress frame, mirroring `comfy.event`:
// frame progress does not fit `{progress,total,message}` either, and
// without this case the frames fall through and vanish silently — which
// is also what an older build without this case does with them.
const onEvent = this._pendingBlenderEvents.get(requestId);
if (onEvent) {
onEvent(msg.data as BlenderEvent);
}
}
}
private _rejectBlobTransfer(requestId: string, message: string): void {
const pending = this._pending.get(requestId);
if (!pending) return;
this._pending.delete(requestId);
pending.reject(new Error(message));
try {
this.cancel(requestId);
} catch {
// The worker may already have completed; cancellation is best-effort.
}
}
private _startBlobTransfer(
requestId: string,
data: Record<string, unknown>
): void {
const pending = this._pending.get(requestId);
const name = data["name"];
const size = data["size"];
if (!pending || typeof name !== "string" || typeof size !== "number") return;
if (!Number.isSafeInteger(size) || size < 0 || size > MAX_RESULT_BLOB_BYTES) {
this._rejectBlobTransfer(
requestId,
`Python worker declared invalid blob size ${String(size)} for "${name}"`
);
return;
}
pending.blobTransfers ??= new Map();
pending.completedBlobs ??= Object.create(null) as Record<string, Uint8Array>;
if (pending.blobTransfers.has(name) || Object.hasOwn(pending.completedBlobs, name)) {
this._rejectBlobTransfer(requestId, `Python worker started duplicate blob "${name}"`);
return;
}
pending.blobTransfers.set(name, { size, received: 0, chunks: [] });
}
private _appendBlobChunk(
requestId: string,
data: Record<string, unknown>
): void {
const pending = this._pending.get(requestId);
const name = data["name"];
const offset = data["offset"];
const bytes = data["bytes"];
if (
!pending ||
typeof name !== "string" ||
typeof offset !== "number" ||
!(bytes instanceof Uint8Array)
) return;
const transfer = pending.blobTransfers?.get(name);
if (!transfer || offset !== transfer.received || offset + bytes.length > transfer.size) {
this._rejectBlobTransfer(
requestId,
`Python worker sent an out-of-order or oversized chunk for blob "${name}"`
);
return;
}
transfer.chunks.push(bytes);
transfer.received += bytes.length;
}
private _finishBlobTransfer(
requestId: string,
data: Record<string, unknown>
): void {
const pending = this._pending.get(requestId);
const name = data["name"];
const size = data["size"];
const expectedDigest = data["sha256"];
if (
!pending ||
typeof name !== "string" ||
typeof size !== "number" ||
typeof expectedDigest !== "string"
) return;
const transfer = pending.blobTransfers?.get(name);
if (!transfer || size !== transfer.size || transfer.received !== transfer.size) {
this._rejectBlobTransfer(requestId, `Python worker truncated blob "${name}"`);
return;
}
const blob = new Uint8Array(transfer.size);
let offset = 0;
for (const chunk of transfer.chunks) {
blob.set(chunk, offset);
offset += chunk.length;
}
const digest = nodeCrypto?.createHash("sha256").update(blob).digest("hex");
if (!digest || digest !== expectedDigest) {
this._rejectBlobTransfer(requestId, `Python worker blob "${name}" failed SHA-256 verification`);
return;
}
pending.blobTransfers?.delete(name);
pending.completedBlobs ??= Object.create(null) as Record<string, Uint8Array>;
pending.completedBlobs[name] = blob;
}
/**
* A frame decoded fine off the wire (valid msgpack) but failed its
* `@nodetool-ai/protocol` schema — a worker-side protocol bug, not a
* transport desync. Unlike an undecodable frame (bad length prefix,
* corrupt msgpack — see each transport's `_failProtocol`), this does NOT
* tear down the connection: only the request the malformed frame carries
* a `request_id` for is failed, so a concurrent request already in flight
* still settles normally.
*
* A frame with no (or non-string) `request_id` can't be attributed to any
* pending request — logged and dropped, matching the dispatcher's
* existing silent-ignore behavior for frame types/ids it doesn't
* recognize.
*/
private _handleInvalidFrame(
type: string | undefined,
requestId: string | null,
reason: string | undefined
): void {
log.warn(
`Rejected malformed Python bridge frame (type=${type ?? "<unknown>"}, request_id=${
requestId ?? "<none>"
}): ${reason ?? "failed schema validation"}`
);
if (!requestId) return;
const err = new Error(
`Received malformed '${type ?? "<unknown>"}' frame from Python worker: ${
reason ?? "failed schema validation"
}`
);
const streamReq = this._pendingStream.get(requestId);
if (streamReq) {
this._pendingStream.delete(requestId);
this._pendingComfyEvents.delete(requestId);
this._pendingBlenderEvents.delete(requestId);
streamReq.reject(err);
return;
}
const pending = this._pending.get(requestId);
if (pending) {
this._pending.delete(requestId);
pending.reject(err);
}
}
protected _rejectAllPending(error: Error): void {
for (const [, req] of this._pending) {
req.reject(error);
}
this._pending.clear();
for (const [, req] of this._pendingStream) {
req.reject(error);
}
this._pendingStream.clear();
this._pendingComfyEvents.clear();
this._pendingBlenderEvents.clear();
}
// ── Discover ───────────────────────────────────────────────────────
protected async _discover(): Promise<void> {
const requestId = randomUUID();
// Bound the discover RPC: _openTransport resolves as soon as the worker
// signals readiness, so a worker that becomes READY but never answers
// discover (wedged/hung post-ready init) would leave connect() pending
// forever. Mirror _getWorkerStatusWithTimeout's timeout handling.
const timeoutMs =
this._options.statusTimeoutMs ?? DEFAULT_STATUS_TIMEOUT_MS;
return new Promise<void>((resolve, reject) => {
let timer: NodeJS.Timeout | undefined;
this._pending.set(requestId, {
resolve: () => {
if (timer) clearTimeout(timer);
this._pending.delete(requestId);
resolve();
},
reject: (err) => {
if (timer) clearTimeout(timer);
this._pending.delete(requestId);
reject(err);
}
});
if (timeoutMs > 0) {
timer = setTimeout(() => {
this._pending.delete(requestId);
reject(
new Error(`Python worker discover timed out after ${timeoutMs}ms.`)
);
}, timeoutMs);
}
try {
this._send({ type: "discover", request_id: requestId, data: {} });
} catch (err) {
if (timer) clearTimeout(timer);
this._pending.delete(requestId);
reject(err instanceof Error ? err : new Error(String(err)));
}
});
}
// ── Node execution ─────────────────────────────────────────────────
/**
* Snake-case the run identity onto the `execute` / `execute.stream` payload,
* dropping fields the caller could not name so the worker sees an absent key
* rather than a null it has to special-case.
*
* Sent unconditionally, not gated on {@link supportsJobLifecycle}: these are
* extra dict entries, and a pre-v4 worker that reads `data["node_type"]`,
* `["fields"]`, `["secrets"]` and `["blobs"]` never looks at them. Gating
* them would only mean a worker that DOES understand them gets nothing
* whenever its `worker.status` hasn't landed yet.
*/
protected _identityPayload(
identity: ExecuteIdentity | undefined
) {
if (!identity) return {};
const payload: Record<string, unknown> = {};
if (identity.nodeId) payload.node_id = identity.nodeId;
if (identity.jobId) payload.job_id = identity.jobId;
if (identity.workflowId) payload.workflow_id = identity.workflowId;
if (identity.userId) payload.user_id = identity.userId;
if (identity.requiresVramGb != null) {
payload.requires_vram_gb = identity.requiresVramGb;
}
return payload;
}
async execute(
nodeType: string,
fields: Record<string, unknown>,
secrets: Record<string, string>,
blobs: ExecuteInputBlobs,
onProgress?: (event: ProgressEvent) => void,
identity?: ExecuteIdentity
): Promise<ExecuteResult> {
const requestId = randomUUID();
const timeoutMs =
this._options.executeTimeoutMs ?? DEFAULT_EXECUTE_TIMEOUT_MS;
log.debug("Python bridge execute dispatched", { nodeType, requestId });
const executeData: Record<string, unknown> = {
node_type: nodeType,
fields,
secrets,
blobs,
...this._identityPayload(identity)
};
if (
this._workerStatus?.protocol_version != null &&
this._workerStatus.protocol_version >= 5
) {
executeData["blob_transfer"] = "chunked-v1";
}
const executePromise = new Promise<ExecuteResult>((resolve, reject) => {
this._pending.set(requestId, { resolve, reject, onProgress });
try {
this._send({
type: "execute",
request_id: requestId,
data: executeData
});
} catch (err) {
this._pending.delete(requestId);
reject(err instanceof Error ? err : new Error(String(err)));
}
});
if (timeoutMs <= 0) {
return executePromise;
}
let timer: NodeJS.Timeout | undefined;
const timeoutPromise = new Promise<ExecuteResult>((_, reject) => {
timer = setTimeout(() => {
if (!this._pending.has(requestId)) {
return;
}
this._pending.delete(requestId);
try {
this.cancel(requestId);
} catch {
// Worker may already be gone; cancel is best-effort.
}
const stderrHint = this.getRecentStderrSummary(4);
reject(
new Error(
`Python node "${nodeType}" timed out after ${timeoutMs}ms waiting for the worker.` +
(stderrHint ? ` Recent stderr: ${stderrHint}` : "")
)
);
}, timeoutMs);
});
try {
return await Promise.race([executePromise, timeoutPromise]);
} finally {
if (timer) {
clearTimeout(timer);
}
}
}
async *executeStream(
nodeType: string,
fields: Record<string, unknown>,
secrets: Record<string, string>,
blobs: ExecuteInputBlobs,
onProgress?: (event: ProgressEvent) => void,
identity?: ExecuteIdentity
): AsyncGenerator<ExecuteResult> {
const requestId = randomUUID();
const chunks: ExecuteResult[] = [];
let done = false;
let error: Error | null = null;
let finalResult: ExecuteResult | null = null;
let emittedCount = 0;
let resolveWait: (() => void) | null = null;
if (onProgress) {
this._pending.set(requestId, {
resolve: () => undefined,
reject: () => undefined,
onProgress
});
}
const onChunk = (chunk: Record<string, unknown>) => {
chunks.push({
outputs: (chunk.outputs as Record<string, unknown>) ?? {},
blobs: (chunk.blobs as Record<string, Uint8Array>) ?? {}
});
if (resolveWait) {
resolveWait();
resolveWait = null;
}
};
const streamPromise = new Promise<Record<string, unknown>>(
(resolve, reject) => {
this._pendingStream.set(requestId, { resolve, reject, onChunk });
}
);
streamPromise
.then((result) => {
finalResult = {
outputs: (result.outputs as Record<string, unknown>) ?? {},
blobs: (result.blobs as Record<string, Uint8Array>) ?? {}
};
done = true;
this._pending.delete(requestId);
if (resolveWait) {
resolveWait();
resolveWait = null;
}
})
.catch((err) => {
error = err;
done = true;
this._pending.delete(requestId);
if (resolveWait) {
resolveWait();
resolveWait = null;
}
});
try {
this._send({
type: "execute.stream",
request_id: requestId,
data: {
node_type: nodeType,
fields,
secrets,
blobs,
...this._identityPayload(identity)
}
});
while (true) {
while (chunks.length > 0) {
emittedCount += 1;
yield chunks.shift()!;
}
if (done) break;
if (error) throw error;
await new Promise<void>((resolve) => {
resolveWait = resolve;
});
}
if (error) throw error;
if (emittedCount === 0 && finalResult) {
yield finalResult;
}
} finally {
// If the stream never reached its terminal frame (consumer abandoned the
// generator via break/return, or the initial _send threw), the worker is
// still producing output nobody reads. Cancel it and release pending
// state so chunks[] stops growing and the entries don't leak.
if (!done) {
this._pending.delete(requestId);
this._pendingStream.delete(requestId);
try {
this.cancel(requestId);
} catch {
// Worker may already be gone; cancel is best-effort.
}
}
}
}
cancel(requestId: string): void {
this._send({ type: "cancel", request_id: requestId, data: {} });
}
getNodeMetadata(): PythonNodeMetadata[] {
return this._nodeMetadata;
}
getLoadErrors() {
return this._loadErrors;
}
async getWorkerStatus() {
const requestId = randomUUID();
const result = await new Promise<Record<string, unknown>>(
(resolve, reject) => {
this._pendingStream.set(requestId, {
resolve,
reject,
onChunk: () => {}
});
try {
this._send({
type: "worker.status",
request_id: requestId,
data: {}
});
} catch (err) {
this._pendingStream.delete(requestId);
reject(err instanceof Error ? err : new Error(String(err)));
}
}
);
this._workerStatus = workerStatusSchema.parse(result);
// A status reply that carries no `load_errors` leaves the ones `discover`
// reported in place; only a reply that names the field replaces them.
this._loadErrors =
result["load_errors"] == null
? this._loadErrors
: this._workerStatus.load_errors;
return this._workerStatus;
}
/**
* getWorkerStatus() guarded by a timeout so a silent worker cannot hang
* connect() forever. On timeout we reject this single call and clean up its
* pending entry + timer; connect()'s catch then logs and proceeds.
*
* Protected so transports that override connect() (e.g. the WebSocket
* bridge, which wraps the whole RPC phase in its own timeout) can still
* honor statusTimeoutMs for the status sub-call.
*/
protected async _getWorkerStatusWithTimeout(): Promise<PythonWorkerStatus> {
const timeoutMs =
this._options.statusTimeoutMs ?? DEFAULT_STATUS_TIMEOUT_MS;
if (timeoutMs <= 0) {
return this.getWorkerStatus();
}
const requestId = randomUUID();
let timer: NodeJS.Timeout | undefined;
const statusPromise = new Promise<Record<string, unknown>>(
(resolve, reject) => {
this._pendingStream.set(requestId, {
resolve,
reject,
onChunk: () => {}
});
try {
this._send({
type: "worker.status",
request_id: requestId,
data: {}
});
} catch (err) {
this._pendingStream.delete(requestId);
reject(err instanceof Error ? err : new Error(String(err)));
}
}
);
const timeoutPromise = new Promise<Record<string, unknown>>((_, reject) => {
timer = setTimeout(() => {
// Reject only this single call and drop its pending entry so a late
// response is ignored rather than resolving a dead promise.
this._pendingStream.delete(requestId);
reject(
new Error(`Python worker status timed out after ${timeoutMs}ms.`)
);
}, timeoutMs);
});
try {
const result = await Promise.race([statusPromise, timeoutPromise]);
this._workerStatus = workerStatusSchema.parse(result);
// See getWorkerStatus: absence keeps the discover-reported errors.
this._loadErrors =
result["load_errors"] == null
? this._loadErrors
: this._workerStatus.load_errors;
return this._workerStatus;
} finally {
if (timer) {
clearTimeout(timer);
}
}
}
hasNodeType(nodeType: string): boolean {
return this._nodeMetadata.some((n) => n.node_type === nodeType);
}
get isConnected(): boolean {
return this._connected;
}
/**
* Whether this bridge has a worker it can attempt to connect to. Gates
* boot-time auto-connect — the server only eagerly calls ensureConnected()
* when this returns true. The base default is true (a WebSocket bridge always
* has a configured URL); the stdio subclass overrides it to report whether a
* local Python interpreter was found.
*/
isAvailable(): boolean {
return true;
}
// ── Provider bridge methods ────────────────────────────────────────
async listProviders(): Promise<PythonProviderInfo[]> {
const result = await this._providerCall("provider.list", {});
return (result as { providers: PythonProviderInfo[] }).providers;
}
async getProviderModels(
providerId: string,
modelType: string,
secrets?: Record<string, string>
): Promise<Record<string, unknown>[]> {
const result = await this._providerCall("provider.models", {
provider: providerId,
model_type: modelType,
secrets: secrets ?? {}
});
return (result as { models: Record<string, unknown>[] }).models;
}
async providerGenerate(
providerId: string,
messages: Record<string, unknown>[],
model: string,
options?: Record<string, unknown>
): Promise<Record<string, unknown>> {
const result = await this._providerCall("provider.generate", {
provider: providerId,
messages,
model,
...options
});
return (result as { message: Record<string, unknown> }).message;
}
async *providerStream(
providerId: string,
messages: Record<string, unknown>[],
model: string,
options?: Record<string, unknown>
): AsyncGenerator<Record<string, unknown>> {
const requestId = randomUUID();
const chunks: Record<string, unknown>[] = [];
let done = false;
let error: Error | null = null;
let resolveWait: (() => void) | null = null;
const onChunk = (chunk: Record<string, unknown>) => {
chunks.push(chunk);
if (resolveWait) {
resolveWait();
resolveWait = null;
}
};
const streamPromise = new Promise<Record<string, unknown>>(
(resolve, reject) => {
this._pendingStream.set(requestId, { resolve, reject, onChunk });
}
);