@g9tm/aiassistant-react 0.0.0-stage → 1.8.1

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,46 @@
1
+ /**
2
+ * What every React component of one assistant shares: the core assistant, its texts, the host's per-part classes
3
+ * and styles, the unstyled switch and component overrides. Any component, small or large, can be replaced by the host;
4
+ * the replacement gets the same props and the library's own as `Default`, so it can wrap it.
5
+ */
6
+ import type { CSSProperties, ReactNode } from "react";
7
+ import type { Assistant, AssistantSnapshot, PartName, PartStyles, Texts } from "@g9tm/aiassistant";
8
+ /** Any component a host gives in place of the library's (it gets the same props, plus the default as Default). */
9
+ export type HostComponent = (props: any) => ReactNode;
10
+ /** A component of the library (a plain function of its props). */
11
+ export type Part<P> = (props: P) => ReactNode;
12
+ /** Host replacements: by component name, and per block type (including the host's x:* blocks). */
13
+ export interface Overrides {
14
+ [name: string]: HostComponent | Record<string, HostComponent> | undefined;
15
+ Block?: Record<string, HostComponent>;
16
+ }
17
+ export interface AssistantUi {
18
+ assistant: Assistant;
19
+ texts: Texts;
20
+ styles: PartStyles;
21
+ unstyled: boolean;
22
+ components: Overrides;
23
+ /** The layer dialogs inside the panel sit on (above the panel). */
24
+ layer: number;
25
+ }
26
+ /** Shares the assistant's UI with the components inside. */
27
+ export declare function UiProvider(props: {
28
+ value: AssistantUi;
29
+ children?: ReactNode;
30
+ }): ReactNode;
31
+ export declare function useUi(): AssistantUi;
32
+ /** The assistant's snapshot, kept up to date. */
33
+ export declare function useSnapshot(assistant: Assistant): AssistantSnapshot;
34
+ /** The class of a part (the library's stable class and the host's). */
35
+ export declare function cls(ui: AssistantUi, part: PartName): string;
36
+ /** The inline style the host gave a part (a CSS declaration list, as in the Svelte renderer). */
37
+ export declare function sty(ui: AssistantUi, part: PartName): CSSProperties | undefined;
38
+ /** The host's replacement of a component, if any. */
39
+ export declare function override(ui: AssistantUi, name: string): HostComponent | undefined;
40
+ /** The host's renderer of a block type, if any. */
41
+ export declare function blockOverride(ui: AssistantUi, type: string): HostComponent | undefined;
42
+ /**
43
+ * A component a host can replace by name wherever it is drawn, by the library or by the host's own composition. The
44
+ * host's one gets the same props plus the library's as `Default`, so it can wrap it without drawing itself again.
45
+ */
46
+ export declare function swappable<P extends object>(name: string, Base: Part<P>): Part<P>;
@@ -0,0 +1,68 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * What every React component of one assistant shares: the core assistant, its texts, the host's per-part classes
4
+ * and styles, the unstyled switch and component overrides. Any component, small or large, can be replaced by the host;
5
+ * the replacement gets the same props and the library's own as `Default`, so it can wrap it.
6
+ */
7
+ import { createContext, useContext, useEffect, useState } from "react";
8
+ import { partClass } from "@g9tm/aiassistant";
9
+ const UiContext = createContext(null);
10
+ /** Shares the assistant's UI with the components inside. */
11
+ export function UiProvider(props) {
12
+ return _jsx(UiContext.Provider, { value: props.value, children: props.children });
13
+ }
14
+ export function useUi() {
15
+ const ui = useContext(UiContext);
16
+ if (!ui)
17
+ throw new Error("Use the assistant's components inside AssistantRoot.");
18
+ return ui;
19
+ }
20
+ /** The assistant's snapshot, kept up to date. */
21
+ export function useSnapshot(assistant) {
22
+ const [snap, setSnap] = useState(() => assistant.snapshot());
23
+ useEffect(() => {
24
+ setSnap(assistant.snapshot());
25
+ return assistant.subscribe(setSnap);
26
+ }, [assistant]);
27
+ return snap;
28
+ }
29
+ /** The class of a part (the library's stable class and the host's). */
30
+ export function cls(ui, part) {
31
+ return partClass(part, ui.styles, ui.unstyled);
32
+ }
33
+ /** The inline style the host gave a part (a CSS declaration list, as in the Svelte renderer). */
34
+ export function sty(ui, part) {
35
+ const text = ui.styles.styles ? new Map(Object.entries(ui.styles.styles)).get(part) : undefined;
36
+ if (!text)
37
+ return undefined;
38
+ const out = new Map();
39
+ for (const decl of text.split(";")) {
40
+ const at = decl.indexOf(":");
41
+ if (at <= 0)
42
+ continue;
43
+ const name = decl.slice(0, at).trim();
44
+ const value = decl.slice(at + 1).trim();
45
+ out.set(name.startsWith("--") ? name : name.replace(/-([a-z])/gu, (_m, c) => c.toUpperCase()), value);
46
+ }
47
+ return Object.fromEntries(out);
48
+ }
49
+ /** The host's replacement of a component, if any. */
50
+ export function override(ui, name) {
51
+ const c = new Map(Object.entries(ui.components)).get(name);
52
+ return typeof c === "function" ? c : undefined;
53
+ }
54
+ /** The host's renderer of a block type, if any. */
55
+ export function blockOverride(ui, type) {
56
+ return ui.components.Block ? new Map(Object.entries(ui.components.Block)).get(type) : undefined;
57
+ }
58
+ /**
59
+ * A component a host can replace by name wherever it is drawn, by the library or by the host's own composition. The
60
+ * host's one gets the same props plus the library's as `Default`, so it can wrap it without drawing itself again.
61
+ */
62
+ export function swappable(name, Base) {
63
+ const Swappable = (props) => {
64
+ const Own = override(useUi(), name);
65
+ return Own ? _jsx(Own, { ...props, Default: Base }) : _jsx(Base, { ...props });
66
+ };
67
+ return Swappable;
68
+ }
@@ -0,0 +1,19 @@
1
+ /** @g9tm/aiassistant-react: React DOM components of the G9 AI assistant, customisable in five layers like the Svelte ones. */
2
+ export { AssistantRoot, AssistantChat, AssistantPanel, MessageList, Surfaces } from "./surfaces.js";
3
+ export type { AssistantPanelProps, AssistantRootProps, SurfaceKind, SurfaceProps } from "./surfaces.js";
4
+ export { Composer, Message, ModelPicker, PdfButton, RevealText, Small, StagesThinking, ThinkingOrb, WorkCard } from "./parts.js";
5
+ export type { ComposerProps, SmallKind } from "./parts.js";
6
+ export { BlockView, Chart, CsvButton, TextView } from "./blocks.js";
7
+ export type { ChartView, CsvButtonProps } from "./blocks.js";
8
+ export { ApprovalCard, Cards } from "./cards.js";
9
+ export { Dialog, PinPad, SecretField } from "./slots.js";
10
+ export type { DialogProps, PinPadProps } from "./slots.js";
11
+ export { Abilities, ActionsPage, FindingsPage, History, KnowledgePage, LearnedPage, Page, RoutineWizard, SlotPicker } from "./pages.js";
12
+ export type { PageKind, PageProps, SlotPickerProps } from "./pages.js";
13
+ export { pageKeys, pageTexts } from "@g9tm/aiassistant/pages";
14
+ export { browserHost } from "./browser.js";
15
+ export type { BrowserHostOptions } from "./browser.js";
16
+ export { blockOverride, cls, override, sty, swappable, UiProvider, useSnapshot, useUi } from "./context.js";
17
+ export type { AssistantUi, HostComponent, Overrides, Part } from "./context.js";
18
+ export { themeVars, LIGHT, DARK } from "./theme.js";
19
+ export { STYLES } from "./styles.js";
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ /** @g9tm/aiassistant-react: React DOM components of the G9 AI assistant, customisable in five layers like the Svelte ones. */
2
+ export { AssistantRoot, AssistantChat, AssistantPanel, MessageList, Surfaces } from "./surfaces.js";
3
+ export { Composer, Message, ModelPicker, PdfButton, RevealText, Small, StagesThinking, ThinkingOrb, WorkCard } from "./parts.js";
4
+ export { BlockView, Chart, CsvButton, TextView } from "./blocks.js";
5
+ export { ApprovalCard, Cards } from "./cards.js";
6
+ export { Dialog, PinPad, SecretField } from "./slots.js";
7
+ export { Abilities, ActionsPage, FindingsPage, History, KnowledgePage, LearnedPage, Page, RoutineWizard, SlotPicker } from "./pages.js";
8
+ export { pageKeys, pageTexts } from "@g9tm/aiassistant/pages";
9
+ export { browserHost } from "./browser.js";
10
+ export { blockOverride, cls, override, sty, swappable, UiProvider, useSnapshot, useUi } from "./context.js";
11
+ export { themeVars, LIGHT, DARK } from "./theme.js";
12
+ export { STYLES } from "./styles.js";
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The assistant's pages for React DOM: history, abilities, knowledge, what it learned, findings, routines, the actions
3
+ * it took and the manager's gates. Each reads its own endpoint, with type checks only; each page is replaceable by name
4
+ * (`History`, `Abilities`...). History has four tabs with counts, a search, pin and delete; the routine wizard asks a
5
+ * routine's slots (a picker for things, typed fields for the rest), previews it, and runs it with the person's code.
6
+ */
7
+ import type { ReactNode } from "react";
8
+ import type { RoutineSlot } from "@g9tm/aiassistant/pages";
9
+ export type PageKind = "history" | "abilities" | "knowledge" | "learned" | "findings" | "routines" | "actions" | "admin";
10
+ export interface PageProps {
11
+ onOpen?: (conversationId: string) => void;
12
+ }
13
+ /** A page by its kind (history and the routine wizard are their own replaceable pages; the rest read one endpoint). */
14
+ export declare function Page(props: PageProps & {
15
+ kind: PageKind;
16
+ }): ReactNode;
17
+ export interface SlotPickerProps {
18
+ slot: RoutineSlot;
19
+ label: string;
20
+ picked?: {
21
+ id: string;
22
+ label: string;
23
+ } | null;
24
+ onPick: (pick: {
25
+ id: string;
26
+ label: string;
27
+ } | null) => void;
28
+ delay?: number;
29
+ }
30
+ /**
31
+ * A routine's entity slot: a searchable picker over the host's things of the slot's kind (`GET pick`), asked a short
32
+ * while after the person stops typing; an answer that came after a newer question is dropped. Replaceable as `SlotPicker`.
33
+ */
34
+ export declare const SlotPicker: import("./context.js").Part<SlotPickerProps>;
35
+ export declare const History: import("./context.js").Part<PageProps>;
36
+ export declare const Abilities: import("./context.js").Part<PageProps>;
37
+ export declare const KnowledgePage: import("./context.js").Part<PageProps>;
38
+ export declare const LearnedPage: import("./context.js").Part<PageProps>;
39
+ export declare const FindingsPage: import("./context.js").Part<PageProps>;
40
+ export declare const RoutineWizard: import("./context.js").Part<object>;
41
+ export declare const ActionsPage: import("./context.js").Part<PageProps>;
package/dist/pages.js ADDED
@@ -0,0 +1,274 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /**
3
+ * The assistant's pages for React DOM: history, abilities, knowledge, what it learned, findings, routines, the actions
4
+ * it took and the manager's gates. Each reads its own endpoint, with type checks only; each page is replaceable by name
5
+ * (`History`, `Abilities`...). History has four tabs with counts, a search, pin and delete; the routine wizard asks a
6
+ * routine's slots (a picker for things, typed fields for the rest), previews it, and runs it with the person's code.
7
+ */
8
+ import { useEffect, useRef, useState } from "react";
9
+ import { ApiError, arr, faDigits, needsCode, num, obj, planView, str } from "@g9tm/aiassistant";
10
+ import { HISTORY_TABS, historyTabs, missingSlots, pageCalls, pageTexts, readConversations, readPicks, readRoutines, slotValue, tabCounts } from "@g9tm/aiassistant/pages";
11
+ import { BlockView } from "./blocks.js";
12
+ import { cls, override, swappable, useSnapshot, useUi } from "./context.js";
13
+ import { Dialog, PinPad } from "./slots.js";
14
+ const PATHS = new Map([
15
+ ["abilities", "capabilities"], ["knowledge", "knowledge"], ["learned", "learned/dashboard?capability=chat"], ["findings", "findings"], ["actions", "conversations"], ["admin", "gates"],
16
+ ]);
17
+ /** A page by its kind (history and the routine wizard are their own replaceable pages; the rest read one endpoint). */
18
+ export function Page(props) {
19
+ const ui = useUi();
20
+ if (props.kind === "history") {
21
+ const Own = override(ui, "History") ?? HistoryBody;
22
+ return _jsx(Own, { ...props });
23
+ }
24
+ if (props.kind === "routines") {
25
+ const Own = override(ui, "RoutineWizard") ?? RoutineBody;
26
+ return _jsx(Own, { ...props });
27
+ }
28
+ return _jsx(PlainPage, { ...props });
29
+ }
30
+ function PlainPage(props) {
31
+ const ui = useUi();
32
+ const t = ui.texts.t;
33
+ const api = ui.assistant.api;
34
+ const snap = useSnapshot(ui.assistant);
35
+ const [data, setData] = useState(null);
36
+ const [failed, setFailed] = useState(false);
37
+ const [purpose, setPurpose] = useState("");
38
+ const [code, setCode] = useState("");
39
+ const [token, setToken] = useState(null);
40
+ const load = () => api.get(PATHS.get(props.kind) ?? "").then((r) => { setData(obj(r)); setFailed(false); }, () => { setData({}); setFailed(true); });
41
+ useEffect(() => { void load(); }, [props.kind]);
42
+ const act = (path, body) => { void api.post(path, body).catch(() => undefined).then(load); };
43
+ const d = data ?? {};
44
+ const loaded = data !== null;
45
+ const empty = _jsx("li", { className: "g9a-note g9a-empty", children: pageTexts(ui.texts).t("page." + props.kind + ".empty") });
46
+ const id = (r) => encodeURIComponent(str(r["id"]));
47
+ let body = null;
48
+ if (props.kind === "abilities") {
49
+ const groups = arr(d["groups"]).map(obj);
50
+ const closed = arr(d["closed"]).map(obj);
51
+ body = (_jsxs(_Fragment, { children: [groups.map((g) => (_jsxs("div", { children: [_jsx("h4", { children: str(g["title"], str(g["name"])) }), _jsx("ul", { children: arr(g["tools"]).map(obj).map((x) => _jsx("li", { children: str(x["title"], str(x["name"])) }, str(x["name"]))) })] }, str(g["name"])))), closed.map((c) => _jsx("p", { className: "g9a-note", children: str(c["name"]) + " · " + str(c["layer"]) }, str(c["name"]))), loaded && groups.length === 0 && closed.length === 0 ? _jsx("ul", { children: empty }) : null] }));
52
+ }
53
+ else if (props.kind === "knowledge") {
54
+ const notes = arr(d["notes"] ?? d["items"]).map(obj);
55
+ body = _jsx("ul", { children: notes.length === 0 ? (loaded ? empty : null) : notes.map((n, i) => _jsx("li", { children: str(n["text"], str(n["name"])) }, i)) });
56
+ }
57
+ else if (props.kind === "learned") {
58
+ const items = arr(d["items"]).map(obj);
59
+ body = (_jsxs(_Fragment, { children: [loaded ? _jsx("p", { children: String(Math.round(num(d["modelFreeRate"]) * 100)) + "% · " + String(num(d["tokensSaved"])) }) : null, _jsx("ul", { children: items.length === 0 ? (loaded ? empty : null) : items.map((x, i) => _jsx("li", { "data-status": str(x["status"]), children: str(x["signature"]) + " · " + str(x["status"]) + " · " + String(num(x["hits"])) }, i)) })] }));
60
+ }
61
+ else if (props.kind === "findings") {
62
+ const findings = arr(d["findings"]).map(obj);
63
+ body = (_jsx("ul", { children: findings.length === 0 ? (loaded ? empty : null) : findings.map((f) => (_jsxs("li", { children: [str(obj(f["title"])["text"], t(str(obj(f["title"])["key"]))), _jsx("button", { type: "button", onClick: () => act("findings/" + id(f) + "/fixed"), children: "\u2713" }), _jsx("button", { type: "button", onClick: () => act("findings/" + id(f) + "/dismiss", { reason: "—" }), children: t("no") })] }, str(f["id"])))) }));
64
+ }
65
+ else if (props.kind === "actions") {
66
+ const done = [...snap.plans.values()].filter((p) => p.answered === "confirmed");
67
+ body = _jsx("ul", { children: done.length === 0 ? empty : done.map((p) => _jsxs("li", { children: [p.title, " ", _jsx("button", { type: "button", onClick: () => void ui.assistant.undo(p.id), children: t("undo.all") })] }, p.id)) });
68
+ }
69
+ else {
70
+ body = (_jsxs(_Fragment, { children: [_jsxs("form", { onSubmit: (e) => {
71
+ e.preventDefault();
72
+ void api.post("gates", { purpose, code }).catch(() => null).then((r) => { setToken(str(obj(r)["token"]) || null); setPurpose(""); setCode(""); return load(); });
73
+ }, children: [_jsx("input", { value: purpose, placeholder: "purpose", "aria-label": "purpose", onChange: (e) => setPurpose(e.currentTarget.value) }), _jsx("input", { value: code, type: "password", placeholder: t("card.code"), "aria-label": t("card.code"), onChange: (e) => setCode(e.currentTarget.value) }), _jsx("button", { type: "submit", children: "+" })] }), token ? _jsx("p", { className: "g9a-note", children: _jsx("code", { children: token }) }) : null, _jsx("ul", { children: arr(d["gates"]).map(obj).map((g) => (_jsxs("li", { "data-revoked": g["revoked"] === true, children: [str(g["purpose"]) + " · " + String(num(g["callsToday"])), " ", _jsx("button", { type: "button", onClick: () => { void api.delete("gates/" + id(g)).catch(() => undefined).then(load); }, children: "\u00D7" })] }, str(g["id"])))) })] }));
74
+ }
75
+ return (_jsxs("div", { className: cls(ui, "panel.body"), "data-page": props.kind, children: [failed ? _jsx("p", { className: "g9a-note", role: "alert", children: t("error.network") }) : null, body] }));
76
+ }
77
+ /**
78
+ * The person's conversations in four tabs with their counts (today, earlier, pinned, waiting for a code), one search
79
+ * over all of them, pin or unpin, delete after a confirmation, and open. The rows and tabs come from the core's page
80
+ * helpers; this only draws them.
81
+ */
82
+ function HistoryBody(props) {
83
+ const ui = useUi();
84
+ const t = pageTexts(ui.texts).t;
85
+ const api = ui.assistant.api;
86
+ const Confirm = override(ui, "Dialog") ?? Dialog;
87
+ const [rows, setRows] = useState([]);
88
+ const [failed, setFailed] = useState(false);
89
+ const [search, setSearch] = useState("");
90
+ const [tab, setTab] = useState("today");
91
+ const [removing, setRemoving] = useState(null);
92
+ const digits = (n) => (ui.texts.locale === "fa" ? faDigits(String(n)) : String(n));
93
+ const load = () => api.conversations().then((r) => { setRows(readConversations(r)); setFailed(false); }, () => setFailed(true));
94
+ useEffect(() => { void load(); }, []);
95
+ const call = (work) => { void work.then(() => undefined, () => setFailed(true)).then(load); };
96
+ const tabs = historyTabs(rows, new Date(), search);
97
+ const counts = new Map(Object.entries(tabCounts(tabs)));
98
+ const shown = new Map(Object.entries(tabs)).get(tab) ?? [];
99
+ const open = async (id) => { await ui.assistant.open(id); props.onOpen?.(id); };
100
+ const remove = () => { const row = removing; setRemoving(null); if (row)
101
+ call(pageCalls.remove(api, row.id)); };
102
+ return (_jsxs("div", { className: cls(ui, "panel.body") + " g9a-history", "data-page": "history", children: [failed ? _jsx("p", { className: "g9a-note", role: "alert", children: t("error.network") }) : null, _jsx("input", { type: "search", value: search, placeholder: t("history.search"), "aria-label": t("history.search"), onChange: (e) => setSearch(e.currentTarget.value) }), _jsx("div", { role: "tablist", className: "g9a-tabs", "aria-label": t("history.tabs"), children: HISTORY_TABS.map((x) => (_jsxs("button", { type: "button", role: "tab", "data-tab": x, "aria-selected": tab === x, onClick: () => setTab(x), children: [t("history." + x), " ", _jsx("span", { className: "g9a-count", children: digits(counts.get(x) ?? 0) })] }, x))) }), _jsx("div", { role: "tabpanel", "data-tab": tab, children: _jsx("ul", { className: "g9a-history__list", children: shown.length === 0 ? _jsx("li", { className: "g9a-note", children: t("history.empty") }) : shown.map((row) => (_jsxs("li", { className: "g9a-history__row", "data-id": row.id, "data-pinned": row.pinned, "data-waiting": row.waiting, children: [_jsx("button", { type: "button", className: "g9a-history__open", onClick: () => void open(row.id), children: row.title || t("history.untitled") }), _jsx("button", { type: "button", className: "g9a-history__pin", "aria-pressed": row.pinned, onClick: () => call(pageCalls.pin(api, row.id, !row.pinned)), children: row.pinned ? t("history.unpin") : t("history.pin") }), _jsx("button", { type: "button", className: "g9a-history__delete", onClick: () => setRemoving(row), children: t("history.delete") })] }, row.id))) }) }), _jsxs(Confirm, { open: removing !== null, label: t("history.delete_confirm"), onClose: () => setRemoving(null), children: [_jsx("p", { children: t("history.delete_confirm") }), _jsx("p", { children: _jsx("strong", { children: removing?.title || t("history.untitled") }) }), _jsxs("div", { className: "g9a-row", children: [_jsx("button", { type: "button", className: "g9a-history__delete-yes", onClick: remove, children: t("history.delete") }), _jsx("button", { type: "button", onClick: () => setRemoving(null), children: t("no") })] })] })] }));
103
+ }
104
+ /**
105
+ * A routine's entity slot: a searchable picker over the host's things of the slot's kind (`GET pick`), asked a short
106
+ * while after the person stops typing; an answer that came after a newer question is dropped. Replaceable as `SlotPicker`.
107
+ */
108
+ export const SlotPicker = swappable("SlotPicker", (props) => {
109
+ const ui = useUi();
110
+ const t = pageTexts(ui.texts).t;
111
+ const [q, setQ] = useState("");
112
+ const [found, setFound] = useState([]);
113
+ const [asked, setAsked] = useState(false);
114
+ const [askedFor, setAskedFor] = useState(""); // before anything is typed an empty answer is a hint, not "nothing found"
115
+ const [failed, setFailed] = useState(false);
116
+ const handle = useRef(undefined);
117
+ const seq = useRef(0);
118
+ useEffect(() => () => { if (handle.current !== undefined)
119
+ clearTimeout(handle.current); seq.current++; }, []);
120
+ const ask = (text) => {
121
+ if (handle.current !== undefined)
122
+ clearTimeout(handle.current);
123
+ const mine = ++seq.current;
124
+ handle.current = setTimeout(() => {
125
+ pageCalls.pick(ui.assistant.api, props.slot.kind, text.trim()).then((raw) => {
126
+ if (mine !== seq.current)
127
+ return;
128
+ setFound(readPicks(raw));
129
+ setAskedFor(text.trim());
130
+ setAsked(true);
131
+ setFailed(false);
132
+ }, () => { if (mine === seq.current)
133
+ setFailed(true); });
134
+ }, props.delay ?? 250);
135
+ };
136
+ return (_jsx("div", { className: "g9a-picker", "data-slot": props.slot.name, children: props.picked ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "g9a-picker__chosen", children: props.picked.label }), _jsx("button", { type: "button", className: "g9a-picker__change", onClick: () => { props.onPick(null); setQ(""); setFound([]); setAsked(false); }, children: t("routine.change") })] })) : (_jsxs(_Fragment, { children: [_jsx("input", { type: "search", value: q, "aria-label": props.label, placeholder: t("routine.search"), onChange: (e) => { setQ(e.currentTarget.value); ask(e.currentTarget.value); }, onFocus: () => { if (!asked)
137
+ ask(q); } }), failed ? _jsx("p", { className: "g9a-note", role: "alert", children: t("error.network") }) : null, found.length > 0 ? (_jsx("ul", { className: "g9a-picker__list", role: "listbox", "aria-label": props.label, children: found.map((p) => _jsx("li", { role: "option", "aria-selected": "false", children: _jsx("button", { type: "button", onClick: () => props.onPick(p), children: p.label }) }, p.id)) })) : asked ? _jsx("p", { className: "g9a-note", children: t(askedFor.length === 0 ? "routine.type_to_search" : "routine.none_found") }) : null] })) }));
138
+ });
139
+ /**
140
+ * The routine wizard: the routines the person may run; choosing one asks for its slots (entity slots through a
141
+ * searchable picker, the rest typed and checked by the core's slotValue), then "Preview". A read-only routine answers
142
+ * with its report; one that changes things returns its card, confirmed here (with the code its method asks for) and
143
+ * run bound to the preview's run and hash.
144
+ */
145
+ function RoutineBody() {
146
+ const ui = useUi();
147
+ const t = pageTexts(ui.texts).t;
148
+ const api = ui.assistant.api;
149
+ const Picker = override(ui, "SlotPicker") ?? SlotPicker;
150
+ const [routines, setRoutines] = useState(null);
151
+ const [loadFailed, setLoadFailed] = useState(false);
152
+ const [chosen, setChosen] = useState(null);
153
+ const [typed, setTyped] = useState(new Map());
154
+ const [picks, setPicks] = useState(new Map());
155
+ const [tried, setTried] = useState(false);
156
+ const [serverMissing, setServerMissing] = useState([]);
157
+ const [report, setReport] = useState(null);
158
+ const [card, setCard] = useState(null);
159
+ const [code, setCode] = useState("");
160
+ const [busy, setBusy] = useState(false);
161
+ const [failure, setFailure] = useState(null);
162
+ const [triesLeft, setTriesLeft] = useState(null);
163
+ const [result, setResult] = useState(null);
164
+ useEffect(() => { pageCalls.routines(api).then((raw) => { setRoutines(readRoutines(raw)); setLoadFailed(false); }, () => { setRoutines([]); setLoadFailed(true); }); }, [api]);
165
+ const textOf = (name) => typed.get(name) ?? "";
166
+ const valueOf = (slot) => (slot.field === "pick" ? picks.get(slot.name)?.id ?? null : slotValue(slot, textOf(slot.name)));
167
+ const values = Object.fromEntries((chosen?.slots ?? []).flatMap((s) => { const v = valueOf(s); return v === null ? [] : [[s.name, v]]; }));
168
+ const missing = chosen ? missingSlots(chosen.slots, values).map((s) => s.name) : [];
169
+ /** A slot's state: filled, missing (shown once the person asked for the preview, or the server said so) or not right. */
170
+ const stateOf = (slot) => {
171
+ if (slot.field !== "pick" && textOf(slot.name).trim().length > 0 && valueOf(slot) === null)
172
+ return "invalid";
173
+ if (serverMissing.includes(slot.name))
174
+ return "missing";
175
+ return tried && missing.includes(slot.name) ? "missing" : "ok";
176
+ };
177
+ const labelOf = (slot) => { const key = "slot." + slot.name; const v = t(key); return v === key ? slot.name : v; };
178
+ const say = (key, args) => { const text = t(key, args); return text === key ? Object.values(args).join(" ") || key : text; };
179
+ const choose = (r) => {
180
+ setChosen(r);
181
+ setTyped(new Map());
182
+ setPicks(new Map());
183
+ setTried(false);
184
+ setServerMissing([]);
185
+ setReport(null);
186
+ setCard(null);
187
+ setCode("");
188
+ setFailure(null);
189
+ setTriesLeft(null);
190
+ setResult(null);
191
+ };
192
+ const failed = (e) => {
193
+ setFailure(e instanceof ApiError ? e.code : "error.network");
194
+ const left = e instanceof ApiError ? obj(e.body)["triesLeft"] : undefined;
195
+ setTriesLeft(typeof left === "number" ? left : null);
196
+ };
197
+ const preview = async () => {
198
+ setTried(true);
199
+ setFailure(null);
200
+ setServerMissing([]);
201
+ if (!chosen || missing.length > 0 || chosen.slots.some((s) => stateOf(s) === "invalid"))
202
+ return;
203
+ setBusy(true);
204
+ try {
205
+ const r = obj(await pageCalls.preview(api, chosen.id, values, ui.assistant.snapshot().conversationId ?? undefined));
206
+ const state = str(r["state"]);
207
+ if (state === "report")
208
+ setReport(arr(r["blocks"]));
209
+ else if (state === "missing" || !r["card"])
210
+ setServerMissing(arr(r["missing"]).filter((m) => typeof m === "string"));
211
+ else {
212
+ const plan = planView(r["card"]);
213
+ setCard({ plan, routineRunId: str(r["routineRunId"]), hash: str(r["hash"], plan.hash) });
214
+ }
215
+ }
216
+ catch (e) {
217
+ failed(e);
218
+ }
219
+ setBusy(false);
220
+ };
221
+ const run = async () => {
222
+ if (!chosen || !card)
223
+ return;
224
+ setBusy(true);
225
+ setFailure(null);
226
+ setTriesLeft(null);
227
+ try {
228
+ const r = obj(await pageCalls.run(api, chosen.id, card.routineRunId, card.hash, needsCode(card.plan.method) ? code : undefined));
229
+ if (r["ok"] === false) {
230
+ setFailure(str(obj(r["error"])["code"], "routine.failed"));
231
+ setTriesLeft(typeof r["triesLeft"] === "number" ? num(r["triesLeft"]) : null);
232
+ }
233
+ else {
234
+ setResult(str(r["text"]) || t("routine.done"));
235
+ setCard(null);
236
+ }
237
+ }
238
+ catch (e) {
239
+ failed(e);
240
+ }
241
+ setCode("");
242
+ setBusy(false);
243
+ };
244
+ let body;
245
+ if (!chosen) {
246
+ body = (_jsxs(_Fragment, { children: [_jsx("h4", { children: t("routine.list") }), _jsx("ul", { className: "g9a-routines__list", children: routines === null ? null : routines.length === 0 ? _jsx("li", { className: "g9a-note g9a-empty", children: t("routine.empty") })
247
+ : routines.map((r) => _jsx("li", { children: _jsx("button", { type: "button", className: "g9a-routines__choose", "data-id": r.id, onClick: () => choose(r), children: r.title || r.id }) }, r.id)) })] }));
248
+ }
249
+ else {
250
+ const plan = card?.plan;
251
+ body = (_jsxs(_Fragment, { children: [_jsx("div", { className: "g9a-row", children: _jsx("button", { type: "button", className: "g9a-routines__back", onClick: () => choose(null), children: t("routine.back") }) }), _jsx("h4", { children: chosen.title || chosen.id }), result !== null ? _jsx("p", { className: "g9a-note g9a-routines__result", role: "status", children: result })
252
+ : report ? _jsx("div", { className: "g9a-routines__report", children: report.map((b, i) => _jsx(BlockView, { block: b }, i)) })
253
+ : plan ? (_jsxs("div", { className: cls(ui, "card.approval"), "data-routine-card": plan.id, children: [_jsx("h3", { children: plan.readOnly ? t("card.readonly_routine") : plan.title }), plan.warning ? _jsx("p", { className: "g9a-warning", role: "note", children: t("card.tainted") }) : null, _jsx("ol", { children: plan.steps.map((s) => (_jsxs("li", { className: cls(ui, "card.approval.step"), children: [s.text, s.undoable ? null : _jsxs("span", { className: "g9a-irreversible", children: [" (", t("card.irreversible"), ")"] }), s.facts.map((f, i) => _jsx("div", { className: cls(ui, "card.approval.fact"), children: say(f.key, f.args) }, i)), s.diff.map((d, i) => _jsx("div", { className: cls(ui, "card.approval.fact"), children: say(d.name, d.args) + ": " + (d.before ?? "—") + " ← " + (d.after ?? "—") }, "d" + String(i)))] }, s.index))) }), needsCode(plan.method) ? _jsx(PinPad, { label: t("card.code"), value: code, onInput: setCode }) : null, failure ? _jsx("p", { className: "g9a-note", role: "alert", "data-code": failure, children: (failure === "confirm.waiting" ? t("card.waiting") : t("routine.failed")) + (triesLeft !== null ? " · " + t("card.tries_left", { count: triesLeft }) : "") }) : null, _jsxs("div", { className: "g9a-row", children: [_jsx("button", { type: "button", className: cls(ui, "card.approval.confirm"), disabled: busy || (needsCode(plan.method) && code.length === 0), onClick: () => void run(), children: t("card.confirm") }), _jsx("button", { type: "button", className: cls(ui, "card.approval.refuse"), disabled: busy, onClick: () => { setCard(null); setFailure(null); }, children: t("card.refuse") })] })] })) : (_jsxs("form", { className: "g9a-routines__form", noValidate: true, onSubmit: (e) => { e.preventDefault(); void preview(); }, children: [chosen.slots.map((slot) => {
254
+ const st = stateOf(slot);
255
+ return (_jsxs("div", { className: "g9a-routines__slot", "data-slot": slot.name, "data-field": slot.field, "data-state": st, children: [slot.field === "pick" ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "g9a-routines__label", children: labelOf(slot) }), _jsx(Picker, { slot: slot, label: labelOf(slot), picked: picks.get(slot.name) ?? null, onPick: (p) => setPicks((m) => {
256
+ const next = new Map(m);
257
+ if (p)
258
+ next.set(slot.name, p);
259
+ else
260
+ next.delete(slot.name);
261
+ return next;
262
+ }) })] })) : (_jsxs(_Fragment, { children: [_jsx("label", { htmlFor: "g9a-slot-" + slot.name, children: labelOf(slot) }), _jsx("input", { id: "g9a-slot-" + slot.name, value: textOf(slot.name), inputMode: slot.field === "number" || slot.field === "money" ? "decimal" : undefined, "aria-invalid": st !== "ok", onChange: (e) => { const v = e.currentTarget.value; setTyped((m) => new Map(m).set(slot.name, v)); } })] })), st !== "ok" ? _jsx("span", { className: "g9a-note", "data-bad": "true", children: t(st === "missing" ? "routine.missing" : "routine.invalid") }) : null] }, slot.name));
263
+ }), failure ? _jsx("p", { className: "g9a-note", role: "alert", "data-code": failure, children: t("routine.failed") }) : null, _jsx("div", { className: "g9a-row", children: _jsx("button", { type: "submit", className: "g9a-routines__preview", disabled: busy, children: t("routine.preview") }) })] }))] }));
264
+ }
265
+ return (_jsxs("div", { className: cls(ui, "panel.body") + " g9a-routines", "data-page": "routines", children: [loadFailed ? _jsx("p", { className: "g9a-note", role: "alert", children: t("error.network") }) : null, body] }));
266
+ }
267
+ const pageOf = (name, kind) => swappable(name, (props) => _jsx(Page, { ...props, kind: kind }));
268
+ export const History = swappable("History", HistoryBody);
269
+ export const Abilities = pageOf("Abilities", "abilities");
270
+ export const KnowledgePage = pageOf("KnowledgePage", "knowledge");
271
+ export const LearnedPage = pageOf("LearnedPage", "learned");
272
+ export const FindingsPage = pageOf("FindingsPage", "findings");
273
+ export const RoutineWizard = swappable("RoutineWizard", RoutineBody);
274
+ export const ActionsPage = pageOf("ActionsPage", "actions");
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The conversation's parts for React DOM, each exported on its own so a host can compose its own panel: a message, the
3
+ * work card, the composer, the model picker, the PDF button, the small chips, the thinking orb and the stages.
4
+ */
5
+ import type { ReactNode } from "react";
6
+ import type { AssistantState, MessageView, PlanView, Provenance, RunView } from "@g9tm/aiassistant";
7
+ import type { Part } from "./context.js";
8
+ /** Reveals an answer that arrived in front of the person over about 1.5 s; history and reduced motion show it whole. */
9
+ export declare function RevealText(props: {
10
+ text: string;
11
+ reveal?: boolean;
12
+ }): ReactNode;
13
+ export type SmallKind = "provenance" | "mode" | "usage";
14
+ /** Small parts used across the components: the provenance chip, the offline banner and the usage chip. */
15
+ export declare function Small(props: {
16
+ kind: SmallKind;
17
+ provenance?: Provenance | null;
18
+ state?: AssistantState | null;
19
+ }): ReactNode;
20
+ /** The thinking orb: transform and opacity only; static with reduced motion. */
21
+ export declare const ThinkingOrb: Part<Record<string, never>>;
22
+ /** Named stages lit by the run's real stage events (a pipeline's roles too, by the names given); never a show of thinking. */
23
+ export declare const StagesThinking: Part<{
24
+ run: RunView;
25
+ names?: Record<string, string>;
26
+ }>;
27
+ /**
28
+ * "Working": the run's real stages (from its stage events), the progress line, tools, the clock, stop; after 40 s,
29
+ * "still working". The clock starts again when another run comes into the same card.
30
+ */
31
+ export declare function WorkCard(props: {
32
+ run: RunView;
33
+ }): ReactNode;
34
+ /** One message: its text (revealed only when it arrived in front of the person), blocks, card, provenance and feedback. */
35
+ export declare function Message(props: {
36
+ message: MessageView;
37
+ plans: ReadonlyMap<string, PlanView>;
38
+ runId: string | null;
39
+ }): ReactNode;
40
+ export interface ComposerProps {
41
+ busy: boolean;
42
+ attachments: {
43
+ id: string;
44
+ name: string;
45
+ kind: string;
46
+ }[];
47
+ placeholder?: string | undefined;
48
+ }
49
+ /** The composer: input, attach (only when the host can pick a file), mic (only when the host or the server can dictate), send or stop. */
50
+ export declare function Composer(props: ComposerProps): ReactNode;
51
+ /**
52
+ * The model and thinking effort for what the person sends next (`assistant.model`, kept on the conversation by the
53
+ * server). Drawn only where the host lets the person choose (`GET models` says `choose`); "automatic" leaves it to
54
+ * the route. A model that cannot answer now is listed but cannot be picked.
55
+ */
56
+ export declare function ModelPicker(props: {
57
+ efforts?: readonly string[];
58
+ }): ReactNode;
59
+ /**
60
+ * "Download PDF" of the open conversation, once it has messages: the server's signed link (ten minutes), opened by the
61
+ * host. Busy while the link is asked for; a notice if it could not be made. Hidden when the host cannot open links.
62
+ */
63
+ export declare const PdfButton: Part<Record<string, never>>;