@ghuri/ai-widget 0.4.0 → 0.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/README.md CHANGED
@@ -44,7 +44,16 @@ chat.addEventListener('ghuri:tool-result', (e) => {/* e.detail: toolName, input,
44
44
  **Parts** for anything else (`ghuri-chat::part(user-bubble) { background: … }`): `header`, `title`, `user-bubble`,
45
45
  `assistant`, `tool-step`, `decided`, `confirm-card`, `confirm-header`, `button-primary`, `button-secondary`,
46
46
  `problem`, `composer`, `input`, `send`, `stop`, `history`, `empty`, `starter`, `preview` (the product's description of a waiting change),
47
- `attach-button`, `attachment-chips`, `attachment-chip`, `message-photos`.
47
+ `attach-button`, `attachment-chips`, `attachment-chip`, `message-photos`, `confirm-group` and `confirm-line` (many
48
+ waiting changes of one tool), `decided-group` (decided steps of one tool, folded), `carried-over`.
49
+
50
+ **Many changes of one tool** (0.7.0, [docs/many-changes.md](../docs/many-changes.md)): three or more waiting changes
51
+ of one tool are one compact list in the confirm card: a tick for the group, one line per change with the product's
52
+ description and its first change ("now 0 → 10"), the first 6 lines shown and the rest behind "Show all N" (still
53
+ ticked and counted in "Confirm N"); a line opens to exactly what will be sent, and a change without a description
54
+ shows its values on its line. After the decision, three or more decided steps of one tool in a row fold into one line
55
+ with their counts ("17 done · 1 failed · 1 cancelled"); a failed one stays outside the fold with its error. Labels:
56
+ `labels.many`.
48
57
 
49
58
  **Custom cards** (`cards: { <tool name>: { result?, confirm? } }`): `result` replaces a finished tool's step,
50
59
  `confirm` replaces the generic confirm card when that tool's change waits alone (`ctx.decide(true | false)`). The
@@ -98,6 +107,32 @@ allow them (`attachments.enabled`), and `thumbnailUrl` must be on the profile's
98
107
  `attachments.thumbnailHosts`. Roll out the widget with `uploadFile` first, then turn the profile on. Saved photos show
99
108
  from `thumbnailUrl` (https only); one that cannot load shows its file name.
100
109
 
110
+ ## Pointing at the page (selections)
111
+
112
+ When the host shows a page beside the chat (Ghuri Commerce: a design preview), the user can point at an element and
113
+ the assistant is told exactly which one (docs/preview-picker.md in ghuri-ai). Pass `selections: true`, then hand the
114
+ widget what was picked:
115
+
116
+ ```ts
117
+ chat.configure({ apiUrl, startSession, refreshUserToken, selections: true })
118
+ const id = chat.addSelection({
119
+ label: 'Button “Add to cart” · ProductCard.tsx', // what the chip shows (required, at most 80 characters)
120
+ source: { file: 'app/components/ProductCard.tsx', line: 14 },
121
+ within: [{ file: 'app/routes/home.tsx', line: 58 }],
122
+ exact: true, tag: 'button', role: 'button', name: 'Add to cart',
123
+ box: { x: 302, y: 1210, width: 259, height: 42 }, viewport: { width: 1280, height: 800 },
124
+ page: '/collections/eid', version: 'draft v4',
125
+ }) // null when the app's profile does not take selections
126
+ chat.addEventListener('ghuri:selection-removed', (e) => clearOutline(e.detail.id))
127
+ ```
128
+
129
+ Chips sit above the box, at most 3 (or the profile's `selections.maxCount`); a fourth replaces the oldest
130
+ (`ghuri:selection-removed`). They go only with words, as `selections` on `POST /v1/chat` (`ghuri:selection-sent`),
131
+ and the sent message keeps them as read-only chips (history included). An opened conversation takes them only if its
132
+ pinned profile does (`selections` in its JSON); otherwise the chips stay and a note offers a new conversation. Also
133
+ `removeSelection(id)`, `clearSelections()` and `selections`. Ghuri AI checks every field and treats all of it as page
134
+ content, never instructions. Needs the profile's `selections.enabled`.
135
+
101
136
  ## React
102
137
 
103
138
  ```tsx
@@ -110,6 +145,7 @@ import { GhuriChat } from '@ghuri/ai-widget/react'
110
145
  onToolResult={(e) => queryClient.invalidateQueries(/* … */)}
111
146
  cards={{ inventory_adjust: { confirm: (ctx) => <StockChange ctx={ctx} /> } }}
