@widgetic/chat 0.1.44 → 0.1.47

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 (75) hide show
  1. package/README.md +162 -20
  2. package/dist/components/ActionBar.svelte +14 -1
  3. package/dist/components/ActionBar.svelte.d.ts +6 -0
  4. package/dist/components/AttachmentDisplay.svelte +22 -130
  5. package/dist/components/AttachmentPreviewDialog.svelte +428 -0
  6. package/dist/components/AttachmentPreviewDialog.svelte.d.ts +14 -0
  7. package/dist/components/Chat.svelte +556 -121
  8. package/dist/components/Chat.svelte.d.ts +15 -2
  9. package/dist/components/ChatComposer.svelte +63 -69
  10. package/dist/components/ChatComposer.svelte.d.ts +8 -3
  11. package/dist/components/ChatDropOverlay.svelte +58 -0
  12. package/dist/components/ChatDropOverlay.svelte.d.ts +8 -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/PanelSuggestionButtons.svelte +67 -19
  20. package/dist/components/PanelSuggestionButtons.svelte.d.ts +3 -1
  21. package/dist/components/RestoreCheckpointDialog.svelte +66 -0
  22. package/dist/components/RestoreCheckpointDialog.svelte.d.ts +11 -0
  23. package/dist/components/SentAttachments.svelte +118 -0
  24. package/dist/components/SentAttachments.svelte.d.ts +12 -0
  25. package/dist/components/agent/AgentTurn.svelte +17 -2
  26. package/dist/components/agent/CodeCard.svelte +9 -3
  27. package/dist/i18n/index.d.ts +1 -1
  28. package/dist/i18n/index.js +1 -1
  29. package/dist/i18n/messages.d.ts +52 -4
  30. package/dist/i18n/messages.js +58 -6
  31. package/dist/i18n/suggestions.d.ts +17 -2
  32. package/dist/i18n/suggestions.js +11 -12
  33. package/dist/services/index.d.ts +4 -2
  34. package/dist/services/index.js +2 -1
  35. package/dist/services/limitRefusal.d.ts +42 -0
  36. package/dist/services/limitRefusal.js +60 -0
  37. package/dist/services/sketchAssistantClient.d.ts +11 -3
  38. package/dist/services/sketchAssistantClient.js +37 -10
  39. package/dist/services/sketchAssistantErrors.d.ts +16 -1
  40. package/dist/services/sketchAssistantErrors.js +25 -4
  41. package/dist/services/sketchAssistantOrchestrator.d.ts +7 -1
  42. package/dist/services/sketchAssistantOrchestrator.js +2 -2
  43. package/dist/types/attachment.d.ts +11 -0
  44. package/dist/utils/agentTurn.d.ts +32 -1
  45. package/dist/utils/agentTurn.js +46 -3
  46. package/dist/utils/attachmentDuplicates.d.ts +48 -0
  47. package/dist/utils/attachmentDuplicates.js +70 -0
  48. package/dist/utils/attachmentPolicy.d.ts +88 -0
  49. package/dist/utils/attachmentPolicy.js +135 -0
  50. package/dist/utils/attachmentPreview.d.ts +146 -0
  51. package/dist/utils/attachmentPreview.js +224 -0
  52. package/dist/utils/attachmentTray.d.ts +35 -0
  53. package/dist/utils/attachmentTray.js +27 -0
  54. package/dist/utils/chatFileDrag.d.ts +39 -0
  55. package/dist/utils/chatFileDrag.js +29 -0
  56. package/dist/utils/composerPreview.d.ts +33 -0
  57. package/dist/utils/composerPreview.js +31 -0
  58. package/dist/utils/generationArchiveStore.d.ts +5 -1
  59. package/dist/utils/generationArchiveStore.js +9 -4
  60. package/dist/utils/index.d.ts +1 -1
  61. package/dist/utils/index.js +1 -1
  62. package/dist/utils/limitFailureLine.d.ts +20 -0
  63. package/dist/utils/limitFailureLine.js +40 -0
  64. package/dist/utils/panelListPadding.d.ts +20 -0
  65. package/dist/utils/panelListPadding.js +31 -0
  66. package/dist/utils/pasteInsertion.d.ts +43 -0
  67. package/dist/utils/pasteInsertion.js +94 -0
  68. package/dist/utils/pastedContent.d.ts +13 -0
  69. package/dist/utils/pastedContent.js +18 -1
  70. package/dist/utils/referenceItems.js +11 -3
  71. package/dist/utils/sentAttachments.d.ts +43 -0
  72. package/dist/utils/sentAttachments.js +38 -0
  73. package/dist/utils/sentReferenceBadges.d.ts +11 -1
  74. package/dist/utils/sentReferenceBadges.js +47 -2
  75. package/package.json +3 -3
