@widgetic/chat 0.1.39 → 0.1.41

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 (58) hide show
  1. package/README.md +71 -0
  2. package/dist/components/Chat.svelte +63 -4
  3. package/dist/components/Chat.svelte.d.ts +31 -0
  4. package/dist/components/ChatComposer.svelte +5 -1
  5. package/dist/components/ChatMessages.svelte +574 -214
  6. package/dist/components/ChatMessages.svelte.d.ts +18 -0
  7. package/dist/components/agent/AgentAvatar.svelte +153 -0
  8. package/dist/components/agent/AgentAvatar.svelte.d.ts +27 -0
  9. package/dist/components/agent/AgentTurn.svelte +64 -0
  10. package/dist/components/agent/AgentTurn.svelte.d.ts +32 -0
  11. package/dist/components/agent/AvatarBoundary.svelte +29 -0
  12. package/dist/components/agent/AvatarBoundary.svelte.d.ts +20 -0
  13. package/dist/components/agent/CodeCard.svelte +288 -0
  14. package/dist/components/agent/CodeCard.svelte.d.ts +12 -0
  15. package/dist/components/agent/GenerationModule.svelte +99 -0
  16. package/dist/components/agent/GenerationModule.svelte.d.ts +16 -0
  17. package/dist/components/agent/MemberAvatar.svelte +87 -0
  18. package/dist/components/agent/MemberAvatar.svelte.d.ts +8 -0
  19. package/dist/components/index.d.ts +5 -0
  20. package/dist/components/index.js +9 -0
  21. package/dist/i18n/index.d.ts +1 -0
  22. package/dist/i18n/index.js +1 -0
  23. package/dist/i18n/messages.d.ts +46 -9
  24. package/dist/i18n/messages.js +48 -10
  25. package/dist/i18n/sketchLocales.d.ts +2 -0
  26. package/dist/i18n/sketchLocales.js +83 -0
  27. package/dist/services/index.d.ts +5 -0
  28. package/dist/services/index.js +3 -0
  29. package/dist/services/sketchAssistantClient.d.ts +68 -0
  30. package/dist/services/sketchAssistantClient.js +73 -0
  31. package/dist/services/sketchAssistantOrchestrator.d.ts +45 -0
  32. package/dist/services/sketchAssistantOrchestrator.js +128 -0
  33. package/dist/services/sketchAssistantReply.d.ts +12 -0
  34. package/dist/services/sketchAssistantReply.js +28 -0
  35. package/dist/stores/chatStore.d.ts +1 -0
  36. package/dist/stores/chatStore.js +21 -0
  37. package/dist/types/agent.d.ts +74 -0
  38. package/dist/types/agent.js +1 -0
  39. package/dist/types/index.d.ts +1 -0
  40. package/dist/types/index.js +2 -0
  41. package/dist/types/message.d.ts +2 -0
  42. package/dist/utils/agentTurn.d.ts +219 -0
  43. package/dist/utils/agentTurn.js +301 -0
  44. package/dist/utils/bubbleFit.d.ts +75 -0
  45. package/dist/utils/bubbleFit.js +116 -0
  46. package/dist/utils/bubbleShrinkWrap.d.ts +32 -0
  47. package/dist/utils/bubbleShrinkWrap.js +360 -0
  48. package/dist/utils/codeHighlight.d.ts +13 -0
  49. package/dist/utils/codeHighlight.js +61 -0
  50. package/dist/utils/codePrettier.d.ts +6 -0
  51. package/dist/utils/codePrettier.js +34 -0
  52. package/dist/utils/codeStreamFormat.d.ts +90 -0
  53. package/dist/utils/codeStreamFormat.js +429 -0
  54. package/dist/utils/generationArchiveStore.d.ts +5 -0
  55. package/dist/utils/generationArchiveStore.js +1 -0
  56. package/dist/utils/index.d.ts +2 -0
  57. package/dist/utils/index.js +3 -0
  58. package/package.json +3 -2
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Typed client for POST /agent/sketch (base URL already includes `/v1`) until the generated SDK exposes it.
3
+ */
4
+ /** The status of a request that got no answer at all (offline, the gateway down), which is no HTTP status. */
5
+ export const SKETCH_ASSISTANT_NO_ANSWER_STATUS = 0;
6
+ /**
7
+ * 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`.
10
+ */
11
+ export class SketchAssistantRequestError extends Error {
12
+ status;
13
+ code;
14
+ constructor(message, status, code = null) {
15
+ super(message);
16
+ this.name = 'SketchAssistantRequestError';
17
+ this.status = status;
18
+ this.code = code;
19
+ }
20
+ }
21
+ /** The sentence and the code of a refusal. The gateway writes `{ message, error: { code, message } }`; some doors write `{ error, code }`. */
22
+ function readRefusal(payload) {
23
+ if (!payload || typeof payload !== 'object')
24
+ return { message: null, code: null };
25
+ const body = payload;
26
+ const nested = body.error && typeof body.error === 'object' ? body.error : null;
27
+ const message = [body.message, nested?.message, typeof body.error === 'string' ? body.error : null].find((candidate) => typeof candidate === 'string' && candidate.trim().length > 0);
28
+ const code = [nested?.code, body.code].find((candidate) => typeof candidate === 'string' && candidate.length > 0);
29
+ return { message: message ?? null, code: code ?? null };
30
+ }
31
+ async function postJson(baseUrl, path, body, token, signal) {
32
+ let response;
33
+ try {
34
+ response = await fetch(`${baseUrl.replace(/\/$/, '')}${path}`, {
35
+ method: 'POST',
36
+ headers: {
37
+ 'Content-Type': 'application/json',
38
+ ...(token ? { Authorization: `Bearer ${token}` } : {})
39
+ },
40
+ body: JSON.stringify(body),
41
+ signal
42
+ });
43
+ }
44
+ catch (error) {
45
+ // A stop asked for stays what it is; anything else is a request that never got an answer.
46
+ if (signal?.aborted)
47
+ throw error;
48
+ throw new SketchAssistantRequestError(error instanceof Error ? error.message : 'no answer', SKETCH_ASSISTANT_NO_ANSWER_STATUS, 'NO_ANSWER');
49
+ }
50
+ // A proxy in front of the gateway can answer with a page that is not JSON; the status is still the answer.
51
+ const payload = (await response.json().catch(() => null));
52
+ if (!response.ok) {
53
+ const refusal = readRefusal(payload);
54
+ throw new SketchAssistantRequestError(refusal.message ?? `Sketch assistant HTTP ${response.status}`, response.status, refusal.code);
55
+ }
56
+ return (payload?.data ?? payload);
57
+ }
58
+ export async function startSketchAssistantRequest(input) {
59
+ return postJson(input.apiBaseUrl, '/agent/sketch', {
60
+ prompt: input.prompt,
61
+ sceneSummary: input.sceneSummary,
62
+ conversationId: input.conversationId,
63
+ canvasId: input.canvasId
64
+ }, input.authToken, input.signal);
65
+ }
66
+ export async function sketchAssistantStepRequest(input) {
67
+ return postJson(input.apiBaseUrl, '/agent/sketch/step', {
68
+ sessionId: input.sessionId,
69
+ step: input.step,
70
+ toolResults: input.toolResults,
71
+ sceneSummary: input.sceneSummary
72
+ }, input.authToken, input.signal);
73
+ }
@@ -0,0 +1,45 @@
1
+ import { type SketchSceneSummary } from './sketchAssistantClient.js';
2
+ import { type SketchToolTrace } from './sketchAssistantReply.js';
3
+ import type { Translate } from '@widgetic/design-system/i18n';
4
+ import type { ChatMessageKey } from '../i18n/messages.js';
5
+ export interface CanvasSketchExecutor {
6
+ getSceneSummary(): SketchSceneSummary;
7
+ executeTool(name: string, args: Record<string, unknown>): Record<string, unknown>;
8
+ undoLastDrawing?(): void;
9
+ beginToolBatch?(): void;
10
+ endToolBatch?(): void;
11
+ }
12
+ export interface SketchAssistantLoopResult {
13
+ ok: boolean;
14
+ message: string;
15
+ steps: number;
16
+ tools: SketchToolTrace[];
17
+ /** Whether a tool changed the canvas, so a run that only talked leaves nothing to undo. */
18
+ changedCanvas: boolean;
19
+ }
20
+ /**
21
+ * The words for a request the gateway did not take, in the page's language where the catalog has them.
22
+ * A refusal the person can act on gets its own sentence (no credits left, a run already going); a gateway that cannot
23
+ * be reached is one sentence; anything else shows the gateway's own words.
24
+ */
25
+ export declare function describeSketchRequestFailure(error: unknown, translate?: Translate<ChatMessageKey>): string;
26
+ /**
27
+ * Runs one request of the author on the canvas: the gateway's model asks for tools, the canvas runs them here, and
28
+ * the results go back until the model has nothing more to ask.
29
+ *
30
+ * A tool that fails (a shape out of the canvas, an id that is gone) is not the end of the run: its error goes back to
31
+ * the model like any other result, so it can correct itself. The run ends when the model answers, when the gateway
32
+ * refuses, or when it has taken too many steps. It never throws: what went wrong comes back as `ok: false` and a message.
33
+ */
34
+ export declare function runSketchAssistantLoop(input: {
35
+ apiBaseUrl: string;
36
+ authToken: string | null;
37
+ prompt: string;
38
+ executor: CanvasSketchExecutor;
39
+ conversationId?: string | null;
40
+ canvasId?: string | null;
41
+ maxSteps?: number;
42
+ translate?: Translate<ChatMessageKey>;
43
+ /** Stops the run between requests, and the request that is on its way. */
44
+ signal?: AbortSignal;
45
+ }): Promise<SketchAssistantLoopResult>;
@@ -0,0 +1,128 @@
1
+ import { SKETCH_ASSISTANT_NO_ANSWER_STATUS, SketchAssistantRequestError, sketchAssistantStepRequest, startSketchAssistantRequest } from './sketchAssistantClient.js';
2
+ import { buildSketchAssistantReply } from './sketchAssistantReply.js';
3
+ import { translateEnglish } from '../i18n/language.js';
4
+ /**
5
+ * How many times a run answers the gateway with tool results. The gateway stops a run after the same number of steps
6
+ * (its last answer is words only), so a run that is still asking for tools after this many has not understood the
7
+ * gateway and is stopped here.
8
+ */
9
+ const SKETCH_ASSISTANT_MAX_STEPS = 8;
10
+ /** The only tool whose job is to read the canvas; every other tool changes it. */
11
+ const READ_ONLY_TOOL_NAME = 'get_canvas';
12
+ /**
13
+ * The words for a request the gateway did not take, in the page's language where the catalog has them.
14
+ * A refusal the person can act on gets its own sentence (no credits left, a run already going); a gateway that cannot
15
+ * be reached is one sentence; anything else shows the gateway's own words.
16
+ */
17
+ export function describeSketchRequestFailure(error, translate = translateEnglish) {
18
+ if (error instanceof SketchAssistantRequestError) {
19
+ if (error.status === 402 || error.code === 'BILLING_INSUFFICIENT_CREDITS')
20
+ return translate('chat.sketch.noCredits');
21
+ if (error.status === 429)
22
+ return translate('chat.sketch.busy');
23
+ if (error.status === SKETCH_ASSISTANT_NO_ANSWER_STATUS || error.status === 408 || error.status >= 500) {
24
+ return translate('chat.sketch.unavailable');
25
+ }
26
+ return translate('chat.sketch.failed', { detail: error.message });
27
+ }
28
+ if (error instanceof Error && error.name === 'AbortError')
29
+ return translate('chat.sketch.stopped');
30
+ return translate('chat.sketch.failedUnknown');
31
+ }
32
+ /** A tool result without the copy of the canvas the executors attach: the gateway is sent the canvas once, in `sceneSummary`. */
33
+ function withoutSceneCopy(result) {
34
+ const { summary: _sceneCopy, ...rest } = result;
35
+ return rest;
36
+ }
37
+ /** What a run says when it is over: the model's own words, else what the tools did, else a plain sentence. */
38
+ function closingMessage(response, tools, translate) {
39
+ const modelWords = response.message?.trim();
40
+ if (modelWords)
41
+ return modelWords;
42
+ return tools.length > 0 ? buildSketchAssistantReply(tools, translate) : translate('chat.sketch.genericDone');
43
+ }
44
+ /**
45
+ * Runs one request of the author on the canvas: the gateway's model asks for tools, the canvas runs them here, and
46
+ * the results go back until the model has nothing more to ask.
47
+ *
48
+ * A tool that fails (a shape out of the canvas, an id that is gone) is not the end of the run: its error goes back to
49
+ * the model like any other result, so it can correct itself. The run ends when the model answers, when the gateway
50
+ * refuses, or when it has taken too many steps. It never throws: what went wrong comes back as `ok: false` and a message.
51
+ */
52
+ export async function runSketchAssistantLoop(input) {
53
+ const translate = input.translate ?? translateEnglish;
54
+ const maxSteps = input.maxSteps ?? SKETCH_ASSISTANT_MAX_STEPS;
55
+ const toolTrace = [];
56
+ let steps = 0;
57
+ let batchOpen = false;
58
+ const outcome = (ok, message) => ({
59
+ ok,
60
+ message,
61
+ steps,
62
+ tools: toolTrace,
63
+ changedCanvas: toolTrace.some((tool) => tool.ok && tool.name !== READ_ONLY_TOOL_NAME)
64
+ });
65
+ try {
66
+ let response = await startSketchAssistantRequest({
67
+ apiBaseUrl: input.apiBaseUrl,
68
+ authToken: input.authToken,
69
+ prompt: input.prompt,
70
+ sceneSummary: input.executor.getSceneSummary(),
71
+ conversationId: input.conversationId,
72
+ canvasId: input.canvasId,
73
+ signal: input.signal
74
+ });
75
+ input.executor.beginToolBatch?.();
76
+ batchOpen = true;
77
+ for (;;) {
78
+ if (response.status === 'failed' || response.status === 'disabled') {
79
+ return outcome(false, response.error ?? response.message ?? translate('chat.sketch.failedUnknown'));
80
+ }
81
+ if (response.status === 'completed') {
82
+ return outcome(true, closingMessage(response, toolTrace, translate));
83
+ }
84
+ if (steps >= maxSteps)
85
+ return outcome(false, translate('chat.sketch.stepCap'));
86
+ const toolResults = [];
87
+ for (const call of response.toolCalls ?? []) {
88
+ let result;
89
+ try {
90
+ result = input.executor.executeTool(call.name, call.arguments);
91
+ }
92
+ catch (error) {
93
+ // A canvas that throws is told to the model like a tool that refused, not left to end the run.
94
+ console.warn('[Sketch] A canvas tool threw', call.name, error);
95
+ result = { ok: false, error: error instanceof Error ? error.message : String(error), code: 'internal' };
96
+ }
97
+ toolTrace.push({
98
+ name: call.name,
99
+ ok: Boolean(result.ok),
100
+ message: typeof result.message === 'string' ? result.message : undefined,
101
+ error: typeof result.error === 'string' ? result.error : undefined
102
+ });
103
+ toolResults.push({ toolCallId: call.id, result: withoutSceneCopy(result) });
104
+ }
105
+ steps += 1;
106
+ response = await sketchAssistantStepRequest({
107
+ apiBaseUrl: input.apiBaseUrl,
108
+ authToken: input.authToken,
109
+ sessionId: response.sessionId,
110
+ step: response.step,
111
+ toolResults,
112
+ sceneSummary: input.executor.getSceneSummary(),
113
+ signal: input.signal
114
+ });
115
+ }
116
+ }
117
+ catch (error) {
118
+ // A refusal of the gateway is an answer the person reads; anything else is a fault worth a line in the console.
119
+ if (!(error instanceof SketchAssistantRequestError) && !input.signal?.aborted) {
120
+ console.warn('[Sketch] The sketch assistant stopped', error);
121
+ }
122
+ return outcome(false, describeSketchRequestFailure(error, translate));
123
+ }
124
+ finally {
125
+ if (batchOpen)
126
+ input.executor.endToolBatch?.();
127
+ }
128
+ }
@@ -0,0 +1,12 @@
1
+ import type { Translate } from '@widgetic/design-system/i18n';
2
+ import type { ChatMessageKey } from '../i18n/messages.js';
3
+ export interface SketchToolTrace {
4
+ name: string;
5
+ ok: boolean;
6
+ message?: string;
7
+ error?: string;
8
+ }
9
+ /**
10
+ * User-facing assistant copy from executed tool results (not gateway filler).
11
+ */
12
+ export declare function buildSketchAssistantReply(tools: SketchToolTrace[], translate?: Translate<ChatMessageKey>): string;
@@ -0,0 +1,28 @@
1
+ import { translateEnglish } from '../i18n/language.js';
2
+ /**
3
+ * User-facing assistant copy from executed tool results (not gateway filler).
4
+ */
5
+ export function buildSketchAssistantReply(tools, translate = translateEnglish) {
6
+ const okTools = tools.filter((tool) => tool.ok);
7
+ if (okTools.length === 0) {
8
+ const firstError = tools.find((tool) => !tool.ok)?.error ?? tools[0]?.message;
9
+ return firstError ? translate('chat.sketch.failed', { detail: firstError }) : translate('chat.sketch.failedUnknown');
10
+ }
11
+ const names = new Set(okTools.map((tool) => tool.name));
12
+ if (names.has('draw_ui_component')) {
13
+ return `${translate('chat.sketch.drewVideoPlayer')} ${translate('chat.sketch.followUp')}`;
14
+ }
15
+ if (names.has('move_elements')) {
16
+ return `${translate('chat.sketch.movedNavigation')} ${translate('chat.sketch.followUp')}`;
17
+ }
18
+ if (names.has('delete_elements')) {
19
+ return translate('chat.sketch.deletedAll');
20
+ }
21
+ if (names.has('name_components_with_arrows')) {
22
+ return `${translate('chat.sketch.namedComponents')} ${translate('chat.sketch.followUp')}`;
23
+ }
24
+ if (names.has('add_shape')) {
25
+ return `${translate('chat.sketch.addedShapes')} ${translate('chat.sketch.followUp')}`;
26
+ }
27
+ return okTools.map((tool) => tool.message).filter(Boolean).join(' ') || translate('chat.sketch.genericDone');
28
+ }
@@ -25,6 +25,7 @@ export declare const chatStore: {
25
25
  updateMessageId: (conversationId: string, oldId: string, newId: string) => void;
26
26
  updateMessageContent: (conversationId: string, messageId: string, messageContent: string) => void;
27
27
  updateMessageAttachments: (conversationId: string, messageId: string, attachments: any[]) => void;
28
+ updateMessageSuggestions: (conversationId: string, messageId: string, suggestions: ChatMessage["suggestions"] | undefined) => void;
28
29
  };
