@ghuri/ai-widget 0.1.3 → 0.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/README.md CHANGED
@@ -36,12 +36,14 @@ chat.addEventListener('ghuri:tool-result', (e) => {/* e.detail: toolName, input,
36
36
  `--ghuri-accent`, `--ghuri-accent-text`, `--ghuri-accent-soft`, `--ghuri-accent-soft-text`, `--ghuri-accent-border`,
37
37
  `--ghuri-surface`, `--ghuri-background`, `--ghuri-muted-surface`, `--ghuri-text`, `--ghuri-muted`, `--ghuri-border`,
38
38
  `--ghuri-success`, `--ghuri-warning`, `--ghuri-warning-soft`, `--ghuri-danger`, `--ghuri-danger-soft`,
39
+ `--ghuri-allowed`, `--ghuri-allowed-soft` (the "Allowed" tag and bar),
39
40
  `--ghuri-font`, `--ghuri-font-size`, `--ghuri-radius`, `--ghuri-radius-sm`, `--ghuri-bubble-radius`,
40
41
  `--ghuri-shadow`, `--ghuri-page-width`, and `--ghuri-kite-maroon` / `-red` / `-green` (lift them in dark mode).
41
42
 
42
43
  **Parts** for anything else (`ghuri-chat::part(user-bubble) { background: … }`): `header`, `title`, `user-bubble`,
43
44
  `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).
45
+ `problem`, `composer`, `input`, `send`, `stop`, `history`, `empty`, `starter`, `preview` (the product's description of a waiting change),
46
+ `attach-button`, `attachment-chips`, `attachment-chip`, `message-photos`.
45
47
 
46
48
  **Custom cards** (`cards: { <tool name>: { result?, confirm? } }`): `result` replaces a finished tool's step,
47
49
  `confirm` replaces the generic confirm card when that tool's change waits alone (`ctx.decide(true | false)`). The
@@ -53,6 +55,37 @@ and only `http(s)` and `mailto` links become links (new tab, no referrer). Enter
53
55
  and Enter during IME composition (Bangla keyboards) never sends. While a reply is streaming, closing the tab asks
54
56
  first.
55
57
 
58
+ ## Photos
59
+
60
+ Give `uploadFile` and the widget offers photos (button, drag and drop, paste) in conversations that take them:
61
+
62
+ ```ts
63
+ chat.configure({
64
+ // …
65
+ // Upload to YOUR backend; return the reference your MCP tools take. Ghuri AI never gets the bytes.
66
+ uploadFile: async (file, { name, signal, onProgress }) => {
67
+ const form = new FormData()
68
+ form.append('image', file, name)
69
+ const { file: f } = await post('/admin-api/files/', form, { signal }) // Commerce's Files upload
70
+ return { ref: f.id, name: f.name, contentType: f.contentType, size: f.size, width: f.width, height: f.height,
71
+ thumbnailUrl: new URL(f.url, location.origin).href }
72
+ },
73
+ attachments: { maxCount: 10, maxBytes: 5 * 1024 * 1024 }, // defaults; also accept, maxEdge (2048)
74
+ })
75
+ chat.addEventListener('ghuri:attachment-error', (e) => { /* e.detail: { name, reason: type|size|count|upload } */ })
76
+ ```
77
+
78
+ The photo button appears only after Ghuri AI says the app's profile takes photos (`GET /v1/capabilities`, asked when
79
+ the widget opens), and in an opened conversation only if it was started with photos; the profile's types and count
80
+ cap yours. If Ghuri AI still refuses the photos, nothing is sent, the words go back into the box and the widget says
81
+ 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
82
+ metadata (the phone's location); GIFs are sent as they are. Send waits until every photo is uploaded, and while a failed
83
+ upload can still be retried (retry or remove it first). The first message of a new conversation tells Ghuri AI this client can upload
84
+ (`capabilities.attachments`), and Ghuri AI pins that on the conversation. Photos also need the product's profile to
85
+ allow them (`attachments.enabled`), and `thumbnailUrl` must be on the profile's MCP host or one listed in
86
+ `attachments.thumbnailHosts`. Roll out the widget with `uploadFile` first, then turn the profile on. Saved photos show
87
+ from `thumbnailUrl` (https only); one that cannot load shows its file name.
88
+
56
89
  ## React
57
90
 
58
91
  ```tsx
