@ghuri/ai-widget 0.1.2 → 0.2.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
@@ -41,7 +41,8 @@ chat.addEventListener('ghuri:tool-result', (e) => {/* e.detail: toolName, input,
41
41
 
42
42
  **Parts** for anything else (`ghuri-chat::part(user-bubble) { background: … }`): `header`, `title`, `user-bubble`,
43
43
  `assistant`, `tool-step`, `decided`, `confirm-card`, `confirm-header`, `button-primary`, `button-secondary`,
44
- `problem`, `composer`, `input`, `send`, `stop`, `history`, `empty`, `starter`, `preview` (the product's description of a waiting change).
44
+ `problem`, `composer`, `input`, `send`, `stop`, `history`, `empty`, `starter`, `preview` (the product's description of a waiting change),
45
+ `attach-button`, `attachment-chips`, `attachment-chip`, `message-photos`.
45
46
 
46
47
  **Custom cards** (`cards: { <tool name>: { result?, confirm? } }`): `result` replaces a finished tool's step,
47
48
  `confirm` replaces the generic confirm card when that tool's change waits alone (`ctx.decide(true | false)`). The
@@ -53,6 +54,37 @@ and only `http(s)` and `mailto` links become links (new tab, no referrer). Enter
53
54
  and Enter during IME composition (Bangla keyboards) never sends. While a reply is streaming, closing the tab asks
54
55
  first.
55
56
 
57
+ ## Photos
58
+
59
+ Give `uploadFile` and the widget offers photos (button, drag and drop, paste) in conversations that take them:
60
+
61
+ ```ts
62
+ chat.configure({
63
+ // …
64
+ // Upload to YOUR backend; return the reference your MCP tools take. Ghuri AI never gets the bytes.
65
+ uploadFile: async (file, { name, signal, onProgress }) => {
66
+ const form = new FormData()
67
+ form.append('image', file, name)
68
+ const { file: f } = await post('/admin-api/files/', form, { signal }) // Commerce's Files upload
69
+ return { ref: f.id, name: f.name, contentType: f.contentType, size: f.size, width: f.width, height: f.height,
70
+ thumbnailUrl: new URL(f.url, location.origin).href }
71
+ },
72
+ attachments: { maxCount: 10, maxBytes: 5 * 1024 * 1024 }, // defaults; also accept, maxEdge (2048)
73
+ })
74
+ chat.addEventListener('ghuri:attachment-error', (e) => { /* e.detail: { name, reason: type|size|count|upload } */ })
75
+ ```
76
+
77
+ The photo button appears only after Ghuri AI says the app's profile takes photos (`GET /v1/capabilities`, asked when
78
+ the widget opens), and in an opened conversation only if it was started with photos; the profile's types and count
79
+ cap yours. If Ghuri AI still refuses the photos, nothing is sent, the words go back into the box and the widget says
80
+ why (`photos-refused`). Before uploading, each photo is scaled so its longest edge is at most 2,048 px and re-encoded, which drops its
81
+ metadata (the phone's location); GIFs are sent as they are. Send waits until every photo is uploaded, and while a failed
82
+ upload can still be retried (retry or remove it first). The first message of a new conversation tells Ghuri AI this client can upload
83
+ (`capabilities.attachments`), and Ghuri AI pins that on the conversation. Photos also need the product's profile to
84
+ allow them (`attachments.enabled`), and `thumbnailUrl` must be on the profile's MCP host or one listed in
85
+ `attachments.thumbnailHosts`. Roll out the widget with `uploadFile` first, then turn the profile on. Saved photos show
86
+ from `thumbnailUrl` (https only); one that cannot load shows its file name.
87
+
56
88
  ## React
57
89
 
58
90
  ```tsx
@@ -64,6 +96,7 @@ import { GhuriChat } from '@ghuri/ai-widget/react'
64
96
  open={open} onClose={() => setOpen(false)} locale="bn" subtitle={store.name}
65
97
  onToolResult={(e) => queryClient.invalidateQueries(/* … */)}
66
98
  cards={{ inventory_adjust: { confirm: (ctx) => <StockChange ctx={ctx} /> } }}
99
+ uploadFile={uploadToFiles} onAttachmentError={(e) => console.warn(e)}
67
100
  />