@@ -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
@@ -59,6 +59,14 @@ export interface TurnReplyFacts {
59
59
  * the turn (or a generation that ran for it) makes an ordinary last reply a success.
60
60
  */
61
61
  export declare function turnOutcome(replies: readonly TurnReplyFacts[], generationRanForTurn: boolean): TurnOutcome | null;
62
+ /**
63
+ * The outcome the avatar is DRAWN for. A success is celebrated (the large avatar plays its one-shot) only by a person who just
64
+ * watched the work succeed. A turn that was judged a success but was not watched happen is drawn as a plain answer, at rest:
65
+ * a conversation that was loaded, work that came back from this browser's archive after a reload (or when the conversation was
66
+ * opened again) is the work of an earlier run, and a refresh must leave the avatar as it was and not make it do the task again.
67
+ * Every other outcome (a failure, a stop, a question) is how the turn really ended and is drawn as it is.
68
+ */
69
+ export declare function outcomeToShow(outcome: TurnOutcome, successWasWatched: boolean): TurnOutcome;
62
70
  /**
63
71
  * The look of a turn that is not running. Only the newest turn moves, and only its conclusion is large (the success avatar,
64
72
  * or a question to answer): older turns are small still pictures, so a long chat keeps one mascot alive instead of one per
@@ -169,12 +177,26 @@ export interface FinishedGeneration {
169
177
  * on the diff. Null when the run has none: the first message of a conversation, a page that does not give changes.
170
178
  */
171
179
  changes?: CodeChanges | null;
180
+ /**
181
+ * The agent's own words about what the run changed, when the page gave them (the gateway sends them with the completed
182
+ * operation). The conclusion says them in place of the catalog's "Done" sentence. Null when the run has none: a gateway that
183
+ * sends no summary, a build that was not kept.
184
+ */
185
+ summary?: string | null;
172
186
  }
173
187
  /**
174
188
  * The most text kept of either part. A generation streams tails; the chat stitches them, and a runaway stream
175
189
  * must not grow memory without end.
176
190
  */
177
191
  export declare const MAX_KEPT_GENERATION_CHARS = 120000;
192
+ /** The most characters kept of the agent's summary of a run: a sentence or two, never an essay. A longer one is cut and ends in "…". */
193
+ export declare const MAX_KEPT_SUMMARY_CHARS = 600;
194
+ /**
195
+ * The agent's summary of a run, read from whatever the page gave: the words as one paragraph (line breaks and runs of spaces become
196
+ * one space), within `MAX_KEPT_SUMMARY_CHARS`. Anything that is not text, or is only spaces, reads as no summary, and the conclusion
197
+ * keeps the catalog's sentence. It never throws.
198
+ */
199
+ export declare function readGenerationSummary(raw: unknown): string | null;
178
200
  /**
179
201
  * A prompt as a way to recognise its turn. A message id is no use: the host swaps a made-up id for the saved one, and
180
202
  * may reload the whole conversation after a generation. The words the person wrote survive both.
@@ -182,7 +204,8 @@ export declare const MAX_KEPT_GENERATION_CHARS = 120000;
182
204
  export declare function normalizePromptText(content: string | null | undefined): string;
183
205
  /**
184
206
  * What to keep of a generation that ended, or null when it left nothing to show. `changes` is whatever the page gave as the
185
- * changes of the run: it is read here (a part that is not usable is dropped), so what is kept is always plain, bounded data.
207
+ * changes of the run, and `summary` the agent's words about them: both are read here (a part that is not usable is dropped), so
208
+ * what is kept is always plain, bounded data. A run that left only a summary is kept: its conclusion says it.
186
209
  */
