@g9tm/aiassistant 1.1.0 → 1.3.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/api.d.ts CHANGED
@@ -60,12 +60,14 @@ export declare class AssistantApi {
60
60
  capabilities(): Promise<unknown>;
61
61
  feedback(conversationId: string, messageId: string, good: boolean, note?: string): Promise<unknown>;
62
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
- }>;
63
+ upload(name: string, bytes: Uint8Array): Promise<UploadedFile>;
64
+ /** Where a host's own uploader sends a file (`AssistantHost.uploadFile`). */
65
+ get filesPath(): string;
66
+ /** The server's answer to a host's own upload, read as `upload` reads its own (a refusal throws its code). */
67
+ readUpload(answer: {
68
+ status: number;
69
+ body: string;
70
+ }): UploadedFile;
69
71
  /** Dictation: audio to text on the server (the audio is not kept). */
70
72
  speech(bytes: Uint8Array, mime: string): Promise<string>;
71
73
  removeFile(id: string): Promise<unknown>;
@@ -79,3 +81,10 @@ export declare class AssistantApi {
79
81
  delete(path: string): Promise<unknown>;
80
82
  }
81
83
  export declare function toRawEvent(v: unknown): RawEvent;
84
+ /** A file the server took. */
85
+ export interface UploadedFile {
86
+ id: string;
87
+ kind: string;
88
+ name: string;
89
+ rows?: number;
90
+ }
package/dist/api.js CHANGED
@@ -46,21 +46,7 @@ export class AssistantApi {
46
46
  const init = payload === undefined ? { method, headers } : { method, headers, body: payload };
47
47
  try {
48
48
  const response = await Promise.race([this.host.fetch(this.base + path, init), timeout]); // AbortController is not on Lynx
49
- const text = await response.text();
50
- let parsed = null;
51
- if (text.length > 0) {
52
- try {
53
- parsed = JSON.parse(text);
54
- }
55
- catch {
56
- parsed = text;
57
- }
58
- }
59
- if (!response.ok) {
60
- const e = obj(parsed)["error"];
61
- throw new ApiError(response.status, typeof e === "string" ? e : str(obj(e)["code"], "error"), parsed);
62
- }
63
- return parsed;
49
+ return answerOf(response.status, await response.text());
64
50
  }
65
51
  finally {
66
52
  t.clear(handle);
@@ -108,12 +94,12 @@ export class AssistantApi {
108
94
  return this.request("POST", kind + "/" + encodeURIComponent(id) + "/" + verb);
109
95
  }
110
96
  async upload(name, bytes) {
111
- const r = obj(await this.request("POST", "files?name=" + encodeURIComponent(name), undefined, { bytes, type: "application/octet-stream" }));
112
- const out = { id: str(r["id"]), kind: str(r["kind"]), name: str(r["name"]) };
113
- if (typeof r["rows"] === "number")
114
- out.rows = r["rows"];
115
- return out;
97
+ return uploaded(await this.request("POST", "files?name=" + encodeURIComponent(name), undefined, { bytes, type: "application/octet-stream" }));
116
98
  }
99
+ /** Where a host's own uploader sends a file (`AssistantHost.uploadFile`). */
100
+ get filesPath() { return this.base + "files"; }
101
+ /** The server's answer to a host's own upload, read as `upload` reads its own (a refusal throws its code). */
102
+ readUpload(answer) { return uploaded(answerOf(answer.status, answer.body)); }
117
103
  /** Dictation: audio to text on the server (the audio is not kept). */
118
104
  async speech(bytes, mime) {
119
105
  return str(obj(await this.request("POST", "speech?mime=" + encodeURIComponent(mime), undefined, { bytes, type: "application/octet-stream" }))["text"]);
@@ -132,3 +118,27 @@ export function toRawEvent(v) {
132
118
  const e = obj(v);
133
119
  return { seq: num(e["seq"]), type: str(e["type"]), at: str(e["at"]), body: obj(e["body"]) };
134
120
  }
121
+ function uploaded(v) {
122
+ const r = obj(v);
123
+ const out = { id: str(r["id"]), kind: str(r["kind"]), name: str(r["name"]) };
124
+ if (typeof r["rows"] === "number")
125
+ out.rows = r["rows"];
126
+ return out;
127
+ }
128
+ /** A response's JSON (or its text), or the `ApiError` of a status outside 2xx. */
129
+ function answerOf(status, text) {
130
+ let parsed = null;
131
+ if (text.length > 0) {
132
+ try {
133
+ parsed = JSON.parse(text);
134
+ }
135
+ catch {
136
+ parsed = text;
137
+ }
138
+ }
139
+ if (status < 200 || status > 299) {
140
+ const e = obj(parsed)["error"];
141
+ throw new ApiError(status, typeof e === "string" ? e : str(obj(e)["code"], "error"), parsed);
142
+ }
143
+ return parsed;
144
+ }
@@ -36,6 +36,8 @@ export interface AssistantSnapshot {
36
36
  state: AssistantState;
37
37
  error: string | null;
38
38
  }
39
+ /** The files the composer offers by default. */
40
+ export declare const ATTACH_ACCEPT: readonly string[];
39
41
  export declare class Assistant {
40
42
  readonly host: AssistantHost;
41
43
  readonly api: AssistantApi;
@@ -81,6 +83,11 @@ export declare class Assistant {
81
83
  answer(runId: string, cardId: string, picked: string[], text: string | null): Promise<boolean>;
82
84
  /** Answers a "learn this?" or "make it a routine?" card once. */
83
85
  choose(kind: "knowledge" | "learned", cardId: string, verb: string): Promise<boolean>;
86
+ /**
87
+ * The composer's attach button: the host's own uploader when it has one (the bytes never cross a bridge), otherwise
88
+ * its picker and `attach`.
89
+ */
90
+ attachFromDevice(accept?: readonly string[]): Promise<void>;
84
91
  attach(name: string, bytes: Uint8Array): Promise<void>;
85
92
  detach(id: string): void;
86
93
  notRight(messageId: string): Promise<void>;
package/dist/assistant.js CHANGED
@@ -13,6 +13,8 @@ import { emptyRun, finished, reduceRun } from "./run.js";
13
13
  import { StateWatch } from "./state.js";
14
14
  import { transcript } from "./transcript.js";
15
15
  import { pickTransport } from "./transport.js";
16
+ /** The files the composer offers by default. */
17
+ export const ATTACH_ACCEPT = [".pdf", ".xlsx", ".csv", "image/*"];
16
18
  export class Assistant {
17
19
  constructor(host, options = {}) {
18
20
  this.host = host;
@@ -221,6 +223,30 @@ export class Assistant {
221
223
  await this.api.card(kind, cardId, verb);
222
224
  return true;
223
225
  }
226
+ /**
227
+ * The composer's attach button: the host's own uploader when it has one (the bytes never cross a bridge), otherwise
228
+ * its picker and `attach`.
229
+ */
230
+ async attachFromDevice(accept = ATTACH_ACCEPT) {
231
+ const up = this.host.uploadFile;
232
+ if (!up) {
233
+ const f = await this.host.pickFile?.([...accept]);
234
+ if (f)
235
+ await this.attach(f.name, f.bytes);
236
+ return;
237
+ }
238
+ try {
239
+ const answer = await up.call(this.host, this.api.filesPath, [...accept]);
240
+ if (answer === null)
241
+ return;
242
+ const f = this.api.readUpload(answer);
243
+ this.attachments = [...this.attachments, { id: f.id, name: f.name, kind: f.kind }];
244
+ }
245
+ catch (e) {
246
+ this.error = e instanceof ApiError ? e.code : "error.network";
247
+ }
248
+ this.emit();
249
+ }
224
250
  async attach(name, bytes) {
225
251
  try {
226
252
  const f = await this.api.upload(name, bytes);
package/dist/host.d.ts CHANGED
@@ -41,6 +41,16 @@ export interface AssistantHost {
41
41
  copy?(text: string): Promise<void>;
42
42
  openUrl?(url: string): void;
43
43
  pickFile?(accept: string[]): Promise<HostFile | null>;
44
+ /**
45
+ * A device's own picker and uploader: it lets the person pick a file and sends it as `multipart/form-data` (field
46
+ * `file`, with the host's own `Authorization`) to `path`, so the bytes never cross a bridge. It returns the server's
47
+ * answer as it came, or `null` when the person cancelled. When present, the composer uses it instead of `pickFile`.
48
+ * The server takes such an upload only from a request its `IRequestGuard` vouches for (a bearer token).
49
+ */
50
+ uploadFile?(path: string, accept: string[]): Promise<{
51
+ status: number;
52
+ body: string;
53
+ } | null>;
44
54
  pickImage?(): Promise<HostFile | null>;
45
55
  saveFile?(name: string, data: Uint8Array | string): Promise<boolean>;
46
56
  share?(text: string): Promise<void>;
package/dist/host.js CHANGED
@@ -3,7 +3,7 @@
3
3
  export function can(host, feature) {
4
4
  switch (feature) {
5
5
  case "copy": return typeof host.copy === "function";
6
- case "attach": return typeof host.pickFile === "function" || typeof host.pickImage === "function";
6
+ case "attach": return typeof host.pickFile === "function" || typeof host.uploadFile === "function" || typeof host.pickImage === "function";
7
7
  case "save": return typeof host.saveFile === "function";
8
8
  case "share": return typeof host.share === "function";
9
9
  case "stream": return typeof host.eventSource === "function";
package/dist/i18n.js CHANGED
@@ -52,16 +52,6 @@ const fa = {
52
52
  "history.pinned": "سنجاق‌شده",
53
53
  "history.waiting": "منتظر",
54
54
  "history.search": "جست‌وجو",
55
- "history.pin": "سنجاق",
56
- "history.unpin": "برداشتن سنجاق",
57
- "history.delete": "حذف",
58
- "history.delete_confirm": "این گفت‌وگو حذف شود؟",
59
- "routine.choose": "انتخاب",
60
- "routine.back": "بازگشت",
61
- "routine.preview": "پیش‌نمایش",
62
- "routine.missing": "لازم است",
63
- "routine.invalid": "درست نیست",
64
- "routine.done": "انجام شد",
65
55
  "csv.save": "ذخیره به CSV",
66
56
  "csv.saved": "ذخیره شد",
67
57
  "csv.not_saved": "ذخیره نشد",
@@ -129,16 +119,6 @@ const en = {
129
119
  "history.pinned": "Pinned",
130
120
  "history.waiting": "Waiting",
131
121
  "history.search": "Search",
132
- "history.pin": "Pin",
133
- "history.unpin": "Unpin",
134
- "history.delete": "Delete",
135
- "history.delete_confirm": "Delete this conversation?",
136
- "routine.choose": "Choose",
137
- "routine.back": "Back",
138
- "routine.preview": "Preview",
139
- "routine.missing": "Required",
140
- "routine.invalid": "Not right",
141
- "routine.done": "Done",
142
122
  "csv.save": "Save as CSV",
143
123
  "csv.saved": "Saved",
144
124
  "csv.not_saved": "Not saved",
package/dist/pages.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { AssistantApi } from "./api.js";
2
+ import type { Assistant } from "./assistant.js";
3
+ import type { Texts } from "./i18n.js";
2
4
  export * from "./csv.js";
3
5
  export * from "./history.js";
4
6
  export * from "./routine.js";
@@ -17,3 +19,27 @@ export declare const pageCalls: {
17
19
  /** Runs a previewed routine with the person's confirmation. */
18
20
  run: (api: AssistantApi, routineId: string, routineRunId: string, hash: string, code?: string) => Promise<unknown>;
19
21
  };
22
+ /**
23
+ * Starts a run of a non-conversation capability (`POST capabilities/{id}/runs`, for a host's own screens without a
24
+ * chat) and follows it on the assistant: `snapshot().run` shows its stages, then its `result` (output, provenance).
25
+ * Returns the run's id; a refusal throws its `ApiError` (`assistant-limit` with the limit reached).
26
+ */
27
+ export declare function runCapability(assistant: Assistant, id: string, options?: {
28
+ input?: Record<string, unknown>;
29
+ key?: string;
30
+ }): Promise<string>;
31
+ /** The pages' texts over the assistant's: the host's texts and the core's win, then the pages' own. */
32
+ export declare function pageTexts(texts: Texts): Texts;
33
+ /** Every key the pages add (for hosts that translate to another language). */
34
+ export declare function pageKeys(): string[];
35
+ /**
36
+ * The host's own words (`GET texts`: its `AssistantSetup.Texts` for the locale), read once by a renderer's root. An older
37
+ * server without the endpoint gives none: nothing changes.
38
+ */
39
+ export declare function loadHostTexts(assistant: Assistant): Promise<Readonly<Record<string, string>>>;
40
+ /**
41
+ * The assistant's texts with the host's server words under them: a key the client knows (the host's client overrides,
42
+ * the library's words) keeps its words; a host key it does not know (a card's fact, a finding's title, a tool's name)
43
+ * shows the host's server words. `own` is read at every call, so texts loaded later apply at the next render.
44
+ */
45
+ export declare function withHostTexts(texts: Texts, own: () => Readonly<Record<string, string>>): Texts;
package/dist/pages.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createTexts } from "./i18n.js";
1
2
  export * from "./csv.js";
2
3
  export * from "./history.js";
3
4
  export * from "./routine.js";
@@ -17,3 +18,124 @@ export const pageCalls = {
17
18
  /** Runs a previewed routine with the person's confirmation. */
18
19
  run: (api, routineId, routineRunId, hash, code) => api.post("routines/" + enc(routineId) + "/run", code ? { routineRunId, hash, code } : { routineRunId, hash }),
19
20
  };
21
+ /**
22
+ * Starts a run of a non-conversation capability (`POST capabilities/{id}/runs`, for a host's own screens without a
23
+ * chat) and follows it on the assistant: `snapshot().run` shows its stages, then its `result` (output, provenance).
24
+ * Returns the run's id; a refusal throws its `ApiError` (`assistant-limit` with the limit reached).
25
+ */
26
+ export async function runCapability(assistant, id, options = {}) {
27
+ const r = await assistant.api.post("capabilities/" + enc(id) + "/runs", options);
28
+ const runId = typeof r === "object" && r !== null ? r.runId : undefined;
29
+ if (typeof runId !== "string" || runId.length === 0)
30
+ throw new Error("assistant api: no runId");
31
+ assistant.follow(runId);
32
+ return runId;
33
+ }
34
+ /** The words of the person's pages (history, routine wizard) and of a refused confirmation, both languages, kept out of the core every surface loads. */
35
+ const PAGE_FA = {
36
+ "history.tabs": "گفت‌وگوها",
37
+ "history.empty": "چیزی اینجا نیست",
38
+ "history.untitled": "بی‌نام",
39
+ "routine.list": "روال‌ها",
40
+ "routine.empty": "هنوز روالی نیست",
41
+ "routine.search": "جست‌وجو…",
42
+ "routine.none_found": "چیزی پیدا نشد",
43
+ "routine.change": "تغییر",
44
+ "routine.failed": "اجرا نشد",
45
+ "history.pin": "سنجاق",
46
+ "history.unpin": "برداشتن سنجاق",
47
+ "history.delete": "حذف",
48
+ "history.delete_confirm": "این گفت‌وگو حذف شود؟",
49
+ "routine.choose": "انتخاب",
50
+ "routine.back": "بازگشت",
51
+ "routine.preview": "پیش‌نمایش",
52
+ "routine.missing": "لازم است",
53
+ "routine.invalid": "درست نیست",
54
+ "routine.done": "انجام شد",
55
+ "confirm.code_wrong": "کد درست نیست",
56
+ "confirm.code_missing": "کد را وارد کنید",
57
+ "confirm.locked": "تلاش‌ها زیاد شد؛ کمی بعد دوباره امتحان کنید",
58
+ "confirm.expired": "زمان این کارت گذشته است",
59
+ "confirm.not_pending": "این کارت دیگر منتظر نیست",
60
+ "confirm.plan_changed": "این کار عوض شده است؛ کارت تازه را ببینید",
61
+ "confirm.nothing_left": "کاری برای انجام نماند",
62
+ "confirm.no_gate": "تأیید با کد اینجا راه نیفتاده است",
63
+ "confirm.failed": "تأیید نشد",
64
+ "plan.locked": "این کارت بسته شد",
65
+ "error": "کار انجام نشد",
66
+ };
67
+ const PAGE_EN = {
68
+ "history.tabs": "Conversations",
69
+ "history.empty": "Nothing here",
70
+ "history.untitled": "Untitled",
71
+ "routine.list": "Routines",
72
+ "routine.empty": "No routines yet",
73
+ "routine.search": "Search…",
74
+ "routine.none_found": "Nothing found",
75
+ "routine.change": "Change",
76
+ "routine.failed": "It did not run",
77
+ "history.pin": "Pin",
78
+ "history.unpin": "Unpin",
79
+ "history.delete": "Delete",
80
+ "history.delete_confirm": "Delete this conversation?",
81
+ "routine.choose": "Choose",
82
+ "routine.back": "Back",
83
+ "routine.preview": "Preview",
84
+ "routine.missing": "Required",
85
+ "routine.invalid": "Not right",
86
+ "routine.done": "Done",
87
+ "confirm.code_wrong": "The code is not right",
88
+ "confirm.code_missing": "Enter the code",
89
+ "confirm.locked": "Too many tries; try again a little later",
90
+ "confirm.expired": "This card's time is over",
91
+ "confirm.not_pending": "This card is no longer waiting",
92
+ "confirm.plan_changed": "This work changed; see the new card",
93
+ "confirm.nothing_left": "Nothing is left to do",
94
+ "confirm.no_gate": "Confirming with a code is not set up here",
95
+ "confirm.failed": "Not confirmed",
96
+ "plan.locked": "This card was closed",
97
+ "error": "It did not go through",
98
+ };
99
+ /** The pages' texts over the assistant's: the host's texts and the core's win, then the pages' own. */
100
+ export function pageTexts(texts) {
101
+ const own = createTexts(texts.locale, texts.locale === "fa" ? PAGE_FA : PAGE_EN);
102
+ return {
103
+ locale: texts.locale,
104
+ t(key, args) {
105
+ const v = texts.t(key, args);
106
+ return v !== key ? v : own.t(key, args);
107
+ },
108
+ };
109
+ }
110
+ /** Every key the pages add (for hosts that translate to another language). */
111
+ export function pageKeys() {
112
+ return Object.keys(PAGE_EN).sort();
113
+ }
114
+ /**
115
+ * The host's own words (`GET texts`: its `AssistantSetup.Texts` for the locale), read once by a renderer's root. An older
116
+ * server without the endpoint gives none: nothing changes.
117
+ */
118
+ export async function loadHostTexts(assistant) {
119
+ try {
120
+ const own = (await assistant.api.get("texts?locale=" + enc(assistant.texts.locale))).texts;
121
+ return typeof own === "object" && own !== null ? own : {};
122
+ }
123
+ catch {
124
+ return {};
125
+ }
126
+ }
127
+ /**
128
+ * The assistant's texts with the host's server words under them: a key the client knows (the host's client overrides,
129
+ * the library's words) keeps its words; a host key it does not know (a card's fact, a finding's title, a tool's name)
130
+ * shows the host's server words. `own` is read at every call, so texts loaded later apply at the next render.
131
+ */
132
+ export function withHostTexts(texts, own) {
133
+ return {
134
+ locale: texts.locale,
135
+ t(key, args) {
136
+ const v = texts.t(key, args);
137
+ const words = own()[key];
138
+ return v !== key || words === undefined ? v : createTexts(texts.locale, { [key]: words }).t(key, args);
139
+ },
140
+ };
141
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@g9tm/aiassistant",
3
- "version": "1.1.0",
3
+ "version": "1.3.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.1.0"
36
+ "@g9tm/aiassistant-contracts": "1.3.0"
37
37
  },
38
38
  "scripts": {
39
39
  "build": "tsc -p tsconfig.json",