@widgetic/chat 0.1.45 → 0.1.48

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.
Files changed (69) hide show
  1. package/README.md +148 -20
  2. package/dist/components/AttachmentDisplay.svelte +22 -130
  3. package/dist/components/AttachmentPreviewDialog.svelte +428 -0
  4. package/dist/components/AttachmentPreviewDialog.svelte.d.ts +14 -0
  5. package/dist/components/Chat.svelte +514 -94
  6. package/dist/components/Chat.svelte.d.ts +19 -2
  7. package/dist/components/ChatComposer.svelte +126 -72
  8. package/dist/components/ChatComposer.svelte.d.ts +13 -3
  9. package/dist/components/ChatDropOverlay.svelte +58 -0
  10. package/dist/components/ChatDropOverlay.svelte.d.ts +8 -0
  11. package/dist/components/ChatInput.svelte +42 -1
  12. package/dist/components/ChatInput.svelte.d.ts +2 -0
  13. package/dist/components/ChatMessages.svelte +322 -98
  14. package/dist/components/ChatMessages.svelte.d.ts +11 -2
  15. package/dist/components/ComposerAttachmentsTray.svelte +144 -56
  16. package/dist/components/ComposerAttachmentsTray.svelte.d.ts +11 -1
  17. package/dist/components/FileGlyphIcon.svelte +34 -0
  18. package/dist/components/FileGlyphIcon.svelte.d.ts +8 -0
  19. package/dist/components/RestoreCheckpointDialog.svelte +66 -0
  20. package/dist/components/RestoreCheckpointDialog.svelte.d.ts +11 -0
  21. package/dist/components/SentAttachments.svelte +118 -0
  22. package/dist/components/SentAttachments.svelte.d.ts +12 -0
  23. package/dist/components/agent/AgentTurn.svelte +17 -2
  24. package/dist/components/agent/CodeCard.svelte +9 -3
  25. package/dist/i18n/messages.d.ts +45 -3
  26. package/dist/i18n/messages.js +51 -5
  27. package/dist/services/index.d.ts +4 -2
  28. package/dist/services/index.js +2 -1
  29. package/dist/services/limitRefusal.d.ts +42 -0
  30. package/dist/services/limitRefusal.js +60 -0
  31. package/dist/services/sketchAssistantClient.d.ts +11 -3
  32. package/dist/services/sketchAssistantClient.js +37 -10
  33. package/dist/services/sketchAssistantErrors.d.ts +16 -1
  34. package/dist/services/sketchAssistantErrors.js +25 -4
  35. package/dist/services/sketchAssistantOrchestrator.d.ts +7 -1
  36. package/dist/services/sketchAssistantOrchestrator.js +2 -2
  37. package/dist/types/attachment.d.ts +11 -0
  38. package/dist/utils/agentTurn.d.ts +32 -1
  39. package/dist/utils/agentTurn.js +46 -3
  40. package/dist/utils/attachmentDuplicates.d.ts +48 -0
  41. package/dist/utils/attachmentDuplicates.js +70 -0
  42. package/dist/utils/attachmentPolicy.d.ts +88 -0
  43. package/dist/utils/attachmentPolicy.js +135 -0
  44. package/dist/utils/attachmentPreview.d.ts +146 -0
  45. package/dist/utils/attachmentPreview.js +224 -0
  46. package/dist/utils/attachmentTray.d.ts +35 -0
  47. package/dist/utils/attachmentTray.js +27 -0
  48. package/dist/utils/chatFileDrag.d.ts +39 -0
  49. package/dist/utils/chatFileDrag.js +29 -0
  50. package/dist/utils/composerPreview.d.ts +33 -0
  51. package/dist/utils/composerPreview.js +31 -0
  52. package/dist/utils/generationArchiveStore.d.ts +5 -1
  53. package/dist/utils/generationArchiveStore.js +9 -4
  54. package/dist/utils/index.d.ts +1 -1
  55. package/dist/utils/index.js +1 -1
  56. package/dist/utils/limitFailureLine.d.ts +20 -0
  57. package/dist/utils/limitFailureLine.js +40 -0
  58. package/dist/utils/panelListPadding.d.ts +20 -0
  59. package/dist/utils/panelListPadding.js +31 -0
  60. package/dist/utils/pasteInsertion.d.ts +43 -0
  61. package/dist/utils/pasteInsertion.js +94 -0
  62. package/dist/utils/pastedContent.d.ts +13 -0
  63. package/dist/utils/pastedContent.js +18 -1
  64. package/dist/utils/referenceItems.js +11 -3
  65. package/dist/utils/sentAttachments.d.ts +43 -0
  66. package/dist/utils/sentAttachments.js +38 -0
  67. package/dist/utils/sentReferenceBadges.d.ts +11 -1
  68. package/dist/utils/sentReferenceBadges.js +47 -2
  69. package/package.json +3 -3
