@g9tm/aiassistant-react 0.0.0-stage → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -2
- package/dist/admin.d.ts +10 -0
- package/dist/admin.js +191 -0
- package/dist/blocks.d.ts +36 -0
- package/dist/blocks.js +112 -0
- package/dist/browser.d.ts +16 -0
- package/dist/browser.js +80 -0
- package/dist/cards.d.ts +19 -0
- package/dist/cards.js +58 -0
- package/dist/context.d.ts +46 -0
- package/dist/context.js +68 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +12 -0
- package/dist/pages.d.ts +41 -0
- package/dist/pages.js +274 -0
- package/dist/parts.d.ts +63 -0
- package/dist/parts.js +200 -0
- package/dist/slots.d.ts +24 -0
- package/dist/slots.js +42 -0
- package/dist/styles.d.ts +5 -0
- package/dist/styles.js +105 -0
- package/dist/surfaces.d.ts +68 -0
- package/dist/surfaces.js +138 -0
- package/dist/theme.d.ts +10 -0
- package/dist/theme.js +22 -0
- package/package.json +42 -3
package/README.md
CHANGED
|
@@ -1,3 +1,35 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @g9tm/aiassistant-react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
React DOM components for the G9 AI assistant, drawn from the headless client `@g9tm/aiassistant`, with the same part
|
|
4
|
+
names and the same ways to customise as the Svelte and ReactLynx packages. React 18 or later.
|
|
5
|
+
|
|
6
|
+
- Surfaces and parts: `AssistantRoot`, `AssistantChat`, `AssistantPanel` in six layouts (`sheet`, `side`, `fullscreen`,
|
|
7
|
+
`inline`, `card`, `compact`, or `auto` by the container's width), `MessageList`, `Message`, `Composer`, `WorkCard`,
|
|
8
|
+
`ModelPicker`, `PdfButton`, `BlockView`, `Chart`, `ApprovalCard` and `Cards`.
|
|
9
|
+
- Pages: `History`, `Abilities`, `KnowledgePage`, `LearnedPage`, `FindingsPage`, `RoutineWizard`, `ActionsPage`
|
|
10
|
+
(or `Page` with a `kind`). Small surfaces: `Surfaces` with `kind` `hero`, `bar-button` or `ask-about`.
|
|
11
|
+
- Customising: theme tokens as CSS variables (`--g9a-*`, light and dark), per-part classes and styles, `unstyled`
|
|
12
|
+
(structure and class names only, no sheet), and replaced components by name through `components` of `AssistantRoot`;
|
|
13
|
+
the replacement gets the same props plus the library's own as `Default`. Block types (and the host's `x:*` blocks)
|
|
14
|
+
through `components.Block`.
|
|
15
|
+
- The panel: Escape closes it, Alt+A (by key position) toggles it, and focus goes back to what opened it. Give `open`
|
|
16
|
+
and `onOpenChange` to hold its state yourself.
|
|
17
|
+
- `browserHost()` is a ready host for a plain browser app.
|
|
18
|
+
- `@g9tm/aiassistant-react/admin`: the manager's page as a separate entry, loaded only by managers.
|
|
19
|
+
|
|
20
|
+
```tsx
|
|
21
|
+
import { createAssistant } from "@g9tm/aiassistant";
|
|
22
|
+
import { AssistantPanel, AssistantRoot, browserHost } from "@g9tm/aiassistant-react";
|
|
23
|
+
|
|
24
|
+
const assistant = createAssistant(browserHost({ locale: "fa", headers: () => ({ Authorization: "Bearer " + token() }) }));
|
|
25
|
+
|
|
26
|
+
export function App() {
|
|
27
|
+
return (
|
|
28
|
+
<AssistantRoot assistant={assistant}>
|
|
29
|
+
<AssistantPanel layout="auto" />
|
|
30
|
+
</AssistantRoot>
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Part of the G9 AI assistant library. Documentation: see the guides that ship with the library.
|
package/dist/admin.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The manager's pages for React DOM, a separate entry (`@g9tm/aiassistant-react/admin`), a lazy chunk only managers
|
|
3
|
+
* load: capabilities, models, connections, usage, audit, suggestions and gates, with a scope picker that says where a
|
|
4
|
+
* new provider or server goes (this app, or the whole installation). The logic is the core's; this file only draws.
|
|
5
|
+
*/
|
|
6
|
+
import type { ReactNode } from "react";
|
|
7
|
+
/** The manager's page: each group loads when its tab opens; models and connections ask where a new entry goes. */
|
|
8
|
+
export declare function AdminPage(props: {
|
|
9
|
+
onOpen?: (id: string) => void;
|
|
10
|
+
}): ReactNode;
|
package/dist/admin.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* The manager's pages for React DOM, a separate entry (`@g9tm/aiassistant-react/admin`), a lazy chunk only managers
|
|
4
|
+
* load: capabilities, models, connections, usage, audit, suggestions and gates, with a scope picker that says where a
|
|
5
|
+
* new provider or server goes (this app, or the whole installation). The logic is the core's; this file only draws.
|
|
6
|
+
*/
|
|
7
|
+
import { useEffect, useState } from "react";
|
|
8
|
+
import { faDigits, item } from "@g9tm/aiassistant";
|
|
9
|
+
import { AdminClient, adminTexts, parseRoute } from "@g9tm/aiassistant/admin";
|
|
10
|
+
import { cls, useUi } from "./context.js";
|
|
11
|
+
import { Page } from "./pages.js";
|
|
12
|
+
function useAdmin() {
|
|
13
|
+
const ui = useUi();
|
|
14
|
+
return { admin: new AdminClient(ui.assistant.api), t: adminTexts(ui.texts).t, locale: ui.texts.locale };
|
|
15
|
+
}
|
|
16
|
+
const failText = (e) => (e instanceof Error ? e.message : "error.network");
|
|
17
|
+
function Failed(props) {
|
|
18
|
+
return props.error ? _jsx("p", { className: "g9a-note", role: "alert", children: props.t("error.network") }) : null;
|
|
19
|
+
}
|
|
20
|
+
const FIELDS = [
|
|
21
|
+
["maxRounds", "admin.max_rounds"], ["perMinute", "admin.per_minute"], ["perPersonPerDay", "admin.per_person_day"],
|
|
22
|
+
["perTenantPerDay", "admin.per_space_day"], ["monthlyTokenBudget", "admin.monthly_tokens"],
|
|
23
|
+
];
|
|
24
|
+
/** Capabilities as they run now; a manager changes the route, the limits or the switch, and runs the entry-test probes. */
|
|
25
|
+
function AdminCapabilities() {
|
|
26
|
+
const { admin, t } = useAdmin();
|
|
27
|
+
const [list, setList] = useState([]);
|
|
28
|
+
const [probes, setProbes] = useState([]);
|
|
29
|
+
const [routes, setRoutes] = useState(new Map());
|
|
30
|
+
const [error, setError] = useState(null);
|
|
31
|
+
const [results, setResults] = useState([]);
|
|
32
|
+
const [busy, setBusy] = useState(false);
|
|
33
|
+
useEffect(() => {
|
|
34
|
+
admin.capabilities().then((r) => { setList(r.capabilities); setProbes(r.probes); setRoutes(new Map(r.capabilities.map((c) => [c.id, c.route.join(" > ")]))); setError(null); }, (e) => setError(failText(e)));
|
|
35
|
+
}, []);
|
|
36
|
+
const replace = (c) => { setList((xs) => xs.map((x) => (x.id === c.id ? c : x))); setRoutes((m) => new Map(m).set(c.id, c.route.join(" > "))); };
|
|
37
|
+
const edit = (c) => setList((xs) => xs.map((x) => (x.id === c.id ? c : x)));
|
|
38
|
+
const save = (c) => { admin.setCapability(c.id, { route: parseRoute(routes.get(c.id) ?? ""), limits: c.limits, enabled: c.enabled }).then(replace, (e) => setError(failText(e))); };
|
|
39
|
+
const reset = (c) => { admin.resetCapability(c.id).then(replace, (e) => setError(failText(e))); };
|
|
40
|
+
const probeAll = async (c) => {
|
|
41
|
+
const model = item(c.route, 0);
|
|
42
|
+
if (!model || busy)
|
|
43
|
+
return;
|
|
44
|
+
setBusy(true);
|
|
45
|
+
setResults([]);
|
|
46
|
+
for (const p of probes) {
|
|
47
|
+
// one probe per request: each shows as it ends
|
|
48
|
+
const r = await admin.probe(p, model).catch(() => ({ probe: p, model, quality: "error", rightKind: false, tokensIn: 0, ms: 0, head: null, error: "error.network" }));
|
|
49
|
+
setResults((xs) => [...xs, r]);
|
|
50
|
+
}
|
|
51
|
+
setBusy(false);
|
|
52
|
+
};
|
|
53
|
+
return (_jsxs(_Fragment, { children: [_jsx(Failed, { error: error, t: t }), list.length === 0 && !error ? _jsx("p", { className: "g9a-note", children: t("admin.empty") }) : null, list.map((c) => (_jsxs("section", { className: "g9a-admin-capability", "data-overridden": c.overridden, children: [_jsxs("h4", { children: [c.id + " · " + c.kind, c.overridden ? _jsxs(_Fragment, { children: [" \u00B7 ", _jsx("small", { children: t("admin.overridden") })] }) : null] }), _jsxs("label", { children: [t("admin.enabled"), " ", _jsx("input", { type: "checkbox", checked: c.enabled, onChange: (e) => edit({ ...c, enabled: e.currentTarget.checked }) })] }), _jsxs("label", { children: [t("admin.route"), " ", _jsx("input", { dir: "ltr", value: routes.get(c.id) ?? "", onChange: (e) => { const v = e.currentTarget.value; setRoutes((m) => new Map(m).set(c.id, v)); } })] }), FIELDS.map(([key, label]) => (_jsxs("label", { children: [t(label), " ", _jsx("input", { type: "number", min: "0", dir: "ltr", value: c.limits[key], onChange: (e) => edit({ ...c, limits: { ...c.limits, [key]: Number(e.currentTarget.value) } }) })] }, key))), _jsxs("div", { children: [_jsx("button", { type: "button", onClick: () => save(c), children: t("admin.save") }), c.overridden ? _jsx("button", { type: "button", onClick: () => reset(c), children: t("admin.reset") }) : null, probes.length > 0 && c.route.length > 0 ? _jsx("button", { type: "button", disabled: busy, onClick: () => void probeAll(c), children: t("admin.probe") }) : null] })] }, c.id))), results.length > 0 ? (_jsxs(_Fragment, { children: [_jsx("h4", { children: t("admin.probe") }), _jsx("ul", { children: results.map((r) => _jsx("li", { "data-ok": r.rightKind, children: (r.rightKind ? "✓" : "✗") + " " + r.probe + " · " + r.quality + " · " + String(r.tokensIn) + " · " + String(r.ms) + " ms" + (r.error ? " · " + r.error : "") }, r.probe)) })] })) : null] }));
|
|
54
|
+
}
|
|
55
|
+
/** The usage ledger: the model-free rate, by capability and model, the windows, the latest calls and a run's black box. */
|
|
56
|
+
function AdminUsage() {
|
|
57
|
+
const { admin, t, locale } = useAdmin();
|
|
58
|
+
const [days, setDays] = useState(7);
|
|
59
|
+
const [usage, setUsage] = useState(null);
|
|
60
|
+
const [windows, setWindows] = useState([]);
|
|
61
|
+
const [calls, setCalls] = useState([]);
|
|
62
|
+
const [box, setBox] = useState(null);
|
|
63
|
+
const [error, setError] = useState(null);
|
|
64
|
+
const pct = (x) => { const s = String(Math.round(x * 100)) + "%"; return locale === "fa" ? faDigits(s) : s; };
|
|
65
|
+
useEffect(() => {
|
|
66
|
+
Promise.all([admin.usage(days), admin.windows().catch(() => []), admin.calls(days, 50)]).then(([u, w, c]) => { setUsage(u); setWindows(w); setCalls(c); setError(null); }, (e) => setError(failText(e)));
|
|
67
|
+
}, [days]);
|
|
68
|
+
const open = (runId) => { admin.timeline(runId).then((r) => setBox({ runId, lines: r.lines }), () => setBox(null)); };
|
|
69
|
+
const group = (title, groups) => (_jsxs(_Fragment, { children: [_jsx("h4", { children: t(title) }), _jsx("table", { children: _jsx("tbody", { children: groups.map((g) => (_jsxs("tr", { children: [_jsx("th", { scope: "row", dir: "ltr", children: g.id }), _jsx("td", { children: g.rows }), _jsx("td", { children: pct(g.rows === 0 ? 0 : g.withoutModel / g.rows) }), _jsx("td", { children: t("admin.tokens", { in: g.tokensIn, cached: g.tokensCached, out: g.tokensOut }) }), _jsx("td", { children: String(g.avgMs) + " ms" }), _jsx("td", { children: g.errors > 0 ? "✗ " + String(g.errors) : "" })] }, g.id))) }) })] }));
|
|
70
|
+
return (_jsxs(_Fragment, { children: [_jsx(Failed, { error: error, t: t }), _jsx("label", { children: _jsx("select", { value: days, onChange: (e) => setDays(Number(e.currentTarget.value)), children: [1, 7, 30, 90].map((d) => _jsx("option", { value: d, children: d }, d)) }) }), usage ? (_jsxs(_Fragment, { children: [_jsxs("p", { children: [_jsx("strong", { children: t("admin.without_model", { percent: pct(usage.withoutModelRate) }) }), " · " + t("admin.rows", { count: usage.rows })] }), group("admin.capabilities", usage.capabilities), group("admin.route", usage.models)] })) : null, windows.length > 0 ? (_jsxs(_Fragment, { children: [_jsx("h4", { children: t("admin.windows") }), windows.flatMap((s) => s.windows.map((w) => _jsx("p", { className: "g9a-usage-chip", style: { ["--g9a-usage"]: String(w.usedPercent) + "%" }, children: s.backend + " · " + w.name + " · " + t("usage.left", { percent: pct(1 - w.usedPercent / 100) }) }, s.backend + w.name)))] })) : null, _jsx("h4", { children: t("admin.calls") }), _jsx("ul", { children: calls.map((c) => (_jsxs("li", { "data-outcome": c.outcome, children: [c.runId ? _jsx("button", { type: "button", onClick: () => open(c.runId ?? ""), children: c.capability + " · " + c.role + " #" + String(c.round) }) : c.capability + " · " + c.role, " · ", _jsx("span", { dir: "ltr", children: c.model ?? "—" }), " · " + c.outcome + " · " + String(c.tokensIn) + "/" + String(c.tokensOut) + " · " + String(c.ms) + " ms"] }, c.id))) }), box ? (_jsxs(_Fragment, { children: [_jsxs("h4", { children: [t("admin.timeline") + " · ", _jsx("span", { dir: "ltr", children: box.runId })] }), _jsx("ol", { children: box.lines.map((l, i) => _jsxs("li", { "data-kind": l.kind, "data-bad": l.bad, children: [_jsx("time", { children: new Date(l.at).toLocaleTimeString(locale) }), " " + l.title + " ", _jsx("span", { dir: "ltr", children: l.detail })] }, i)) })] })) : null] }));
|
|
71
|
+
}
|
|
72
|
+
/** The audit, newest first: steps run, cards answered, undos, gates and settings changed. */
|
|
73
|
+
function AdminAudit() {
|
|
74
|
+
const { admin, t, locale } = useAdmin();
|
|
75
|
+
const [rows, setRows] = useState([]);
|
|
76
|
+
const [error, setError] = useState(null);
|
|
77
|
+
useEffect(() => { admin.audit(200).then((r) => { setRows(r); setError(null); }, (e) => setError(failText(e))); }, []);
|
|
78
|
+
return (_jsxs(_Fragment, { children: [_jsx(Failed, { error: error, t: t }), rows.length === 0 && !error ? _jsx("p", { className: "g9a-note", children: t("admin.empty") }) : null, _jsx("table", { children: _jsx("tbody", { children: rows.map((a, i) => (_jsxs("tr", { "data-tainted": a.tainted, children: [_jsx("td", { children: _jsx("time", { children: new Date(a.at).toLocaleString(locale) }) }), _jsx("td", { children: a.user }), _jsx("td", { children: a.actor }), _jsx("td", { dir: "ltr", children: a.action }), _jsx("td", { dir: "ltr", children: a.tool ?? "" }), _jsx("td", { dir: "ltr", children: a.decision ?? "" }), _jsx("td", { dir: "ltr", children: a.outcome ?? "" })] }, i))) }) })] }));
|
|
79
|
+
}
|
|
80
|
+
/** The "Models" group: providers (from a preset, a key sent once, a test), the backends with their windows, and the gateway's keys. */
|
|
81
|
+
function AdminModels(props) {
|
|
82
|
+
const { admin, t, locale } = useAdmin();
|
|
83
|
+
const [providers, setProviders] = useState([]);
|
|
84
|
+
const [presets, setPresets] = useState([]);
|
|
85
|
+
const [backends, setBackends] = useState([]);
|
|
86
|
+
const [keys, setKeys] = useState([]);
|
|
87
|
+
const [log, setLog] = useState({ count: 0, errors: 0, tokens: 0 });
|
|
88
|
+
const [preset, setPreset] = useState("");
|
|
89
|
+
const [newId, setNewId] = useState("");
|
|
90
|
+
const [secret, setSecret] = useState("");
|
|
91
|
+
const [keyName, setKeyName] = useState("");
|
|
92
|
+
const [shown, setShown] = useState(null);
|
|
93
|
+
const [error, setError] = useState(null);
|
|
94
|
+
const load = async () => {
|
|
95
|
+
try {
|
|
96
|
+
const p = await admin.providers();
|
|
97
|
+
setProviders(p.providers);
|
|
98
|
+
setPresets(p.presets);
|
|
99
|
+
setBackends(await admin.backends().catch(() => []));
|
|
100
|
+
setKeys(await admin.gatewayKeys().catch(() => []));
|
|
101
|
+
setLog(await admin.gatewayRequests(1).catch(() => ({ count: 0, errors: 0, tokens: 0, rows: [] })));
|
|
102
|
+
setError(null);
|
|
103
|
+
}
|
|
104
|
+
catch (e) {
|
|
105
|
+
setError(failText(e));
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
useEffect(() => { void load(); }, []);
|
|
109
|
+
const add = async () => {
|
|
110
|
+
const id = (newId || preset).trim();
|
|
111
|
+
if (!id)
|
|
112
|
+
return;
|
|
113
|
+
try {
|
|
114
|
+
await admin.saveProvider(id, { preset: preset || undefined, secret: secret || undefined, level: props.level });
|
|
115
|
+
setSecret("");
|
|
116
|
+
setNewId("");
|
|
117
|
+
await load();
|
|
118
|
+
}
|
|
119
|
+
catch (e) {
|
|
120
|
+
setError(failText(e));
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
const test = (id) => { admin.testProvider(id).then((p) => setProviders((xs) => xs.map((x) => (x.id === id ? p : x))), (e) => setError(failText(e))); };
|
|
124
|
+
const makeKey = async () => {
|
|
125
|
+
if (!keyName.trim())
|
|
126
|
+
return;
|
|
127
|
+
try {
|
|
128
|
+
setShown(await admin.createGatewayKey(keyName.trim()));
|
|
129
|
+
setKeyName("");
|
|
130
|
+
await load();
|
|
131
|
+
}
|
|
132
|
+
catch (e) {
|
|
133
|
+
setError(failText(e));
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
return (_jsxs(_Fragment, { children: [_jsx(Failed, { error: error, t: t }), _jsx("h4", { children: t("admin.providers") }), _jsx("ul", { children: providers.map((p) => (_jsxs("li", { "data-state": p.state, children: [_jsx("strong", { dir: "ltr", children: p.id }), " · " + p.state + " · " + p.level + " · ", _jsx("span", { dir: "ltr", children: p.route }), p.defaultModel ? _jsxs(_Fragment, { children: [" · ", _jsx("span", { dir: "ltr", children: p.defaultModel })] }) : null, " · " + String(p.models.length), _jsx("button", { type: "button", onClick: () => test(p.id), children: t("admin.test") }), _jsx("button", { type: "button", onClick: () => { void admin.deleteProvider(p.id).catch(() => undefined).then(load); }, children: t("admin.remove") })] }, p.id))) }), _jsxs("form", { className: "g9a-row", onSubmit: (e) => { e.preventDefault(); void add(); }, children: [_jsxs("select", { value: preset, "aria-label": t("admin.providers"), onChange: (e) => setPreset(e.currentTarget.value), children: [_jsx("option", { value: "", children: "\u2014" }), presets.map((x) => _jsx("option", { value: x.id, children: x.id }, x.id))] }), _jsx("input", { dir: "ltr", value: newId, placeholder: "id", "aria-label": "id", onChange: (e) => setNewId(e.currentTarget.value) }), _jsx("input", { dir: "ltr", type: "password", value: secret, placeholder: t("admin.secret"), "aria-label": t("admin.secret"), autoComplete: "off", onChange: (e) => setSecret(e.currentTarget.value) }), _jsx("button", { type: "submit", children: t("admin.add") })] }), backends.length > 0 ? (_jsxs(_Fragment, { children: [_jsx("h4", { children: t("admin.backends") }), _jsx("ul", { children: backends.map((b) => (_jsxs("li", { "data-state": b.state, children: [_jsx("span", { dir: "ltr", children: b.id }), " · " + b.state + (b.until ? " · " + new Date(b.until).toLocaleString(locale) : "") + (b.usage?.windows ?? []).map((w) => " · " + w.name + " " + String(Math.round(w.usedPercent)) + "%").join("")] }, b.id))) })] })) : null, _jsx("h4", { children: t("admin.gateway") }), _jsx("p", { children: String(log.count) + " · ✗ " + String(log.errors) + " · " + String(log.tokens) }), shown ? _jsxs("p", { className: "g9a-note", children: [t("admin.key_once") + " ", _jsx("code", { dir: "ltr", children: shown })] }) : null, _jsx("ul", { children: keys.map((k) => (_jsxs("li", { "data-revoked": k.revoked, children: [k.name + (k.lastUsedAt ? " · " + new Date(k.lastUsedAt).toLocaleString(locale) : ""), k.revoked ? null : _jsx("button", { type: "button", onClick: () => { void admin.revokeGatewayKey(k.id).catch(() => undefined).then(load); }, children: t("admin.remove") })] }, k.id))) }), _jsxs("form", { className: "g9a-row", onSubmit: (e) => { e.preventDefault(); void makeKey(); }, children: [_jsx("input", { value: keyName, placeholder: t("admin.gateway"), "aria-label": t("admin.gateway"), onChange: (e) => setKeyName(e.currentTarget.value) }), _jsx("button", { type: "submit", children: t("admin.add") })] })] }));
|
|
137
|
+
}
|
|
138
|
+
/** The "Connections" group: other MCP servers (an address, a way in, a secret sent once, a test listing the tools). */
|
|
139
|
+
function AdminConnections(props) {
|
|
140
|
+
const { admin, t } = useAdmin();
|
|
141
|
+
const [client, setClient] = useState(true);
|
|
142
|
+
const [servers, setServers] = useState([]);
|
|
143
|
+
const [tested, setTested] = useState(null);
|
|
144
|
+
const [id, setId] = useState("");
|
|
145
|
+
const [url, setUrl] = useState("");
|
|
146
|
+
const [auth, setAuth] = useState("none");
|
|
147
|
+
const [secret, setSecret] = useState("");
|
|
148
|
+
const [error, setError] = useState(null);
|
|
149
|
+
const load = () => admin.mcpServers().then((r) => { setClient(r.client); setServers(r.servers); setError(null); }, (e) => setError(failText(e)));
|
|
150
|
+
useEffect(() => { void load(); }, []);
|
|
151
|
+
const add = async () => {
|
|
152
|
+
if (!id.trim() || !url.trim())
|
|
153
|
+
return;
|
|
154
|
+
try {
|
|
155
|
+
await admin.saveMcpServer(id.trim(), { url: url.trim(), auth, secret: secret || undefined, level: props.level });
|
|
156
|
+
setId("");
|
|
157
|
+
setUrl("");
|
|
158
|
+
setSecret("");
|
|
159
|
+
await load();
|
|
160
|
+
}
|
|
161
|
+
catch (e) {
|
|
162
|
+
setError(failText(e));
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
return (_jsxs(_Fragment, { children: [_jsx(Failed, { error: error, t: t }), _jsx("h4", { children: t("admin.mcp") }), client ? null : _jsx("p", { className: "g9a-note", children: t("admin.no_client") }), _jsx("ul", { children: servers.map((s) => (_jsxs("li", { "data-enabled": s.enabled, children: [_jsx("strong", { dir: "ltr", children: s.id }), " · ", _jsx("span", { dir: "ltr", children: s.url }), " · " + s.auth + (s.hasSecret ? " 🔒" : "") + " · " + s.level + " · ", _jsx("span", { dir: "ltr", children: s.route }), _jsx("button", { type: "button", onClick: () => { admin.testMcpServer(s.id).catch(() => ({ ok: false, error: "error.network", tools: [] })).then((r) => setTested({ id: s.id, ...r }), () => undefined); }, children: t("admin.test") }), _jsx("button", { type: "button", onClick: () => { void admin.deleteMcpServer(s.id).catch(() => undefined).then(load); }, children: t("admin.remove") })] }, s.id))) }), tested ? (_jsxs(_Fragment, { children: [_jsx("p", { children: tested.id + ": " + (tested.ok ? "✓" : "✗ " + (tested.error ?? "")) }), _jsx("ul", { children: tested.tools.map((x) => _jsx("li", { dir: "ltr", "data-allowed": x.allowed, children: x.name + " " + (x.readOnly ? "(read)" : "(change)") }, x.name)) })] })) : null, _jsxs("form", { className: "g9a-row", onSubmit: (e) => { e.preventDefault(); void add(); }, children: [_jsx("input", { dir: "ltr", value: id, placeholder: "name", "aria-label": "name", onChange: (e) => setId(e.currentTarget.value) }), _jsx("input", { dir: "ltr", value: url, placeholder: "https://\u2026/mcp", "aria-label": "url", onChange: (e) => setUrl(e.currentTarget.value) }), _jsxs("select", { value: auth, "aria-label": "auth", onChange: (e) => setAuth(e.currentTarget.value), children: [_jsx("option", { value: "none", children: "none" }), _jsx("option", { value: "bearer", children: "bearer" })] }), auth !== "none" ? _jsx("input", { dir: "ltr", type: "password", value: secret, placeholder: t("admin.secret"), "aria-label": t("admin.secret"), autoComplete: "off", onChange: (e) => setSecret(e.currentTarget.value) }) : null, _jsx("button", { type: "submit", children: t("admin.add") })] })] }));
|
|
166
|
+
}
|
|
167
|
+
const STATES = ["new", "seen", "planned", "done", "dismissed"];
|
|
168
|
+
/** The agents' suggestions (a repeat counts on one row), marked by the manager; the two knowledge budgets as bars above. */
|
|
169
|
+
function AdminFeedback() {
|
|
170
|
+
const { admin, t } = useAdmin();
|
|
171
|
+
const [rows, setRows] = useState([]);
|
|
172
|
+
const [budget, setBudget] = useState(null);
|
|
173
|
+
const load = async () => {
|
|
174
|
+
setRows((await admin.agentFeedback().catch(() => ({ fresh: 0, rows: [] }))).rows);
|
|
175
|
+
setBudget(await admin.budget().catch(() => null));
|
|
176
|
+
};
|
|
177
|
+
useEffect(() => { void load(); }, []);
|
|
178
|
+
return (_jsxs(_Fragment, { children: [budget ? (_jsxs(_Fragment, { children: [_jsx("p", { children: t("admin.budget", { notes: budget.notes, max: budget.maxNotes, chars: budget.pinnedChars, maxChars: budget.maxPinnedChars }) }), _jsx("progress", { max: budget.maxNotes, value: budget.notes }), _jsx("progress", { max: budget.maxPinnedChars, value: budget.pinnedChars })] })) : null, rows.length === 0 ? _jsx("p", { className: "g9a-note", children: t("admin.empty") }) : null, _jsx("ul", { children: rows.map((f) => (_jsxs("li", { "data-status": f.status, children: [_jsx("strong", { children: f.title }), " · " + f.kind + " · ×" + String(f.count), f.detail ? _jsx("p", { children: f.detail }) : null, _jsx("select", { value: f.status, "aria-label": f.title, onChange: (e) => { void admin.setFeedback(f.id, e.currentTarget.value).catch(() => undefined).then(load); }, children: STATES.map((s) => _jsx("option", { value: s, children: s }, s)) })] }, f.id))) })] }));
|
|
179
|
+
}
|
|
180
|
+
const TABS = ["capabilities", "models", "connections", "usage", "audit", "feedback", "gates"];
|
|
181
|
+
/** The manager's page: each group loads when its tab opens; models and connections ask where a new entry goes. */
|
|
182
|
+
export function AdminPage(props) {
|
|
183
|
+
const ui = useUi();
|
|
184
|
+
const { admin, t } = useAdmin();
|
|
185
|
+
const [tab, setTab] = useState("capabilities");
|
|
186
|
+
const [level, setLevel] = useState("app");
|
|
187
|
+
const [chain, setChain] = useState([]);
|
|
188
|
+
useEffect(() => { admin.scopes().then(setChain, () => setChain([])); }, []);
|
|
189
|
+
return (_jsxs("div", { className: cls(ui, "panel.body"), "data-page": "admin", children: [_jsx("div", { role: "tablist", className: "g9a-tabs", children: TABS.map((x) => _jsx("button", { type: "button", role: "tab", "aria-selected": tab === x, onClick: () => setTab(x), children: t("admin." + x) }, x)) }), tab === "models" || tab === "connections" ? (_jsxs("label", { className: "g9a-row", children: [t("admin.scope"), _jsx("select", { value: level, onChange: (e) => setLevel(e.currentTarget.value), children: chain.filter((c) => c.level === "app" || c.level === "general").map((c) => _jsx("option", { value: c.level, children: c.level }, c.level)) })] })) : null, tab === "capabilities" ? _jsx(AdminCapabilities, {}) : tab === "models" ? _jsx(AdminModels, { level: level }) : tab === "connections" ? _jsx(AdminConnections, { level: level })
|
|
190
|
+
: tab === "usage" ? _jsx(AdminUsage, {}) : tab === "audit" ? _jsx(AdminAudit, {}) : tab === "feedback" ? _jsx(AdminFeedback, {}) : _jsx(Page, { kind: "admin", ...(props.onOpen ? { onOpen: props.onOpen } : {}) })] }));
|
|
191
|
+
}
|
package/dist/blocks.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every block type from the core's view model, and the safe text view. The host may replace any block type (its x:*
|
|
3
|
+
* blocks too) through `components.Block`; a block no renderer knows shows its fallback text, never an error or a hole.
|
|
4
|
+
*/
|
|
5
|
+
import type { ReactNode } from "react";
|
|
6
|
+
import type { BlockView as BlockViewModel } from "@g9tm/aiassistant";
|
|
7
|
+
import type { Part } from "./context.js";
|
|
8
|
+
/** The model's text as safe tokens: paragraphs, lists, bold, code, links (https on the host's hosts only). Never HTML. */
|
|
9
|
+
export declare function TextView(props: {
|
|
10
|
+
text: string;
|
|
11
|
+
}): ReactNode;
|
|
12
|
+
export interface CsvButtonProps {
|
|
13
|
+
title?: string | undefined;
|
|
14
|
+
labels: readonly string[];
|
|
15
|
+
rows: readonly (readonly string[])[];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* "Save as CSV" for a table or an export block, through the host's file save (hidden when the host cannot save). The
|
|
19
|
+
* file is the core's: a BOM, every cell quoted, no formula injection. A short notice says whether it was saved.
|
|
20
|
+
*/
|
|
21
|
+
export declare const CsvButton: Part<CsvButtonProps>;
|
|
22
|
+
export type ChartView = Extract<BlockViewModel, {
|
|
23
|
+
type: "chart";
|
|
24
|
+
}>;
|
|
25
|
+
/**
|
|
26
|
+
* The built-in light chart: horizontal bars for rankings, bars and stacks; one or several lines on a time axis; and a
|
|
27
|
+
* donut. A host gives its own chart library by replacing `Chart`, or the whole block with `components.Block.chart`;
|
|
28
|
+
* either gets the same view.
|
|
29
|
+
*/
|
|
30
|
+
export declare const Chart: Part<{
|
|
31
|
+
view: ChartView;
|
|
32
|
+
}>;
|
|
33
|
+
export declare function BlockView(props: {
|
|
34
|
+
block: unknown;
|
|
35
|
+
compact?: boolean;
|
|
36
|
+
}): ReactNode;
|
package/dist/blocks.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* Every block type from the core's view model, and the safe text view. The host may replace any block type (its x:*
|
|
4
|
+
* blocks too) through `components.Block`; a block no renderer knows shows its fallback text, never an error or a hole.
|
|
5
|
+
*/
|
|
6
|
+
import { useState } from "react";
|
|
7
|
+
import { blockView, can, formatNumber, item, obj, parseText, shares } from "@g9tm/aiassistant";
|
|
8
|
+
import { pageTexts, saveCsv } from "@g9tm/aiassistant/pages";
|
|
9
|
+
import { blockOverride, cls, swappable, useUi } from "./context.js";
|
|
10
|
+
/** The model's text as safe tokens: paragraphs, lists, bold, code, links (https on the host's hosts only). Never HTML. */
|
|
11
|
+
export function TextView(props) {
|
|
12
|
+
const ui = useUi();
|
|
13
|
+
const open = (e, href) => {
|
|
14
|
+
if (ui.assistant.host.openUrl) {
|
|
15
|
+
e.preventDefault();
|
|
16
|
+
ui.assistant.host.openUrl(href);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const line = (xs) => xs.map((x, i) => x.kind === "bold" ? _jsx("strong", { children: x.text }, i)
|
|
20
|
+
: x.kind === "code" ? _jsx("code", { children: x.text }, i)
|
|
21
|
+
: x.kind === "link" && x.href ? _jsx("a", { href: x.href, target: "_blank", rel: "noopener noreferrer", onClick: (e) => open(e, x.href ?? ""), children: x.text }, i)
|
|
22
|
+
: _jsx("span", { children: x.text }, i));
|
|
23
|
+
return (_jsx(_Fragment, { children: parseText(props.text, ui.assistant.host.linkHosts ?? []).map((b, i) => b.kind === "paragraph"
|
|
24
|
+
? _jsx("p", { className: "g9a-p", children: line(b.inlines) }, i)
|
|
25
|
+
: b.ordered ? _jsx("ol", { className: "g9a-list", children: b.items.map((it, n) => _jsx("li", { children: line(it) }, n)) }, i)
|
|
26
|
+
: _jsx("ul", { className: "g9a-list", children: b.items.map((it, n) => _jsx("li", { children: line(it) }, n)) }, i)) }));
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* "Save as CSV" for a table or an export block, through the host's file save (hidden when the host cannot save). The
|
|
30
|
+
* file is the core's: a BOM, every cell quoted, no formula injection. A short notice says whether it was saved.
|
|
31
|
+
*/
|
|
32
|
+
export const CsvButton = swappable("CsvButton", (props) => {
|
|
33
|
+
const ui = useUi();
|
|
34
|
+
const t = pageTexts(ui.texts).t;
|
|
35
|
+
const [saved, setSaved] = useState(null);
|
|
36
|
+
const [busy, setBusy] = useState(false);
|
|
37
|
+
if (!can(ui.assistant.host, "save"))
|
|
38
|
+
return null;
|
|
39
|
+
const save = async () => {
|
|
40
|
+
setBusy(true);
|
|
41
|
+
setSaved(await saveCsv(ui.assistant.host, props.title, props.labels, props.rows));
|
|
42
|
+
setBusy(false);
|
|
43
|
+
};
|
|
44
|
+
return (_jsxs("div", { className: "g9a-csv", children: [_jsx("button", { type: "button", className: "g9a-csv__save", disabled: busy, onClick: () => void save(), children: t("csv.save") }), saved !== null ? _jsx("span", { className: "g9a-note", role: "status", "data-saved": saved, children: t(saved ? "csv.saved" : "csv.not_saved") }) : null] }));
|
|
45
|
+
});
|
|
46
|
+
const W = 300;
|
|
47
|
+
const H = 140;
|
|
48
|
+
/**
|
|
49
|
+
* The built-in light chart: horizontal bars for rankings, bars and stacks; one or several lines on a time axis; and a
|
|
50
|
+
* donut. A host gives its own chart library by replacing `Chart`, or the whole block with `components.Block.chart`;
|
|
51
|
+
* either gets the same view.
|
|
52
|
+
*/
|
|
53
|
+
export const Chart = swappable("Chart", (props) => {
|
|
54
|
+
const ui = useUi();
|
|
55
|
+
const v = props.view;
|
|
56
|
+
const fmt = (x) => formatNumber(x, ui.texts.locale);
|
|
57
|
+
const first = v.series[0]?.values ?? [];
|
|
58
|
+
if (v.kind === "hbars" || v.kind === "bars" || v.kind === "stacked") {
|
|
59
|
+
const sh = shares(first);
|
|
60
|
+
return (_jsx("div", { className: "g9a-hbars", role: "img", "aria-label": v.fallbackText, children: v.labels.map((label, i) => (_jsxs("div", { className: cls(ui, "block.chart.bar"), children: [_jsx("span", { className: "g9a-bar-label", children: label }), _jsx("span", { className: "g9a-bar-track", children: _jsx("span", { className: "g9a-bar-fill", style: { inlineSize: String(Math.round((item(sh, i) ?? 0) * 100)) + "%" } }) }), _jsx("span", { className: "g9a-bar-value", children: fmt(item(first, i) ?? 0) })] }, i))) }));
|
|
61
|
+
}
|
|
62
|
+
if (v.kind === "donut") {
|
|
63
|
+
const total = first.reduce((a, b) => a + Math.max(0, b), 0) || 1;
|
|
64
|
+
const p = (f) => (50 + 40 * Math.sin(f * 2 * Math.PI)).toFixed(2) + " " + (50 - 40 * Math.cos(f * 2 * Math.PI)).toFixed(2);
|
|
65
|
+
let at = 0;
|
|
66
|
+
const arcs = first.map((x) => { const from = at; at += Math.max(0, x) / total; return { from, to: Math.min(at, from + 0.9999) }; });
|
|
67
|
+
return (_jsxs(_Fragment, { children: [_jsx("svg", { viewBox: "0 0 100 100", className: "g9a-donut", role: "img", "aria-label": v.fallbackText, children: arcs.map((d, i) => d.to <= d.from ? null : _jsx("path", { "data-index": i, d: "M " + p(d.from) + " A 40 40 0 " + (d.to - d.from > 0.5 ? "1" : "0") + " 1 " + p(d.to) }, i)) }), _jsx("div", { className: "g9a-legend", children: v.labels.map((l, i) => _jsx("span", { "data-index": i, children: l }, i)) })] }));
|
|
68
|
+
}
|
|
69
|
+
const max = Math.max(1, ...v.series.flatMap((s) => s.values));
|
|
70
|
+
const path = (values) => values.map((x, i) => (i === 0 ? "M" : "L") + ((i / Math.max(1, values.length - 1)) * W).toFixed(1) + " " + (H - (x / max) * H).toFixed(1)).join(" ");
|
|
71
|
+
return (_jsxs(_Fragment, { children: [_jsx("svg", { viewBox: "0 0 " + String(W) + " " + String(H), className: cls(ui, "block.chart.line"), role: "img", "aria-label": v.fallbackText, preserveAspectRatio: "none", children: v.series.map((s, i) => _jsx("path", { "data-index": i, d: path(s.values), fill: "none" }, s.name)) }), v.series.length > 1 ? _jsx("div", { className: "g9a-legend", children: v.series.map((s, i) => _jsx("span", { "data-index": i, children: s.name }, s.name)) }) : null] }));
|
|
72
|
+
});
|
|
73
|
+
/** Only the server's own files. */
|
|
74
|
+
const fileUrl = (id) => "/api/assistant/files/" + encodeURIComponent(id);
|
|
75
|
+
export function BlockView(props) {
|
|
76
|
+
const ui = useUi();
|
|
77
|
+
const t = ui.texts.t;
|
|
78
|
+
const v = blockView(props.block, ui.texts.locale, ui.assistant.customBlocks);
|
|
79
|
+
const [open, setOpen] = useState(false);
|
|
80
|
+
const Own = blockOverride(ui, v.type === "custom" ? v.name : v.type);
|
|
81
|
+
if (Own)
|
|
82
|
+
return _jsx(Own, { view: v, block: props.block, compact: props.compact ?? false });
|
|
83
|
+
switch (v.type) {
|
|
84
|
+
case "text": return _jsx("div", { className: cls(ui, "block.text"), children: _jsx(TextView, { text: v.text }) });
|
|
85
|
+
case "callout": return _jsx("div", { className: cls(ui, "block.callout"), "data-tone": v.tone, children: _jsx(TextView, { text: v.text }) });
|
|
86
|
+
case "table": {
|
|
87
|
+
// A table's file has the raw values (the export view of the same rows), not the text drawn for reading.
|
|
88
|
+
const raw = blockView({ ...obj(props.block), type: "export" }, ui.texts.locale);
|
|
89
|
+
const rows = v.rows.slice(0, open ? v.rows.length : v.shown);
|
|
90
|
+
return (_jsxs(_Fragment, { children: [_jsxs("div", { className: cls(ui, "block.table"), children: [v.title ? _jsx("div", { className: "g9a-block-title", children: v.title }) : null, v.asCards || props.compact
|
|
91
|
+
? rows.map((row, r) => (_jsx("dl", { className: cls(ui, "block.table.card"), children: v.columns.map((c, i) => [_jsx("dt", { children: c.label }, c.name + ":t"), _jsx("dd", { "data-kind": c.kind, children: item(row, i) }, c.name + ":d")]) }, r)))
|
|
92
|
+
: (_jsxs("table", { children: [_jsx("thead", { children: _jsx("tr", { children: v.columns.map((c) => _jsx("th", { "data-kind": c.kind, children: c.label }, c.name)) }) }), _jsx("tbody", { children: rows.map((row, r) => _jsx("tr", { children: row.map((x, i) => _jsx("td", { "data-kind": item(v.columns, i)?.kind, children: x }, i)) }, r)) })] })), v.more > 0 && !open ? _jsx("button", { type: "button", className: "g9a-more", onClick: () => setOpen(true), children: t("block.more_rows", { count: v.more }) }) : null] }), raw.type === "export" ? _jsx(CsvButton, { title: v.title, labels: raw.columns.map((c) => c.label), rows: raw.rows }) : null] }));
|
|
93
|
+
}
|
|
94
|
+
case "export":
|
|
95
|
+
return (_jsxs("div", { className: cls(ui, "block") + " g9a-block__export", children: [v.title ? _jsx("div", { className: "g9a-block-title", children: v.title }) : null, can(ui.assistant.host, "save") ? _jsx(CsvButton, { title: v.title, labels: v.columns.map((c) => c.label), rows: v.rows }) : _jsx("div", { children: v.fallbackText })] }));
|
|
96
|
+
case "chart":
|
|
97
|
+
return (_jsxs("div", { className: cls(ui, "block.chart"), children: [v.title ? _jsx("div", { className: "g9a-block-title", children: v.title }) : null, _jsx(Chart, { view: v }), v.fewData ? _jsx("div", { className: "g9a-note", children: t("block.few_data") }) : null] }));
|
|
98
|
+
case "kpi": return _jsx("div", { className: cls(ui, "block.kpi"), children: v.items.map((k, i) => _jsxs("div", { children: [_jsx("span", { children: k.label }), _jsx("strong", { children: k.value })] }, i)) });
|
|
99
|
+
case "steps": return _jsx("ol", { className: cls(ui, "block.steps"), children: v.items.map((s, i) => _jsx("li", { "data-state": s.state, children: s.text }, i)) });
|
|
100
|
+
case "actions":
|
|
101
|
+
return (_jsx("div", { className: cls(ui, "block.actions"), children: v.items.map((a, i) => (_jsxs("button", { type: "button", className: cls(ui, "block.action"), onClick: () => void ui.assistant.send(a.send), children: [a.label, a.suggested ? _jsx("span", { className: "g9a-suggested", children: t("block.suggested") }) : null] }, i))) }));
|
|
102
|
+
case "flow": return _jsx("div", { className: cls(ui, "block.flow"), children: v.line });
|
|
103
|
+
case "image": return _jsx("div", { className: cls(ui, "block.image"), children: v.fileIds.map((id) => _jsx("img", { src: fileUrl(id), alt: v.fallbackText, loading: "lazy" }, id)) });
|
|
104
|
+
case "open": {
|
|
105
|
+
const navigate = ui.assistant.host.navigate;
|
|
106
|
+
if (!navigate)
|
|
107
|
+
return _jsx("div", { className: cls(ui, "block.fallback"), children: v.fallbackText });
|
|
108
|
+
return _jsx("button", { type: "button", className: cls(ui, "block.open"), onClick: () => navigate(v.pageId), children: ui.assistant.host.pageName?.(v.pageId) ?? v.fallbackText });
|
|
109
|
+
}
|
|
110
|
+
default: return _jsx("div", { className: cls(ui, "block.fallback"), children: v.fallbackText });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A ready host for a plain browser app (a product without a bridge talks HTTP itself). Nothing here runs during
|
|
3
|
+
* server rendering; call it in the browser.
|
|
4
|
+
*/
|
|
5
|
+
import type { AssistantHost, AssistantTheme } from "@g9tm/aiassistant";
|
|
6
|
+
export interface BrowserHostOptions {
|
|
7
|
+
locale?: "fa" | "en";
|
|
8
|
+
theme?: AssistantTheme;
|
|
9
|
+
/** Extra headers on every request (the host's own sign-in). */
|
|
10
|
+
headers?: () => Record<string, string>;
|
|
11
|
+
linkHosts?: readonly string[];
|
|
12
|
+
navigate?: AssistantHost["navigate"];
|
|
13
|
+
pageName?: AssistantHost["pageName"];
|
|
14
|
+
sheetLayer?: number;
|
|
15
|
+
}
|
|
16
|
+
export declare function browserHost(o?: BrowserHostOptions): AssistantHost;
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A ready host for a plain browser app (a product without a bridge talks HTTP itself). Nothing here runs during
|
|
3
|
+
* server rendering; call it in the browser.
|
|
4
|
+
*/
|
|
5
|
+
export function browserHost(o = {}) {
|
|
6
|
+
const locale = o.locale ?? (document.documentElement.lang === "en" ? "en" : "fa");
|
|
7
|
+
const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
8
|
+
const dark = typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches;
|
|
9
|
+
const host = {
|
|
10
|
+
locale,
|
|
11
|
+
dir: locale === "fa" ? "rtl" : "ltr",
|
|
12
|
+
theme: o.theme ?? { mode: dark ? "dark" : "light", tokens: {} },
|
|
13
|
+
reducedMotion: reduced,
|
|
14
|
+
sheetLayer: o.sheetLayer ?? 1000,
|
|
15
|
+
linkHosts: o.linkHosts ?? [location.hostname],
|
|
16
|
+
async fetch(input, init) {
|
|
17
|
+
const headers = { ...(o.headers?.() ?? {}), ...(init?.headers ?? {}) };
|
|
18
|
+
const body = init?.body;
|
|
19
|
+
const r = await fetch(input, { method: init?.method ?? "GET", headers, credentials: "same-origin", ...(body === undefined ? {} : { body: body }) });
|
|
20
|
+
return { status: r.status, ok: r.ok, text: () => r.text(), headers: r.headers };
|
|
21
|
+
},
|
|
22
|
+
eventSource: (url) => new EventSource(url),
|
|
23
|
+
copy: (text) => navigator.clipboard.writeText(text),
|
|
24
|
+
// Recording for dictation: one channel of WebM/Opus (MediaRecorder's default), at most two minutes.
|
|
25
|
+
...(typeof MediaRecorder === "function" && navigator.mediaDevices ? {
|
|
26
|
+
async record() {
|
|
27
|
+
const stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1 } });
|
|
28
|
+
const rec = new MediaRecorder(stream);
|
|
29
|
+
const parts = [];
|
|
30
|
+
rec.ondataavailable = (e) => { if (e.data.size > 0)
|
|
31
|
+
parts.push(e.data); };
|
|
32
|
+
const ended = new Promise((resolve) => { rec.onstop = () => resolve(); });
|
|
33
|
+
rec.start();
|
|
34
|
+
const cap = setTimeout(() => { if (rec.state === "recording")
|
|
35
|
+
rec.stop(); }, 120000);
|
|
36
|
+
return async () => {
|
|
37
|
+
clearTimeout(cap);
|
|
38
|
+
if (rec.state === "recording")
|
|
39
|
+
rec.stop();
|
|
40
|
+
await ended;
|
|
41
|
+
stream.getTracks().forEach((t) => t.stop());
|
|
42
|
+
const blob = new Blob(parts, { type: rec.mimeType || "audio/webm" });
|
|
43
|
+
return blob.size > 0 ? { bytes: new Uint8Array(await blob.arrayBuffer()), mime: blob.type.split(";")[0] ?? "audio/webm" } : null;
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
} : {}),
|
|
47
|
+
openUrl: (url) => { window.open(url, "_blank", "noopener"); },
|
|
48
|
+
async pickFile(accept) {
|
|
49
|
+
return new Promise((resolve) => {
|
|
50
|
+
const input = document.createElement("input");
|
|
51
|
+
input.type = "file";
|
|
52
|
+
input.accept = accept.join(",");
|
|
53
|
+
input.onchange = async () => {
|
|
54
|
+
const f = input.files?.[0];
|
|
55
|
+
resolve(f ? { name: f.name, type: f.type, bytes: new Uint8Array(await f.arrayBuffer()) } : null);
|
|
56
|
+
};
|
|
57
|
+
input.click();
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
async saveFile(name, data) {
|
|
61
|
+
const blob = new Blob([typeof data === "string" ? data : data]);
|
|
62
|
+
const a = document.createElement("a");
|
|
63
|
+
a.href = URL.createObjectURL(blob);
|
|
64
|
+
a.download = name;
|
|
65
|
+
a.click();
|
|
66
|
+
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
|
|
67
|
+
return true;
|
|
68
|
+
},
|
|
69
|
+
onBackground(listener) {
|
|
70
|
+
const on = () => listener(document.visibilityState === "hidden");
|
|
71
|
+
document.addEventListener("visibilitychange", on);
|
|
72
|
+
return () => document.removeEventListener("visibilitychange", on);
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
if (o.navigate)
|
|
76
|
+
host.navigate = o.navigate;
|
|
77
|
+
if (o.pageName)
|
|
78
|
+
host.pageName = o.pageName;
|
|
79
|
+
return host;
|
|
80
|
+
}
|
package/dist/cards.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The cards. The approval card: facts, before and after, step ticks, the method (click, PinPad, code), the taint
|
|
3
|
+
* warning; confirming always goes through the core, bound to the plan's hash. The other cards: undo all, a question
|
|
4
|
+
* with options (and a secret field), "learn this?" and "make it a routine?". Each answers once; the answer stays in
|
|
5
|
+
* the core.
|
|
6
|
+
*/
|
|
7
|
+
import type { ReactNode } from "react";
|
|
8
|
+
import type { PlanView } from "@g9tm/aiassistant";
|
|
9
|
+
export declare function ApprovalCard(props: {
|
|
10
|
+
plan: PlanView;
|
|
11
|
+
}): ReactNode;
|
|
12
|
+
export declare function Cards(props: {
|
|
13
|
+
card: {
|
|
14
|
+
kind: string;
|
|
15
|
+
id: string;
|
|
16
|
+
body: Record<string, unknown>;
|
|
17
|
+
};
|
|
18
|
+
runId: string | null;
|
|
19
|
+
}): ReactNode;
|
package/dist/cards.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* The cards. The approval card: facts, before and after, step ticks, the method (click, PinPad, code), the taint
|
|
4
|
+
* warning; confirming always goes through the core, bound to the plan's hash. The other cards: undo all, a question
|
|
5
|
+
* with options (and a secret field), "learn this?" and "make it a routine?". Each answers once; the answer stays in
|
|
6
|
+
* the core.
|
|
7
|
+
*/
|
|
8
|
+
import { useState } from "react";
|
|
9
|
+
import { arr, needsCode, obj, REMOTE_EXPIRED, str } from "@g9tm/aiassistant";
|
|
10
|
+
import { pageTexts } from "@g9tm/aiassistant/pages";
|
|
11
|
+
import { cls, useUi } from "./context.js";
|
|
12
|
+
import { PinPad, SecretField } from "./slots.js";
|
|
13
|
+
export function ApprovalCard(props) {
|
|
14
|
+
const ui = useUi();
|
|
15
|
+
const t = ui.texts.t;
|
|
16
|
+
const p = props.plan;
|
|
17
|
+
const [code, setCode] = useState("");
|
|
18
|
+
const [busy, setBusy] = useState(false);
|
|
19
|
+
// A fact without a text of its own shows its values, never its key.
|
|
20
|
+
const say = (key, args) => { const text = t(key, args); return text === key ? Object.values(args).join(" ") || key : text; };
|
|
21
|
+
const confirm = async () => {
|
|
22
|
+
setBusy(true);
|
|
23
|
+
try {
|
|
24
|
+
await ui.assistant.confirm(p.id, needsCode(p.method) || (p.failCode === REMOTE_EXPIRED && code.length > 0) ? code : null); // after the phone ran out, a code may stand in
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
setCode("");
|
|
28
|
+
setBusy(false);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
return (_jsxs("div", { className: cls(ui, "card.approval"), "data-answered": p.answered ?? "", children: [_jsx("h3", { children: p.readOnly ? t("card.readonly_routine") : p.title }), p.warning ? _jsx("p", { className: "g9a-warning", role: "note", children: t("card.tainted") }) : null, _jsx("ol", { children: p.steps.map((s) => (_jsxs("li", { className: cls(ui, "card.approval.step"), children: [_jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: s.ticked, disabled: p.answered !== null || p.steps.length === 1, onChange: () => ui.assistant.tick(p.id, s.index) }), 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))) }), p.answered === null ? (_jsxs(_Fragment, { children: [needsCode(p.method) || p.failCode === REMOTE_EXPIRED ? _jsx("div", { className: cls(ui, "card.approval.code"), children: _jsx(PinPad, { label: t("card.code"), value: code, onInput: setCode }) }) : null, p.failCode === "confirm.waiting" ? _jsx("p", { className: "g9a-note", role: "status", children: t("card.waiting") })
|
|
32
|
+
: p.failCode ? _jsxs("p", { className: "g9a-note", role: "alert", children: [pageTexts(ui.texts).t(p.failCode), p.triesLeft !== null ? " · " + t("card.tries_left", { count: p.triesLeft }) : ""] }) : null, _jsxs("div", { className: "g9a-row", children: [_jsx("button", { type: "button", className: cls(ui, "card.approval.confirm"), disabled: busy || (needsCode(p.method) && code.length === 0), onClick: () => void confirm(), children: t("card.confirm") }), _jsx("button", { type: "button", className: cls(ui, "card.approval.refuse"), disabled: busy, onClick: () => void ui.assistant.refuse(p.id), children: t("card.refuse") })] })] })) : _jsx("p", { className: "g9a-note", children: t("card.answered") })] }));
|
|
33
|
+
}
|
|
34
|
+
export function Cards(props) {
|
|
35
|
+
const ui = useUi();
|
|
36
|
+
const t = ui.texts.t;
|
|
37
|
+
const c = props.card;
|
|
38
|
+
const b = c.body;
|
|
39
|
+
const answered = ui.assistant.answered.of(c.id);
|
|
40
|
+
const [text, setText] = useState("");
|
|
41
|
+
const [undone, setUndone] = useState(null);
|
|
42
|
+
const options = arr(b["options"]).map(obj).map((o) => str(o["label"])).filter((l) => l.length > 0);
|
|
43
|
+
const steps = arr(b["steps"]).map(obj).map((s) => str(s["text"], str(s["title"], str(s["tool"]))));
|
|
44
|
+
if (c.kind === "undo") {
|
|
45
|
+
return (_jsxs("div", { className: cls(ui, "card.undo"), children: [_jsx("ul", { children: steps.map((s, i) => _jsx("li", { children: s }, i)) }), undone === null
|
|
46
|
+
? _jsx("button", { type: "button", onClick: () => { ui.assistant.undo(c.id).then((r) => setUndone(str(obj(r)["text"], t("card.answered"))), () => setUndone(t("card.answered"))); }, children: t("undo.all") })
|
|
47
|
+
: _jsx("p", { className: "g9a-note", children: undone })] }));
|
|
48
|
+
}
|
|
49
|
+
if (c.kind === "ask" && props.runId) {
|
|
50
|
+
const runId = props.runId;
|
|
51
|
+
return (_jsxs("div", { className: cls(ui, "card.ask"), children: [_jsx("p", { children: str(b["question"]) }), answered ? _jsx("p", { className: "g9a-note", children: t("card.answered") }) : (_jsxs(_Fragment, { children: [options.map((o) => _jsx("button", { type: "button", className: "g9a-option", onClick: () => void ui.assistant.answer(runId, c.id, [o], null), children: o }, o)), b["secret"] === true ? _jsx(SecretField, { onSubmit: (v) => void ui.assistant.answer(runId, c.id, [], v) }) : (_jsxs("form", { onSubmit: (e) => { e.preventDefault(); const v = text; setText(""); void ui.assistant.answer(runId, c.id, [], v); }, children: [_jsx("input", { value: text, "aria-label": t("ask.send"), onChange: (e) => setText(e.currentTarget.value) }), _jsx("button", { type: "submit", children: t("ask.send") })] }))] }))] }));
|
|
52
|
+
}
|
|
53
|
+
if (c.kind !== "learn" && c.kind !== "routine" && c.kind !== "routine_revision")
|
|
54
|
+
return null;
|
|
55
|
+
const learn = c.kind === "learn";
|
|
56
|
+
const id = str(b["id"], c.id);
|
|
57
|
+
return (_jsxs("div", { className: cls(ui, "card.choice"), children: [_jsx("p", { children: learn ? t("learn.ask") : t("routine.ask") }), learn ? _jsx("blockquote", { children: str(b["text"]) }) : _jsx("ol", { children: steps.map((s, i) => _jsx("li", { children: s }, i)) }), answered ? _jsx("p", { className: "g9a-note", children: t("card.answered") }) : (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", onClick: () => void ui.assistant.choose(learn ? "knowledge" : "learned", id, learn ? "accept" : "approve"), children: t("yes") }), _jsx("button", { type: "button", onClick: () => void ui.assistant.choose(learn ? "knowledge" : "learned", id, learn ? "refuse" : "retire"), children: t("no") })] }))] }));
|
|
58
|
+
}
|