@g9tm/aiassistant 1.6.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin.js +2 -2
- package/dist/api.d.ts +18 -0
- package/dist/api.js +28 -2
- package/dist/assistant.d.ts +22 -0
- package/dist/assistant.js +103 -2
- package/dist/blocks.js +10 -10
- package/dist/conversation.d.ts +7 -0
- package/dist/conversation.js +18 -1
- package/dist/csv.d.ts +0 -1
- package/dist/csv.js +3 -1
- package/dist/flows.d.ts +125 -0
- package/dist/flows.js +327 -0
- package/dist/host.d.ts +12 -0
- package/dist/i18n.js +8 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/pages.js +1 -1
- package/dist/state.d.ts +1 -0
- package/dist/state.js +6 -1
- package/dist/types.d.ts +2 -1
- package/package.json +2 -2
package/dist/admin.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* one entry-test probe per request, the usage ledger with the model-free rate, a run's black box, the usage windows
|
|
4
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
5
|
*/
|
|
6
|
-
import { arr, num, obj, str } from "./api.js";
|
|
6
|
+
import { arr, item, num, obj, str } from "./api.js";
|
|
7
7
|
import { createTexts } from "./i18n.js";
|
|
8
8
|
const ADMIN_TEXTS = new Map([
|
|
9
9
|
["fa", {
|
|
@@ -231,7 +231,7 @@ export class AdminClient {
|
|
|
231
231
|
}
|
|
232
232
|
async backends() {
|
|
233
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"]] })
|
|
234
|
+
id: str(b["id"]), state: str(b["state"]), until: nul(b["until"]), usage: b["usage"] ? item(readWindows({ backends: [b["usage"]] }), 0) ?? null : null,
|
|
235
235
|
}));
|
|
236
236
|
}
|
|
237
237
|
async gatewayKeys() {
|
package/dist/api.d.ts
CHANGED
|
@@ -33,6 +33,11 @@ export declare function obj(v: unknown): Record<string, unknown>;
|
|
|
33
33
|
export declare function str(v: unknown, fallback?: string): string;
|
|
34
34
|
export declare function num(v: unknown, fallback?: number): number;
|
|
35
35
|
export declare function arr(v: unknown): unknown[];
|
|
36
|
+
/**
|
|
37
|
+
* The item at an index (negative counts from the end), or undefined: `Array.prototype.at` is ES2022 and the Lynx
|
|
38
|
+
* engine on a phone (PrimJS) has none, so library code never calls it.
|
|
39
|
+
*/
|
|
40
|
+
export declare function item<T>(xs: readonly T[], i: number): T | undefined;
|
|
36
41
|
export declare class AssistantApi {
|
|
37
42
|
private readonly host;
|
|
38
43
|
private readonly base;
|
|
@@ -56,6 +61,19 @@ export declare class AssistantApi {
|
|
|
56
61
|
undo(planId: string): Promise<unknown>;
|
|
57
62
|
answer(runId: string, picked: string[], text: string | null): Promise<unknown>;
|
|
58
63
|
lock(): Promise<unknown>;
|
|
64
|
+
/** A device tool's answer to a `client.call` of a run. */
|
|
65
|
+
clientResult(runId: string, body: {
|
|
66
|
+
callId: string;
|
|
67
|
+
ok: boolean;
|
|
68
|
+
output?: unknown;
|
|
69
|
+
error?: string;
|
|
70
|
+
confirmed?: boolean;
|
|
71
|
+
made?: string;
|
|
72
|
+
}): Promise<unknown>;
|
|
73
|
+
/** The person's flow pack (`unchanged` when `version` is current). */
|
|
74
|
+
flows(version: string): Promise<unknown>;
|
|
75
|
+
/** Outcomes of flows the device ran. */
|
|
76
|
+
flowOutcomes(outcomes: readonly unknown[]): Promise<unknown>;
|
|
59
77
|
conversations(): Promise<unknown>;
|
|
60
78
|
messages(conversationId: string, after?: string): Promise<unknown>;
|
|
61
79
|
state(): Promise<unknown>;
|
package/dist/api.js
CHANGED
|
@@ -20,6 +20,15 @@ export function num(v, fallback = 0) {
|
|
|
20
20
|
export function arr(v) {
|
|
21
21
|
return Array.isArray(v) ? v : [];
|
|
22
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* The item at an index (negative counts from the end), or undefined: `Array.prototype.at` is ES2022 and the Lynx
|
|
25
|
+
* engine on a phone (PrimJS) has none, so library code never calls it.
|
|
26
|
+
*/
|
|
27
|
+
export function item(xs, i) {
|
|
28
|
+
const k = i < 0 ? xs.length + i : i;
|
|
29
|
+
// eslint-disable-next-line security/detect-object-injection -- a number index into an array, bounds checked
|
|
30
|
+
return k >= 0 && k < xs.length ? xs[k] : undefined;
|
|
31
|
+
}
|
|
23
32
|
export class AssistantApi {
|
|
24
33
|
constructor(host, base = "/api/assistant/") {
|
|
25
34
|
this.host = host;
|
|
@@ -57,8 +66,17 @@ export class AssistantApi {
|
|
|
57
66
|
const body = { text: input.text };
|
|
58
67
|
if (input.files && input.files.length > 0)
|
|
59
68
|
body["files"] = input.files;
|
|
60
|
-
|
|
61
|
-
|
|
69
|
+
// The wire's names (contracts/api.v1.yaml, page): id, kind, subject, label.
|
|
70
|
+
if (input.page) {
|
|
71
|
+
const p = { id: input.page.pageId };
|
|
72
|
+
if (input.page.subjectKind)
|
|
73
|
+
p["kind"] = input.page.subjectKind;
|
|
74
|
+
if (input.page.subjectId)
|
|
75
|
+
p["subject"] = input.page.subjectId;
|
|
76
|
+
if (input.page.subjectLabel)
|
|
77
|
+
p["label"] = input.page.subjectLabel;
|
|
78
|
+
body["page"] = p;
|
|
79
|
+
}
|
|
62
80
|
if (input.model)
|
|
63
81
|
body["model"] = input.model;
|
|
64
82
|
return this.request("POST", path, body).then((r) => ({ conversationId: str(obj(r)["conversationId"]), runId: str(obj(r)["runId"]) }));
|
|
@@ -83,6 +101,14 @@ export class AssistantApi {
|
|
|
83
101
|
return this.request("POST", "asks/" + encodeURIComponent(runId) + "/answer", { picked, text });
|
|
84
102
|
}
|
|
85
103
|
lock() { return this.request("POST", "lock"); }
|
|
104
|
+
/** A device tool's answer to a `client.call` of a run. */
|
|
105
|
+
clientResult(runId, body) {
|
|
106
|
+
return this.request("POST", "runs/" + encodeURIComponent(runId) + "/client-results", body);
|
|
107
|
+
}
|
|
108
|
+
/** The person's flow pack (`unchanged` when `version` is current). */
|
|
109
|
+
flows(version) { return this.request("GET", "flows" + (version ? "?version=" + encodeURIComponent(version) : "")); }
|
|
110
|
+
/** Outcomes of flows the device ran. */
|
|
111
|
+
flowOutcomes(outcomes) { return this.request("POST", "flows/outcomes", { outcomes }); }
|
|
86
112
|
conversations() { return this.request("GET", "conversations"); }
|
|
87
113
|
messages(conversationId, after) {
|
|
88
114
|
return this.request("GET", "conversations/" + encodeURIComponent(conversationId) + "/messages" + (after ? "?after=" + encodeURIComponent(after) : ""));
|
package/dist/assistant.d.ts
CHANGED
|
@@ -7,6 +7,8 @@ import { AssistantApi } from "./api.js";
|
|
|
7
7
|
import type { SendInput } from "./api.js";
|
|
8
8
|
import type { MessageView } from "./conversation.js";
|
|
9
9
|
import type { AssistantHost } from "./host.js";
|
|
10
|
+
import { DeviceFlows } from "./flows.js";
|
|
11
|
+
import type { DeviceTools } from "./flows.js";
|
|
10
12
|
import type { Texts } from "./i18n.js";
|
|
11
13
|
import { AnsweredCards } from "./plan.js";
|
|
12
14
|
import type { PlanView } from "./plan.js";
|
|
@@ -21,7 +23,13 @@ export interface AssistantOptions {
|
|
|
21
23
|
texts?: Readonly<Record<string, string>>;
|
|
22
24
|
/** Custom block types (x:*) the host draws. */
|
|
23
25
|
customBlocks?: readonly string[];
|
|
26
|
+
/** The device's own tools: the server's `client.call`s run here, and so do the device's flows. */
|
|
27
|
+
deviceTools?: DeviceTools;
|
|
28
|
+
/** Device flows (with `deviceTools`): questions the device answers itself, without a model or a connection. Default on. */
|
|
29
|
+
flows?: boolean;
|
|
24
30
|
}
|
|
31
|
+
/** Where `ask` sent a question. */
|
|
32
|
+
export type AskedVia = "device" | "offline" | "server" | "refused";
|
|
25
33
|
export interface AssistantSnapshot {
|
|
26
34
|
conversationId: string | null;
|
|
27
35
|
messages: MessageView[];
|
|
@@ -58,6 +66,11 @@ export declare class Assistant {
|
|
|
58
66
|
model: string | null;
|
|
59
67
|
private error;
|
|
60
68
|
private stateNow;
|
|
69
|
+
/** The device's flow pack (null without device tools or with flows off). */
|
|
70
|
+
readonly devices: DeviceFlows | null;
|
|
71
|
+
private readonly deviceTools;
|
|
72
|
+
/** `client.call`s already answered (a replayed event never runs a tool twice). */
|
|
73
|
+
private readonly answeredCalls;
|
|
61
74
|
constructor(host: AssistantHost, options?: AssistantOptions);
|
|
62
75
|
/** Listens to every change; returns the function that stops listening. */
|
|
63
76
|
subscribe(listener: (s: AssistantSnapshot) => void): () => void;
|
|
@@ -71,6 +84,15 @@ export declare class Assistant {
|
|
|
71
84
|
send(text: string, page?: SendInput["page"]): Promise<boolean>;
|
|
72
85
|
/** Follows a run (null stops following). */
|
|
73
86
|
follow(runId: string | null, after?: number): void;
|
|
87
|
+
/**
|
|
88
|
+
* Asks: a device flow first (no model, no connection), then — offline — says the question needs a connection, else the
|
|
89
|
+
* server. Returns where it went.
|
|
90
|
+
*/
|
|
91
|
+
ask(text: string, page?: SendInput["page"]): Promise<AskedVia>;
|
|
92
|
+
/** Fetches a newer flow pack and sends the queued flow outcomes (online only; a failure waits for the next time). */
|
|
93
|
+
syncDevice(): Promise<boolean>;
|
|
94
|
+
/** Runs a run's `client.call` on the device once and answers the server. */
|
|
95
|
+
private clientCall;
|
|
74
96
|
/** Stops the run that is working. */
|
|
75
97
|
stop(): Promise<void>;
|
|
76
98
|
private notePlan;
|
package/dist/assistant.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { ApiError, AssistantApi } from "./api.js";
|
|
7
7
|
import { ConversationStore } from "./conversation.js";
|
|
8
8
|
import { timer } from "./host.js";
|
|
9
|
+
import { DeviceFlows } from "./flows.js";
|
|
9
10
|
import { createTexts } from "./i18n.js";
|
|
10
11
|
import { AnsweredCards, REMOTE_EXPIRED, WAITING, afterConfirm, confirmation, planView, toggle } from "./plan.js";
|
|
11
12
|
import { Watched } from "./reveal.js";
|
|
@@ -30,10 +31,14 @@ export class Assistant {
|
|
|
30
31
|
/** The model a person picked for what they send next (`id` or `id@effort`); null lets the route decide. */
|
|
31
32
|
this.model = null;
|
|
32
33
|
this.error = null;
|
|
34
|
+
/** `client.call`s already answered (a replayed event never runs a tool twice). */
|
|
35
|
+
this.answeredCalls = new Set();
|
|
33
36
|
this.api = new AssistantApi(host, options.base);
|
|
34
37
|
this.texts = createTexts(host.locale, options.texts);
|
|
35
38
|
this.transport = pickTransport(this.api, host, options);
|
|
36
39
|
this.customBlocks = new Set(options.customBlocks ?? []);
|
|
40
|
+
this.deviceTools = options.deviceTools ?? null;
|
|
41
|
+
this.devices = options.deviceTools && options.flows !== false ? new DeviceFlows(this.api, host, options.deviceTools) : null;
|
|
37
42
|
this.stateWatch = new StateWatch(this.api, host);
|
|
38
43
|
this.stateNow = this.stateWatch.state;
|
|
39
44
|
this.stateWatch.subscribe((s) => { this.stateNow = s; this.emit(); });
|
|
@@ -99,8 +104,9 @@ export class Assistant {
|
|
|
99
104
|
input.conversationId = this.store.id;
|
|
100
105
|
if (this.attachments.length > 0)
|
|
101
106
|
input.files = this.attachments.map((a) => a.id);
|
|
102
|
-
|
|
103
|
-
|
|
107
|
+
const where = page ?? this.host.page?.();
|
|
108
|
+
if (where)
|
|
109
|
+
input.page = where;
|
|
104
110
|
if (this.model)
|
|
105
111
|
input.model = this.model;
|
|
106
112
|
try {
|
|
@@ -111,6 +117,7 @@ export class Assistant {
|
|
|
111
117
|
return true;
|
|
112
118
|
}
|
|
113
119
|
catch (e) {
|
|
120
|
+
this.store.settle(); // not sent: the question stays, no longer dim
|
|
114
121
|
this.error = e instanceof ApiError ? e.code : "error.network";
|
|
115
122
|
this.emit();
|
|
116
123
|
return false;
|
|
@@ -129,6 +136,10 @@ export class Assistant {
|
|
|
129
136
|
if (!this.run || this.run.runId !== runId)
|
|
130
137
|
return;
|
|
131
138
|
this.run = reduceRun(this.run, e, timer(this.host).now());
|
|
139
|
+
if (e.type === "run.finished")
|
|
140
|
+
this.store.settle(); // answered or not, the question is no longer waiting
|
|
141
|
+
if (e.type === "client.call")
|
|
142
|
+
void this.clientCall(runId, e.body);
|
|
132
143
|
if (e.type === "message") {
|
|
133
144
|
const added = this.store.merge([e.body.message]);
|
|
134
145
|
for (const m of added)
|
|
@@ -141,6 +152,96 @@ export class Assistant {
|
|
|
141
152
|
onEnd: () => this.emit(),
|
|
142
153
|
});
|
|
143
154
|
}
|
|
155
|
+
/**
|
|
156
|
+
* Asks: a device flow first (no model, no connection), then — offline — says the question needs a connection, else the
|
|
157
|
+
* server. Returns where it went.
|
|
158
|
+
*/
|
|
159
|
+
async ask(text, page) {
|
|
160
|
+
const trimmed = text.trim();
|
|
161
|
+
if (trimmed.length === 0 || this.snapshot().busy)
|
|
162
|
+
return "refused";
|
|
163
|
+
const at = () => new Date(timer(this.host).now()).toISOString();
|
|
164
|
+
const online = this.host.online ? this.host.online() : true;
|
|
165
|
+
const hit = this.devices?.match(trimmed, this.host.locale) ?? null;
|
|
166
|
+
if (hit && this.devices) {
|
|
167
|
+
this.store.local("user", trimmed, at());
|
|
168
|
+
this.emit();
|
|
169
|
+
const r = await this.devices.run(hit.flow, hit.slots, !online);
|
|
170
|
+
const say = r.say || (r.ok ? "" : this.texts.t(r.code === "refused" ? "device.refused" : "device.flow_failed"));
|
|
171
|
+
this.store.local("assistant", say, at(), r.blocks, "device", r.ok ? "text" : "error");
|
|
172
|
+
this.host.onAnswerShown?.();
|
|
173
|
+
this.emit();
|
|
174
|
+
if (online)
|
|
175
|
+
void this.devices.flush().catch(() => undefined);
|
|
176
|
+
return "device";
|
|
177
|
+
}
|
|
178
|
+
if (!online) {
|
|
179
|
+
this.store.local("user", trimmed, at());
|
|
180
|
+
this.store.local("assistant", this.texts.t("device.needs_online"), at(), [], "device", "error");
|
|
181
|
+
this.emit();
|
|
182
|
+
return "offline";
|
|
183
|
+
}
|
|
184
|
+
return (await this.send(trimmed, page)) ? "server" : "refused";
|
|
185
|
+
}
|
|
186
|
+
/** Fetches a newer flow pack and sends the queued flow outcomes (online only; a failure waits for the next time). */
|
|
187
|
+
async syncDevice() {
|
|
188
|
+
if (!this.devices || (this.host.online && !this.host.online()))
|
|
189
|
+
return false;
|
|
190
|
+
try {
|
|
191
|
+
const changed = await this.devices.refresh();
|
|
192
|
+
await this.devices.flush();
|
|
193
|
+
return changed;
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/** Runs a run's `client.call` on the device once and answers the server. */
|
|
200
|
+
async clientCall(runId, raw) {
|
|
201
|
+
const b = raw !== null && typeof raw === "object" ? raw : {};
|
|
202
|
+
const callId = typeof b["callId"] === "string" ? b["callId"] : "";
|
|
203
|
+
if (callId.length === 0 || this.answeredCalls.has(callId))
|
|
204
|
+
return;
|
|
205
|
+
this.answeredCalls.add(callId);
|
|
206
|
+
const tool = typeof b["tool"] === "string" ? b["tool"] : "";
|
|
207
|
+
const title = b["title"] !== null && typeof b["title"] === "object" ? b["title"] : null;
|
|
208
|
+
const call = {
|
|
209
|
+
callId,
|
|
210
|
+
runId,
|
|
211
|
+
tool,
|
|
212
|
+
input: b["input"] !== null && typeof b["input"] === "object" ? b["input"] : {},
|
|
213
|
+
risk: b["risk"] === "change" || b["risk"] === "dangerous" ? b["risk"] : "read",
|
|
214
|
+
confirmed: b["confirmed"] === true,
|
|
215
|
+
title: title && typeof title["key"] === "string" ? this.texts.t(title["key"]) : null,
|
|
216
|
+
source: "run",
|
|
217
|
+
};
|
|
218
|
+
let r;
|
|
219
|
+
if (!this.deviceTools || !this.deviceTools.has(tool))
|
|
220
|
+
r = { ok: false, error: "device_unavailable" };
|
|
221
|
+
else {
|
|
222
|
+
try {
|
|
223
|
+
r = await this.deviceTools.run(call);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
r = { ok: false, error: "device_error" };
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const body = { callId, ok: r.ok };
|
|
230
|
+
if (r.output !== undefined)
|
|
231
|
+
body.output = r.output;
|
|
232
|
+
if (!r.ok)
|
|
233
|
+
body.error = r.error ?? "device_error";
|
|
234
|
+
if (r.confirmed)
|
|
235
|
+
body.confirmed = true;
|
|
236
|
+
if (r.made)
|
|
237
|
+
body.made = r.made;
|
|
238
|
+
try {
|
|
239
|
+
await this.api.clientResult(runId, body);
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
// the run timed out or ended: it went on without this answer
|
|
243
|
+
}
|
|
244
|
+
}
|
|
144
245
|
/** Stops the run that is working. */
|
|
145
246
|
async stop() {
|
|
146
247
|
if (!this.run || finished(this.run))
|
package/dist/blocks.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* wordy table becomes cards, a long one folds after 8 rows, a ranking is horizontal bars (at most 10), a line only on a
|
|
5
5
|
* time axis, and too little data shows no percentages or averages.
|
|
6
6
|
*/
|
|
7
|
-
import { arr, num, obj, str } from "./api.js";
|
|
7
|
+
import { arr, item, num, obj, str } from "./api.js";
|
|
8
8
|
import { formatNumber } from "./fa.js";
|
|
9
9
|
/** A table with more columns than this, or long texts, shows each row as a card. */
|
|
10
10
|
export const CARD_COLUMNS = 4;
|
|
@@ -55,7 +55,7 @@ export function blockView(raw, locale, custom = new Set()) {
|
|
|
55
55
|
const cols = columns(b["columns"]);
|
|
56
56
|
if (cols.length === 0)
|
|
57
57
|
return { type: "fallback", fallbackText };
|
|
58
|
-
const rows = arr(b["rows"]).map((r) => cols.map((c, i) => cell(arr(r)
|
|
58
|
+
const rows = arr(b["rows"]).map((r) => cols.map((c, i) => cell(item(arr(r), i), c.kind, locale)));
|
|
59
59
|
const wordy = rows.some((r) => r.some((c) => c.length > 40));
|
|
60
60
|
const shown = rows.length > FOLD_ROWS ? FOLD_ROWS : rows.length;
|
|
61
61
|
return withTitle({ type: "table", columns: cols, rows, asCards: cols.length > CARD_COLUMNS || wordy, shown, more: rows.length - shown, truncated: b["truncated"] === true, fallbackText });
|
|
@@ -64,7 +64,7 @@ export function blockView(raw, locale, custom = new Set()) {
|
|
|
64
64
|
case "kpi": {
|
|
65
65
|
const cs = columns(b["columns"]);
|
|
66
66
|
const row = arr(arr(b["rows"])[0]);
|
|
67
|
-
const items = cs.map((c, i) => ({ label: c.label, value: cell(row
|
|
67
|
+
const items = cs.map((c, i) => ({ label: c.label, value: cell(item(row, i), c.kind, locale) }));
|
|
68
68
|
return items.length > 0 ? { type: "kpi", items, fallbackText } : { type: "fallback", fallbackText };
|
|
69
69
|
}
|
|
70
70
|
case "steps": return { type: "steps", items: arr(b["items"]).map(obj).map((s) => ({ text: str(s["text"]), state: str(s["state"], "todo") })), fallbackText };
|
|
@@ -76,7 +76,7 @@ export function blockView(raw, locale, custom = new Set()) {
|
|
|
76
76
|
case "export": {
|
|
77
77
|
// every row and column, as raw text: the file is for a spreadsheet, not for reading here
|
|
78
78
|
const cols = columns(b["columns"]);
|
|
79
|
-
const rows = arr(b["rows"]).map((r) => cols.map((_, i) => { const v = arr(r)
|
|
79
|
+
const rows = arr(b["rows"]).map((r) => cols.map((_, i) => { const v = item(arr(r), i); return v === null || v === undefined ? "" : typeof v === "string" ? v : String(v); }));
|
|
80
80
|
return withTitle({ type: "export", format: str(b["format"], "csv"), columns: cols, rows, fallbackText });
|
|
81
81
|
}
|
|
82
82
|
default: return { type: "fallback", fallbackText }; // compare, gauge, timeline, items: drawn by the host or shown as text
|
|
@@ -89,12 +89,12 @@ function chart(b, cs, fallbackText) {
|
|
|
89
89
|
const rows = arr(b["rows"]).map(arr);
|
|
90
90
|
const x = str(b["x"], cs[0]?.name ?? "");
|
|
91
91
|
const xIndex = Math.max(0, cs.findIndex((c) => c.name === x));
|
|
92
|
-
const xCol = cs
|
|
93
|
-
const valueCols = cs.filter((_, i) => i !== xIndex && ["number", "money", "percent"].includes(cs
|
|
92
|
+
const xCol = item(cs, xIndex);
|
|
93
|
+
const valueCols = cs.filter((_, i) => i !== xIndex && ["number", "money", "percent"].includes(item(cs, i)?.kind ?? ""));
|
|
94
94
|
if (!xCol || valueCols.length === 0 || rows.length === 0)
|
|
95
95
|
return { type: "fallback", fallbackText };
|
|
96
|
-
const labels = rows.map((r) => (r
|
|
97
|
-
const series = valueCols.map((c) => ({ name: c.label, values: rows.map((r) => num(r
|
|
96
|
+
const labels = rows.map((r) => (item(r, xIndex) === null || item(r, xIndex) === undefined ? "" : String(item(r, xIndex))));
|
|
97
|
+
const series = valueCols.map((c) => ({ name: c.label, values: rows.map((r) => num(item(r, cs.indexOf(c)))) }));
|
|
98
98
|
const timeAxis = xCol.kind === "date" || xCol.kind === "day";
|
|
99
99
|
const asked = str(b["kind"]);
|
|
100
100
|
let kind;
|
|
@@ -107,8 +107,8 @@ function chart(b, cs, fallbackText) {
|
|
|
107
107
|
else
|
|
108
108
|
kind = timeAxis ? "line" : "hbars";
|
|
109
109
|
if (kind === "hbars") {
|
|
110
|
-
const order = labels.map((_, i) => i).sort((a, c) => (series[0]?.values
|
|
111
|
-
return { type: "chart", kind, labels: order.map((i) => labels
|
|
110
|
+
const order = labels.map((_, i) => i).sort((a, c) => (item(series[0]?.values ?? [], c) ?? 0) - (item(series[0]?.values ?? [], a) ?? 0)).slice(0, RANK_BARS);
|
|
111
|
+
return { type: "chart", kind, labels: order.map((i) => item(labels, i) ?? ""), series: series.map((s) => ({ name: s.name, values: order.map((i) => item(s.values, i) ?? 0) })), fewData: rows.length < FEW_DATA, fallbackText };
|
|
112
112
|
}
|
|
113
113
|
return { type: "chart", kind, labels, series, fewData: rows.length < FEW_DATA, fallbackText };
|
|
114
114
|
}
|
package/dist/conversation.d.ts
CHANGED
|
@@ -31,7 +31,14 @@ export declare class ConversationStore {
|
|
|
31
31
|
merge(raw: readonly unknown[]): MessageView[];
|
|
32
32
|
/** Shows the person's question at once, until the server's copy replaces it. */
|
|
33
33
|
optimistic(text: string, at: string): MessageView;
|
|
34
|
+
/** The question stays, no longer dim: its run ended (answered or not) or it could not be sent; the server's copy still replaces it. */
|
|
35
|
+
settle(): void;
|
|
34
36
|
private dropPending;
|
|
37
|
+
/**
|
|
38
|
+
* A message made on the device (a flow's answer, the "needs a connection" line): never sent to the server, shown in
|
|
39
|
+
* order with the rest, gone when the conversation is reopened from history.
|
|
40
|
+
*/
|
|
41
|
+
local(role: "user" | "assistant", text: string, at: string, blocks?: unknown[], provenance?: Provenance | null, kind?: string): MessageView;
|
|
35
42
|
/** Clears the store for another conversation. */
|
|
36
43
|
reset(id: string | null): void;
|
|
37
44
|
/** The id of the last message (the history opens at the end). */
|
package/dist/conversation.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* server's copy arrives, history opened from the end, and the answer revealed only when it arrived in front of the person.
|
|
4
4
|
*/
|
|
5
5
|
import { arr, obj, str } from "./api.js";
|
|
6
|
-
const PROVENANCES = new Set(["rule", "learned", "model", "fallback", "cached"]);
|
|
6
|
+
const PROVENANCES = new Set(["rule", "learned", "model", "fallback", "cached", "device"]);
|
|
7
7
|
/** A stored or streamed message, read with type checks only. */
|
|
8
8
|
export function messageView(raw) {
|
|
9
9
|
const m = obj(raw);
|
|
@@ -59,6 +59,12 @@ export class ConversationStore {
|
|
|
59
59
|
this.pendingId = id;
|
|
60
60
|
return m;
|
|
61
61
|
}
|
|
62
|
+
/** The question stays, no longer dim: its run ended (answered or not) or it could not be sent; the server's copy still replaces it. */
|
|
63
|
+
settle() {
|
|
64
|
+
const m = this.pendingId === null ? undefined : this.byId.get(this.pendingId);
|
|
65
|
+
if (m && this.pendingId !== null)
|
|
66
|
+
this.byId.set(this.pendingId, { ...m, pending: false });
|
|
67
|
+
}
|
|
62
68
|
dropPending() {
|
|
63
69
|
if (this.pendingId === null)
|
|
64
70
|
return;
|
|
@@ -66,6 +72,17 @@ export class ConversationStore {
|
|
|
66
72
|
this.order = this.order.filter((x) => x !== this.pendingId);
|
|
67
73
|
this.pendingId = null;
|
|
68
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* A message made on the device (a flow's answer, the "needs a connection" line): never sent to the server, shown in
|
|
77
|
+
* order with the rest, gone when the conversation is reopened from history.
|
|
78
|
+
*/
|
|
79
|
+
local(role, text, at, blocks = [], provenance = null, kind = "text") {
|
|
80
|
+
const id = "local:" + String(this.order.length) + ":" + at;
|
|
81
|
+
const m = { id, role, kind, text, blocks, next: [], provenance, at, card: null, pending: false };
|
|
82
|
+
this.byId.set(id, m);
|
|
83
|
+
this.order.push(id);
|
|
84
|
+
return m;
|
|
85
|
+
}
|
|
69
86
|
/** Clears the store for another conversation. */
|
|
70
87
|
reset(id) {
|
|
71
88
|
this.id = id;
|
package/dist/csv.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
/** A table as a CSV file a spreadsheet opens right: a BOM for the encoding, every cell quoted, no formula injection. */
|
|
2
1
|
import type { AssistantHost } from "./host.js";
|
|
3
2
|
/** One cell: quoted, with inner quotes doubled; a cell a spreadsheet would run as a formula gets a leading apostrophe. */
|
|
4
3
|
export declare function csvCell(value: string): string;
|
package/dist/csv.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** A table as a CSV file a spreadsheet opens right: a BOM for the encoding, every cell quoted, no formula injection. */
|
|
2
|
+
import { item } from "./api.js";
|
|
1
3
|
const BOM = "\uFEFF";
|
|
2
4
|
/** One cell: quoted, with inner quotes doubled; a cell a spreadsheet would run as a formula gets a leading apostrophe. */
|
|
3
5
|
export function csvCell(value) {
|
|
@@ -6,7 +8,7 @@ export function csvCell(value) {
|
|
|
6
8
|
}
|
|
7
9
|
/** The whole file: a BOM, a header row of the column labels, then the rows, lines ended with CRLF. */
|
|
8
10
|
export function toCsv(labels, rows) {
|
|
9
|
-
const lines = [labels.map(csvCell).join(","), ...rows.map((r) => labels.map((_, i) => csvCell(r
|
|
11
|
+
const lines = [labels.map(csvCell).join(","), ...rows.map((r) => labels.map((_, i) => csvCell(item(r, i) ?? "")).join(","))];
|
|
10
12
|
return BOM + lines.join("\r\n") + "\r\n";
|
|
11
13
|
}
|
|
12
14
|
/** A file name from a title: letters, digits and dashes only, with the extension. */
|
package/dist/flows.d.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Device tools and device flows (flows.ts). A device tool runs on the person's device: the server asks with a
|
|
3
|
+
* `client.call` event and waits for the answer. A flow is a question shape the device answers by itself, without a
|
|
4
|
+
* model and without a connection: intents (normalized token patterns with gaps) → device tool steps.
|
|
5
|
+
*
|
|
6
|
+
* The normalization is the SAME as the .NET core's FlowText (both are checked against contracts/examples/flow-text.json),
|
|
7
|
+
* so the server learns exactly the shapes a device matches. No Unicode property escapes (PrimJS rejects them): explicit
|
|
8
|
+
* ranges, like the .NET side.
|
|
9
|
+
*/
|
|
10
|
+
import type { AssistantApi } from "./api.js";
|
|
11
|
+
import type { AssistantHost } from "./host.js";
|
|
12
|
+
/** A device tool call: from a run (`client.call`) or from a flow the device matched itself. */
|
|
13
|
+
export interface DeviceCall {
|
|
14
|
+
callId: string;
|
|
15
|
+
runId: string | null;
|
|
16
|
+
tool: string;
|
|
17
|
+
input: Record<string, unknown>;
|
|
18
|
+
risk: "read" | "change" | "dangerous";
|
|
19
|
+
/** A card already took the person's confirmation: the device must not ask again. */
|
|
20
|
+
confirmed: boolean;
|
|
21
|
+
title: string | null;
|
|
22
|
+
source: "run" | "flow";
|
|
23
|
+
}
|
|
24
|
+
/** What a device tool answered. `say` and `blocks` are shown when a flow answered on the device. */
|
|
25
|
+
export interface DeviceResult {
|
|
26
|
+
ok: boolean;
|
|
27
|
+
output?: unknown;
|
|
28
|
+
/** Why not: `refused` (the person declined), `invalid`, `not_found`, `offline`, `anchor_missing`… */
|
|
29
|
+
error?: string;
|
|
30
|
+
/** The person confirmed the change on the device (a changing tool only). */
|
|
31
|
+
confirmed?: boolean;
|
|
32
|
+
made?: string;
|
|
33
|
+
say?: string;
|
|
34
|
+
blocks?: unknown[];
|
|
35
|
+
}
|
|
36
|
+
/** The host's device tools. */
|
|
37
|
+
export interface DeviceTools {
|
|
38
|
+
/** Runs one call; never throws (a failure is `{ ok: false, error }`). */
|
|
39
|
+
run(call: DeviceCall): Promise<DeviceResult>;
|
|
40
|
+
/** The tools this device has (a flow naming another is never run). */
|
|
41
|
+
has(tool: string): boolean;
|
|
42
|
+
}
|
|
43
|
+
export interface FlowIntentView {
|
|
44
|
+
locale: string;
|
|
45
|
+
pattern: string;
|
|
46
|
+
}
|
|
47
|
+
export interface FlowStepView {
|
|
48
|
+
tool: string;
|
|
49
|
+
input: unknown;
|
|
50
|
+
}
|
|
51
|
+
export interface FlowView {
|
|
52
|
+
id: string;
|
|
53
|
+
title: string;
|
|
54
|
+
intents: FlowIntentView[];
|
|
55
|
+
steps: FlowStepView[];
|
|
56
|
+
}
|
|
57
|
+
/** A question read the way flows read it. */
|
|
58
|
+
export interface FlowQuery {
|
|
59
|
+
tokens: string[];
|
|
60
|
+
raw: string[];
|
|
61
|
+
}
|
|
62
|
+
/** One character folded (as FlowText.Fold): "" removes it. */
|
|
63
|
+
export declare function foldChar(c: string): string;
|
|
64
|
+
/** A letter or digit of a word (as FlowText.IsWord). */
|
|
65
|
+
export declare function isWordChar(c: string): boolean;
|
|
66
|
+
/** The gap a token stands for (as FlowText.Gap). */
|
|
67
|
+
export declare function gapOf(token: string): string;
|
|
68
|
+
/** Normalizes and splits a question (as FlowText.Read). */
|
|
69
|
+
export declare function readFlowText(text: string): FlowQuery;
|
|
70
|
+
/**
|
|
71
|
+
* A pattern's tokens: its words read as a question is (folded, fillers dropped), its slots kept. A host writes a seed
|
|
72
|
+
* pattern in plain words — «بارکد {code} را به این محموله اضافه کن» — and the question loses «را»: split as it was, the
|
|
73
|
+
* pattern kept it and never matched. A pattern already in the normal form reads the same.
|
|
74
|
+
*/
|
|
75
|
+
export declare function flowPatternTokens(pattern: string): string[];
|
|
76
|
+
/** Matches a question against a pattern (as FlowText.Match); null when it does not match exactly. */
|
|
77
|
+
export declare function matchFlowPattern(pattern: string, q: FlowQuery): Record<string, string> | null;
|
|
78
|
+
/** A step's input with its slots filled: a string "{slot}" becomes the value; "{slot}" inside a string is replaced. */
|
|
79
|
+
export declare function fillTemplate(template: unknown, slots: Readonly<Record<string, string>>): unknown;
|
|
80
|
+
/** Reads a flow from the wire, with type checks only. */
|
|
81
|
+
export declare function flowView(raw: unknown): FlowView | null;
|
|
82
|
+
/** One run of a flow on the device. */
|
|
83
|
+
export interface FlowRunResult {
|
|
84
|
+
ok: boolean;
|
|
85
|
+
flowId: string;
|
|
86
|
+
say: string;
|
|
87
|
+
blocks: unknown[];
|
|
88
|
+
code: string | null;
|
|
89
|
+
ms: number;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The device's flow pack: kept in the host's storage (it works offline from the first open after a sync), refreshed with
|
|
93
|
+
* its version (the server answers `unchanged`), matched against questions, run through the device tools, and every run's
|
|
94
|
+
* outcome queued and sent when online. A flow naming a tool this device does not have is never run.
|
|
95
|
+
*/
|
|
96
|
+
export declare class DeviceFlows {
|
|
97
|
+
private readonly api;
|
|
98
|
+
private readonly host;
|
|
99
|
+
private readonly tools;
|
|
100
|
+
private readonly key;
|
|
101
|
+
private readonly maxQueue;
|
|
102
|
+
version: string;
|
|
103
|
+
off: boolean;
|
|
104
|
+
flows: FlowView[];
|
|
105
|
+
private queue;
|
|
106
|
+
private seq;
|
|
107
|
+
constructor(api: AssistantApi, host: AssistantHost, tools: DeviceTools, key?: string, maxQueue?: number);
|
|
108
|
+
/** Reads the kept pack and the unsent outcomes. */
|
|
109
|
+
load(): void;
|
|
110
|
+
private save;
|
|
111
|
+
/** Asks the server for a newer pack (`unchanged` keeps the kept one). Returns whether it changed. */
|
|
112
|
+
refresh(): Promise<boolean>;
|
|
113
|
+
/** The flow and slots for a question, or null. The person's language first; only flows whose tools this device has. */
|
|
114
|
+
match(text: string, locale: string): {
|
|
115
|
+
flow: FlowView;
|
|
116
|
+
slots: Record<string, string>;
|
|
117
|
+
} | null;
|
|
118
|
+
/** Runs a matched flow: its steps in order through the device tools; a failure stops it. Records the outcome. */
|
|
119
|
+
run(flow: FlowView, slots: Readonly<Record<string, string>>, offline: boolean): Promise<FlowRunResult>;
|
|
120
|
+
/** Unsent outcomes. */
|
|
121
|
+
get pending(): number;
|
|
122
|
+
private note;
|
|
123
|
+
/** Sends the queued outcomes (in batches of 200); a failure keeps them for the next time. */
|
|
124
|
+
flush(): Promise<number>;
|
|
125
|
+
}
|
package/dist/flows.js
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Device tools and device flows (flows.ts). A device tool runs on the person's device: the server asks with a
|
|
3
|
+
* `client.call` event and waits for the answer. A flow is a question shape the device answers by itself, without a
|
|
4
|
+
* model and without a connection: intents (normalized token patterns with gaps) → device tool steps.
|
|
5
|
+
*
|
|
6
|
+
* The normalization is the SAME as the .NET core's FlowText (both are checked against contracts/examples/flow-text.json),
|
|
7
|
+
* so the server learns exactly the shapes a device matches. No Unicode property escapes (PrimJS rejects them): explicit
|
|
8
|
+
* ranges, like the .NET side.
|
|
9
|
+
*/
|
|
10
|
+
import { arr, num, obj, str } from "./api.js";
|
|
11
|
+
import { timer } from "./host.js";
|
|
12
|
+
const FILLERS = new Set([
|
|
13
|
+
"لطفا", "لطفن", "خواهشا", "رو", "را",
|
|
14
|
+
"یه", "یک", "من", "برام", "منو",
|
|
15
|
+
"میخوام", "میخواستم",
|
|
16
|
+
"please", "pls", "the", "a", "an", "me", "my", "i", "want", "to", "can", "you",
|
|
17
|
+
]);
|
|
18
|
+
/** One character folded (as FlowText.Fold): "" removes it. */
|
|
19
|
+
export function foldChar(c) {
|
|
20
|
+
const k = c.charCodeAt(0);
|
|
21
|
+
if (k >= 0x06f0 && k <= 0x06f9)
|
|
22
|
+
return String.fromCharCode(48 + k - 0x06f0);
|
|
23
|
+
if (k >= 0x0660 && k <= 0x0669)
|
|
24
|
+
return String.fromCharCode(48 + k - 0x0660);
|
|
25
|
+
if (k === 0x064a || k === 0x0649)
|
|
26
|
+
return "ی";
|
|
27
|
+
if (k === 0x0643)
|
|
28
|
+
return "ک";
|
|
29
|
+
if (k === 0x0629 || k === 0x06c0)
|
|
30
|
+
return "ه";
|
|
31
|
+
if (k === 0x0623 || k === 0x0625)
|
|
32
|
+
return "ا";
|
|
33
|
+
if (k === 0x0624)
|
|
34
|
+
return "و";
|
|
35
|
+
if (k === 0x0640)
|
|
36
|
+
return "";
|
|
37
|
+
if ((k >= 0x064b && k <= 0x065f) || k === 0x0670)
|
|
38
|
+
return "";
|
|
39
|
+
if (k >= 0x200c && k <= 0x200f)
|
|
40
|
+
return "";
|
|
41
|
+
return c;
|
|
42
|
+
}
|
|
43
|
+
/** A letter or digit of a word (as FlowText.IsWord). */
|
|
44
|
+
export function isWordChar(c) {
|
|
45
|
+
const k = c.charCodeAt(0);
|
|
46
|
+
return (k >= 97 && k <= 122) || (k >= 65 && k <= 90) || (k >= 48 && k <= 57)
|
|
47
|
+
|| (k >= 0x00c0 && k <= 0x024f && k !== 0x00d7 && k !== 0x00f7)
|
|
48
|
+
|| (k >= 0x0621 && k <= 0x063a) || (k >= 0x0641 && k <= 0x064a)
|
|
49
|
+
|| (k >= 0x066e && k <= 0x06d3) || k === 0x06d5 || k === 0x06ee || k === 0x06ef || (k >= 0x06fa && k <= 0x06fc) || k === 0x06ff;
|
|
50
|
+
}
|
|
51
|
+
function isAsciiDigit(c) {
|
|
52
|
+
const k = c.charCodeAt(0);
|
|
53
|
+
return k >= 48 && k <= 57;
|
|
54
|
+
}
|
|
55
|
+
function isAsciiLetterOrDigit(c) {
|
|
56
|
+
const k = c.charCodeAt(0);
|
|
57
|
+
return (k >= 48 && k <= 57) || (k >= 65 && k <= 90) || (k >= 97 && k <= 122);
|
|
58
|
+
}
|
|
59
|
+
/** The gap a token stands for (as FlowText.Gap). */
|
|
60
|
+
export function gapOf(token) {
|
|
61
|
+
let digits = 0;
|
|
62
|
+
let codeChars = true;
|
|
63
|
+
for (let i = 0; i < token.length; i++) {
|
|
64
|
+
const c = token.charAt(i);
|
|
65
|
+
if (isAsciiDigit(c))
|
|
66
|
+
digits++;
|
|
67
|
+
if (!(isAsciiLetterOrDigit(c) || c === "/" || c === "-" || c === "_" || c === "."))
|
|
68
|
+
codeChars = false;
|
|
69
|
+
}
|
|
70
|
+
if (digits === token.length && token.length > 0 && token.length <= 3)
|
|
71
|
+
return "{n}";
|
|
72
|
+
if (digits > 0 && token.length >= 4 && codeChars)
|
|
73
|
+
return "{code}";
|
|
74
|
+
return token;
|
|
75
|
+
}
|
|
76
|
+
/** Normalizes and splits a question (as FlowText.Read). */
|
|
77
|
+
export function readFlowText(text) {
|
|
78
|
+
let folded = "";
|
|
79
|
+
for (let i = 0; i < text.length; i++)
|
|
80
|
+
folded += foldChar(text.charAt(i));
|
|
81
|
+
let spaced = "";
|
|
82
|
+
for (let i = 0; i < folded.length; i++) {
|
|
83
|
+
const c = folded.charAt(i);
|
|
84
|
+
const joins = (c === "/" || c === "-" || c === "_" || c === ".") && i > 0 && i + 1 < folded.length
|
|
85
|
+
&& isWordChar(folded.charAt(i - 1)) && isWordChar(folded.charAt(i + 1));
|
|
86
|
+
spaced += isWordChar(c) || joins ? c : " ";
|
|
87
|
+
}
|
|
88
|
+
const tokens = [];
|
|
89
|
+
const raw = [];
|
|
90
|
+
for (const word of spaced.split(" ")) {
|
|
91
|
+
if (word.length === 0)
|
|
92
|
+
continue;
|
|
93
|
+
const w = word.toLowerCase();
|
|
94
|
+
if (FILLERS.has(w))
|
|
95
|
+
continue;
|
|
96
|
+
raw.push(word);
|
|
97
|
+
tokens.push(gapOf(w));
|
|
98
|
+
}
|
|
99
|
+
return { tokens, raw };
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* A pattern's tokens: its words read as a question is (folded, fillers dropped), its slots kept. A host writes a seed
|
|
103
|
+
* pattern in plain words — «بارکد {code} را به این محموله اضافه کن» — and the question loses «را»: split as it was, the
|
|
104
|
+
* pattern kept it and never matched. A pattern already in the normal form reads the same.
|
|
105
|
+
*/
|
|
106
|
+
export function flowPatternTokens(pattern) {
|
|
107
|
+
const out = [];
|
|
108
|
+
for (const part of pattern.split(" ")) {
|
|
109
|
+
if (part.length === 0)
|
|
110
|
+
continue;
|
|
111
|
+
if (part.length > 2 && part.charAt(0) === "{" && part.charAt(part.length - 1) === "}")
|
|
112
|
+
out.push(part);
|
|
113
|
+
else
|
|
114
|
+
out.push(...readFlowText(part).tokens);
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
/** Matches a question against a pattern (as FlowText.Match); null when it does not match exactly. */
|
|
119
|
+
export function matchFlowPattern(pattern, q) {
|
|
120
|
+
const p = flowPatternTokens(pattern);
|
|
121
|
+
const slots = {};
|
|
122
|
+
return walk(p, 0, q, 0, slots) ? slots : null;
|
|
123
|
+
}
|
|
124
|
+
function slotName(gap, slots) {
|
|
125
|
+
const base = gap.slice(1, -1);
|
|
126
|
+
if (!(base in slots))
|
|
127
|
+
return base;
|
|
128
|
+
for (let i = 2;; i++)
|
|
129
|
+
if (!(base + String(i) in slots))
|
|
130
|
+
return base + String(i);
|
|
131
|
+
}
|
|
132
|
+
function walk(p, pi, q, qi, slots) {
|
|
133
|
+
if (pi === p.length)
|
|
134
|
+
return qi === q.tokens.length;
|
|
135
|
+
const t = p[pi] ?? "";
|
|
136
|
+
if (t === "{code}" || t === "{n}") {
|
|
137
|
+
if (qi >= q.tokens.length || q.tokens[qi] !== t)
|
|
138
|
+
return false;
|
|
139
|
+
const name = slotName(t, slots);
|
|
140
|
+
slots[name] = q.raw[qi] ?? "";
|
|
141
|
+
if (walk(p, pi + 1, q, qi + 1, slots))
|
|
142
|
+
return true;
|
|
143
|
+
delete slots[name];
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
if (t.length > 2 && t.charAt(0) === "{" && t.charAt(t.length - 1) === "}") {
|
|
147
|
+
const name = t.slice(1, -1);
|
|
148
|
+
for (let end = qi + 1; end <= q.tokens.length; end++) {
|
|
149
|
+
slots[name] = q.raw.slice(qi, end).join(" ");
|
|
150
|
+
if (walk(p, pi + 1, q, end, slots))
|
|
151
|
+
return true;
|
|
152
|
+
}
|
|
153
|
+
delete slots[name];
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
return qi < q.tokens.length && q.tokens[qi] === t && walk(p, pi + 1, q, qi + 1, slots);
|
|
157
|
+
}
|
|
158
|
+
/** A step's input with its slots filled: a string "{slot}" becomes the value; "{slot}" inside a string is replaced. */
|
|
159
|
+
export function fillTemplate(template, slots) {
|
|
160
|
+
if (typeof template === "string") {
|
|
161
|
+
const whole = /^\{([a-z0-9_]+)\}$/i.exec(template);
|
|
162
|
+
if (whole && whole[1] !== undefined && whole[1] in slots)
|
|
163
|
+
return slots[whole[1]];
|
|
164
|
+
return template.replace(/\{([a-z0-9_]+)\}/gi, (m, name) => (name in slots ? (slots[name] ?? m) : m));
|
|
165
|
+
}
|
|
166
|
+
if (Array.isArray(template))
|
|
167
|
+
return template.map((x) => fillTemplate(x, slots));
|
|
168
|
+
if (template !== null && typeof template === "object") {
|
|
169
|
+
const out = {};
|
|
170
|
+
for (const k of Object.keys(template))
|
|
171
|
+
out[k] = fillTemplate(template[k], slots);
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
return template;
|
|
175
|
+
}
|
|
176
|
+
/** Reads a flow from the wire, with type checks only. */
|
|
177
|
+
export function flowView(raw) {
|
|
178
|
+
const f = obj(raw);
|
|
179
|
+
const id = str(f["id"]);
|
|
180
|
+
if (id.length === 0)
|
|
181
|
+
return null;
|
|
182
|
+
const intents = arr(f["intents"]).map((i) => ({ locale: str(obj(i)["locale"], "fa"), pattern: str(obj(i)["pattern"]) })).filter((i) => i.pattern.length > 0);
|
|
183
|
+
const steps = arr(f["steps"]).map((s) => ({ tool: str(obj(s)["tool"]), input: obj(s)["input"] ?? {} })).filter((s) => s.tool.length > 0);
|
|
184
|
+
if (intents.length === 0 || steps.length === 0)
|
|
185
|
+
return null;
|
|
186
|
+
return { id, title: str(f["title"]), intents, steps };
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The device's flow pack: kept in the host's storage (it works offline from the first open after a sync), refreshed with
|
|
190
|
+
* its version (the server answers `unchanged`), matched against questions, run through the device tools, and every run's
|
|
191
|
+
* outcome queued and sent when online. A flow naming a tool this device does not have is never run.
|
|
192
|
+
*/
|
|
193
|
+
export class DeviceFlows {
|
|
194
|
+
constructor(api, host, tools, key = "g9ai.flows", maxQueue = 500) {
|
|
195
|
+
this.api = api;
|
|
196
|
+
this.host = host;
|
|
197
|
+
this.tools = tools;
|
|
198
|
+
this.key = key;
|
|
199
|
+
this.maxQueue = maxQueue;
|
|
200
|
+
this.version = "";
|
|
201
|
+
this.off = false;
|
|
202
|
+
this.flows = [];
|
|
203
|
+
this.queue = [];
|
|
204
|
+
this.seq = 0;
|
|
205
|
+
this.load();
|
|
206
|
+
}
|
|
207
|
+
/** Reads the kept pack and the unsent outcomes. */
|
|
208
|
+
load() {
|
|
209
|
+
const s = this.host.storage;
|
|
210
|
+
if (!s)
|
|
211
|
+
return;
|
|
212
|
+
try {
|
|
213
|
+
const pack = obj(JSON.parse(s.get(this.key) ?? "{}"));
|
|
214
|
+
this.version = str(pack["version"]);
|
|
215
|
+
this.off = pack["off"] === true;
|
|
216
|
+
this.flows = arr(pack["flows"]).map(flowView).filter((f) => f !== null);
|
|
217
|
+
this.queue = arr(JSON.parse(s.get(this.key + ".outcomes") ?? "[]")).map((o) => {
|
|
218
|
+
const x = obj(o);
|
|
219
|
+
return { flowId: str(x["flowId"]), version: str(x["version"]), ok: x["ok"] === true, code: typeof x["code"] === "string" ? x["code"] : null, ms: num(x["ms"]), offline: x["offline"] === true, at: str(x["at"]) };
|
|
220
|
+
}).filter((o) => o.flowId.length > 0);
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
this.version = "";
|
|
224
|
+
this.flows = [];
|
|
225
|
+
this.queue = [];
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
save() {
|
|
229
|
+
const s = this.host.storage;
|
|
230
|
+
if (!s)
|
|
231
|
+
return;
|
|
232
|
+
try {
|
|
233
|
+
s.set(this.key, JSON.stringify({ version: this.version, off: this.off, flows: this.flows }));
|
|
234
|
+
s.set(this.key + ".outcomes", JSON.stringify(this.queue));
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
// storage full or gone: the pack is fetched again next time
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/** Asks the server for a newer pack (`unchanged` keeps the kept one). Returns whether it changed. */
|
|
241
|
+
async refresh() {
|
|
242
|
+
const r = obj(await this.api.flows(this.version));
|
|
243
|
+
if (r["unchanged"] === true && this.version.length > 0) {
|
|
244
|
+
this.off = r["off"] === true;
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
247
|
+
this.version = str(r["version"]);
|
|
248
|
+
this.off = r["off"] === true;
|
|
249
|
+
this.flows = arr(r["flows"]).map(flowView).filter((f) => f !== null);
|
|
250
|
+
this.save();
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
/** The flow and slots for a question, or null. The person's language first; only flows whose tools this device has. */
|
|
254
|
+
match(text, locale) {
|
|
255
|
+
if (this.off || this.flows.length === 0)
|
|
256
|
+
return null;
|
|
257
|
+
const q = readFlowText(text);
|
|
258
|
+
if (q.tokens.length === 0)
|
|
259
|
+
return null;
|
|
260
|
+
for (const pass of [true, false]) {
|
|
261
|
+
for (const flow of this.flows) {
|
|
262
|
+
if (!flow.steps.every((s) => this.tools.has(s.tool)))
|
|
263
|
+
continue;
|
|
264
|
+
for (const intent of flow.intents) {
|
|
265
|
+
if ((intent.locale === locale) !== pass)
|
|
266
|
+
continue;
|
|
267
|
+
const slots = matchFlowPattern(intent.pattern, q);
|
|
268
|
+
if (slots)
|
|
269
|
+
return { flow, slots };
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
/** Runs a matched flow: its steps in order through the device tools; a failure stops it. Records the outcome. */
|
|
276
|
+
async run(flow, slots, offline) {
|
|
277
|
+
const t = timer(this.host);
|
|
278
|
+
const started = t.now();
|
|
279
|
+
const says = [];
|
|
280
|
+
const blocks = [];
|
|
281
|
+
let code = null;
|
|
282
|
+
for (const step of flow.steps) {
|
|
283
|
+
this.seq++;
|
|
284
|
+
const input = obj(fillTemplate(step.input, slots));
|
|
285
|
+
let r;
|
|
286
|
+
try {
|
|
287
|
+
r = await this.tools.run({ callId: "flow:" + flow.id + ":" + String(this.seq), runId: null, tool: step.tool, input, risk: "read", confirmed: false, title: flow.title || null, source: "flow" });
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
r = { ok: false, error: "device_error" };
|
|
291
|
+
}
|
|
292
|
+
if (r.say)
|
|
293
|
+
says.push(r.say);
|
|
294
|
+
if (Array.isArray(r.blocks))
|
|
295
|
+
blocks.push(...r.blocks);
|
|
296
|
+
if (!r.ok) {
|
|
297
|
+
code = r.error ?? "device_error";
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
const ms = Math.max(0, t.now() - started);
|
|
302
|
+
this.note({ flowId: flow.id, version: this.version, ok: code === null, code, ms, offline, at: new Date(t.now()).toISOString() });
|
|
303
|
+
return { ok: code === null, flowId: flow.id, say: says.join("\n"), blocks, code, ms };
|
|
304
|
+
}
|
|
305
|
+
/** Unsent outcomes. */
|
|
306
|
+
get pending() {
|
|
307
|
+
return this.queue.length;
|
|
308
|
+
}
|
|
309
|
+
note(o) {
|
|
310
|
+
this.queue.push(o);
|
|
311
|
+
if (this.queue.length > this.maxQueue)
|
|
312
|
+
this.queue = this.queue.slice(this.queue.length - this.maxQueue);
|
|
313
|
+
this.save();
|
|
314
|
+
}
|
|
315
|
+
/** Sends the queued outcomes (in batches of 200); a failure keeps them for the next time. */
|
|
316
|
+
async flush() {
|
|
317
|
+
let sent = 0;
|
|
318
|
+
while (this.queue.length > 0) {
|
|
319
|
+
const batch = this.queue.slice(0, 200);
|
|
320
|
+
await this.api.flowOutcomes(batch);
|
|
321
|
+
this.queue = this.queue.slice(batch.length);
|
|
322
|
+
sent += batch.length;
|
|
323
|
+
this.save();
|
|
324
|
+
}
|
|
325
|
+
return sent;
|
|
326
|
+
}
|
|
327
|
+
}
|
package/dist/host.d.ts
CHANGED
|
@@ -80,6 +80,18 @@ export interface AssistantHost {
|
|
|
80
80
|
sheetLayer?: number;
|
|
81
81
|
/** Hosts whose links may be opened (https only). */
|
|
82
82
|
linkHosts?: readonly string[];
|
|
83
|
+
/** Whether the device can reach the server now (missing: assumed online). A question no device flow answers says so offline. */
|
|
84
|
+
online?(): boolean;
|
|
85
|
+
/**
|
|
86
|
+
* The page the person is on, sent with every message whose caller gives none (the composer's): an app address and
|
|
87
|
+
* what is open there (`subjectKind`/`subjectId`/`subjectLabel`). Read at the moment of sending.
|
|
88
|
+
*/
|
|
89
|
+
page?(): {
|
|
90
|
+
pageId: string;
|
|
91
|
+
subjectKind?: string;
|
|
92
|
+
subjectId?: string;
|
|
93
|
+
subjectLabel?: string;
|
|
94
|
+
} | undefined;
|
|
83
95
|
/** Called when an answer is shown, so other sheets do not cover it. */
|
|
84
96
|
onAnswerShown?(): void;
|
|
85
97
|
/** A timer (defaults to the platform's). */
|
package/dist/i18n.js
CHANGED
|
@@ -23,6 +23,10 @@ const fa = {
|
|
|
23
23
|
"provenance.model": "هوش مصنوعی",
|
|
24
24
|
"provenance.fallback": "بدون هوش مصنوعی",
|
|
25
25
|
"provenance.cached": "نتیجهٔ نگهداشته",
|
|
26
|
+
"provenance.device": "پاسخ فوری",
|
|
27
|
+
"device.needs_online": "برای این پرسش باید به اینترنت وصل باشید. کارهای آماده بدون اینترنت هم انجام میشوند.",
|
|
28
|
+
"device.flow_failed": "انجام نشد.",
|
|
29
|
+
"device.refused": "انجام ندادم؛ تأیید نکردید.",
|
|
26
30
|
"card.confirm": "تأیید و اجرا",
|
|
27
31
|
"card.refuse": "نه",
|
|
28
32
|
"card.code": "رمز تأیید",
|
|
@@ -90,6 +94,10 @@ const en = {
|
|
|
90
94
|
"provenance.model": "AI",
|
|
91
95
|
"provenance.fallback": "Without AI",
|
|
92
96
|
"provenance.cached": "Kept result",
|
|
97
|
+
"provenance.device": "Instant",
|
|
98
|
+
"device.needs_online": "This question needs the internet. Ready-made tasks still work offline.",
|
|
99
|
+
"device.flow_failed": "It did not work.",
|
|
100
|
+
"device.refused": "Not done: you did not confirm it.",
|
|
93
101
|
"card.confirm": "Confirm and run",
|
|
94
102
|
"card.refuse": "No",
|
|
95
103
|
"card.code": "Confirmation code",
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/pages.js
CHANGED
|
@@ -169,7 +169,7 @@ export function withHostTexts(texts, own) {
|
|
|
169
169
|
t(key, args) {
|
|
170
170
|
const v = texts.t(key, args);
|
|
171
171
|
const mine = own();
|
|
172
|
-
const words = Object.
|
|
172
|
+
const words = Object.prototype.hasOwnProperty.call(mine, key) ? new Map(Object.entries(mine)).get(key) : undefined; // never a prototype's member
|
|
173
173
|
return v !== key || words === undefined ? v : createTexts(texts.locale, { [key]: words }).t(key, args);
|
|
174
174
|
},
|
|
175
175
|
};
|
package/dist/state.d.ts
CHANGED
package/dist/state.js
CHANGED
|
@@ -31,6 +31,7 @@ export class StateWatch {
|
|
|
31
31
|
this.host = host;
|
|
32
32
|
this.intervalMs = intervalMs;
|
|
33
33
|
this.current = OFF;
|
|
34
|
+
this.reached = false;
|
|
34
35
|
this.listeners = new Set();
|
|
35
36
|
this.hidden = false;
|
|
36
37
|
this.stopped = true;
|
|
@@ -63,9 +64,13 @@ export class StateWatch {
|
|
|
63
64
|
t.clear(this.handle);
|
|
64
65
|
try {
|
|
65
66
|
this.current = readState(await this.api.state());
|
|
67
|
+
this.reached = true;
|
|
66
68
|
}
|
|
67
69
|
catch {
|
|
68
|
-
//
|
|
70
|
+
// Not reached: the device is offline, or the server has never answered yet — say «offline», never «off» (only the
|
|
71
|
+
// server says off). A state the server gave stays until the device knows it lost the connection.
|
|
72
|
+
if (!this.reached || this.host.online?.() === false)
|
|
73
|
+
this.current = { ...this.current, mode: "offline" };
|
|
69
74
|
}
|
|
70
75
|
for (const l of this.listeners)
|
|
71
76
|
l(this.current);
|
package/dist/types.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** Small shared types of the client core. */
|
|
2
|
-
|
|
2
|
+
/** Where an answer came from; `device` = a flow the device answered by itself (no model, no connection needed). */
|
|
3
|
+
export type Provenance = "rule" | "learned" | "model" | "fallback" | "cached" | "device";
|
|
3
4
|
/** The layouts of the ready-made components (layer 1). */
|
|
4
5
|
export type Layout = "sheet" | "side" | "fullscreen" | "inline" | "card" | "compact" | "auto";
|
|
5
6
|
/** Container widths at which "auto" picks a layout (by the container, not the window). */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@g9tm/aiassistant",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"description": "Headless client of the G9 AI assistant: API client, run state, transports, block view models, safe text and Persian helpers. No DOM, no framework.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"access": "public"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@g9tm/aiassistant-contracts": "1.
|
|
36
|
+
"@g9tm/aiassistant-contracts": "1.7.0"
|
|
37
37
|
},
|
|
38
38
|
"scripts": {
|
|
39
39
|
"build": "tsc -p tsconfig.json",
|