68
101
  ```
69
102
 
@@ -92,7 +125,9 @@ await chat.end() // logout or store switch
92
125
 
93
126
  `state.problem.code` says what went wrong in terms a UI can word: `reconnecting`, `token-expired` (offer "Continue"),
94
127
  `in-progress`, `conversation-full`, `throttled` (`retryAfter` seconds), `forbidden`, `store-unreachable`,
95
- `unavailable`, `cut-off` (offer "Reload"), `failed` (`message`).
128
+ `unavailable`, `step-limit` (the reply used all its steps with work unfinished; offer "Continue"), `too-long` (a
129
+ tool call hit the output limit and was not done; offer "Continue", which sends `continueSmallerMessage`), `answer-cut` (an answer hit the output limit and is unfinished; offer "Continue"),
130
+ `cut-off` (offer "Reload"), `failed` (`message`).
96
131
 
97
132
  The session token is kept in memory only. A `401` is handled once per request: an expired user token is refreshed
98
133
  through your backend (a new session is started if your backend says its session is gone), an expired session is
@@ -1,6 +1,13 @@
1
1
  import type { ChatClientOptions, ChatEvents, ChatState, ConversationSummary, Decision, Problem } from './types';
2
2
  type Listener = (state: ChatState) => void;
3
3
  type EventListener<K extends keyof ChatEvents> = (event: ChatEvents[K]) => void;
4
+ /** Photo defaults (Ghuri AI takes at most 10 per message; Commerce's limit is 5 MB). */
5
+ export declare const ATTACHMENT_DEFAULTS: {
6
+ readonly accept: readonly ["image/jpeg", "image/png", "image/webp", "image/gif"];
7
+ readonly maxCount: 10;
8
+ readonly maxBytes: number;
9
+ readonly maxEdge: 2048;
10
+ };
4
11
  /** What the user is told about a failed request. */
5
12
  export declare function problemFor(err: unknown): Problem;
6
13
  export declare class ChatClient {
@@ -23,6 +30,13 @@ export declare class ChatClient {
23
30
  */
24
31
  private generation;
25
32
  private seq;
33
+ /** The files behind `state.uploads` (for retries) and their upload's abort controller. */
34
+ private files;
35
+ /** Object URLs made for chips and sent photos, freed when the conversation is replaced. */
36
+ private previews;
37
+ /** The app's photo policy for new conversations, once Ghuri AI told us (`loadCapabilities`). */
38
+ private policy;
39
+ private loadingPolicy;
26
40
  constructor(opts: ChatClientOptions);
27
41
  getState(): ChatState;
28
42
  /** Called on every change; returns the unsubscribe function. */
@@ -40,8 +54,42 @@ export declare class ChatClient {
40
54
  */
41
55
  private request;
42
56
  private json;
43
- /** Send a message. Waiting changes, if any, are cancelled by it (Ghuri AI closes them). */
57
+ /**
58
+ * Send a message with the photos that finished uploading. Waiting changes, if any, are cancelled by it (Ghuri AI
59
+ * closes them). Nothing is sent while a photo is still being prepared or uploaded.
60
+ */
44
61
  send(text: string): Promise<void>;
62
+ /** The limits photos are checked against: the product's own, within what the app's profile takes. */
63
+ attachmentLimits(): {
64
+ accept: string[];
65
+ maxCount: number;
66
+ maxBytes: number;
67
+ maxEdge: number;
68
+ };
69
+ /** A photo that failed to upload and can be retried: sending would silently leave it out. */
70
+ private retryable;
71
+ /** Whether a new conversation offers photos: this client can upload and the app's profile takes them. */
72
+ private newConversationTakesPhotos;
73
+ /**
74
+ * Ask Ghuri AI whether the app takes photos (once; again after a refusal). Until it answers, no photo button: a
75
+ * photo uploaded to an app that refuses it would only leave a stray file in the product. Starts the session.
76
+ */
77
+ loadCapabilities(): Promise<void>;
78
+ private uploading;
79
+ private upload;
80
+ private refuse;
81
+ /**
82
+ * Add photos to the message being written: each is checked, scaled (location data dropped) and uploaded to the
83
+ * product. Refused ones stay as failed chips the user can remove. Does nothing where photos are not offered.
84
+ */
85
+ addFiles(files: Iterable<Blob> | ArrayLike<Blob>): void;
86
+ /** Take a photo off the message being written (stops its upload). */
87
+ removeUpload(id: string): void;
88
+ /** Upload a photo again after it failed to upload. */
89
+ retryUpload(id: string): void;
90
+ private startUpload;
91
+ /** Stop every upload and free every preview (the conversation is replaced). */
92
+ private dropPhotos;
45
93
  /** Confirm or cancel the waiting changes: one decision for each, sent together. */
46
94
  decide(decisions: Decision[]): Promise<void>;
47
95
  /** Confirm every waiting change. */
@@ -1,4 +1,6 @@
1
- export { ChatClient, problemFor } from './client';
1
+ export { ATTACHMENT_DEFAULTS, ChatClient, problemFor } from './client';
2
2
  export { messagesFromHistory } from './history';
3
+ export { parsedOutput } from './output';
4
+ export { prepareImage, scaledSize } from './prepare';
3
5
  export { parseSse, readChunks, SseParser, type StreamChunk } from './sse';
4
6
  export type * from './types';
@@ -0,0 +1,2 @@
1
+ /** Text that is a JSON object or array, parsed; anything else unchanged. */
2
+ export declare function parsedOutput(output: unknown): unknown;
@@ -0,0 +1,10 @@
1
+ import type { PreparedImage } from './types';
2
+ /** The size to draw at: the longest edge at most `maxEdge`, never enlarged. */
3
+ export declare function scaledSize(width: number, height: number, maxEdge: number): {
4
+ width: number;
5
+ height: number;
6
+ };
7
+ export declare function prepareImage(file: Blob, opts: {
8
+ maxEdge: number;
9
+ contentType: string;
10
+ }): Promise<PreparedImage>;
@@ -14,11 +14,100 @@ export interface ChatClientOptions {
14
14
  refreshUserToken: (sessionId: string) => Promise<void>;
15
15
  /** End the session, through the product's backend (logout, store switch). */
16
16
  endSession?: (sessionId: string) => Promise<void>;
17
+ /**
18
+ * Upload a photo to the product's own storage and return its reference (Commerce: `POST /admin-api/files/`). With
19
+ * it, the widget offers photos in conversations that take them; without it, never. Ghuri AI never gets the bytes.
20
+ */
21
+ uploadFile?: UploadFile;
22
+ /** Limits checked before uploading (the product checks again). */
23
+ attachments?: AttachmentOptions;
24
+ /**
25
+ * Scale a photo down and drop its metadata (phone location) before upload. Defaults to the browser helper
26
+ * (`prepareImage` in `core/prepare.ts`); pass your own on other platforms or in tests.
27
+ */
28
+ prepareImage?: (file: Blob, opts: {
29
+ maxEdge: number;
30
+ contentType: string;
31
+ }) => Promise<PreparedImage>;
17
32
  /** Defaults to the global `fetch`. */
18
33
  fetch?: typeof fetch;
19
34
  /** Defaults to `Date.now`. */
20
35
  now?: () => number;
21
36
  }
37
+ /** A photo on the product's storage, as Ghuri AI's `attachments` takes it and history returns it. */
38
+ export interface Attachment {
39
+ /** The product's opaque reference to the file (e.g. a Files library id). */
40
+ ref: string;
41
+ name: string;
42
+ contentType: string;
43
+ size?: number;
44
+ width?: number;
45
+ height?: number;
46
+ /** A picture of it on the product's own host, for display (must be a host the product declared to Ghuri AI). */
47
+ thumbnailUrl?: string;
48
+ }
49
+ /** What `uploadFile` gets with the (already scaled) file. */
50
+ export interface UploadInfo {
51
+ name: string;
52
+ contentType: string;
53
+ size: number;
54
+ width?: number;
55
+ height?: number;
56
+ /** Aborted when the user removes the photo or the conversation changes. */
57
+ signal: AbortSignal;
58
+ /** Report progress from 0 to 1 (optional). */
59
+ onProgress: (fraction: number) => void;
60
+ }
61
+ export type UploadFile = (file: Blob, info: UploadInfo) => Promise<Attachment>;
62
+ export interface AttachmentOptions {
63
+ /** Accepted types (default JPEG, PNG, WebP, GIF). */
64
+ accept?: string[];
65
+ /** Photos per message (default 10, Ghuri AI's maximum). */
66
+ maxCount?: number;
67
+ /** Largest file after scaling, in bytes (default 5 MB). */
68
+ maxBytes?: number;
69
+ /** Longest edge after scaling, in pixels (default 2048). */
70
+ maxEdge?: number;
71
+ }
72
+ /** What the app's active profile allows for photos (Ghuri AI's `GET /v1/capabilities`). */
73
+ export interface AttachmentPolicy {
74
+ enabled: boolean;
75
+ accept?: string[];
76
+ maxCount?: number;
77
+ }
78
+ export interface PreparedImage {
79
+ blob: Blob;
80
+ contentType: string;
81
+ width?: number;
82
+ height?: number;
83
+ }
84
+ /**
85
+ * A photo the user added to the message being written.
86
+ *
87
+ * - `preparing`: being scaled; `uploading`: going to the product (`progress` 0-1); `ready`: uploaded (`attachment`)
88
+ * - `failed`: `error` says why: `type` / `size` / `count` (remove it) or `upload` (retry or remove)
89
+ */
90
+ export interface Upload {
91
+ id: string;
92
+ name: string;
93
+ contentType: string;
94
+ size: number;
95
+ /** A local picture of it for the chip (an object URL), when the platform has them. */
96
+ previewUrl?: string;
97
+ status: 'preparing' | 'uploading' | 'ready' | 'failed';
98
+ progress: number;
99
+ error?: 'type' | 'size' | 'count' | 'upload';
100
+ message?: string;
101
+ attachment?: Attachment;
102
+ }
103
+ /** The photos of a user message. `previewUrl` is the local picture while the message was sent from this page. */
104
+ export interface AttachmentsPart {
105
+ kind: 'attachments';
106
+ id: string;
107
+ attachments: Array<Attachment & {
108
+ previewUrl?: string;
109
+ }>;
110
+ }
22
111
  /** One step of the AI's work in a reply: a tool it called. */
23
112
  export interface ToolPart {
24
113
  kind: 'tool';
@@ -43,7 +132,7 @@ export interface TextPart {
43
132
  id: string;
44
133
  text: string;
45
134
  }
46
- export type MessagePart = TextPart | ToolPart;
135
+ export type MessagePart = TextPart | ToolPart | AttachmentsPart;
47
136
  export interface ChatMessage {
48
137
  id: string;
49
138
  role: 'user' | 'assistant';
@@ -83,7 +172,13 @@ export interface TurnResult {
83
172
  status: 'ok' | 'paused' | 'error';
84
173
  pendingApprovals: PendingApproval[];
85
174
  error?: string;
86
- limitReached?: 'conversation' | 'turn';
175
+ /**
176
+ * `output`: the reply was cut off at the output limit (see `cut`). `steps` (with status `ok`): the assistant used all
177
+ * the steps one reply may take while it was still working; "Continue" picks the work up.
178
+ */
179
+ limitReached?: 'conversation' | 'turn' | 'output' | 'steps';
180
+ /** With `limitReached: 'output'`: a tool call was cut (it never ran) or a text answer was cut (just unfinished). */
181
+ cut?: 'tool-call' | 'text';
87
182
  userTokenExpired?: boolean;
88
183
  }
89
184
  /**
@@ -97,10 +192,14 @@ export interface TurnResult {
97
192
  * - `forbidden`: the user may not do that in this store
98
193
  * - `store-unreachable`: the product's MCP server failed; nothing was changed
99
194
  * - `unavailable`: Ghuri AI or the network is down
195
+ * - `too-long`: the reply hit the model's output limit inside a step, which was not done. Offer "Continue"
196
+ * - `answer-cut`: the answer hit the model's output limit and is unfinished; nothing was skipped. Offer "Continue"
197
+ * - `step-limit`: the reply used all its steps with work unfinished (what it did is kept). Offer "Continue"
100
198
  * - `cut-off`: the reply stopped before it finished; reload the conversation
199
+ * - `photos-refused`: Ghuri AI did not take the photos here (`message` says why); nothing was sent
101
200
  * - `failed`: anything else (`message` has the server's text)
102
201
  */
103
- export type ProblemCode = 'reconnecting' | 'token-expired' | 'in-progress' | 'conversation-full' | 'throttled' | 'forbidden' | 'store-unreachable' | 'unavailable' | 'cut-off' | 'failed';
202
+ export type ProblemCode = 'reconnecting' | 'token-expired' | 'in-progress' | 'conversation-full' | 'throttled' | 'forbidden' | 'store-unreachable' | 'unavailable' | 'too-long' | 'answer-cut' | 'step-limit' | 'cut-off' | 'photos-refused' | 'failed';
104
203
  export interface Problem {
105
204
  code: ProblemCode;
106
205
  retryAfter?: number;
@@ -129,6 +228,10 @@ export interface ChatState {
129
228
  problem: Problem | null;
130
229
  /** The last turn's result, when there was one. */
131
230
  lastTurn: TurnResult | null;
231
+ /** Whether photos can be added here: `uploadFile` is set and the open conversation takes them. */
232
+ canAttach: boolean;
233
+ /** Photos added to the message being written. */
234
+ uploads: Upload[];
132
235
  }
133
236
  /** Events for the host page (the element re-dispatches them as `ghuri:*` DOM events). */
134
237
  export interface ChatEvents {
@@ -147,4 +250,11 @@ export interface ChatEvents {
147
250
  };
148
251
  /** A turn ended. */
149
252
  'turn-end': TurnResult;
253
+ /** A photo was refused or failed to upload. */
254
+ 'attachment-error': {
255
+ name: string;
256
+ contentType: string;
257
+ reason: 'type' | 'size' | 'count' | 'upload';
258
+ message?: string;
259
+ };
150
260
  }