@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.
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The talk views around a chat: MemoryPane (what is stored, search, sources,
3
+ * protect, forget, export, import, erase), SourcesDrop (files and folders
4
+ * into memory), PersonaRack (a persona in three parts sent in priority order
5
+ * and trimmed to a budget, with presets), VoiceRow (spoken replies) and
6
+ * SessionMenu (clear, export and import of chats). Each binds a library
7
+ * object to hackbuild-ui classes; none holds a model.
8
+ */
9
+ import { type Kind, type StoredItem, type EditPatch, type ExportData, type Recall } from "@hackbuild/memory";
10
+ import type { ChatList } from "./chat.js";
11
+ import type { PersonaRack, VoiceRow } from "./talk.js";
12
+ import type { Speaker } from "./speaker.js";
13
+ import { type Mounted } from "./dom.js";
14
+ /** What a memory pane needs from a store; a `Memory` from @hackbuild/memory fits. */
15
+ export interface MemoryLike {
16
+ all(): StoredItem[];
17
+ add(text: string, o?: {
18
+ kind?: Kind;
19
+ section?: string;
20
+ meta?: Record<string, unknown>;
21
+ }): Promise<unknown>;
22
+ remove(ids: number[]): Promise<void>;
23
+ edit(id: number, patch: EditPatch): Promise<unknown>;
24
+ recall(q: string, o?: {
25
+ k?: number;
26
+ }): Promise<Recall>;
27
+ export(): ExportData;
28
+ import(data: ExportData, o?: {
29
+ replace?: boolean;
30
+ }): Promise<number>;
31
+ }
32
+ /** A memory pane over a host: `refresh` after the store changes elsewhere, `used` to mark what the last reply used. */
33
+ export interface MemoryPaneHandle extends Mounted {
34
+ refresh(): void;
35
+ used(labels: readonly string[]): void;
36
+ }
37
+ /** True when an item is kept out of cleanup: decay never drops it. */
38
+ export declare const isProtected: (it: StoredItem) => boolean;
39
+ /** Protect an item from cleanup (it becomes lore, which never decays) or give it back its kind. */
40
+ export declare function protect(mem: Pick<MemoryLike, "edit">, it: StoredItem, on: boolean): Promise<void>;
41
+ /** Options of a memory pane. */
42
+ export interface MemoryPaneOptions {
43
+ name?: string;
44
+ onChange?: () => void;
45
+ /** The chip filter: by source (default) or by kind. */
46
+ by?: "source" | "kind";
47
+ /** Chip words for kinds, as { doc: "imported", lore: "background" }. */
48
+ kinds?: Readonly<Record<string, string>>;
49
+ /** The export button's words (default "export"). */
50
+ exportLabel?: string;
51
+ /** Extra footer actions, as consolidate; `onAct` gets the id. */
52
+ acts?: readonly {
53
+ id: string;
54
+ label: string;
55
+ }[];
56
+ onAct?: (id: string) => void;
57
+ }
58
+ /** The memory pane: counts, search, a source or kind filter, add a note, the list with protect and forget, export, import, erase. */
59
+ export declare function mountMemoryPane(host: HTMLElement, mem: MemoryLike, o?: MemoryPaneOptions): MemoryPaneHandle;
60
+ /** Options for a sources drop: what reads the files into memory, and a line per file. */
61
+ export interface SourcesDropOptions {
62
+ /** @hackbuild/memory `ingest(mem, files, o)` bound to a store. */
63
+ ingest: (files: File[], o: {
64
+ onFile: (e: {
65
+ name: string;
66
+ chunks: number;
67
+ note?: string;
68
+ }) => void;
69
+ }) => Promise<{
70
+ files: number;
71
+ chunks: number;
72
+ }>;
73
+ accept?: string;
74
+ }
75
+ /** A drop zone for sources: files or a whole folder of text, pdf, docx, zip and mail go into memory; a line per file says what came in. */
76
+ export declare function mountSourcesDrop(host: HTMLElement, o: SourcesDropOptions): Mounted;
77
+ /** The persona rack: presets one press away, name, the three parts with their cost, the template, save, and the persona as a file. */
78
+ export declare function mountPersonaRack(host: HTMLElement, rack: PersonaRack): Mounted;
79
+ /** The voice row: auto speak, voice, rate, pitch, test and stop. */
80
+ export declare function mountVoiceRow(host: HTMLElement, row: VoiceRow, o?: {
81
+ test?: string;
82
+ }): Mounted;
83
+ /** The voice clone row of a speaker: clone from an audio file, record `seconds` of mic, download the clone as wav, clear it. */
84
+ export declare function mountVoiceClone(host: HTMLElement, sp: Speaker, o?: {
85
+ seconds?: number;
86
+ can?: () => boolean;
87
+ hint?: string;
88
+ }): Mounted;
89
+ /** The session menu of a chat list: clear the open chat, export it as markdown, every chat as json, and import. */
90
+ export declare function mountSessionMenu(host: HTMLElement, list: ChatList, o?: {
91
+ onImport?: (n: number) => void;
92
+ }): Mounted;
@@ -0,0 +1,502 @@
1
+ /**
2
+ * The talk views around a chat: MemoryPane (what is stored, search, sources,
3
+ * protect, forget, export, import, erase), SourcesDrop (files and folders
4
+ * into memory), PersonaRack (a persona in three parts sent in priority order
5
+ * and trimmed to a budget, with presets), VoiceRow (spoken replies) and
6
+ * SessionMenu (clear, export and import of chats). Each binds a library
7
+ * object to hackbuild-ui classes; none holds a model.
8
+ */
9
+ import {} from "@hackbuild/memory";
10
+ import { memoryCounts, scoreText, PERSONA_TEMPLATE, insertTemplate, costLine, tokenEstimate } from "@virgilvox/hackbuild-ui/vanilla";
11
+ import { download, esc, listeners } from "./dom.js";
12
+ /** True when an item is kept out of cleanup: decay never drops it. */
13
+ export const isProtected = (it) => it.meta?.protected === true;
14
+ /** Protect an item from cleanup (it becomes lore, which never decays) or give it back its kind. */
15
+ export async function protect(mem, it, on) {
16
+ if (on === isProtected(it))
17
+ return;
18
+ const meta = { ...(it.meta ?? {}) };
19
+ if (on)
20
+ await mem.edit(it.id, { kind: "lore", meta: { ...meta, protected: true, was: it.kind } });
21
+ else {
22
+ const was = meta.was ?? "fact";
23
+ delete meta.protected;
24
+ delete meta.was;
25
+ await mem.edit(it.id, { kind: was, meta });
26
+ }
27
+ }
28
+ const sourceOf = (it) => (typeof it.meta?.source === "string" ? it.meta.source.split("/")[0] : it.kind === "doc" ? it.section ?? "file" : "notes");
29
+ /** The memory pane: counts, search, a source or kind filter, add a note, the list with protect and forget, export, import, erase. */
30
+ export function mountMemoryPane(host, mem, o = {}) {
31
+ const l = listeners();
32
+ let query = "";
33
+ let source = "";
34
+ let armed = 0;
35
+ let wipe = false;
36
+ let used = new Set();
37
+ let hits = null;
38
+ let seq = 0;
39
+ const file = document.createElement("input");
40
+ file.type = "file";
41
+ file.accept = ".json,application/json";
42
+ file.hidden = true;
43
+ const box = document.createElement("div");
44
+ host.replaceChildren(box, file);
45
+ const changed = () => (o.onChange?.(), draw());
46
+ const groupOf = (it) => (o.by === "kind" ? (isProtected(it) ? String(it.meta?.was ?? it.kind) : it.kind) : sourceOf(it));
47
+ const groupWord = (g) => (o.by === "kind" ? o.kinds?.[g] ?? g : g);
48
+ const draw = () => {
49
+ const all = mem.all();
50
+ const sources = [...new Set(all.map(groupOf))];
51
+ let shown = all.filter((it) => !source || groupOf(it) === source);
52
+ if (hits)
53
+ shown = shown.filter((it) => hits.has(it.id)).sort((a, b) => hits.get(b.id) - hits.get(a.id));
54
+ else
55
+ shown = shown.slice().sort((a, b) => b.created - a.created);
56
+ const focus = document.activeElement === box.querySelector("[data-q]");
57
+ box.innerHTML =
58
+ `<section class="hb-mempanel" aria-label="${esc(o.name ?? "memory")}">` +
59
+ `<div class="hb-mempanel-sec"><p class="hb-mempanel-counts">${esc(memoryCounts(all.map((it) => ({ id: String(it.id), text: it.text, kind: it.kind }))) || "nothing stored")}</p></div>` +
60
+ `<div class="hb-mempanel-sec"><input class="hb-input" type="search" data-q placeholder="search memory" aria-label="search memory" value="${esc(query)}">` +
61
+ (sources.length > 1 ? `<div class="hb-chipgroup" role="group" aria-label="${o.by === "kind" ? "kind" : "source"}"><button type="button" class="hb-chip${source ? "" : " is-on"}" data-src="" aria-pressed="${!source}">all</button>${sources.map((s) => `<button type="button" class="hb-chip${s === source ? " is-on" : ""}" data-src="${esc(s)}" aria-pressed="${s === source}">${esc(groupWord(s))}</button>`).join("")}</div>` : "") +
62
+ `</div>` +
63
+ `<div class="hb-mempanel-sec"><textarea class="hb-textarea" rows="2" data-note placeholder="a fact to keep" aria-label="add a note"></textarea><div class="hb-mempanel-row"><button type="button" class="hb-btn hb-btn-sm" data-add>add</button></div></div>` +
64
+ `<div class="hb-mempanel-sec"><h3 class="hb-mempanel-hd">${query ? "matches" : "notes"} (${shown.length})</h3>` +
65
+ (shown.length
66
+ ? `<div class="hb-mempanel-list">${shown
67
+ .slice(0, 200)
68
+ .map((it) => {
69
+ const p = isProtected(it);
70
+ const u = used.has(it.text);
71
+ return (`<div class="hb-mem${u ? " is-used" : ""}${p ? " is-pinned" : ""}"><div class="hb-mem-body">${p ? `<span class="hb-mem-pin">kept</span>` : ""}<span class="hb-mem-kind">${esc(p ? String(it.meta?.was ?? it.kind) : it.kind)}${hits?.has(it.id) ? `<b class="hb-mem-score">${esc(scoreText(hits.get(it.id)))}</b>` : ""}</span><span class="hb-mem-text">${esc(it.text.length > 280 ? `${it.text.slice(0, 277)}...` : it.text)}</span>` +
72
+ `<span class="hb-mem-when">${esc([u ? "used last reply" : "", sourceOf(it) === "notes" ? "" : sourceOf(it)].filter(Boolean).join(", "))}</span></div>` +
73
+ `<div class="hb-mem-acts"><button type="button" class="hb-mem-act${p ? " is-on" : ""}" data-keep="${it.id}" aria-pressed="${p}" aria-label="${p ? "let cleanup drop it" : "keep from cleanup"}" title="${p ? "kept from cleanup" : "keep"}">keep</button><button type="button" class="hb-mem-act is-forget${armed === it.id ? " is-armed" : ""}" data-forget="${it.id}">${armed === it.id ? "forget?" : "forget"}</button></div></div>`);
74
+ })
75
+ .join("")}</div>`
76
+ : `<p class="hb-mempanel-empty">${query ? "nothing matches. try other words." : "nothing stored yet. add a note, drop a file, or talk and it fills."}</p>`) +
77
+ `</div>` +
78
+ `<div class="hb-mempanel-foot">${all.length ? (o.acts ?? []).map((a) => `<button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-act="${esc(a.id)}">${esc(a.label)}</button>`).join("") : ""}<button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-export>${esc(o.exportLabel ?? "export")}</button><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-import>import</button>${all.length ? `<button type="button" class="hb-btn hb-btn-2 hb-btn-sm hb-mempanel-wipe${wipe ? " is-armed" : ""}" data-wipe>${wipe ? "erase everything?" : "erase all"}</button>` : ""}</div></section>`;
79
+ if (focus) {
80
+ const q = box.querySelector("[data-q]");
81
+ q.focus();
82
+ q.setSelectionRange(q.value.length, q.value.length);
83
+ }
84
+ };
85
+ const search = async () => {
86
+ const mine = ++seq;
87
+ if (!query.trim())
88
+ hits = null;
89
+ else {
90
+ const r = await mem.recall(query, { k: 50 });
91
+ if (mine !== seq)
92
+ return;
93
+ hits = new Map(r.hits.map((h) => [h.item.id, h.score]));
94
+ }
95
+ draw();
96
+ };
97
+ l.on(box, "input", (e) => {
98
+ const t = e.target;
99
+ if (t.matches("[data-q]")) {
100
+ query = t.value;
101
+ void search();
102
+ }
103
+ });
104
+ l.on(box, "keydown", (e) => {
105
+ const ke = e;
106
+ if (ke.target.matches("[data-note]") && ke.key === "Enter" && !ke.shiftKey) {
107
+ ke.preventDefault();
108
+ box.querySelector("[data-add]")?.click();
109
+ }
110
+ });
111
+ l.on(box, "click", (e) => {
112
+ const t = e.target;
113
+ const src = t.closest("[data-src]");
114
+ if (src)
115
+ return ((source = src.dataset.src ?? ""), draw());
116
+ const all = () => mem.all();
117
+ const keep = t.closest("[data-keep]");
118
+ if (keep) {
119
+ const it = all().find((x) => x.id === Number(keep.dataset.keep));
120
+ if (it)
121
+ void protect(mem, it, !isProtected(it)).then(changed);
122
+ return;
123
+ }
124
+ const fg = t.closest("[data-forget]");
125
+ if (fg) {
126
+ const id = Number(fg.dataset.forget);
127
+ if (armed !== id)
128
+ return ((armed = id), draw());
129
+ armed = 0;
130
+ void mem.remove([id]).then(changed);
131
+ return;
132
+ }
133
+ if (t.closest("[data-add]")) {
134
+ const ta = box.querySelector("[data-note]");
135
+ const text = ta.value.trim();
136
+ if (text)
137
+ void mem.add(text, { kind: "fact" }).then(changed);
138
+ return;
139
+ }
140
+ const act = t.closest("[data-act]");
141
+ if (act)
142
+ return o.onAct?.(act.dataset.act ?? "");
143
+ if (t.closest("[data-export]"))
144
+ return download(`memory-${new Date().toISOString().slice(0, 10)}.json`, JSON.stringify(mem.export(), null, 2), "application/json");
145
+ if (t.closest("[data-import]"))
146
+ return file.click();
147
+ if (t.closest("[data-wipe]")) {
148
+ if (!wipe)
149
+ return ((wipe = true), draw());
150
+ wipe = false;
151
+ void mem.remove(all().map((x) => x.id)).then(changed);
152
+ }
153
+ });
154
+ l.on(file, "change", () => {
155
+ const f = file.files?.[0];
156
+ file.value = "";
157
+ if (!f)
158
+ return;
159
+ void f
160
+ .text()
161
+ .then((t) => mem.import(JSON.parse(t), { replace: false }))
162
+ .then(changed)
163
+ .catch((err) => {
164
+ box.querySelector(".hb-mempanel-foot")?.insertAdjacentHTML("beforeend", `<p class="hb-error" role="alert">that file did not import: ${esc(err instanceof Error ? err.message : String(err))}</p>`);
165
+ });
166
+ });
167
+ draw();
168
+ return {
169
+ refresh: () => void search(),
170
+ used(labels) {
171
+ used = new Set(labels);
172
+ draw();
173
+ },
174
+ dispose: () => l.off(),
175
+ };
176
+ }
177
+ async function walk(e, out, path, depth = 0) {
178
+ if (e.isFile && e.file) {
179
+ const f = await new Promise((ok, bad) => e.file(ok, bad));
180
+ out.push(path ? Object.assign(new File([f], f.name, { type: f.type }), { webkitRelativePath: `${path}/${f.name}` }) : f);
181
+ }
182
+ else if (e.isDirectory && e.createReader && depth < 8) {
183
+ const r = e.createReader();
184
+ for (;;) {
185
+ const batch = await new Promise((ok, bad) => r.readEntries(ok, bad));
186
+ if (!batch.length)
187
+ break;
188
+ for (const c of batch)
189
+ await walk(c, out, path ? `${path}/${e.name}` : e.name, depth + 1);
190
+ }
191
+ }
192
+ }
193
+ /** A drop zone for sources: files or a whole folder of text, pdf, docx, zip and mail go into memory; a line per file says what came in. */
194
+ export function mountSourcesDrop(host, o) {
195
+ const l = listeners();
196
+ const pick = (dir) => {
197
+ const i = document.createElement("input");
198
+ i.type = "file";
199
+ i.hidden = true;
200
+ i.multiple = true;
201
+ if (dir)
202
+ i.setAttribute("webkitdirectory", "");
203
+ else
204
+ i.accept = o.accept ?? ".txt,.md,.csv,.json,.html,.htm,.pdf,.docx,.zip,.eml,text/*";
205
+ return i;
206
+ };
207
+ const files = pick(false);
208
+ const dir = pick(true);
209
+ const zone = document.createElement("div");
210
+ const log = document.createElement("ul");
211
+ zone.className = "hb-dropzone";
212
+ zone.innerHTML = `<p class="hb-note">drop files or a folder: text, pdf, docx, zip, mail. they are read here and kept in this browser.</p><div class="hb-toolbar"><button type="button" class="hb-btn hb-btn-sm" data-files>add files</button><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-dir>a folder</button></div>`;
213
+ log.className = "hb-list";
214
+ log.setAttribute("aria-live", "polite");
215
+ host.replaceChildren(zone, log, files, dir);
216
+ const line = (t, err = false) => log.insertAdjacentHTML("afterbegin", `<li${err ? ` class="hb-error"` : ""}>${esc(t)}</li>`);
217
+ const run = (list) => {
218
+ if (!list.length)
219
+ return;
220
+ zone.classList.add("is-busy");
221
+ line(`reading ${list.length} file${list.length === 1 ? "" : "s"}`);
222
+ o.ingest(list, { onFile: (e) => line(e.note ? `${e.name}: ${e.note}` : `${e.name}: ${e.chunks} part${e.chunks === 1 ? "" : "s"}`, !!e.note && e.note.startsWith("failed")) })
223
+ .then((r) => line(`done. ${r.files} file${r.files === 1 ? "" : "s"}, ${r.chunks} parts in memory.`))
224
+ .catch((err) => line(`stopped: ${err instanceof Error ? err.message : String(err)}`, true))
225
+ .finally(() => zone.classList.remove("is-busy"));
226
+ };
227
+ l.on(zone, "click", (e) => {
228
+ const t = e.target;
229
+ if (t.closest("[data-files]"))
230
+ files.click();
231
+ else if (t.closest("[data-dir]"))
232
+ dir.click();
233
+ });
234
+ for (const i of [files, dir])
235
+ l.on(i, "change", () => {
236
+ run([...(i.files ?? [])]);
237
+ i.value = "";
238
+ });
239
+ l.on(zone, "dragover", (e) => (e.preventDefault(), zone.classList.add("is-over")));
240
+ l.on(zone, "dragleave", () => zone.classList.remove("is-over"));
241
+ l.on(zone, "drop", (e) => {
242
+ e.preventDefault();
243
+ zone.classList.remove("is-over");
244
+ const dt = e.dataTransfer;
245
+ const entries = [...(dt?.items ?? [])].map((i) => i.webkitGetAsEntry?.()).filter((x) => x !== null && x !== undefined);
246
+ if (!entries.length)
247
+ return run([...(dt?.files ?? [])]);
248
+ const out = [];
249
+ void Promise.all(entries.map((en) => walk(en, out, "").catch(() => undefined))).then(() => run(out));
250
+ });
251
+ return { dispose: () => l.off() };
252
+ }
253
+ /* ---------- PersonaRack ---------- */
254
+ /** The persona rack: presets one press away, name, the three parts with their cost, the template, save, and the persona as a file. */
255
+ export function mountPersonaRack(host, rack) {
256
+ const l = listeners();
257
+ const file = document.createElement("input");
258
+ file.type = "file";
259
+ file.accept = ".json,application/json";
260
+ file.hidden = true;
261
+ const box = document.createElement("div");
262
+ host.replaceChildren(box, file);
263
+ let err = "";
264
+ const field = (key, label, hint, rows, v) => `<div class="hb-field"><span class="hb-field-head"><label class="hb-label" for="pr-${key}">${label}</label></span><textarea id="pr-${key}" class="hb-textarea" rows="${rows}" data-k="${key}" placeholder="${esc(hint)}">${esc(v)}</textarea><span class="hb-field-foot"><span class="hb-hint">${esc(costLine(tokenEstimate(v)))}</span></span></div>`;
265
+ const draw = () => {
266
+ if (box.contains(document.activeElement) && document.activeElement.matches("[data-k]"))
267
+ return;
268
+ const { persona: p, presets, on, builtIn } = rack.snapshot();
269
+ box.innerHTML =
270
+ `<div class="hb-persona"><div class="hb-persona-presets"><div class="hb-persona-chips" role="group" aria-label="personas">${presets
271
+ .map((x, i) => `<span class="hb-persona-chip${i === on ? " is-on" : ""}"><button type="button" class="hb-persona-chip-n" data-load="${i}" aria-pressed="${i === on}">${esc(x.label)}</button>${i < builtIn ? "" : `<button type="button" class="hb-persona-chip-x" data-rm="${i}" aria-label="remove ${esc(x.label)}">&times;</button>`}</span>`)
272
+ .join("")}</div></div>` +
273
+ `<div class="hb-field"><span class="hb-field-head"><label class="hb-label" for="pr-name">name</label></span><input id="pr-name" class="hb-input" data-k="name" value="${esc(p.name)}" autocomplete="off"></div>` +
274
+ field("profile", "profile", "who you are talking to and how to answer. always sent.", 5, p.profile) +
275
+ `<div class="hb-persona-row"><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-tpl>insert template</button></div>` +
276
+ field("notes", "extra notes", "sent after memory; dropped before the profile when room runs out.", 3, p.notes) +
277
+ field("rules", "extra rules", "dropped first when room runs out.", 3, p.rules) +
278
+ `<form class="hb-persona-save" data-save><input class="hb-input" data-label placeholder="${esc(p.name || "preset name")}" aria-label="preset name" autocomplete="off"><button type="submit" class="hb-btn hb-btn-2 hb-btn-sm">save</button></form>` +
279
+ `<div class="hb-persona-row"><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-import>import</button><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-export>export</button></div>${err ? `<p class="hb-error" role="alert">${esc(err)}</p>` : ""}</div>`;
280
+ };
281
+ l.on(box, "input", (e) => {
282
+ const t = e.target;
283
+ const k = t.dataset.k;
284
+ if (k) {
285
+ rack.set({ [k]: t.value });
286
+ const foot = t.parentElement?.querySelector(".hb-hint");
287
+ if (foot)
288
+ foot.textContent = costLine(tokenEstimate(t.value));
289
+ }
290
+ });
291
+ l.on(box, "focusout", () => setTimeout(draw, 0));
292
+ l.on(box, "submit", (e) => {
293
+ e.preventDefault();
294
+ rack.save(box.querySelector("[data-label]")?.value ?? "");
295
+ });
296
+ l.on(box, "click", (e) => {
297
+ const t = e.target;
298
+ const ld = t.closest("[data-load]");
299
+ if (ld)
300
+ return rack.load(Number(ld.dataset.load));
301
+ const rm = t.closest("[data-rm]");
302
+ if (rm)
303
+ return rack.removePreset(Number(rm.dataset.rm));
304
+ if (t.closest("[data-tpl]")) {
305
+ const p = rack.snapshot().persona;
306
+ rack.set({ profile: insertTemplate(p.profile, PERSONA_TEMPLATE, p.name) });
307
+ return draw();
308
+ }
309
+ if (t.closest("[data-export]")) {
310
+ const p = rack.snapshot().persona;
311
+ return download(`${(p.name || "persona").replace(/[^a-z0-9]+/gi, "-").toLowerCase()}.persona.json`, JSON.stringify({ v: 1, name: p.name, prompt: p.profile, notes: p.notes, rules: p.rules, ...(p.first ? { first: p.first } : {}) }, null, 2), "application/json");
312
+ }
313
+ if (t.closest("[data-import]"))
314
+ file.click();
315
+ });
316
+ l.on(file, "change", () => {
317
+ const f = file.files?.[0];
318
+ file.value = "";
319
+ if (!f)
320
+ return;
321
+ void f.text().then((t) => {
322
+ try {
323
+ const j = JSON.parse(t);
324
+ const profile = typeof j.prompt === "string" ? j.prompt : typeof j.system_prompt === "string" ? j.system_prompt : typeof j.description === "string" ? j.description : "";
325
+ if (!profile && typeof j.name !== "string")
326
+ throw new Error("no name or prompt in it");
327
+ err = "";
328
+ rack.set({ name: String(j.name ?? "assistant"), profile, notes: String(j.notes ?? ""), rules: String(j.rules ?? ""), ...(typeof j.first === "string" ? { first: j.first } : {}) });
329
+ }
330
+ catch (e2) {
331
+ err = `that file is not a persona: ${e2 instanceof Error ? e2.message : String(e2)}`;
332
+ }
333
+ draw();
334
+ });
335
+ });
336
+ l.add(rack.subscribe(draw));
337
+ return { dispose: () => l.off() };
338
+ }
339
+ /* ---------- VoiceRow ---------- */
340
+ /** The voice row: auto speak, voice, rate, pitch, test and stop. */
341
+ export function mountVoiceRow(host, row, o = {}) {
342
+ const l = listeners();
343
+ const draw = () => {
344
+ if (host.contains(document.activeElement) && document.activeElement.matches("input[type=range]"))
345
+ return;
346
+ const s = row.snapshot();
347
+ host.innerHTML =
348
+ `<div class="hb-panel"><label class="hb-check"><input type="checkbox" data-auto${s.auto ? " checked" : ""}> speak each reply</label>` +
349
+ `<div class="hb-field"><span class="hb-field-head"><label class="hb-label" for="vr-voice">voice</label></span><select id="vr-voice" class="hb-select" data-voice><option value="">system default</option>${s.voices.map((v) => `<option${v === s.voice ? " selected" : ""}>${esc(v)}</option>`).join("")}</select></div>` +
350
+ `<div class="hb-slider"><span class="hb-label">rate</span><span class="hb-readout">${s.rate.toFixed(1)}</span><input type="range" min="0.5" max="2" step="0.1" value="${s.rate}" data-rate aria-label="rate"></div>` +
351
+ `<div class="hb-slider"><span class="hb-label">pitch</span><span class="hb-readout">${s.pitch.toFixed(1)}</span><input type="range" min="0" max="2" step="0.1" value="${s.pitch}" data-pitch aria-label="pitch"></div>` +
352
+ `<div class="hb-toolbar">${s.speaking ? `<button type="button" class="hb-btn hb-btn-sm" data-stop>stop</button>` : `<button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-test>test</button>`}</div>${s.error ? `<p class="hb-error" role="alert">${esc(s.error)}</p>` : ""}</div>`;
353
+ };
354
+ l.on(host, "input", (e) => {
355
+ const t = e.target;
356
+ if (t.matches("[data-rate]"))
357
+ row.set({ rate: Number(t.value) });
358
+ else if (t.matches("[data-pitch]"))
359
+ row.set({ pitch: Number(t.value) });
360
+ const r = t.parentElement?.querySelector(".hb-readout");
361
+ if (r && t.type === "range")
362
+ r.textContent = Number(t.value).toFixed(1);
363
+ });
364
+ l.on(host, "change", (e) => {
365
+ const t = e.target;
366
+ if (t.matches("[data-auto]"))
367
+ row.set({ auto: t.checked });
368
+ else if (t.matches("[data-voice]"))
369
+ row.set({ voice: t.value });
370
+ else if (t.type === "range")
371
+ draw();
372
+ });
373
+ l.on(host, "click", (e) => {
374
+ const t = e.target;
375
+ if (t.closest("[data-test]"))
376
+ void row.speak(o.test ?? "this is how replies will sound.");
377
+ else if (t.closest("[data-stop]"))
378
+ row.stop();
379
+ });
380
+ l.add(row.subscribe(draw));
381
+ return { dispose: () => (row.stop(), l.off()) };
382
+ }
383
+ /* ---------- VoiceClone ---------- */
384
+ /** The voice clone row of a speaker: clone from an audio file, record `seconds` of mic, download the clone as wav, clear it. */
385
+ export function mountVoiceClone(host, sp, o = {}) {
386
+ const l = listeners();
387
+ const secs = o.seconds ?? 10;
388
+ const file = document.createElement("input");
389
+ file.type = "file";
390
+ file.accept = "audio/*";
391
+ file.hidden = true;
392
+ const box = document.createElement("div");
393
+ host.replaceChildren(box, file);
394
+ let note = "";
395
+ let busy = false;
396
+ const draw = () => {
397
+ const can = o.can?.() ?? true;
398
+ box.innerHTML =
399
+ `<div>` +
400
+ (can
401
+ ? `<div class="hb-toolbar" role="group" aria-label="voice clone"><button type="button" class="hb-btn hb-btn-sm" data-file${busy ? " disabled" : ""}>clone from audio file</button><button type="button" class="hb-btn hb-btn-sm" data-rec${busy ? " disabled" : ""}>record ${secs} s</button>${sp.cloned ? `<button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-wav>download clone, wav</button><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-clear>clear clone</button>` : ""}</div>`
402
+ : "") +
403
+ `<p class="hb-note" role="status">${esc(note || (can ? o.hint ?? `clones a voice from ${secs} s of audio. nothing leaves this tab.` : "this voice cannot clone. load pocket in the voice list."))}</p></div>`;
404
+ };
405
+ const fail = (err) => {
406
+ const name = err.name ?? "";
407
+ note = name === "NotAllowedError" || name === "SecurityError" ? "the mic is blocked. allow it in the address bar, or clone from a file." : err instanceof Error ? err.message : String(err);
408
+ };
409
+ l.on(box, "click", (e) => {
410
+ const t = e.target;
411
+ if (t.closest("[data-file]"))
412
+ return file.click();
413
+ if (t.closest("[data-wav]")) {
414
+ const w = sp.cloneWav();
415
+ if (w)
416
+ download("voice-clone.wav", w, "audio/wav");
417
+ return;
418
+ }
419
+ if (t.closest("[data-clear]")) {
420
+ sp.clearClone();
421
+ note = "clone cleared. the voice is its own again.";
422
+ return draw();
423
+ }
424
+ if (t.closest("[data-rec]") && !busy) {
425
+ busy = true;
426
+ void sp
427
+ .cloneMic(secs, (left) => ((note = `recording, ${left} s left`), draw()))
428
+ .then((s) => (note = `cloned from ${s.toFixed(1)} s of your mic.`), fail)
429
+ .finally(() => ((busy = false), draw()));
430
+ }
431
+ });
432
+ l.on(file, "change", () => {
433
+ const f = file.files?.[0];
434
+ file.value = "";
435
+ if (!f)
436
+ return;
437
+ busy = true;
438
+ note = "cloning...";
439
+ draw();
440
+ void sp
441
+ .cloneFile(f)
442
+ .then((s) => (note = `cloned from ${s.toFixed(1)} s of ${f.name}.`), fail)
443
+ .finally(() => ((busy = false), draw()));
444
+ });
445
+ l.add(sp.subscribe(draw));
446
+ draw();
447
+ return { dispose: () => l.off() };
448
+ }
449
+ /* ---------- SessionMenu ---------- */
450
+ /** The session menu of a chat list: clear the open chat, export it as markdown, every chat as json, and import. */
451
+ export function mountSessionMenu(host, list, o = {}) {
452
+ const l = listeners();
453
+ const file = document.createElement("input");
454
+ file.type = "file";
455
+ file.accept = ".json,application/json";
456
+ file.hidden = true;
457
+ const box = document.createElement("div");
458
+ host.replaceChildren(box, file);
459
+ let armed = false;
460
+ let note = "";
461
+ const draw = () => {
462
+ const has = list.thread.snapshot().turns.length > 0;
463
+ box.innerHTML =
464
+ `<div class="hb-toolbar" role="group" aria-label="session">${has ? `<button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-md>save as markdown</button>` : ""}<button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-json>export chats</button><button type="button" class="hb-btn hb-btn-2 hb-btn-sm" data-import>import chats</button>${has ? `<button type="button" class="hb-btn hb-btn-2 hb-btn-sm${armed ? " is-armed" : ""}" data-clear>${armed ? "clear this chat?" : "clear"}</button>` : ""}</div>${note ? `<p class="hb-note" role="status">${esc(note)}</p>` : ""}`;
465
+ };
466
+ l.on(box, "click", (e) => {
467
+ const t = e.target;
468
+ const day = new Date().toISOString().slice(0, 10);
469
+ if (t.closest("[data-md]"))
470
+ return download(`chat-${day}.md`, list.thread.markdown(), "text/markdown");
471
+ if (t.closest("[data-json]"))
472
+ return download(`chats-${day}.json`, JSON.stringify(list.dump(), null, 2), "application/json");
473
+ if (t.closest("[data-import]"))
474
+ return file.click();
475
+ if (t.closest("[data-clear]")) {
476
+ if (!armed)
477
+ return ((armed = true), draw());
478
+ armed = false;
479
+ list.thread.clear();
480
+ }
481
+ });
482
+ l.on(file, "change", () => {
483
+ const f = file.files?.[0];
484
+ file.value = "";
485
+ if (!f)
486
+ return;
487
+ void f.text().then((t) => {
488
+ try {
489
+ const data = JSON.parse(t);
490
+ list.restore(data);
491
+ note = `${data.chats.length} chat${data.chats.length === 1 ? "" : "s"} imported.`;
492
+ o.onImport?.(data.chats.length);
493
+ }
494
+ catch (err) {
495
+ note = `that file did not import: ${err instanceof Error ? err.message : String(err)}`;
496
+ }
497
+ draw();
498
+ });
499
+ });
500
+ l.add(list.subscribe(() => draw()));
501
+ return { dispose: () => l.off() };
502
+ }
@@ -30,6 +30,8 @@ export interface TranscribeDropOptions extends TranscriptViewOptions {
30
30
  title?: string;
31
31
  note?: string;
32
32
  pickLabel?: string;
33
+ /** A "choose a folder" button; a dropped folder is read whole either way. */
34
+ folders?: boolean;
33
35
  /** A sample a person can try with no file; the page queues it. */
34
36
  sampleLabel?: string;
35
37
  onSample?: () => void;
@@ -38,7 +40,16 @@ export interface TranscribeDropOptions extends TranscriptViewOptions {
38
40
  export interface TranscribeDropHandle extends Mounted {
39
41
  /** Open the file picker: the add files verb. */
40
42
  pick(): void;
43
+ /** Open the folder picker. */
44
+ pickFolder(): void;
41
45
  }
46
+ /** A file a speech run can read: audio or video by type or by name. */
47
+ export declare const isMedia: (f: {
48
+ name: string;
49
+ type: string;
50
+ }) => boolean;
51
+ /** The files of a drop, with dropped folders read through, media only. */
52
+ export declare function droppedFiles(dt: DataTransfer | null | undefined): Promise<File[]>;
42
53
  /** The drop zone that becomes the transcript. */
43
54
  export declare function mountTranscribeDrop(host: HTMLElement, queue: TranscribeQueue, o?: TranscribeDropOptions): TranscribeDropHandle;
44
55
  /** The queue as hackbuild-ui strips: name, state, figures, progress, remove; run and stop. */
@@ -49,3 +60,14 @@ export declare function mountTranscriptExports(host: HTMLElement, queue: Transcr
49
60
  save?: (name: string, text: string, type: string) => void;
50
61
  go?: boolean;
51
62
  }): Mounted;
63
+ /**
64
+ * ExportMenu: the selected transcript as txt, srt, vtt or json, a copy, and
65
+ * every finished transcript as one zip with a manifest, plus undo and redo of
66
+ * edits. Nothing shows until there is text; undo shows once there is a change.
67
+ * `go` makes the first export the one pink action.
68
+ */
69
+ export declare function mountExportMenu(host: HTMLElement, queue: TranscribeQueue, o?: {
70
+ save?: (name: string, data: string | Uint8Array, type: string) => void;
71
+ tool?: string;
72
+ go?: boolean;
73
+ }): Mounted;