@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/README.md CHANGED
@@ -1,3 +1,37 @@
1
- # Temporary Holding Version
1
+ # @g9tm/aiassistant
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The headless client of the G9 AI assistant: everything a screen needs, with no DOM, no framework and no runtime
4
+ dependency. The Svelte and ReactLynx packages draw it; a host can draw it with anything else.
5
+
6
+ - An API client for the assistant's HTTP endpoints, over the host's own `fetch`, so sign-in, headers and base address
7
+ stay the host's.
8
+ - Run state: conversations, messages, the work card, plans waiting for confirmation (one confirmation in flight at a
9
+ time), questions, attachments and the assistant's mode, as one snapshot to subscribe to.
10
+ - Transports: a stream when the host gives an `EventSource`, long polling otherwise, or a synchronous answer; it falls
11
+ back to polling by itself.
12
+ - View models for blocks (tables, charts, KPIs, comparisons), safe text with links limited to the host's own hosts,
13
+ transcripts, and Persian helpers (digits, numbers, direction).
14
+ - `@g9tm/aiassistant/admin`: readers for the manager's pages (capabilities, usage, calls, timelines, usage windows).
15
+
16
+ ```ts
17
+ import { createAssistant } from "@g9tm/aiassistant";
18
+ import type { AssistantHost } from "@g9tm/aiassistant";
19
+
20
+ const host: AssistantHost = {
21
+ locale: "en",
22
+ dir: "ltr",
23
+ theme: { mode: "light", tokens: {} },
24
+ reducedMotion: false,
25
+ async fetch(input, init) {
26
+ const r = await fetch(input, { method: init?.method ?? "GET", headers: init?.headers, body: init?.body as BodyInit | undefined });
27
+ return { status: r.status, ok: r.ok, text: () => r.text() };
28
+ },
29
+ };
30
+
31
+ const assistant = createAssistant(host);
32
+ const stop = assistant.subscribe((s) => console.log(s.busy, s.messages.length));
33
+ await assistant.send("Sales of last week?");
34
+ stop();
35
+ ```
36
+
37
+ Part of the G9 AI assistant library. Documentation: see the guides that ship with the library.
@@ -0,0 +1,247 @@
1
+ /**
2
+ * The manager's pages without a renderer: capabilities (route, limits, switch) changed without a release,
3
+ * one entry-test probe per request, the usage ledger with the model-free rate, a run's black box, the usage windows
4
+ * and the audit; a separate entry (`@g9tm/aiassistant/admin`), loaded only by the manager's pages. Every server answer is read with type checks only; renderers draw what these functions return.
5
+ */
6
+ import type { AssistantApi } from "./api.js";
7
+ import type { Texts } from "./i18n.js";
8
+ /**
9
+ * The texts of the manager's pages (kept in this chunk, not in the core): the host's texts and overrides first, then
10
+ * the pages' own words.
11
+ */
12
+ export declare function adminTexts(texts: Texts): Texts;
13
+ /** Every key the manager's pages use (for hosts that translate to another language). */
14
+ export declare function adminKeys(): string[];
15
+ export interface CapabilityLimitsView {
16
+ maxRounds: number;
17
+ perMinute: number;
18
+ perPersonPerDay: number;
19
+ perTenantPerDay: number;
20
+ monthlyTokenBudget: number;
21
+ maxResultChars: number;
22
+ }
23
+ export interface CapabilityView {
24
+ id: string;
25
+ kind: string;
26
+ route: string[];
27
+ limits: CapabilityLimitsView;
28
+ enabled: boolean;
29
+ overridden: boolean;
30
+ }
31
+ export interface ProbeView {
32
+ probe: string;
33
+ model: string;
34
+ quality: string;
35
+ rightKind: boolean;
36
+ tokensIn: number;
37
+ ms: number;
38
+ head: string | null;
39
+ error: string | null;
40
+ }
41
+ export interface UsageGroupView {
42
+ id: string;
43
+ rows: number;
44
+ modelCalls: number;
45
+ withoutModel: number;
46
+ errors: number;
47
+ tokensIn: number;
48
+ tokensCached: number;
49
+ tokensOut: number;
50
+ avgMs: number;
51
+ }
52
+ export interface UsageView {
53
+ days: number;
54
+ rows: number;
55
+ withoutModelRate: number;
56
+ capabilities: UsageGroupView[];
57
+ models: UsageGroupView[];
58
+ outcomes: [string, number][];
59
+ }
60
+ export interface CallView {
61
+ id: string;
62
+ runId: string | null;
63
+ capability: string;
64
+ role: string;
65
+ round: number;
66
+ model: string | null;
67
+ outcome: string;
68
+ tokensIn: number;
69
+ tokensCached: number;
70
+ tokensOut: number;
71
+ ms: number;
72
+ head: string | null;
73
+ error: string | null;
74
+ guards: {
75
+ name: string;
76
+ pass: boolean;
77
+ code: string | null;
78
+ }[];
79
+ at: string;
80
+ }
81
+ /** One line of a run's black box: an event or a model call, in time order. */
82
+ export interface TimelineLine {
83
+ at: string;
84
+ kind: "event" | "call";
85
+ title: string;
86
+ detail: string;
87
+ bad: boolean;
88
+ }
89
+ export interface WindowSetView {
90
+ backend: string;
91
+ windows: {
92
+ name: string;
93
+ usedPercent: number;
94
+ resetsAt: string | null;
95
+ }[];
96
+ readAt: string;
97
+ }
98
+ export interface AuditView {
99
+ at: string;
100
+ user: string;
101
+ actor: string;
102
+ action: string;
103
+ runId: string | null;
104
+ tool: string | null;
105
+ decision: string | null;
106
+ outcome: string | null;
107
+ tainted: boolean;
108
+ }
109
+ export declare function readCapability(raw: unknown): CapabilityView;
110
+ export declare function readUsage(raw: unknown): UsageView;
111
+ export declare function readCall(raw: unknown): CallView;
112
+ /** A run's black box as lines in time order: stages, tools, guard votes and rounds from its events, and its model calls. */
113
+ export declare function readTimeline(raw: unknown): {
114
+ run: Record<string, unknown>;
115
+ lines: TimelineLine[];
116
+ };
117
+ export declare function readWindows(raw: unknown): WindowSetView[];
118
+ export declare function readAudit(raw: unknown): AuditView[];
119
+ /** A manager's change to a capability: only what is given is sent (the rest keeps the host's values). */
120
+ export interface CapabilityPatch {
121
+ route?: string[];
122
+ limits?: Partial<CapabilityLimitsView>;
123
+ enabled?: boolean;
124
+ }
125
+ /** Parses a route typed as text: models separated by "&gt;", commas or new lines, best first. */
126
+ export declare function parseRoute(text: string): string[];
127
+ /** The manager's endpoints. A person who is not a manager gets 404 from each (the page then shows nothing). */
128
+ export declare class AdminClient {
129
+ private readonly api;
130
+ constructor(api: AssistantApi);
131
+ capabilities(): Promise<{
132
+ capabilities: CapabilityView[];
133
+ probes: string[];
134
+ }>;
135
+ setCapability(id: string, patch: CapabilityPatch): Promise<CapabilityView>;
136
+ resetCapability(id: string): Promise<CapabilityView>;
137
+ probe(name: string, model: string): Promise<ProbeView>;
138
+ usage(days?: number): Promise<UsageView>;
139
+ calls(days?: number, max?: number): Promise<CallView[]>;
140
+ timeline(runId: string): Promise<{
141
+ run: Record<string, unknown>;
142
+ lines: TimelineLine[];
143
+ }>;
144
+ windows(): Promise<WindowSetView[]>;
145
+ audit(max?: number): Promise<AuditView[]>;
146
+ providers(): Promise<{
147
+ providers: ProviderView[];
148
+ presets: {
149
+ id: string;
150
+ baseUrl: string;
151
+ }[];
152
+ }>;
153
+ /** Saves a provider; a secret is sent once and never read back (ref:name refers to the host's vault). */
154
+ saveProvider(id: string, body: Record<string, unknown>): Promise<ProviderView>;
155
+ deleteProvider(id: string): Promise<unknown>;
156
+ testProvider(id: string): Promise<ProviderView>;
157
+ backends(): Promise<{
158
+ id: string;
159
+ state: string;
160
+ until: string | null;
161
+ usage: WindowSetView | null;
162
+ }[]>;
163
+ gatewayKeys(): Promise<{
164
+ id: string;
165
+ name: string;
166
+ revoked: boolean;
167
+ lastUsedAt: string | null;
168
+ }[]>;
169
+ /** Makes a gateway key; its value is in this answer only. */
170
+ createGatewayKey(name: string, policy?: Record<string, unknown>): Promise<string>;
171
+ revokeGatewayKey(id: string): Promise<unknown>;
172
+ gatewayRequests(days?: number): Promise<{
173
+ count: number;
174
+ errors: number;
175
+ tokens: number;
176
+ rows: Record<string, unknown>[];
177
+ }>;
178
+ mcpServers(): Promise<{
179
+ client: boolean;
180
+ servers: McpServerView[];
181
+ }>;
182
+ saveMcpServer(id: string, body: Record<string, unknown>): Promise<McpServerView>;
183
+ deleteMcpServer(id: string): Promise<unknown>;
184
+ testMcpServer(id: string): Promise<{
185
+ ok: boolean;
186
+ error: string | null;
187
+ tools: {
188
+ name: string;
189
+ readOnly: boolean;
190
+ allowed: boolean;
191
+ }[];
192
+ }>;
193
+ agentFeedback(): Promise<{
194
+ fresh: number;
195
+ rows: FeedbackView[];
196
+ }>;
197
+ setFeedback(id: string, status: string, note?: string): Promise<unknown>;
198
+ budget(): Promise<{
199
+ notes: number;
200
+ maxNotes: number;
201
+ pinnedChars: number;
202
+ maxPinnedChars: number;
203
+ }>;
204
+ /** The person's scope chain, narrowest first (the scope picker of the manager's pages). */
205
+ scopes(): Promise<{
206
+ level: string;
207
+ space: string | null;
208
+ user: string | null;
209
+ }[]>;
210
+ }
211
+ export interface ProviderView {
212
+ id: string;
213
+ kind: string;
214
+ baseUrl: string | null;
215
+ level: string;
216
+ hasSecret: boolean;
217
+ secretIsRef: boolean;
218
+ enabled: boolean;
219
+ state: string;
220
+ defaultModel: string | null;
221
+ route: string;
222
+ models: {
223
+ id: string;
224
+ tools: boolean;
225
+ }[];
226
+ }
227
+ export declare function readProvider(raw: unknown): ProviderView;
228
+ export interface McpServerView {
229
+ id: string;
230
+ url: string;
231
+ auth: string;
232
+ hasSecret: boolean;
233
+ enabled: boolean;
234
+ level: string;
235
+ route: string;
236
+ }
237
+ export declare function readMcp(raw: unknown): McpServerView;
238
+ export interface FeedbackView {
239
+ id: string;
240
+ kind: string;
241
+ title: string;
242
+ detail: string | null;
243
+ count: number;
244
+ status: string;
245
+ note: string | null;
246
+ lastAt: string;
247
+ }
package/dist/admin.js ADDED
@@ -0,0 +1,295 @@
1
+ /**
2
+ * The manager's pages without a renderer: capabilities (route, limits, switch) changed without a release,
3
+ * one entry-test probe per request, the usage ledger with the model-free rate, a run's black box, the usage windows
4
+ * and the audit; a separate entry (`@g9tm/aiassistant/admin`), loaded only by the manager's pages. Every server answer is read with type checks only; renderers draw what these functions return.
5
+ */
6
+ import { arr, num, obj, str } from "./api.js";
7
+ import { createTexts } from "./i18n.js";
8
+ const ADMIN_TEXTS = new Map([
9
+ ["fa", {
10
+ "admin.gates": "گیت‌ها",
11
+ "admin.capabilities": "قابلیت‌ها",
12
+ "admin.usage": "مصرف",
13
+ "admin.audit": "رخدادها",
14
+ "admin.route": "مسیر مدل",
15
+ "admin.enabled": "روشن",
16
+ "admin.overridden": "تغییر داده شده",
17
+ "admin.save": "ذخیره",
18
+ "admin.reset": "برگشت به پیش‌فرض",
19
+ "admin.probe": "آزمون ورود",
20
+ "admin.max_rounds": "سقف دور",
21
+ "admin.per_minute": "در دقیقه",
22
+ "admin.per_person_day": "هر نفر در روز",
23
+ "admin.per_space_day": "هر فضا در روز",
24
+ "admin.monthly_tokens": "توکن ماهانه",
25
+ "admin.without_model": "بدون مدل: {percent}",
26
+ "admin.rows": "{count} ردیف",
27
+ "admin.tokens": "توکن ورودی {in} (نگه‌داشته {cached})، خروجی {out}",
28
+ "admin.calls": "تماس‌های اخیر",
29
+ "admin.timeline": "جعبهٔ سیاه اجرا",
30
+ "admin.windows": "پنجره‌های مصرف",
31
+ "admin.empty": "چیزی نیست",
32
+ "admin.models": "مدل‌ها",
33
+ "admin.connections": "اتصال‌ها",
34
+ "admin.feedback": "پیشنهادها",
35
+ "admin.providers": "ارائه‌دهنده‌ها",
36
+ "admin.backends": "backendها",
37
+ "admin.gateway": "درگاه",
38
+ "admin.test": "آزمون",
39
+ "admin.remove": "حذف",
40
+ "admin.add": "افزودن",
41
+ "admin.secret": "کلید (یک بار فرستاده می‌شود)",
42
+ "admin.key_once": "این کلید فقط همین یک بار نشان داده می‌شود:",
43
+ "admin.mcp": "سرورهای MCP",
44
+ "admin.no_client": "کلاینت MCP نصب نیست",
45
+ "admin.scope": "دامنه",
46
+ "admin.budget": "{notes} از {max} نکته؛ {chars} از {maxChars} نویسهٔ سنجاق‌شده",
47
+ }],
48
+ ["en", {
49
+ "admin.gates": "Gates",
50
+ "admin.capabilities": "Capabilities",
51
+ "admin.usage": "Usage",
52
+ "admin.audit": "Audit",
53
+ "admin.route": "Model route",
54
+ "admin.enabled": "On",
55
+ "admin.overridden": "Changed",
56
+ "admin.save": "Save",
57
+ "admin.reset": "Back to default",
58
+ "admin.probe": "Entry test",
59
+ "admin.max_rounds": "Max rounds",
60
+ "admin.per_minute": "Per minute",
61
+ "admin.per_person_day": "Per person per day",
62
+ "admin.per_space_day": "Per space per day",
63
+ "admin.monthly_tokens": "Monthly tokens",
64
+ "admin.without_model": "Without a model: {percent}",
65
+ "admin.rows": "{count} rows",
66
+ "admin.tokens": "Tokens in {in} (cached {cached}), out {out}",
67
+ "admin.calls": "Recent calls",
68
+ "admin.timeline": "Run black box",
69
+ "admin.windows": "Usage windows",
70
+ "admin.empty": "Nothing here",
71
+ "admin.models": "Models",
72
+ "admin.connections": "Connections",
73
+ "admin.feedback": "Suggestions",
74
+ "admin.providers": "Providers",
75
+ "admin.backends": "Backends",
76
+ "admin.gateway": "Gateway",
77
+ "admin.test": "Test",
78
+ "admin.remove": "Remove",
79
+ "admin.add": "Add",
80
+ "admin.secret": "Key (sent once)",
81
+ "admin.key_once": "This key is shown only this once:",
82
+ "admin.mcp": "MCP servers",
83
+ "admin.no_client": "No MCP client is installed",
84
+ "admin.scope": "Scope",
85
+ "admin.budget": "{notes} of {max} notes; {chars} of {maxChars} pinned characters",
86
+ }],
87
+ ]);
88
+ /**
89
+ * The texts of the manager's pages (kept in this chunk, not in the core): the host's texts and overrides first, then
90
+ * the pages' own words.
91
+ */
92
+ export function adminTexts(texts) {
93
+ const own = createTexts(texts.locale, ADMIN_TEXTS.get(texts.locale));
94
+ return {
95
+ locale: texts.locale,
96
+ t(key, args) {
97
+ const v = texts.t(key, args);
98
+ return v !== key ? v : own.t(key, args);
99
+ },
100
+ };
101
+ }
102
+ /** Every key the manager's pages use (for hosts that translate to another language). */
103
+ export function adminKeys() {
104
+ return Object.keys(ADMIN_TEXTS.get("en") ?? {}).sort();
105
+ }
106
+ const nul = (v) => (typeof v === "string" ? v : null);
107
+ export function readCapability(raw) {
108
+ const c = obj(raw);
109
+ const l = obj(c["limits"]);
110
+ return {
111
+ id: str(c["id"]), kind: str(c["kind"]), route: arr(c["route"]).map((m) => str(m)).filter((m) => m.length > 0),
112
+ limits: {
113
+ maxRounds: num(l["maxRounds"]), perMinute: num(l["perMinute"]), perPersonPerDay: num(l["perPersonPerDay"]),
114
+ perTenantPerDay: num(l["perTenantPerDay"]), monthlyTokenBudget: num(l["monthlyTokenBudget"]), maxResultChars: num(l["maxResultChars"]),
115
+ },
116
+ enabled: c["enabled"] !== false, overridden: c["overridden"] === true,
117
+ };
118
+ }
119
+ function readGroup(raw) {
120
+ const g = obj(raw);
121
+ return {
122
+ id: str(g["id"]), rows: num(g["rows"]), modelCalls: num(g["modelCalls"]), withoutModel: num(g["withoutModel"]), errors: num(g["errors"]),
123
+ tokensIn: num(g["tokensIn"]), tokensCached: num(g["tokensCached"]), tokensOut: num(g["tokensOut"]), avgMs: num(g["avgMs"]),
124
+ };
125
+ }
126
+ export function readUsage(raw) {
127
+ const u = obj(raw);
128
+ return {
129
+ days: num(u["days"]), rows: num(u["rows"]), withoutModelRate: Math.max(0, Math.min(1, num(u["withoutModelRate"]))),
130
+ capabilities: arr(u["capabilities"]).map(readGroup), models: arr(u["models"]).map(readGroup),
131
+ outcomes: Object.entries(obj(u["outcomes"])).map(([k, v]) => [k, num(v)]),
132
+ };
133
+ }
134
+ export function readCall(raw) {
135
+ const c = obj(raw);
136
+ return {
137
+ id: str(c["id"]), runId: nul(c["runId"]), capability: str(c["capability"]), role: str(c["role"]), round: num(c["round"]), model: nul(c["model"]),
138
+ outcome: str(c["outcome"]), tokensIn: num(c["tokensIn"]), tokensCached: num(c["tokensCached"]), tokensOut: num(c["tokensOut"]), ms: num(c["ms"]),
139
+ head: nul(c["head"]), error: nul(c["error"]),
140
+ guards: arr(c["guards"]).map(obj).map((g) => ({ name: str(g["name"]), pass: g["pass"] === true, code: nul(g["code"]) })),
141
+ at: str(c["at"]),
142
+ };
143
+ }
144
+ /** A run's black box as lines in time order: stages, tools, guard votes and rounds from its events, and its model calls. */
145
+ export function readTimeline(raw) {
146
+ const t = obj(raw);
147
+ const lines = [];
148
+ for (const e of arr(t["events"]).map(obj)) {
149
+ const type = str(e["type"]);
150
+ const body = obj(e["body"]);
151
+ if (type === "text.delta" || type === "progress")
152
+ continue; // too many to read; the message has the text
153
+ // Bodies as contracts/events.v1.schema.json has them: tool {name,state,ms}, stage {id,state,role}, run.finished {outcome}.
154
+ const detail = type === "tool" ? str(body["name"]) + " " + str(body["state"]) + (typeof body["ms"] === "number" ? " " + String(body["ms"]) + " ms" : "")
155
+ : type === "stage" ? str(body["id"]) + (typeof body["role"] === "string" ? " " + body["role"] : "") + " " + str(body["state"])
156
+ : type === "guard" ? str(body["name"]) + (body["pass"] === false ? " ✗ " + str(body["code"]) : " ✓")
157
+ : type === "run.finished" ? str(body["outcome"]) + " " + str(body["provenance"])
158
+ : "";
159
+ lines.push({ at: str(e["at"]), kind: "event", title: type, detail, bad: (type === "guard" && body["pass"] === false) || (type === "tool" && body["state"] === "fail") });
160
+ }
161
+ for (const c of arr(t["calls"]).map(readCall)) {
162
+ const guards = c.guards.filter((g) => !g.pass).map((g) => g.name + (g.code ? ":" + g.code : ""));
163
+ lines.push({
164
+ at: c.at, kind: "call", title: c.role + " #" + String(c.round) + " " + (c.model ?? "—"),
165
+ detail: c.outcome + " · " + String(c.tokensIn) + "/" + String(c.tokensOut) + " · " + String(c.ms) + " ms" + (guards.length > 0 ? " · " + guards.join(", ") : "") + (c.error ? " · " + c.error : ""),
166
+ bad: c.outcome === "error" || c.outcome === "unreadable" || guards.length > 0,
167
+ });
168
+ }
169
+ lines.sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
170
+ return { run: obj(t["run"]), lines };
171
+ }
172
+ export function readWindows(raw) {
173
+ return arr(obj(raw)["backends"]).map(obj).map((s) => ({
174
+ backend: str(s["backend"]), readAt: str(s["readAt"]),
175
+ windows: arr(s["windows"]).map(obj).map((w) => ({ name: str(w["name"]), usedPercent: Math.max(0, Math.min(100, num(w["usedPercent"]))), resetsAt: nul(w["resetsAt"]) })),
176
+ }));
177
+ }
178
+ export function readAudit(raw) {
179
+ return arr(obj(raw)["audit"]).map(obj).map((a) => ({
180
+ at: str(a["at"]), user: str(a["user"]), actor: str(a["actor"]), action: str(a["action"]), runId: nul(a["runId"]), tool: nul(a["tool"]),
181
+ decision: nul(a["decision"]), outcome: nul(a["outcome"]), tainted: a["tainted"] === true,
182
+ }));
183
+ }
184
+ /** Parses a route typed as text: models separated by "&gt;", commas or new lines, best first. */
185
+ export function parseRoute(text) {
186
+ return text.split(/[>,\n]/u).map((m) => m.trim()).filter((m) => m.length > 0 && m.length <= 160).slice(0, 8);
187
+ }
188
+ /** The manager's endpoints. A person who is not a manager gets 404 from each (the page then shows nothing). */
189
+ export class AdminClient {
190
+ constructor(api) {
191
+ this.api = api;
192
+ }
193
+ async capabilities() {
194
+ const r = obj(await this.api.get("admin/capabilities"));
195
+ return { capabilities: arr(r["capabilities"]).map(readCapability), probes: arr(r["probes"]).map((p) => str(p)).filter((p) => p.length > 0) };
196
+ }
197
+ async setCapability(id, patch) {
198
+ return readCapability(await this.api.put("admin/capabilities/" + encodeURIComponent(id), patch));
199
+ }
200
+ async resetCapability(id) {
201
+ return readCapability(await this.api.put("admin/capabilities/" + encodeURIComponent(id), { reset: true }));
202
+ }
203
+ async probe(name, model) {
204
+ const p = obj(await this.api.post("admin/entry-test/" + encodeURIComponent(name), { model }));
205
+ return {
206
+ probe: str(p["probe"]), model: str(p["model"]), quality: str(p["quality"]), rightKind: p["rightKind"] === true,
207
+ tokensIn: num(p["tokensIn"]), ms: num(p["ms"]), head: nul(p["head"]), error: nul(p["error"]),
208
+ };
209
+ }
210
+ async usage(days = 30) { return readUsage(await this.api.get("admin/usage?days=" + String(days))); }
211
+ async calls(days = 7, max = 100) {
212
+ return arr(obj(await this.api.get("admin/calls?days=" + String(days) + "&max=" + String(max)))["calls"]).map(readCall);
213
+ }
214
+ async timeline(runId) {
215
+ return readTimeline(await this.api.get("admin/runs/" + encodeURIComponent(runId) + "/timeline"));
216
+ }
217
+ async windows() { return readWindows(await this.api.get("admin/usage-windows")); }
218
+ async audit(max = 100) { return readAudit(await this.api.get("admin/audit?max=" + String(max))); }
219
+ // --- models: providers, backends, the gateway
220
+ async providers() {
221
+ const r = obj(await this.api.get("admin/providers"));
222
+ return { providers: arr(r["providers"]).map(readProvider), presets: arr(r["presets"]).map(obj).map((x) => ({ id: str(x["id"]), baseUrl: str(x["baseUrl"]) })) };
223
+ }
224
+ /** Saves a provider; a secret is sent once and never read back (ref:name refers to the host's vault). */
225
+ async saveProvider(id, body) {
226
+ return readProvider(obj(await this.api.put("admin/providers/" + encodeURIComponent(id), body))["provider"]);
227
+ }
228
+ deleteProvider(id) { return this.api.delete("admin/providers/" + encodeURIComponent(id)); }
229
+ async testProvider(id) {
230
+ return readProvider(obj(await this.api.post("admin/providers/" + encodeURIComponent(id) + "/test"))["provider"]);
231
+ }
232
+ async backends() {
233
+ return arr(obj(await this.api.get("admin/backends"))["backends"]).map(obj).map((b) => ({
234
+ id: str(b["id"]), state: str(b["state"]), until: nul(b["until"]), usage: b["usage"] ? readWindows({ backends: [b["usage"]] }).at(0) ?? null : null,
235
+ }));
236
+ }
237
+ async gatewayKeys() {
238
+ return arr(obj(await this.api.get("admin/gateway/keys"))["keys"]).map(obj).map((k) => ({ id: str(k["id"]), name: str(k["name"]), revoked: k["revoked"] === true, lastUsedAt: nul(k["lastUsedAt"]) }));
239
+ }
240
+ /** Makes a gateway key; its value is in this answer only. */
241
+ async createGatewayKey(name, policy = {}) {
242
+ return str(obj(await this.api.post("admin/gateway/keys", { name, policy }))["token"]);
243
+ }
244
+ revokeGatewayKey(id) { return this.api.delete("admin/gateway/keys/" + encodeURIComponent(id)); }
245
+ async gatewayRequests(days = 1) {
246
+ const r = obj(await this.api.get("admin/gateway/requests?days=" + String(days)));
247
+ return { count: num(r["count"]), errors: num(r["errors"]), tokens: num(r["tokens"]), rows: arr(r["requests"]).map(obj) };
248
+ }
249
+ // --- connections: other MCP servers
250
+ async mcpServers() {
251
+ const r = obj(await this.api.get("admin/mcp-servers"));
252
+ return { client: r["client"] === true, servers: arr(r["servers"]).map(readMcp) };
253
+ }
254
+ async saveMcpServer(id, body) {
255
+ return readMcp(obj(await this.api.put("admin/mcp-servers/" + encodeURIComponent(id), body))["server"]);
256
+ }
257
+ deleteMcpServer(id) { return this.api.delete("admin/mcp-servers/" + encodeURIComponent(id)); }
258
+ async testMcpServer(id) {
259
+ const r = obj(await this.api.post("admin/mcp-servers/" + encodeURIComponent(id) + "/test"));
260
+ return { ok: r["ok"] === true, error: nul(r["error"]), tools: arr(r["tools"]).map(obj).map((t) => ({ name: str(t["name"]), readOnly: t["readOnly"] === true, allowed: t["allowed"] === true })) };
261
+ }
262
+ // --- the agents' suggestions, the knowledge budgets, the scope chain
263
+ async agentFeedback() {
264
+ const r = obj(await this.api.get("feedback/agent"));
265
+ return {
266
+ fresh: num(r["new"]),
267
+ rows: arr(r["feedback"]).map(obj).map((f) => ({
268
+ id: str(f["id"]), kind: str(f["kind"]), title: str(f["title"]), detail: nul(f["detail"]), count: num(f["count"], 1), status: str(f["status"], "new"), note: nul(f["note"]), lastAt: str(f["lastAt"]),
269
+ })),
270
+ };
271
+ }
272
+ setFeedback(id, status, note) {
273
+ return this.api.put("feedback/agent/" + encodeURIComponent(id), note === undefined ? { status } : { status, note });
274
+ }
275
+ async budget() {
276
+ const r = obj(await this.api.get("knowledge/budget"));
277
+ return { notes: num(r["notes"]), maxNotes: num(r["maxNotes"], 100), pinnedChars: num(r["pinnedChars"]), maxPinnedChars: num(r["maxPinnedChars"], 6000) };
278
+ }
279
+ /** The person's scope chain, narrowest first (the scope picker of the manager's pages). */
280
+ async scopes() {
281
+ return arr(obj(await this.api.get("scopes/me"))["chain"]).map(obj).map((c) => ({ level: str(c["level"]), space: nul(c["space"]), user: nul(c["user"]) }));
282
+ }
283
+ }
284
+ export function readProvider(raw) {
285
+ const p = obj(raw);
286
+ return {
287
+ id: str(p["id"]), kind: str(p["kind"]), baseUrl: nul(p["baseUrl"]), level: str(p["level"], "app"), hasSecret: p["hasSecret"] === true, secretIsRef: p["secretIsRef"] === true,
288
+ enabled: p["enabled"] !== false, state: str(p["state"], "unknown"), defaultModel: nul(p["defaultModel"]), route: str(p["route"], "direct"),
289
+ models: arr(p["models"]).map(obj).map((m) => ({ id: str(m["id"]), tools: m["tools"] === true })),
290
+ };
291
+ }
292
+ export function readMcp(raw) {
293
+ const s = obj(raw);
294
+ return { id: str(s["id"]), url: str(s["url"]), auth: str(s["auth"], "none"), hasSecret: s["hasSecret"] === true, enabled: s["enabled"] !== false, level: str(s["level"], "app"), route: str(s["route"], "direct") };
295
+ }
package/dist/api.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ /** The typed HTTP client of the assistant's API. fetch comes from the host. */
2
+ import type { AssistantHost, HostRequest } from "./host.js";
3
+ import type { RawEvent } from "./run.js";
4
+ export declare class ApiError extends Error {
5
+ readonly status: number;
6
+ readonly code: string;
7
+ readonly body: unknown;
8
+ constructor(status: number, code: string, body: unknown);
9
+ }
10
+ export interface SendInput {
11
+ text: string;
12
+ conversationId?: string;
13
+ files?: string[];
14
+ page?: {
15
+ pageId: string;
16
+ subjectKind?: string;
17
+ subjectId?: string;
18
+ subjectLabel?: string;
19
+ };
20
+ }
21
+ export interface EventPage {
22
+ events: RawEvent[];
23
+ last: number;
24
+ finished: boolean;
25
+ }
26
+ /** A JSON value read with type checks only (a stored null never breaks the client). */
27
+ export type Json = null | boolean | number | string | Json[] | {
28
+ [k: string]: Json;
29
+ };
30
+ export declare function obj(v: unknown): Record<string, unknown>;
31
+ export declare function str(v: unknown, fallback?: string): string;
32
+ export declare function num(v: unknown, fallback?: number): number;
33
+ export declare function arr(v: unknown): unknown[];
34
+ export declare class AssistantApi {
35
+ private readonly host;
36
+ private readonly base;
37
+ /** The time one request may take (a long poll waits up to 25 s on the server). */
38
+ timeoutMs: number;
39
+ constructor(host: AssistantHost, base?: string);
40
+ request(method: NonNullable<HostRequest["method"]>, path: string, body?: unknown, raw?: {
41
+ bytes: Uint8Array;
42
+ type: string;
43
+ }): Promise<unknown>;
44
+ send(input: SendInput): Promise<{
45
+ conversationId: string;
46
+ runId: string;
47
+ }>;
48
+ events(runId: string, after: number, wait: number): Promise<EventPage>;
49
+ ticket(runId: string): Promise<string>;
50
+ streamUrl(runId: string, after: number, ticket: string): string;
51
+ cancel(runId: string): Promise<unknown>;
52
+ confirm(planId: string, hash: string, code: string | null, skip: number[]): Promise<unknown>;
53
+ refuse(planId: string): Promise<unknown>;
54
+ undo(planId: string): Promise<unknown>;
55
+ answer(runId: string, picked: string[], text: string | null): Promise<unknown>;
56
+ lock(): Promise<unknown>;
57
+ conversations(): Promise<unknown>;
58
+ messages(conversationId: string, after?: string): Promise<unknown>;
59
+ state(): Promise<unknown>;
60
+ capabilities(): Promise<unknown>;
61
+ feedback(conversationId: string, messageId: string, good: boolean, note?: string): Promise<unknown>;
62
+ card(kind: "knowledge" | "learned", id: string, verb: string): Promise<unknown>;
63
+ upload(name: string, bytes: Uint8Array): Promise<{
64
+ id: string;
65
+ kind: string;
66
+ name: string;
67
+ rows?: number;
68
+ }>;
69
+ /** Dictation: audio to text on the server (the audio is not kept). */
70
+ speech(bytes: Uint8Array, mime: string): Promise<string>;
71
+ removeFile(id: string): Promise<unknown>;
72
+ transcript(conversationId: string): Promise<unknown>;
73
+ documentLink(conversationId: string): Promise<unknown>;
74
+ /** Any other endpoint (admin pages, findings, gates...). */
75
+ get(path: string): Promise<unknown>;
76
+ post(path: string, body?: unknown): Promise<unknown>;
77
+ put(path: string, body?: unknown): Promise<unknown>;
78
+ patch(path: string, body?: unknown): Promise<unknown>;
79
+ delete(path: string): Promise<unknown>;
80
+ }
81
+ export declare function toRawEvent(v: unknown): RawEvent;