@@ -64,6 +97,7 @@ import { GhuriChat } from '@ghuri/ai-widget/react'
64
97
  open={open} onClose={() => setOpen(false)} locale="bn" subtitle={store.name}
65
98
  onToolResult={(e) => queryClient.invalidateQueries(/* … */)}
66
99
  cards={{ inventory_adjust: { confirm: (ctx) => <StockChange ctx={ctx} /> } }}
100
+ uploadFile={uploadToFiles} onAttachmentError={(e) => console.warn(e)}
67
101
  />
68
102
  ```
69
103
 
@@ -85,6 +119,8 @@ chat.on('tool-result', (e) => { /* e.toolName, e.input, e.output */ })
85
119
 
86
120
  await chat.send('lal saree koto ache?')
87
121
  await chat.decide([{ approvalId, approved: true }]) // or chat.approveAll() / chat.rejectAll()
122
+ await chat.decide([{ approvalId, approved: true, allowForConversation: true }]) // only where approval.allowable
123
+ await chat.revokeAllowance('theme_files_write') // "Ask every time": state.allowances lists what is allowed
88
124
  chat.stop(); await chat.retry(); await chat.reload()
89
125
  await chat.listConversations(); await chat.openConversation(id); chat.newConversation()
90
126
  await chat.end() // logout or store switch
@@ -92,7 +128,9 @@ await chat.end() // logout or store switch
92
128
 
93
129
  `state.problem.code` says what went wrong in terms a UI can word: `reconnecting`, `token-expired` (offer "Continue"),
94
130
  `in-progress`, `conversation-full`, `throttled` (`retryAfter` seconds), `forbidden`, `store-unreachable`,
95
- `unavailable`, `cut-off` (offer "Reload"), `failed` (`message`).
131
+ `unavailable`, `step-limit` (the reply used all its steps with work unfinished; offer "Continue"), `too-long` (a
132
+ 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"),
133
+ `cut-off` (offer "Reload"), `failed` (`message`).
96
134
 
97
135
  The session token is kept in memory only. A `401` is handled once per request: an expired user token is refreshed
98
136
  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,10 +54,49 @@ 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>;
95
+ /**
96
+ * Take back "Allow for this conversation" for a tool: its next call asks again. Returns whether Ghuri AI took it
97
+ * back (false: nothing was in force, or the request failed; the problem then says why).
98
+ */
99
+ revokeAllowance(toolName: string): Promise<boolean>;
47
100
  /** Confirm every waiting change. */
48
101
  approveAll(): Promise<void>;
49
102
  /** Cancel every waiting change. */
@@ -1,5 +1,6 @@
1
- export { ChatClient, problemFor } from './client';
1
+ export { ATTACHMENT_DEFAULTS, ChatClient, problemFor } from './client';
2
2
  export { messagesFromHistory } from './history';
3
3
  export { parsedOutput } from './output';
4
+ export { prepareImage, scaledSize } from './prepare';
4
5
  export { parseSse, readChunks, SseParser, type StreamChunk } from './sse';
5
6
  export type * from './types';
@@ -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';
@@ -37,13 +126,17 @@ export interface ToolPart {
37
126
  approvalId?: string;
38
127
  output?: unknown;
39
128
  errorText?: string;
129
+ /** It ran without a confirm card, on an allowance the user gave for this conversation ("Allowed"). */
130
+ allowed?: boolean;
131
+ /** The user confirmed this change with "Allow for this conversation". */
132
+ granted?: boolean;
40
133
  }
41
134
  export interface TextPart {
42
135
  kind: 'text';
43
136
  id: string;
44
137
  text: string;
45
138
  }
46
- export type MessagePart = TextPart | ToolPart;
139
+ export type MessagePart = TextPart | ToolPart | AttachmentsPart;
47
140
  export interface ChatMessage {
48
141
  id: string;
49
142
  role: 'user' | 'assistant';
@@ -70,11 +163,22 @@ export interface PendingApproval {
70
163
  input: unknown;
71
164
  /** The product's description of the change, when it gave one. */
72
165
  preview?: ChangePreview;
166
+ /** The user may answer with "Allow for this conversation" (the product made this tool allowable). */
167
+ allowable?: boolean;
73
168
  }
74
169
  export interface Decision {
75
170
  approvalId: string;
76
171
  approved: boolean;
77
172
  reason?: string;
173
+ /** Confirm and let later calls of the same tool in this conversation run without a card. Needs `allowable`. */
174
+ allowForConversation?: boolean;
175
+ }
176
+ /** A tool the user allowed for this conversation: it runs without asking until taken back or `expiresAt`. */
177
+ export interface Allowance {
178
+ toolName: string;
179
+ title?: string;
180
+ grantedAt: string;
181
+ expiresAt: string;
78
182
  }
79
183
  /** The end of a turn (Ghuri AI's `data-turn` part). */
80
184
  export interface TurnResult {
@@ -83,7 +187,15 @@ export interface TurnResult {
83
187
  status: 'ok' | 'paused' | 'error';
84
188
  pendingApprovals: PendingApproval[];
85
189
  error?: string;
86
- limitReached?: 'conversation' | 'turn';
190
+ /**
191
+ * `output`: the reply was cut off at the output limit (see `cut`). `steps` (with status `ok`): the assistant used all
192
+ * the steps one reply may take while it was still working; "Continue" picks the work up.
193
+ */
194
+ limitReached?: 'conversation' | 'turn' | 'output' | 'steps';
195
+ /** The tools allowed for this conversation when the turn ended (absent: none). */
196
+ allowances?: Allowance[];
197
+ /** With `limitReached: 'output'`: a tool call was cut (it never ran) or a text answer was cut (just unfinished). */
198
+ cut?: 'tool-call' | 'text';
87
199
  userTokenExpired?: boolean;
88
200
  }
89
201
  /**
@@ -97,10 +209,14 @@ export interface TurnResult {
97
209
  * - `forbidden`: the user may not do that in this store
98
210
  * - `store-unreachable`: the product's MCP server failed; nothing was changed
99
211
  * - `unavailable`: Ghuri AI or the network is down
212
+ * - `too-long`: the reply hit the model's output limit inside a step, which was not done. Offer "Continue"
213
+ * - `answer-cut`: the answer hit the model's output limit and is unfinished; nothing was skipped. Offer "Continue"
214
+ * - `step-limit`: the reply used all its steps with work unfinished (what it did is kept). Offer "Continue"
100
215
  * - `cut-off`: the reply stopped before it finished; reload the conversation
216
+ * - `photos-refused`: Ghuri AI did not take the photos here (`message` says why); nothing was sent
101
217
  * - `failed`: anything else (`message` has the server's text)
102
218
  */
103
- export type ProblemCode = 'reconnecting' | 'token-expired' | 'in-progress' | 'conversation-full' | 'throttled' | 'forbidden' | 'store-unreachable' | 'unavailable' | 'cut-off' | 'failed';
219
+ 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
220
  export interface Problem {
105
221
  code: ProblemCode;
106
222
  retryAfter?: number;
@@ -129,6 +245,12 @@ export interface ChatState {
129
245
  problem: Problem | null;
130
246
  /** The last turn's result, when there was one. */
131
247
  lastTurn: TurnResult | null;
248
+ /** Whether photos can be added here: `uploadFile` is set and the open conversation takes them. */
249
+ canAttach: boolean;
250
+ /** Photos added to the message being written. */
251
+ uploads: Upload[];
252
+ /** Tools allowed for this conversation ("Allow for this conversation"); the bar above the composer lists them. */
253
+ allowances: Allowance[];
132
254
  }
133
255
  /** Events for the host page (the element re-dispatches them as `ghuri:*` DOM events). */
134
256
  export interface ChatEvents {
@@ -147,4 +269,11 @@ export interface ChatEvents {
147
269
  };
148
270
  /** A turn ended. */
149
271
  'turn-end': TurnResult;
272
+ /** A photo was refused or failed to upload. */
273
+ 'attachment-error': {
274
+ name: string;
275
+ contentType: string;
276
+ reason: 'type' | 'size' | 'count' | 'upload';
277
+ message?: string;
278
+ };
150
279
  }