@hackbuild/ai-views 0.1.1 → 0.1.5

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.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Put a model picker, a chat, a transcriber, a mask studio or a camera frame on your page, drawn with the hackbuild-ui stylesheet, as custom elements or Vue components.
4
4
 
5
- [![npm](https://img.shields.io/npm/v/@hackbuild/ai-views)](https://www.npmjs.com/package/@hackbuild/ai-views) [![licence MIT](https://img.shields.io/badge/licence-MIT-blue)](../../LICENSE) ![gzip 12.4 kB measured](https://img.shields.io/badge/gzip-12.4%20kB-blue) ![types included](https://img.shields.io/badge/types-included-blue)
5
+ [![npm](https://img.shields.io/npm/v/@hackbuild/ai-views)](https://www.npmjs.com/package/@hackbuild/ai-views) [![licence MIT](https://img.shields.io/badge/licence-MIT-blue)](../../LICENSE) ![gzip 21.5 kB measured](https://img.shields.io/badge/gzip-21.5%20kB-blue) ![types included](https://img.shields.io/badge/types-included-blue)
6
6
 
7
7
  Browser status: no model run of this package has been verified in a real browser yet.
8
8
 
@@ -91,7 +91,25 @@ const thread = chatThread({ engine });
91
91
 
92
92
  ### picks and loaders
93
93
 
94
- A pick loads only through its loader (none is an error the row shows), runs it for every row, a no download row included, and keeps its result on `snapshot().loaded`; `remove()` deletes through `onRemove`. It starts on the first "start here" record that fits, else the first fast or steady one. `weightsLoader(store)` fetches a record's files through @hackbuild/weights; a record that loads through its runtime (WebLLM, MediaPipe and the like) needs a loader from the page. `useJobsPick` joins pickers as a rack with a line per job, presets with their download totals, and load all.
94
+ A pick loads only through its loader (none is an error the row shows), runs it for every row, a no download row included, and keeps its result on `snapshot().loaded`; `remove()` deletes through `onRemove`. It starts on the first "start here" record that fits, else the first fast or steady one. `weightsLoader(store)` fetches a record's files through @hackbuild/weights; a record that loads through its runtime (WebLLM, MediaPipe and the like) takes `jobLoader(job)`. `useJobsPick` joins pickers as a rack with a line per job, presets with their download totals, and load all.
95
+
96
+ ### real loads
97
+
98
+ `jobLoader(job, { store?, env?, allowGplPhonemizer? })` is the loader a page passes to `useModelPick(job, { loader })`. A load imports the runtime from its pinned CDN only when the person presses load, fetches weights through @hackbuild/weights where the runtime does not fetch its own, sends progress to the row, stops on the row's stop, and fails in plain words. One models hub serves every loader made with the same options object. Probe the machine with `probe()` from @hackbuild/ai-env and pass it to the pick as `env`.
99
+
100
+ | job | resolves to | runtimes |
101
+ |---|---|---|
102
+ | chat | a @hackbuild/chat `ChatEngine` | WebLLM, wllama (gguf through the weight store), transformers.js, the browser's built in model |
103
+ | transcribe | a `Transcriber` for TranscribeDrop | whisper on transformers.js, the dsp core inlined |
104
+ | detect | `(image) => FrameBox[]` | MediaPipe EfficientDet, YOLO on onnxruntime web |
105
+ | masks | `MaskModels`: click segment, and segment everything from a 4 by 3 grid of points | SlimSAM on transformers.js; FastSAM is refused until it has a decoder |
106
+ | depth | `(image) => { width, height, data }`, 0 to 1, larger is nearer | Depth Anything on transformers.js |
107
+ | vision | `(image, question?) => string`, a caption without a question | SmolVLM, LFM2-VL, Gemma on transformers.js |
108
+ | image | an imagegen `ImageGenerator` with its CLIP `tokenize` and `make(form)` | onnxruntime web; the tokenizer on transformers.js |
109
+ | voice | a loaded @hackbuild/speak `Engine` | the system voice (no download), bellows, pocket tts, kokoro (gpl phonemizer, opt in) |
110
+ | embed | an @hackbuild/embed `Embedder` | static potion files, transformers.js |
111
+
112
+ The bar chip shows the name cut short (`shortName`: "hermes 3 llama 3.2 3b" reads "hermes 3 3b") and the size, then the state once a load moves; the full name is its label.
95
113
 
96
114
  ### views
97
115
 
@@ -115,6 +133,7 @@ Jobs and their records: chat (the chat rows of the @hackbuild/models catalogue),
115
133
  | [`useModelPick`](../../docs/api/ai-views/index.md#usemodelpick) | a model picker for one job |
116
134
  | [`useJobsPick`](../../docs/api/ai-views/index.md#usejobspick) | pickers for several jobs as one rack |
117
135
  | [`weightsLoader`](../../docs/api/ai-views/index.md#weightsloader) | a loader that fetches files through a weight store |
136
+ | [`jobLoader`](../../docs/api/ai-views/index.md#jobloader) | the real loader of a job: runtime and weights at load time |
118
137
  | [`chatThread`](../../docs/api/ai-views/index.md#chatthread) | a chat thread over an engine |
119
138
  | [`chatList`](../../docs/api/ai-views/index.md#chatlist) | several chats, one open |
120
139
  | [`transcribeQueue`](../../docs/api/ai-views/index.md#transcribequeue) | a queue of files to transcribe, with edits and exports |
@@ -223,10 +242,11 @@ Changes are in the repository [CHANGELOG](../../CHANGELOG.md). Code is MIT ([LIC
223
242
  |---|---|---|
224
243
  | 2026-11-25 | `npx vitest run packages/ai-views` | pass: every job has the records above with a speed word and a verdict; rows carry size, memory, backend, marks, detail and options, and a row that does not fit names why; a pick loads with progress, cancels and keeps a failure's words; presets total their download; the chat thread streams with the reasoning apart and memory used; the queue runs, edits with undo and exports; the frame mapping crops and mirrors; define registers every element |
225
244
  | 2026-11-25 | `node tools/smoke-views.mjs`, headless | pass: one smoke per demo page on stub providers with no weights |
245
+ | 2026-11-25 | `npx vitest run packages/ai-views/test/loaders.test.ts` | pass: jobLoader loads a transformers.js chat model and a depth model through fake runtime modules, a WebLLM model through a fake module, refuses kokoro without the opt in and FastSAM in plain words, stops on abort, imports nothing before a load, makes no network request; the chip cuts a name and shows its size |
226
246
 
227
247
  ### Not verified by anything
228
248
 
229
- - A real model through any view in this package (the demos use stubs).
249
+ - A real model through jobLoader or any view in this package: tests use fake runtime modules and the demos stubs; no weights were fetched. The transcribe, detect, masks, vision, image, voice and embed paths of jobLoader have no test of their own yet.
230
250
  - Touch drawing on a phone.
231
251
  - Screen readers.
232
252
 
@@ -234,8 +254,8 @@ Changes are in the repository [CHANGELOG](../../CHANGELOG.md). Code is MIT ([LIC
234
254
 
235
255
  | file | gzip (measured) | ceiling |
236
256
  |---|---|---|
237
- | `dist/index.js` (main entry, imports external) | 12,413 bytes | 13,033 bytes |
238
- | `dist/single/elements.iife.js` (single file build) | 86,649 bytes | 90,981 bytes |
257
+ | `dist/index.js` (main entry, imports external) | 21,494 bytes | 22,568 bytes |
258
+ | `dist/single/elements.iife.js` (single file build) | 100,092 bytes | 105,096 bytes |
239
259
 
240
260
  Measured 2026-11-25 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
241
261
  tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
package/dist/chat.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * with its reasoning kept apart for the think fold, the memory each reply
5
5
  * used, stop, regenerate, and a markdown export. Framework free.
6
6
  */
7
- import type { ChatEngine } from "@hackbuild/chat";
7
+ import type { ChatEngine, StreamOptions } from "@hackbuild/chat";
8
8
  /** A memory recalled for a reply, with its label and score. */
9
9
  export interface MemoryUsed {
10
10
  label: string;
@@ -40,7 +40,19 @@ export interface ThreadSnapshot {
40
40
  */
41
41
  export interface ThreadOptions {
42
42
  engine?: ChatEngine | null;
43
- system?: string;
43
+ /** The system prompt, or a function read at each reply (a persona that changes). */
44
+ system?: string | (() => string);
45
+ /**
46
+ * Builds the system prompt from the persona and the memory recalled for this reply, in place
47
+ * of the default join; a page fits both to a budget here (priority trimmed sections).
48
+ */
49
+ systemFor?: (mem: MemoryUsed[]) => string;
50
+ /** Sampling, schema and other reply options, read at each reply. */
51
+ stream?: () => Omit<StreamOptions, "signal">;
52
+ /** How many earlier turns go with each request; all when unset. */
53
+ history?: () => number;
54
+ /** Called when a reply ends with text, with the user's message: speak it, save a note. */
55
+ onReply?: (turn: Turn, said: string) => void;
44
56
  /** Memory for a message; its hits ride along in the system prompt and show under the reply. */
45
57
  recall?: (query: string) => Promise<MemoryUsed[]>;
46
58
  /** What a reply says with no engine. */
@@ -62,6 +74,8 @@ export interface ChatThread {
62
74
  setEngine(engine: ChatEngine | null): void;
63
75
  /** The thread as markdown, for an export. */
64
76
  markdown(title?: string): string;
77
+ /** Replace the turns (a restored or imported chat). */
78
+ load(turns: readonly Turn[]): void;
65
79
  }
66
80
  /** What a reply says when no chat engine is set. */
67
81
  export declare const NO_ENGINE = "this needs a model. pick one in the bar and load it.";
@@ -93,6 +107,25 @@ export interface ChatList {
93
107
  rename(id: string, title: string): void;
94
108
  remove(id: string): void;
95
109
  setEngine(engine: ChatEngine | null): void;
110
+ /** Every chat as plain data, for storage or an export. */
111
+ dump(): ChatListData;
112
+ /** Adds chats from `dump()` data (an import or a reload); `replace` drops the current ones first. */
113
+ restore(data: ChatListData, o?: {
114
+ replace?: boolean;
115
+ }): void;
116
+ }
117
+ /** A chat list as plain data: format, version, the open chat and each chat's title and turns. */
118
+ export interface ChatListData {
119
+ format: "hackbuild-chats";
120
+ version: 1;
121
+ current?: string;
122
+ chats: {
123
+ id: string;
124
+ title: string;
125
+ updated: number;
126
+ named?: boolean;
127
+ turns: Turn[];
128
+ }[];
96
129
  }
97
130
  /**
98
131
  * Creates a list of chat threads, newest first, with one open; its `thread` always speaks for the
package/dist/chat.js CHANGED
@@ -46,20 +46,27 @@ export function chatThread(o = {}) {
46
46
  mem = await o.recall(lastUser.text);
47
47
  if (mem.length)
48
48
  patch(live.id, { mem });
49
- const sys = [o.system, mem.length ? `things you remember:\n${mem.map((m) => `- ${m.label}`).join("\n")}` : ""].filter(Boolean).join("\n\n");
49
+ const base = typeof o.system === "function" ? o.system() : o.system;
50
+ const sys = o.systemFor ? o.systemFor(mem) : [base, mem.length ? `things you remember:\n${mem.map((m) => `- ${m.label}`).join("\n")}` : ""].filter(Boolean).join("\n\n");
51
+ const past = turns.filter((t) => t.id !== live.id && t.text);
52
+ const keep = o.history?.();
53
+ const sent = keep !== undefined && keep >= 0 ? past.slice(Math.max(0, past.length - 1 - keep)) : past;
50
54
  const history = [
51
55
  ...(sys ? [{ role: "system", content: sys }] : []),
52
- ...turns.filter((t) => t.id !== live.id && t.text).map((t) => ({ role: t.role, content: t.text })),
56
+ ...sent.map((t) => ({ role: t.role, content: t.text })),
53
57
  ];
54
58
  let text = "";
55
59
  let think = "";
56
- const it = engine.stream(history, { signal, ...(o.maxTokens ? { maxTokens: o.maxTokens } : {}) });
60
+ const it = engine.stream(history, { ...(o.maxTokens ? { maxTokens: o.maxTokens } : {}), ...o.stream?.(), signal });
57
61
  for (;;) {
58
62
  const step = await it.next();
59
63
  if (step.done) {
60
64
  const s = step.value?.stats;
61
65
  const stats = s ? statsText({ tokPerSec: s.tokensPerSecond, firstMs: s.firstTokenMs, tokens: s.tokens, source: s.tokensSource }) : "";
62
66
  patch(live.id, { done: true, ...(stats ? { stats } : {}) });
67
+ const fin = turns.find((t) => t.id === live.id);
68
+ if (fin?.text)
69
+ o.onReply?.(fin, lastUser?.text ?? "");
63
70
  break;
64
71
  }
65
72
  const ev = step.value;
@@ -122,6 +129,11 @@ export function chatThread(o = {}) {
122
129
  engine = e;
123
130
  emit();
124
131
  },
132
+ load(next) {
133
+ ac?.abort();
134
+ turns = next.map((t) => ({ ...t, id: ++seq, done: true }));
135
+ emit();
136
+ },
125
137
  markdown(title = "chat") {
126
138
  const lines = [`# ${title}`, ""];
127
139
  for (const t of turns)
@@ -181,6 +193,7 @@ export function chatList(o = {}) {
181
193
  clear: () => chats.get(current).t.clear(),
182
194
  setEngine: (e) => list.setEngine(e),
183
195
  markdown: (title) => chats.get(current).t.markdown(title ?? chats.get(current).title),
196
+ load: (t) => chats.get(current).t.load(t),
184
197
  },
185
198
  snapshot: snap,
186
199
  subscribe(fn) {
@@ -227,6 +240,37 @@ export function chatList(o = {}) {
227
240
  for (const c of chats.values())
228
241
  c.t.setEngine(e);
229
242
  },
243
+ dump() {
244
+ return {
245
+ format: "hackbuild-chats",
246
+ version: 1,
247
+ current,
248
+ chats: [...chats].map(([id, c]) => ({ id, title: c.title, updated: c.updated, named: c.named, turns: c.t.snapshot().turns.filter((t) => t.done).map((t) => ({ ...t })) })),
249
+ };
250
+ },
251
+ restore(data, ro = {}) {
252
+ if (data?.format !== "hackbuild-chats" || data.version !== 1 || !Array.isArray(data.chats))
253
+ throw new Error("not a hackbuild-chats version 1 file.");
254
+ const empty = [...chats.values()].every((c) => !c.t.snapshot().turns.length);
255
+ if (ro.replace || empty) {
256
+ for (const c of chats.values())
257
+ c.t.stop();
258
+ chats.clear();
259
+ }
260
+ let open = "";
261
+ for (const c of data.chats) {
262
+ const id = `chat-${++seq}`;
263
+ const t = chatThread({ ...o, engine });
264
+ t.load((c.turns ?? []).filter((x) => (x.role === "user" || x.role === "assistant") && typeof x.text === "string").map((x) => ({ ...x, think: x.think ?? "" })));
265
+ chats.set(id, { t, title: String(c.title || "chat"), updated: +c.updated || now(), named: !!c.named });
266
+ if (c.id === data.current)
267
+ open = id;
268
+ }
269
+ if (!chats.size)
270
+ return void list.create();
271
+ current = open || (chats.has(current) ? current : snap().items[0].id);
272
+ follow();
273
+ },
230
274
  };
231
275
  list.create();
232
276
  return list;
@@ -14,10 +14,12 @@
14
14
  import type { Env } from "@hackbuild/ai-env";
15
15
  import type { ModelRecord } from "@hackbuild/models";
16
16
  import { type Loader, type ModelPick } from "./pick.js";
17
- export { mountModelSelect, mountModelJobs, pickSheet, gateWords, type ModelSelectOptions } from "./mount-model.js";
17
+ export { mountModelSelect, mountModelJobs, pickSheet, gateWords, chipWords, shortName, type ModelSelectOptions } from "./mount-model.js";
18
18
  export { mountChatPane, mountComposer, mountChatList, mountContextMeter, turnHtml, type ChatPaneOptions, type ComposerOptions } from "./mount-chat.js";
19
+ export { mountExportMenu, isMedia, droppedFiles } from "./mount-transcribe.js";
20
+ export { mountMemoryPane, mountSourcesDrop, mountPersonaRack, mountVoiceRow, mountVoiceClone, mountSessionMenu, protect, isProtected, type MemoryLike, type MemoryPaneHandle, type MemoryPaneOptions, type SourcesDropOptions } from "./mount-talk.js";
19
21
  export { mountTranscribeDrop, mountTranscriptView, mountTranscribeQueue, mountTranscriptExports, transcriptHtml, type TranscribeDropOptions, type TranscribeDropHandle, type TranscriptViewOptions } from "./mount-transcribe.js";
20
- export { mountMaskStudio, mountMaskTools, mountMaskVerbs, mountMaskRack, type MaskStudio, type MaskModels, type MaskStudioOptions, type FoundMask, type StudioState, type StudioTool } from "./mount-mask.js";
22
+ export { mountMaskStudio, mountMaskTools, mountMaskVerbs, mountMaskRack, type MaskStudio, type MaskModels, type MaskStudioOptions, type FoundMask, type MaskEverythingOptions, type StudioState, type StudioTool, type StudioView } from "./mount-mask.js";
21
23
  export { mountFrameView, mountCameraFeed, type FrameView, type FrameViewOptions, type CameraFeed, type CameraFeedOptions } from "./mount-frame.js";
22
24
  export { mountMemoryInspector, type MemoryInspector } from "./memory.js";
23
25
  type Base = new () => HTMLElement;
package/dist/elements.js CHANGED
@@ -21,8 +21,10 @@ import { mountModelJobs, mountModelSelect } from "./mount-model.js";
21
21
  import { mountTranscribeDrop, mountTranscribeQueue, mountTranscriptExports, mountTranscriptView } from "./mount-transcribe.js";
22
22
  import { transcribeQueue } from "./transcribe.js";
23
23
  import { mountMemoryInspector } from "./memory.js";
24
- export { mountModelSelect, mountModelJobs, pickSheet, gateWords } from "./mount-model.js";
24
+ export { mountModelSelect, mountModelJobs, pickSheet, gateWords, chipWords, shortName } from "./mount-model.js";
25
25
  export { mountChatPane, mountComposer, mountChatList, mountContextMeter, turnHtml } from "./mount-chat.js";
26
+ export { mountExportMenu, isMedia, droppedFiles } from "./mount-transcribe.js";
27
+ export { mountMemoryPane, mountSourcesDrop, mountPersonaRack, mountVoiceRow, mountVoiceClone, mountSessionMenu, protect, isProtected } from "./mount-talk.js";
26
28
  export { mountTranscribeDrop, mountTranscriptView, mountTranscribeQueue, mountTranscriptExports, transcriptHtml } from "./mount-transcribe.js";
27
29
  export { mountMaskStudio, mountMaskTools, mountMaskVerbs, mountMaskRack } from "./mount-mask.js";
28
30
  export { mountFrameView, mountCameraFeed } from "./mount-frame.js";
package/dist/index.d.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  export { JOBS, JOB_NAMES, ALL_RECORDS, FACE_API_BASE, jobRecords, isJob, type Job, type JobDef } from "./jobs.js";
2
2
  export { rowOf, groupOf, backendOf, sizeWords, detailOf, optionsOf, isNoDownload, isUncensored, type RowContext } from "./rows.js";
3
- export { useModelPick, useJobsPick, weightsLoader, weightsRemover, weightKeys, defaultPick, ownRecord, type ModelPick, type PickOptions, type PickSnapshot, type Loader, type LoadContext, type JobsPick, type JobLine, type PickPreset, } from "./pick.js";
4
- export { chatThread, chatList, contextSegments, NO_ENGINE, type ChatList, type ChatListItem, type ChatListSnapshot, type ChatThread, type ThreadOptions, type ThreadSnapshot, type Turn, type MemoryUsed } from "./chat.js";
5
- export { transcribeQueue, type TranscribeQueue, type Transcriber, type RunResult, type RunContext, type Channel, type ExportKind, type QueueSnapshot } from "./transcribe.js";
3
+ export { useModelPick, useJobsPick, weightsLoader, weightsRemover, weightKeys, storedIds, verifyRepo, type RepoCheck, defaultPick, ownRecord, type ModelPick, type PickOptions, type PickSnapshot, type Loader, type LoadContext, type JobsPick, type JobLine, type PickPreset, } from "./pick.js";
4
+ export { chatThread, chatList, contextSegments, NO_ENGINE, type ChatList, type ChatListData, type ChatListItem, type ChatListSnapshot, type ChatThread, type ThreadOptions, type ThreadSnapshot, type Turn, type MemoryUsed } from "./chat.js";
5
+ export { transcribeQueue, type TranscribeQueue, type Transcriber, type RunResult, type RunContext, type TranscribeRunOptions, type Channel, type ExportKind, type QueueSnapshot } from "./transcribe.js";
6
6
  export { fitMap, toView, boxWords, frameTag, labelColour, type FrameBox, type FrameLandmarks, type FrameResults } from "./frame.js";
7
7
  export { traceRows, inspectorHtml, type TraceRow, type RecallLike } from "./memory.js";
8
+ export { jobLoader, asImage, RUNTIME_URLS, type JobLoaderOptions, type JobValues, type RuntimeModules, type DetectFn, type DepthFn, type AskFn, type ImageJob } from "./loaders.js";
9
+ export { speaker, canClone, type Speaker, type SpeakerOptions, type SpokenLine } from "./speaker.js";
10
+ export { personaRack, voiceRow, type Persona, type PersonaPresetX, type PersonaRack, type VoiceRow } from "./talk.js";
package/dist/index.js CHANGED
@@ -3,8 +3,11 @@
3
3
  // "@hackbuild/ai-views/elements"; the Vue components in "@hackbuild/ai-views/vue".
4
4
  export { JOBS, JOB_NAMES, ALL_RECORDS, FACE_API_BASE, jobRecords, isJob } from "./jobs.js";
5
5
  export { rowOf, groupOf, backendOf, sizeWords, detailOf, optionsOf, isNoDownload, isUncensored } from "./rows.js";
6
- export { useModelPick, useJobsPick, weightsLoader, weightsRemover, weightKeys, defaultPick, ownRecord, } from "./pick.js";
6
+ export { useModelPick, useJobsPick, weightsLoader, weightsRemover, weightKeys, storedIds, verifyRepo, defaultPick, ownRecord, } from "./pick.js";
7
7
  export { chatThread, chatList, contextSegments, NO_ENGINE } from "./chat.js";
8
8
  export { transcribeQueue } from "./transcribe.js";
9
9
  export { fitMap, toView, boxWords, frameTag, labelColour } from "./frame.js";
10
10
  export { traceRows, inspectorHtml } from "./memory.js";
11
+ export { jobLoader, asImage, RUNTIME_URLS } from "./loaders.js";
12
+ export { speaker, canClone } from "./speaker.js";
13
+ export { personaRack, voiceRow } from "./talk.js";
@@ -0,0 +1,100 @@
1
+ /**
2
+ * jobLoader: the real loader of a pick. Pass it to `useModelPick(job, {
3
+ * loader: jobLoader(job) })` and a load fetches the runtime (transformers.js,
4
+ * onnxruntime web, WebLLM, wllama, MediaPipe, a voice) from its pinned CDN
5
+ * only when the person presses load, fetches the weights through
6
+ * @hackbuild/weights where the runtime does not fetch its own, and resolves
7
+ * to the object a page uses for that job. Nothing loads at import.
8
+ *
9
+ * One models hub is shared by every jobLoader made with the same options
10
+ * object (or with none), so a model loaded for one view is reused by the next
11
+ * and webgpu work takes one gpu lock.
12
+ */
13
+ import { type Env } from "@hackbuild/ai-env";
14
+ import type { ChatEngine } from "@hackbuild/chat";
15
+ import type { Dsp } from "@hackbuild/audio-dsp";
16
+ import type { OrtModule, TjsModule } from "@hackbuild/devices";
17
+ import type { Embedder } from "@hackbuild/embed";
18
+ import type { ClipTokenize, FormOptions, ImageGenerator } from "@hackbuild/imagegen";
19
+ import type { Engine } from "@hackbuild/speak";
20
+ import type { WeightStore } from "@hackbuild/weights";
21
+ import { type Job } from "./jobs.js";
22
+ import type { FrameBox } from "./frame.js";
23
+ import type { MaskModels } from "./mount-mask.js";
24
+ import type { Loader } from "./pick.js";
25
+ import type { Transcriber } from "./transcribe.js";
26
+ /** Pinned CDN modules jobLoader imports at load time. */
27
+ export declare const RUNTIME_URLS: {
28
+ readonly webllm: readonly ["https://esm.run/@mlc-ai/web-llm@0.2.84", "https://cdn.jsdelivr.net/npm/@mlc-ai/web-llm@0.2.84/+esm"];
29
+ readonly bellows: readonly ["https://cdn.jsdelivr.net/npm/bellows-voice@0.8.0/engine/+esm"];
30
+ readonly kokoro: readonly ["https://cdn.jsdelivr.net/npm/kokoro-js@1.2.1/+esm"];
31
+ };
32
+ /** The runtime modules, each a function that imports it. Tests pass fakes; a page leaves them out. */
33
+ export interface RuntimeModules {
34
+ transformers?: () => Promise<TjsModule>;
35
+ ort?: () => Promise<OrtModule>;
36
+ webllm?: () => Promise<unknown>;
37
+ wllama?: () => Promise<unknown>;
38
+ tasksVision?: () => Promise<unknown>;
39
+ kokoro?: () => Promise<unknown>;
40
+ bellows?: () => Promise<unknown>;
41
+ /** The audio dsp core transcription runs on; default the wasm inlined in @hackbuild/audio-dsp. */
42
+ dsp?: () => Promise<Dsp>;
43
+ }
44
+ /** Options for {@link jobLoader}. Share one object between loaders to share one hub. */
45
+ export interface JobLoaderOptions {
46
+ /** Where weights are kept; default `openWeightStore()`. */
47
+ store?: WeightStore | Promise<WeightStore>;
48
+ /** This machine; default `probe()` from @hackbuild/ai-env. */
49
+ env?: Env;
50
+ /** Runtime modules in place of the pinned CDN imports (tests). */
51
+ modules?: RuntimeModules;
52
+ /** Kokoro's phonemizer is GPL-3.0-or-later; it is fetched only when this is true. */
53
+ allowGplPhonemizer?: boolean;
54
+ /** fetch for files a runtime does not fetch itself (static embedders). */
55
+ fetch?: typeof fetch;
56
+ /** Random numbers for the bellows voice; default a fixed seed. */
57
+ rng?: () => number;
58
+ }
59
+ /** A detector as a page calls it: boxes in image pixels, best first. */
60
+ export type DetectFn = (image: unknown) => Promise<FrameBox[]>;
61
+ /** A depth model as a page calls it: 0 to 1 per pixel, larger is nearer (relative inverse depth). */
62
+ export type DepthFn = (image: unknown) => Promise<{
63
+ width: number;
64
+ height: number;
65
+ data: Float32Array;
66
+ }>;
67
+ /** A vision language model as a page calls it: a question about an image (a caption without one), answered in words. */
68
+ export type AskFn = (image: unknown, question?: string) => Promise<string>;
69
+ /** An image model with its CLIP tokenizer: `make` generates with the form's defaults filled in. */
70
+ export type ImageJob = ImageGenerator & {
71
+ tokenize: ClipTokenize;
72
+ make(o: FormOptions): ReturnType<ImageGenerator["generate"]>;
73
+ };
74
+ /**
75
+ * What a jobLoader load resolves to, per job: chat a ChatEngine; transcribe a
76
+ * Transcriber; detect a DetectFn; masks MaskModels; depth a DepthFn; vision an
77
+ * AskFn; image an ImageJob; voice a loaded @hackbuild/speak Engine; embed an
78
+ * Embedder. faceswap and landmarks resolve to the hub's loaded value as is.
79
+ */
80
+ export interface JobValues {
81
+ chat: ChatEngine;
82
+ transcribe: Transcriber;
83
+ detect: DetectFn;
84
+ masks: MaskModels;
85
+ depth: DepthFn;
86
+ vision: AskFn;
87
+ image: ImageJob;
88
+ voice: Engine;
89
+ embed: Embedder;
90
+ faceswap: unknown;
91
+ landmarks: unknown;
92
+ }
93
+ /** Pixels ({ width, height, data }) as a canvas, which every runtime reads; anything else passes through. */
94
+ export declare function asImage(img: unknown): unknown;
95
+ /**
96
+ * A real Loader for a job. The runtime and weights load only when a pick
97
+ * calls it; progress goes to `ctx.onProgress`, `ctx.signal` stops it, and a
98
+ * failure throws in plain words. Resolves to {@link JobValues}[job].
99
+ */
100
+ export declare function jobLoader<J extends Job>(job: J, o?: JobLoaderOptions): Loader;