@celljs/ta-local-models 0.0.0-stage → 4.36.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.
package/README.en.md ADDED
@@ -0,0 +1,22 @@
1
+ # @celljs/ta-local-models
2
+
3
+ [简体中文](./README.md)
4
+
5
+ A built-in package of Ta: models of this computer. A feature that runs a model here (the decision model of live hands) leaves it all to this package: downloading, checking, starting, stopping and clearing are done in this one place, and the feature only says what it needs. Design: [ta-local-models.md](../../docs/design/ta-local-models.md).
6
+
7
+ - **Downloaded when turned on**: a package registers a need with the models it can use (file, size, SHA-256, sources). Only once the user turns it on in Settings → Local models is anything downloaded: the program that runs it (the server of llama.cpp, for macOS, Linux or Windows and the CPU), then the model; after the network went, the lid closed or Ta restarted it goes on from where it stopped, each file checked by its SHA-256 and downloaded again when it does not match. The model is chosen by the memory of the computer (the larger from 16 GB), and can be changed.
8
+ - **Started when used**: the server of a model starts when its feature asks `url`, at a free port of 127.0.0.1; it stops once nothing asked for a while, longer when it was soon wanted again, shorter when long unused (2 to 30 minutes, from 5). One still running after Ta restarted is used again.
9
+ - **Cleared**: turned off, what only it used goes; Settings → Storage shows what it takes and clears it, and a model unused for 90 days goes by itself (the days can be changed).
10
+ - **Falls back**: with the package off, no build for the platform or too little room, the feature gets no address and does without (live hands ask the commander).
11
+
12
+ ## For other packages
13
+
14
+ ```ts
15
+ import { TA_LOCAL_MODELS, type TaLocalNeed } from '@celljs/ta-protocol';
16
+
17
+ await host.callPackageHost(TA_LOCAL_MODELS, 'need', [need]); // each time the package starts
18
+ const status = await host.callPackageHost(TA_LOCAL_MODELS, 'needStatus', [need.id]); // state: off | getting | ready | failed
19
+ const url = await host.callPackageHost(TA_LOCAL_MODELS, 'url', [need.id]); // http://127.0.0.1:<port>, OpenAI-compatible
20
+ ```
21
+
22
+ The runtime is llama.cpp (`b12776`) for now; another is one more entry of `local-runtimes.ts`.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @celljs/ta-local-models
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [English](./README.en.md)
4
+
5
+ Ta 的内置包:本机模型。别的功能要在这台电脑上跑模型时(比如实时操作的决策模型),都交给它:下载、校验、启动、停下、清理只在这一处,用的一方只说要什么。设计见 [ta-local-models.md](../../docs/design/ta-local-models.md)。
6
+
7
+ - **按需下载**:包登记一项用途(need),列出可用的模型(文件名、大小、SHA-256、下载地址)。用户在 设置 → 本机模型 打开这一项后才下载:先下运行它的程序(llama.cpp 的服务端,按 Mac / Linux / Windows 和 CPU 架构选包),再下模型;断网、合盖、Ta 重启后从断点接着下,每个文件校验 SHA-256,不对就重下。默认按内存挑模型(16 GB 以上用大的),可以改选。
8
+ - **用到才启动**:用的一方调 `url`,模型的服务才在 127.0.0.1 的空闲端口上启动;一段时间没人用就停下,停了很快又要用就把这段时间放长,很久不用就缩短(2–30 分钟,从 5 分钟起)。Ta 重启后还在跑的服务直接接着用。
9
+ - **回收**:关掉一项就删掉只有它用的文件;设置 → 存储空间 里能看到占用、一键清除,90 天没用的模型自动清理(天数可改)。
10
+ - **降级**:这个包关掉、平台没有对应的包、磁盘不够时,用的一方拿不到地址,照它自己的办法退回(实时操作退到问大模型)。
11
+
12
+ ## 给别的包用
13
+
14
+ ```ts
15
+ import { TA_LOCAL_MODELS, type TaLocalNeed } from '@celljs/ta-protocol';
16
+
17
+ await host.callPackageHost(TA_LOCAL_MODELS, 'need', [need]); // 每次启动时登记
18
+ const status = await host.callPackageHost(TA_LOCAL_MODELS, 'needStatus', [need.id]); // state: off | getting | ready | failed
19
+ const url = await host.callPackageHost(TA_LOCAL_MODELS, 'url', [need.id]); // http://127.0.0.1:<port>,OpenAI 兼容
20
+ ```
21
+
22
+ 运行时目前是 llama.cpp(`b12776`);加别的运行时只需在 `local-runtimes.ts` 里加一项。
package/host/index.mjs ADDED
@@ -0,0 +1,879 @@
1
+ // web-src/host.ts
2
+ import { totalmem } from "node:os";
3
+ import { join as join3 } from "node:path";
4
+
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"];
11
+
12
+ // web-src/file-fetch.ts
13
+ import { createHash } from "node:crypto";
14
+ import { createReadStream } from "node:fs";
15
+ import { open, rename, rm, stat } from "node:fs/promises";
16
+
17
+ class FileFetch {
18
+ fetch;
19
+ constructor(fetch2 = globalThis.fetch) {
20
+ this.fetch = fetch2;
21
+ }
22
+ async get(job) {
23
+ const failures = [];
24
+ for (const url of job.urls) {
25
+ try {
26
+ await this.from(url, job);
27
+ return;
28
+ } catch (failure) {
29
+ if (job.signal?.aborted) {
30
+ throw failure;
31
+ }
32
+ failures.push(`${new URL(url).host}: ${failure instanceof Error ? failure.message : String(failure)}`);
33
+ }
34
+ }
35
+ throw new Error(failures.join("; "));
36
+ }
37
+ async from(url, job) {
38
+ const part = `${job.to}.part`;
39
+ let have = await stat(part).then((info) => info.size, () => 0);
40
+ job.progress?.(have, 0);
41
+ let hash = have ? await FileFetch.hashOf(part) : createHash("sha256");
42
+ const response = await this.fetch(url, {
43
+ headers: have ? { range: `bytes=${have}-` } : {},
44
+ redirect: "follow",
45
+ ...job.signal ? { signal: job.signal } : {}
46
+ });
47
+ if (have && response.status === 416) {
48
+ return this.finish(part, job, hash);
49
+ }
50
+ if (have && response.status === 200) {
51
+ have = 0;
52
+ hash = createHash("sha256");
53
+ }
54
+ if (!response.ok || !response.body) {
55
+ throw new Error(`HTTP ${response.status}`);
56
+ }
57
+ const length = Number(response.headers.get("content-length") ?? 0);
58
+ const total = length ? have + length : 0;
59
+ const file = await open(part, have ? "a" : "w");
60
+ try {
61
+ let done = have;
62
+ for await (const chunk of response.body) {
63
+ hash.update(chunk);
64
+ await file.write(chunk);
65
+ done += chunk.byteLength;
66
+ job.progress?.(done, total);
67
+ }
68
+ } finally {
69
+ await file.close();
70
+ }
71
+ return this.finish(part, job, hash);
72
+ }
73
+ async finish(part, job, hash) {
74
+ const got = hash.digest("hex");
75
+ if (got !== job.sha256) {
76
+ await rm(part, { force: true });
77
+ throw new Error(`The file does not check out (SHA-256 ${got.slice(0, 12)}…): downloading it again.`);
78
+ }
79
+ await rename(part, job.to);
80
+ }
81
+ static hashOf(path) {
82
+ const hash = createHash("sha256");
83
+ return new Promise((resolve, reject) => {
84
+ createReadStream(path).on("data", (chunk) => hash.update(chunk)).on("error", reject).on("end", () => resolve(hash));
85
+ });
86
+ }
87
+ }
88
+
89
+ // web-src/local-checks.ts
90
+ var SHA256 = /^[0-9a-f]{64}$/;
91
+ var LocalChecks;
92
+ ((LocalChecks) => {
93
+ function check(need) {
94
+ if (typeof need?.id !== "string" || !/^[@\w.-]+(\/[\w.-]+)+$/.test(need.id) || !Array.isArray(need.models) || !need.models.length) {
95
+ throw new Error('A need is {id: "<package>/<name>", title, hint, models: [at least one]}.');
96
+ }
97
+ for (const model of need.models) {
98
+ const runtime = model.runtime;
99
+ if (!TA_LOCAL_RUNTIMES.includes(runtime)) {
100
+ throw new Error(`The runtimes are ${TA_LOCAL_RUNTIMES.join(", ")}, not ${runtime}.`);
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).`);
104
+ }
105
+ if (!model.urls.length || model.urls.some((url) => !url.startsWith("https://"))) {
106
+ throw new Error(`${model.id} is downloaded over HTTPS alone.`);
107
+ }
108
+ if (model.args?.some((arg) => ["--host", "--port", "-m", "--model"].includes(arg))) {
109
+ throw new Error(`${model.id} cannot set where its server listens nor which file it serves.`);
110
+ }
111
+ }
112
+ }
113
+ LocalChecks.check = check;
114
+ function errorOf(failure) {
115
+ const code = failure?.code;
116
+ const message = failure instanceof Error ? failure.message : String(failure);
117
+ if (code === "disk") {
118
+ const { needed, free } = failure;
119
+ return { code, needed, free };
120
+ }
121
+ if (code === "unsupported" || code === "start") {
122
+ return { code };
123
+ }
124
+ if (code === "system") {
125
+ return { code, detail: message.slice(0, 300) };
126
+ }
127
+ return { code: code === "check" || /check out/.test(message) ? "check" : "network", detail: message.slice(0, 200) };
128
+ }
129
+ LocalChecks.errorOf = errorOf;
130
+ })(LocalChecks ||= {});
131
+
132
+ // web-src/local-runtimes.ts
133
+ var LLAMA_CPP = "b12776";
134
+ var LOCAL_RUNTIMES = {
135
+ "llama.cpp": {
136
+ version: LLAMA_CPP,
137
+ builds: {
138
+ "darwin-arm64": {
139
+ file: `llama-${LLAMA_CPP}-bin-macos-arm64.tar.gz`,
140
+ sha256: "cb0c5c97a1a4ad50a0d64e228a67694de5c3a876d1ae0077b39e3c2381f3a039",
141
+ bytes: 16100000
142
+ },
143
+ "darwin-x64": {
144
+ file: `llama-${LLAMA_CPP}-bin-macos-x64.tar.gz`,
145
+ sha256: "e644d574b6800879163352cea41b4ebbe03d88a6704adab28dddbe44805f4918",
146
+ bytes: 12000000
147
+ },
148
+ "linux-x64": {
149
+ file: `llama-${LLAMA_CPP}-bin-ubuntu-x64.tar.gz`,
150
+ sha256: "27e18f608c7cd1e2f86d70f91bde4299e795113c0065322f6339cbe5135e79c2",
151
+ bytes: 22400000
152
+ },
153
+ "linux-arm64": {
154
+ file: `llama-${LLAMA_CPP}-bin-ubuntu-arm64.tar.gz`,
155
+ sha256: "69a37e8fc18bf06214052d39fd83605846273ba08d7a6d88651e95788ca926db",
156
+ bytes: 18100000
157
+ },
158
+ "win32-x64": {
159
+ file: `llama-${LLAMA_CPP}-bin-win-cpu-x64.zip`,
160
+ sha256: "bba23437a597b7b346acb87dbac2e5452c7b188cec67ca6315bec513a067ace8",
161
+ bytes: 24100000
162
+ },
163
+ "win32-arm64": {
164
+ file: `llama-${LLAMA_CPP}-bin-win-cpu-arm64.zip`,
165
+ sha256: "e0b56f7388e77bb7ee2adffa006ef41fe2485b2f5bf28eb3cc8ea16a96fdfa99",
166
+ bytes: 12700000
167
+ }
168
+ },
169
+ urls: (build) => [`https://github.com/ggml-org/llama.cpp/releases/download/${LLAMA_CPP}/${build.file}`],
170
+ 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;
195
+ }
196
+ }
197
+ }
198
+ };
199
+ var LocalRuntimes;
200
+ ((LocalRuntimes) => {
201
+ function build(runtime, platform, arch) {
202
+ const of = LOCAL_RUNTIMES[runtime];
203
+ const build2 = of?.builds[`${platform}-${arch}`];
204
+ return build2 ? { ...build2, urls: of.urls(build2) } : undefined;
205
+ }
206
+ LocalRuntimes.build = build;
207
+ function recommended(models, memory) {
208
+ const gb = memory / 1024 ** 3;
209
+ return models.find((model) => gb >= (model.forMemoryGB ?? 0) * 0.95) ?? models[models.length - 1];
210
+ }
211
+ LocalRuntimes.recommended = recommended;
212
+ })(LocalRuntimes ||= {});
213
+
214
+ // web-src/local-system.ts
215
+ import { spawn } from "node:child_process";
216
+ import { mkdir, readdir, stat as stat2, statfs } from "node:fs/promises";
217
+ import { createServer } from "node:net";
218
+ import { dirname, join } from "node:path";
219
+ var LocalSystem;
220
+ ((LocalSystem) => {
221
+ function exists(path) {
222
+ return stat2(path).then(() => true, () => false);
223
+ }
224
+ LocalSystem.exists = exists;
225
+ async function find(dir, name) {
226
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
227
+ if (entries.some((entry) => entry.isFile() && entry.name === name)) {
228
+ return join(dir, name);
229
+ }
230
+ for (const entry of entries) {
231
+ if (entry.isDirectory()) {
232
+ const found = await find(join(dir, entry.name), name);
233
+ if (found) {
234
+ return found;
235
+ }
236
+ }
237
+ }
238
+ return;
239
+ }
240
+ LocalSystem.find = find;
241
+ async function sizeOf(path) {
242
+ const info = await stat2(path).catch(() => {
243
+ return;
244
+ });
245
+ if (!info?.isDirectory()) {
246
+ return info?.size ?? 0;
247
+ }
248
+ let bytes = 0;
249
+ for (const name of await readdir(path).catch(() => [])) {
250
+ bytes += await sizeOf(join(path, name));
251
+ }
252
+ return bytes;
253
+ }
254
+ LocalSystem.sizeOf = sizeOf;
255
+ async function free(dir) {
256
+ await mkdir(dir, { recursive: true }).catch(() => {
257
+ return;
258
+ });
259
+ return statfs(dir).then((info) => info.bavail * info.bsize, () => {
260
+ return;
261
+ });
262
+ }
263
+ LocalSystem.free = free;
264
+ function extract(archive, to) {
265
+ const tar = process.platform === "win32" ? join(process.env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe") : "tar";
266
+ return new Promise((resolve, reject) => {
267
+ const child = spawn(tar, ["-xf", archive, "-C", to], { stdio: "ignore", windowsHide: true });
268
+ child.once("error", reject);
269
+ child.once("exit", (code) => code === 0 ? resolve() : reject(new Error(`tar exited with ${code}`)));
270
+ });
271
+ }
272
+ LocalSystem.extract = extract;
273
+ function probe(program, env) {
274
+ return new Promise((resolve) => {
275
+ let said = "";
276
+ const child = spawn(program, ["--version"], { cwd: dirname(program), env, stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
277
+ child.stderr?.on("data", (chunk) => {
278
+ said += String(chunk);
279
+ });
280
+ const timer = setTimeout(() => child.kill(), 20000);
281
+ child.once("error", (error) => {
282
+ clearTimeout(timer);
283
+ resolve(error.message);
284
+ });
285
+ child.once("exit", (code) => {
286
+ clearTimeout(timer);
287
+ resolve(code === 0 ? undefined : missing(said) || exitWhy(code));
288
+ });
289
+ });
290
+ }
291
+ LocalSystem.probe = probe;
292
+ function exitWhy(code) {
293
+ return code === 3221225781 || code === -1073741515 ? "Microsoft Visual C++ Redistributable (vcruntime140_1.dll)" : `exited with ${code}`;
294
+ }
295
+ LocalSystem.exitWhy = exitWhy;
296
+ function missing(said) {
297
+ const found = new Set;
298
+ for (const match of said.matchAll(/(lib[\w.+-]+\.so[\w.]*): cannot open|version `([\w.]+)' not found|(\S+\.dll)/g)) {
299
+ found.add(match[1] ?? match[2] ?? match[3]);
300
+ }
301
+ return found.size ? [...found].join(", ") : said.split(`
302
+ `)[0].slice(0, 200);
303
+ }
304
+ LocalSystem.missing = missing;
305
+ function run(program, args, options) {
306
+ const child = spawn(program, args, { ...options, stdio: "ignore", windowsHide: true });
307
+ child.once("error", () => {
308
+ return;
309
+ });
310
+ return child;
311
+ }
312
+ LocalSystem.run = run;
313
+ async function get(url) {
314
+ try {
315
+ const response = await fetch(url, { signal: AbortSignal.timeout(1500) });
316
+ return { status: response.status, body: await response.text() };
317
+ } catch {
318
+ return;
319
+ }
320
+ }
321
+ LocalSystem.get = get;
322
+ function freePort() {
323
+ return new Promise((resolve, reject) => {
324
+ const server = createServer();
325
+ server.once("error", reject);
326
+ server.listen(0, "127.0.0.1", () => {
327
+ const address = server.address();
328
+ const port = typeof address === "object" && address ? address.port : 0;
329
+ server.close(() => resolve(port));
330
+ });
331
+ });
332
+ }
333
+ LocalSystem.freePort = freePort;
334
+ function sleep(ms, signal) {
335
+ return new Promise((resolve) => {
336
+ const timer = setTimeout(resolve, ms);
337
+ signal?.addEventListener("abort", () => {
338
+ clearTimeout(timer);
339
+ resolve();
340
+ });
341
+ });
342
+ }
343
+ LocalSystem.sleep = sleep;
344
+ })(LocalSystem ||= {});
345
+
346
+ // web-src/local-models.ts
347
+ var IDLE_START_MS = 5 * 60000;
348
+ var IDLE_MIN_MS = 2 * 60000;
349
+ var IDLE_MAX_MS = 30 * 60000;
350
+ var START_MS = 90000;
351
+ var RETRY_MS = [5000, 15000, 60000, 300000];
352
+ var DISK_SPARE = 512 * 1024 * 1024;
353
+
354
+ class LocalModels {
355
+ deps;
356
+ fetch;
357
+ now;
358
+ job;
359
+ got = new Map;
360
+ errors = new Map;
361
+ servers = new Map;
362
+ state = {};
363
+ loaded;
364
+ touchedAt = new Map;
365
+ needs = {};
366
+ constructor(deps) {
367
+ this.deps = deps;
368
+ this.fetch = deps.fetch ?? new FileFetch;
369
+ this.now = deps.now ?? (() => Date.now());
370
+ }
371
+ async resume() {
372
+ await this.load();
373
+ await this.adopt();
374
+ if (Object.keys(await this.deps.store.on() ?? {}).length) {
375
+ this.pump();
376
+ }
377
+ }
378
+ async need(need) {
379
+ LocalChecks.check(need);
380
+ await this.load();
381
+ this.needs[need.id] = need;
382
+ const kept = { ...await this.deps.store.needs() ?? {}, [need.id]: need };
383
+ await this.deps.store.saveNeeds(kept);
384
+ if ((await this.deps.store.on())?.[need.id] !== undefined) {
385
+ this.pump();
386
+ }
387
+ return this.needStatus(need.id);
388
+ }
389
+ async status() {
390
+ const needs = Object.keys(await this.allNeeds());
391
+ return {
392
+ needs: await Promise.all(needs.map((id) => this.needStatus(id))),
393
+ bytes: await this.usage(),
394
+ memoryGB: Math.round(this.deps.memory / 1024 ** 3)
395
+ };
396
+ }
397
+ async needStatus(id) {
398
+ await this.load();
399
+ const need = (await this.allNeeds())[id];
400
+ if (!need) {
401
+ throw new Error(`No package needs a local model as ${id}.`);
402
+ }
403
+ const on = (await this.deps.store.on())?.[id];
404
+ const model = this.modelOf(need, on);
405
+ const recommended = LocalRuntimes.recommended(need.models, this.deps.memory);
406
+ const ready = on !== undefined && await this.ready(model);
407
+ const getting = on !== undefined && !ready && this.job !== undefined;
408
+ const got = getting ? this.progressOf(model) : undefined;
409
+ const error = on !== undefined && !ready ? this.errors.get(id) : undefined;
410
+ return {
411
+ need,
412
+ supported: LocalRuntimes.build(model.runtime, this.deps.platform, this.deps.arch) !== undefined,
413
+ on: on !== undefined,
414
+ model: model.id,
415
+ recommended: recommended.id,
416
+ state: on === undefined ? "off" : ready ? "ready" : error && !getting ? "failed" : "getting",
417
+ ...got ? got : {},
418
+ ...error ? { error } : {},
419
+ running: this.servers.has(this.serverKey(model)),
420
+ ...this.state.lastUsed?.[id] ? { lastUsed: this.state.lastUsed[id] } : {}
421
+ };
422
+ }
423
+ async enable(id, modelId) {
424
+ const need = (await this.allNeeds())[id];
425
+ if (!need) {
426
+ throw new Error(`No package needs a local model as ${id}.`);
427
+ }
428
+ const model = this.modelOf(need, modelId);
429
+ if (!LocalRuntimes.build(model.runtime, this.deps.platform, this.deps.arch)) {
430
+ throw new Error(`${model.runtime} has no build for ${this.deps.platform}-${this.deps.arch}.`);
431
+ }
432
+ const on = { ...await this.deps.store.on() ?? {} };
433
+ const before = on[id];
434
+ on[id] = model.id;
435
+ await this.deps.store.saveOn(on);
436
+ this.errors.delete(id);
437
+ if (before !== undefined && before !== model.id) {
438
+ await this.restart();
439
+ await this.tidy();
440
+ }
441
+ this.pump();
442
+ return this.needStatus(id);
443
+ }
444
+ async disable(id) {
445
+ const on = { ...await this.deps.store.on() ?? {} };
446
+ delete on[id];
447
+ await this.deps.store.saveOn(on);
448
+ this.errors.delete(id);
449
+ await this.restart();
450
+ await this.tidy();
451
+ if ((await this.wanted()).size) {
452
+ this.pump();
453
+ }
454
+ return this.needStatus(id);
455
+ }
456
+ async url(id) {
457
+ await this.load();
458
+ const need = (await this.allNeeds())[id];
459
+ const chosen = (await this.deps.store.on())?.[id];
460
+ if (!need || chosen === undefined) {
461
+ throw new Error(`The local model for ${id} is off.`);
462
+ }
463
+ const model = this.modelOf(need, chosen);
464
+ if (!await this.ready(model)) {
465
+ throw new Error(`The local model for ${id} is not downloaded yet.`);
466
+ }
467
+ this.used(id);
468
+ const key = this.serverKey(model);
469
+ let server = this.servers.get(key);
470
+ if (!server) {
471
+ server = this.start(model);
472
+ this.servers.set(key, server);
473
+ }
474
+ this.keepUp(server);
475
+ return server.ready;
476
+ }
477
+ async touch(id) {
478
+ const need = (await this.allNeeds())[id];
479
+ const chosen = (await this.deps.store.on())?.[id];
480
+ const server = need && chosen !== undefined ? this.servers.get(this.serverKey(this.modelOf(need, chosen))) : undefined;
481
+ if (server) {
482
+ this.used(id);
483
+ this.keepUp(server);
484
+ }
485
+ }
486
+ async prune(limits) {
487
+ await this.load();
488
+ const days = limits.keepDays;
489
+ if (!days) {
490
+ return;
491
+ }
492
+ for (const id of Object.keys(await this.deps.store.on() ?? {})) {
493
+ const since = this.state.lastUsed?.[id];
494
+ if (since && this.now() - since > days * 86400000) {
495
+ await this.disable(id);
496
+ }
497
+ }
498
+ }
499
+ async clear() {
500
+ await this.deps.store.saveOn({});
501
+ this.errors.clear();
502
+ await this.restart();
503
+ const bytes = await this.usage();
504
+ await rm2(this.deps.dir, { recursive: true, force: true });
505
+ this.state = {};
506
+ return bytes;
507
+ }
508
+ usage() {
509
+ return LocalSystem.sizeOf(this.deps.dir);
510
+ }
511
+ dispose() {
512
+ this.job?.abort.abort();
513
+ for (const server of [...this.servers.values()]) {
514
+ this.stop(server);
515
+ }
516
+ }
517
+ async adopt() {
518
+ const models = Object.values(await this.allNeeds()).flatMap((need) => need.models);
519
+ const on = new Set([...(await this.wanted()).values()].map((model) => this.serverKey(model)));
520
+ const get = this.deps.get ?? LocalSystem.get;
521
+ for (const [key, { pid, port }] of Object.entries(this.state.servers ?? {})) {
522
+ const model = models.find((one) => this.serverKey(one) === key);
523
+ const url = `http://127.0.0.1:${port}`;
524
+ if (!model || !await LOCAL_RUNTIMES[model.runtime].serves((at) => get(`${url}${at}`), this.modelPath(model))) {
525
+ delete this.state.servers?.[key];
526
+ await this.save();
527
+ } else if (!on.has(key)) {
528
+ await this.stop({ key, pid, url, ready: Promise.resolve(url) });
529
+ } else if (!this.servers.has(key)) {
530
+ const server = { key, pid, url, ready: Promise.resolve(url) };
531
+ this.servers.set(key, server);
532
+ this.keepUp(server);
533
+ }
534
+ }
535
+ }
536
+ async allNeeds() {
537
+ return { ...await this.deps.store.needs() ?? {}, ...this.needs };
538
+ }
539
+ modelOf(need, id) {
540
+ return need.models.find((model) => model.id === id) ?? LocalRuntimes.recommended(need.models, this.deps.memory);
541
+ }
542
+ serverKey(model) {
543
+ return [model.runtime, model.file, ...model.args ?? []].join(" ");
544
+ }
545
+ used(id) {
546
+ if (this.now() - (this.touchedAt.get(id) ?? 0) > 60000) {
547
+ this.touchedAt.set(id, this.now());
548
+ this.state.lastUsed = { ...this.state.lastUsed, [id]: this.now() };
549
+ this.save();
550
+ }
551
+ }
552
+ async wanted() {
553
+ const needs = await this.allNeeds();
554
+ const out = new Map;
555
+ for (const [id, model] of Object.entries(await this.deps.store.on() ?? {})) {
556
+ if (needs[id]) {
557
+ out.set(id, this.modelOf(needs[id], model));
558
+ }
559
+ }
560
+ return out;
561
+ }
562
+ pump() {
563
+ if (this.job) {
564
+ return;
565
+ }
566
+ const abort = new AbortController;
567
+ const done = (async () => {
568
+ for (let attempt = 0;!abort.signal.aborted; attempt++) {
569
+ let failed = false;
570
+ for (const [id, model] of await this.wanted()) {
571
+ if (abort.signal.aborted) {
572
+ return;
573
+ }
574
+ this.errors.delete(id);
575
+ try {
576
+ await this.download(model, abort.signal);
577
+ } catch (failure) {
578
+ if (abort.signal.aborted) {
579
+ return;
580
+ }
581
+ const error = LocalChecks.errorOf(failure);
582
+ this.errors.set(id, error);
583
+ failed ||= error.code !== "disk" && error.code !== "unsupported" && error.code !== "system";
584
+ }
585
+ }
586
+ if (!failed) {
587
+ return;
588
+ }
589
+ await LocalSystem.sleep(RETRY_MS[Math.min(attempt, RETRY_MS.length - 1)], abort.signal);
590
+ }
591
+ })().finally(() => {
592
+ if (this.job?.abort === abort) {
593
+ this.job = undefined;
594
+ }
595
+ });
596
+ this.job = { abort, done };
597
+ }
598
+ async restart() {
599
+ const job = this.job;
600
+ job?.abort.abort();
601
+ await job?.done;
602
+ const keep = new Set([...(await this.wanted()).values()].map((model) => this.serverKey(model)));
603
+ for (const server of [...this.servers.values()]) {
604
+ if (!keep.has(server.key)) {
605
+ await this.stop(server);
606
+ }
607
+ }
608
+ }
609
+ async download(model, signal) {
610
+ const build = LocalRuntimes.build(model.runtime, this.deps.platform, this.deps.arch);
611
+ if (!build) {
612
+ throw Object.assign(new Error("unsupported"), { code: "unsupported" });
613
+ }
614
+ const runtimeDir = this.runtimeDir(model.runtime);
615
+ const modelPath = this.modelPath(model);
616
+ const hasProgram = await this.program(model.runtime) !== undefined;
617
+ const hasModel = await LocalSystem.exists(modelPath);
618
+ if (hasProgram && hasModel) {
619
+ return;
620
+ }
621
+ const needed = (hasProgram ? 0 : build.bytes * 3) + (hasModel ? 0 : model.bytes);
622
+ const free = await (this.deps.free ?? LocalSystem.free)(this.deps.dir);
623
+ if (free !== undefined && free < needed + DISK_SPARE) {
624
+ throw Object.assign(new Error(`${needed} bytes are needed, ${free} free`), { code: "disk", needed, free });
625
+ }
626
+ await mkdir2(join2(this.deps.dir, "models"), { recursive: true });
627
+ if (!hasProgram) {
628
+ const archive = join2(this.deps.dir, build.file);
629
+ await this.fetch.get({
630
+ urls: build.urls,
631
+ to: archive,
632
+ sha256: build.sha256,
633
+ signal,
634
+ progress: (done, total) => this.got.set(build.file, { done, total: total || build.bytes })
635
+ });
636
+ await rm2(runtimeDir, { recursive: true, force: true });
637
+ await mkdir2(runtimeDir, { recursive: true });
638
+ await (this.deps.extract ?? LocalSystem.extract)(archive, runtimeDir);
639
+ await rm2(archive, { force: true });
640
+ this.got.delete(build.file);
641
+ const unpacked = await this.program(model.runtime);
642
+ if (!unpacked) {
643
+ throw Object.assign(new Error(`${build.file} has no ${LOCAL_RUNTIMES[model.runtime].program(this.deps.platform)}`), { code: "check" });
644
+ }
645
+ const why = await (this.deps.probe ?? LocalSystem.probe)(unpacked, this.envOf(unpacked));
646
+ if (why) {
647
+ await rm2(runtimeDir, { recursive: true, force: true });
648
+ throw Object.assign(new Error(why), { code: "system" });
649
+ }
650
+ }
651
+ if (!hasModel) {
652
+ await this.fetch.get({
653
+ urls: model.urls,
654
+ to: modelPath,
655
+ sha256: model.sha256,
656
+ signal,
657
+ progress: (done, total) => this.got.set(model.file, { done, total: total || model.bytes })
658
+ });
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;
670
+ }
671
+ return { done, total: Math.max(total, model.bytes) };
672
+ }
673
+ 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
+ }
699
+ }
700
+ runtimeDir(runtime) {
701
+ return join2(this.deps.dir, "runtimes", runtime, LOCAL_RUNTIMES[runtime].version);
702
+ }
703
+ modelPath(model) {
704
+ return join2(this.deps.dir, "models", model.file);
705
+ }
706
+ async ready(model) {
707
+ return await LocalSystem.exists(this.modelPath(model)) && await this.program(model.runtime) !== undefined;
708
+ }
709
+ program(runtime) {
710
+ return LocalSystem.find(this.runtimeDir(runtime), LOCAL_RUNTIMES[runtime].program(this.deps.platform));
711
+ }
712
+ start(model) {
713
+ const key = this.serverKey(model);
714
+ const runtime = LOCAL_RUNTIMES[model.runtime];
715
+ const get = this.deps.get ?? LocalSystem.get;
716
+ const server = { key, ready: Promise.resolve("") };
717
+ server.ready = (async () => {
718
+ const path = this.modelPath(model);
719
+ const before = this.state.servers?.[key];
720
+ if (before && await runtime.serves((at) => get(`http://127.0.0.1:${before.port}${at}`), path)) {
721
+ server.pid = before.pid;
722
+ server.url = `http://127.0.0.1:${before.port}`;
723
+ return server.url;
724
+ }
725
+ const program = await this.program(model.runtime);
726
+ if (!program) {
727
+ throw new Error(`${model.runtime} is not downloaded.`);
728
+ }
729
+ const port = await LocalSystem.freePort();
730
+ const cwd = dirname2(program);
731
+ const env = this.envOf(program);
732
+ const child = (this.deps.run ?? LocalSystem.run)(program, runtime.args(path, port, model.args ?? []), { cwd, env });
733
+ server.child = child;
734
+ server.pid = child.pid;
735
+ server.url = `http://127.0.0.1:${port}`;
736
+ let exited = false;
737
+ child.once("exit", () => {
738
+ exited = true;
739
+ if (this.servers.get(key) === server) {
740
+ this.servers.delete(key);
741
+ clearTimeout(server.idle);
742
+ if (this.state.servers) {
743
+ delete this.state.servers[key];
744
+ }
745
+ this.save();
746
+ }
747
+ });
748
+ const started = this.now();
749
+ while (!await runtime.serves((at) => get(`${server.url}${at}`), path)) {
750
+ if (exited || this.now() - started > START_MS) {
751
+ child.kill();
752
+ throw Object.assign(new Error(`${model.label} did not start.`), { code: "start" });
753
+ }
754
+ await LocalSystem.sleep(250);
755
+ }
756
+ this.tune(key);
757
+ this.state.servers = { ...this.state.servers, [key]: { pid: child.pid ?? 0, port } };
758
+ await this.save();
759
+ return server.url;
760
+ })();
761
+ server.ready.catch(() => {
762
+ if (this.servers.get(key) === server) {
763
+ this.servers.delete(key);
764
+ }
765
+ });
766
+ return server;
767
+ }
768
+ 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(":") } : {} };
771
+ }
772
+ keepUp(server) {
773
+ clearTimeout(server.idle);
774
+ server.idle = setTimeout(() => void this.stop(server, true), this.state.idle?.[server.key]?.ms ?? IDLE_START_MS);
775
+ server.idle.unref?.();
776
+ }
777
+ tune(key) {
778
+ const idle = this.state.idle?.[key] ?? { ms: IDLE_START_MS };
779
+ const since = idle.stoppedAt === undefined ? undefined : this.now() - idle.stoppedAt;
780
+ let ms = idle.ms;
781
+ if (since !== undefined && since < idle.ms) {
782
+ ms = Math.min(IDLE_MAX_MS, idle.ms * 2);
783
+ } else if (since !== undefined && since > idle.ms * 12) {
784
+ ms = Math.max(IDLE_MIN_MS, Math.round(idle.ms * 0.75));
785
+ }
786
+ this.state.idle = { ...this.state.idle, [key]: { ms } };
787
+ }
788
+ async stop(server, idle = false) {
789
+ clearTimeout(server.idle);
790
+ if (this.servers.get(server.key) === server) {
791
+ this.servers.delete(server.key);
792
+ }
793
+ await server.ready.catch(() => {
794
+ return;
795
+ });
796
+ if (server.child) {
797
+ server.child.kill();
798
+ } else if (server.pid) {
799
+ try {
800
+ process.kill(server.pid);
801
+ } catch {}
802
+ }
803
+ if (this.state.servers) {
804
+ delete this.state.servers[server.key];
805
+ }
806
+ if (idle) {
807
+ this.state.idle = { ...this.state.idle, [server.key]: { ms: this.state.idle?.[server.key]?.ms ?? IDLE_START_MS, stoppedAt: this.now() } };
808
+ }
809
+ await this.save();
810
+ }
811
+ load() {
812
+ this.loaded ??= readFile(join2(this.deps.dir, "state.json"), "utf8").then((text) => {
813
+ this.state = JSON.parse(text);
814
+ }, () => {
815
+ return;
816
+ });
817
+ return this.loaded;
818
+ }
819
+ async save() {
820
+ await mkdir2(this.deps.dir, { recursive: true }).catch(() => {
821
+ return;
822
+ });
823
+ await writeFile(join2(this.deps.dir, "state.json"), JSON.stringify(this.state)).catch(() => {
824
+ return;
825
+ });
826
+ }
827
+ }
828
+
829
+ // web-src/host.ts
830
+ var NAME = "@celljs/ta-local-models";
831
+ var KEEP_DAYS = 90;
832
+ function activate(host) {
833
+ const models = new LocalModels({
834
+ dir: join3(host.agentDir, "local-models"),
835
+ platform: process.platform,
836
+ arch: process.arch,
837
+ memory: totalmem(),
838
+ store: {
839
+ needs: async () => await host.getExtensionData(NAME, "needs").catch(() => {
840
+ return;
841
+ }),
842
+ saveNeeds: (needs) => host.setExtensionData(NAME, "needs", needs),
843
+ on: async () => await host.getExtensionData(NAME, "on").catch(() => {
844
+ return;
845
+ }),
846
+ saveOn: (on) => host.setExtensionData(NAME, "on", on)
847
+ }
848
+ });
849
+ models.resume();
850
+ host.storage?.register({
851
+ name: "models",
852
+ title: { "zh-CN": "本机模型", "zh-TW": "本機模型", "en-US": "Local models", "ja-JP": "ローカルモデル" },
853
+ hint: {
854
+ "zh-CN": "在这台电脑上运行的模型和运行它们的程序;清除后对应功能关闭,要用时再下载。",
855
+ "zh-TW": "在這台電腦上執行的模型和執行它們的程式;清除後對應功能關閉,要用時再下載。",
856
+ "en-US": "Models that run on this computer, and what runs them; once cleared, what uses them is off till they are downloaded again.",
857
+ "ja-JP": "このコンピューターで動くモデルとその実行プログラム。消すと使う機能はオフになり、使うときにまたダウンロードします。"
858
+ },
859
+ defaults: { keepDays: KEEP_DAYS },
860
+ order: 40
861
+ }, {
862
+ usage: () => models.usage(),
863
+ prune: (limits) => models.prune(limits),
864
+ clear: () => models.clear()
865
+ });
866
+ return {
867
+ need: (need) => models.need(need),
868
+ needStatus: (id) => models.needStatus(String(id)),
869
+ url: (id) => models.url(String(id)),
870
+ touch: (id) => models.touch(String(id)),
871
+ status: () => models.status(),
872
+ enable: (id, model) => models.enable(String(id), model === undefined ? undefined : String(model)),
873
+ disable: (id) => models.disable(String(id)),
874
+ dispose: () => models.dispose()
875
+ };
876
+ }
877
+ export {
878
+ activate as default
879
+ };
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@celljs/ta-local-models",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.36.0",
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
+ "keywords": [
6
+ "pi-package"
7
+ ],
8
+ "homepage": "https://github.com/cellbang/ta",
9
+ "bugs": {
10
+ "url": "https://github.com/cellbang/ta/issues"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/cellbang/cell.git"
15
+ },
16
+ "license": "MIT",
17
+ "files": [
18
+ "web",
19
+ "host",
20
+ "!**/*.map"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -b && bun build web-src/index.tsx --format esm --target browser --outfile web/index.js && bun build web-src/host.ts --format esm --target node --outfile host/index.mjs",
24
+ "clean": "rm -rf lib web host *.tsbuildinfo",
25
+ "test": "bun test ./lib",
26
+ "watch": "tsc -b -w --preserveWatchOutput"
27
+ },
28
+ "devDependencies": {
29
+ "@celljs/ta-protocol": "4.36.0",
30
+ "@celljs/ta-web": "4.36.0",
31
+ "@types/react": "^19.3.0"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "pi": {
37
+ "title": {
38
+ "en": "Local models",
39
+ "zh-CN": "本机模型",
40
+ "zh-TW": "本機模型",
41
+ "ja-JP": "ローカルモデル"
42
+ },
43
+ "summary": {
44
+ "en": "Models that run on this computer for what other features need (the decision model of live hands): downloaded only once you turn one on, stopped when unused, cleared in Settings → Storage.",
45
+ "zh-CN": "在这台电脑上运行其他功能要用的模型(如实时操作的决策模型):打开某项后才下载,不用时自动停下,可在设置 → 存储空间里清除。",
46
+ "zh-TW": "在這台電腦上執行其他功能要用的模型(如即時操作的決策模型):開啟某項後才下載,不用時自動停下,可在設定 → 儲存空間裡清除。",
47
+ "ja-JP": "ほかの機能が使うモデル(リアルタイム操作の判断モデルなど)をこのコンピューターで動かします。オンにしたときだけダウンロードし、使わないと止まり、設定 → ストレージで消せます。"
48
+ },
49
+ "icon": "Cpu",
50
+ "web": [
51
+ "./web/index.js"
52
+ ],
53
+ "host": "./host/index.mjs",
54
+ "permissions": {
55
+ "host": {
56
+ "status": "models.use",
57
+ "needStatus": "models.use",
58
+ "*": "settings.manage"
59
+ }
60
+ }
61
+ }
62
+ }
package/web/index.js ADDED
@@ -0,0 +1,326 @@
1
+ // ../ta-protocol/esm/common/language.js
2
+ var TaLanguageUtil;
3
+ (function(TaLanguageUtil2) {
4
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
5
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
6
+ function of(tag) {
7
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
8
+ if (/^zh(\b|-)/.test(said)) {
9
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
10
+ }
11
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
12
+ }
13
+ TaLanguageUtil2.of = of;
14
+ function server(env = typeof process === "undefined" ? {} : process.env) {
15
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
16
+ }
17
+ TaLanguageUtil2.server = server;
18
+ function pick(language, words) {
19
+ return words[of(language)];
20
+ }
21
+ TaLanguageUtil2.pick = pick;
22
+ function say(words) {
23
+ return words[server()];
24
+ }
25
+ TaLanguageUtil2.say = say;
26
+ function chinese(language) {
27
+ return of(language).startsWith("zh");
28
+ }
29
+ TaLanguageUtil2.chinese = chinese;
30
+ function cjk(language) {
31
+ return of(language) !== "en-US";
32
+ }
33
+ TaLanguageUtil2.cjk = cjk;
34
+ function list(language, items) {
35
+ return items.join(cjk(language) ? "、" : ", ");
36
+ }
37
+ TaLanguageUtil2.list = list;
38
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
39
+
40
+ // web-src/i18n.ts
41
+ var EN = {
42
+ section: "Local models",
43
+ none: "Nothing uses a model of this computer yet.",
44
+ off: "Off · turn it on to download {size}",
45
+ getting: "Downloading {percent}% · {done} of {total}",
46
+ ready: "Ready · {size}",
47
+ running: "Ready · {size} · running",
48
+ recommended: "for this computer",
49
+ retry: "Try again",
50
+ unsupported: "Not available on this computer",
51
+ errorDisk: "Not enough room on the disk: {needed} needed, {free} free",
52
+ errorNetwork: "The download stopped; it goes on by itself once the network is back",
53
+ errorCheck: "The download did not check out; it is downloaded again",
54
+ errorStart: "It did not start; it is tried again the next time it is needed",
55
+ errorSystem: "This system cannot run it (lacks {what}): install it, or use Ollama or LM Studio instead",
56
+ total: "Takes {size} in all. Not used for 90 days, a model goes by itself (Settings → Storage).",
57
+ runs: "Uses about {mb} of memory while it runs"
58
+ };
59
+ var WORDS = {
60
+ "en-US": EN,
61
+ "zh-CN": {
62
+ section: "本机模型",
63
+ none: "还没有功能要用本机模型。",
64
+ off: "未开启 · 打开后下载 {size}",
65
+ getting: "下载中 {percent}% · {done} / {total}",
66
+ ready: "已就绪 · {size}",
67
+ running: "已就绪 · {size} · 正在运行",
68
+ recommended: "适合这台电脑",
69
+ retry: "重试",
70
+ unsupported: "这台电脑用不了",
71
+ errorDisk: "磁盘空间不够:需要 {needed},只剩 {free}",
72
+ errorNetwork: "下载中断了,网络恢复后会自动接着下",
73
+ errorCheck: "下载的文件校验没通过,会重新下载",
74
+ errorStart: "没能启动,下次用到时会再试",
75
+ errorSystem: "这台电脑的系统跑不了它(缺 {what}):装上后重试,或改用 Ollama、LM Studio",
76
+ total: "共占用 {size}。模型 90 天没用会自动清理(设置 → 存储空间)。",
77
+ runs: "运行时约占 {mb} 内存"
78
+ },
79
+ "zh-TW": {
80
+ section: "本機模型",
81
+ none: "還沒有功能要用本機模型。",
82
+ off: "未開啟 · 開啟後下載 {size}",
83
+ getting: "下載中 {percent}% · {done} / {total}",
84
+ ready: "已就緒 · {size}",
85
+ running: "已就緒 · {size} · 正在執行",
86
+ recommended: "適合這台電腦",
87
+ retry: "重試",
88
+ unsupported: "這台電腦用不了",
89
+ errorDisk: "磁碟空間不夠:需要 {needed},只剩 {free}",
90
+ errorNetwork: "下載中斷了,網路恢復後會自動接著下",
91
+ errorCheck: "下載的檔案驗證沒通過,會重新下載",
92
+ errorStart: "沒能啟動,下次用到時會再試",
93
+ errorSystem: "這台電腦的系統跑不了它(缺 {what}):裝上後重試,或改用 Ollama、LM Studio",
94
+ total: "共佔用 {size}。模型 90 天沒用會自動清理(設定 → 儲存空間)。",
95
+ runs: "執行時約佔 {mb} 記憶體"
96
+ },
97
+ "ja-JP": {
98
+ section: "ローカルモデル",
99
+ none: "このコンピューターのモデルを使う機能はまだありません。",
100
+ off: "オフ · オンにすると {size} をダウンロード",
101
+ getting: "ダウンロード中 {percent}% · {done} / {total}",
102
+ ready: "準備完了 · {size}",
103
+ running: "準備完了 · {size} · 実行中",
104
+ recommended: "このコンピューター向け",
105
+ retry: "再試行",
106
+ unsupported: "このコンピューターでは使えません",
107
+ errorDisk: "ディスクの空きが足りません:{needed} 必要、空き {free}",
108
+ errorNetwork: "ダウンロードが止まりました。ネットワークが戻ると自動で続きます",
109
+ errorCheck: "ダウンロードしたファイルの検証に失敗しました。もう一度ダウンロードします",
110
+ errorStart: "起動できませんでした。次に使うときにまた試します",
111
+ errorSystem: "このシステムでは動きません({what} がありません)。入れてから再試行するか、Ollama や LM Studio を使えます",
112
+ total: "合計 {size}。90 日使わないモデルは自動で消えます(設定 → ストレージ)。",
113
+ runs: "実行中は約 {mb} のメモリを使います"
114
+ }
115
+ };
116
+ var LocalWords;
117
+ ((LocalWords) => {
118
+ function of(language) {
119
+ return TaLanguageUtil.pick(language, WORDS);
120
+ }
121
+ LocalWords.of = of;
122
+ function fill(text, values) {
123
+ return text.replace(/\{(\w+)\}/g, (all, key) => (key in values) ? String(values[key]) : all);
124
+ }
125
+ LocalWords.fill = fill;
126
+ function size(bytes) {
127
+ return bytes >= 1e9 ? `${(bytes / 1e9).toFixed(1)} GB` : `${Math.max(1, Math.round(bytes / 1e6))} MB`;
128
+ }
129
+ LocalWords.size = size;
130
+ })(LocalWords ||= {});
131
+
132
+ // web-src/react.ts
133
+ var React;
134
+ function bind(react) {
135
+ React = react;
136
+ }
137
+
138
+ // web-src/style.ts
139
+ var STYLE = `
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; }
142
+ .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-hint, .ta-local-note { margin: 0; color: var(--ta-secondary); font-size: calc(13px * var(--ta-font-scale)); line-height: 1.5; }
145
+ .ta-local-models button { display: flex; flex-direction: column; align-items: center; gap: 1px; height: auto; min-height: 40px; padding: 4px 8px; }
146
+ .ta-local-model { font-weight: 500; }
147
+ .ta-local-size { font-size: calc(11px * var(--ta-font-scale)); color: var(--ta-secondary); }
148
+ .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
+ .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; }
154
+ @keyframes ta-local-blink { 50% { opacity: 0.35; } }
155
+ `;
156
+ function injectStyle() {
157
+ const element = document.createElement("style");
158
+ element.dataset.taPackage = "ta-local-models";
159
+ element.textContent = STYLE;
160
+ document.head.appendChild(element);
161
+ return () => element.remove();
162
+ }
163
+
164
+ // web-src/index.tsx
165
+ var POLL_MS = 5000;
166
+ var POLL_GETTING_MS = 1000;
167
+ function activate(pi) {
168
+ bind(pi.React);
169
+ const removeStyle = injectStyle();
170
+ pi.registerSettings({
171
+ title: () => LocalWords.of(pi.ui.language).section,
172
+ icon: pi.ui.icons.Cpu ?? pi.ui.icons.Sparkles,
173
+ group: "ta",
174
+ order: 60,
175
+ rows: [{ key: "needs", label: "", stacked: true, render: () => /* @__PURE__ */ React.createElement(Needs, {
176
+ pi
177
+ }) }]
178
+ });
179
+ return removeStyle;
180
+ }
181
+ function useStatus(pi) {
182
+ const [status, setStatus] = React.useState();
183
+ const live = React.useRef(true);
184
+ const read = React.useCallback(() => pi.callHost("status").then((next) => {
185
+ if (live.current) {
186
+ setStatus(next);
187
+ }
188
+ }, () => {
189
+ return;
190
+ }), [pi]);
191
+ const getting = status?.needs.some((need) => need.state === "getting") ?? false;
192
+ React.useEffect(() => {
193
+ live.current = true;
194
+ read();
195
+ const timer = setInterval(read, getting ? POLL_GETTING_MS : POLL_MS);
196
+ return () => {
197
+ live.current = false;
198
+ clearInterval(timer);
199
+ };
200
+ }, [read, getting]);
201
+ return [status, read];
202
+ }
203
+ function Needs({ pi }) {
204
+ const words = LocalWords.of(pi.ui.language);
205
+ const [status, read] = useStatus(pi);
206
+ if (!status) {
207
+ return null;
208
+ }
209
+ if (!status.needs.length) {
210
+ return /* @__PURE__ */ React.createElement("p", {
211
+ className: "ta-local-note"
212
+ }, words.none);
213
+ }
214
+ return /* @__PURE__ */ React.createElement("div", {
215
+ className: "ta-local"
216
+ }, status.needs.map((need) => /* @__PURE__ */ React.createElement(Need, {
217
+ key: need.need.id,
218
+ pi,
219
+ status: need,
220
+ read,
221
+ words
222
+ })), status.bytes > 0 && /* @__PURE__ */ React.createElement("p", {
223
+ className: "ta-local-note"
224
+ }, LocalWords.fill(words.total, { size: LocalWords.size(status.bytes) })));
225
+ }
226
+ function Need({ pi, status, read, words }) {
227
+ const language = pi.ui.language;
228
+ const [busy, run] = (pi.ui.useBusy ?? useFallbackBusy)();
229
+ const [chosen, setChosen] = React.useState(status.model);
230
+ const picked = status.on ? status.model : chosen;
231
+ const model = status.need.models.find((one) => one.id === picked) ?? status.need.models[0];
232
+ const act = (method, ...params) => run(() => pi.callHost(method, status.need.id, ...params).then(read, (error) => {
233
+ pi.ui.notify(String(error?.message ?? error), "error");
234
+ }));
235
+ const Switch = pi.ui.Switch;
236
+ return /* @__PURE__ */ React.createElement("section", {
237
+ className: "ta-local-need"
238
+ }, /* @__PURE__ */ React.createElement("div", {
239
+ className: "ta-local-head"
240
+ }, /* @__PURE__ */ React.createElement("div", {
241
+ className: "ta-local-title"
242
+ }, status.need.title[language] ?? status.need.title["en-US"]), /* @__PURE__ */ React.createElement(Switch, {
243
+ checked: status.on,
244
+ disabled: !status.supported || busy,
245
+ label: status.need.title[language] ?? status.need.title["en-US"],
246
+ onChange: (on) => on ? act("enable", picked) : act("disable")
247
+ })), /* @__PURE__ */ React.createElement("p", {
248
+ className: "ta-local-hint"
249
+ }, status.need.hint[language] ?? status.need.hint["en-US"]), status.need.models.length > 1 && status.supported && /* @__PURE__ */ React.createElement("fieldset", {
250
+ className: "ta-segmented ta-local-models",
251
+ "aria-label": status.need.title[language],
252
+ disabled: busy
253
+ }, status.need.models.map((one) => /* @__PURE__ */ React.createElement("button", {
254
+ key: one.id,
255
+ type: "button",
256
+ "aria-pressed": one.id === picked,
257
+ className: one.id === picked ? "ta-on" : "",
258
+ onClick: () => one.id === picked ? undefined : status.on ? act("enable", one.id) : setChosen(one.id)
259
+ }, /* @__PURE__ */ React.createElement("span", {
260
+ className: "ta-local-model"
261
+ }, one.label), /* @__PURE__ */ React.createElement("span", {
262
+ className: "ta-local-size"
263
+ }, LocalWords.size(one.bytes), one.id === status.recommended ? ` · ${words.recommended}` : "")))), /* @__PURE__ */ React.createElement("p", {
264
+ className: `ta-local-state${status.state === "failed" ? " ta-local-failed" : ""}`
265
+ }, /* @__PURE__ */ React.createElement("span", {
266
+ className: `ta-local-dot ta-local-${status.state}`,
267
+ "aria-hidden": "true"
268
+ }), stateText(status, model, words), status.state === "failed" && status.error?.code !== "unsupported" && /* @__PURE__ */ React.createElement("button", {
269
+ type: "button",
270
+ className: "ta-local-retry",
271
+ onClick: () => act("enable", status.model)
272
+ }, words.retry)));
273
+ }
274
+ function stateText(status, model, words) {
275
+ if (!status.supported) {
276
+ return words.unsupported;
277
+ }
278
+ const size = LocalWords.size(model.bytes);
279
+ const memory = model.runMB ? ` · ${LocalWords.fill(words.runs, { mb: LocalWords.size(model.runMB * 1e6) })}` : "";
280
+ switch (status.state) {
281
+ case "off":
282
+ return LocalWords.fill(words.off, { size }) + memory;
283
+ case "getting": {
284
+ const total = status.total || model.bytes;
285
+ const done = status.done ?? 0;
286
+ return LocalWords.fill(words.getting, { percent: Math.floor(done / total * 100), done: LocalWords.size(done), total: LocalWords.size(total) });
287
+ }
288
+ case "ready":
289
+ return LocalWords.fill(status.running ? words.running : words.ready, { size }) + memory;
290
+ case "failed":
291
+ return errorText(status.error, words);
292
+ }
293
+ }
294
+ function errorText(error, words) {
295
+ switch (error?.code) {
296
+ case "disk":
297
+ return LocalWords.fill(words.errorDisk, { needed: LocalWords.size(error.needed), free: LocalWords.size(error.free) });
298
+ case "check":
299
+ return words.errorCheck;
300
+ case "start":
301
+ return words.errorStart;
302
+ case "system":
303
+ return LocalWords.fill(words.errorSystem, { what: error.detail ?? "" });
304
+ case "unsupported":
305
+ return words.unsupported;
306
+ default:
307
+ return words.errorNetwork;
308
+ }
309
+ }
310
+ function useFallbackBusy() {
311
+ const [busy, setBusy] = React.useState(false);
312
+ return [
313
+ busy,
314
+ async (action) => {
315
+ setBusy(true);
316
+ try {
317
+ return await action();
318
+ } finally {
319
+ setBusy(false);
320
+ }
321
+ }
322
+ ];
323
+ }
324
+ export {
325
+ activate as default
326
+ };