187
210
  export declare function keepFinishedGeneration(input: {
188
211
  promptText: string | null | undefined;
@@ -190,7 +213,15 @@ export declare function keepFinishedGeneration(input: {
190
213
  code: string;
191
214
  thoughtSeconds: number | null;
192
215
  changes?: unknown;
216
+ summary?: unknown;
193
217
  }): FinishedGeneration | null;
218
+ /**
219
+ * The kept work of a run with the agent's summary of that run put into it, for a page that gives the summary AFTER the run ended
220
+ * (it comes with the completed operation, like the changes: see `withChangesOfTheRun`). It gives back the very same object when
221
+ * there is nothing to put in (the work has a summary already, or what was given is not usable), so the caller can tell by identity
222
+ * that nothing changed.
223
+ */
224
+ export declare function withSummaryOfTheRun(finished: FinishedGeneration, summary: unknown): FinishedGeneration;
194
225
  /**
195
226
  * The kept work of a run with the changes of that run put into it, for a page that gives the changes AFTER the run ended. The
196
227
  * gateway sends them with the completed operation, and a page that lets the chat take the next message as soon as the preview is
@@ -45,6 +45,16 @@ export function turnOutcome(replies, generationRanForTurn) {
45
45
  return 'success';
46
46
  return 'answer';
47
47
  }
48
+ /**
49
+ * The outcome the avatar is DRAWN for. A success is celebrated (the large avatar plays its one-shot) only by a person who just
50
+ * watched the work succeed. A turn that was judged a success but was not watched happen is drawn as a plain answer, at rest:
51
+ * a conversation that was loaded, work that came back from this browser's archive after a reload (or when the conversation was
52
+ * opened again) is the work of an earlier run, and a refresh must leave the avatar as it was and not make it do the task again.
53
+ * Every other outcome (a failure, a stop, a question) is how the turn really ended and is drawn as it is.
54
+ */
55
+ export function outcomeToShow(outcome, successWasWatched) {
56
+ return outcome === 'success' && !successWasWatched ? 'answer' : outcome;
57
+ }
48
58
  /**
49
59
  * The look of a turn that is not running. Only the newest turn moves, and only its conclusion is large (the success avatar,
50
60
  * or a question to answer): older turns are small still pictures, so a long chat keeps one mascot alive instead of one per
@@ -189,6 +199,23 @@ export function finishedModulesView(finished) {
189
199
  * must not grow memory without end.
190
200
  */
191
201
  export const MAX_KEPT_GENERATION_CHARS = 120_000;
202
+ /** The most characters kept of the agent's summary of a run: a sentence or two, never an essay. A longer one is cut and ends in "…". */
203
+ export const MAX_KEPT_SUMMARY_CHARS = 600;
204
+ /**
205
+ * The agent's summary of a run, read from whatever the page gave: the words as one paragraph (line breaks and runs of spaces become
206
+ * one space), within `MAX_KEPT_SUMMARY_CHARS`. Anything that is not text, or is only spaces, reads as no summary, and the conclusion
207
+ * keeps the catalog's sentence. It never throws.
208
+ */
209
+ export function readGenerationSummary(raw) {
210
+ if (typeof raw !== 'string')
211
+ return null;
212
+ const asOneParagraph = raw.replace(/\s+/g, ' ').trim();
213
+ if (asOneParagraph === '')
214
+ return null;
215
+ if (asOneParagraph.length <= MAX_KEPT_SUMMARY_CHARS)
216
+ return asOneParagraph;
217
+ return `${asOneParagraph.slice(0, MAX_KEPT_SUMMARY_CHARS - 1).trimEnd()}…`;
218
+ }
192
219
  /**
193
220
  * A prompt as a way to recognise its turn. A message id is no use: the host swaps a made-up id for the saved one, and
194
221
  * may reload the whole conversation after a generation. The words the person wrote survive both.
@@ -198,22 +225,38 @@ export function normalizePromptText(content) {
198
225
  }
199
226
  /**
200
227
  * What to keep of a generation that ended, or null when it left nothing to show. `changes` is whatever the page gave as the
201
- * changes of the run: it is read here (a part that is not usable is dropped), so what is kept is always plain, bounded data.
228
+ * changes of the run, and `summary` the agent's words about them: both are read here (a part that is not usable is dropped), so
229
+ * what is kept is always plain, bounded data. A run that left only a summary is kept: its conclusion says it.
202
230
  */
203
231
  export function keepFinishedGeneration(input) {
204
232
  const thinking = input.thinking.slice(-MAX_KEPT_GENERATION_CHARS);
205
233
  const code = input.code.slice(-MAX_KEPT_GENERATION_CHARS);
206
234
  const changes = readCodeChanges(input.changes);
207
- if (thinking.trim().length === 0 && code.trim().length === 0 && changes === null)
235
+ const summary = readGenerationSummary(input.summary);
236
+ if (thinking.trim().length === 0 && code.trim().length === 0 && changes === null && summary === null)
208
237
  return null;
209
238
  return {
210
239
  prompt: normalizePromptText(input.promptText),
211
240
  thinking,
212
241
  code,
213
242
  thoughtSeconds: input.thoughtSeconds,
214
- changes
243
+ changes,
244
+ // Left out when there is none: work kept without a summary has the shape it always had
245
+ ...(summary !== null ? { summary } : {})
215
246
  };
216
247
  }
248
+ /**
249
+ * The kept work of a run with the agent's summary of that run put into it, for a page that gives the summary AFTER the run ended
250
+ * (it comes with the completed operation, like the changes: see `withChangesOfTheRun`). It gives back the very same object when
251
+ * there is nothing to put in (the work has a summary already, or what was given is not usable), so the caller can tell by identity
252
+ * that nothing changed.
253
+ */
254
+ export function withSummaryOfTheRun(finished, summary) {
255
+ if (finished.summary)
256
+ return finished;
257
+ const readSummary = readGenerationSummary(summary);
258
+ return readSummary === null ? finished : { ...finished, summary: readSummary };
259
+ }
217
260
  /**
218
261
  * The kept work of a run with the changes of that run put into it, for a page that gives the changes AFTER the run ended. The
219
262
  * gateway sends them with the completed operation, and a page that lets the chat take the next message as soon as the preview is
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Telling a file that comes again from a file that is new. A picture dragged twice, a screenshot pasted after it was dropped, a
3
+ * file picked a second time: they are the same bytes under another name or none ("image.png" is every screenshot's name), so the
4
+ * name says nothing and the bytes do. A file's fingerprint is made from them, and a file whose fingerprint is in the tray is not
5
+ * attached again.
6
+ *
7
+ * Plain TypeScript apart from the Web Crypto call, which a test can reach in Node: no Svelte in it.
8
+ */
9
+ import type { AttachmentInput } from '../types/attachment.js';
10
+ /** A file up to this size is read whole to make its fingerprint; a larger one (a video) is told by its two ends and its size. */
11
+ export declare const FULL_FINGERPRINT_MAX_BYTES: number;
12
+ /**
13
+ * What the file's bytes are, as a short text: its type and size, and a SHA-256 of its content (of the two ends of a large file).
14
+ * Two files with the same fingerprint are the same file for the tray. When the browser cannot hash (a page that is not a secure
15
+ * context has no `crypto.subtle`) or the file cannot be read, the fingerprint is made from the name, size and date instead: the
16
+ * same file picked again still matches, and nothing is ever refused because of it.
17
+ */
18
+ export declare function fingerprintFile(file: File): Promise<string>;
19
+ /** The place, in the list given, of the file that has this fingerprint; -1 when the file is new (or has no fingerprint to compare). */
20
+ export declare function indexOfAttachmentWithFingerprint(attachments: readonly Pick<AttachmentInput, 'fingerprint'>[], fingerprint: string): number;
21
+ /** One file that arrives, with its fingerprint. */
22
+ export interface FingerprintedFile<Entry extends {
23
+ file: File;
24
+ }> {
25
+ entry: Entry;
26
+ fingerprint: string;
27
+ }
28
+ /** What `splitNewFromKnown` found. */
29
+ export interface KnownAndNewFiles<Entry extends {
30
+ file: File;
31
+ }> {
32
+ /** The files that are new, in the order they arrived, each with its fingerprint. */
33
+ fresh: FingerprintedFile<Entry>[];
34
+ /** The files whose bytes the tray already holds (or that came twice in this batch), with the place of the file in the list given. */
35
+ known: Array<{
36
+ entry: Entry;
37
+ fingerprint: string;
38
+ existingIndex: number;
39
+ }>;
40
+ }
41
+ /**
42
+ * Sorts what arrives into what is new and what the tray (or the batch itself, or a batch still being prepared: `pendingFingerprints`)
43
+ * already holds. A file that comes twice in one batch is new once. `existingIndex` of a file that came twice in a batch, or that is
44
+ * still being prepared, is -1: there is no tile to point at yet.
45
+ */
46
+ export declare function splitNewFromKnown<Entry extends {
47
+ file: File;
48
+ }>(arrivals: readonly FingerprintedFile<Entry>[], attachments: readonly Pick<AttachmentInput, 'fingerprint'>[], pendingFingerprints?: ReadonlySet<string>): KnownAndNewFiles<Entry>;
@@ -0,0 +1,70 @@
1
+ import { chatWarn } from './logger.js';
2
+ /** A file up to this size is read whole to make its fingerprint; a larger one (a video) is told by its two ends and its size. */
3
+ export const FULL_FINGERPRINT_MAX_BYTES = 32 * 1024 * 1024;
4
+ /** How much of each end of a large file its fingerprint reads. */
5
+ const LARGE_FILE_SAMPLE_BYTES = 1024 * 1024;
6
+ /** The bytes as a hexadecimal text. */
7
+ function toHexadecimal(bytes) {
8
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, '0')).join('');
9
+ }
10
+ /**
11
+ * What the file's bytes are, as a short text: its type and size, and a SHA-256 of its content (of the two ends of a large file).
12
+ * Two files with the same fingerprint are the same file for the tray. When the browser cannot hash (a page that is not a secure
13
+ * context has no `crypto.subtle`) or the file cannot be read, the fingerprint is made from the name, size and date instead: the
14
+ * same file picked again still matches, and nothing is ever refused because of it.
15
+ */
16
+ export async function fingerprintFile(file) {
17
+ const kind = `${file.type || 'unknown'}:${file.size}`;
18
+ try {
19
+ const digest = globalThis.crypto?.subtle?.digest;
20
+ if (typeof digest !== 'function')
21
+ throw new Error('no Web Crypto in this page');
22
+ let content;
23
+ if (file.size <= FULL_FINGERPRINT_MAX_BYTES) {
24
+ content = await file.arrayBuffer();
25
+ }
26
+ else {
27
+ const head = await file.slice(0, LARGE_FILE_SAMPLE_BYTES).arrayBuffer();
28
+ const tail = await file.slice(file.size - LARGE_FILE_SAMPLE_BYTES).arrayBuffer();
29
+ const joined = new Uint8Array(head.byteLength + tail.byteLength);
30
+ joined.set(new Uint8Array(head), 0);
31
+ joined.set(new Uint8Array(tail), head.byteLength);
32
+ content = joined.buffer;
33
+ }
34
+ const hash = await globalThis.crypto.subtle.digest('SHA-256', content);
35
+ return `${kind}:${toHexadecimal(hash)}`;
36
+ }
37
+ catch (error) {
38
+ chatWarn('[attachmentDuplicates] The file could not be hashed, its name, size and date stand in for it:', file.name, error);
39
+ return `${kind}:name=${file.name}:modified=${file.lastModified}`;
40
+ }
41
+ }
42
+ /** The place, in the list given, of the file that has this fingerprint; -1 when the file is new (or has no fingerprint to compare). */
43
+ export function indexOfAttachmentWithFingerprint(attachments, fingerprint) {
44
+ if (!fingerprint)
45
+ return -1;
46
+ return attachments.findIndex((attachment) => attachment.fingerprint === fingerprint);
47
+ }
48
+ /**
49
+ * Sorts what arrives into what is new and what the tray (or the batch itself, or a batch still being prepared: `pendingFingerprints`)
50
+ * already holds. A file that comes twice in one batch is new once. `existingIndex` of a file that came twice in a batch, or that is
51
+ * still being prepared, is -1: there is no tile to point at yet.
52
+ */
53
+ export function splitNewFromKnown(arrivals, attachments, pendingFingerprints = new Set()) {
54
+ const result = { fresh: [], known: [] };
55
+ const seenInBatch = new Set();
56
+ for (const arrival of arrivals) {
57
+ const existingIndex = indexOfAttachmentWithFingerprint(attachments, arrival.fingerprint);
58
+ if (existingIndex >= 0) {
59
+ result.known.push({ ...arrival, existingIndex });
60
+ }
61
+ else if (seenInBatch.has(arrival.fingerprint) || pendingFingerprints.has(arrival.fingerprint)) {
62
+ result.known.push({ ...arrival, existingIndex: -1 });
63
+ }
64
+ else {
65
+ seenInBatch.add(arrival.fingerprint);
66
+ result.fresh.push(arrival);
67
+ }
68
+ }
69
+ return result;
70
+ }