@celljs/ta-local-models 4.42.0 → 4.44.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 (3) hide show
  1. package/host/index.mjs +282 -102
  2. package/package.json +3 -3
  3. package/web/index.js +15 -7
package/host/index.mjs CHANGED
@@ -1,13 +1,10 @@
1
1
  // web-src/host.ts
2
2
  import { totalmem } from "node:os";
3
- import { join as join3 } from "node:path";
3
+ import { join as join4 } from "node:path";
4
4
 
5
5
  // web-src/local-models.ts
6
- import { mkdir as mkdir2, readdir as readdir2, readFile, rm as rm2, writeFile } from "node:fs/promises";
7
- import { dirname as dirname2, join as join2 } from "node:path";
8
-
9
- // ../ta-protocol/esm/common/local-models-protocol.js
10
- var TA_LOCAL_RUNTIMES = ["llama.cpp"];
6
+ import { mkdir as mkdir2, readFile, rm as rm3, writeFile } from "node:fs/promises";
7
+ import { dirname as dirname2, join as join3 } from "node:path";
11
8
 
12
9
  // web-src/file-fetch.ts
13
10
  import { createHash } from "node:crypto";
@@ -86,6 +83,9 @@ class FileFetch {
86
83
  }
87
84
  }
88
85
 
86
+ // ../ta-protocol/esm/common/local-models-protocol.js
87
+ var TA_LOCAL_RUNTIMES = ["llama.cpp", "sherpa-onnx"];
88
+
89
89
  // web-src/local-checks.ts
90
90
  var SHA256 = /^[0-9a-f]{64}$/;
91
91
  var LocalChecks;
@@ -99,11 +99,16 @@ var LocalChecks;
99
99
  if (!TA_LOCAL_RUNTIMES.includes(runtime)) {
100
100
  throw new Error(`The runtimes are ${TA_LOCAL_RUNTIMES.join(", ")}, not ${runtime}.`);
101
101
  }
