@g9tm/aiassistant 0.0.0-stage → 1.1.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/dist/blocks.js ADDED
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Blocks as view models: each block is read with type checks only, so a stored null never breaks it; a
3
+ * type no renderer knows shows its fallback text; and the display rules live here, once, for both renderers: a wide or
4
+ * wordy table becomes cards, a long one folds after 8 rows, a ranking is horizontal bars (at most 10), a line only on a
5
+ * time axis, and too little data shows no percentages or averages.
6
+ */
7
+ import { arr, num, obj, str } from "./api.js";
8
+ import { formatNumber } from "./fa.js";
9
+ /** A table with more columns than this, or long texts, shows each row as a card. */
10
+ export const CARD_COLUMNS = 4;
11
+ /** Rows shown before a long table folds. */
12
+ export const FOLD_ROWS = 8;
13
+ /** Bars in a ranking. */
14
+ export const RANK_BARS = 10;
15
+ /** Fewer data points than this show no percentages or averages. */
16
+ export const FEW_DATA = 3;
17
+ const KNOWN = new Set(["text", "callout", "table", "chart", "kpi", "steps", "actions", "flow", "image", "open", "export", "gallery", "items", "compare", "gauge", "timeline"]);
18
+ function columns(v) {
19
+ const kinds = new Set(["text", "number", "money", "percent", "date", "day", "id"]);
20
+ return arr(v).map(obj).map((c) => ({ name: str(c["name"]), kind: (kinds.has(str(c["kind"])) ? str(c["kind"]) : "text"), label: str(c["label"], str(c["name"])) }));
21
+ }
22
+ /** One cell as the person reads it: numbers in the locale's digits and separators. */
23
+ export function cell(v, kind, locale) {
24
+ if (v === null || v === undefined)
25
+ return "";
26
+ if (typeof v === "number") {
27
+ if (kind === "percent")
28
+ return formatNumber(v, locale, Number.isInteger(v) ? 0 : 1) + (locale === "fa" ? "٪" : "%");
29
+ return kind === "id" ? String(v) : formatNumber(v, locale, Number.isInteger(v) ? 0 : 2);
30
+ }
31
+ if (typeof v === "string")
32
+ return v;
33
+ if (typeof v === "boolean")
34
+ return v ? "✓" : "—";
35
+ return "";
36
+ }
37
+ /** The view model of a stored block; anything unreadable is its fallback text. */
38
+ export function blockView(raw, locale, custom = new Set()) {
39
+ const b = obj(raw);
40
+ const type = str(b["type"]);
41
+ const fallbackText = str(b["fallbackText"], str(b["text"]));
42
+ const title = typeof b["title"] === "string" ? b["title"] : undefined;
43
+ const withTitle = (v) => (title === undefined ? v : { ...v, title });
44
+ if (type.startsWith("x:"))
45
+ return custom.has(type) ? { type: "custom", name: type, data: obj(b["data"]), fallbackText } : { type: "fallback", fallbackText };
46
+ if (!KNOWN.has(type))
47
+ return { type: "fallback", fallbackText };
48
+ switch (type) {
49
+ case "text": return { type: "text", text: str(b["text"], fallbackText), fallbackText };
50
+ case "callout": {
51
+ const tones = new Set(["info", "warn", "ok", "danger", "neutral"]);
52
+ return { type: "callout", text: str(b["text"], fallbackText), tone: (tones.has(str(b["tone"])) ? str(b["tone"]) : "info"), fallbackText };
53
+ }
54
+ case "table": {
55
+ const cols = columns(b["columns"]);
56
+ if (cols.length === 0)
57
+ return { type: "fallback", fallbackText };
58
+ const rows = arr(b["rows"]).map((r) => cols.map((c, i) => cell(arr(r).at(i), c.kind, locale)));
59
+ const wordy = rows.some((r) => r.some((c) => c.length > 40));
60
+ const shown = rows.length > FOLD_ROWS ? FOLD_ROWS : rows.length;
61
+ return withTitle({ type: "table", columns: cols, rows, asCards: cols.length > CARD_COLUMNS || wordy, shown, more: rows.length - shown, truncated: b["truncated"] === true, fallbackText });
62
+ }
63
+ case "chart": return withTitle(chart(b, cols(b), fallbackText));
64
+ case "kpi": {
65
+ const cs = columns(b["columns"]);
66
+ const row = arr(arr(b["rows"])[0]);
67
+ const items = cs.map((c, i) => ({ label: c.label, value: cell(row.at(i), c.kind, locale) }));
68
+ return items.length > 0 ? { type: "kpi", items, fallbackText } : { type: "fallback", fallbackText };
69
+ }
70
+ case "steps": return { type: "steps", items: arr(b["items"]).map(obj).map((s) => ({ text: str(s["text"]), state: str(s["state"], "todo") })), fallbackText };
71
+ case "actions": return { type: "actions", items: arr(b["items"]).map(obj).map((a) => ({ label: str(a["label"]), send: str(a["send"]), suggested: a["backed"] === false })).filter((a) => a.label.length > 0 && a.send.length > 0).slice(0, 6), fallbackText };
72
+ case "flow": return { type: "flow", line: str(b["line"], fallbackText), fallbackText };
73
+ case "image":
74
+ case "gallery": return { type: "image", fileIds: arr(b["fileIds"]).filter((x) => typeof x === "string"), fallbackText };
75
+ case "open": return str(b["pageId"]).length > 0 ? { type: "open", pageId: str(b["pageId"]), fallbackText } : { type: "fallback", fallbackText };
76
+ case "export": {
77
+ // every row and column, as raw text: the file is for a spreadsheet, not for reading here
78
+ const cols = columns(b["columns"]);
79
+ const rows = arr(b["rows"]).map((r) => cols.map((_, i) => { const v = arr(r).at(i); return v === null || v === undefined ? "" : typeof v === "string" ? v : String(v); }));
80
+ return withTitle({ type: "export", format: str(b["format"], "csv"), columns: cols, rows, fallbackText });
81
+ }
82
+ default: return { type: "fallback", fallbackText }; // compare, gauge, timeline, items: drawn by the host or shown as text
83
+ }
84
+ function cols(x) {
85
+ return columns(x["columns"]);
86
+ }
87
+ }
88
+ function chart(b, cs, fallbackText) {
89
+ const rows = arr(b["rows"]).map(arr);
90
+ const x = str(b["x"], cs[0]?.name ?? "");
91
+ const xIndex = Math.max(0, cs.findIndex((c) => c.name === x));
92
+ const xCol = cs.at(xIndex);
93
+ const valueCols = cs.filter((_, i) => i !== xIndex && ["number", "money", "percent"].includes(cs.at(i)?.kind ?? ""));
94
+ if (!xCol || valueCols.length === 0 || rows.length === 0)
95
+ return { type: "fallback", fallbackText };
96
+ const labels = rows.map((r) => (r.at(xIndex) === null || r.at(xIndex) === undefined ? "" : String(r.at(xIndex))));
97
+ const series = valueCols.map((c) => ({ name: c.label, values: rows.map((r) => num(r.at(cs.indexOf(c)))) }));
98
+ const timeAxis = xCol.kind === "date" || xCol.kind === "day";
99
+ const asked = str(b["kind"]);
100
+ let kind;
101
+ if (!timeAxis && (asked === "bars" || asked === "line" || asked === "lines" || asked === ""))
102
+ kind = "hbars"; // a ranking: horizontal bars, never a line
103
+ else if (timeAxis && series.length > 1)
104
+ kind = "lines";
105
+ else if (asked === "donut" || asked === "stacked" || asked === "lines")
106
+ kind = asked;
107
+ else
108
+ kind = timeAxis ? "line" : "hbars";
109
+ if (kind === "hbars") {
110
+ const order = labels.map((_, i) => i).sort((a, c) => (series[0]?.values.at(c) ?? 0) - (series[0]?.values.at(a) ?? 0)).slice(0, RANK_BARS);
111
+ return { type: "chart", kind, labels: order.map((i) => labels.at(i) ?? ""), series: series.map((s) => ({ name: s.name, values: order.map((i) => s.values.at(i) ?? 0) })), fewData: rows.length < FEW_DATA, fallbackText };
112
+ }
113
+ return { type: "chart", kind, labels, series, fewData: rows.length < FEW_DATA, fallbackText };
114
+ }
115
+ /** Bar lengths as shares of the largest value (0..1), for the built-in chart. */
116
+ export function shares(values) {
117
+ const max = Math.max(0, ...values);
118
+ return values.map((v) => (max > 0 && v > 0 ? v / max : 0));
119
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * A conversation's messages on the client (conversation.ts): merged by id, an optimistic question until the
3
+ * server's copy arrives, history opened from the end, and the answer revealed only when it arrived in front of the person.
4
+ */
5
+ import type { Provenance } from "./types.js";
6
+ export interface MessageView {
7
+ id: string;
8
+ role: "user" | "assistant" | "system";
9
+ kind: string;
10
+ text: string;
11
+ blocks: unknown[];
12
+ next: string[];
13
+ provenance: Provenance | null;
14
+ at: string;
15
+ card: {
16
+ kind: string;
17
+ id: string;
18
+ body: Record<string, unknown>;
19
+ } | null;
20
+ pending: boolean;
21
+ }
22
+ /** A stored or streamed message, read with type checks only. */
23
+ export declare function messageView(raw: unknown): MessageView;
24
+ export declare class ConversationStore {
25
+ id: string | null;
26
+ private readonly byId;
27
+ private order;
28
+ private pendingId;
29
+ get messages(): MessageView[];
30
+ /** Merges messages (a known id is replaced, a new one appended in order). */
31
+ merge(raw: readonly unknown[]): MessageView[];
32
+ /** Shows the person's question at once, until the server's copy replaces it. */
33
+ optimistic(text: string, at: string): MessageView;
34
+ private dropPending;
35
+ /** Clears the store for another conversation. */
36
+ reset(id: string | null): void;
37
+ /** The id of the last message (the history opens at the end). */
38
+ get lastId(): string | null;
39
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * A conversation's messages on the client (conversation.ts): merged by id, an optimistic question until the
3
+ * server's copy arrives, history opened from the end, and the answer revealed only when it arrived in front of the person.
4
+ */
5
+ import { arr, obj, str } from "./api.js";
6
+ const PROVENANCES = new Set(["rule", "learned", "model", "fallback", "cached"]);
7
+ /** A stored or streamed message, read with type checks only. */
8
+ export function messageView(raw) {
9
+ const m = obj(raw);
10
+ const role = m["role"] === "user" || m["role"] === "system" ? m["role"] : "assistant";
11
+ const card = obj(m["card"]);
12
+ return {
13
+ id: str(m["id"]),
14
+ role,
15
+ kind: str(m["kind"], "text"),
16
+ text: str(m["text"]),
17
+ blocks: arr(m["blocks"]).filter((b) => b !== null && typeof b === "object"),
18
+ next: arr(m["next"]).filter((n) => typeof n === "string"),
19
+ provenance: typeof m["provenance"] === "string" && PROVENANCES.has(m["provenance"]) ? m["provenance"] : null,
20
+ at: str(m["at"]),
21
+ card: typeof card["kind"] === "string" ? { kind: card["kind"], id: str(card["id"]), body: obj(card["body"]) } : null,
22
+ pending: false,
23
+ };
24
+ }
25
+ export class ConversationStore {
26
+ constructor() {
27
+ this.id = null;
28
+ this.byId = new Map();
29
+ this.order = [];
30
+ this.pendingId = null;
31
+ }
32
+ get messages() {
33
+ return this.order.map((id) => this.byId.get(id)).filter((m) => m !== undefined);
34
+ }
35
+ /** Merges messages (a known id is replaced, a new one appended in order). */
36
+ merge(raw) {
37
+ const added = [];
38
+ for (const r of raw) {
39
+ const m = messageView(r);
40
+ if (m.id.length === 0)
41
+ continue;
42
+ if (this.pendingId && m.role === "user")
43
+ this.dropPending();
44
+ if (!this.byId.has(m.id)) {
45
+ this.order.push(m.id);
46
+ added.push(m);
47
+ }
48
+ this.byId.set(m.id, m);
49
+ }
50
+ return added;
51
+ }
52
+ /** Shows the person's question at once, until the server's copy replaces it. */
53
+ optimistic(text, at) {
54
+ this.dropPending();
55
+ const id = "pending:" + String(this.order.length);
56
+ const m = { id, role: "user", kind: "text", text, blocks: [], next: [], provenance: null, at, card: null, pending: true };
57
+ this.byId.set(id, m);
58
+ this.order.push(id);
59
+ this.pendingId = id;
60
+ return m;
61
+ }
62
+ dropPending() {
63
+ if (this.pendingId === null)
64
+ return;
65
+ this.byId.delete(this.pendingId);
66
+ this.order = this.order.filter((x) => x !== this.pendingId);
67
+ this.pendingId = null;
68
+ }
69
+ /** Clears the store for another conversation. */
70
+ reset(id) {
71
+ this.id = id;
72
+ this.byId.clear();
73
+ this.order = [];
74
+ this.pendingId = null;
75
+ }
76
+ /** The id of the last message (the history opens at the end). */
77
+ get lastId() {
78
+ return this.order.length > 0 ? (this.order[this.order.length - 1] ?? null) : null;
79
+ }
80
+ }
package/dist/csv.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /** A table as a CSV file a spreadsheet opens right: a BOM for the encoding, every cell quoted, no formula injection. */
2
+ import type { AssistantHost } from "./host.js";
3
+ /** One cell: quoted, with inner quotes doubled; a cell a spreadsheet would run as a formula gets a leading apostrophe. */
4
+ export declare function csvCell(value: string): string;
5
+ /** The whole file: a BOM, a header row of the column labels, then the rows, lines ended with CRLF. */
6
+ export declare function toCsv(labels: readonly string[], rows: readonly (readonly string[])[]): string;
7
+ /** A file name from a title: letters, digits and dashes only, with the extension. */
8
+ export declare function fileName(title: string | undefined, extension: string): string;
9
+ /** Saves a table through the host; false when the host cannot save files or the save did not happen. */
10
+ export declare function saveCsv(host: AssistantHost, title: string | undefined, labels: readonly string[], rows: readonly (readonly string[])[]): Promise<boolean>;
package/dist/csv.js ADDED
@@ -0,0 +1,27 @@
1
+ const BOM = "\uFEFF";
2
+ /** One cell: quoted, with inner quotes doubled; a cell a spreadsheet would run as a formula gets a leading apostrophe. */
3
+ export function csvCell(value) {
4
+ const safe = /^[-=+@\t\r]/u.test(value) ? "'" + value : value;
5
+ return '"' + safe.replace(/"/gu, '""') + '"';
6
+ }
7
+ /** The whole file: a BOM, a header row of the column labels, then the rows, lines ended with CRLF. */
8
+ export function toCsv(labels, rows) {
9
+ const lines = [labels.map(csvCell).join(","), ...rows.map((r) => labels.map((_, i) => csvCell(r[i] ?? "")).join(","))];
10
+ return BOM + lines.join("\r\n") + "\r\n";
11
+ }
12
+ /** A file name from a title: letters, digits and dashes only, with the extension. */
13
+ export function fileName(title, extension) {
14
+ const base = (title ?? "").trim().replace(/[\\/:*?"<>|\s]+/gu, "-").replace(/-+/gu, "-").replace(/^-|-$/gu, "");
15
+ return (base.length > 0 ? base.slice(0, 80) : "export") + "." + extension;
16
+ }
17
+ /** Saves a table through the host; false when the host cannot save files or the save did not happen. */
18
+ export async function saveCsv(host, title, labels, rows) {
19
+ if (typeof host.saveFile !== "function")
20
+ return false;
21
+ try {
22
+ return await host.saveFile(fileName(title, "csv"), toCsv(labels, rows));
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
package/dist/fa.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ /** Persian digits, thousands separators, direction and isolation. */
2
+ /** Latin and Arabic-Indic digits as Persian digits. */
3
+ export declare function faDigits(text: string): string;
4
+ /** Persian and Arabic-Indic digits as Latin digits (for parsing). */
5
+ export declare function latinDigits(text: string): string;
6
+ /** A number with thousands separators, in the locale's digits (Persian uses «٬»). */
7
+ export declare function formatNumber(value: number, locale: "fa" | "en", fractionDigits?: number): string;
8
+ /** The direction of a text by its first strong letter. */
9
+ export declare function directionOf(text: string): "rtl" | "ltr" | "neutral";
10
+ /** Wraps a piece in first-strong isolates (FSI…PDI) so a number or a Latin name cannot turn the line around. */
11
+ export declare function isolate(text: string): string;
12
+ /** A label and a number side by side, safe in both directions (Lynx reverses them in one ltr text otherwise). */
13
+ export declare function labelled(label: string, value: string): string;
package/dist/fa.js ADDED
@@ -0,0 +1,61 @@
1
+ /** Persian digits, thousands separators, direction and isolation. */
2
+ const PERSIAN = "۰۱۲۳۴۵۶۷۸۹";
3
+ const ARABIC_INDIC = "٠١٢٣٤٥٦٧٨٩";
4
+ /** Latin and Arabic-Indic digits as Persian digits. */
5
+ export function faDigits(text) {
6
+ let out = "";
7
+ for (const ch of text) {
8
+ const latin = ch >= "0" && ch <= "9" ? ch.charCodeAt(0) - 48 : -1;
9
+ const arabic = ARABIC_INDIC.indexOf(ch);
10
+ const d = latin >= 0 ? latin : arabic;
11
+ out += d >= 0 ? PERSIAN.charAt(d) : ch;
12
+ }
13
+ return out;
14
+ }
15
+ /** Persian and Arabic-Indic digits as Latin digits (for parsing). */
16
+ export function latinDigits(text) {
17
+ let out = "";
18
+ for (const ch of text) {
19
+ const p = PERSIAN.indexOf(ch);
20
+ const a = ARABIC_INDIC.indexOf(ch);
21
+ out += p >= 0 ? String(p) : a >= 0 ? String(a) : ch;
22
+ }
23
+ return out;
24
+ }
25
+ /** A number with thousands separators, in the locale's digits (Persian uses «٬»). */
26
+ export function formatNumber(value, locale, fractionDigits = 0) {
27
+ if (!Number.isFinite(value))
28
+ return "";
29
+ const negative = value < 0;
30
+ const fixed = Math.abs(value).toFixed(fractionDigits);
31
+ const [whole = "0", fraction] = fixed.split(".");
32
+ const sep = locale === "fa" ? "٬" : ",";
33
+ let grouped = "";
34
+ for (let i = 0; i < whole.length; i++) {
35
+ if (i > 0 && (whole.length - i) % 3 === 0)
36
+ grouped += sep;
37
+ grouped += whole.charAt(i);
38
+ }
39
+ const text = (negative ? "-" : "") + grouped + (fraction ? (locale === "fa" ? "٫" : ".") + fraction : "");
40
+ return locale === "fa" ? faDigits(text) : text;
41
+ }
42
+ const RTL = /[֐-ࣿיִ-﷿ﹰ-]/u;
43
+ const LTR = /[A-Za-zÀ-ɏ]/u;
44
+ /** The direction of a text by its first strong letter. */
45
+ export function directionOf(text) {
46
+ for (const ch of text) {
47
+ if (RTL.test(ch))
48
+ return "rtl";
49
+ if (LTR.test(ch))
50
+ return "ltr";
51
+ }
52
+ return "neutral";
53
+ }
54
+ /** Wraps a piece in first-strong isolates (FSI…PDI) so a number or a Latin name cannot turn the line around. */
55
+ export function isolate(text) {
56
+ return String.fromCharCode(0x2068) + text + String.fromCharCode(0x2069);
57
+ }
58
+ /** A label and a number side by side, safe in both directions (Lynx reverses them in one ltr text otherwise). */
59
+ export function labelled(label, value) {
60
+ return label + " " + isolate(value);
61
+ }
@@ -0,0 +1,20 @@
1
+ export interface ConversationRow {
2
+ id: string;
3
+ title: string;
4
+ capability: string;
5
+ pinned: boolean;
6
+ /** A card in it waits for the person's code or click. */
7
+ waiting: boolean;
8
+ /** When it last changed (milliseconds since 1970). */
9
+ updatedAt: number;
10
+ }
11
+ export type HistoryTab = "today" | "earlier" | "pinned" | "waiting";
12
+ export declare const HISTORY_TABS: readonly HistoryTab[];
13
+ /** Reads the server's list (`GET conversations`), pinned first and then the newest. */
14
+ export declare function readConversations(raw: unknown): ConversationRow[];
15
+ /** Folds the letters people type two ways (Arabic yeh and kaf, digits, case) so a search finds both. */
16
+ export declare function foldSearch(text: string): string;
17
+ /** The rows of each tab, after a search over the titles; a day starts at the person's local midnight. */
18
+ export declare function historyTabs(rows: readonly ConversationRow[], now: Date, search?: string): Record<HistoryTab, ConversationRow[]>;
19
+ /** How many rows each tab has. */
20
+ export declare function tabCounts(tabs: Record<HistoryTab, ConversationRow[]>): Record<HistoryTab, number>;
@@ -0,0 +1,39 @@
1
+ /** The person's conversations as tabs: today, earlier, pinned and waiting for their code, each with its count. */
2
+ import { latinDigits } from "./fa.js";
3
+ export const HISTORY_TABS = ["today", "earlier", "pinned", "waiting"];
4
+ function obj(v) {
5
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
6
+ }
7
+ /** Reads the server's list (`GET conversations`), pinned first and then the newest. */
8
+ export function readConversations(raw) {
9
+ const list = obj(raw)["conversations"];
10
+ const rows = (Array.isArray(list) ? list : []).map(obj).map((c) => ({
11
+ id: typeof c["id"] === "string" ? c["id"] : "",
12
+ title: typeof c["title"] === "string" ? c["title"] : "",
13
+ capability: typeof c["capability"] === "string" ? c["capability"] : "",
14
+ pinned: c["pinned"] === true,
15
+ waiting: c["waiting"] === true,
16
+ updatedAt: typeof c["updatedAt"] === "number" ? c["updatedAt"] : 0,
17
+ })).filter((c) => c.id.length > 0);
18
+ return rows.sort((a, b) => Number(b.pinned) - Number(a.pinned) || b.updatedAt - a.updatedAt);
19
+ }
20
+ /** Folds the letters people type two ways (Arabic yeh and kaf, digits, case) so a search finds both. */
21
+ export function foldSearch(text) {
22
+ return latinDigits(text).replace(/\u064A/gu, "\u06CC").replace(/\u0643/gu, "\u06A9").replace(/\u200C/gu, " ").toLowerCase().trim();
23
+ }
24
+ /** The rows of each tab, after a search over the titles; a day starts at the person's local midnight. */
25
+ export function historyTabs(rows, now, search = "") {
26
+ const start = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
27
+ const q = foldSearch(search);
28
+ const found = q.length === 0 ? [...rows] : rows.filter((r) => foldSearch(r.title).includes(q));
29
+ return {
30
+ today: found.filter((r) => r.updatedAt >= start),
31
+ earlier: found.filter((r) => r.updatedAt < start),
32
+ pinned: found.filter((r) => r.pinned),
33
+ waiting: found.filter((r) => r.waiting),
34
+ };
35
+ }
36
+ /** How many rows each tab has. */
37
+ export function tabCounts(tabs) {
38
+ return { today: tabs.today.length, earlier: tabs.earlier.length, pinned: tabs.pinned.length, waiting: tabs.waiting.length };
39
+ }
package/dist/host.d.ts ADDED
@@ -0,0 +1,87 @@
1
+ /** What the host gives the assistant. Anything optional that is missing hides its feature. */
2
+ export interface HostRequest {
3
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
4
+ headers?: Record<string, string>;
5
+ body?: string | Uint8Array;
6
+ }
7
+ export interface HostResponse {
8
+ status: number;
9
+ ok: boolean;
10
+ text(): Promise<string>;
11
+ headers?: {
12
+ get(name: string): string | null;
13
+ };
14
+ }
15
+ /** An EventSource-like stream (the browser's, or Lynx's when it has one). */
16
+ export interface HostEventSource {
17
+ addEventListener(type: string, listener: (e: {
18
+ data: string;
19
+ lastEventId?: string;
20
+ }) => void): void;
21
+ close(): void;
22
+ onerror: ((e: unknown) => void) | null;
23
+ }
24
+ export interface HostFile {
25
+ name: string;
26
+ type: string;
27
+ bytes: Uint8Array;
28
+ }
29
+ /** Design tokens in three levels: base, semantic and per component (layer 2). */
30
+ export interface AssistantTheme {
31
+ mode: "light" | "dark";
32
+ tokens: Readonly<Record<string, string>>;
33
+ }
34
+ export interface AssistantHost {
35
+ fetch(input: string, init?: HostRequest): Promise<HostResponse>;
36
+ locale: "fa" | "en";
37
+ dir: "rtl" | "ltr";
38
+ theme: AssistantTheme;
39
+ reducedMotion: boolean;
40
+ eventSource?(url: string): HostEventSource;
41
+ copy?(text: string): Promise<void>;
42
+ openUrl?(url: string): void;
43
+ pickFile?(accept: string[]): Promise<HostFile | null>;
44
+ pickImage?(): Promise<HostFile | null>;
45
+ saveFile?(name: string, data: Uint8Array | string): Promise<boolean>;
46
+ share?(text: string): Promise<void>;
47
+ haptic?(kind: "tick" | "ok" | "warn"): void;
48
+ play?(sound: "reveal" | "done"): void;
49
+ navigate?(pageId: string, subject?: {
50
+ kind: string;
51
+ id: string;
52
+ }): void;
53
+ pageName?(pageId: string): string | undefined;
54
+ dictate?(): Promise<string | null>;
55
+ /** Starts recording audio; the returned function stops it and gives the audio (the server turns it into text). */
56
+ record?(): Promise<() => Promise<{
57
+ bytes: Uint8Array;
58
+ mime: string;
59
+ } | null>>;
60
+ storage?: {
61
+ get(key: string): string | null;
62
+ set(key: string, value: string): void;
63
+ };
64
+ onBackground?(listener: (hidden: boolean) => void): () => void;
65
+ /**
66
+ * The panel's layer (its z-index). The Svelte renderer's dialogs sit above it at sheetLayer + 2; the Lynx renderer asks
67
+ * for a code inside the card, at the panel's own layer. A product that needs its confirm at layer N sets N - 2 (Svelte)
68
+ * or N (Lynx).
69
+ */
70
+ sheetLayer?: number;
71
+ /** Hosts whose links may be opened (https only). */
72
+ linkHosts?: readonly string[];
73
+ /** Called when an answer is shown, so other sheets do not cover it. */
74
+ onAnswerShown?(): void;
75
+ /** A timer (defaults to the platform's). */
76
+ setTimeout?(fn: () => void, ms: number): unknown;
77
+ clearTimeout?(handle: unknown): void;
78
+ now?(): number;
79
+ }
80
+ /** What a feature needs from the host, to hide it when missing (never an error). */
81
+ export declare function can(host: AssistantHost, feature: "copy" | "attach" | "save" | "share" | "stream" | "mic" | "record" | "open"): boolean;
82
+ /** The host's timer, or the platform's. */
83
+ export declare function timer(host: AssistantHost): {
84
+ set(fn: () => void, ms: number): unknown;
85
+ clear(h: unknown): void;
86
+ now(): number;
87
+ };
package/dist/host.js ADDED
@@ -0,0 +1,31 @@
1
+ /** What the host gives the assistant. Anything optional that is missing hides its feature. */
2
+ /** What a feature needs from the host, to hide it when missing (never an error). */
3
+ export function can(host, feature) {
4
+ switch (feature) {
5
+ case "copy": return typeof host.copy === "function";
6
+ case "attach": return typeof host.pickFile === "function" || typeof host.pickImage === "function";
7
+ case "save": return typeof host.saveFile === "function";
8
+ case "share": return typeof host.share === "function";
9
+ case "stream": return typeof host.eventSource === "function";
10
+ case "mic": return typeof host.dictate === "function";
11
+ case "record": return typeof host.record === "function";
12
+ case "open": return typeof host.navigate === "function";
13
+ }
14
+ }
15
+ function platformSet(fn, ms) {
16
+ return typeof setTimeout === "function" ? setTimeout(fn, ms) : globalThis.setTimeout?.(fn, ms);
17
+ }
18
+ function platformClear(h) {
19
+ if (typeof clearTimeout === "function")
20
+ clearTimeout(h);
21
+ else
22
+ globalThis.clearTimeout?.(h);
23
+ }
24
+ /** The host's timer, or the platform's. */
25
+ export function timer(host) {
26
+ return {
27
+ set: (fn, ms) => (host.setTimeout ? host.setTimeout(fn, ms) : platformSet(fn, ms)),
28
+ clear: (h) => (host.clearTimeout ? host.clearTimeout(h) : platformClear(h)),
29
+ now: () => (host.now ? host.now() : Date.now()),
30
+ };
31
+ }
package/dist/i18n.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /** The library's texts in Persian and English; every key can be overridden by the host (rule 5). */
2
+ export type Locale = "fa" | "en";
3
+ export interface Texts {
4
+ readonly locale: Locale;
5
+ t(key: string, args?: Readonly<Record<string, string | number>>): string;
6
+ }
7
+ /** The texts of a locale, with the host's overrides (a missing key shows itself, never an error). */
8
+ export declare function createTexts(locale: Locale, overrides?: Readonly<Record<string, string>>): Texts;
9
+ /** Every key the library uses (for hosts that translate to another language). */
10
+ export declare function libraryKeys(): string[];