@@ -187,6 +187,8 @@ export declare const CHAT_MESSAGES: {
187
187
  readonly 'chat.input.stop': "Stop generation";
188
188
  readonly 'chat.input.sending': "Sending message...";
189
189
  readonly 'chat.input.send': "Send message";
190
+ readonly 'chat.input.enhance': "Magic Enhance";
191
+ readonly 'chat.input.enhancing': "Enhancing...";
190
192
  readonly 'chat.input.tooLong': "Message is too long";
191
193
  readonly 'chat.input.publishNudge': "First generate your widget, then you can publish it.";
192
194
  /** The name of the send control while an agent works and a message is typed: the message waits its turn. */
@@ -213,7 +215,6 @@ export declare const CHAT_MESSAGES: {
213
215
  readonly 'chat.queue.sendNowTimeout': "The agent did not stop in time, so the message stays in the queue.";
214
216
  readonly 'chat.input.completionHint': "Tab to accept";
215
217
  readonly 'chat.input.completionHintTouch': "Tap the suggestion to accept";
216
- readonly 'chat.input.referenceHint': "Type # to reference an attached file";
217
218
  readonly 'chat.input.referenceMenuLabel': "Attached files";
218
219
  readonly 'chat.input.referenceRemove': "Remove {name}";
219
220
  readonly 'chat.messages.scrollToBottom': "Scroll to latest messages";
@@ -240,6 +241,11 @@ export declare const CHAT_MESSAGES: {
240
241
  readonly 'chat.checkpoint.version': "Version {n}";
241
242
  readonly 'chat.checkpoint.redo': "Redo";
242
243
  readonly 'chat.checkpoint.restored': "Restored to version {n}";
244
+ /** The question before the widget goes back to an earlier checkpoint: what is asked, what it costs, and the two buttons. */
245
+ readonly 'chat.checkpoint.confirmTitle': "Restore this checkpoint?";
246
+ readonly 'chat.checkpoint.confirmMessage': "You will lose the changes made after this checkpoint.";
247
+ readonly 'chat.checkpoint.confirmRestore': "Restore";
248
+ readonly 'chat.checkpoint.confirmCancel': "Cancel";
243
249
  readonly 'chat.actions.screenshot': "Screenshot";
244
250
  readonly 'chat.actions.screenshotTitle': "Take Screenshot";
245
251
  readonly 'chat.actions.screenshotLabel': "Take screenshot of current content";
@@ -252,6 +258,11 @@ export declare const CHAT_MESSAGES: {
252
258
  readonly 'chat.actions.upload': "Upload";
253
259
  readonly 'chat.actions.uploadTitle': "Upload File";
254
260
  readonly 'chat.actions.uploadLabel': "Upload file";
261
+ /**
262
+ * The tooltip of the "+" of the message box, after the pointer rests on it: what it adds. The box takes video and PDF too (they
263
+ * are kept with the message), but the builder reads only pictures, CSV and text, so the tooltip does not promise more.
264
+ */
265
+ readonly 'chat.actions.uploadTooltip': "Add images, CSV or text files. The builder does not read video or PDF yet.";
255
266
  readonly 'chat.actions.selector': "Selector";
256
267
  readonly 'chat.actions.selectorTitle': "Select a specific part of the widget to reference in chat";
257
268
  readonly 'chat.actions.selectorActiveTitle': "Disable widget element selector";
@@ -284,7 +295,6 @@ export declare const CHAT_MESSAGES: {
284
295
  /** What a picture of a typed message is called when its file has no name. */
285
296
  readonly 'chat.attachment.namelessAlt': "attachment";
286
297
  readonly 'chat.attachment.previewAlt': "Attachment preview";
287
- readonly 'chat.attachment.pdfTitle': "PDF Document";
288
298
  readonly 'chat.attachment.noVideo': "Your browser does not support video playback.";
289
299
  readonly 'chat.attachment.view': "Click to view {name}";
290
300
  readonly 'chat.attachment.viewFile': "Click to view file";
@@ -293,6 +303,36 @@ export declare const CHAT_MESSAGES: {
293
303
  /** What a screen reader says for a file chip while its file goes up: `{percent}` is the share sent, from 1 to 99. */
294
304
  readonly 'chat.attachment.uploadProgress': "Uploading, {percent}%";
295
305
  readonly 'chat.attachment.close': "Close";
306
+ /** The name of the group of files (and the group of pictures) a person sent with a message, for screen readers. */
307
+ readonly 'chat.attachment.sentFiles': "Files sent with this message";
308
+ readonly 'chat.attachment.sentPictures': "Pictures sent with this message";
309
+ /** The preview that opens from a file of the message box or of a sent message (the look of the File Browser's preview). */
310
+ readonly 'chat.preview.previous': "Previous file";
311
+ readonly 'chat.preview.next': "Next file";
312
+ readonly 'chat.preview.loading': "Loading preview";
313
+ readonly 'chat.preview.failed': "This file could not be loaded.";
314
+ readonly 'chat.preview.unavailable': "This kind of file has no preview.";
315
+ readonly 'chat.preview.truncated': "The rest of this file is not shown.";
316
+ /** The words of the PDF viewer inside that preview (`{page}` and `{total}` are the number of the page and of the pages). */
317
+ readonly 'chat.preview.pdfLoading': "Loading PDF…";
318
+ readonly 'chat.preview.pdfFailed': "Failed to load PDF";
319
+ readonly 'chat.preview.pdfPage': "Page {page} of {total}";
320
+ readonly 'chat.preview.pdfPreviousPage': "Previous page";
321
+ readonly 'chat.preview.pdfNextPage': "Next page";
322
+ /**
323
+ * What the whole chat says while files are dragged over it (Figma: Chat / Drop files, Chat / Drop not allowed). The kinds named
324
+ * are the ones the builder reads, as the tooltip of the "+" says (`chat.actions.uploadTooltip`).
325
+ */
326
+ readonly 'chat.drop.title': "Drop to attach";
327
+ readonly 'chat.drop.hint': "Images, CSV or text files";
328
+ readonly 'chat.drop.refusedTitle': "This file type is not supported";
329
+ readonly 'chat.drop.refusedHint': "Use images, CSV or text files";
330
+ /** Toasts for files that were dropped, picked or pasted and left out. `{name}` is the file's name, `{limit}` its kind's size limit ("10 MB"), `{count}` how many. */
331
+ readonly 'chat.attachment.refusedTypeOne': "“{name}” can’t be attached. Use images, video, PDF, CSV or text files.";
332
+ readonly 'chat.attachment.refusedTypeMany': "{count} files can’t be attached. Use images, video, PDF, CSV or text files.";
333
+ readonly 'chat.attachment.refusedSizeOne': "“{name}” is too large to attach. The limit is {limit}.";
334
+ readonly 'chat.attachment.refusedSizeMany': "{count} files are too large to attach.";
335
+ readonly 'chat.attachment.refusedFolder': "Folders can’t be attached. Drop the files inside them instead.";
296
336
  /** The size of a file, from bytes to gigabytes: `{size}` is the number, written the way the language writes numbers ("1.5", "1,5"). */
297
337
  readonly 'chat.size.bytes': "{size} B";
298
338
  readonly 'chat.size.kb': "{size} KB";
@@ -366,7 +406,9 @@ export declare const CHAT_MESSAGES: {
366
406
  readonly 'chat.sketch.failed': "Could not update the sketch. Please try again.";
367
407
  readonly 'chat.sketch.failedUnknown': "Could not update the sketch.";
368
408
  readonly 'chat.sketch.stepCap': "Sketch assistant stopped after too many steps.";
369
- readonly 'chat.sketch.noCredits': "You are out of credits, so I cannot draw right now. Add credits and ask me again.";
409
+ readonly 'chat.sketch.noCredits': "You're out of credits.";
410
+ readonly 'chat.sketch.planRequired': "Your plan doesn't include this.";
411
+ readonly 'chat.sketch.limitReached': "You've reached a usage limit.";
370
412
  readonly 'chat.sketch.busy': "A sketch is already being drawn, or you have sent too many requests. Try again in a moment.";
371
413
  readonly 'chat.sketch.unavailable': "The sketch assistant is not available right now. Please try again in a moment.";
372
414
  readonly 'chat.sketch.stopped': "Stopped drawing.";
@@ -193,6 +193,8 @@ export const CHAT_MESSAGES = {
193
193
  'chat.input.stop': 'Stop generation',
194
194
  'chat.input.sending': 'Sending message...',
195
195
  'chat.input.send': 'Send message',
196
+ 'chat.input.enhance': 'Magic Enhance',
197
+ 'chat.input.enhancing': 'Enhancing...',
196
198
  'chat.input.tooLong': 'Message is too long',
197
199
  'chat.input.publishNudge': 'First generate your widget, then you can publish it.',
198
200
  /** The name of the send control while an agent works and a message is typed: the message waits its turn. */
@@ -221,9 +223,9 @@ export const CHAT_MESSAGES = {
221
223
  // What to do with the grey suggestion after the caret: shown in the toolbar while one shows, and said to a screen reader with it
222
224
  'chat.input.completionHint': 'Tab to accept',
223
225
  'chat.input.completionHintTouch': 'Tap the suggestion to accept',
224
- // Referring to an attached file with # in the message: the line under the box while a file is attached, the name a screen reader
225
- // gives the list of files that # opens, and the name of the X of a badge in the text ({name} is the file's own name)
226
- 'chat.input.referenceHint': 'Type # to reference an attached file',
226
+ // Referring to an attached file with # in the message: the name a screen reader gives the list of files that # opens, and the name
227
+ // of the X of a badge in the text ({name} is the file's own name). There is no line of help about it: nothing under the box, and
228
+ // nothing told to a screen reader either.
227
229
  'chat.input.referenceMenuLabel': 'Attached files',
228
230
  'chat.input.referenceRemove': 'Remove {name}',
229
231
  'chat.messages.scrollToBottom': 'Scroll to latest messages',
@@ -250,6 +252,11 @@ export const CHAT_MESSAGES = {
250
252
  'chat.checkpoint.version': 'Version {n}',
251
253
  'chat.checkpoint.redo': 'Redo',
252
254
  'chat.checkpoint.restored': 'Restored to version {n}',
255
+ /** The question before the widget goes back to an earlier checkpoint: what is asked, what it costs, and the two buttons. */
256
+ 'chat.checkpoint.confirmTitle': 'Restore this checkpoint?',
257
+ 'chat.checkpoint.confirmMessage': 'You will lose the changes made after this checkpoint.',
258
+ 'chat.checkpoint.confirmRestore': 'Restore',
259
+ 'chat.checkpoint.confirmCancel': 'Cancel',
253
260
  // ===== The buttons under the messages =====
254
261
  'chat.actions.screenshot': 'Screenshot',
255
262
  'chat.actions.screenshotTitle': 'Take Screenshot',
@@ -263,6 +270,11 @@ export const CHAT_MESSAGES = {
263
270
  'chat.actions.upload': 'Upload',
264
271
  'chat.actions.uploadTitle': 'Upload File',
265
272
  'chat.actions.uploadLabel': 'Upload file',
273
+ /**
274
+ * The tooltip of the "+" of the message box, after the pointer rests on it: what it adds. The box takes video and PDF too (they
275
+ * are kept with the message), but the builder reads only pictures, CSV and text, so the tooltip does not promise more.
276
+ */
277
+ 'chat.actions.uploadTooltip': 'Add images, CSV or text files. The builder does not read video or PDF yet.',
266
278
  'chat.actions.selector': 'Selector',
267
279
  'chat.actions.selectorTitle': 'Select a specific part of the widget to reference in chat',
268
280
  'chat.actions.selectorActiveTitle': 'Disable widget element selector',
@@ -297,7 +309,6 @@ export const CHAT_MESSAGES = {
297
309
  /** What a picture of a typed message is called when its file has no name. */
298
310
  'chat.attachment.namelessAlt': 'attachment',
299
311
  'chat.attachment.previewAlt': 'Attachment preview',
300
- 'chat.attachment.pdfTitle': 'PDF Document',
301
312
  'chat.attachment.noVideo': 'Your browser does not support video playback.',
302
313
  'chat.attachment.view': 'Click to view {name}',
303
314
  'chat.attachment.viewFile': 'Click to view file',
@@ -306,6 +317,36 @@ export const CHAT_MESSAGES = {
306
317
  /** What a screen reader says for a file chip while its file goes up: `{percent}` is the share sent, from 1 to 99. */
307
318
  'chat.attachment.uploadProgress': 'Uploading, {percent}%',
308
319
  'chat.attachment.close': 'Close',
320
+ /** The name of the group of files (and the group of pictures) a person sent with a message, for screen readers. */
321
+ 'chat.attachment.sentFiles': 'Files sent with this message',
322
+ 'chat.attachment.sentPictures': 'Pictures sent with this message',
323
+ /** The preview that opens from a file of the message box or of a sent message (the look of the File Browser's preview). */
324
+ 'chat.preview.previous': 'Previous file',
325
+ 'chat.preview.next': 'Next file',
326
+ 'chat.preview.loading': 'Loading preview',
327
+ 'chat.preview.failed': 'This file could not be loaded.',
328
+ 'chat.preview.unavailable': 'This kind of file has no preview.',
329
+ 'chat.preview.truncated': 'The rest of this file is not shown.',
330
+ /** The words of the PDF viewer inside that preview (`{page}` and `{total}` are the number of the page and of the pages). */
331
+ 'chat.preview.pdfLoading': 'Loading PDF…',
332
+ 'chat.preview.pdfFailed': 'Failed to load PDF',
333
+ 'chat.preview.pdfPage': 'Page {page} of {total}',
334
+ 'chat.preview.pdfPreviousPage': 'Previous page',
335
+ 'chat.preview.pdfNextPage': 'Next page',
336
+ /**
337
+ * What the whole chat says while files are dragged over it (Figma: Chat / Drop files, Chat / Drop not allowed). The kinds named
338
+ * are the ones the builder reads, as the tooltip of the "+" says (`chat.actions.uploadTooltip`).
339
+ */
340
+ 'chat.drop.title': 'Drop to attach',
341
+ 'chat.drop.hint': 'Images, CSV or text files',
342
+ 'chat.drop.refusedTitle': 'This file type is not supported',
343
+ 'chat.drop.refusedHint': 'Use images, CSV or text files',
344
+ /** Toasts for files that were dropped, picked or pasted and left out. `{name}` is the file's name, `{limit}` its kind's size limit ("10 MB"), `{count}` how many. */
345
+ 'chat.attachment.refusedTypeOne': '“{name}” can’t be attached. Use images, video, PDF, CSV or text files.',
346
+ 'chat.attachment.refusedTypeMany': '{count} files can’t be attached. Use images, video, PDF, CSV or text files.',
347
+ 'chat.attachment.refusedSizeOne': '“{name}” is too large to attach. The limit is {limit}.',
348
+ 'chat.attachment.refusedSizeMany': '{count} files are too large to attach.',
349
+ 'chat.attachment.refusedFolder': 'Folders can’t be attached. Drop the files inside them instead.',
309
350
  /** The size of a file, from bytes to gigabytes: `{size}` is the number, written the way the language writes numbers ("1.5", "1,5"). */
310
351
  'chat.size.bytes': '{size} B',
311
352
  'chat.size.kb': '{size} KB',
@@ -384,7 +425,12 @@ export const CHAT_MESSAGES = {
384
425
  'chat.sketch.failed': 'Could not update the sketch. Please try again.',
385
426
  'chat.sketch.failedUnknown': 'Could not update the sketch.',
386
427
  'chat.sketch.stepCap': 'Sketch assistant stopped after too many steps.',
387
- 'chat.sketch.noCredits': 'You are out of credits, so I cannot draw right now. Add credits and ask me again.',
428
+ // The three sentences for a refusal because of money. The chat knows them by their exact words (to draw "Upgrade" under them),
429
+ // so each is one whole sentence that no reply of the model is likely to be. The widget creator says the first two the same way.
430
+ 'chat.sketch.noCredits': "You're out of credits.",
431
+ 'chat.sketch.planRequired': "Your plan doesn't include this.",
432
+ // For the visitor of a page that is not their own: they have no credits or plan to name
433
+ 'chat.sketch.limitReached': "You've reached a usage limit.",
388
434
  'chat.sketch.busy': 'A sketch is already being drawn, or you have sent too many requests. Try again in a moment.',
389
435
  'chat.sketch.unavailable': 'The sketch assistant is not available right now. Please try again in a moment.',
390
436
  'chat.sketch.stopped': 'Stopped drawing.',
@@ -2,6 +2,8 @@ export { WidgeticChatService, createChatService } from './chatService.js';
2
2
  export type { ChatService, ChatInstance, ChatFactory } from '../types/index.js';
3
3
  export { startSketchAssistantRequest, sketchAssistantStepRequest, SketchAssistantRequestError } from './sketchAssistantClient.js';
4
4
  export type { SketchToolCall, SketchAssistantStartResponse, SketchSceneSummary, SketchAssistantContext } from './sketchAssistantClient.js';
5
- export { runSketchAssistantLoop, describeSketchRequestFailure } from './sketchAssistantOrchestrator.js';
6
- export type { CanvasSketchExecutor, SketchAssistantLoopResult } from './sketchAssistantOrchestrator.js';
5
+ export { runSketchAssistantLoop, describeSketchRequestFailure, limitKindOfSketchFailure } from './sketchAssistantOrchestrator.js';
6
+ export type { CanvasSketchExecutor, SketchAssistantLoopResult, SketchFailureWording } from './sketchAssistantOrchestrator.js';
7
+ export { limitFailureKindOfRefusal } from './limitRefusal.js';
8
+ export type { LimitFailureKind, RefusalFacts } from './limitRefusal.js';
7
9
  export { buildSketchAssistantReply } from './sketchAssistantReply.js';
@@ -1,5 +1,6 @@
1
1
  // Chat Service
2
2
  export { WidgeticChatService, createChatService } from './chatService.js';
3
3
  export { startSketchAssistantRequest, sketchAssistantStepRequest, SketchAssistantRequestError } from './sketchAssistantClient.js';
4
- export { runSketchAssistantLoop, describeSketchRequestFailure } from './sketchAssistantOrchestrator.js';
4
+ export { runSketchAssistantLoop, describeSketchRequestFailure, limitKindOfSketchFailure } from './sketchAssistantOrchestrator.js';
5
+ export { limitFailureKindOfRefusal } from './limitRefusal.js';
5
6
  export { buildSketchAssistantReply } from './sketchAssistantReply.js';
@@ -0,0 +1,42 @@
1
+ /**
2
+ * What a refusal of the gateway says about money.
3
+ *
4
+ * A request can be refused because the credits are used up, or because the plan does not include what was asked (a free
5
+ * trial that ended, an account that is not subscribed). Both end the same way for the person: nothing is wrong with the
6
+ * request, and the way out is to upgrade. Every other refusal (busy, down, a bad request) is not that, and is worded
7
+ * elsewhere. This file decides which is which, from what the gateway answered, in one place.
8
+ *
9
+ * What the gateway sends for each, as of this writing:
10
+ *
11
+ * - 402 `BILLING_INSUFFICIENT_CREDITS`: the credits are used up. Two other 402s are NOT a shortage and must never say so:
12
+ * "Could not read your credit balance. Please try again in a moment." (a lookup that failed) and "Credits are only
13
+ * supported for user accounts." (this kind of account holds none).
14
+ * - 403 `AUTHZ_PLAN_RESTRICTION`: the plan lacks the feature. The same refusal also arrives as a plain 403 whose only
15
+ * mark is its sentence ("…free trial has ended, so widget generation is not available in your plan…"), so the
16
+ * sentence is read for those.
17
+ * - An editor session (a partner's visitor) is refused with `error.details.limit` set to `credits` or `plan`.
18
+ *
19
+ * A 403 is also what an ordinary refusal looks like (a route a session may not use), so a 403 with none of those marks
20
+ * is not a limit.
21
+ *
22
+ * The widget creator keeps the same rules for its own failures (`host/limitRefusal.ts` and `errors/toUserFriendlyError.ts`
23
+ * there): the two packages are published apart, so each holds its copy, and each is tested against the words above.
24
+ */
25
+ /** Which limit refused the request. */
26
+ export type LimitFailureKind = 'credits' | 'plan';
27
+ /** What the gateway answered when it did not take a request. */
28
+ export interface RefusalFacts {
29
+ /** The HTTP status. */
30
+ status: number;
31
+ /** The code of the error envelope (for example `BILLING_INSUFFICIENT_CREDITS`). */
32
+ code?: string | null;
33
+ /** The gateway's own sentence. */
34
+ message?: string | null;
35
+ /** The `error.details` of the envelope; an editor session's refusal marks `limit` in it. */
36
+ details?: unknown;
37
+ }
38
+ /**
39
+ * Which limit refused a request, or `null` when the refusal is not about credits or the plan.
40
+ * Pure: nothing is logged here, so a caller can ask as often as it likes.
41
+ */
42
+ export declare function limitFailureKindOfRefusal(refusal: RefusalFacts): LimitFailureKind | null;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * What a refusal of the gateway says about money.
3
+ *
4
+ * A request can be refused because the credits are used up, or because the plan does not include what was asked (a free
5
+ * trial that ended, an account that is not subscribed). Both end the same way for the person: nothing is wrong with the
6
+ * request, and the way out is to upgrade. Every other refusal (busy, down, a bad request) is not that, and is worded
7
+ * elsewhere. This file decides which is which, from what the gateway answered, in one place.
8
+ *
9
+ * What the gateway sends for each, as of this writing:
10
+ *
11
+ * - 402 `BILLING_INSUFFICIENT_CREDITS`: the credits are used up. Two other 402s are NOT a shortage and must never say so:
12
+ * "Could not read your credit balance. Please try again in a moment." (a lookup that failed) and "Credits are only
13
+ * supported for user accounts." (this kind of account holds none).
14
+ * - 403 `AUTHZ_PLAN_RESTRICTION`: the plan lacks the feature. The same refusal also arrives as a plain 403 whose only
15
+ * mark is its sentence ("…free trial has ended, so widget generation is not available in your plan…"), so the
16
+ * sentence is read for those.
17
+ * - An editor session (a partner's visitor) is refused with `error.details.limit` set to `credits` or `plan`.
18
+ *
19
+ * A 403 is also what an ordinary refusal looks like (a route a session may not use), so a 403 with none of those marks
20
+ * is not a limit.
21
+ *
22
+ * The widget creator keeps the same rules for its own failures (`host/limitRefusal.ts` and `errors/toUserFriendlyError.ts`
23
+ * there): the two packages are published apart, so each holds its copy, and each is tested against the words above.
24
+ */
25
+ /** The 402s that are not a shortage of credits (see above). */
26
+ const NOT_A_SHORTAGE_PATTERN = /could not read your credit balance|unable to resolve the account to meter|credits are only supported for user accounts/i;
27
+ /** The gateway's sentences for a plan that lacks what was asked. */
28
+ const PLAN_REFUSAL_PATTERN = /not available (?:in your plan|on the free plan|on this workspace's plan)|free trial has ended|is part of the [^.]{1,40} plan|plan (?:doesn't|does not) include|subscription [^.]{0,80} is not active|limit for this action on your plan/i;
29
+ /** The `limit` an editor session's refusal is marked with, when it is marked. */
30
+ function readLimitMark(details) {
31
+ if (!details || typeof details !== 'object')
32
+ return null;
33
+ const mark = details.limit;
34
+ return typeof mark === 'string' ? mark : null;
35
+ }
36
+ /**
37
+ * Which limit refused a request, or `null` when the refusal is not about credits or the plan.
38
+ * Pure: nothing is logged here, so a caller can ask as often as it likes.
39
+ */
40
+ export function limitFailureKindOfRefusal(refusal) {
41
+ const limitMark = readLimitMark(refusal.details);
42
+ const sentence = refusal.message ?? '';
43
+ if (refusal.status === 402) {
44
+ // A balance that could not be read is a failure to try again, not a shortage
45
+ if (NOT_A_SHORTAGE_PATTERN.test(sentence))
46
+ return null;
47
+ return limitMark === 'plan' ? 'plan' : 'credits';
48
+ }
49
+ if (refusal.status === 403) {
50
+ if (limitMark === 'credits')
51
+ return 'credits';
52
+ if (limitMark === 'plan' || refusal.code === 'AUTHZ_PLAN_RESTRICTION')
53
+ return 'plan';
54
+ return PLAN_REFUSAL_PATTERN.test(sentence) ? 'plan' : null;
55
+ }
56
+ // A proxy can change the status; the code still says the credits are used up
57
+ if (refusal.code === 'BILLING_INSUFFICIENT_CREDITS' && !NOT_A_SHORTAGE_PATTERN.test(sentence))
58
+ return 'credits';
59
+ return null;
60
+ }
@@ -60,15 +60,23 @@ export interface SketchAssistantContext {
60
60
  }
61
61
  /** The status of a request that got no answer at all (offline, the gateway down), which is no HTTP status. */
62
62
  export declare const SKETCH_ASSISTANT_NO_ANSWER_STATUS = 0;
63
+ /**
64
+ * The id as the gateway can take it, or null. `POST /agent/sketch` accepts `conversationId` and `canvasId` only as UUIDs and refuses
65
+ * the whole request (a 400, before the model or any canvas tool runs) for anything else. A draft canvas has no widget yet, so its
66
+ * chat's conversation lives only in the browser (an id like `local_draft_convert_canvas_1731…`): such an id says nothing the gateway
67
+ * could use, so it is left out and the drawing goes on without it. Said once in the console for each request that leaves one out.
68
+ */
69
+ export declare function idForGateway(candidateId: string | null | undefined, fieldName: 'conversationId' | 'canvasId'): string | null;
63
70
  /**
64
71
  * What the gateway answered when it did not take a request: the HTTP status, the code of its error envelope
65
- * (for example `BILLING_INSUFFICIENT_CREDITS`) and its own sentence. A request that got no answer has the status
66
- * `SKETCH_ASSISTANT_NO_ANSWER_STATUS`.
72
+ * (for example `BILLING_INSUFFICIENT_CREDITS`), its own sentence and the `details` of the envelope (an editor session's
73
+ * refusal marks which `limit` it was). A request that got no answer has the status `SKETCH_ASSISTANT_NO_ANSWER_STATUS`.
67
74
  */
68
75
  export declare class SketchAssistantRequestError extends Error {
69
76
  readonly status: number;
70
77
  readonly code: string | null;
71
- constructor(message: string, status: number, code?: string | null);
78
+ readonly details: Record<string, unknown> | null;
79
+ constructor(message: string, status: number, code?: string | null, details?: Record<string, unknown> | null);
72
80
  }
73
81
  export declare function startSketchAssistantRequest(input: {
74
82
  apiBaseUrl: string;
@@ -3,30 +3,56 @@
3
3
  */
4
4
  /** The status of a request that got no answer at all (offline, the gateway down), which is no HTTP status. */
5
5
  export const SKETCH_ASSISTANT_NO_ANSWER_STATUS = 0;
6
+ /** The shape the gateway's schema takes for the id of a conversation or of a canvas. */
7
+ const GATEWAY_UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
+ /**
9
+ * The id as the gateway can take it, or null. `POST /agent/sketch` accepts `conversationId` and `canvasId` only as UUIDs and refuses
10
+ * the whole request (a 400, before the model or any canvas tool runs) for anything else. A draft canvas has no widget yet, so its
11
+ * chat's conversation lives only in the browser (an id like `local_draft_convert_canvas_1731…`): such an id says nothing the gateway
12
+ * could use, so it is left out and the drawing goes on without it. Said once in the console for each request that leaves one out.
13
+ */
14
+ export function idForGateway(candidateId, fieldName) {
15
+ if (typeof candidateId !== 'string')
16
+ return null;
17
+ const trimmedId = candidateId.trim();
18
+ if (trimmedId === '')
19
+ return null;
20
+ if (GATEWAY_UUID_PATTERN.test(trimmedId))
21
+ return trimmedId;
22
+ // console.debug(`[chat] sketch assistant: ${fieldName} is not a UUID, so it is left out of the request`, {
23
+ // 'Left Out': trimmedId.slice(0, 48)
24
+ // });
25
+ return null;
26
+ }
6
27
  /**
7
28
  * What the gateway answered when it did not take a request: the HTTP status, the code of its error envelope
8
- * (for example `BILLING_INSUFFICIENT_CREDITS`) and its own sentence. A request that got no answer has the status
9
- * `SKETCH_ASSISTANT_NO_ANSWER_STATUS`.
29
+ * (for example `BILLING_INSUFFICIENT_CREDITS`), its own sentence and the `details` of the envelope (an editor session's
30
+ * refusal marks which `limit` it was). A request that got no answer has the status `SKETCH_ASSISTANT_NO_ANSWER_STATUS`.
10
31
  */
11
32
  export class SketchAssistantRequestError extends Error {
12
33
  status;
13
34
  code;
14
- constructor(message, status, code = null) {
35
+ details;
36
+ constructor(message, status, code = null, details = null) {
15
37
  super(message);
16
38
  this.name = 'SketchAssistantRequestError';
17
39
  this.status = status;
18
40
  this.code = code;
41
+ this.details = details;
19
42
  }
20
43
  }
21
- /** The sentence and the code of a refusal. The gateway writes `{ message, error: { code, message } }`; some doors write `{ error, code }`. */
44
+ /** The sentence, the code and the details of a refusal. The gateway writes `{ message, error: { code, message, details } }`; some doors write `{ error, code }`. */
22
45
  function readRefusal(payload) {
23
46
  if (!payload || typeof payload !== 'object')
24
- return { message: null, code: null };
47
+ return { message: null, code: null, details: null };
25
48
  const body = payload;
26
- const nested = body.error && typeof body.error === 'object' ? body.error : null;
49
+ const nested = body.error && typeof body.error === 'object'
50
+ ? body.error
51
+ : null;
27
52
  const message = [body.message, nested?.message, typeof body.error === 'string' ? body.error : null].find((candidate) => typeof candidate === 'string' && candidate.trim().length > 0);
28
53
  const code = [nested?.code, body.code].find((candidate) => typeof candidate === 'string' && candidate.length > 0);
29
- return { message: message ?? null, code: code ?? null };
54
+ const details = [nested?.details, body.details].find((candidate) => !!candidate && typeof candidate === 'object' && !Array.isArray(candidate));
55
+ return { message: message ?? null, code: code ?? null, details: details ?? null };
30
56
  }
31
57
  async function postJson(baseUrl, path, body, token, signal) {
32
58
  let response;
@@ -55,7 +81,7 @@ async function postJson(baseUrl, path, body, token, signal) {
55
81
  const refusal = readRefusal(payload);
56
82
  const technical = refusal.message ?? `request failed with status ${response.status}`;
57
83
  console.error('[chat] sketch assistant response', { status: response.status, code: refusal.code, message: technical });
58
- throw new SketchAssistantRequestError(technical, response.status, refusal.code);
84
+ throw new SketchAssistantRequestError(technical, response.status, refusal.code, refusal.details);
59
85
  }
60
86
  return (payload?.data ?? payload);
61
87
  }
@@ -64,8 +90,9 @@ export async function startSketchAssistantRequest(input) {
64
90
  prompt: input.prompt,
65
91
  sceneSummary: input.sceneSummary,
66
92
  sketchContext: input.sketchContext,
67
- conversationId: input.conversationId,
68
- canvasId: input.canvasId
93
+ // Only ids the gateway can take (UUIDs): an id of a conversation that lives in the browser would fail the whole request
94
+ conversationId: idForGateway(input.conversationId, 'conversationId'),
95
+ canvasId: idForGateway(input.canvasId, 'canvasId')
69
96
  }, input.authToken, input.signal);
70
97
  }
71
98
  export async function sketchAssistantStepRequest(input) {
@@ -1,4 +1,19 @@
1
1
  import type { Translate } from '@widgetic/design-system/i18n';
2
2
  import type { ChatMessageKey } from '../i18n/messages.js';
3
+ import { type LimitFailureKind } from './limitRefusal.js';
4
+ /** How a failure is worded, for the places that are not the person's own account. */
5
+ export interface SketchFailureWording {
6
+ /**
7
+ * Say a refusal because of a limit without naming the credits or the plan. The visitor of a page that belongs to someone else
8
+ * (a partner's) has neither, and the page decides what a limit means to them. The chat still shows its "Upgrade" button under the
9
+ * sentence, and a press on it goes to the host (`onUpgradePlans`). Defaults to `false`.
10
+ */
11
+ neutralLimits?: boolean;
12
+ }
13
+ /**
14
+ * Which limit refused a sketch request (the credits are used up, or the plan does not include it), or `null` when the failure is
15
+ * anything else (including a credit balance that could not be read, which is a reason to try again).
16
+ */
17
+ export declare function limitKindOfSketchFailure(error: unknown): LimitFailureKind | null;
3
18
  /** Words shown in the chat bubble when a sketch request fails. */
4
- export declare function describeSketchRequestFailure(error: unknown, translate?: Translate<ChatMessageKey>): string;
19
+ export declare function describeSketchRequestFailure(error: unknown, translate?: Translate<ChatMessageKey>, wording?: SketchFailureWording): string;
@@ -1,15 +1,36 @@
1
1
  import { translateEnglish } from '../i18n/language.js';
2
2
  import { SKETCH_ASSISTANT_NO_ANSWER_STATUS, SketchAssistantRequestError, } from './sketchAssistantClient.js';
3
+ import { limitFailureKindOfRefusal } from './limitRefusal.js';
3
4
  import { logTechnicalUserError } from '../errors/logTechnicalUserError.js';
5
+ /**
6
+ * Which limit refused a sketch request (the credits are used up, or the plan does not include it), or `null` when the failure is
7
+ * anything else (including a credit balance that could not be read, which is a reason to try again).
8
+ */
9
+ export function limitKindOfSketchFailure(error) {
10
+ if (!(error instanceof SketchAssistantRequestError))
11
+ return null;
12
+ return limitFailureKindOfRefusal({
13
+ status: error.status,
14
+ code: error.code,
15
+ message: error.message,
16
+ details: error.details,
17
+ });
18
+ }
4
19
  /** Words shown in the chat bubble when a sketch request fails. */
5
- export function describeSketchRequestFailure(error, translate = translateEnglish) {
20
+ export function describeSketchRequestFailure(error, translate = translateEnglish, wording = {}) {
6
21
  if (error instanceof SketchAssistantRequestError) {
7
22
  logTechnicalUserError('sketch assistant request', error, error.message);
8
- if (error.status === 402 || error.code === 'BILLING_INSUFFICIENT_CREDITS')
9
- return translate('chat.sketch.noCredits');
23
+ // A refusal because of money says so, plainly: the chat draws "Upgrade" under these sentences (it knows them by their words)
24
+ const limitKind = limitKindOfSketchFailure(error);
25
+ if (limitKind !== null) {
26
+ if (wording.neutralLimits === true)
27
+ return translate('chat.sketch.limitReached');
28
+ return limitKind === 'credits' ? translate('chat.sketch.noCredits') : translate('chat.sketch.planRequired');
29
+ }
10
30
  if (error.status === 429)
11
31
  return translate('chat.sketch.busy');
12
- if (error.status === SKETCH_ASSISTANT_NO_ANSWER_STATUS || error.status === 408 || error.status >= 500) {
32
+ // A 402 that is not a shortage is a balance that could not be read: nothing is wrong with the person's account
33
+ if (error.status === SKETCH_ASSISTANT_NO_ANSWER_STATUS || error.status === 402 || error.status === 408 || error.status >= 500) {
13
34
  return translate('chat.sketch.unavailable');
14
35
  }
15
36
  return translate('chat.sketch.failed');
@@ -2,7 +2,8 @@ import { type SketchAssistantContext, type SketchSceneSummary } from './sketchAs
2
2
  import { type SketchToolTrace } from './sketchAssistantReply.js';
3
3
  import type { Translate } from '@widgetic/design-system/i18n';
4
4
  import type { ChatMessageKey } from '../i18n/messages.js';
5
- export { describeSketchRequestFailure } from './sketchAssistantErrors.js';
5
+ export { describeSketchRequestFailure, limitKindOfSketchFailure } from './sketchAssistantErrors.js';
6
+ export type { SketchFailureWording } from './sketchAssistantErrors.js';
6
7
  export interface CanvasSketchExecutor {
7
8
  getSceneSummary(): SketchSceneSummary;
8
9
  executeTool(name: string, args: Record<string, unknown>): Record<string, unknown>;
@@ -40,6 +41,11 @@ export declare function runSketchAssistantLoop(input: {
40
41
  sketchContext?: SketchAssistantContext;
41
42
  maxSteps?: number;
42
43
  translate?: Translate<ChatMessageKey>;
44
+ /**
45
+ * Say a refusal because of a limit (the credits, the plan) without naming either: for the visitor of a page that is not their own,
46
+ * who has neither. See `SketchFailureWording`.
47
+ */
48
+ neutralLimits?: boolean;
43
49
  /** Stops the run between requests, and the request that is on its way. */
44
50
  signal?: AbortSignal;
45
51
  }): Promise<SketchAssistantLoopResult>;
@@ -3,7 +3,7 @@ import { buildSketchAssistantReply } from './sketchAssistantReply.js';
3
3
  import { translateEnglish } from '../i18n/language.js';
4
4
  import { describeSketchRequestFailure } from './sketchAssistantErrors.js';
5
5
  import { logTechnicalUserError } from '../errors/logTechnicalUserError.js';
6
- export { describeSketchRequestFailure } from './sketchAssistantErrors.js';
6
+ export { describeSketchRequestFailure, limitKindOfSketchFailure } from './sketchAssistantErrors.js';
7
7
  /**
8
8
  * How many times a run answers the gateway with tool results. The gateway stops a run after the same number of steps
9
9
  * (its last answer is words only), so a run that is still asking for tools after this many has not understood the
@@ -106,7 +106,7 @@ export async function runSketchAssistantLoop(input) {
106
106
  if (!(error instanceof SketchAssistantRequestError) && !input.signal?.aborted) {
107
107
  console.warn('[Sketch] The sketch assistant stopped', error);
108
108
  }
109
- return outcome(false, describeSketchRequestFailure(error, translate));
109
+ return outcome(false, describeSketchRequestFailure(error, translate, { neutralLimits: input.neutralLimits === true }));
110
110
  }
111
111
  finally {
112
112
  if (batchOpen)
@@ -65,6 +65,17 @@ export interface AttachmentInput {
65
65
  * from the file it is sent with (`referenceLabel`) to tie a `#word` of the text to that file.
66
66
  */
67
67
  referenceLabel?: string;
68
+ /**
69
+ * For a long text that was pasted into the message box: the beginning of the text (see `pastedTextExcerpt`). Its presence is
70
+ * what makes the file a pasted text: it lives in the words of the message, as a badge where the caret was, and the tray has no
71
+ * tile for it. The card over its badge shows this; it is for the screen only and is never sent anywhere.
72
+ */
73
+ excerpt?: string;
74
+ /**
75
+ * What the file's bytes are, as a short text (see `fingerprintFile`): a file that comes again (dragged twice, pasted after it was
76
+ * dropped) is recognised by it and is not attached a second time. For the screen's bookkeeping only; never sent anywhere.
77
+ */
78
+ fingerprint?: string;
68
79
  }
69
80
  /**
70
81
  * Client-side attachment before upload