112
147
  uploadFile={uploadToFiles} onAttachmentError={(e) => console.warn(e)}
148
+ selections onSelectionRemoved={(e) => clearOutline(e.id)}
113
149
  />
114
150
  ```
115
151
 
@@ -135,11 +171,15 @@ await chat.decide([{ approvalId, approved: true, allowForConversation: true }])
135
171
  await chat.revokeAllowance('theme_files_write') // "Ask every time": state.allowances lists what is allowed
136
172
  chat.stop(); await chat.retry(); await chat.reload()
137
173
  await chat.listConversations(); await chat.openConversation(id); chat.newConversation()
174
+ await chat.continueConversation() // a full conversation: carry the work over into a new one
138
175
  await chat.end() // logout or store switch
139
176
  ```
140
177
 
141
178
  `state.problem.code` says what went wrong in terms a UI can word: `reconnecting`, `token-expired` (offer "Continue"),
142
- `in-progress`, `conversation-full`, `throttled` (`retryAfter` seconds), `forbidden`, `store-unreachable`,
179
+ `in-progress`, `conversation-full` (no new message fits; waiting changes can still be answered, and `state.full` stays
180
+ true, so `send()` sends nothing; `continueConversation()` carries the work into a new conversation that starts with
181
+ a hand-over: `state.continuing` while it is written, then `state.continuedFrom` and `state.handover`, shown with
182
+ `handoverText()`; a continued conversation has `state.continuedIn` and is read-only), `throttled` (`retryAfter` seconds), `forbidden`, `store-unreachable`,
143
183
  `unavailable`, `step-limit` (the reply used all its steps with work unfinished; offer "Continue"), `too-long` (a
144
184
  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"),
145
185
  `cut-off` (offer "Reload"), `failed` (`message`).
@@ -1,4 +1,4 @@
1
- import type { ChatClientOptions, ChatEvents, ChatState, ConversationSummary, Decision, Problem } from './types';
1
+ import type { ChatClientOptions, ChatEvents, ChatState, ConversationSummary, Decision, PageSelection, Problem } from './types';
2
2
  type Listener = (state: ChatState) => void;
3
3
  type EventListener<K extends keyof ChatEvents> = (event: ChatEvents[K]) => void;
4
4
  /** Photo defaults (Ghuri AI takes at most 10 per message; Commerce's limit is 5 MB). */
@@ -12,10 +12,13 @@ export declare const ATTACHMENT_DEFAULTS: {
12
12
  * When the app's assistant sees photos (`vision` in `GET /v1/capabilities`): Ghuri AI shows the model pictures of at
13
13
  * most 1,600 px and 1.5 MB, so photos are scaled to Claude's standard 1,568 px and kept under 1 MB.
14
14
  */
15
+ /** Ghuri AI's most selections per message. */
16
+ export declare const SELECTION_MAX = 3;
15
17
  export declare const VISION_DEFAULTS: {
16
18
  readonly maxEdge: 1568;
17
19
  readonly targetBytes: 1000000;
18
20
  };
21
+ export { HANDOVER_CONTRACT, type HandoverLine, handoverLines, handoverParts, handoverText } from './handover';
19
22
  /** What the user is told about a failed request. */
20
23
  export declare function problemFor(err: unknown): Problem;
21
24
  export declare class ChatClient {
@@ -44,6 +47,10 @@ export declare class ChatClient {
44
47
  private previews;
45
48
  /** The app's photo policy for new conversations, once Ghuri AI told us (`loadCapabilities`). */
46
49
  private policy;
50
+ /** The app's selections policy for new conversations, loaded with the photo policy. */
51
+ private selectionPolicy;
52
+ /** The selections of the message being sent, put back in the composer if Ghuri AI refuses them. */
53
+ private sending;
47
54
  private loadingPolicy;
48
55
  /** Set once the widget asked (it was shown); a new conversation then asks again, an ended client does not. */
49
56
  private capabilitiesWanted;
@@ -79,6 +86,20 @@ export declare class ChatClient {
79
86
  };
80
87
  /** A photo that failed to upload and can be retried: sending would silently leave it out. */
81
88
  private retryable;
89
+ /** Whether a new conversation takes selections: this host offers them and the app's profile takes them. */
90
+ private newConversationTakesSelections;
91
+ /**
92
+ * Add something the user pointed at on the host's page to the message being written (a chip above the box).
93
+ * Returns its id, or null when this host or app does not take selections (or it has no label). When the limit (3,
94
+ * or the app's) is reached, the oldest is replaced (`selection-removed`).
95
+ */
96
+ addSelection(selection: PageSelection): string | null;
97
+ /** Most selections one message may carry here (the app's limit, at most Ghuri AI's 3). */
98
+ selectionLimit(): number;
99
+ /** Take a selection out of the message being written. */
100
+ removeSelection(id: string): void;
101
+ /** Take every selection out of the message being written. */
102
+ clearSelections(): void;
82
103
  /** Whether a new conversation offers photos: this client can upload and the app's profile takes them. */
83
104
  private newConversationTakesPhotos;
84
105
  /**
@@ -119,6 +140,13 @@ export declare class ChatClient {
119
140
  /** Run the action that failed again (Try again). */
120
141
  retry(): Promise<void>;
121
142
  dismissProblem(): void;
143
+ /**
144
+ * Continue the open, full conversation in a new one: Ghuri AI writes a hand-over (a few seconds; `state.continuing`)
145
+ * and the new conversation opens with it (`state.continuedFrom`, `state.handover`). Nothing is sent to the
146
+ * assistant: the user carries on with a message. Not while a change is waiting (answer it first), and a conversation
147
+ * already continued just opens where it went on.
148
+ */
149
+ continueConversation(): Promise<void>;
122
150
  /** Start a new conversation (the next message creates it). */
123
151
  newConversation(): void;
124
152
  /** Forget the open conversation (new conversation, end). */
@@ -156,4 +184,3 @@ export declare class ChatClient {
156
184
  private apply;
157
185
  private toolPart;
158
186
  }
159
- export {};
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The readable part of a hand-over (`state.handover`): without its `<handover>` tags and the opening paragraph that
3
+ * tells the assistant how to read it.
4
+ */
5
+ export declare function handoverText(handover: string): string;
6
+ /** One line of "What I carried over": a heading ("Adjust stock: 57 done, 1 cancelled") or an item. */
7
+ export interface HandoverLine {
8
+ text: string;
9
+ heading: boolean;
10
+ }
11
+ /** The strings above, for the server's contract test. */
12
+ export declare const HANDOVER_CONTRACT: {
13
+ summaryHead: string;
14
+ noSummary: string;
15
+ recordHead: string;
16
+ };
17
+ /**
18
+ * "What I carried over" as lines to draw (docs/many-changes.md). With no summary, the record stands alone, without
19
+ * the two lines that say so. In the record, a line that is not an item ("- …") is a heading. Text only: the widget
20
+ * never reads it as markup.
21
+ */
22
+ export declare function handoverLines(handover: string): HandoverLine[];
23
+ /** `handoverLines`, and whether the model's summary is in it (else the record stands alone). */
24
+ export declare function handoverParts(handover: string): {
25
+ summary: boolean;
26
+ lines: HandoverLine[];
27
+ };
@@ -1,4 +1,4 @@
1
- export { ATTACHMENT_DEFAULTS, ChatClient, problemFor } from './client';
1
+ export { ATTACHMENT_DEFAULTS, ChatClient, type HandoverLine, handoverLines, handoverParts, handoverText, problemFor, } from './client';
2
2
  export { messagesFromHistory } from './history';
3
3
  export { parsedOutput, splitSavedOutput, splitToolOutput, type ToolImage } from './output';
4
4
  export { prepareImage, scaledSize } from './prepare';
@@ -28,6 +28,11 @@ export interface ChatClientOptions {
28
28
  discardFile?: (attachment: Attachment) => void | Promise<void>;
29
29
  /** Limits checked before uploading (the product checks again). */
30
30
  attachments?: AttachmentOptions;
31
+ /**
32
+ * This host lets the user point at elements of its page (`addSelection`), e.g. a design preview beside the chat.
33
+ * With it, the widget asks Ghuri AI whether the app takes selections; without it, `addSelection` does nothing.
34
+ */
35
+ selections?: boolean;
31
36
  /**
32
37
  * Scale a photo down and drop its metadata (phone location) before upload. Defaults to the browser helper
33
38
  * (`prepareImage` in `core/prepare.ts`); pass your own on other platforms or in tests.
@@ -116,6 +121,66 @@ export interface Upload {
116
121
  message?: string;
117
122
  attachment?: Attachment;
118
123
  }
124
+ /** A place in the product's code: a file and, when known, a line. */
125
+ export interface SourcePlace {
126
+ file: string;
127
+ line?: number;
128
+ }
129
+ /**
130
+ * Something the user pointed at on the host's page (Ghuri AI's `selections`, docs/preview-picker.md), e.g. one
131
+ * element of a store's design preview. Built by the host; Ghuri AI checks every field and gives the model a short
132
+ * description of it. Only `label` is required.
133
+ */
134
+ export interface PageSelection {
135
+ /** What the chip shows, e.g. `Button “Add to cart” · ProductCard.tsx` (at most 80 characters). */
136
+ label: string;
137
+ /** The file and line of the product's code that made it. */
138
+ source?: SourcePlace;
139
+ /** Files it sits inside, nearest first (at most 3). */
140
+ within?: SourcePlace[];
141
+ /** `source` is on the element itself (false: on an element around it). */
142
+ exact?: boolean;
143
+ /** The product's own reference, e.g. `{ type: 'section', id: 'home/2' }`. */
144
+ ref?: {
145
+ type: string;
146
+ id: string;
147
+ };
148
+ tag?: string;
149
+ role?: string;
150
+ /** Its accessible name (at most 80). */
151
+ name?: string;
152
+ /** Its visible text (at most 160). */
153
+ text?: string;
154
+ box?: {
155
+ x: number;
156
+ y: number;
157
+ width: number;
158
+ height: number;
159
+ };
160
+ viewport?: {
161
+ width: number;
162
+ height: number;
163
+ };
164
+ /** A path on the host's page, e.g. `/collections/eid`. */
165
+ page?: string;
166
+ /** A version label of what was shown, e.g. `draft v4`. */
167
+ version?: string;
168
+ }
169
+ /** A selection waiting in the composer: `id` is the widget's own (for `removeSelection`). */
170
+ export type ComposerSelection = PageSelection & {
171
+ id: string;
172
+ };
173
+ /** What the app's active profile allows for selections (Ghuri AI's `GET /v1/capabilities`). */
174
+ export interface SelectionPolicy {
175
+ enabled: boolean;
176
+ maxCount?: number;
177
+ }
178
+ /** What a user message pointed at. */
179
+ export interface SelectionsPart {
180
+ kind: 'selections';
181
+ id: string;
182
+ selections: PageSelection[];
183
+ }
119
184
  /** The photos of a user message. `previewUrl` is the local picture while the message was sent from this page. */
120
185
  export interface AttachmentsPart {
121
186
  kind: 'attachments';
@@ -154,7 +219,7 @@ export interface TextPart {
154
219
  id: string;
155
220
  text: string;
156
221
  }
157
- export type MessagePart = TextPart | ToolPart | AttachmentsPart;
222
+ export type MessagePart = TextPart | ToolPart | AttachmentsPart | SelectionsPart;
158
223
  export interface ChatMessage {
159
224
  id: string;
160
225
  role: 'user' | 'assistant';
@@ -183,6 +248,20 @@ export interface PendingApproval {
183
248
  preview?: ChangePreview;
184
249
  /** The user may answer with "Allow for this conversation" (the product made this tool allowable). */
185
250
  allowable?: boolean;
251
+ /**
252
+ * It was confirmed before and started, but its result was lost. It never runs again: deciding it (either way) closes
253
+ * it as "outcome unknown".
254
+ */
255
+ started?: boolean;
256
+ }
257
+ /** What became of one change the user decided (Ghuri AI's `decisions` on a turn that answered changes). */
258
+ export interface DecisionOutcome {
259
+ approvalId: string;
260
+ toolCallId: string;
261
+ toolName: string;
262
+ /** `unknown`: it had started before and its result was lost; check before trying again. */
263
+ outcome: 'done' | 'failed' | 'cancelled' | 'unknown';
264
+ error?: string;
186
265
  }
187
266
  export interface Decision {
188
267
  approvalId: string;
@@ -207,7 +286,9 @@ export interface TurnResult {
207
286
  error?: string;
208
287
  /**
209
288
  * `output`: the reply was cut off at the output limit (see `cut`). `steps` (with status `ok`): the assistant used all
210
- * the steps one reply may take while it was still working; "Continue" picks the work up.
289
+ * the steps one reply may take while it was still working; "Continue" picks the work up. `conversation`: the
290
+ * conversation is full and takes no new message; with status `paused` its waiting changes can still be confirmed
291
+ * or cancelled, and with status `ok` the decided changes ran without the assistant writing a reply.
211
292
  */
212
293
  limitReached?: 'conversation' | 'turn' | 'output' | 'steps';
213
294
  /** The tools allowed for this conversation when the turn ended (absent: none). */
@@ -215,6 +296,8 @@ export interface TurnResult {
215
296
  /** With `limitReached: 'output'`: a tool call was cut (it never ran) or a text answer was cut (just unfinished). */
216
297
  cut?: 'tool-call' | 'text';
217
298
  userTokenExpired?: boolean;
299
+ /** For a turn that answered changes: what became of each one. */
300
+ decisions?: DecisionOutcome[];
218
301
  }
219
302
  /**
220
303
  * Something the user should be told, in plain words. The UI picks the wording; `retryAfter` is in seconds.
@@ -222,7 +305,7 @@ export interface TurnResult {
222
305
  * - `reconnecting`: getting a fresh session or token (no action needed)
223
306
  * - `token-expired`: the store stopped accepting the assistant mid-reply; the token was refreshed, offer "Continue"
224
307
  * - `in-progress`: the previous reply is still being written
225
- * - `conversation-full`: start a new conversation
308
+ * - `conversation-full`: no new message fits; answer any waiting change, then start a new conversation
226
309
  * - `throttled`: wait `retryAfter` seconds
227
310
  * - `forbidden`: the user may not do that in this store
228
311
  * - `store-unreachable`: the product's MCP server failed; nothing was changed
@@ -232,9 +315,10 @@ export interface TurnResult {
232
315
  * - `step-limit`: the reply used all its steps with work unfinished (what it did is kept). Offer "Continue"
233
316
  * - `cut-off`: the reply stopped before it finished; reload the conversation
234
317
  * - `photos-refused`: Ghuri AI did not take the photos here (`message` says why); nothing was sent
318
+ * - `selections-refused`: Ghuri AI did not take the selections here (`message` says why); nothing was sent, they stay
235
319
  * - `failed`: anything else (`message` has the server's text)
236
320
  */
237
- 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';
321
+ 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' | 'selections-refused' | 'failed';
238
322
  export interface Problem {
239
323
  code: ProblemCode;
240
324
  retryAfter?: number;
@@ -246,6 +330,10 @@ export interface ConversationSummary {
246
330
  title: string;
247
331
  createdAt: string;
248
332
  updatedAt: string;
333
+ /** The full conversation this one continues ("Continue in a new conversation"). */
334
+ continuedFrom?: string;
335
+ /** This conversation became full and went on in that one. */
336
+ continuedIn?: string;
249
337
  }
250
338
  /**
251
339
  * - `idle`: ready for a message
@@ -267,8 +355,31 @@ export interface ChatState {
267
355
  canAttach: boolean;
268
356
  /** Photos added to the message being written. */
269
357
  uploads: Upload[];
358
+ /** What the user pointed at on the host's page, waiting to go with the next message (at most 3). */
359
+ selections: ComposerSelection[];
360
+ /**
361
+ * Whether the open conversation takes selections (`false` with selections waiting: they cannot be sent here; a new
362
+ * conversation can take them).
363
+ */
364
+ canSelect: boolean;
270
365
  /** Tools allowed for this conversation ("Allow for this conversation"); the bar above the composer lists them. */
271
366
  allowances: Allowance[];
367
+ /**
368
+ * The open conversation is full: it takes no new message (sending only shows `conversation-full` again), but its
369
+ * waiting changes can still be confirmed or cancelled, and it can be continued in a new one (`continueConversation`).
370
+ */
371
+ full: boolean;
372
+ /** The hand-over is being written (`continueConversation`): nothing else can be done until it ends. */
373
+ continuing: boolean;
374
+ /** The full conversation this one continues (its title is this one's too), for "Continued from …". */
375
+ continuedFrom: {
376
+ id: string;
377
+ title: string;
378
+ } | null;
379
+ /** What this conversation started with, for "What I carried over" (`handoverText()` makes it readable). */
380
+ handover: string | null;
381
+ /** Where this (full) conversation went on: it is read-only, with a link there. */
382
+ continuedIn: string | null;
272
383
  }
273
384
  /** Events for the host page (the element re-dispatches them as `ghuri:*` DOM events). */
274
385
  export interface ChatEvents {
@@ -289,6 +400,14 @@ export interface ChatEvents {
289
400
  };
290
401
  /** A turn ended. */
291
402
  'turn-end': TurnResult;
403
+ /** The user removed a selection from the composer (or a new one replaced the oldest). */
404
+ 'selection-removed': {
405
+ id: string;
406
+ };
407
+ /** Selections went with a message (and left the composer). */
408
+ 'selection-sent': {
409
+ ids: string[];
410
+ };
292
411
  /** A photo was refused or failed to upload. */
293
412
  'attachment-error': {
294
413
  name: string;