102
- if (!SHA256.test(model.sha256) || !/^[\w.-]+$/.test(model.file) || /^\.+$/.test(model.file) || !(model.bytes > 0)) {
103
- throw new Error(`${model.id} needs its file's name, size and SHA-256 (64 hex digits).`);
102
+ for (const file of [model, ...Object.values(model.files ?? {})]) {
103
+ if (!SHA256.test(file.sha256) || !/^[\w.-]+$/.test(file.file) || /^\.+$/.test(file.file) || !(file.bytes > 0)) {
104
+ throw new Error(`${model.id} needs the name, size and SHA-256 (64 hex digits) of each of its files.`);
105
+ }
106
+ if (!file.urls?.length || file.urls.some((url) => !url.startsWith("https://"))) {
107
+ throw new Error(`${model.id} is downloaded over HTTPS alone.`);
108
+ }
104
109
  }
105
- if (!model.urls.length || model.urls.some((url) => !url.startsWith("https://"))) {
106
- throw new Error(`${model.id} is downloaded over HTTPS alone.`);
110
+ if (model.files && Object.keys(model.files).some((name) => !/^[a-z][\w-]*$/.test(name))) {
111
+ throw new Error(`${model.id} names the files beside it in lowercase words (tokens).`);
107
112
  }
108
113
  if (model.args?.some((arg) => ["--host", "--port", "-m", "--model"].includes(arg))) {
109
114
  throw new Error(`${model.id} cannot set where its server listens nor which file it serves.`);
@@ -129,8 +134,117 @@ var LocalChecks;
129
134
  LocalChecks.errorOf = errorOf;
130
135
  })(LocalChecks ||= {});
131
136
 
137
+ // web-src/local-progress.ts
138
+ var PROGRESS_MS = 1000;
139
+
140
+ class LocalProgress {
141
+ tell;
142
+ now;
143
+ got = new Map;
144
+ toldAt = Number.NEGATIVE_INFINITY;
145
+ constructor(tell, now) {
146
+ this.tell = tell;
147
+ this.now = now;
148
+ }
149
+ of(file, bytes) {
150
+ return (done, total) => {
151
+ this.got.set(file, { done, total: total || bytes });
152
+ if (this.now() - this.toldAt >= PROGRESS_MS) {
153
+ this.toldAt = this.now();
154
+ this.tell();
155
+ }
156
+ };
157
+ }
158
+ done(file) {
159
+ this.got.delete(file);
160
+ }
161
+ sum(model, runtime) {
162
+ const parts = [
163
+ runtime === undefined ? undefined : this.got.get(runtime) ?? { done: 0, total: 0 },
164
+ this.got.get(model.file) ?? { done: 0, total: model.bytes }
165
+ ];
166
+ let done = 0;
167
+ let total = 0;
168
+ for (const part of parts) {
169
+ done += part?.done ?? 0;
170
+ total += part?.total ?? 0;
171
+ }
172
+ return { done, total: Math.max(total, model.bytes) };
173
+ }
174
+ }
175
+
176
+ // web-src/sherpa-server.ts
177
+ var SHERPA_SERVER = String.raw`
178
+ const http = require('node:http');
179
+ const options = {};
180
+ for (const arg of process.argv.slice(1)) {
181
+ const at = arg.indexOf('=');
182
+ if (arg.startsWith('--') && at > 2) options[arg.slice(2, at)] = arg.slice(at + 1);
183
+ }
184
+ const MAX_BYTES = Number(options['max-bytes'] || 10 * 1024 * 1024);
185
+ const addon = require(options.addon);
186
+ const recognizer = addon.createOfflineRecognizer({
187
+ featConfig: { sampleRate: 16000, featureDim: 80 },
188
+ modelConfig: {
189
+ senseVoice: { model: options.model, language: '', useInverseTextNormalization: 1 },
190
+ tokens: options.tokens,
191
+ numThreads: Number(options.threads || 2),
192
+ provider: 'cpu',
193
+ debug: 0,
194
+ },
195
+ });
196
+ let queue = Promise.resolve();
197
+ // Ta stops it once idle; left behind (Ta ended without stopping it, and did not come back), it ends by itself.
198
+ const IDLE_EXIT_MS = Number(options['idle-exit-ms'] || 45 * 60 * 1000);
199
+ let idle;
200
+ const awake = () => {
201
+ clearTimeout(idle);
202
+ idle = setTimeout(() => process.exit(0), IDLE_EXIT_MS);
203
+ };
204
+ awake();
205
+ async function transcribe(pcm) {
206
+ const samples = new Float32Array(pcm.length >> 1);
207
+ for (let i = 0; i < samples.length; i++) samples[i] = pcm.readInt16LE(i * 2) / 32768;
208
+ const stream = addon.createOfflineStream(recognizer);
209
+ addon.acceptWaveformOffline(stream, { samples, sampleRate: 16000 });
210
+ if (addon.decodeOfflineStreamAsync) await addon.decodeOfflineStreamAsync(recognizer, stream);
211
+ else addon.decodeOfflineStream(recognizer, stream);
212
+ return String(JSON.parse(addon.getOfflineStreamResultAsJson(stream)).text || '').trim();
213
+ }
214
+ function answer(response, status, body) {
215
+ response.writeHead(status, { 'content-type': 'application/json' });
216
+ response.end(JSON.stringify(body));
217
+ }
218
+ const server = http.createServer((request, response) => {
219
+ awake();
220
+ if (request.method === 'GET' && request.url === '/health') return answer(response, 200, { status: 'ok' });
221
+ if (request.method === 'GET' && request.url === '/props') return answer(response, 200, { model_path: options.model });
222
+ if (request.method !== 'POST' || request.url !== '/v1/transcribe') return answer(response, 404, { error: 'not found' });
223
+ const parts = [];
224
+ let bytes = 0;
225
+ request.on('data', part => {
226
+ bytes += part.length;
227
+ if (bytes > MAX_BYTES) {
228
+ answer(response, 413, { error: 'too long' });
229
+ request.destroy();
230
+ } else parts.push(part);
231
+ });
232
+ request.on('end', () => {
233
+ if (bytes > MAX_BYTES) return;
234
+ const pcm = Buffer.concat(parts);
235
+ // One at a time: the recognizer is one, and a second at once would only wait for the first.
236
+ queue = queue.then(() => transcribe(pcm)).then(
237
+ text => answer(response, 200, { text }),
238
+ error => answer(response, 500, { error: String(error && error.message || error) }),
239
+ );
240
+ });
241
+ });
242
+ server.listen(Number(options.port), '127.0.0.1');
243
+ `;
244
+
132
245
  // web-src/local-runtimes.ts
133
246
  var LLAMA_CPP = "b12776";
247
+ var SHERPA_ONNX = "2.0.3";
134
248
  var LOCAL_RUNTIMES = {
135
249
  "llama.cpp": {
136
250
  version: LLAMA_CPP,
@@ -168,34 +282,70 @@ var LOCAL_RUNTIMES = {
168
282
  },
169
283
  urls: (build) => [`https://github.com/ggml-org/llama.cpp/releases/download/${LLAMA_CPP}/${build.file}`],
170
284
  program: (platform) => platform === "win32" ? "llama-server.exe" : "llama-server",
171
- args: (model, port, extra) => [
172
- "-m",
173
- model,
174
- "--host",
175
- "127.0.0.1",
176
- "--port",
177
- String(port),
178
- "-c",
179
- "4096",
180
- "-np",
181
- "1",
182
- "-ngl",
183
- "99",
184
- "--no-webui",
185
- ...extra
186
- ],
187
- serves: async (get, model) => {
188
- if ((await get("/health"))?.status !== 200) {
189
- return false;
190
- }
191
- try {
192
- return JSON.parse((await get("/props"))?.body ?? "{}").model_path === model;
193
- } catch {
194
- return false;
285
+ launch: (program, { model, port, extra }) => ({
286
+ command: program,
287
+ args: ["-m", model, "--host", "127.0.0.1", "--port", String(port), "-c", "4096", "-np", "1", "-ngl", "99", "--no-webui", ...extra]
288
+ }),
289
+ probe: (program) => ({ command: program, args: ["--version"] }),
290
+ serves: (get, model) => servesModel(get, model)
291
+ },
292
+ "sherpa-onnx": {
293
+ version: SHERPA_ONNX,
294
+ builds: {
295
+ "darwin-arm64": {
296
+ file: `sherpa-onnx-darwin-arm64-${SHERPA_ONNX}.tgz`,
297
+ sha256: "7e48259845d72528d344a0a4ca4c2837af7a6ea111bf5604096707dc3d3e2ff8",
298
+ bytes: 10321951
299
+ },
300
+ "darwin-x64": {
301
+ file: `sherpa-onnx-darwin-x64-${SHERPA_ONNX}.tgz`,
302
+ sha256: "0818d29eaff62b9f9f4e8c4042b8f73920562c31879ad33f9862c91dbda10571",
303
+ bytes: 11513279
304
+ },
305
+ "linux-x64": {
306
+ file: `sherpa-onnx-linux-x64-${SHERPA_ONNX}.tgz`,
307
+ sha256: "7db826dabf368aacc5bb63a918948d5aff206d01730c1153e5918ba67d705880",
308
+ bytes: 11339333
309
+ },
310
+ "linux-arm64": {
311
+ file: `sherpa-onnx-linux-arm64-${SHERPA_ONNX}.tgz`,
312
+ sha256: "0d41c3b83cefc468990c718a276079a2d7a3c4eb8d3bf087cff0fbd71524d3c6",
313
+ bytes: 14150358
314
+ },
315
+ "win32-x64": {
316
+ file: `sherpa-onnx-win-x64-${SHERPA_ONNX}.tgz`,
317
+ sha256: "a965ef89c99381d99e0ae45e94021df6e2bd4db47f5cf97914dbde2507f32191",
318
+ bytes: 8958589
319
+ },
320
+ "win32-arm64": {
321
+ file: `sherpa-onnx-win-arm64-${SHERPA_ONNX}.tgz`,
322
+ sha256: "af902465a8cbab4af8398d4dcb6fab16d29e9b9ffdf2a2d39a376109b7421bb6",
323
+ bytes: 8562897
195
324
  }
196
- }
325
+ },
326
+ urls: (build) => {
327
+ const name = build.file.replace(`-${SHERPA_ONNX}.tgz`, "");
328
+ return [`https://registry.npmjs.org/${name}/-/${build.file}`, `https://registry.npmmirror.com/${name}/-/${build.file}`];
329
+ },
330
+ program: () => "sherpa-onnx.node",
331
+ launch: (program, { model, files, port, extra }) => ({
332
+ command: process.execPath,
333
+ args: ["-e", SHERPA_SERVER, "--", `--addon=${program}`, `--model=${model}`, `--tokens=${files.tokens ?? ""}`, `--port=${port}`, ...extra]
334
+ }),
335
+ probe: (program) => ({ command: process.execPath, args: ["-e", `require(${JSON.stringify(program)})`] }),
336
+ serves: (get, model) => servesModel(get, model)
197
337
  }
198
338
  };
339
+ async function servesModel(get, model) {
340
+ if ((await get("/health"))?.status !== 200) {
341
+ return false;
342
+ }
343
+ try {
344
+ return JSON.parse((await get("/props"))?.body ?? "{}").model_path === model;
345
+ } catch {
346
+ return false;
347
+ }
348
+ }
199
349
  var LocalRuntimes;
200
350
  ((LocalRuntimes) => {
201
351
  function build(runtime, platform, arch) {
@@ -222,6 +372,11 @@ var LocalSystem;
222
372
  return stat2(path).then(() => true, () => false);
223
373
  }
224
374
  LocalSystem.exists = exists;
375
+ async function absent(dir, files) {
376
+ const there = await Promise.all(files.map((file) => exists(join(dir, file.file))));
377
+ return files.filter((_, index) => !there[index]);
378
+ }
379
+ LocalSystem.absent = absent;
225
380
  async function find(dir, name) {
226
381
  const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
227
382
  if (entries.some((entry) => entry.isFile() && entry.name === name)) {
@@ -270,10 +425,10 @@ var LocalSystem;
270
425
  });
271
426
  }
272
427
  LocalSystem.extract = extract;
273
- function probe(program, env) {
428
+ function probe(command, args, cwd, env) {
274
429
  return new Promise((resolve) => {
275
430
  let said = "";
276
- const child = spawn(program, ["--version"], { cwd: dirname(program), env, stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
431
+ const child = spawn(command, args, { cwd, env, stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
277
432
  child.stderr?.on("data", (chunk) => {
278
433
  said += String(chunk);
279
434
  });
@@ -302,6 +457,11 @@ var LocalSystem;
302
457
  `)[0].slice(0, 200);
303
458
  }
304
459
  LocalSystem.missing = missing;
460
+ function envOf(program, platform) {
461
+ const beside = (name, gap) => ({ [name]: [dirname(program), process.env[name]].filter(Boolean).join(gap) });
462
+ return { ...process.env, ...platform === "linux" ? beside("LD_LIBRARY_PATH", ":") : platform === "win32" ? beside("PATH", ";") : {} };
463
+ }
464
+ LocalSystem.envOf = envOf;
305
465
  function run(program, args, options) {
306
466
  const child = spawn(program, args, { ...options, stdio: "ignore", windowsHide: true });
307
467
  child.once("error", () => {
@@ -343,6 +503,40 @@ var LocalSystem;
343
503
  LocalSystem.sleep = sleep;
344
504
  })(LocalSystem ||= {});
345
505
 
506
+ // web-src/local-tidy.ts
507
+ import { readdir as readdir2, rm as rm2 } from "node:fs/promises";
508
+ import { join as join2 } from "node:path";
509
+ var LocalTidy;
510
+ ((LocalTidy) => {
511
+ async function keep(dir, wanted) {
512
+ const files = new Set(wanted.flatMap((model) => [model, ...Object.values(model.files ?? {})]).flatMap((file) => [file.file, `${file.file}.part`]));
513
+ for (const name of await readdir2(join2(dir, "models")).catch(() => [])) {
514
+ if (!files.has(name)) {
515
+ await rm2(join2(dir, "models", name), { force: true });
516
+ }
517
+ }
518
+ const runtimes = new Set(wanted.map((model) => model.runtime));
519
+ for (const runtime of TA_LOCAL_RUNTIMES) {
520
+ if (!runtimes.has(runtime)) {
521
+ await rm2(join2(dir, "runtimes", runtime), { recursive: true, force: true });
522
+ }
523
+ }
524
+ for (const runtime of runtimes) {
525
+ for (const version of await readdir2(join2(dir, "runtimes", runtime)).catch(() => [])) {
526
+ if (version !== LOCAL_RUNTIMES[runtime].version) {
527
+ await rm2(join2(dir, "runtimes", runtime, version), { recursive: true, force: true });
528
+ }
529
+ }
530
+ }
531
+ for (const name of await readdir2(dir).catch(() => [])) {
532
+ if (/\.(zip|tar\.gz|tgz)(\.part)?$/.test(name) && !runtimes.size) {
533
+ await rm2(join2(dir, name), { force: true });
534
+ }
535
+ }
536
+ }
537
+ LocalTidy.keep = keep;
538
+ })(LocalTidy ||= {});
539
+
346
540
  // web-src/local-models.ts
347
541
  var IDLE_START_MS = 5 * 60000;
348
542
  var IDLE_MIN_MS = 2 * 60000;
@@ -356,7 +550,7 @@ class LocalModels {
356
550
  fetch;
357
551
  now;
358
552
  job;
359
- got = new Map;
553
+ progress;
360
554
  errors = new Map;
361
555
  servers = new Map;
362
556
  state = {};
@@ -367,6 +561,7 @@ class LocalModels {
367
561
  this.deps = deps;
368
562
  this.fetch = deps.fetch ?? new FileFetch;
369
563
  this.now = deps.now ?? (() => Date.now());
564
+ this.progress = new LocalProgress(() => this.tell(), this.now);
370
565
  }
371
566
  async resume() {
372
567
  await this.load();
@@ -384,6 +579,7 @@ class LocalModels {
384
579
  if ((await this.deps.store.on())?.[need.id] !== undefined) {
385
580
  this.pump();
386
581
  }
582
+ this.tell();
387
583
  return this.needStatus(need.id);
388
584
  }
389
585
  async status() {
@@ -405,7 +601,7 @@ class LocalModels {
405
601
  const recommended = LocalRuntimes.recommended(need.models, this.deps.memory);
406
602
  const ready = on !== undefined && await this.ready(model);
407
603
  const getting = on !== undefined && !ready && this.job !== undefined;
408
- const got = getting ? this.progressOf(model) : undefined;
604
+ const got = getting ? this.progress.sum(model, LocalRuntimes.build(model.runtime, this.deps.platform, this.deps.arch)?.file) : undefined;
409
605
  const error = on !== undefined && !ready ? this.errors.get(id) : undefined;
410
606
  return {
411
607
  need,
@@ -439,6 +635,7 @@ class LocalModels {
439
635
  await this.tidy();
440
636
  }
441
637
  this.pump();
638
+ this.tell();
442
639
  return this.needStatus(id);
443
640
  }
444
641
  async disable(id) {
@@ -451,6 +648,7 @@ class LocalModels {
451
648
  if ((await this.wanted()).size) {
452
649
  this.pump();
453
650
  }
651
+ this.tell();
454
652
  return this.needStatus(id);
455
653
  }
456
654
  async url(id) {
@@ -470,6 +668,7 @@ class LocalModels {
470
668
  if (!server) {
471
669
  server = this.start(model);
472
670
  this.servers.set(key, server);
671
+ this.tell();
473
672
  }
474
673
  this.keepUp(server);
475
674
  return server.ready;
@@ -501,8 +700,9 @@ class LocalModels {
501
700
  this.errors.clear();
502
701
  await this.restart();
503
702
  const bytes = await this.usage();
504
- await rm2(this.deps.dir, { recursive: true, force: true });
703
+ await rm3(this.deps.dir, { recursive: true, force: true });
505
704
  this.state = {};
705
+ this.tell();
506
706
  return bytes;
507
707
  }
508
708
  usage() {
@@ -580,6 +780,7 @@ class LocalModels {
580
780
  }
581
781
  const error = LocalChecks.errorOf(failure);
582
782
  this.errors.set(id, error);
783
+ this.tell();
583
784
  failed ||= error.code !== "disk" && error.code !== "unsupported" && error.code !== "system";
584
785
  }
585
786
  }
@@ -591,6 +792,7 @@ class LocalModels {
591
792
  })().finally(() => {
592
793
  if (this.job?.abort === abort) {
593
794
  this.job = undefined;
795
+ this.tell();
594
796
  }
595
797
  });
596
798
  this.job = { abort, done };
@@ -615,96 +817,70 @@ class LocalModels {
615
817
  const modelPath = this.modelPath(model);
616
818
  const hasProgram = await this.program(model.runtime) !== undefined;
617
819
  const hasModel = await LocalSystem.exists(modelPath);
618
- if (hasProgram && hasModel) {
820
+ const missing = await LocalSystem.absent(join3(this.deps.dir, "models"), Object.values(model.files ?? {}));
821
+ if (hasProgram && hasModel && !missing.length) {
619
822
  return;
620
823
  }
621
- const needed = (hasProgram ? 0 : build.bytes * 3) + (hasModel ? 0 : model.bytes);
824
+ const needed = (hasProgram ? 0 : build.bytes * 3) + (hasModel ? 0 : model.bytes) + missing.reduce((sum, file) => sum + file.bytes, 0);
622
825
  const free = await (this.deps.free ?? LocalSystem.free)(this.deps.dir);
623
826
  if (free !== undefined && free < needed + DISK_SPARE) {
624
827
  throw Object.assign(new Error(`${needed} bytes are needed, ${free} free`), { code: "disk", needed, free });
625
828
  }
626
- await mkdir2(join2(this.deps.dir, "models"), { recursive: true });
829
+ await mkdir2(join3(this.deps.dir, "models"), { recursive: true });
627
830
  if (!hasProgram) {
628
- const archive = join2(this.deps.dir, build.file);
831
+ const archive = join3(this.deps.dir, build.file);
629
832
  await this.fetch.get({
630
833
  urls: build.urls,
631
834
  to: archive,
632
835
  sha256: build.sha256,
633
836
  signal,
634
- progress: (done, total) => this.got.set(build.file, { done, total: total || build.bytes })
837
+ progress: this.progress.of(build.file, build.bytes)
635
838
  });
636
- await rm2(runtimeDir, { recursive: true, force: true });
839
+ await rm3(runtimeDir, { recursive: true, force: true });
637
840
  await mkdir2(runtimeDir, { recursive: true });
638
841
  await (this.deps.extract ?? LocalSystem.extract)(archive, runtimeDir);
639
- await rm2(archive, { force: true });
640
- this.got.delete(build.file);
842
+ await rm3(archive, { force: true });
843
+ this.progress.done(build.file);
641
844
  const unpacked = await this.program(model.runtime);
642
845
  if (!unpacked) {
643
846
  throw Object.assign(new Error(`${build.file} has no ${LOCAL_RUNTIMES[model.runtime].program(this.deps.platform)}`), { code: "check" });
644
847
  }
645
- const why = await (this.deps.probe ?? LocalSystem.probe)(unpacked, this.envOf(unpacked));
848
+ const probe = LOCAL_RUNTIMES[model.runtime].probe(unpacked);
849
+ const why = await (this.deps.probe ?? LocalSystem.probe)(probe.command, probe.args, dirname2(unpacked), this.envOf(unpacked));
646
850
  if (why) {
647
- await rm2(runtimeDir, { recursive: true, force: true });
851
+ await rm3(runtimeDir, { recursive: true, force: true });
648
852
  throw Object.assign(new Error(why), { code: "system" });
649
853
  }
650
854
  }
651
- if (!hasModel) {
855
+ for (const file of [...hasModel ? [] : [model], ...missing]) {
652
856
  await this.fetch.get({
653
- urls: model.urls,
654
- to: modelPath,
655
- sha256: model.sha256,
857
+ urls: file.urls,
858
+ to: join3(this.deps.dir, "models", file.file),
859
+ sha256: file.sha256,
656
860
  signal,
657
- progress: (done, total) => this.got.set(model.file, { done, total: total || model.bytes })
861
+ progress: this.progress.of(file.file, file.bytes)
658
862
  });
659
- this.got.delete(model.file);
660
- }
661
- }
662
- progressOf(model) {
663
- const build = LocalRuntimes.build(model.runtime, this.deps.platform, this.deps.arch);
664
- const parts = [build ? this.got.get(build.file) ?? { done: 0, total: 0 } : undefined, this.got.get(model.file) ?? { done: 0, total: model.bytes }];
665
- let done = 0;
666
- let total = 0;
667
- for (const part of parts) {
668
- done += part?.done ?? 0;
669
- total += part?.total ?? 0;
863
+ this.progress.done(file.file);
670
864
  }
671
- return { done, total: Math.max(total, model.bytes) };
672
865
  }
673
866
  async tidy() {
674
- const wanted = [...(await this.wanted()).values()];
675
- const files = new Set(wanted.flatMap((model) => [model.file, `${model.file}.part`]));
676
- for (const name of await readdir2(join2(this.deps.dir, "models")).catch(() => [])) {
677
- if (!files.has(name)) {
678
- await rm2(join2(this.deps.dir, "models", name), { force: true });
679
- }
680
- }
681
- const runtimes = new Set(wanted.map((model) => model.runtime));
682
- for (const runtime of TA_LOCAL_RUNTIMES) {
683
- if (!runtimes.has(runtime)) {
684
- await rm2(join2(this.deps.dir, "runtimes", runtime), { recursive: true, force: true });
685
- }
686
- }
687
- for (const runtime of runtimes) {
688
- for (const version of await readdir2(join2(this.deps.dir, "runtimes", runtime)).catch(() => [])) {
689
- if (version !== LOCAL_RUNTIMES[runtime].version) {
690
- await rm2(join2(this.deps.dir, "runtimes", runtime, version), { recursive: true, force: true });
691
- }
692
- }
693
- }
694
- for (const name of await readdir2(this.deps.dir).catch(() => [])) {
695
- if (/\.(zip|tar\.gz)(\.part)?$/.test(name) && !runtimes.size) {
696
- await rm2(join2(this.deps.dir, name), { force: true });
697
- }
698
- }
867
+ await LocalTidy.keep(this.deps.dir, [...(await this.wanted()).values()]);
868
+ }
869
+ tell() {
870
+ this.deps.changed?.();
699
871
  }
700
872
  runtimeDir(runtime) {
701
- return join2(this.deps.dir, "runtimes", runtime, LOCAL_RUNTIMES[runtime].version);
873
+ return join3(this.deps.dir, "runtimes", runtime, LOCAL_RUNTIMES[runtime].version);
702
874
  }
703
875
  modelPath(model) {
704
- return join2(this.deps.dir, "models", model.file);
876
+ return join3(this.deps.dir, "models", model.file);
705
877
  }
706
878
  async ready(model) {
707
- return await LocalSystem.exists(this.modelPath(model)) && await this.program(model.runtime) !== undefined;
879
+ const files = [model, ...Object.values(model.files ?? {})];
880
+ return !(await LocalSystem.absent(join3(this.deps.dir, "models"), files)).length && await this.program(model.runtime) !== undefined;
881
+ }
882
+ filesOf(model) {
883
+ return Object.fromEntries(Object.entries(model.files ?? {}).map(([name, file]) => [name, join3(this.deps.dir, "models", file.file)]));
708
884
  }
709
885
  program(runtime) {
710
886
  return LocalSystem.find(this.runtimeDir(runtime), LOCAL_RUNTIMES[runtime].program(this.deps.platform));
@@ -729,7 +905,8 @@ class LocalModels {
729
905
  const port = await LocalSystem.freePort();
730
906
  const cwd = dirname2(program);
731
907
  const env = this.envOf(program);
732
- const child = (this.deps.run ?? LocalSystem.run)(program, runtime.args(path, port, model.args ?? []), { cwd, env });
908
+ const launch = runtime.launch(program, { model: path, files: this.filesOf(model), port, extra: model.args ?? [] });
909
+ const child = (this.deps.run ?? LocalSystem.run)(launch.command, launch.args, { cwd, env });
733
910
  server.child = child;
734
911
  server.pid = child.pid;
735
912
  server.url = `http://127.0.0.1:${port}`;
@@ -738,6 +915,7 @@ class LocalModels {
738
915
  exited = true;
739
916
  if (this.servers.get(key) === server) {
740
917
  this.servers.delete(key);
918
+ this.tell();
741
919
  clearTimeout(server.idle);
742
920
  if (this.state.servers) {
743
921
  delete this.state.servers[key];
@@ -761,13 +939,13 @@ class LocalModels {
761
939
  server.ready.catch(() => {
762
940
  if (this.servers.get(key) === server) {
763
941
  this.servers.delete(key);
942
+ this.tell();
764
943
  }
765
944
  });
766
945
  return server;
767
946
  }
768
947
  envOf(program) {
769
- const dir = dirname2(program);
770
- return { ...process.env, ...this.deps.platform === "linux" ? { LD_LIBRARY_PATH: [dir, process.env.LD_LIBRARY_PATH].filter(Boolean).join(":") } : {} };
948
+ return LocalSystem.envOf(program, this.deps.platform);
771
949
  }
772
950
  keepUp(server) {
773
951
  clearTimeout(server.idle);
@@ -789,6 +967,7 @@ class LocalModels {
789
967
  clearTimeout(server.idle);
790
968
  if (this.servers.get(server.key) === server) {
791
969
  this.servers.delete(server.key);
970
+ this.tell();
792
971
  }
793
972
  await server.ready.catch(() => {
794
973
  return;
@@ -809,7 +988,7 @@ class LocalModels {
809
988
  await this.save();
810
989
  }
811
990
  load() {
812
- this.loaded ??= readFile(join2(this.deps.dir, "state.json"), "utf8").then((text) => {
991
+ this.loaded ??= readFile(join3(this.deps.dir, "state.json"), "utf8").then((text) => {
813
992
  this.state = JSON.parse(text);
814
993
  }, () => {
815
994
  return;
@@ -820,7 +999,7 @@ class LocalModels {
820
999
  await mkdir2(this.deps.dir, { recursive: true }).catch(() => {
821
1000
  return;
822
1001
  });
823
- await writeFile(join2(this.deps.dir, "state.json"), JSON.stringify(this.state)).catch(() => {
1002
+ await writeFile(join3(this.deps.dir, "state.json"), JSON.stringify(this.state)).catch(() => {
824
1003
  return;
825
1004
  });
826
1005
  }
@@ -831,7 +1010,7 @@ var NAME = "@celljs/ta-local-models";
831
1010
  var KEEP_DAYS = 90;
832
1011
  function activate(host) {
833
1012
  const models = new LocalModels({
834
- dir: join3(host.agentDir, "local-models"),
1013
+ dir: join4(host.agentDir, "local-models"),
835
1014
  platform: process.platform,
836
1015
  arch: process.arch,
837
1016
  memory: totalmem(),
@@ -844,7 +1023,8 @@ function activate(host) {
844
1023
  return;
845
1024
  }),
846
1025
  saveOn: (on) => host.setExtensionData(NAME, "on", on)
847
- }
1026
+ },
1027
+ changed: () => host.changed?.("status")
848
1028
  });
849
1029
  models.resume();
850
1030
  host.storage?.register({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-local-models",
3
- "version": "4.42.0",
3
+ "version": "4.44.0",
4
4
  "description": "A pi package for Ta: models that run on this computer, downloaded only once the user turns on a use of them, checked, started when needed and stopped when idle, for other packages to use",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -26,8 +26,8 @@
26
26
  "watch": "tsc -b -w --preserveWatchOutput"
27
27
  },
28
28
  "devDependencies": {
29
- "@celljs/ta-protocol": "4.42.0",
30
- "@celljs/ta-web": "4.42.0",
29
+ "@celljs/ta-protocol": "4.44.0",
30
+ "@celljs/ta-web": "4.44.0",
31
31
  "@types/react": "^19.3.3"
32
32
  },
33
33
  "publishConfig": {
package/web/index.js CHANGED
@@ -138,19 +138,20 @@ function bind(react) {
138
138
  // web-src/style.ts
139
139
  var STYLE = `
140
140
  .ta-local { display: flex; flex-direction: column; gap: 12px; width: 100%; }
141
- .ta-local-need { display: flex; flex-direction: column; gap: 8px; padding: 14px 16px; border: 1px solid var(--ta-border); border-radius: 12px; }
141
+ .ta-local-need { display: flex; flex-direction: column; gap: 8px; }
142
+ .ta-local-need + .ta-local-need { padding-top: 12px; border-top: 1px solid var(--ta-border-muted); }
142
143
  .ta-local-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
143
- .ta-local-title { font-weight: 600; color: var(--ta-text); }
144
+ .ta-local-title { font-weight: 500; color: var(--ta-text); }
144
145
  .ta-local-hint, .ta-local-note { margin: 0; color: var(--ta-secondary); font-size: calc(13px * var(--ta-font-scale)); line-height: 1.5; }
145
146
  .ta-local-models button { display: flex; flex-direction: column; align-items: center; gap: 1px; height: auto; min-height: 40px; padding: 4px 8px; }
146
147
  .ta-local-model { font-weight: 500; }
147
148
  .ta-local-size { font-size: calc(11px * var(--ta-font-scale)); color: var(--ta-secondary); }
148
149
  .ta-local-state { display: flex; align-items: center; gap: 8px; margin: 0; font-size: calc(13px * var(--ta-font-scale)); color: var(--ta-secondary); font-variant-numeric: tabular-nums; }
149
150
  .ta-local-dot { flex: none; width: 7px; height: 7px; border-radius: 50%; background: var(--ta-border-field); }
150
- .ta-local-dot.ta-local-ready { background: #34c759; }
151
- .ta-local-dot.ta-local-getting { background: #0a84ff; animation: ta-local-blink 1.2s ease-in-out infinite; }
152
- .ta-local-dot.ta-local-failed { background: #ff9f0a; }
153
- .ta-local-retry { margin-left: auto; height: 26px; padding: 0 10px; border-radius: 7px; border: 1px solid var(--ta-border); background: transparent; color: var(--ta-text); font: inherit; cursor: pointer; }
151
+ .ta-local-dot.ta-local-ready { background: var(--ta-green); }
152
+ .ta-local-dot.ta-local-getting { background: var(--ta-blue); animation: ta-local-blink 1.2s ease-in-out infinite; }
153
+ .ta-local-dot.ta-local-failed { background: var(--ta-yellow); }
154
+ .ta-local-retry { margin-left: auto; }
154
155
  @keyframes ta-local-blink { 50% { opacity: 0.35; } }
155
156
  `;
156
157
  function injectStyle() {
@@ -179,6 +180,13 @@ function activate(pi) {
179
180
  return removeStyle;
180
181
  }
181
182
  function useStatus(pi) {
183
+ return (typeof pi.ui.useHost === "function" ? useHostStatus : usePolledStatus)(pi);
184
+ }
185
+ function useHostStatus(pi) {
186
+ const status = pi.ui.useHost("status");
187
+ return [status.value, status.read];
188
+ }
189
+ function usePolledStatus(pi) {
182
190
  const [status, setStatus] = React.useState();
183
191
  const live = React.useRef(true);
184
192
  const read = React.useCallback(() => pi.callHost("status").then((next) => {
@@ -267,7 +275,7 @@ function Need({ pi, status, read, words }) {
267
275
  "aria-hidden": "true"
268
276
  }), stateText(status, model, words), status.state === "failed" && status.error?.code !== "unsupported" && /* @__PURE__ */ React.createElement("button", {
269
277
  type: "button",
270
- className: "ta-local-retry",
278
+ className: "ta-button ta-local-retry",
271
279
  onClick: () => act("enable", status.model)
272
280
  }, words.retry)));
273
281
  }