29
30
  };
30
31
  /**
@@ -290,6 +290,27 @@ function createChatStore() {
290
290
  }
291
291
  };
292
292
  });
293
+ },
294
+ updateMessageSuggestions: (conversationId, messageId, suggestions) => {
295
+ update(state => {
296
+ const msgs = state.messages.byConversationId[conversationId];
297
+ if (!msgs)
298
+ return state;
299
+ return {
300
+ ...state,
301
+ messages: {
302
+ ...state.messages,
303
+ byConversationId: {
304
+ ...state.messages.byConversationId,
305
+ [conversationId]: msgs.map((msg) => msg.id === messageId
306
+ ? suggestions && suggestions.length > 0
307
+ ? { ...msg, suggestions }
308
+ : { ...msg, suggestions: undefined }
309
+ : msg)
310
+ }
311
+ }
312
+ };
313
+ });
293
314
  }
294
315
  }
295
316
  };
@@ -0,0 +1,74 @@
1
+ import type { Snippet } from 'svelte';
2
+ /**
3
+ * The five looks of the assistant's avatar.
4
+ *
5
+ * They are the states of the Scribble Mascot of `@widgetic/brand`, word for word, so a page that draws the mascot
6
+ * passes `state` straight on. `success` and `error` play once and then rest (the mascot's `settleTo`).
7
+ */
8
+ export type AgentAvatarState = 'idle' | 'thinking' | 'writing' | 'success' | 'error';
9
+ /** What the chat gives the page's avatar snippet each time something about the avatar changes. */
10
+ export interface AgentAvatarRenderProps {
11
+ /** What the assistant is doing right now. */
12
+ state: AgentAvatarState;
13
+ /**
14
+ * Side of the square the avatar is drawn in, in CSS pixels. It changes a little at a time while the avatar grows
15
+ * or shrinks, so the page only has to draw the avatar at this size.
16
+ */
17
+ size: number;
18
+ /**
19
+ * False for an avatar that only has to sit there (a message that is not the newest): draw a still picture and keep
20
+ * nothing running. True for the one that moves.
21
+ */
22
+ live: boolean;
23
+ /**
24
+ * What a screen reader says about the avatar, already in the language of the page. Empty when it should say nothing (an
25
+ * avatar at rest sits beside words that say it all): draw it as decoration then.
26
+ */
27
+ label: string;
28
+ }
29
+ /**
30
+ * How a page draws the assistant's avatar. The chat has no dependency on any drawing code: a page that has the
31
+ * Scribble Mascot gives a snippet that draws it, and a page that does not gets a plain round avatar.
32
+ *
33
+ * @example
34
+ * ```svelte
35
+ * {#snippet agentAvatar({ state: avatarState, size, live, label })}
36
+ * <Mascot state={avatarState} {size} {label} decorative={!label} frozenAt={live ? undefined : 0.5} settleTo="idle" />
37
+ * {/snippet}
38
+ * <Chat renderAgentAvatar={agentAvatar} … />
39
+ * ```
40
+ */
41
+ export type AgentAvatarRenderer = Snippet<[AgentAvatarRenderProps]>;
42
+ /**
43
+ * How a page lets the assistant's avatar be heard. The chat has no dependency on any sound code: a page that has the
44
+ * mascot's sound gives it (`createMascotSound()` of `@widgetic/brand/mascot/sound` fits as it is), and a page that does not
45
+ * gets silence. The chat tells it the state of the avatar the person is looking at, once for each change, and only for what
46
+ * the person watched happen: never for a conversation that was just opened, whatever state its last message left the avatar in.
47
+ *
48
+ * Whether sound is on, how loud, the browser's lock on audio and every other rule of sounding belong to the player (the
49
+ * mascot's is off until the person asks, and keeps the same cue from repeating): the chat has no control for it, the page does.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * import { createMascotSound } from '@widgetic/brand/mascot/sound';
54
+ * const agentSound = createMascotSound(); // off until `agentSound.enable()` runs inside a click
55
+ * // <Chat {agentSound} … />
56
+ * ```
57
+ */
58
+ export interface AgentSoundPlayer {
59
+ /** The avatar the person is looking at went to `state`. The player decides whether anything sounds for it. */
60
+ notifyStateChange(state: AgentAvatarState): unknown;
61
+ }
62
+ /**
63
+ * A person of the team, as the chat needs to know them to put a face on what they wrote.
64
+ * Everything but `id` is optional: a person without a name still gets their initials from the e-mail.
65
+ */
66
+ export interface ChatMember {
67
+ /** The id the messages carry as `userId`. */
68
+ id: string;
69
+ name?: string | null;
70
+ /** Shown when the pointer rests on the avatar. */
71
+ email?: string | null;
72
+ /** A picture of the person. Without one (or when it cannot be loaded) the initials stay. */
73
+ avatarUrl?: string | null;
74
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -7,6 +7,7 @@ export * from './state.js';
7
7
  export * from './config.js';
8
8
  export * from './adapter.js';
9
9
  export * from './events.js';
10
+ export * from './agent.js';
10
11
  export type { ChatService, ChatInstance, ChatFactory } from './chat.js';
11
12
  export type { ChatMessage, MessageInput } from './message.js';
12
13
  export type { ChatConversation, ConversationInput } from './conversation.js';
@@ -8,3 +8,5 @@ export * from './state.js';
8
8
  export * from './config.js';
9
9
  export * from './adapter.js';
10
10
  export * from './events.js';
11
+ // The assistant's avatar and the people of the team (what a page hands over to put faces on the messages)
12
+ export * from './agent.js';
@@ -105,6 +105,8 @@ export type VersionRating = 'up' | 'down' | 'none';
105
105
  export interface ClarificationSuggestion {
106
106
  label: string;
107
107
  intent: 'refine' | 'generate_anyway';
108
+ /** When true, the host undoes the last sketch assistant turn instead of sending the label as a prompt. */
109
+ undoSketch?: boolean;
108
110
  }
109
111
  /**
110
112
  * Message input type for creating new messages
@@ -0,0 +1,219 @@
1
+ import type { ChatMessageKey } from '../i18n/messages.js';
2
+ import type { AgentAvatarState, ChatMember } from '../types/agent.js';
3
+ import type { GenerationActivityPhase } from './generationActivity.js';
4
+ /**
5
+ * The rules of the assistant's turn: what its avatar looks like and does at each moment, how a finished turn is judged,
6
+ * who wrote a message of a person, and what is kept of the work once it is done.
7
+ *
8
+ * Plain TypeScript with no Svelte in it, so the rules can be tested in Node as they are (`tests/agent-turn.test.mjs`)
9
+ * and a page that is not the chat (the workflows assistant) can follow the same choreography.
10
+ */
11
+ /** `large` is the avatar of the moments that matter (waiting, a card to answer, the conclusion); `small` sits by the text. */
12
+ export type AgentAvatarSize = 'large' | 'small';
13
+ /** What the avatar of an assistant turn looks like and does. */
14
+ export interface AgentLook {
15
+ state: AgentAvatarState;
16
+ size: AgentAvatarSize;
17
+ /** True for the avatar that moves (the newest turn); false for one that only sits there as a still picture. */
18
+ live: boolean;
19
+ }
20
+ /**
21
+ * The look while a generation runs.
22
+ *
23
+ * - Waiting for the first word of the model: the avatar is large and thinks. A plan card or a question, when there is
24
+ * one, sits to its right.
25
+ * - Its reasoning streams: the avatar shrinks to the left and KEEPS THINKING for as long as the reasoning is being written.
26
+ * The words beside it say "Thinking…" (the thinking module's own title): the avatar carries no name or label.
27
+ * - What it writes next streams (the code, or the reply the model writes: the chat has no other stream than the reasoning and
28
+ * this one): still small, and now it WRITES; the code module's title says "Writing code…".
29
+ *
30
+ * (The mascot package maps the phases the same way: `thinking-stream` is its `thinking` state.)
31
+ */
32
+ export declare function liveAgentLook(phase: GenerationActivityPhase): AgentLook;
33
+ /** How a turn ended, as far as the avatar cares. */
34
+ export type TurnOutcome =
35
+ /** The assistant built something (a commit, "Code generation completed") or a generation ran for this turn. */
36
+ 'success'
37
+ /** The last thing it said is a failure. */
38
+ | 'error'
39
+ /** The person stopped it: their own command, not a failure. */
40
+ | 'stopped'
41
+ /** The last thing it said is a card waiting for an answer. */
42
+ | 'question'
43
+ /** Anything else it said (a plain answer). */
44
+ | 'answer';
45
+ /** What the chat found out about one visible reply of a turn (the chat's own tests of the text, kept out of this file). */
46
+ export interface TurnReplyFacts {
47
+ isFailure: boolean;
48
+ isStopped: boolean;
49
+ /** The reply carries clarification suggestions: a question card waits under it. */
50
+ hasQuestion: boolean;
51
+ /** The reply announces a widget commit. */
52
+ hasCommit: boolean;
53
+ /** The reply is the "Code generation completed" line. */
54
+ isCompletion: boolean;
55
+ }
56
+ /**
57
+ * Judges a turn from its visible replies. The LAST reply decides how it ended; a commit or a completion line anywhere in
58
+ * the turn (or a generation that ran for it) makes an ordinary last reply a success.
59
+ */
60
+ export declare function turnOutcome(replies: readonly TurnReplyFacts[], generationRanForTurn: boolean): TurnOutcome | null;
61
+ /**
62
+ * The look of a turn that is not running. Only the newest turn moves, and only its conclusion is large (the success or
63
+ * the error avatar, or a question to answer): older turns are small still pictures, so a long chat keeps one mascot
64
+ * alive instead of one per message.
65
+ */
66
+ export declare function settledAgentLook(outcome: TurnOutcome, isNewestTurn: boolean): AgentLook;
67
+ /** Where the avatar that takes over from the live one starts. */
68
+ export interface AvatarStart {
69
+ /** The size it glides from to its own. */
70
+ startSize: AgentAvatarSize;
71
+ /** The state it is drawn in first, before it moves on to its own (a mascot blends between the two). Undefined: its own from the start. */
72
+ startState: AgentAvatarState | undefined;
73
+ }
74
+ /**
75
+ * The live avatar of a run and the one of its ending are two avatars, one after the other, in the same place. The second one starts
76
+ * from how the first one looked when the run ended, so what the person watched carries on instead of being swapped: a Stop pressed
77
+ * while the avatar is still large shrinks it down to its small size, and the mascot calms from what it was doing; a conclusion
78
+ * grows out of the avatar of the work.
79
+ *
80
+ * Without a live avatar to take over from (the conversation was opened or reloaded after the run) it starts from the small one,
81
+ * which is where a conclusion has always grown out of.
82
+ */
83
+ export declare function avatarStartAfter(lastLiveLook: AgentLook | null): AvatarStart;
84
+ /** What `soundStateOf` looks at. */
85
+ export interface SoundStateInput {
86
+ /** A run is working and its live avatar is on screen. */
87
+ runIsLive: boolean;
88
+ /** How the live avatar looks for the phase the run is in. */
89
+ liveLook: AgentLook;
90
+ /** A run worked while this conversation was open here (the person saw it happen). */
91
+ runWasWatched: boolean;
92
+ /** How the avatar of the newest turn looks, or null when that turn has no assistant to show (yet). */
93
+ newestTurnLook: AgentLook | null;
94
+ }
95
+ /**
96
+ * The state of the avatar the person is looking at, for the page's sound to follow, or null when there is nothing to hear.
97
+ *
98
+ * - While a run works, the live avatar's own state: thinking when it starts, writing when code or the answer is written.
99
+ * - When it ends, the state of the newest turn's avatar: success or error say how it went, and idle (a question, a stop) says it
100
+ * is waiting.
101
+ * - Never for a conversation that was only opened: its newest turn may be left in `error` or `success`, but nothing happened in
102
+ * front of the person, so nothing is heard. Opening a chat must not play the sound of a failure.
103
+ * - Null as well while the newest turn has nothing to show yet (a prompt just sent, or a run that has ended a moment before its
104
+ * conclusion arrives): the sound keeps what it last heard.
105
+ *
106
+ * Only a change of this value is worth telling the sound about, and the caller tells it once for each.
107
+ */
108
+ export declare function soundStateOf(input: SoundStateInput): AgentAvatarState | null;
109
+ /** The side of the avatar in pixels. Without a page's own avatar the large one is only a little larger: a plain circle that big is noise. */
110
+ export declare const AGENT_AVATAR_PIXELS: {
111
+ /** The mascot's full drawing (64 px and up). */
112
+ readonly largeWithPageAvatar: 80;
113
+ readonly largeWithoutPageAvatar: 32;
114
+ /** The mascot's compact drawing, which still moves (28 px and up). */
115
+ readonly small: 28;
116
+ };
117
+ export declare function agentAvatarPixels(size: AgentAvatarSize, hasPageAvatar: boolean): number;
118
+ /**
119
+ * The catalog key of what a screen reader says about the avatar in a state, or null when it says nothing: an avatar at rest
120
+ * sits beside the words of the turn, which are what is read (the others say what is going on, which no words beside it do).
121
+ */
122
+ export declare function agentAvatarLabelKey(state: AgentAvatarState): ChatMessageKey | null;
123
+ /** A stable text for a look, so the chat can say a change once and not on every redraw. */
124
+ export declare function agentLookSignature(look: AgentLook): string;
125
+ /** Which parts of the work are on screen, and which of them start open. */
126
+ export interface GenerationModulesView {
127
+ /** The typed "Assistant is thinking" line: nothing has streamed yet. */
128
+ showShimmer: boolean;
129
+ showThinking: boolean;
130
+ /** Reasoning is still arriving (and nothing else has started). */
131
+ thinkingStreaming: boolean;
132
+ /** A module is open while it is the live one, and closed once the next has taken over. The person can still open it. */
133
+ thinkingOpenByDefault: boolean;
134
+ showCode: boolean;
135
+ codeStreaming: boolean;
136
+ codeOpenByDefault: boolean;
137
+ }
138
+ /** The modules while a generation runs. The thoughts fold away once the code starts, the code stays open while it streams. */
139
+ export declare function liveModulesView(phase: GenerationActivityPhase): GenerationModulesView;
140
+ /** The modules under a conclusion: whatever was kept, closed, for the person to open. */
141
+ export declare function finishedModulesView(finished: Pick<FinishedGeneration, 'thinking' | 'code'> | null): GenerationModulesView;
142
+ /**
143
+ * The thinking and the code of the generation that just ended: what the modules under the conclusion show.
144
+ * Kept in memory for the newest turn only (the host saves neither); it is gone after a reload, and the conclusion
145
+ * simply shows without them.
146
+ */
147
+ export interface FinishedGeneration {
148
+ /** The prompt of the turn it belongs to, normalized with `normalizePromptText`. */
149
+ prompt: string;
150
+ thinking: string;
151
+ code: string;
152
+ thoughtSeconds: number | null;
153
+ }
154
+ /**
155
+ * The most text kept of either part. A generation streams tails; the chat stitches them, and a runaway stream
156
+ * must not grow memory without end.
157
+ */
158
+ export declare const MAX_KEPT_GENERATION_CHARS = 120000;
159
+ /**
160
+ * 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
161
+ * may reload the whole conversation after a generation. The words the person wrote survive both.
162
+ */
163
+ export declare function normalizePromptText(content: string | null | undefined): string;
164
+ /** What to keep of a generation that ended, or null when it left nothing to show. */
165
+ export declare function keepFinishedGeneration(input: {
166
+ promptText: string | null | undefined;
167
+ thinking: string;
168
+ code: string;
169
+ thoughtSeconds: number | null;
170
+ }): FinishedGeneration | null;
171
+ /** Whether the kept work belongs under the turn of this prompt: the newest turn, found again by the words of its prompt. */
172
+ export declare function finishedGenerationBelongsTo(finished: FinishedGeneration | null, newestTurnPromptText: string | null | undefined): finished is FinishedGeneration;
173
+ /**
174
+ * Whether the work kept for a run is out of date because the person sent another prompt after the one that run answered.
175
+ * The words of a prompt sent again (a retry) are the same, so `finishedGenerationBelongsTo` cannot tell the new turn from the
176
+ * old one, and for as long as the host takes to save the prompt and start the run (the chat adds the message first) the new turn
177
+ * would show the last run's conclusion. The message the kept work answered tells them apart: a user message after it is a new turn.
178
+ *
179
+ * That message is found by its id, not by the object: the chat builds new message objects when a prompt is sent (it clears the
180
+ * marks of the last version first), while the id of a prompt is the saved one by the time its run ends, because the host
181
+ * saves a prompt before it starts the run.
182
+ *
183
+ * When there is no id, or no message with it in the list any more (the host loaded the conversation again, or the work came back
184
+ * from the archive, which knows only the words) there is nothing to tell by, and the words decide, as they always did.
185
+ */
186
+ export declare function keptWorkIsOutdated(answeredMessageId: string | null, messagesInOrder: ReadonlyArray<{
187
+ id: string;
188
+ messageType: string;
189
+ }>): boolean;
190
+ /** The `userId` the chat gives a message the signed-in person adds with `addUserMessage`, before the host has saved it and told the real one. */
191
+ export declare const CURRENT_USER_PLACEHOLDER_ID = "current_user";
192
+ /**
193
+ * The `userId` the chat's own local service gives every message the person types: `Chat.sendMessage` shows the message at
194
+ * once, made by that service, and `onSaveMessage` swaps the id of the message but never this. A made-up id too: until the page
195
+ * loads the history again (and the messages carry the real ids), it stands for the signed-in person.
196
+ */
197
+ export declare const LOCAL_SERVICE_USER_ID = "test_user";
198
+ /**
199
+ * Finds the person behind a message. The team the page gave wins (it is the list the page keeps up to date); the
200
+ * signed-in person comes next, which is also who the made-up ids of a message that is not saved yet stand for.
201
+ * Null when nobody can be named: the message then has no face and no tooltip, instead of a wrong one.
202
+ */
203
+ export declare function resolveChatMember(userId: string | null | undefined, members: readonly ChatMember[], currentUser: ChatMember | null | undefined): ChatMember | null;
204
+ /** The text the initials of an avatar come from: the name, or the part of the e-mail before the @. Empty when there is neither. */
205
+ export declare function memberDisplayName(member: ChatMember | null | undefined): string;
206
+ /**
207
+ * The e-mail line of the tooltip over an avatar: the e-mail only, never a placeholder word. The same rule as the
208
+ * project header of the Widgetic site (`projectMemberTooltipEmail`), so a person sees the same thing in both places.
209
+ */
210
+ export declare function memberTooltipEmail(email: string | null | undefined): string | null;
211
+ /**
212
+ * Where a click on an avatar goes: a `mailto:` link to the e-mail of the person, as the avatars of the project header of the
213
+ * Widgetic site do (`personMailtoHref`). Null when there is no e-mail to write to (the same rule as the tooltip's: never a
214
+ * placeholder word), and the avatar is then only a picture. The part before the @ is encoded (a `+` in it would otherwise be
215
+ * read as a space); the domain is left as it is.
216
+ */
217
+ export declare function memberMailtoHref(email: string | null | undefined): string | null;
218
+ /** Whether the page told the chat anything about who is who: without it the chat draws no faces next to what people wrote. */
219
+ export declare function pageNamesPeople(members: readonly ChatMember[], currentUser: ChatMember | null | undefined): boolean;