@flaxia/node 0.5.1 → 0.6.1

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.
package/dist/worker.js CHANGED
@@ -1,4 +1,4 @@
1
- import { M as e, N as t, O as n, a as r, c as i, f as a, h as o, j as s, k as c, l, m as u, o as d, r as f, t as p, u as m, v as h, x as g, y as _ } from "./assets/webgpuProbe.js";
1
+ import { F as e, O as t, P as n, _ as r, a as i, b as a, d as o, h as s, k as c, l, m as u, o as d, p as f, r as p, s as m, t as h, x as g, y as _ } from "./assets/webgpuProbe.js";
2
2
  //#region src/executor/throttle.ts
3
3
  function v(e) {
4
4
  return new Promise((t) => setTimeout(t, e));
@@ -7,7 +7,7 @@ var y = 3e4, ee = 500, b = class extends Error {
7
7
  constructor(e, t, n) {
8
8
  super(`device is over its CPU budget (load ${e.toFixed(2)} > max ${t.toFixed(2)}) after waiting ${Math.round(n)}ms; task not started`), this.load = e, this.maxLoad = t, this.waitedMs = n, this.retryable = !0, this.name = "ThrottleBusyError";
9
9
  }
10
- }, te = class {
10
+ }, x = class {
11
11
  constructor(e = .15) {
12
12
  this.windowStart = performance.now(), this.windowBusyMs = 0, this.lastLoad = 0, this.dutyStartedAt = null, this.maxLoad = Math.max(.05, Math.min(.3, e));
13
13
  }
@@ -57,13 +57,13 @@ var y = 3e4, ee = 500, b = class extends Error {
57
57
  get maxLoadValue() {
58
58
  return this.maxLoad;
59
59
  }
60
- }, x = 4096;
61
- function ne(e) {
60
+ }, S = 4096;
61
+ function te(e) {
62
62
  let t = e.maxSeq;
63
- return typeof t == "number" && Number.isInteger(t) && t > 0 ? t : x;
63
+ return typeof t == "number" && Number.isInteger(t) && t > 0 ? t : S;
64
64
  }
65
- function S(e, t, n) {
66
- let { pos: r, tokens: i } = e.header, a = ne(t);
65
+ function C(e, t, n) {
66
+ let { pos: r, tokens: i } = e.header, a = te(t);
67
67
  if (!Number.isInteger(i) || i < 1) return {
68
68
  kind: "corrupt",
69
69
  reason: `carried ${i} token columns`
@@ -95,78 +95,78 @@ function S(e, t, n) {
95
95
  hidden: o
96
96
  };
97
97
  }
98
- function re(e, t, n, r) {
98
+ function ne(e, t, n, r) {
99
99
  let i = _(e);
100
- return i ? i.header.pos !== t || i.header.requestId !== t ? { kind: "stale" } : S(i, n, r) : {
100
+ return i ? i.header.pos !== t || i.header.requestId !== t ? { kind: "stale" } : C(i, n, r) : {
101
101
  kind: "corrupt",
102
102
  reason: "malformed frame header"
103
103
  };
104
104
  }
105
- async function ie(n) {
106
- let { engine: r, link: i, semantics: a, promptTokens: o, chainLength: s, maxNewTokens: c } = n;
107
- if (o.length === 0) throw Error("swarm host requires at least one prompt token");
108
- r.reset();
109
- let l = null;
110
- i.onFrame((e) => {
111
- if (t(e)) return;
112
- let n = l;
105
+ async function re(t) {
106
+ let { engine: i, link: a, semantics: o, promptTokens: s, chainLength: c, maxNewTokens: l } = t;
107
+ if (s.length === 0) throw Error("swarm host requires at least one prompt token");
108
+ i.reset();
109
+ let u = null;
110
+ a.onFrame((t) => {
111
+ if (e(t)) return;
112
+ let n = u;
113
113
  if (!n) return;
114
- let i = re(e, n.pos, r, a);
115
- if (i.kind !== "stale") {
116
- if (l = null, i.kind === "corrupt") {
117
- n.reject(/* @__PURE__ */ Error(`swarm hop failed: ${i.reason}`));
114
+ let r = ne(t, n.pos, i, o);
115
+ if (r.kind !== "stale") {
116
+ if (u = null, r.kind === "corrupt") {
117
+ n.reject(/* @__PURE__ */ Error(`swarm hop failed: ${r.reason}`));
118
118
  return;
119
119
  }
120
- n.resolve(i.hidden);
120
+ n.resolve(r.hidden);
121
121
  }
122
122
  });
123
- let u = (e, t) => s <= 1 ? Promise.resolve(e) : new Promise((n, r) => {
124
- l = {
123
+ let d = (e, t) => c <= 1 ? Promise.resolve(e) : new Promise((n, i) => {
124
+ u = {
125
125
  pos: t,
126
126
  resolve: n,
127
- reject: r
128
- }, i.send(h({
127
+ reject: i
128
+ }, a.send(r({
129
129
  requestId: t,
130
130
  pos: t,
131
131
  tokens: 1
132
- }, a.packHidden(e)));
133
- }), d = async (e, t) => u(await r.embedRun(e, t), t), f = null;
134
- for (let e = 0; e < o.length; e++) {
135
- let t = await d(o[e], e);
136
- e === o.length - 1 && (f = await r.headFromHidden(t));
137
- }
138
- if (!f) throw Error("swarm host produced no logits for the prompt");
139
- let p = [], m = o.length, g = a.argmax(f);
140
- for (; p.length < c && !(n.eosIds?.has(g) || (p.push(g), await n.onToken?.(g), p.length >= c));) {
141
- let e = await d(g, m++);
142
- f = await r.headFromHidden(e), g = a.argmax(f);
143
- }
144
- return s > 1 && i.send(e()), { tokens: p };
145
- }
146
- function ae(e) {
147
- let { engine: n, link: r, semantics: i } = e;
148
- return n.reset(), new Promise((e, a) => {
149
- let o = Promise.resolve(), s = !1;
150
- r.onFrame((c) => {
151
- if (!s) {
152
- if (t(c)) {
153
- s = !0, r.send(c), o = o.then(() => e());
132
+ }, o.packHidden(e)));
133
+ }), f = async (e, t) => d(await i.embedRun(e, t), t), p = null;
134
+ for (let e = 0; e < s.length; e++) {
135
+ let t = await f(s[e], e);
136
+ e === s.length - 1 && (p = await i.headFromHidden(t));
137
+ }
138
+ if (!p) throw Error("swarm host produced no logits for the prompt");
139
+ let m = [], h = s.length, g = o.argmax(p);
140
+ for (; m.length < l && !(t.eosIds?.has(g) || (m.push(g), await t.onToken?.(g), m.length >= l));) {
141
+ let e = await f(g, h++);
142
+ p = await i.headFromHidden(e), g = o.argmax(p);
143
+ }
144
+ return c > 1 && a.send(n()), { tokens: m };
145
+ }
146
+ function ie(t) {
147
+ let { engine: n, link: i, semantics: a } = t;
148
+ return n.reset(), new Promise((t, o) => {
149
+ let s = Promise.resolve(), c = !1;
150
+ i.onFrame((l) => {
151
+ if (!c) {
152
+ if (e(l)) {
153
+ c = !0, i.send(l), s = s.then(() => t());
154
154
  return;
155
155
  }
156
- o = o.then(async () => {
157
- if (s) return;
158
- let e = _(c);
156
+ s = s.then(async () => {
157
+ if (c) return;
158
+ let e = _(l);
159
159
  if (!e) throw Error("swarm frame has a malformed frame header");
160
- let t = S(e, n, i);
160
+ let t = C(e, n, a);
161
161
  if (t.kind === "corrupt") throw Error(`swarm frame is unusable: ${t.reason}`);
162
- let a = await n.runHidden(t.hidden, e.header.pos);
163
- r.send(h({
162
+ let o = await n.runHidden(t.hidden, e.header.pos);
163
+ i.send(r({
164
164
  requestId: e.header.requestId,
165
165
  pos: e.header.pos,
166
166
  tokens: e.header.tokens
167
- }, i.packHidden(a)));
167
+ }, a.packHidden(o)));
168
168
  }).catch((e) => {
169
- s = !0, a(e instanceof Error ? e : Error(String(e)));
169
+ c = !0, o(e instanceof Error ? e : Error(String(e)));
170
170
  });
171
171
  }
172
172
  });
@@ -174,7 +174,7 @@ function ae(e) {
174
174
  }
175
175
  //#endregion
176
176
  //#region src/swarm/controller.ts
177
- var oe = class {
177
+ var ae = class {
178
178
  constructor(e) {
179
179
  this.options = e, this.frameHandler = null, this.engine = null, this.semantics = null, this.sessionId = "", this.model = "", this.chainLength = 1, this.chain = [], this.slice = null, this.hostWarm = void 0, this.prompt = "", this.maxNewTokens = 128, this.sliceLoaded = !1, this.generationStarted = !1, this.settled = !1, this.flowPaused = !1, this.flowWaiters = /* @__PURE__ */ new Set();
180
180
  }
@@ -238,11 +238,11 @@ var oe = class {
238
238
  this.engine = t, this.semantics = n, this.hostWarm = r, this.sliceLoaded = !0, this.options.sendControl({
239
239
  type: "swarm-ready",
240
240
  sessionId: e.sessionId
241
- }), e.role === "worker" && (this.generationStarted = !0, ae({
241
+ }), e.role === "worker" && (this.generationStarted = !0, ie({
242
242
  engine: t,
243
243
  link: this.link(),
244
244
  semantics: n
245
- }).then(() => this.finish(se())).catch((e) => this.fail(e)));
245
+ }).then(() => this.finish(oe())).catch((e) => this.fail(e)));
246
246
  }
247
247
  async startHost() {
248
248
  if (this.generationStarted) return;
@@ -254,7 +254,7 @@ var oe = class {
254
254
  let r = t.encodePrompt(this.prompt), i = e.maxSeq ?? 4096;
255
255
  if (r.length + n > i) throw Error(`swarm request needs ${r.length + n} tokens but the model context holds ${i}`);
256
256
  this.generationStarted = !0;
257
- let a = performance.now(), { tokens: o } = await ie({
257
+ let a = performance.now(), { tokens: o } = await re({
258
258
  chainLength: this.chainLength,
259
259
  promptTokens: r,
260
260
  maxNewTokens: n,
@@ -310,7 +310,7 @@ var oe = class {
310
310
  this.flowWaiters.clear();
311
311
  }
312
312
  };
313
- function se() {
313
+ function oe() {
314
314
  return {
315
315
  output: "",
316
316
  tokens: [],
@@ -320,13 +320,13 @@ function se() {
320
320
  }
321
321
  //#endregion
322
322
  //#region src/swarm/adapter.ts
323
- var C = class extends Error {
323
+ var w = class extends Error {
324
324
  constructor(e) {
325
325
  super(e), this.name = "SwarmEngineUnavailableError";
326
326
  }
327
327
  };
328
- async function w(e, t) {
329
- if (!(await p()).webgpu) throw new C("WebGPU is not available in this context");
328
+ async function se(e, t) {
329
+ if (!(await h()).webgpu) throw new w("WebGPU is not available in this context");
330
330
  let n = t ?? ((e) => import(
331
331
  /* @vite-ignore */
332
332
  e
@@ -334,13 +334,13 @@ async function w(e, t) {
334
334
  try {
335
335
  r = await n(e);
336
336
  } catch (e) {
337
- throw new C(`failed to load swarm engine module: ${e instanceof Error ? e.message : String(e)}`);
337
+ throw new w(`failed to load swarm engine module: ${e instanceof Error ? e.message : String(e)}`);
338
338
  }
339
339
  let i = r?.Qwen35Engine;
340
- if (!i || typeof i.create != "function") throw new C(`module at ${e} does not export Qwen35Engine.create`);
340
+ if (!i || typeof i.create != "function") throw new w(`module at ${e} does not export Qwen35Engine.create`);
341
341
  return r;
342
342
  }
343
- function ce(e, t, n, r) {
343
+ function T(e, t, n, r) {
344
344
  let i = !1, a = async (e) => {
345
345
  r?.();
346
346
  let t = await e();
@@ -383,19 +383,19 @@ function ce(e, t, n, r) {
383
383
  }
384
384
  //#endregion
385
385
  //#region src/swarm/runtime.ts
386
- var T = {
386
+ var E = {
387
387
  "qwen3.5-2b": "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/Qwen3.5-2B-Q4_0.gguf",
388
388
  "qwen3.8-27b": "https://huggingface.co/unsloth/Qwen3.8-27B-GGUF/resolve/main/Qwen3.8-27B-Q4_0.gguf",
389
389
  "qwen3.6-35b-moe": "https://huggingface.co/bartowski/Qwen_Qwen3.6-35B-A3B-GGUF/resolve/main/Qwen_Qwen3.6-35B-A3B-Q4_0.gguf"
390
- }, le = "flaxia-swarm-weights-v1", ue = 12 * 1024 * 1024, E = 256 * 1024 * 1024, D = /* @__PURE__ */ new Map();
391
- function O(e, t) {
392
- D.set(e, {
390
+ }, ce = "flaxia-swarm-weights-v1", le = 12 * 1024 * 1024, D = 256 * 1024 * 1024, O = /* @__PURE__ */ new Map();
391
+ function k(e, t) {
392
+ O.set(e, {
393
393
  status: t,
394
394
  failedExpiresAt: t.state === "failed" ? Date.now() + 3e4 : void 0
395
395
  });
396
396
  }
397
- function k(e, t, n, r) {
398
- let i = j(e);
397
+ function A(e, t, n, r) {
398
+ let i = M(e);
399
399
  return {
400
400
  modelId: e,
401
401
  revision: /\/resolve\/([^/]+)\//.exec(new URL(i).pathname)?.[1] ?? "unknown",
@@ -406,11 +406,11 @@ function k(e, t, n, r) {
406
406
  referenceCount: r
407
407
  };
408
408
  }
409
- function A(e = Date.now()) {
409
+ function j(e = Date.now()) {
410
410
  let t = [];
411
- for (let [n, r] of D) {
411
+ for (let [n, r] of O) {
412
412
  if (r.failedExpiresAt !== void 0 && r.failedExpiresAt <= e) {
413
- D.delete(n);
413
+ O.delete(n);
414
414
  continue;
415
415
  }
416
416
  t.push(r.status);
@@ -418,40 +418,40 @@ function A(e = Date.now()) {
418
418
  return {
419
419
  version: 1,
420
420
  sampledAt: e,
421
- expiresAt: e + s,
421
+ expiresAt: e + g,
422
422
  entries: t.slice(0, 8)
423
423
  };
424
424
  }
425
- function j(e) {
426
- let t = Object.prototype.hasOwnProperty.call(T, e) ? T[e] : void 0;
425
+ function M(e) {
426
+ let t = Object.prototype.hasOwnProperty.call(E, e) ? E[e] : void 0;
427
427
  if (t) return t;
428
- throw new C(`unknown swarm model: ${e}`);
428
+ throw new w(`unknown swarm model: ${e}`);
429
429
  }
430
- var M = null, N = 0, P = 0;
431
- async function de() {
432
- if (M !== null) return M;
430
+ var N = null, P = 0, F = 0;
431
+ async function ue() {
432
+ if (N !== null) return N;
433
433
  try {
434
- M = typeof caches < "u" ? await caches.open(le) : !1;
434
+ N = typeof caches < "u" ? await caches.open(ce) : !1;
435
435
  } catch {
436
- M = !1;
436
+ N = !1;
437
437
  }
438
- return M;
438
+ return N;
439
439
  }
440
- function fe(e, t, n) {
440
+ function de(e, t, n) {
441
441
  return `https://flaxia-weights.local/${encodeURIComponent(e)}/${t}-${n}`;
442
442
  }
443
- async function F(e, t, n) {
444
- let r = await I(e, t, n), i = new Uint8Array(await r.arrayBuffer()), a = n - t + 1;
443
+ async function I(e, t, n) {
444
+ let r = await L(e, t, n), i = new Uint8Array(await r.arrayBuffer()), a = n - t + 1;
445
445
  if (i.byteLength !== a) throw Error(`short range ${i.byteLength}/${a}`);
446
446
  return i;
447
447
  }
448
- async function I(e, t, n) {
449
- let r = n - t + 1, i = await de(), a = fe(e, t, n);
448
+ async function L(e, t, n) {
449
+ let r = n - t + 1, i = await ue(), a = de(e, t, n);
450
450
  if (i) try {
451
451
  let e = await i.match(a);
452
452
  if (e) {
453
453
  let t = new Uint8Array(await e.arrayBuffer());
454
- if (t.byteLength === r) return N++, new Response(t, { status: 200 });
454
+ if (t.byteLength === r) return P++, new Response(t, { status: 200 });
455
455
  await i.delete(a).catch(() => {});
456
456
  }
457
457
  } catch {}
@@ -460,7 +460,7 @@ async function I(e, t, n) {
460
460
  try {
461
461
  let s = await fetch(e, { headers: { Range: `bytes=${t}-${n}` } });
462
462
  if (s.status !== 206) o = /* @__PURE__ */ Error(`model host refused range requests (${s.status})`);
463
- else return P++, i && s.clone().arrayBuffer().then((e) => {
463
+ else return F++, i && s.clone().arrayBuffer().then((e) => {
464
464
  if (e.byteLength === r) return i.put(a, new Response(e, {
465
465
  status: 200,
466
466
  headers: { "content-type": "application/octet-stream" }
@@ -473,29 +473,29 @@ async function I(e, t, n) {
473
473
  }
474
474
  throw Error(`range fetch ${t}-${n} failed: ${o instanceof Error ? o.message : String(o)}`);
475
475
  }
476
- async function pe(e, t) {
477
- let n = ue;
476
+ async function fe(e, t) {
477
+ let n = le;
478
478
  for (;;) {
479
- let r = await F(t, 0, n - 1), i = r.buffer.slice(r.byteOffset, r.byteOffset + r.byteLength);
479
+ let r = await I(t, 0, n - 1), i = r.buffer.slice(r.byteOffset, r.byteOffset + r.byteLength);
480
480
  try {
481
481
  return e.parseGGUFHeader(i);
482
482
  } catch (e) {
483
- if (n >= E) throw e;
484
- n = Math.min(n * 2, E);
483
+ if (n >= D) throw e;
484
+ n = Math.min(n * 2, D);
485
485
  }
486
486
  }
487
487
  }
488
- async function me() {
488
+ async function pe() {
489
489
  let e = navigator.gpu;
490
- if (!e) throw new C("WebGPU is not available in this context");
490
+ if (!e) throw new w("WebGPU is not available in this context");
491
491
  let t = await e.requestAdapter({ powerPreference: "high-performance" });
492
- if (!t) throw new C("no WebGPU adapter");
492
+ if (!t) throw new w("no WebGPU adapter");
493
493
  return t.requestDevice({ requiredLimits: {
494
494
  maxBufferSize: t.limits.maxBufferSize,
495
495
  maxStorageBufferBindingSize: t.limits.maxStorageBufferBindingSize
496
496
  } });
497
497
  }
498
- function he(e, t) {
498
+ function me(e, t) {
499
499
  let n = t.vocab, r = n["<|im_start|>"], i = n["<|im_end|>"], a = n["<think>"], o = n["</think>"], s = (e) => [
500
500
  r,
501
501
  ...t.encode("user\n" + e),
@@ -525,21 +525,21 @@ function he(e, t) {
525
525
  eosIds: new Set(c)
526
526
  };
527
527
  }
528
- function L(e) {
528
+ function R(e) {
529
529
  let t = null, n = null, r = () => {
530
530
  if (!t) {
531
531
  let n = new URL("./swarm-engine.js", "" + import.meta.url).href;
532
- t = e ? e() : w(n).then((e) => e);
532
+ t = e ? e() : se(n).then((e) => e);
533
533
  }
534
534
  return t;
535
535
  }, i = async (e) => {
536
- let t = await r(), i = j(e);
536
+ let t = await r(), i = M(e);
537
537
  (!n || n.url !== i) && (n = {
538
538
  url: i,
539
- gguf: await pe(t, i)
539
+ gguf: await fe(t, i)
540
540
  });
541
541
  let a = Number(n.gguf.meta["qwen35.block_count"]) - Number(n.gguf.meta["qwen35.nextn_predict_layers"] || 0);
542
- if (!Number.isInteger(a) || a < 1) throw new C(`model ${e} has no qwen35 trunk layers`);
542
+ if (!Number.isInteger(a) || a < 1) throw new w(`model ${e} has no qwen35 trunk layers`);
543
543
  return {
544
544
  mod: t,
545
545
  url: i,
@@ -550,7 +550,7 @@ function L(e) {
550
550
  return {
551
551
  async plan(e, t) {
552
552
  let { layers: n } = await i(t);
553
- return g({
553
+ return a({
554
554
  sessionId: "",
555
555
  taskId: "",
556
556
  model: t,
@@ -562,17 +562,17 @@ function L(e) {
562
562
  }).chain;
563
563
  },
564
564
  async load(e, t) {
565
- N = 0, P = 0;
565
+ P = 0, F = 0;
566
566
  let n = JSON.stringify([
567
567
  t,
568
568
  e.start,
569
569
  e.end
570
570
  ]);
571
- O(n, k(t, e, "loading", 1));
571
+ k(n, A(t, e, "loading", 1));
572
572
  let r, a = !1;
573
573
  try {
574
574
  let { mod: o, url: s, gguf: c } = await i(t);
575
- r = await me();
575
+ r = await pe();
576
576
  let l = null, u = r;
577
577
  u.addEventListener?.("uncapturederror", () => {
578
578
  l = "swarm GPU validation failed";
@@ -580,9 +580,9 @@ function L(e) {
580
580
  l = "swarm GPU device lost";
581
581
  });
582
582
  let d = () => {
583
- if (l) throw new C(l);
584
- }, f = he(o, o.makeTokenizer(o.tokenizerFromGGUF(c.meta))), p = (e) => F(s, e.byteOffset, e.byteOffset + e.byteLength - 1);
585
- c.streamEntry = (e) => o.streamEntryToGPU(r, e, (e) => I(s, e.byteOffset, e.byteOffset + e.byteLength - 1), { staging: 4 * 1024 * 1024 });
583
+ if (l) throw new w(l);
584
+ }, f = me(o, o.makeTokenizer(o.tokenizerFromGGUF(c.meta))), p = (e) => I(s, e.byteOffset, e.byteOffset + e.byteLength - 1);
585
+ c.streamEntry = (e) => o.streamEntryToGPU(r, e, (e) => L(s, e.byteOffset, e.byteOffset + e.byteLength - 1), { staging: 4 * 1024 * 1024 });
586
586
  let m = await o.qwen35Weights(c, p, {
587
587
  lo: e.start,
588
588
  hi: e.end,
@@ -596,21 +596,21 @@ function L(e) {
596
596
  hasEmbed: e.hasEmbed,
597
597
  hasHead: e.hasHead,
598
598
  vocab: h,
599
- maxSeq: Math.min(x, Number(c.meta["qwen35.context_length"]) || 4096),
599
+ maxSeq: Math.min(S, Number(c.meta["qwen35.context_length"]) || 4096),
600
600
  batchCols: 4,
601
601
  weights: m
602
602
  });
603
603
  d();
604
- let _ = ce(g, r, () => {
605
- O(n, k(t, e, "evicting", 0)), queueMicrotask(() => D.delete(n));
604
+ let _ = T(g, r, () => {
605
+ k(n, A(t, e, "evicting", 0)), queueMicrotask(() => O.delete(n));
606
606
  }, d);
607
- return a = !0, O(n, k(t, e, "ready", 1)), {
607
+ return a = !0, k(n, A(t, e, "ready", 1)), {
608
608
  engine: _,
609
609
  semantics: f,
610
- warm: N > 0 && P === 0
610
+ warm: P > 0 && F === 0
611
611
  };
612
612
  } catch (i) {
613
- if (O(n, k(t, e, "failed", 0)), !a) try {
613
+ if (k(n, A(t, e, "failed", 0)), !a) try {
614
614
  r?.destroy?.();
615
615
  } catch {}
616
616
  throw i;
@@ -620,45 +620,45 @@ function L(e) {
620
620
  }
621
621
  //#endregion
622
622
  //#region src/swarm/messages.ts
623
- function ge(e) {
624
- return a(e) || m(e) || o(e) || c(e) || i(e) || n(e);
623
+ function he(e) {
624
+ return o(e) || l(e) || f(e) || c(e) || m(e) || t(e);
625
625
  }
626
- function _e(e) {
626
+ function ge(e) {
627
627
  if (!e || typeof e != "object") return !1;
628
628
  let t = e;
629
- return t.type === "swarm-control" && typeof t.id == "string" && ge(t.message);
629
+ return t.type === "swarm-control" && typeof t.id == "string" && he(t.message);
630
630
  }
631
631
  //#endregion
632
632
  //#region src/worker/main.worker.ts
633
- var R = null, ve = y, ye = 1, z = 15e3, B = /* @__PURE__ */ new Map(), V = /* @__PURE__ */ new Set(), H = /* @__PURE__ */ new Map();
634
- function U(e) {
635
- V.delete(e);
636
- let t = H.get(e);
633
+ var z = null, _e = y, ve = 1, B = 15e3, V = /* @__PURE__ */ new Map(), H = /* @__PURE__ */ new Set(), U = /* @__PURE__ */ new Map();
634
+ function W(e) {
635
+ H.delete(e);
636
+ let t = U.get(e);
637
637
  if (t) {
638
- H.delete(e);
638
+ U.delete(e);
639
639
  for (let e of t) e();
640
640
  }
641
641
  }
642
- function be(e) {
643
- return V.has(e) ? new Promise((t) => {
644
- let n = H.get(e) ?? /* @__PURE__ */ new Set();
645
- n.add(t), H.set(e, n);
642
+ function ye(e) {
643
+ return H.has(e) ? new Promise((t) => {
644
+ let n = U.get(e) ?? /* @__PURE__ */ new Set();
645
+ n.add(t), U.set(e, n);
646
646
  }) : Promise.resolve();
647
647
  }
648
- var W = null, G = null, K = null, xe = 6e4;
649
- async function Se() {
648
+ var G = null, K = null, q = null, be = 6e4;
649
+ async function xe() {
650
650
  for (let e = 0;; e++) try {
651
- await R.waitForSlot(ve);
651
+ await z.waitForSlot(_e);
652
652
  return;
653
653
  } catch (t) {
654
654
  if (!(t instanceof b)) throw t;
655
- if (e >= ye) throw Error(`device CPU busy: ${t.message}; task not started, retry on an idle node (retryable)`);
656
- console.warn(`[flaxia-node:worker] ${t.message}; cooling down ${z}ms before retrying`), await new Promise((e) => setTimeout(e, z));
655
+ if (e >= ve) throw Error(`device CPU busy: ${t.message}; task not started, retry on an idle node (retryable)`);
656
+ console.warn(`[flaxia-node:worker] ${t.message}; cooling down ${B}ms before retrying`), await new Promise((e) => setTimeout(e, B));
657
657
  }
658
658
  }
659
- function Ce(e) {
659
+ function Se(e) {
660
660
  let t = (t) => {
661
- let n = B.get(e);
661
+ let n = V.get(e);
662
662
  if (n !== void 0) throw Error(n);
663
663
  self.postMessage({
664
664
  id: e,
@@ -667,22 +667,22 @@ function Ce(e) {
667
667
  });
668
668
  };
669
669
  return async (n) => {
670
- await be(e), t(n), await R?.yieldIfOverloaded();
670
+ await ye(e), t(n), await z?.yieldIfOverloaded();
671
671
  };
672
672
  }
673
- var q = d(), J = q >= f;
674
- console.log(`[flaxia-node:worker] startup memory probe wasmMemoryBytes=${q} capable=${J}`);
675
- function Y() {
676
- return r();
673
+ var J = d(), Y = J >= p;
674
+ console.log(`[flaxia-node:worker] startup memory probe wasmMemoryBytes=${J} capable=${Y}`);
675
+ function Ce() {
676
+ return i();
677
677
  }
678
678
  var X = /* @__PURE__ */ new Map(), Z = /* @__PURE__ */ new Map();
679
- Z.set("swarm-inference", A);
679
+ Z.set("swarm-inference", j);
680
680
  var Q = null;
681
681
  function we() {
682
682
  for (let e of X.values()) try {
683
683
  e();
684
684
  } catch {}
685
- X.clear(), Z.clear(), Z.set("swarm-inference", A);
685
+ X.clear(), Z.clear(), Z.set("swarm-inference", j);
686
686
  }
687
687
  function $() {
688
688
  let e = Date.now(), t = [...Z.values()].flatMap((e) => {
@@ -702,13 +702,19 @@ function $() {
702
702
  function Te() {
703
703
  Q && clearTimeout(Q), Q = setTimeout(() => {
704
704
  Q = null, we();
705
- }, xe);
705
+ }, be);
706
706
  }
707
707
  async function Ee(e, t, n, r) {
708
708
  switch (e) {
709
709
  case "ai-inference":
710
- let i = await import("./assets/ai-inference.js");
710
+ let i = await import("./assets/ai-inference.js").then((e) => e.s);
711
711
  return X.set(e, i.releaseCache), Z.set(e, i.getModelCacheSnapshot), await i.handleAiInference(t, n);
712
+ case "ai-preload": {
713
+ let e = await import("./assets/ai-inference.js").then((e) => e.s);
714
+ X.set("ai-inference", e.releaseCache), Z.set("ai-inference", e.getModelCacheSnapshot);
715
+ let n = t;
716
+ return await e.preloadAiModel(n), { preloaded: !0 };
717
+ }
712
718
  case "image-process": return await (await import("./assets/image-process.js")).handleImageProcess(t);
713
719
  case "container": return await (await import("./assets/container.js")).handleContainer(t, r?.fileSourceOrigins ?? [], r?.containerImageOrigins ?? []);
714
720
  case "vector-embed":
@@ -728,9 +734,9 @@ async function Ee(e, t, n, r) {
728
734
  }
729
735
  function De(e, t, n) {
730
736
  return new Promise((r, i) => {
731
- let a = new oe({
737
+ let a = new ae({
732
738
  initial: t,
733
- runtime: L(),
739
+ runtime: R(),
734
740
  sendControl: (t) => self.postMessage({
735
741
  id: e,
736
742
  type: "swarm-message",
@@ -743,55 +749,55 @@ function De(e, t, n) {
743
749
  }, [t]),
744
750
  emitToken: n,
745
751
  onDone: (e) => {
746
- W === a && (W = null, G = null), r(e);
752
+ G === a && (G = null, K = null), r(e);
747
753
  },
748
754
  onError: (e) => {
749
- W === a && (W = null, G = null), i(Error(e));
755
+ G === a && (G = null, K = null), i(Error(e));
750
756
  }
751
757
  });
752
- W = a, G = e, a.start();
758
+ G = a, K = e, a.start();
753
759
  });
754
760
  }
755
761
  self.onmessage = async (e) => {
756
762
  let t = e.data;
757
763
  if (t?.type === "token-flow") {
758
764
  let e = typeof t.id == "string" ? t.id : "";
759
- e && K === e && typeof t.paused == "boolean" && (t.paused ? V.add(e) : U(e));
765
+ e && q === e && typeof t.paused == "boolean" && (t.paused ? H.add(e) : W(e));
760
766
  return;
761
767
  }
762
768
  if (t?.type === "swarm-control") {
763
- if (!_e(t)) {
769
+ if (!ge(t)) {
764
770
  console.warn("[flaxia-node:worker] dropped malformed swarm-control message");
765
771
  return;
766
772
  }
767
- W && W.handleControl(t.message);
773
+ G && G.handleControl(t.message);
768
774
  return;
769
775
  }
770
776
  if (t?.type === "swarm-frame") {
771
- t.frame instanceof ArrayBuffer ? W?.handleFrame(t.frame) : console.warn("[flaxia-node:worker] dropped malformed swarm-frame message");
777
+ t.frame instanceof ArrayBuffer ? G?.handleFrame(t.frame) : console.warn("[flaxia-node:worker] dropped malformed swarm-frame message");
772
778
  return;
773
779
  }
774
780
  if (t?.type === "abort") {
775
781
  let e = t.id, n = typeof t.reason == "string" && t.reason ? t.reason : "aborted by the coordinator";
776
- U(e), W && G === e ? W.abort(n) : K === e && B.set(e, n);
782
+ W(e), G && K === e ? G.abort(n) : q === e && V.set(e, n);
777
783
  return;
778
784
  }
779
785
  let { id: n, workload: r, payload: i, config: a } = t, o = performance.now();
780
- K = n, U(n);
786
+ q = n, W(n);
781
787
  try {
782
- if (R ||= new te(a?.maxCpuLoad), console.log(`[flaxia-node:worker] task start id=${n} workload=${r}`), !J) throw Error(`node incapable: insufficient WASM memory (${q} bytes < ${f}); rejecting all tasks`);
783
- if (l.has(r) && !Y()) throw Error(`${r}: insufficient WASM memory (${q} bytes < ${f})`);
784
- await Se(), R.beginWork();
788
+ if (z ||= new x(a?.maxCpuLoad), console.log(`[flaxia-node:worker] task start id=${n} workload=${r}`), !Y) throw Error(`node incapable: insufficient WASM memory (${J} bytes < ${p}); rejecting all tasks`);
789
+ if (s.has(r) && !Ce()) throw Error(`${r}: insufficient WASM memory (${J} bytes < ${p})`);
790
+ await xe(), z.beginWork();
785
791
  let e = setInterval(() => {
786
792
  self.postMessage({
787
793
  id: n,
788
794
  type: "heartbeat",
789
- cpuLoad: R?.lastMeasuredLoad ?? 0,
795
+ cpuLoad: z?.lastMeasuredLoad ?? 0,
790
796
  modelCache: $()
791
797
  });
792
798
  }, 1e4), t = performance.now();
793
799
  try {
794
- let e = Ce(n), t = Array.isArray(a?.fileSourceOrigins) ? a.fileSourceOrigins.filter((e) => typeof e == "string") : [], s = Array.isArray(a?.containerImageOrigins) ? a.containerImageOrigins.filter((e) => typeof e == "string") : [], c = r === "swarm-inference" ? await De(n, i, e) : await Ee(r, i, e, {
800
+ let e = Se(n), t = Array.isArray(a?.fileSourceOrigins) ? a.fileSourceOrigins.filter((e) => typeof e == "string") : [], s = Array.isArray(a?.containerImageOrigins) ? a.containerImageOrigins.filter((e) => typeof e == "string") : [], c = r === "swarm-inference" ? await De(n, i, e) : await Ee(r, i, e, {
795
801
  fileSourceOrigins: t,
796
802
  containerImageOrigins: s
797
803
  });
@@ -802,14 +808,17 @@ self.onmessage = async (e) => {
802
808
  modelCache: $()
803
809
  }), console.log(`[flaxia-node:worker] task done id=${n} workload=${r} durationMs=${Math.round(performance.now() - o)}`);
804
810
  } finally {
805
- K = null, B.delete(n), U(n), clearInterval(e), R.markTaskComplete(performance.now() - t), Te();
811
+ q = null, V.delete(n), W(n), clearInterval(e), z.markTaskComplete(performance.now() - t), Te();
806
812
  }
807
813
  } catch (e) {
808
- let t = e instanceof Error ? e.message : String(e);
809
- console.error(`[flaxia-node:worker] task error id=${n} workload=${r} error=${t}`), K === n && (K = null), U(n), self.postMessage({
814
+ let t = e instanceof Error ? e.message : String(e), i = e, a = typeof i?.code == "string" ? i.code : void 0, o = typeof i?.status == "number" ? i.status : void 0, s = typeof i?.detail == "string" ? i.detail : void 0;
815
+ console.error(`[flaxia-node:worker] task error id=${n} workload=${r} error=${t}`), q === n && (q = null), W(n), self.postMessage({
810
816
  id: n,
811
817
  type: "error",
812
818
  error: t,
819
+ errorCode: a,
820
+ errorStatus: o,
821
+ detail: s,
813
822
  modelCache: $()
814
823
  });
815
824
  }