@happyvertical/smrt-chat 0.60.14 → 0.60.15

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 (39) hide show
  1. package/AGENTS.md +6 -2
  2. package/agents/ai-unavailable.md +42 -0
  3. package/dist/ai-unavailable.d.ts +33 -0
  4. package/dist/ai-unavailable.d.ts.map +1 -0
  5. package/dist/chat-stream.d.ts +5 -0
  6. package/dist/chat-stream.d.ts.map +1 -1
  7. package/dist/chunks/{chat-stream-BEQxcBwW.js → chat-stream-FDF9I30Z.js} +45 -14
  8. package/dist/chunks/chat-stream-FDF9I30Z.js.map +1 -0
  9. package/dist/client.d.ts +26 -0
  10. package/dist/client.d.ts.map +1 -1
  11. package/dist/client.js +59 -4
  12. package/dist/client.js.map +1 -1
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +2 -2
  16. package/dist/manifest.json +1 -1
  17. package/dist/smrt-knowledge.json +11 -5
  18. package/dist/smrt-knowledge.okf.md +11 -7
  19. package/dist/svelte/components/assistant/AssistantDock.svelte +34 -2
  20. package/dist/svelte/components/assistant/AssistantDock.svelte.d.ts +4 -0
  21. package/dist/svelte/components/assistant/AssistantDock.svelte.d.ts.map +1 -1
  22. package/dist/svelte/components/assistant/assistant-http-client.d.ts +6 -1
  23. package/dist/svelte/components/assistant/assistant-http-client.d.ts.map +1 -1
  24. package/dist/svelte/components/assistant/assistant-http-client.js +21 -2
  25. package/dist/svelte/components/shared/AiUnavailableNotice.svelte +66 -0
  26. package/dist/svelte/components/shared/AiUnavailableNotice.svelte.d.ts +13 -0
  27. package/dist/svelte/components/shared/AiUnavailableNotice.svelte.d.ts.map +1 -0
  28. package/dist/svelte/i18n.d.ts +5 -0
  29. package/dist/svelte/i18n.d.ts.map +1 -1
  30. package/dist/svelte/i18n.js +6 -0
  31. package/dist/svelte/index.d.ts +2 -0
  32. package/dist/svelte/index.d.ts.map +1 -1
  33. package/dist/svelte/index.js +1 -0
  34. package/dist/sveltekit.d.ts +11 -5
  35. package/dist/sveltekit.d.ts.map +1 -1
  36. package/dist/sveltekit.js +45 -6
  37. package/dist/sveltekit.js.map +1 -1
  38. package/package.json +17 -17
  39. package/dist/chunks/chat-stream-BEQxcBwW.js.map +0 -1
package/dist/client.d.ts CHANGED
@@ -118,7 +118,33 @@ export type ChatClientStreamFrame = {
118
118
  } | {
119
119
  type: 'error';
120
120
  error?: string;
121
+ code?: string;
122
+ unavailable?: ChatUnavailableStatus;
121
123
  };
124
+ /**
125
+ * Why AI is unavailable, as the server sends it (#4757): the shape of core's
126
+ * `InferenceStatus`, repeated here so this module stays dependency-free.
127
+ */
128
+ export interface ChatUnavailableStatus {
129
+ available: false;
130
+ mode: 'byo' | 'local' | 'hosted' | 'off';
131
+ reason: 'off' | 'unconfigured' | 'entitlement' | 'capability';
132
+ tier?: 'cheap' | 'good' | 'great' | 'best';
133
+ }
134
+ /** The `code` of an unavailable answer. */
135
+ export declare const CHAT_UNAVAILABLE_CODE = "ai_unavailable";
136
+ /** The status in an `ai_unavailable` body or event, else `undefined`. */
137
+ export declare function readChatUnavailableStatus(body: unknown): ChatUnavailableStatus | undefined;
138
+ /**
139
+ * AI is off or not set up (#4757): the server answered `ai_unavailable`
140
+ * (a 503, or an in-band stream `error` event). `unavailable` says why; a UI
141
+ * renders "AI is off" with a settings link instead of a failure.
142
+ */
143
+ export declare class ChatUnavailableError extends Error {
144
+ readonly unavailable: ChatUnavailableStatus;
145
+ readonly code = "ai_unavailable";
146
+ constructor(message: string, unavailable: ChatUnavailableStatus);
147
+ }
122
148
  /**
123
149
  * SSE client for the streaming chat route (smrt-chat #1936). Structurally
124
150
  * implements `@happyvertical/animation`'s `ChatBackend`, so it plugs straight
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AA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,EAAE,EAC7B,QAAQ,EAAE,wBAAwB,GACjC,oBAAoB;CAwGxB"}
package/dist/client.js CHANGED
@@ -1,4 +1,52 @@
1
1
  //#region src/client.ts
2
+ var UNAVAILABLE_REASONS = [
3
+ "off",
4
+ "unconfigured",
5
+ "entitlement",
6
+ "capability"
7
+ ];
8
+ var INFERENCE_MODES = [
9
+ "byo",
10
+ "local",
11
+ "hosted",
12
+ "off"
13
+ ];
14
+ var INFERENCE_TIERS = [
15
+ "cheap",
16
+ "good",
17
+ "great",
18
+ "best"
19
+ ];
20
+ var CHAT_UNAVAILABLE_CODE = "ai_unavailable";
21
+ function readChatUnavailableStatus(body) {
22
+ if (!body || typeof body !== "object") return void 0;
23
+ const record = body;
24
+ if (record.code !== "ai_unavailable") return void 0;
25
+ const status = record.unavailable;
26
+ if (!status || !UNAVAILABLE_REASONS.includes(status.reason)) return;
27
+ const reason = status.reason;
28
+ return {
29
+ available: false,
30
+ mode: reason === "off" || reason === "unconfigured" ? "off" : INFERENCE_MODES.includes(status.mode) ? status.mode : "off",
31
+ reason,
32
+ ...INFERENCE_TIERS.includes(status.tier) ? { tier: status.tier } : {}
33
+ };
34
+ }
35
+ var ChatUnavailableError = class extends Error {
36
+ constructor(message, unavailable) {
37
+ super(message);
38
+ this.unavailable = unavailable;
39
+ this.name = "ChatUnavailableError";
40
+ }
41
+ unavailable;
42
+ code = CHAT_UNAVAILABLE_CODE;
43
+ };
44
+ function unavailableErrorFrom(body) {
45
+ const status = readChatUnavailableStatus(body);
46
+ if (!status) return void 0;
47
+ const message = body.error;
48
+ return new ChatUnavailableError(typeof message === "string" && message ? message : "AI is unavailable.", status);
49
+ }
2
50
  var counter = 0;
3
51
  function messageId() {
4
52
  const c = globalThis.crypto;
@@ -46,10 +94,17 @@ var SmrtChatBackend = class {
46
94
  signal: controller.signal
47
95
  });
48
96
  if (!response.ok || !response.body) {
49
- let detail = "";
97
+ let text = "";
98
+ try {
99
+ text = await response.text();
100
+ } catch {}
101
+ const detail = text.slice(0, 200);
102
+ let parsed;
50
103
  try {
51
- detail = (await response.text()).slice(0, 200);
104
+ parsed = JSON.parse(text);
52
105
  } catch {}
106
+ const unavailable = unavailableErrorFrom(parsed);
107
+ if (unavailable) throw unavailable;
53
108
  throw new Error(`[smrt-chat] chat endpoint responded ${response.status}${detail ? `: ${detail}` : ""}`);
54
109
  }
55
110
  const reader = response.body.getReader();
@@ -72,7 +127,7 @@ var SmrtChatBackend = class {
72
127
  handlers.onToken(event.text);
73
128
  } else if (event.type === "emotion" && event.name) handlers.onEmotion?.(event.name);
74
129
  else if (event.type === "control") {} else if (event.type === "error") {
75
- handlers.onError(new Error(event.error ?? "[smrt-chat] chat stream error"));
130
+ handlers.onError(unavailableErrorFrom(event) ?? new Error(event.error ?? "[smrt-chat] chat stream error"));
76
131
  reader.cancel().catch(() => {});
77
132
  return;
78
133
  } else if (event.type === "done") {
@@ -92,6 +147,6 @@ var SmrtChatBackend = class {
92
147
  }
93
148
  };
94
149
  //#endregion
95
- export { SmrtChatBackend };
150
+ export { CHAT_UNAVAILABLE_CODE, ChatUnavailableError, SmrtChatBackend, readChatUnavailableStatus };
96
151
 
97
152
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":[],"sources":["../src/client.ts"],"sourcesContent":["/**\n * Browser client for smrt-chat's streaming chat route — the consume side of\n * the SSE contract `createChatStreamHandler` serves (see `chat-stream.ts`,\n * which owns the wire contract and exports the encode side).\n *\n * This module is BROWSER-SAFE and dependency-free: it must not import the\n * server runtime (models, services, tool loop) or any workspace package, so\n * a static site can ship it without dragging server code into the bundle. It\n * is exported under the dedicated `@happyvertical/smrt-chat/client` subpath.\n *\n * POST {endpoint}\n * Authorization: Bearer <sessionId> (SMRT bearer = session id)\n * Content-Type: application/json\n * Body: { \"messages\": ChatClientMessage[], \"session\": SmrtChatSession? }\n *\n * Response: text/event-stream, events as `data: <json>` lines:\n * { \"type\": \"token\", \"text\": \"...\" }\n * { \"type\": \"emotion\", \"name\": \"heart\" } (reserved; v1 engine forwards\n * the model's inline cue as tokens)\n * { \"type\": \"control\", \"command\": {...} } (#1921 host-page control lane;\n * parsed, no client hook yet)\n * { \"type\": \"done\", \"message\": ChatStreamMessage }\n * { \"type\": \"error\", \"error\": \"...\" }\n * plus `: heartbeat` comment lines every ~15s, which clients must ignore.\n *\n * The server always terminates a turn with a `done` or `error` frame; a clean\n * close without one means an intermediary cut the stream (proxy idle timeout)\n * and is surfaced as an error rather than an empty success.\n *\n * The widget-facing types below are STRUCTURALLY identical to\n * `@happyvertical/animation`'s chat contract (`ChatBackend`, `ChatMessage`,\n * `ChatStreamHandlers`, `ChatSendHandle`), so an instance drops straight into\n * `createHappyChat({ backend })` without this package depending on the widget\n * library. `client.contract.ts` pins the other seam under `pnpm typecheck`:\n * every `ChatStreamEvent` the server can emit is assignable to\n * `ChatClientStreamFrame`.\n */\n\n/** A rendered conversation message (the widget-side shape; all fields set). */\nexport interface ChatClientMessage {\n id: string;\n role: 'user' | 'assistant' | 'system';\n content: string;\n createdAt: string;\n}\n\n/** Streaming callbacks for one assistant reply. */\nexport interface ChatClientStreamHandlers {\n /** A chunk of assistant text (may be words or partial words). */\n onToken(text: string): void;\n /** An expression cue for the character (e.g. 'heart', 'wink'). */\n onEmotion?(name: string): void;\n /** The reply is complete; `message` is the final assembled message. */\n onDone(message: ChatClientMessage): void;\n onError(error: unknown): void;\n}\n\nexport interface ChatClientSendHandle {\n cancel(): void;\n}\n\n/**\n * A conversation backend. `send` receives the FULL message history (latest\n * user message last) and streams the assistant reply through `handlers`.\n */\nexport interface ChatClientBackend {\n send(\n messages: ChatClientMessage[],\n handlers: ChatClientStreamHandlers,\n ): ChatClientSendHandle;\n}\n\n/**\n * Conversation identity, mirroring `ChatStreamSession`\n * (`VoiceGatewayTurnMetadata`) so a server route can bind the turn to an\n * AgentSession/persona. Mirrored rather than imported to keep this module\n * free of server imports; `client.test.ts` asserts the shapes stay aligned.\n */\nexport interface SmrtChatSession {\n tenantId?: string;\n actorProfileId?: string;\n chatRoomId?: string;\n threadId?: string;\n agentSessionId?: string;\n personaId?: string;\n voiceSessionId?: string;\n}\n\nexport interface SmrtChatBackendOptions {\n /** Full URL of the streaming chat route. */\n endpoint: string;\n /** SMRT bearer token (the session id). Omit for cookie/same-origin auth. */\n token?: string;\n /**\n * fetch credentials mode (the `RequestCredentials` union, spelled out so\n * this module typechecks without the DOM lib). Cookie auth from a\n * cross-origin embed needs 'include' (pairs with the server's allow-listed\n * credentialed CORS, smrt #1861); the default is fetch's own 'same-origin'.\n */\n credentials?: 'omit' | 'same-origin' | 'include';\n /** Conversation identity (persona/agent-session binding). */\n session?: SmrtChatSession;\n fetchImpl?: typeof fetch;\n}\n\n/**\n * One parsed wire frame. Deliberately lenient where the client can degrade\n * (optional `message`/`error`) — and provably a superset of the server's\n * `ChatStreamEvent` union (compile-time lock in `client.test.ts`).\n */\nexport type ChatClientStreamFrame =\n | { type: 'token'; text: string }\n | { type: 'emotion'; name: string }\n | { type: 'control'; command: unknown }\n | {\n type: 'done';\n message?: {\n id?: string;\n role: ChatClientMessage['role'];\n content: string;\n createdAt?: string;\n };\n }\n | { type: 'error'; error?: string };\n\nlet counter = 0;\n\n/** Message id: crypto.randomUUID when available, counter fallback. */\nfunction messageId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c && typeof c.randomUUID === 'function') return c.randomUUID();\n counter += 1;\n return `msg-${Date.now()}-${counter}`;\n}\n\n/**\n * Pull `[emotion:name]` cues out of a reply, returning the clean text and the\n * last cue seen. The v1 streaming engine forwards the model's inline cue as\n * plain token text rather than an `emotion` frame, so the done message can\n * still carry it; strip it here so it never lands in the bubble/history, and\n * surface the emotion so the character still emotes.\n */\nfunction extractEmotion(text: string): {\n clean: string;\n emotion: string | null;\n} {\n let emotion: string | null = null;\n const clean = text\n .replace(/\\s*\\[emotion:(\\w+)\\]/g, (_, name: string) => {\n emotion = name;\n return '';\n })\n .trim();\n return { clean, emotion };\n}\n\n/**\n * Final message handed to `onDone`: keep the server's persisted identity\n * (id/createdAt) when present so a consumer reconciling with fetched room\n * history can match it, and fill honestly when the wire omitted it — the\n * wire shape has optional id/createdAt, the widget shape does not.\n */\nfunction finalizeMessage(\n message: Extract<ChatClientStreamFrame, { type: 'done' }>['message'],\n content: string,\n): ChatClientMessage {\n return {\n id: message?.id ?? messageId(),\n role: message?.role ?? 'assistant',\n content,\n createdAt: message?.createdAt ?? new Date().toISOString(),\n };\n}\n\n/**\n * SSE client for the streaming chat route (smrt-chat #1936). Structurally\n * implements `@happyvertical/animation`'s `ChatBackend`, so it plugs straight\n * into the floating chat widget.\n */\nexport class SmrtChatBackend implements ChatClientBackend {\n private options: SmrtChatBackendOptions;\n\n constructor(options: SmrtChatBackendOptions) {\n this.options = options;\n }\n\n send(\n messages: ChatClientMessage[],\n handlers: ChatClientStreamHandlers,\n ): ChatClientSendHandle {\n const controller = new AbortController();\n const fetchImpl = this.options.fetchImpl ?? fetch;\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n };\n if (this.options.token) {\n headers.authorization = `Bearer ${this.options.token}`;\n }\n\n (async () => {\n const response = await fetchImpl(this.options.endpoint, {\n method: 'POST',\n headers,\n credentials: this.options.credentials,\n body: JSON.stringify({\n messages,\n session: this.options.session,\n }),\n signal: controller.signal,\n });\n if (!response.ok || !response.body) {\n // The handler renders structured errors ({error, code}) — carry the\n // body so auth failures are distinguishable from bad requests.\n let detail = '';\n try {\n detail = (await response.text()).slice(0, 200);\n } catch {\n /* body unreadable — status alone will have to do */\n }\n throw new Error(\n `[smrt-chat] chat endpoint responded ${response.status}${\n detail ? `: ${detail}` : ''\n }`,\n );\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n let assembled = '';\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let newline = buffer.indexOf('\\n');\n while (newline !== -1) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n newline = buffer.indexOf('\\n');\n if (!line.startsWith('data:')) continue; // blank + `: heartbeat`\n const event = JSON.parse(line.slice(5)) as ChatClientStreamFrame;\n if (event.type === 'token' && event.text) {\n assembled += event.text;\n handlers.onToken(event.text);\n } else if (event.type === 'emotion' && event.name) {\n handlers.onEmotion?.(event.name);\n } else if (event.type === 'control') {\n // #1921 host-page control lane — recognized so the union stays\n // honest; no client hook yet (the widget executes controls via\n // its own registry when that wiring lands).\n } else if (event.type === 'error') {\n handlers.onError(\n new Error(event.error ?? '[smrt-chat] chat stream error'),\n );\n // The turn is settled but the server may keep sending (heartbeats,\n // late frames) — release the connection instead of leaving the\n // stream open until GC.\n reader.cancel().catch(() => {\n /* stream already closed — nothing to release */\n });\n return;\n } else if (event.type === 'done') {\n const raw = event.message?.content ?? assembled;\n const { clean, emotion } = extractEmotion(raw);\n if (emotion) handlers.onEmotion?.(emotion);\n handlers.onDone(finalizeMessage(event.message, clean));\n reader.cancel().catch(() => {\n /* stream already closed — nothing to release */\n });\n return;\n }\n }\n }\n // The server always terminates with done or error; a clean close\n // without one means an intermediary cut the stream. Never fabricate\n // a successful (possibly empty) reply out of a truncation.\n throw new Error('[smrt-chat] chat stream ended without a done frame');\n })().catch((error) => {\n if (!controller.signal.aborted) handlers.onError(error);\n });\n\n return { cancel: () => controller.abort() };\n }\n}\n"],"mappings":";AA6HA,IAAI,UAAU;AAGd,SAAS,YAAoB;CAC3B,MAAM,IAAK,WAA0D;CACrE,IAAI,KAAK,OAAO,EAAE,eAAe,YAAY,OAAO,EAAE,WAAW;CACjE,WAAW;CACX,OAAO,OAAO,KAAK,IAAI,EAAC,GAAI;AAC9B;AASA,SAAS,eAAe,MAGtB;CACA,IAAI,UAAyB;CAO7B,OAAO;EAAE,OANK,KACX,QAAQ,0BAA0B,GAAG,SAAiB;GACrD,UAAU;GACV,OAAO;EACT,CAAC,CAAA,CACA,KACM;EAAO;CAAQ;AAC1B;AAQA,SAAS,gBACP,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O,MAAM,UAAU,CAAC;KACjC,UAAU,OAAO,QAAQ,IAAI;KAC7B,IAAI,CAAC,KAAK,WAAW,OAAO,GAAG;KAC/B,MAAM,QAAQ,KAAK,MAAM,KAAK,MAAM,CAAC,CAAC;KACtC,IAAI,MAAM,SAAS,WAAW,MAAM,MAAM;MACxC,aAAa,MAAM;MACnB,SAAS,QAAQ,MAAM,IAAI;KAC7B,OAAA,IAAW,MAAM,SAAS,aAAa,MAAM,MAC3C,SAAS,YAAY,MAAM,IAAI;UACjC,IAAW,MAAM,SAAS,WAAW,CAIrC,OAAA,IAAW,MAAM,SAAS,SAAS;MACjC,SAAS,QACP,IAAI,MAAM,MAAM,SAAS,+BAA+B,CAC1D;MAIA,OAAO,OAAO,CAAA,CAAE,YAAY,CAE5B,CAAC;MACD;KACF,OAAA,IAAW,MAAM,SAAS,QAAQ;MAEhC,MAAM,EAAE,OAAO,YAAY,eADf,MAAM,SAAS,WAAW,SACO;MAC7C,IAAI,SAAS,SAAS,YAAY,OAAO;MACzC,SAAS,OAAO,gBAAgB,MAAM,SAAS,KAAK,CAAC;MACrD,OAAO,OAAO,CAAA,CAAE,YAAY,CAE5B,CAAC;MACD;KACF;IACF;GACF;GAIA,MAAM,IAAI,MAAM,oDAAoD;EACtE,EAAA,CAAG,CAAA,CAAE,OAAO,UAAU;GACpB,IAAI,CAAC,WAAW,OAAO,SAAS,SAAS,QAAQ,KAAK;EACxD,CAAC;EAED,OAAO,EAAE,cAAc,WAAW,MAAM,EAAE;CAC5C;AACF"}
1
+ {"version":3,"file":"client.js","names":[],"sources":["../src/client.ts"],"sourcesContent":["/**\n * Browser client for smrt-chat's streaming chat route — the consume side of\n * the SSE contract `createChatStreamHandler` serves (see `chat-stream.ts`,\n * which owns the wire contract and exports the encode side).\n *\n * This module is BROWSER-SAFE and dependency-free: it must not import the\n * server runtime (models, services, tool loop) or any workspace package, so\n * a static site can ship it without dragging server code into the bundle. It\n * is exported under the dedicated `@happyvertical/smrt-chat/client` subpath.\n *\n * POST {endpoint}\n * Authorization: Bearer <sessionId> (SMRT bearer = session id)\n * Content-Type: application/json\n * Body: { \"messages\": ChatClientMessage[], \"session\": SmrtChatSession? }\n *\n * Response: text/event-stream, events as `data: <json>` lines:\n * { \"type\": \"token\", \"text\": \"...\" }\n * { \"type\": \"emotion\", \"name\": \"heart\" } (reserved; v1 engine forwards\n * the model's inline cue as tokens)\n * { \"type\": \"control\", \"command\": {...} } (#1921 host-page control lane;\n * parsed, no client hook yet)\n * { \"type\": \"done\", \"message\": ChatStreamMessage }\n * { \"type\": \"error\", \"error\": \"...\" }\n * plus `: heartbeat` comment lines every ~15s, which clients must ignore.\n *\n * The server always terminates a turn with a `done` or `error` frame; a clean\n * close without one means an intermediary cut the stream (proxy idle timeout)\n * and is surfaced as an error rather than an empty success.\n *\n * The widget-facing types below are STRUCTURALLY identical to\n * `@happyvertical/animation`'s chat contract (`ChatBackend`, `ChatMessage`,\n * `ChatStreamHandlers`, `ChatSendHandle`), so an instance drops straight into\n * `createHappyChat({ backend })` without this package depending on the widget\n * library. `client.contract.ts` pins the other seam under `pnpm typecheck`:\n * every `ChatStreamEvent` the server can emit is assignable to\n * `ChatClientStreamFrame`.\n */\n\n/** A rendered conversation message (the widget-side shape; all fields set). */\nexport interface ChatClientMessage {\n id: string;\n role: 'user' | 'assistant' | 'system';\n content: string;\n createdAt: string;\n}\n\n/** Streaming callbacks for one assistant reply. */\nexport interface ChatClientStreamHandlers {\n /** A chunk of assistant text (may be words or partial words). */\n onToken(text: string): void;\n /** An expression cue for the character (e.g. 'heart', 'wink'). */\n onEmotion?(name: string): void;\n /** The reply is complete; `message` is the final assembled message. */\n onDone(message: ChatClientMessage): void;\n onError(error: unknown): void;\n}\n\nexport interface ChatClientSendHandle {\n cancel(): void;\n}\n\n/**\n * A conversation backend. `send` receives the FULL message history (latest\n * user message last) and streams the assistant reply through `handlers`.\n */\nexport interface ChatClientBackend {\n send(\n messages: ChatClientMessage[],\n handlers: ChatClientStreamHandlers,\n ): ChatClientSendHandle;\n}\n\n/**\n * Conversation identity, mirroring `ChatStreamSession`\n * (`VoiceGatewayTurnMetadata`) so a server route can bind the turn to an\n * AgentSession/persona. Mirrored rather than imported to keep this module\n * free of server imports; `client.test.ts` asserts the shapes stay aligned.\n */\nexport interface SmrtChatSession {\n tenantId?: string;\n actorProfileId?: string;\n chatRoomId?: string;\n threadId?: string;\n agentSessionId?: string;\n personaId?: string;\n voiceSessionId?: string;\n}\n\nexport interface SmrtChatBackendOptions {\n /** Full URL of the streaming chat route. */\n endpoint: string;\n /** SMRT bearer token (the session id). Omit for cookie/same-origin auth. */\n token?: string;\n /**\n * fetch credentials mode (the `RequestCredentials` union, spelled out so\n * this module typechecks without the DOM lib). Cookie auth from a\n * cross-origin embed needs 'include' (pairs with the server's allow-listed\n * credentialed CORS, smrt #1861); the default is fetch's own 'same-origin'.\n */\n credentials?: 'omit' | 'same-origin' | 'include';\n /** Conversation identity (persona/agent-session binding). */\n session?: SmrtChatSession;\n fetchImpl?: typeof fetch;\n}\n\n/**\n * One parsed wire frame. Deliberately lenient where the client can degrade\n * (optional `message`/`error`) — and provably a superset of the server's\n * `ChatStreamEvent` union (compile-time lock in `client.test.ts`).\n */\nexport type ChatClientStreamFrame =\n | { type: 'token'; text: string }\n | { type: 'emotion'; name: string }\n | { type: 'control'; command: unknown }\n | {\n type: 'done';\n message?: {\n id?: string;\n role: ChatClientMessage['role'];\n content: string;\n createdAt?: string;\n };\n }\n | {\n type: 'error';\n error?: string;\n code?: string;\n unavailable?: ChatUnavailableStatus;\n };\n\n/**\n * Why AI is unavailable, as the server sends it (#4757): the shape of core's\n * `InferenceStatus`, repeated here so this module stays dependency-free.\n */\nexport interface ChatUnavailableStatus {\n available: false;\n mode: 'byo' | 'local' | 'hosted' | 'off';\n reason: 'off' | 'unconfigured' | 'entitlement' | 'capability';\n tier?: 'cheap' | 'good' | 'great' | 'best';\n}\n\nconst UNAVAILABLE_REASONS = [\n 'off',\n 'unconfigured',\n 'entitlement',\n 'capability',\n];\nconst INFERENCE_MODES = ['byo', 'local', 'hosted', 'off'];\nconst INFERENCE_TIERS = ['cheap', 'good', 'great', 'best'];\n\n/** The `code` of an unavailable answer. */\nexport const CHAT_UNAVAILABLE_CODE = 'ai_unavailable';\n\n/** The status in an `ai_unavailable` body or event, else `undefined`. */\nexport function readChatUnavailableStatus(\n body: unknown,\n): ChatUnavailableStatus | undefined {\n if (!body || typeof body !== 'object') return undefined;\n const record = body as { code?: unknown; unavailable?: unknown };\n if (record.code !== CHAT_UNAVAILABLE_CODE) return undefined;\n const status = record.unavailable as Record<string, unknown> | undefined;\n if (!status || !UNAVAILABLE_REASONS.includes(status.reason as string)) {\n return undefined;\n }\n const reason = status.reason as ChatUnavailableStatus['reason'];\n const mode =\n reason === 'off' || reason === 'unconfigured'\n ? 'off'\n : INFERENCE_MODES.includes(status.mode as string)\n ? (status.mode as ChatUnavailableStatus['mode'])\n : 'off';\n return {\n available: false,\n mode,\n reason,\n ...(INFERENCE_TIERS.includes(status.tier as string)\n ? { tier: status.tier as ChatUnavailableStatus['tier'] }\n : {}),\n };\n}\n\n/**\n * AI is off or not set up (#4757): the server answered `ai_unavailable`\n * (a 503, or an in-band stream `error` event). `unavailable` says why; a UI\n * renders \"AI is off\" with a settings link instead of a failure.\n */\nexport class ChatUnavailableError extends Error {\n readonly code = CHAT_UNAVAILABLE_CODE;\n constructor(\n message: string,\n readonly unavailable: ChatUnavailableStatus,\n ) {\n super(message);\n this.name = 'ChatUnavailableError';\n }\n}\n\n/** The unavailable error a body describes, else `undefined`. */\nfunction unavailableErrorFrom(body: unknown): ChatUnavailableError | undefined {\n const status = readChatUnavailableStatus(body);\n if (!status) return undefined;\n const message = (body as { error?: unknown }).error;\n return new ChatUnavailableError(\n typeof message === 'string' && message ? message : 'AI is unavailable.',\n status,\n );\n}\n\nlet counter = 0;\n\n/** Message id: crypto.randomUUID when available, counter fallback. */\nfunction messageId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c && typeof c.randomUUID === 'function') return c.randomUUID();\n counter += 1;\n return `msg-${Date.now()}-${counter}`;\n}\n\n/**\n * Pull `[emotion:name]` cues out of a reply, returning the clean text and the\n * last cue seen. The v1 streaming engine forwards the model's inline cue as\n * plain token text rather than an `emotion` frame, so the done message can\n * still carry it; strip it here so it never lands in the bubble/history, and\n * surface the emotion so the character still emotes.\n */\nfunction extractEmotion(text: string): {\n clean: string;\n emotion: string | null;\n} {\n let emotion: string | null = null;\n const clean = text\n .replace(/\\s*\\[emotion:(\\w+)\\]/g, (_, name: string) => {\n emotion = name;\n return '';\n })\n .trim();\n return { clean, emotion };\n}\n\n/**\n * Final message handed to `onDone`: keep the server's persisted identity\n * (id/createdAt) when present so a consumer reconciling with fetched room\n * history can match it, and fill honestly when the wire omitted it — the\n * wire shape has optional id/createdAt, the widget shape does not.\n */\nfunction finalizeMessage(\n message: Extract<ChatClientStreamFrame, { type: 'done' }>['message'],\n content: string,\n): ChatClientMessage {\n return {\n id: message?.id ?? messageId(),\n role: message?.role ?? 'assistant',\n content,\n createdAt: message?.createdAt ?? new Date().toISOString(),\n };\n}\n\n/**\n * SSE client for the streaming chat route (smrt-chat #1936). Structurally\n * implements `@happyvertical/animation`'s `ChatBackend`, so it plugs straight\n * into the floating chat widget.\n */\nexport class SmrtChatBackend implements ChatClientBackend {\n private options: SmrtChatBackendOptions;\n\n constructor(options: SmrtChatBackendOptions) {\n this.options = options;\n }\n\n send(\n messages: ChatClientMessage[],\n handlers: ChatClientStreamHandlers,\n ): ChatClientSendHandle {\n const controller = new AbortController();\n const fetchImpl = this.options.fetchImpl ?? fetch;\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n };\n if (this.options.token) {\n headers.authorization = `Bearer ${this.options.token}`;\n }\n\n (async () => {\n const response = await fetchImpl(this.options.endpoint, {\n method: 'POST',\n headers,\n credentials: this.options.credentials,\n body: JSON.stringify({\n messages,\n session: this.options.session,\n }),\n signal: controller.signal,\n });\n if (!response.ok || !response.body) {\n // The handler renders structured errors ({error, code}) — carry the\n // body so auth failures are distinguishable from bad requests.\n let text = '';\n try {\n text = await response.text();\n } catch {\n /* body unreadable — status alone will have to do */\n }\n const detail = text.slice(0, 200);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n /* not JSON */\n }\n const unavailable = unavailableErrorFrom(parsed);\n if (unavailable) throw unavailable;\n throw new Error(\n `[smrt-chat] chat endpoint responded ${response.status}${\n detail ? `: ${detail}` : ''\n }`,\n );\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n let assembled = '';\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let newline = buffer.indexOf('\\n');\n while (newline !== -1) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n newline = buffer.indexOf('\\n');\n if (!line.startsWith('data:')) continue; // blank + `: heartbeat`\n const event = JSON.parse(line.slice(5)) as ChatClientStreamFrame;\n if (event.type === 'token' && event.text) {\n assembled += event.text;\n handlers.onToken(event.text);\n } else if (event.type === 'emotion' && event.name) {\n handlers.onEmotion?.(event.name);\n } else if (event.type === 'control') {\n // #1921 host-page control lane — recognized so the union stays\n // honest; no client hook yet (the widget executes controls via\n // its own registry when that wiring lands).\n } else if (event.type === 'error') {\n handlers.onError(\n unavailableErrorFrom(event) ??\n new Error(event.error ?? '[smrt-chat] chat stream error'),\n );\n // The turn is settled but the server may keep sending (heartbeats,\n // late frames) — release the connection instead of leaving the\n // stream open until GC.\n reader.cancel().catch(() => {\n /* stream already closed — nothing to release */\n });\n return;\n } else if (event.type === 'done') {\n const raw = event.message?.content ?? assembled;\n const { clean, emotion } = extractEmotion(raw);\n if (emotion) handlers.onEmotion?.(emotion);\n handlers.onDone(finalizeMessage(event.message, clean));\n reader.cancel().catch(() => {\n /* stream already closed — nothing to release */\n });\n return;\n }\n }\n }\n // The server always terminates with done or error; a clean close\n // without one means an intermediary cut the stream. Never fabricate\n // a successful (possibly empty) reply out of a truncation.\n throw new Error('[smrt-chat] chat stream ended without a done frame');\n })().catch((error) => {\n if (!controller.signal.aborted) handlers.onError(error);\n });\n\n return { cancel: () => controller.abort() };\n }\n}\n"],"mappings":";AA6IA,IAAM,sBAAsB;CAC1B;CACA;CACA;CACA;AACF;AACA,IAAM,kBAAkB;CAAC;CAAO;CAAS;CAAU;AAAK;AACxD,IAAM,kBAAkB;CAAC;CAAS;CAAQ;CAAS;AAAM;AAGlD,IAAM,wBAAwB;AAG9B,SAAS,0BACd,MACmC;CACnC,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU,OAAO,KAAA;CAC9C,MAAM,SAAS;CACf,IAAI,OAAO,SAAA,kBAAgC,OAAO,KAAA;CAClD,MAAM,SAAS,OAAO;CACtB,IAAI,CAAC,UAAU,CAAC,oBAAoB,SAAS,OAAO,MAAgB,GAClE;CAEF,MAAM,SAAS,OAAO;CAOtB,OAAO;EACL,WAAW;EACX,MAPA,WAAW,SAAS,WAAW,iBAC3B,QACA,gBAAgB,SAAS,OAAO,IAAc,IAC3C,OAAO,OACR;EAIN;EACA,GAAI,gBAAgB,SAAS,OAAO,IAAc,IAC9C,EAAE,MAAM,OAAO,KAAsC,IACrD,CAAC;CACP;AACF;AAOO,IAAM,uBAAN,cAAmC,MAAM;CAE9C,YACE,SACS,aACT;EACA,MAAM,OAAO;EAFJ,KAAA,cAAA;EAGT,KAAK,OAAO;CACd;CAJW;CAHF,OAAO;AAQlB;AAGA,SAAS,qBAAqB,MAAiD;CAC7E,MAAM,SAAS,0BAA0B,IAAI;CAC7C,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,MAAM,UAAW,KAA6B;CAC9C,OAAO,IAAI,qBACT,OAAO,YAAY,YAAY,UAAU,UAAU,sBACnD,MACF;AACF;AAEA,IAAI,UAAU;AAGd,SAAS,YAAoB;CAC3B,MAAM,IAAK,WAA0D;CACrE,IAAI,KAAK,OAAO,EAAE,eAAe,YAA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,CAAE,OAAO,UAAU;GACpB,IAAI,CAAC,WAAW,OAAO,SAAS,SAAS,QAAQ,KAAK;EACxD,CAAC;EAED,OAAO,EAAE,cAAc,WAAW,MAAM,EAAE;CAC5C;AACF"}
package/dist/index.d.ts CHANGED
@@ -40,6 +40,7 @@
40
40
  * @packageDocumentation
41
41
  */
42
42
  import './__smrt-register__.js';
43
+ export { CHAT_AI_UNAVAILABLE_CODE, type ChatUnavailableBody, chatUnavailableBody, chatUnconfiguredBody, } from './ai-unavailable.js';
43
44
  export { ASSISTANT_TURN_GENERIC_ERROR, type AssistantContinuationStore, type AssistantTurnAuthor, type AssistantTurnContinuation, type AssistantTurnErrorLogger, type AssistantTurnOptions, type AssistantTurnResult, type AssistantTurnState, AssistantTurnUserError, type AuthoredToolReply, CONTINUATION_CLAIM_TTL_MS, type ContinuationSessionLike, createAssistantTurnResponse, createMemoryContinuationStore, createSessionContinuationStore, DEFAULT_ASSISTANT_TURN_HEARTBEAT_MS, DEFAULT_CONTINUATION_TTL_MS, type ProviderErrorFallback, runAssistantTurn, SESSION_CONTINUATIONS_FIELD, } from './assistant-turn.js';
44
45
  export * from './assistant-turn-events.js';
45
46
  export { acceptAppliedChange, type CaptureChatFeedbackOptions, type ChatFeedbackBase, type ChatFeedbackPersona, type ChatFeedbackResult, captureChatFeedback, correctResponse, rateResponse, rejectAppliedChange, thumbsDown, thumbsUp, } from './chat-feedback.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAKH,OAAO,wBAAwB,CAAC;AAehC,OAAO,EACL,4BAA4B,EAC5B,KAAK,0BAA0B,EAC/B,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAC9B,KAAK,wBAAwB,EAC7B,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,EACvB,sBAAsB,EAC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,WAAW,EACX,wCAAwC,EACxC,8BAA8B,EAC9B,sBAAsB,EACtB,+BAA+B,EAC/B,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,EACpC,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACtB,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,SAAS,EACd,wBAAwB,EACxB,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AAExB,YAAY,EACV,mBAAmB,EACnB,kBAAkB,EAClB,kBAAkB,EAClB,eAAe,EACf,wBAAwB,EACxB,eAAe,EACf,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,EACrB,mBAAmB,EACnB,eAAe,EACf,cAAc,EACd,YAAY,EACZ,iBAAiB,EACjB,YAAY,EACZ,uBAAuB,EACvB,sBAAsB,EACtB,mBAAmB,EACnB,kBAAkB,GACnB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,EACL,wBAAwB,EACxB,KAAK,6BAA6B,EAClC,sBAAsB,EACtB,6BAA6B,EAC7B,KAAK,6BAA6B,EAClC,sBAAsB,EACtB,6BAA6B,EAC7B,sBAAsB,EACtB,KAAK,8BAA8B,EACnC,2BAA2B,EAC3B,iBAAiB,EACjB,uBAAuB,EACvB,KAAK,8BAA8B,EACnC,KAAK,wBAAwB,EAC7B,KAAK,uBAAuB,EAC5B,KAAK,wBAAwB,EAC7B,KAAK,gCAAgC,EACrC,6BAA6B,EAC7B,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,YAAY,CAAC"}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { c as ChatThread, d as ChatParticipant, f as ChatMessage, i as clientRequestMessageId, l as ChatRoom, n as ChatService, o as VoiceSessionCollection, p as AgentSession, s as VoiceSession, t as ChatClientRequestConflictError, u as ChatReaction } from "./chunks/ChatService-BGBAqmZq.js";
2
- import { $ as isFallbackReply, A as DEFAULT_EMPTY_ANSWER_FALLBACK, B as MAX_SERVER_TOOL_OBSERVATION_CHARS, C as DEFAULT_CONTINUATION_TTL_MS, D as createSessionContinuationStore, E as createMemoryContinuationStore, F as MAX_CLIENT_TOOLS, G as TOOL_CALL_DEDUPED_REJECTED_NOTE, H as MAX_TOOL_LOOP_REASONING_CHARS, I as MAX_CLIENT_TOOL_RESULT_CHARS, J as TOOL_LOOP_REPEATED_CALLS_INSTRUCTION, K as TOOL_EXECUTION_ERROR_HINT, L as MAX_CLIENT_TOOL_SCHEMA_BYTES, M as DEFAULT_MAX_STEPS, N as FALLBACK_HISTORY_PLACEHOLDER, O as runAssistantTurn, P as FALLBACK_REPLY_METADATA_KEY, Q as invokeManifestTool, R as MAX_DEDUPED_CALLS_PER_TURN, S as DEFAULT_ASSISTANT_TURN_HEARTBEAT_MS, T as createAssistantTurnResponse, U as SERVER_TOOL_OBSERVATION_TRUNCATED_MARKER, V as MAX_TOOL_FAILURE_ARGS_CHARS, W as TOOL_CALL_DEDUPED_NOTE, X as buildManifestToolCatalog, Y as appendClientToolResults, Z as classifyToolError, _ as resolveConversationInstructions, a as DEFAULT_CHAT_STREAM_HEARTBEAT_MS, at as sanitizeClientToolDeclarations, b as AssistantTurnUserError, c as createChatStreamHandler, ct as RUNTIME_REPORT_DEFINE_FUNCTION_NAME, d as bindPersonaToSession, dt as RUNTIME_REPORT_LIST_TOOL_SLUG, et as manifestToolToAITool, f as conversationPersonaFromAgentPersona, ft as RUNTIME_REPORT_RUN_FUNCTION_NAME, g as recallPersonaMemory, gt as createRuntimeReportTools, h as principalBindingFor, ht as RUNTIME_REPORT_SOURCES_TOOL_SLUG, i as ChatStreamUnauthorizedError, it as runToolLoop, j as DEFAULT_MAX_REPEATED_CALLS, k as CLIENT_TOOL_RESULT_GUIDANCE, l as encodeChatStreamEvent, lt as RUNTIME_REPORT_DEFINE_TOOL_SLUG, m as formatRecalledMemory, mt as RUNTIME_REPORT_SOURCES_FUNCTION_NAME, n as ChatStreamBadRequestError, nt as replyMetadataFor, o as MAX_CHAT_STREAM_CONTENT_LENGTH, ot as toolFailureAuditMetadata, p as conversationPersonaFromResolved, pt as RUNTIME_REPORT_RUN_TOOL_SLUG, q as TOOL_LOOP_ANSWER_NOW_INSTRUCTION, r as ChatStreamError, rt as resolveTurnReply, s as MAX_CHAT_STREAM_MESSAGES, st as toolFailureRecord, t as CHAT_STREAM_TIMEOUT_ERROR, tt as replyContentFor, u as runChatConversationStream, ut as RUNTIME_REPORT_LIST_FUNCTION_NAME, v as runPersonaConversationTurn, w as SESSION_CONTINUATIONS_FIELD, x as CONTINUATION_CLAIM_TTL_MS, y as ASSISTANT_TURN_GENERIC_ERROR, z as MAX_REPEATED_CALLS_LIMIT } from "./chunks/chat-stream-BEQxcBwW.js";
2
+ import { $ as isFallbackReply, A as DEFAULT_EMPTY_ANSWER_FALLBACK, B as MAX_SERVER_TOOL_OBSERVATION_CHARS, C as DEFAULT_CONTINUATION_TTL_MS, D as createSessionContinuationStore, E as createMemoryContinuationStore, F as MAX_CLIENT_TOOLS, G as TOOL_CALL_DEDUPED_REJECTED_NOTE, H as MAX_TOOL_LOOP_REASONING_CHARS, I as MAX_CLIENT_TOOL_RESULT_CHARS, J as TOOL_LOOP_REPEATED_CALLS_INSTRUCTION, K as TOOL_EXECUTION_ERROR_HINT, L as MAX_CLIENT_TOOL_SCHEMA_BYTES, M as DEFAULT_MAX_STEPS, N as FALLBACK_HISTORY_PLACEHOLDER, O as runAssistantTurn, P as FALLBACK_REPLY_METADATA_KEY, Q as invokeManifestTool, R as MAX_DEDUPED_CALLS_PER_TURN, S as DEFAULT_ASSISTANT_TURN_HEARTBEAT_MS, T as createAssistantTurnResponse, U as SERVER_TOOL_OBSERVATION_TRUNCATED_MARKER, V as MAX_TOOL_FAILURE_ARGS_CHARS, W as TOOL_CALL_DEDUPED_NOTE, X as buildManifestToolCatalog, Y as appendClientToolResults, Z as classifyToolError, _ as resolveConversationInstructions, _t as CHAT_AI_UNAVAILABLE_CODE, a as DEFAULT_CHAT_STREAM_HEARTBEAT_MS, at as sanitizeClientToolDeclarations, b as AssistantTurnUserError, c as createChatStreamHandler, ct as RUNTIME_REPORT_DEFINE_FUNCTION_NAME, d as bindPersonaToSession, dt as RUNTIME_REPORT_LIST_TOOL_SLUG, et as manifestToolToAITool, f as conversationPersonaFromAgentPersona, ft as RUNTIME_REPORT_RUN_FUNCTION_NAME, g as recallPersonaMemory, gt as createRuntimeReportTools, h as principalBindingFor, ht as RUNTIME_REPORT_SOURCES_TOOL_SLUG, i as ChatStreamUnauthorizedError, it as runToolLoop, j as DEFAULT_MAX_REPEATED_CALLS, k as CLIENT_TOOL_RESULT_GUIDANCE, l as encodeChatStreamEvent, lt as RUNTIME_REPORT_DEFINE_TOOL_SLUG, m as formatRecalledMemory, mt as RUNTIME_REPORT_SOURCES_FUNCTION_NAME, n as ChatStreamBadRequestError, nt as replyMetadataFor, o as MAX_CHAT_STREAM_CONTENT_LENGTH, ot as toolFailureAuditMetadata, p as conversationPersonaFromResolved, pt as RUNTIME_REPORT_RUN_TOOL_SLUG, q as TOOL_LOOP_ANSWER_NOW_INSTRUCTION, r as ChatStreamError, rt as resolveTurnReply, s as MAX_CHAT_STREAM_MESSAGES, st as toolFailureRecord, t as CHAT_STREAM_TIMEOUT_ERROR, tt as replyContentFor, u as runChatConversationStream, ut as RUNTIME_REPORT_LIST_FUNCTION_NAME, v as runPersonaConversationTurn, vt as chatUnavailableBody, w as SESSION_CONTINUATIONS_FIELD, x as CONTINUATION_CLAIM_TTL_MS, y as ASSISTANT_TURN_GENERIC_ERROR, yt as chatUnconfiguredBody, z as MAX_REPEATED_CALLS_LIMIT } from "./chunks/chat-stream-FDF9I30Z.js";
3
3
  import { i as matchesToolAllowList, n as encodeAssistantTurnEvent, r as readAssistantTurnStream, t as AssistantTurnStreamError } from "./chunks/assistant-turn-events-BbZUf-Ju.js";
4
4
  import { a as createServerDataSurfaceBridge, i as createDataSurfaceCommandBridge, n as DEFAULT_DATA_SURFACE_BRIDGE_TTL_MS, r as createDataSurfaceBridge, t as DATA_SURFACE_BRIDGE_VERSION } from "./chunks/data-surface-bridge-BJomMxjS.js";
5
5
  import { HELPER_CLEARED_PREFERENCES, HELPER_PREFERENCES_VERSION, helperPreferenceFields, isHelperClearedPreferences, parseHelperPreferences } from "./helper-preferences.js";
@@ -1302,6 +1302,6 @@ function jsonResponse(body, status) {
1302
1302
  });
1303
1303
  }
1304
1304
  //#endregion
1305
- export { ASSISTANT_TURN_GENERIC_ERROR, AgentSession, AssistantRecipe, AssistantTurnStreamError, AssistantTurnUserError, CHAT_MODULE_META, CHAT_STREAM_TIMEOUT_ERROR, CHAT_UI_SLOTS, CLIENT_TOOL_RESULT_GUIDANCE, CONTINUATION_CLAIM_TTL_MS, ChatClientRequestConflictError, ChatMessage, ChatParticipant, ChatReaction, ChatRoom, ChatRoomsRecipe, ChatService, ChatStreamBadRequestError, ChatStreamError, ChatStreamUnauthorizedError, ChatThread, DATA_DISCOVER_FUNCTION_NAME, DATA_DISCOVER_TOOL_SLUG, DATA_INSPECT_FUNCTION_NAME, DATA_INSPECT_TOOL_SLUG, DATA_QUERY_FUNCTION_NAME, DATA_QUERY_TOOL_SLUG, DATA_SURFACE_BRIDGE_VERSION, DEFAULT_ASSISTANT_TURN_HEARTBEAT_MS, DEFAULT_CHAT_STREAM_HEARTBEAT_MS, DEFAULT_CONTINUATION_TTL_MS, DEFAULT_DATA_SURFACE_BRIDGE_TTL_MS, DEFAULT_DATA_SURFACE_DEADLINE_MS, DEFAULT_EMPTY_ANSWER_FALLBACK, DEFAULT_MAX_REPEATED_CALLS, DEFAULT_MAX_STEPS, DataSurfaceActionDeniedError, DataSurfaceDeadlineError, DataSurfaceDeniedError, DataSurfaceQueryError, DataSurfaceRequestError, DataSurfaceResultOrderError, FALLBACK_HISTORY_PLACEHOLDER, FALLBACK_REPLY_METADATA_KEY, HELPER_CLEARED_PREFERENCES, HELPER_PREFERENCES_VERSION, HelperPreferencesAuthorizationError, HelperPreferencesService, HelperPreferencesValidationError, HelperProfileStoreError, MAX_CHAT_STREAM_CONTENT_LENGTH, MAX_CHAT_STREAM_MESSAGES, MAX_CLIENT_TOOLS, MAX_CLIENT_TOOL_RESULT_CHARS, MAX_CLIENT_TOOL_SCHEMA_BYTES, MAX_DATA_SURFACE_DEADLINE_MS, MAX_DEDUPED_CALLS_PER_TURN, MAX_REPEATED_CALLS_LIMIT, MAX_SERVER_TOOL_OBSERVATION_CHARS, MAX_TOOL_FAILURE_ARGS_CHARS, MAX_TOOL_LOOP_REASONING_CHARS, MAX_VOICE_GATEWAY_TEXT_LENGTH, OVERVIEW_APPLY_FUNCTION_NAME, OVERVIEW_APPLY_TOOL_SLUG, OVERVIEW_DESCRIBE_FUNCTION_NAME, OVERVIEW_DESCRIBE_TOOL_SLUG, OVERVIEW_TOOL_MAX_OPERATIONS, OVERVIEW_UNDO_FUNCTION_NAME, OVERVIEW_UNDO_TOOL_SLUG, OverviewToolError, ProfileHelperPreferenceStore, RUNTIME_REPORT_DEFINE_FUNCTION_NAME, RUNTIME_REPORT_DEFINE_TOOL_SLUG, RUNTIME_REPORT_LIST_FUNCTION_NAME, RUNTIME_REPORT_LIST_TOOL_SLUG, RUNTIME_REPORT_RUN_FUNCTION_NAME, RUNTIME_REPORT_RUN_TOOL_SLUG, RUNTIME_REPORT_SOURCES_FUNCTION_NAME, RUNTIME_REPORT_SOURCES_TOOL_SLUG, SERVER_TOOL_OBSERVATION_TRUNCATED_MARKER, SESSION_CONTINUATIONS_FIELD, SMRT_CHAT_VOICE_TARGET, TOOL_CALL_DEDUPED_NOTE, TOOL_CALL_DEDUPED_REJECTED_NOTE, TOOL_EXECUTION_ERROR_HINT, TOOL_LOOP_ANSWER_NOW_INSTRUCTION, TOOL_LOOP_REPEATED_CALLS_INSTRUCTION, VoiceGatewayBadRequestError, VoiceGatewayError, VoiceGatewayReplayError, VoiceGatewayTurn, VoiceGatewayUnauthorizedError, VoiceSession, VoiceSessionExpiredError, VoiceSessionRejectedError, acceptAppliedChange, appendClientToolResults, assertVoiceGatewayBearer, bindPersonaToSession, buildManifestToolCatalog, captureChatFeedback, classifyToolError, clientRequestMessageId, conversationPersonaFromAgentPersona, conversationPersonaFromResolved, correctResponse, createAssistantTurnResponse, createChatStreamHandler, createDataSurfaceBridge, createDataSurfaceCommandBridge, createDataSurfaceQueryFingerprint, createDataSurfaceTools, createHelperProfilePreferenceStore, createMemoryContinuationStore, createMemoryOverviewUndoStore, createOverviewTools, createRuntimeReportTools, createServerDataSurfaceBridge, createSessionContinuationStore, createVoiceChatSession, createVoiceGatewayTurnHandler, defaultOverviewUndoStore, encodeAssistantTurnEvent, encodeChatStreamEvent, formatOverviewIssues, formatRecalledMemory, handleVoiceGatewayTurn, helperPreferenceFields, invokeManifestTool, isFallbackReply, isHelperClearedPreferences, manifestToolToAITool, matchesToolAllowList, normalizeDataSurfaceRowCountHint, parseHelperPreferences, principalBindingFor, rateResponse, readAssistantTurnStream, recallPersonaMemory, rejectAppliedChange, replyContentFor, replyMetadataFor, resolveConversationInstructions, resolveTurnReply, runAssistantTurn, runChatConversationStream, runPersonaConversationTurn, runToolLoop, sanitizeClientToolDeclarations, thumbsDown, thumbsUp, toolFailureAuditMetadata, toolFailureRecord };
1305
+ export { ASSISTANT_TURN_GENERIC_ERROR, AgentSession, AssistantRecipe, AssistantTurnStreamError, AssistantTurnUserError, CHAT_AI_UNAVAILABLE_CODE, CHAT_MODULE_META, CHAT_STREAM_TIMEOUT_ERROR, CHAT_UI_SLOTS, CLIENT_TOOL_RESULT_GUIDANCE, CONTINUATION_CLAIM_TTL_MS, ChatClientRequestConflictError, ChatMessage, ChatParticipant, ChatReaction, ChatRoom, ChatRoomsRecipe, ChatService, ChatStreamBadRequestError, ChatStreamError, ChatStreamUnauthorizedError, ChatThread, DATA_DISCOVER_FUNCTION_NAME, DATA_DISCOVER_TOOL_SLUG, DATA_INSPECT_FUNCTION_NAME, DATA_INSPECT_TOOL_SLUG, DATA_QUERY_FUNCTION_NAME, DATA_QUERY_TOOL_SLUG, DATA_SURFACE_BRIDGE_VERSION, DEFAULT_ASSISTANT_TURN_HEARTBEAT_MS, DEFAULT_CHAT_STREAM_HEARTBEAT_MS, DEFAULT_CONTINUATION_TTL_MS, DEFAULT_DATA_SURFACE_BRIDGE_TTL_MS, DEFAULT_DATA_SURFACE_DEADLINE_MS, DEFAULT_EMPTY_ANSWER_FALLBACK, DEFAULT_MAX_REPEATED_CALLS, DEFAULT_MAX_STEPS, DataSurfaceActionDeniedError, DataSurfaceDeadlineError, DataSurfaceDeniedError, DataSurfaceQueryError, DataSurfaceRequestError, DataSurfaceResultOrderError, FALLBACK_HISTORY_PLACEHOLDER, FALLBACK_REPLY_METADATA_KEY, HELPER_CLEARED_PREFERENCES, HELPER_PREFERENCES_VERSION, HelperPreferencesAuthorizationError, HelperPreferencesService, HelperPreferencesValidationError, HelperProfileStoreError, MAX_CHAT_STREAM_CONTENT_LENGTH, MAX_CHAT_STREAM_MESSAGES, MAX_CLIENT_TOOLS, MAX_CLIENT_TOOL_RESULT_CHARS, MAX_CLIENT_TOOL_SCHEMA_BYTES, MAX_DATA_SURFACE_DEADLINE_MS, MAX_DEDUPED_CALLS_PER_TURN, MAX_REPEATED_CALLS_LIMIT, MAX_SERVER_TOOL_OBSERVATION_CHARS, MAX_TOOL_FAILURE_ARGS_CHARS, MAX_TOOL_LOOP_REASONING_CHARS, MAX_VOICE_GATEWAY_TEXT_LENGTH, OVERVIEW_APPLY_FUNCTION_NAME, OVERVIEW_APPLY_TOOL_SLUG, OVERVIEW_DESCRIBE_FUNCTION_NAME, OVERVIEW_DESCRIBE_TOOL_SLUG, OVERVIEW_TOOL_MAX_OPERATIONS, OVERVIEW_UNDO_FUNCTION_NAME, OVERVIEW_UNDO_TOOL_SLUG, OverviewToolError, ProfileHelperPreferenceStore, RUNTIME_REPORT_DEFINE_FUNCTION_NAME, RUNTIME_REPORT_DEFINE_TOOL_SLUG, RUNTIME_REPORT_LIST_FUNCTION_NAME, RUNTIME_REPORT_LIST_TOOL_SLUG, RUNTIME_REPORT_RUN_FUNCTION_NAME, RUNTIME_REPORT_RUN_TOOL_SLUG, RUNTIME_REPORT_SOURCES_FUNCTION_NAME, RUNTIME_REPORT_SOURCES_TOOL_SLUG, SERVER_TOOL_OBSERVATION_TRUNCATED_MARKER, SESSION_CONTINUATIONS_FIELD, SMRT_CHAT_VOICE_TARGET, TOOL_CALL_DEDUPED_NOTE, TOOL_CALL_DEDUPED_REJECTED_NOTE, TOOL_EXECUTION_ERROR_HINT, TOOL_LOOP_ANSWER_NOW_INSTRUCTION, TOOL_LOOP_REPEATED_CALLS_INSTRUCTION, VoiceGatewayBadRequestError, VoiceGatewayError, VoiceGatewayReplayError, VoiceGatewayTurn, VoiceGatewayUnauthorizedError, VoiceSession, VoiceSessionExpiredError, VoiceSessionRejectedError, acceptAppliedChange, appendClientToolResults, assertVoiceGatewayBearer, bindPersonaToSession, buildManifestToolCatalog, captureChatFeedback, chatUnavailableBody, chatUnconfiguredBody, classifyToolError, clientRequestMessageId, conversationPersonaFromAgentPersona, conversationPersonaFromResolved, correctResponse, createAssistantTurnResponse, createChatStreamHandler, createDataSurfaceBridge, createDataSurfaceCommandBridge, createDataSurfaceQueryFingerprint, createDataSurfaceTools, createHelperProfilePreferenceStore, createMemoryContinuationStore, createMemoryOverviewUndoStore, createOverviewTools, createRuntimeReportTools, createServerDataSurfaceBridge, createSessionContinuationStore, createVoiceChatSession, createVoiceGatewayTurnHandler, defaultOverviewUndoStore, encodeAssistantTurnEvent, encodeChatStreamEvent, formatOverviewIssues, formatRecalledMemory, handleVoiceGatewayTurn, helperPreferenceFields, invokeManifestTool, isFallbackReply, isHelperClearedPreferences, manifestToolToAITool, matchesToolAllowList, normalizeDataSurfaceRowCountHint, parseHelperPreferences, principalBindingFor, rateResponse, readAssistantTurnStream, recallPersonaMemory, rejectAppliedChange, replyContentFor, replyMetadataFor, resolveConversationInstructions, resolveTurnReply, runAssistantTurn, runChatConversationStream, runPersonaConversationTurn, runToolLoop, sanitizeClientToolDeclarations, thumbsDown, thumbsUp, toolFailureAuditMetadata, toolFailureRecord };
1306
1306
 
1307
1307
  //# sourceMappingURL=index.js.map
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-chat",
5
- "packageVersion": "0.60.14",
5
+ "packageVersion": "0.60.15",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-chat:AgentSessionCollection": {
8
8
  "name": "agentsessioncollection",
@@ -3,17 +3,18 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-chat",
6
- "packageVersion": "0.60.14",
6
+ "packageVersion": "0.60.15",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "f26d0698aeb152e309fe9a51f523f55416fc120f861755cc27b32a5b642707b7",
11
- "packageJson": "f162321ba774b1cd51ca62368ee13a308fe15c0084263c4456bbe443d310ed7f",
12
- "agents": "44b54fd3a94f6f255b66032c138c81f120d4d8ba9fe219b45c5d926b3f22fcb3",
10
+ "manifest": "1d40efcd4dde5432ead5a01591bae2a8e700e43b44da0e1958f4cb48e38d0ea1",
11
+ "packageJson": "dd5a7cdc0d7d00a11af14f1a302d51c3ee5a7c3d440337a4d1493d2af0e4699e",
12
+ "agents": "ee0c14eaf728ecdb3379451fe8b8172be6a2617092418128744a48d3a72ee176",
13
13
  "moduleDoc:agents/dev-workbench.md": "f07a428519e8cca4a46371da0a3b33b9c8d3102f1d9056e4c8efba3c0b702048",
14
14
  "moduleDoc:agents/overview-tools.md": "752a4afb6b57a2e9224f3c65a98b0deb23cda87371f01ac0566f0887e9bb12da",
15
15
  "moduleDoc:agents/tool-loop.md": "81ec1de9c5fac66b526ae8b2feeda8f33f1916cff19c4060f09989ce79b2acc1",
16
16
  "moduleDoc:agents/token-streaming.md": "e92a28a8702d111a3751a86b8cdff30cb5146cc115fed86c227402bef1c683fd",
17
+ "moduleDoc:agents/ai-unavailable.md": "e12b175c932411c4445b59ee8144ae06cc962c430960b6c5a26e0002f2d15369",
17
18
  "moduleDoc:agents/assistant-questions.md": "a0371870b3bc99e313d8287912208f3e315bab7dc4ee138214895031ae79a5b0",
18
19
  "moduleDoc:agents/recipes.md": "89c2c86e4e26cea9ba10d917f8ad71c23a71d4fd8eaacf638a6cd252e2376c07",
19
20
  "agentSurface:src/routes/chat-dev.intents.ts": "ff8f7c19c7eb6e841a08f03c97773c53092ed208004666bfed372bd1ad456b35"
@@ -4513,7 +4514,7 @@
4513
4514
  "polymorphicAssociations": 0,
4514
4515
  "uuidColumns": 78
4515
4516
  },
4516
- "agentDoc": "# @happyvertical/smrt-chat\n\nChat rooms, threads, and agent sessions with app-controlled tool whitelisting.\n\n## Dev Server\n\n`pnpm --dir packages/chat dev` runs a package-local SvelteKit workbench. The root\nroute separates **Character setup** and **Chat dev** into tabs; switching tabs\nretains the current character rig and chat state. The chat tab is an interactive\nsurface with a dev-only `/api/dev-chat` endpoint:\nit uses `@happyvertical/ai` when local provider credentials are present and\nfalls back to a deterministic local assistant otherwise. `/api/dev-chat-stream`\nis its SSE companion (#1936) — the same provider/local-fallback resolution wired\nthrough `createChatStreamHandler` in plain mode, so an embedded `SmrtChatBackend`\nclient can exercise token streaming locally. `/previews` hosts the shared\ncomponent playground entries from `src/svelte/playground.ts`.\n\nThe root route also drives the **browser inference path**\n(`@happyvertical/smrt-web/ai`: bitgpu, WebLLM, and route backends composed by\n`createInferencePath`) and an **agent-addressable draft form** (`useViewIntent`\nover `src/routes/chat-dev.intents.ts`, #2588). Their dev-config dependencies\n(static optional-peer imports, `workspace-aliases.js` prefix rules, the theme\nstylesheet import) and the stage→apply tool-call gotchas are in\n[agents/dev-workbench.md](agents/dev-workbench.md).\n\nDev-only voice and opt-in local character persistence are documented in\n[agents/dev-workbench.md](agents/dev-workbench.md#voice-and-local-character-persistence).\nThese endpoints are loopback-only demos; production hosts supply authenticated\nprincipals, tenancy, and authorization to the owning services.\n\n## Models\n\nAll seven models expose only generated REST/MCP `list`/`get`; structural tests\ncheck the registry for accidental mutating operations. Writes go through\nmembership/owner-checked `ChatService` or the binding-checked voice adapter.\n\n`ChatService` is a closed facade. Its collections and security-sensitive\nhelpers use ES `#private` fields/methods (TypeScript `private` is erased).\nCollection classes are not exported from the package index. The agent-reply\nbridge is a Symbol-keyed static accessible through a non-exported symbol held\nby the module-local `sendAgentReply` function.\n\n- **ChatRoom**: `roomType` (public/private/dm/agent), `status`, `topic`, `maxParticipants`, `lastMessageAt`. Tenant-scoped (required).\n- **ChatMessage**: shared by users + agents. `role` (user/assistant/system/tool), `messageType` (text/system/action/file/tool_call/tool_result), `toolCallData` JSON. Unified model — no separate agent message type. Tenant-scoped (required).\n- **ChatParticipant**: `role` (owner/admin/member/viewer), `onlineStatus`, `lastReadMessageId`, `isMuted`. Tenant-scoped (required).\n- **ChatThread**: `rootMessageId`, `isResolved`, `messageCount`. Created via `ChatService.startThread()` (member-checked). Tenant-scoped (required).\n- **ChatReaction**: `messageId`, `profileId`, `emoji`. Added/removed via `ChatService.addReaction()`/`removeReaction()` (member-checked, self-keyed). Tenant-scoped (required).\n- **AgentSession**: `agentId` (application slug, string ref, not FK), `agentProfileId` (nullable `crossPackageRef` to `Profile` — the `bot` profile the agent AUTHORS as, #2995), `allowedTools` (JSON string array), `sessionContext` (JSON, sensitive), `systemPrompt`, limits (`maxTokens`/`maxMessages`/`expiresAt`). Optional tenancy.\n- **VoiceSession**: short-lived voice-gateway binding over `(tenant, actorProfileId, personaId, room/thread/agentSession)` plus a persona snapshot, gateway `session_id`, expiry, replay tracking, and metadata. Tenant-scoped (required). Generated surface is read-only; creation and turns go through `createVoiceChatSession()` / `handleVoiceGatewayTurn()`.\n\n## ChatService\n\nPublic writes take server-supplied `actorProfileId`; never trust a request's\n`senderProfileId`, `role`, owner id, or participant id as authority.\n\n| Operation | Authorization and behavior |\n|---|---|\n| `sendMessage()` | Room member; authors as actor with `role: 'user'`; no public membership bypass |\n| `createRoom()` | Actor becomes owner |\n| `startThread()` | Member; optional root message bound to room and tenant |\n| `addParticipant()` / `removeParticipant()` | Owner/admin; self-leave allowed |\n| `updateRoom()` | Owner/admin |\n| `addReaction()` / `removeReaction()` | Member; self-keyed |\n| `getOrCreateDM()` | Actor must be a DM participant |\n| `createAgentSession()` | Actor becomes session participant; existing-session lookup tenant-bound; optional `sessionKey` isolates conversation subjects |\n| `updateAgentSessionConfig()` | Owner; mandatory tenant-bound lookup |\n| `sendAgentUserMessage()` | Actor must be session participant; authored as participant |\n\nRead facade: `getAgentSession({agentSessionId, tenantId})`,\n`findActiveAgentSessions({tenantId, agentId, participantProfileId})`, and\n`getThread({threadId, tenantId})` are tenant-bound; consumers still check\nownership/context. `listRoomThreads({roomId, actorProfileId, tenantId})`,\n`getThreadMessages({threadId, actorProfileId, tenantId, limit?})` (chronological),\n`getRoomMessages({roomId, actorProfileId, tenantId})`, and\n`getRoomForMember(roomId, actorProfileId, tenantId)` additionally require\nmembership of the server-supplied actor, not a caller-selected subject.\n\nTrusted agent runtime imports `sendAgentReply(service, params)` only from\n`@happyvertical/smrt-chat/internal/agent-runtime`. It is not a `ChatService`\nmethod or package-index export. It authors as `session.agentProfileId` — the\nagent's resolved `bot` Profile, NEVER the `agentId` slug (#2995) — accepts a\nsame-room/tenant thread, and enforces `allowedTools` fail-closed.\n\nPrivate `#writeMessage` alone can select arbitrary authors/roles or bypass\nmembership. It binds every supplied `threadId`, `agentSessionId`, and\n`replyToMessageId` to the same room **and** tenant. Internal enrollment supports\nautomatically created rooms, sessions, and participants.\n\n## Agent Tool Whitelisting\n\n`allowedTools` is a JSON array controlled by the consuming app. Fail-closed: an empty/unparseable whitelist permits NO tools. The internal `sendAgentReply(service, params)` function enforces the whitelist before emitting any `tool`/`tool_call` message; a caller cannot supply a `senderProfileId`/`role` to post as the agent, and the function is not reachable from the package index.\n\nPrincipal-bound data discovery and reads are available as `PrincipalTool[]` via\n`createDataSurfaceTools()` (re-exported by the chat package). Pass the tools as\n`extraTools` to the persona conversation/tool loop. They use the same\nfail-closed `allowedTools` offer/execution gates; RBAC, tenant, redaction,\nbounded query results, and audit authority remain in the authenticated\n`PrincipalRun` supplied by `@happyvertical/smrt-agents`.\n\n## Commerce money tools (#3937)\n\nHosts that offer invoice money work must explicitly register\n`createCommerceMoneyTools()` from `@happyvertical/smrt-commerce` in\ntheir authenticated assistant route's `extraTools` (for example, `extraTools: () => createCommerceMoneyTools()`) and\nadd only the desired `commerce.*` slugs to the persona's `allowedTools`.\nThey are not generic manifest CRUD tools: tax codes are selected by code,\npreview is calculator-only, and line writes run through the document-money\ncoordinator. Each execution reasserts the principal allow-list and required\n`Invoice`, `InvoiceLineItem`, `DocumentTax`, and `TaxCode` operations. The\ngenerated MCP invoice `get` serializer remains commerce-owned; use its\nstored-facts integration when that serializer exposes `DocumentTax` rows.\n\n## Runtime report tools (#3711)\n\n`createRuntimeReportTools()` (`runtime-report-tools.ts`) returns four\n`PrincipalTool`s for the persona `extraTools` seam: `reports.runtime.sources`,\n`reports.runtime.define` (`preview` / `apply`), `reports.runtime.list`, and\n`reports.runtime.run`. The model supplies only a declarative\n`RuntimeReportSpec` from `@happyvertical/smrt-reports`; sources are a\nserver-owned allow-list gated by `run.assertOperation(collection, 'read')`, and\nfield policy, `readPermission`, and tenancy are enforced by the compiler against\nthe live run on every compile and every stored-report run. `apply` needs the\n`specHash` of the previewed spec plus an app-owned `confirmation` host that\nresolves only after a human approved that exact spec; with no host apply returns an `awaiting_confirmation` proposal for the\nsame-origin browser confirm route and stores nothing and a model-supplied `confirmed` flag is ignored. Saving also needs\n`create` on the `RuntimeReport` collection, and `list`/`run` need `read`; the\ndefault `reportsCollection` is the `RuntimeReport` class itself, which resolves\nto the catalog slug. A string `collection`/`reportsCollection` is used verbatim\nas a catalog slug (never a class name); tests must run the tools under the real\n`assertOperationPermission` guard so a wrong slug fails. A stored report is\nwritten only by this confirmed `apply`: the model layer refuses every other\ninsert/spec change, and the generic manifest tools (`buildManifestToolCatalog`,\n`invokeManifestTool`) never offer or run a `RuntimeReport` write. Stored-report\nreads/saves run under the principal's tenant (`withPrincipalTenant`), refuse a\nmismatching ambient tenant (checked before `confirmSave`), and filter by the principal tenant explicitly. Contract and authority model:\n[`packages/reports/agents/runtime-reports.md`](../reports/agents/runtime-reports.md).\n\n## Overview tools (#3727)\n\n`createOverviewTools({ host })` (`overview-tools.ts`) returns\n`overviews.describe`, `overviews.apply` (an atomic batch of structured widget\noperations) and `overviews.undo` (single step, keyed by tenant, user and page).\nThe host opens a page per `PrincipalRun` (smrt-svelte's\n`createOverviewAssistantSurface`, typed structurally here); validation and\n`canCustomize` are the surface's. Contract:\n[agents/overview-tools.md](agents/overview-tools.md).\n\n## Conversational Harness (L3, #1891)\n\nThe `AgentSession` runtime depends on personas, agents, and users. Keep those\nedges acyclic: none of those packages may depend back on chat.\n\n- **`runToolLoop(options)`** (`tool-loop.ts`) — a bounded `tool_call → observe → respond` loop. Tools are **manifest operations** of installed packages: `buildManifestToolCatalog({ allowedTools })` reads the `PermissionCatalogService` catalog and keeps only the `(collection, action)` entries named in the persona's allow-list (the **offer gate**; absent/empty ⇒ NO tools). The loop runs inside one `executeAsPrincipal` context, and `invokeManifestTool` executes each op **in-process (\"side door\")** against `run.context.database` (the RLS tx when Postgres RLS is on), after re-asserting the fail-closed allow-list (`run.assertToolAllowed`) AND the catalog permission (`run.assertOperation`) — the **execution gate**. Bounded by `DEFAULT_MAX_STEPS = 8`, an optional token budget and a deadline. Termination, the forced final call, observation caps, argument validation and tool-error classification: [agents/tool-loop.md](agents/tool-loop.md).\n- **`runPersonaConversationTurn(options)`** (`persona-conversation.ts`) — binds a conversation to an `AgentPersona`/`ResolvedPersona`: runs as its principal (`runAsUserId`), offers only its `allowedTools`, speaks its instructions (`resolvePersonaInstructions`, layering approved learned directives), and injects its **recalled learning memory** (`personaLearningMemory`, isolated per `memoryScope`) into the system prompt. `bindPersonaToSession()` mirrors the persona's `allowedTools`/instructions onto the `AgentSession` so the chat authoring gate agrees with the loop's offer gate. Authors the reply (and each executed tool) via the internal `sendAgentReply` bridge. Tools run with the run-as user's **live** permissions unless the host passes a `permissions` snapshot (#2978), which `runToolLoop` forwards to `executeAsPrincipal` so a narrowed principal (e.g. a shared station) cannot reach grants — such as `readPermission`-gated data-surface fields — beyond that snapshot, including through `agents.invoke` delegation (the snapshot becomes the worker's permission ceiling).\n- **Agent orchestration** (L3, #1892) — the loop accepts non-manifest **`extraTools`** (`PrincipalTool[]`, from `@happyvertical/smrt-agents`), gated by the *same* fail-closed allow-list. The standard **`invoke-agent`** tool (`createInvokeAgentTool`, slug `agents.invoke`) lets a conversational agent delegate to a **worker agent under its own principal** — the worker runs via `executeAsPrincipal` as the originating user (never its own authority), the principal is immutable along the chain, and its completion is surfaced back into the conversation. `runPersonaConversationTurn` filters `extraTools` by the persona's `allowedTools` (offer gate); the tool's `execute` re-asserts `assertToolAllowed` (execution gate). See `@happyvertical/smrt-agents` for the delegation envelope + transports.\n- **Chat feedback capture** (`chat-feedback.ts`) — `captureChatFeedback()` + `acceptAppliedChange`/`rejectAppliedChange`/`correctResponse`/`rateResponse`/`thumbsUp`/`thumbsDown` write a `Feedback` row (personas) carrying the conversation's **correlation-id**, and (by default) reinforce the persona's learning memory (`reinforceFromFeedback`). So an in-chat reject decays a strategy below the reuse floor and it stops being recalled; a correction supersedes its stored value.\n\n## Voice Gateway Turns (#1910)\n\nVoice is an input mode for the existing persona chat harness, not a separate chat runtime. `createVoiceChatSession()` creates a short-lived `VoiceSession` for an authenticated actor/profile, binding tenant, persona, agent session, room, and optional thread. `handleVoiceGatewayTurn()` resolves that binding from `metadata.voiceSessionId`, checks the gateway's `session_id` and any supplied tenant/profile/persona/session/thread metadata against the server-side binding, persists the transcript through `ChatService.sendAgentUserMessage()`, runs `runPersonaConversationTurn()`, stamps voice/correlation metadata onto the persisted user/assistant/tool messages, records the gateway `turn_id`, and returns the gateway response contract. The Fetch-compatible `createVoiceGatewayTurnHandler()` adds the coarse gateway bearer-token check.\n\nThe gateway bearer token proves only \"this request came from the gateway\"; it never authorizes the end user. The short-lived `VoiceSession` binding is the user/session proof, and untrusted gateway metadata must be validated against that binding before any chat write or tool loop. Tool execution remains fail-closed through the persona allow-list mirrored onto `AgentSession` by `bindPersonaToSession()`.\n\n## Token streaming\n\n`chat-stream.ts` serves browser-safe SSE through `./client`. The host's\n`authorize(request, body)` is the sole trust boundary: resolve identity, tenant,\ncapabilities, and generation limits server-side; never authorize from request\nsession metadata. Persona turns reuse the principal and fail-closed tool gates.\nThe engine and browser-safe `SmrtChatBackend` keep custom-tool resolution\nserver-side. See [agents/token-streaming.md](agents/token-streaming.md) for the\nevent contract, CORS policy, and streaming behavior.\n\n## Streamed assistant turns with browser tools (#2908)\n\n`runAssistantTurn()` (`assistant-turn.ts`) is the host-route engine for the\nAssistantDock: one turn over `runToolLoop` with server tools (offer-gated by\n`principal.allowedTools`), browser tools (validated by\n`sanitizeClientToolDeclarations` + a server allow-list), `maxSteps`, `signal`,\nand `onUsage`. A browser tool call SUSPENDS the turn (`stoppedReason:\n'client_tools'`); the transcript waits in an `AssistantContinuationStore`\n(single-use, 15-minute TTL; `createSessionContinuationStore` keeps it in the\nAgentSession's `sessionContext`) and the browser resumes it with results,\nwhich reach the model wrapped `untrusted`. `createAssistantTurnResponse`\nserves the events as SSE; `assistant-turn-events.ts` is the browser-safe wire\ncontract (`./assistant-turn` subpath, also a vite library entry because the\nSvelte dock imports it). The dock decides whether a browser call runs or waits\nfor the user from the page registry, never the server's echo; destructive\nalways waits. Details: [`docs/assistant-dock.md`](../../docs/assistant-dock.md).\n\n## AssistantDock (#2904)\n\n`AssistantDock` (`svelte/components/assistant/`, exported from `./svelte`)\nuses a host `DataSurfaceRegistry`'s mounted descriptors (none: plain chat).\nActions: `normalizeDataSurfaceActionRequest` → `AssistantActionClient`\n(preview/apply over a server `DataSurfaceActionAdapter`, not the\n`data-surface-bridge.ts` channel). Generated `ChatThread`/`ChatMessage`\n`list`/`get` are tenant- not member-scoped; the dock never calls them.\n\n**Server routes (#3368).** `./sveltekit` `mountAssistantRoutes()` serves the\ndock from one `[...path]` route; `createAssistantHttp{Transport,ActionClient}`\n(`./svelte`) are its browser half. Principal from `event.locals` or\n`resolvePrincipal`; threads only from the actor's keyed session room in that\ntenant (else 404). `allowedTools` is fail-closed; without `tools` it offers\nthose manifest ops (an unprovided name is an error, #3414). `ai` defaults to\nthe config `ai` block. Pass `runtime`: a turn never keeps the RLS request tx\n(own `runAsPrincipal` tx). `clientRequestId` makes the row id a UUIDv5\n(`clientRequestMessageId`): the PK is the retry reservation. See\n[docs](../../docs/assistant-dock.md).\n\n#4505: `messageFormat=\"markdown\"` / `renderMessage` ([docs](../../docs/assistant-dock.md));\n`collapseRecoveredFailures` ([tool-loop](agents/tool-loop.md#failed-calls-are-persisted-4383)).\n\nStructured questions and page requests (#4100): [agents/assistant-questions.md](agents/assistant-questions.md).\n\n## Recipes (#3719)\n\n`src/recipes.ts` declares `chat.assistant` (the AssistantDock as a `header.end`\nshell widget, an `llm` provider, runtime `both`; help in\n`src/assistant.recipe.md`). Keep each recipe class self-contained. Details:\n[agents/recipes.md](agents/recipes.md).\n\n## Gotchas\n\n- **sessionContext, not context**: `context` is reserved for slug scoping. Use `getSessionContext()`/`updateSessionContext()` for agent memory.\n- **Agent rooms auto-created**: `roomType: 'agent'`, `maxParticipants` defaults to 2; the agent is enrolled as a member so its replies pass the membership check. `createAgentSession()` re-enrolls the participant AND the agent on the existing-session path, so legacy sessions created before the agent was enrolled self-heal.\n- **The agent's author is a Profile, not `agentId` (#2995)**: `senderProfileId`/`profileId` are `crossPackageRef`s to `Profile` and therefore uuid columns on PostgreSQL, so the slug fails the cast (`22P02`) and no agent reply can persist. `createAgentSession()` resolves the agent's `bot` Profile through `resolveAgentProfile()` in `@happyvertical/smrt-profiles` (created on first use, tenant-bound) and records it as `AgentSession.agentProfileId`; both enrolment and `sendAgentReply` use that uuid. A consumer whose agent already has an acting identity passes `agentProfileId` to skip resolution — the voice path does this with the persona's `actsAsProfileId`, so persona replies stay attributed to the configured acting profile. Like `actorProfileId`, `agentProfileId` is SERVER-supplied, never request input: it selects the author of every later assistant message. It is validated (`#requireAgentProfile`) to exist and be visible in the tenant and to differ from the acting participant, and it can never re-point a session that already resolved one — only a pre-#2995 session with none is backfilled. **Migration**: `agent_profile_id` is an ordinary additive manifest field, so a consumer adopts it the same way as any other — `smrt db:migrate` generates and applies the column from the manifest, and `db:status --parity` verifies it; the framework never creates application schema at runtime. It is nullable and needs no offline DATA backfill — a session created before #2995 resolves and persists its `agentProfileId`, and re-enrols the agent, on its first agent turn after the upgrade. Two pre-#2995 cohorts: a session whose `agentId` is an ordinary slug never committed an author on PostgreSQL (the cast failed), so there is nothing to repair there, while SQLite/DuckDB may hold `chat_messages`/`chat_participants` rows whose id column holds the slug — readable, but not joinable to `profiles`. A session whose `agentId` is already a Profile uuid (the voice path used to collapse a persona's `actsAsProfileId` into it) DID commit on PostgreSQL; that profile is ADOPTED as the author, tenant-checked and never the participant, so the conversation's author does not change and the two-seat room gains no third identity. Known one-time effect: because `voice.ts` no longer derives `agentId` from `actsAsProfileId`, a keyless `createVoiceChatSession()` for such a persona opens a new session and room instead of reusing the legacy one; the old room and its messages stay intact and readable, and resuming with an explicit `agentSessionId` is unaffected.\n- **Only SQLite-backed tests would miss this class of bug**: uuid columns accept any text on SQLite. `src/__tests__/agent-reply-postgres.test.ts` (`pnpm --filter @happyvertical/smrt-chat test:postgres`) pins the agent-reply path against real PostgreSQL. That suite runs in `postgres-tests.yml` on every same-repository PR and merge group (#2659); keep a cheap SQLite assertion alongside it anyway, since the default lane is SQLite-only (`chat-service.test.ts` asserts the author is the profile uuid, not the slug).\n- **Per-subject sessions need `sessionKey`**: `createAgentSession()` reuses ANY active session for the same `(agentId, participantProfileId, tenantId)`. Callers that open separate conversations per subject (e.g. one content-editor session per content id) MUST pass a stable `sessionKey` (stored in `sessionContext.__sessionKey`, read via `AgentSession.getSessionKey()`); otherwise a session opened for one subject is reused and its context overwritten for another, surfacing the wrong room/threads (S5 #1392). A keyed create never reuses a keyless/legacy session.\n- **Session expiry**: check `isActive()` before allowing messages (expiresAt or limit-based)\n- **DM identity**: derived from the deterministic per-tenant `canonicalDmRoomId()` and the authoritative `chat_participants` join, not client metadata; concurrent creates upsert onto one row.\n- **Tenant-bound lookups**: membership/session/DM lookups REQUIRE `tenantId` and always bind it into the WHERE clause (`findActiveMembership`/`isActiveMember`/`findActiveSession` take a required `tenantId`; AgentSession's `null` tenant is an explicit bound scope, not \"any tenant\") so they can never resolve a row from another tenant.\n",
4517
+ "agentDoc": "# @happyvertical/smrt-chat\n\nChat rooms, threads, and agent sessions with app-controlled tool whitelisting.\n\n## Dev Server\n\n`pnpm --dir packages/chat dev` runs a package-local SvelteKit workbench. The root\nroute separates **Character setup** and **Chat dev** into tabs; switching tabs\nretains the current character rig and chat state. The chat tab is an interactive\nsurface with a dev-only `/api/dev-chat` endpoint:\nit uses `@happyvertical/ai` when local provider credentials are present and\nfalls back to a deterministic local assistant otherwise. `/api/dev-chat-stream`\nis its SSE companion (#1936) — the same provider/local-fallback resolution wired\nthrough `createChatStreamHandler` in plain mode, so an embedded `SmrtChatBackend`\nclient can exercise token streaming locally. `/previews` hosts the shared\ncomponent playground entries from `src/svelte/playground.ts`.\n\nThe root route also drives the **browser inference path**\n(`@happyvertical/smrt-web/ai`: bitgpu, WebLLM, and route backends composed by\n`createInferencePath`) and an **agent-addressable draft form** (`useViewIntent`\nover `src/routes/chat-dev.intents.ts`, #2588). Their dev-config dependencies\n(static optional-peer imports, `workspace-aliases.js` prefix rules, the theme\nstylesheet import) and the stage→apply tool-call gotchas are in\n[agents/dev-workbench.md](agents/dev-workbench.md).\n\nDev-only voice and opt-in local character persistence are documented in\n[agents/dev-workbench.md](agents/dev-workbench.md#voice-and-local-character-persistence).\nThese endpoints are loopback-only demos; production hosts supply authenticated\nprincipals, tenancy, and authorization to the owning services.\n\n## Models\n\nAll seven models expose only generated REST/MCP `list`/`get`; structural tests\ncheck the registry for mutating operations. Writes go through\nmembership/owner-checked `ChatService` or the binding-checked voice adapter.\n\n`ChatService` is a closed facade. Its collections and security-sensitive\nhelpers use ES `#private` fields/methods (TypeScript `private` is erased).\nCollection classes are not exported from the package index. The agent-reply\nbridge is a Symbol-keyed static accessible through a non-exported symbol held\nby the module-local `sendAgentReply` function.\n\n- **ChatRoom**: `roomType` (public/private/dm/agent), `status`, `topic`, `maxParticipants`, `lastMessageAt`. Tenant-scoped (required).\n- **ChatMessage**: shared by users + agents. `role` (user/assistant/system/tool), `messageType` (text/system/action/file/tool_call/tool_result), `toolCallData` JSON. Unified model — no separate agent message type. Tenant-scoped (required).\n- **ChatParticipant**: `role` (owner/admin/member/viewer), `onlineStatus`, `lastReadMessageId`, `isMuted`. Tenant-scoped (required).\n- **ChatThread**: `rootMessageId`, `isResolved`, `messageCount`. Created via `ChatService.startThread()` (member-checked). Tenant-scoped (required).\n- **ChatReaction**: `messageId`, `profileId`, `emoji`. Added/removed via `ChatService.addReaction()`/`removeReaction()` (member-checked, self-keyed). Tenant-scoped (required).\n- **AgentSession**: `agentId` (application slug, string ref, not FK), `agentProfileId` (nullable `crossPackageRef` to `Profile` — the `bot` profile the agent AUTHORS as, #2995), `allowedTools` (JSON string array), `sessionContext` (JSON, sensitive), `systemPrompt`, limits (`maxTokens`/`maxMessages`/`expiresAt`). Optional tenancy.\n- **VoiceSession**: short-lived voice-gateway binding over `(tenant, actorProfileId, personaId, room/thread/agentSession)` plus a persona snapshot, gateway `session_id`, expiry, replay tracking, and metadata. Tenant-scoped (required). Generated surface is read-only; creation and turns go through `createVoiceChatSession()` / `handleVoiceGatewayTurn()`.\n\n## ChatService\n\nPublic writes take server-supplied `actorProfileId`; never trust a request's\n`senderProfileId`, `role`, owner id, or participant id as authority.\n\n| Operation | Authorization and behavior |\n|---|---|\n| `sendMessage()` | Room member; authors as actor with `role: 'user'`; no public membership bypass |\n| `createRoom()` | Actor becomes owner |\n| `startThread()` | Member; optional root message bound to room and tenant |\n| `addParticipant()` / `removeParticipant()` | Owner/admin; self-leave allowed |\n| `updateRoom()` | Owner/admin |\n| `addReaction()` / `removeReaction()` | Member; self-keyed |\n| `getOrCreateDM()` | Actor must be a DM participant |\n| `createAgentSession()` | Actor becomes session participant; existing-session lookup tenant-bound; optional `sessionKey` isolates conversation subjects |\n| `updateAgentSessionConfig()` | Owner; mandatory tenant-bound lookup |\n| `sendAgentUserMessage()` | Actor must be session participant; authored as participant |\n\nRead facade: `getAgentSession({agentSessionId, tenantId})`,\n`findActiveAgentSessions({tenantId, agentId, participantProfileId})`, and\n`getThread({threadId, tenantId})` are tenant-bound; consumers still check\nownership/context. `listRoomThreads({roomId, actorProfileId, tenantId})`,\n`getThreadMessages({threadId, actorProfileId, tenantId, limit?})` (chronological),\n`getRoomMessages({roomId, actorProfileId, tenantId})`, and\n`getRoomForMember(roomId, actorProfileId, tenantId)` additionally require\nmembership of the server-supplied actor, not a caller-selected subject.\n\nTrusted agent runtime imports `sendAgentReply(service, params)` only from\n`@happyvertical/smrt-chat/internal/agent-runtime`. It is not a `ChatService`\nmethod or package-index export. It authors as `session.agentProfileId` — the\nagent's resolved `bot` Profile, NEVER the `agentId` slug (#2995) — accepts a\nsame-room/tenant thread, and enforces `allowedTools` fail-closed.\n\nPrivate `#writeMessage` alone can select arbitrary authors/roles or bypass\nmembership. It binds every supplied `threadId`, `agentSessionId`, and\n`replyToMessageId` to the same room **and** tenant. Internal enrollment supports\nautomatically created rooms, sessions, and participants.\n\n## Agent Tool Whitelisting\n\n`allowedTools` is a JSON array controlled by the consuming app. Fail-closed: an empty/unparseable whitelist permits NO tools. The internal `sendAgentReply(service, params)` function enforces the whitelist before emitting any `tool`/`tool_call` message; a caller cannot supply a `senderProfileId`/`role` to post as the agent, and the function is not reachable from the package index.\n\nPrincipal-bound data discovery and reads are available as `PrincipalTool[]` via\n`createDataSurfaceTools()` (re-exported by the chat package). Pass the tools as\n`extraTools` to the persona conversation/tool loop. They use the same\nfail-closed `allowedTools` offer/execution gates; RBAC, tenant, redaction,\nbounded query results, and audit authority remain in the authenticated\n`PrincipalRun` supplied by `@happyvertical/smrt-agents`.\n\n## Commerce money tools (#3937)\n\nHosts that offer invoice money work must explicitly register\n`createCommerceMoneyTools()` from `@happyvertical/smrt-commerce` in\ntheir authenticated assistant route's `extraTools` (for example, `extraTools: () => createCommerceMoneyTools()`) and\nadd only the desired `commerce.*` slugs to the persona's `allowedTools`.\nThey are not generic manifest CRUD tools: tax codes are selected by code,\npreview is calculator-only, and line writes run through the document-money\ncoordinator. Each execution reasserts the principal allow-list and required\n`Invoice`, `InvoiceLineItem`, `DocumentTax`, and `TaxCode` operations. The\ngenerated MCP invoice `get` serializer remains commerce-owned; use its\nstored-facts integration when that serializer exposes `DocumentTax` rows.\n\n## Runtime report tools (#3711)\n\n`createRuntimeReportTools()` (`runtime-report-tools.ts`) returns four\n`PrincipalTool`s for the persona `extraTools` seam: `reports.runtime.sources`,\n`reports.runtime.define` (`preview` / `apply`), `reports.runtime.list`, and\n`reports.runtime.run`. The model supplies only a declarative\n`RuntimeReportSpec` from `@happyvertical/smrt-reports`; sources are a\nserver-owned allow-list gated by `run.assertOperation(collection, 'read')`, and\nfield policy, `readPermission`, and tenancy are enforced by the compiler against\nthe live run on every compile and every stored-report run. `apply` needs the\n`specHash` of the previewed spec plus an app-owned `confirmation` host that\nresolves only after a human approved that exact spec; with no host apply returns an `awaiting_confirmation` proposal for the\nsame-origin browser confirm route and stores nothing and a model-supplied `confirmed` flag is ignored. Saving also needs\n`create` on the `RuntimeReport` collection, and `list`/`run` need `read`; the\ndefault `reportsCollection` is the `RuntimeReport` class itself, which resolves\nto the catalog slug. A string `collection`/`reportsCollection` is used verbatim\nas a catalog slug (never a class name); tests must run the tools under the real\n`assertOperationPermission` guard so a wrong slug fails. A stored report is\nwritten only by this confirmed `apply`: the model layer refuses every other\ninsert/spec change, and the generic manifest tools (`buildManifestToolCatalog`,\n`invokeManifestTool`) never offer or run a `RuntimeReport` write. Stored-report\nreads/saves run under the principal's tenant (`withPrincipalTenant`), refuse a\nmismatching ambient tenant (checked before `confirmSave`), and filter by the principal tenant explicitly. Contract and authority model:\n[`packages/reports/agents/runtime-reports.md`](../reports/agents/runtime-reports.md).\n\n## Overview tools (#3727)\n\n`createOverviewTools({ host })` (`overview-tools.ts`) returns\n`overviews.describe`, `overviews.apply` (an atomic batch of structured widget\noperations) and `overviews.undo` (single step, keyed by tenant, user and page).\nThe host opens a page per `PrincipalRun` (smrt-svelte's\n`createOverviewAssistantSurface`, typed structurally here); validation and\n`canCustomize` are the surface's. Contract:\n[agents/overview-tools.md](agents/overview-tools.md).\n\n## Conversational Harness (L3, #1891)\n\nThe `AgentSession` runtime depends on personas, agents, and users. Keep those\nedges acyclic: none of those packages may depend back on chat.\n\n- **`runToolLoop(options)`** (`tool-loop.ts`) — a bounded `tool_call → observe → respond` loop. Tools are **manifest operations** of installed packages: `buildManifestToolCatalog({ allowedTools })` reads the `PermissionCatalogService` catalog and keeps only the `(collection, action)` entries named in the persona's allow-list (the **offer gate**; absent/empty ⇒ NO tools). The loop runs inside one `executeAsPrincipal` context, and `invokeManifestTool` executes each op **in-process (\"side door\")** against `run.context.database` (the RLS tx when Postgres RLS is on), after re-asserting the fail-closed allow-list (`run.assertToolAllowed`) AND the catalog permission (`run.assertOperation`) — the **execution gate**. Bounded by `DEFAULT_MAX_STEPS = 8`, an optional token budget and a deadline. Termination, the forced final call, observation caps, argument validation and tool-error classification: [agents/tool-loop.md](agents/tool-loop.md).\n- **`runPersonaConversationTurn(options)`** (`persona-conversation.ts`) — binds a conversation to an `AgentPersona`/`ResolvedPersona`: runs as its principal (`runAsUserId`), offers only its `allowedTools`, speaks its instructions (`resolvePersonaInstructions`, layering approved learned directives), and injects its **recalled learning memory** (`personaLearningMemory`, isolated per `memoryScope`) into the system prompt. `bindPersonaToSession()` mirrors the persona's `allowedTools`/instructions onto the `AgentSession` so the chat authoring gate agrees with the loop's offer gate. Authors the reply (and each executed tool) via the internal `sendAgentReply` bridge. Tools run with the run-as user's **live** permissions unless the host passes a `permissions` snapshot (#2978), which `runToolLoop` forwards to `executeAsPrincipal` so a narrowed principal (e.g. a shared station) cannot reach grants — such as `readPermission`-gated data-surface fields — beyond that snapshot, including through `agents.invoke` delegation (the snapshot becomes the worker's permission ceiling).\n- **Agent orchestration** (L3, #1892) — the loop accepts non-manifest **`extraTools`** (`PrincipalTool[]`, from `@happyvertical/smrt-agents`), gated by the *same* fail-closed allow-list. The standard **`invoke-agent`** tool (`createInvokeAgentTool`, slug `agents.invoke`) lets a conversational agent delegate to a **worker agent under its own principal** — the worker runs via `executeAsPrincipal` as the originating user (never its own authority), the principal is immutable along the chain, and its completion is surfaced back into the conversation. `runPersonaConversationTurn` filters `extraTools` by the persona's `allowedTools` (offer gate); the tool's `execute` re-asserts `assertToolAllowed` (execution gate). See `@happyvertical/smrt-agents` for the delegation envelope + transports.\n- **Chat feedback capture** (`chat-feedback.ts`) — `captureChatFeedback()` + `acceptAppliedChange`/`rejectAppliedChange`/`correctResponse`/`rateResponse`/`thumbsUp`/`thumbsDown` write a `Feedback` row (personas) carrying the conversation's **correlation-id**, and (by default) reinforce the persona's learning memory (`reinforceFromFeedback`). So an in-chat reject decays a strategy below the reuse floor and it stops being recalled; a correction supersedes its stored value.\n\n## Voice Gateway Turns (#1910)\n\nVoice is an input mode for the existing persona chat harness, not a separate chat runtime. `createVoiceChatSession()` creates a short-lived `VoiceSession` for an authenticated actor/profile, binding tenant, persona, agent session, room, and optional thread. `handleVoiceGatewayTurn()` resolves that binding from `metadata.voiceSessionId`, checks the gateway's `session_id` and any supplied tenant/profile/persona/session/thread metadata against the server-side binding, persists the transcript through `ChatService.sendAgentUserMessage()`, runs `runPersonaConversationTurn()`, stamps voice/correlation metadata onto the persisted user/assistant/tool messages, records the gateway `turn_id`, and returns the gateway response contract. The Fetch-compatible `createVoiceGatewayTurnHandler()` adds the coarse gateway bearer-token check.\n\nThe gateway bearer token proves only \"this request came from the gateway\"; it never authorizes the end user. The short-lived `VoiceSession` binding is the user/session proof, and untrusted gateway metadata must be validated against that binding before any chat write or tool loop. Tool execution remains fail-closed through the persona allow-list mirrored onto `AgentSession` by `bindPersonaToSession()`.\n\n## Token streaming\n\n`chat-stream.ts` serves browser-safe SSE through `./client`. The host's\n`authorize(request, body)` is the sole trust boundary: resolve identity, tenant,\ncapabilities, and generation limits server-side; never authorize from request\nsession metadata. Persona turns reuse the principal and fail-closed tool gates.\nThe engine and browser-safe `SmrtChatBackend` keep custom-tool resolution\nserver-side. See [agents/token-streaming.md](agents/token-streaming.md) for the\nevent contract, CORS policy, and streaming behavior.\n\n## Streamed assistant turns with browser tools (#2908)\n\n`runAssistantTurn()` (`assistant-turn.ts`) is the host-route engine for the\nAssistantDock: one turn over `runToolLoop` with server tools (offer-gated by\n`principal.allowedTools`), browser tools (validated by\n`sanitizeClientToolDeclarations` + a server allow-list), `maxSteps`, `signal`,\nand `onUsage`. A browser tool call SUSPENDS the turn (`stoppedReason:\n'client_tools'`); the transcript waits in an `AssistantContinuationStore`\n(single-use, 15-minute TTL; `createSessionContinuationStore` keeps it in the\nAgentSession's `sessionContext`) and the browser resumes it with results,\nwhich reach the model wrapped `untrusted`. `createAssistantTurnResponse`\nserves the events as SSE; `assistant-turn-events.ts` is the browser-safe wire\ncontract (`./assistant-turn` subpath, also a vite library entry because the\nSvelte dock imports it). The dock decides whether a browser call runs or waits\nfor the user from the page registry, never the server's echo; destructive\nalways waits. Details: [`docs/assistant-dock.md`](../../docs/assistant-dock.md).\n\n## AssistantDock (#2904)\n\n`AssistantDock` (`svelte/components/assistant/`, exported from `./svelte`)\nuses a host `DataSurfaceRegistry`'s mounted descriptors (none: plain chat).\nActions: `normalizeDataSurfaceActionRequest` → `AssistantActionClient`\n(preview/apply over a server `DataSurfaceActionAdapter`, not the\n`data-surface-bridge.ts` channel). Generated `ChatThread`/`ChatMessage`\n`list`/`get` are tenant- not member-scoped; the dock never calls them.\n\n**Server routes (#3368).** `./sveltekit` `mountAssistantRoutes()` serves the\ndock from one `[...path]` route; `createAssistantHttp{Transport,ActionClient}`\n(`./svelte`) are its browser half. Principal from `event.locals` or\n`resolvePrincipal`; threads only from the actor's keyed session room in that\ntenant (else 404). `allowedTools` is fail-closed; without `tools` it offers\nthose manifest ops (an unprovided name is an error, #3414). `ai` defaults to\nthe principal's stored inference binding over the config `ai` block (#4756,\n[core inference.md](../core/agents/inference.md#raw-clients-and-binding-source-4756)). Pass `runtime`: a turn never keeps the RLS request tx\n(own `runAsPrincipal` tx). `clientRequestId` makes the row id a UUIDv5\n(`clientRequestMessageId`): the PK is the retry reservation. See\n[docs](../../docs/assistant-dock.md).\n\nAI off / not set up (#4757): routes answer a structured `ai_unavailable` 503;\ndock `aiSettingsHref` ([agents/ai-unavailable.md](agents/ai-unavailable.md)).\n\n#4505: `messageFormat=\"markdown\"` / `renderMessage` ([docs](../../docs/assistant-dock.md));\n`collapseRecoveredFailures` ([tool-loop](agents/tool-loop.md#failed-calls-are-persisted-4383)).\n\nStructured questions and page requests (#4100): [agents/assistant-questions.md](agents/assistant-questions.md).\n\n## Recipes (#3719)\n\n`src/recipes.ts` declares `chat.assistant` (the AssistantDock as a `header.end`\nshell widget, an `llm` provider, runtime `both`; help in\n`src/assistant.recipe.md`). Keep each recipe class self-contained. Details:\n[agents/recipes.md](agents/recipes.md).\n\n## Gotchas\n\n- **sessionContext, not context**: `context` is reserved for slug scoping. Use `getSessionContext()`/`updateSessionContext()` for agent memory.\n- **Agent rooms auto-created**: `roomType: 'agent'`, `maxParticipants` defaults to 2; the agent is enrolled as a member so its replies pass the membership check. `createAgentSession()` re-enrolls the participant AND the agent on the existing-session path, so legacy sessions created before the agent was enrolled self-heal.\n- **The agent's author is a Profile, not `agentId` (#2995)**: `senderProfileId`/`profileId` are `crossPackageRef`s to `Profile` and therefore uuid columns on PostgreSQL, so the slug fails the cast (`22P02`) and no agent reply can persist. `createAgentSession()` resolves the agent's `bot` Profile through `resolveAgentProfile()` in `@happyvertical/smrt-profiles` (created on first use, tenant-bound) and records it as `AgentSession.agentProfileId`; both enrolment and `sendAgentReply` use that uuid. A consumer whose agent already has an acting identity passes `agentProfileId` to skip resolution — the voice path does this with the persona's `actsAsProfileId`, so persona replies stay attributed to the configured acting profile. Like `actorProfileId`, `agentProfileId` is SERVER-supplied, never request input: it selects the author of every later assistant message. It is validated (`#requireAgentProfile`) to exist and be visible in the tenant and to differ from the acting participant, and it can never re-point a session that already resolved one — only a pre-#2995 session with none is backfilled. **Migration**: `agent_profile_id` is an ordinary additive manifest field, so a consumer adopts it the same way as any other — `smrt db:migrate` generates and applies the column from the manifest, and `db:status --parity` verifies it; the framework never creates application schema at runtime. It is nullable and needs no offline DATA backfill — a session created before #2995 resolves and persists its `agentProfileId`, and re-enrols the agent, on its first agent turn after the upgrade. Two pre-#2995 cohorts: a session whose `agentId` is an ordinary slug never committed an author on PostgreSQL (the cast failed), so there is nothing to repair there, while SQLite/DuckDB may hold `chat_messages`/`chat_participants` rows whose id column holds the slug — readable, but not joinable to `profiles`. A session whose `agentId` is already a Profile uuid (the voice path used to collapse a persona's `actsAsProfileId` into it) DID commit on PostgreSQL; that profile is ADOPTED as the author, tenant-checked and never the participant, so the conversation's author does not change and the two-seat room gains no third identity. Known one-time effect: because `voice.ts` no longer derives `agentId` from `actsAsProfileId`, a keyless `createVoiceChatSession()` for such a persona opens a new session and room instead of reusing the legacy one; the old room and its messages stay intact and readable, and resuming with an explicit `agentSessionId` is unaffected.\n- **Only SQLite-backed tests would miss this class of bug**: uuid columns accept any text on SQLite. `src/__tests__/agent-reply-postgres.test.ts` (`pnpm --filter @happyvertical/smrt-chat test:postgres`) pins the agent-reply path against real PostgreSQL. That suite runs in `postgres-tests.yml` on every same-repository PR and merge group (#2659); keep a cheap SQLite assertion alongside it anyway, since the default lane is SQLite-only (`chat-service.test.ts` asserts the author is the profile uuid, not the slug).\n- **Per-subject sessions need `sessionKey`**: `createAgentSession()` reuses ANY active session for the same `(agentId, participantProfileId, tenantId)`. Callers that open separate conversations per subject (e.g. one content-editor session per content id) MUST pass a stable `sessionKey` (stored in `sessionContext.__sessionKey`, read via `AgentSession.getSessionKey()`); otherwise a session opened for one subject is reused and its context overwritten for another, surfacing the wrong room/threads (S5 #1392). A keyed create never reuses a keyless/legacy session.\n- **Session expiry**: check `isActive()` before allowing messages (expiresAt or limit-based)\n- **DM identity**: derived from the deterministic per-tenant `canonicalDmRoomId()` and the authoritative `chat_participants` join, not client metadata; concurrent creates upsert onto one row.\n- **Tenant-bound lookups**: membership/session/DM lookups REQUIRE `tenantId` and always bind it into the WHERE clause (`findActiveMembership`/`isActiveMember`/`findActiveSession` take a required `tenantId`; AgentSession's `null` tenant is an explicit bound scope, not \"any tenant\") so they can never resolve a row from another tenant.\n",
4517
4518
  "moduleDocs": [
4518
4519
  {
4519
4520
  "path": "agents/dev-workbench.md",
@@ -4535,6 +4536,11 @@
4535
4536
  "module": "token-streaming",
4536
4537
  "content": "# Token Streaming (SSE, #1936)\n\nReference linked from [../AGENTS.md](../AGENTS.md). This contract was moved from\n`packages/chat/AGENTS.md` to keep the instruction chain under the 32 KB cap\n(`pnpm check:agents-chain`); AGENTS.md retains the cap-oriented summary.\n\n`chat-stream.ts` is the SSE seam for embeddable conversational UIs (first consumer: the Happy chat widget, `animation#5`): a client POSTs the conversation so far and receives a `text/event-stream` of `data: <json>` frames — `token` deltas as the model generates, then a final `done` frame with the message. The wire `ChatStreamEvent` union also declares `emotion` and `control` (#1921 host-page control commands) lanes for forward compatibility; the v1 engine emits `token`/`done`/`error`.\n\n- **`runChatConversationStream({ context, messages })`** — the transport-agnostic engine (an `AsyncGenerator<ChatStreamEvent>`). Dispatches on `context.binding`: **persona-bound** runs the full `runPersonaConversationTurn` with a token sink wired through the tool loop (`onToken` → `ai.chat({ stream: true, onProgress })`), then persists via `ChatService` and emits the persisted message as `done`; **plain/unbound** streams `ai.stream()` directly and emits a synthesized (unpersisted) `done`. Streamed tokens are a live PREVIEW (a tool-call round may narrate before acting); the `done` message is authoritative. Failures surface as an in-band `error` event, never a throw (the 200 has already committed once streaming starts).\n- **`createChatStreamHandler({ authorize, allowedOrigins?, allowCredentials? })`** — a Fetch-compatible handler returning `text/event-stream` (mirrors `createVoiceGatewayTurnHandler`). `authorize(request, body)` is the SOLE trust boundary and works exactly like the voice gateway: this module NEVER authorizes from the request's `session` metadata — the app validates the caller (bearer session id / cookie / same-origin) and the claimed ids against the authenticated principal, and returns an already-authorized `ChatStreamContext`. Generation caps (`model`/`maxTokens`/`maxSteps`) live on the context (server-resolved), never on the request. Cross-origin embedding uses the same fail-closed CORS posture as core `_events` (#1861): the `Origin` is echoed only when allow-listed (never `*`), credentials only when opted in.\n- **`SmrtChatBackend` (`@happyvertical/smrt-chat/client`)** — the consume side of the same contract: a browser SSE client (`src/client.ts`) that POSTs the conversation and dispatches `token`/`emotion`/`done`/`error` frames to streaming handlers, tolerating heartbeat comments and frames split across chunks. The subpath is BROWSER-SAFE and dependency-free (no server runtime, no workspace imports — keep it that way), and its widget-facing types are structurally identical to `@happyvertical/animation`'s `ChatBackend` contract so an instance plugs straight into the floating chat widget. `src/client.contract.ts` carries the compile-time locks pinning it to `chat-stream.ts`'s `ChatStreamEvent`/`ChatStreamSession` — a NON-test module precisely so `pnpm typecheck` actually enforces them (`tsconfig.typecheck.json` excludes `.test.ts` files, and Vitest transpiles without typechecking). A clean close without a `done` frame surfaces as an error (never an empty reply), and a settled turn cancels the reader so the connection is released promptly.\n- **Persona path reuses the harness's own gates unchanged** — persona principal, fail-closed `allowedTools` offer+execution gates, tenant binding. `onToken` is best-effort telemetry threaded through `runToolLoop`; it never changes what the loop persists or authorizes.\n- **Custom tools stream via `binding.extraTools`** — the persona binding threads an optional `extraTools?: PrincipalTool[]` down to `runPersonaConversationTurn`, so a *streamed* persona chat can offer non-manifest, service-backed tools (the persona messaging tool `messages.send`, or an assistance-request/lead-ticket tool wrapping a `@smrt({ api:false, mcp:false })` service) and thus *act*, not only answer — matching the non-streaming persona path. It is resolved server-side by `authorize` (trusted), never from request input, and stays fully gated: each tool is filtered by the persona's `allowedTools` (offer gate) and re-asserts the bound principal's authority in `execute` (execution gate). Offering a tool is not authorizing it.\n"
4537
4538
  },
4539
+ {
4540
+ "path": "agents/ai-unavailable.md",
4541
+ "module": "ai-unavailable",
4542
+ "content": "# AI unavailable answers (#4757)\n\nWhen core throws `InferenceUnavailableError` (`AI_UNAVAILABLE`: the\nprincipal's mode is `off`, nothing is configured, ...; see\n[core inference.md](../../core/agents/inference.md#inference-mode-and-ai_unavailable-4757)),\nchat answers a structured message instead of a 500. Source:\n`src/ai-unavailable.ts` (server), `src/client.ts` (browser parsing).\n\n## Wire shape\n\n`503` with `{ type: 'unavailable', code: 'ai_unavailable', error, unavailable }`:\n`error` is a user-safe sentence for the reason, `unavailable` is core's\n`InferenceStatus` (`available: false`, `mode`, `reason`, `tier?`). No stack,\nno provider detail, never a key. `chatUnavailableBody(error)` builds it from\nthe typed error (matched by code, so another core copy's error counts);\n`chatUnconfiguredBody()` is the `unconfigured` body.\n\n- `mountAssistantRoutes()`: the AI factory's `AI_UNAVAILABLE`, and the default\n factory's `AIProviderNotConfiguredError` (as `unconfigured`), answer this\n instead of `assistant_unavailable`, before anything is stored. The\n not-configured error still reaches `onError` (it names the config to\n add); a chosen mode `off` is not logged.\n- `createChatStreamHandler()`: `authorize` throwing it answers the 503; a\n mid-turn one is the in-band `error` event with `code: 'ai_unavailable'`\n and `unavailable`.\n- Dev routes: `/api/dev-chat` and `/api/dev-character-conversation` answer\n the 503; `/api/dev-chat-stream` lets it reach the handler. Unconfigured dev\n routes keep their local fallback (dev-chat, dev-chat-stream).\n\n## Browser\n\n`./client`: `SmrtChatBackend` raises `ChatUnavailableError` (`unavailable`\nstatus) for both shapes; `readChatUnavailableStatus(body)` parses one\n(dependency-free, mirrors core's status type). The dock's HTTP transport sets\n`AssistantHttpError.unavailable`. `AssistantDock`'s `aiSettingsHref` renders\n`AiUnavailableNotice` (\"AI is off\" plus an \"Open AI settings\" link to the\nhost's page) in place of the error banner until a send succeeds; hosts render\nthe notice on their own surfaces from `./svelte`.\n\nTests: `src/ai-unavailable.test.ts`, `src/sveltekit-defaults.test.ts`,\n`src/svelte/components/shared/__tests__/AiUnavailableNotice.test.ts`,\n`src/svelte/components/assistant/__tests__/assistant-dock-ai-unavailable.test.ts`.\n"
4543
+ },
4538
4544
  {
4539
4545
  "path": "agents/assistant-questions.md",
4540
4546
  "module": "assistant-questions",
@@ -5,10 +5,10 @@ description: "Chat rooms, DMs, threads, and agent conversations for the SMRT fra
5
5
  status: "stable"
6
6
  generated:
7
7
  by: "smrt/scripts/generate-knowledge-okf.ts"
8
- at: "2026-11-05T15:48:19Z"
8
+ at: "2026-11-08T22:59:11Z"
9
9
  audience: "internal"
10
10
  evidence_level: "source-inspected"
11
- source_revision: "sha256:6d305ee403a1fc43b71f10a8be7764a9a48be5d3617ddd315b2c0c0ea14d73ac"
11
+ source_revision: "sha256:78fa8f078b95f9a5979d9848ebb14bd46289ef2fa788f178c56203fa8978b5ea"
12
12
  sources:
13
13
  - id: "manifest"
14
14
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/package.json"
@@ -17,21 +17,24 @@ sources:
17
17
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/AGENTS.md"
18
18
  title: "@happyvertical/smrt-chat packages/chat/AGENTS.md"
19
19
  - id: "agents-2"
20
+ resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/ai-unavailable.md"
21
+ title: "@happyvertical/smrt-chat packages/chat/agents/ai-unavailable.md"
22
+ - id: "agents-3"
20
23
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/assistant-questions.md"
21
24
  title: "@happyvertical/smrt-chat packages/chat/agents/assistant-questions.md"
22
- - id: "agents-3"
25
+ - id: "agents-4"
23
26
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/dev-workbench.md"
24
27
  title: "@happyvertical/smrt-chat packages/chat/agents/dev-workbench.md"
25
- - id: "agents-4"
28
+ - id: "agents-5"
26
29
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/overview-tools.md"
27
30
  title: "@happyvertical/smrt-chat packages/chat/agents/overview-tools.md"
28
- - id: "agents-5"
31
+ - id: "agents-6"
29
32
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/recipes.md"
30
33
  title: "@happyvertical/smrt-chat packages/chat/agents/recipes.md"
31
- - id: "agents-6"
34
+ - id: "agents-7"
32
35
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/token-streaming.md"
33
36
  title: "@happyvertical/smrt-chat packages/chat/agents/token-streaming.md"
34
- - id: "agents-7"
37
+ - id: "agents-8"
35
38
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/tool-loop.md"
36
39
  title: "@happyvertical/smrt-chat packages/chat/agents/tool-loop.md"
37
40
  ---
@@ -48,6 +51,7 @@ sources:
48
51
  ## Documentation
49
52
 
50
53
  - `packages/chat/AGENTS.md`
54
+ - `packages/chat/agents/ai-unavailable.md`
51
55
  - `packages/chat/agents/assistant-questions.md`
52
56
  - `packages/chat/agents/dev-workbench.md`
53
57
  - `packages/chat/agents/overview-tools.md`
@@ -29,8 +29,10 @@ import { useI18n } from '@happyvertical/smrt-ui/i18n';
29
29
  import { Button } from '@happyvertical/smrt-ui/ui';
30
30
  import { type Component, type Snippet, tick, untrack } from 'svelte';
31
31
  import type { AssistantStatus } from '../../../assistant-turn-events.js';
32
+ import type { ChatUnavailableStatus } from '../../../client.js';
32
33
  import { M } from '../../i18n.js';
33
34
  import ToolCallDisplay from '../agent/ToolCallDisplay.svelte';
35
+ import AiUnavailableNotice from '../shared/AiUnavailableNotice.svelte';
34
36
  import ModelPicker from '../shared/ModelPicker.svelte';
35
37
  import AssistantChoiceCards from './AssistantChoiceCards.svelte';
36
38
  import AssistantComposer from './AssistantComposer.svelte';
@@ -250,6 +252,10 @@ export interface Props {
250
252
  /** The reply is being read aloud: hands-free listening pauses meanwhile;
251
253
  * see `AssistantComposer`. */
252
254
  speaking?: boolean;
255
+ /** Host route of its AI settings page (#4757). When a send is refused
256
+ * because AI is off or not set up (`ai_unavailable`), the dock shows
257
+ * "AI is off" with a link here instead of an error. */
258
+ aiSettingsHref?: string;
253
259
  }
254
260
 
255
261
  const {
@@ -290,9 +296,23 @@ const {
290
296
  sendOnPause = false,
291
297
  sendOnPauseMs,
292
298
  speaking = false,
299
+ aiSettingsHref,
293
300
  }: Props = $props();
294
301
  const { t } = useI18n();
295
302
 
303
+ // Set when the server answered `ai_unavailable` (#4757); cleared by the next
304
+ // successful send. Rendered as a notice with the host's settings link.
305
+ let aiUnavailable = $state<ChatUnavailableStatus | null>(null);
306
+
307
+ function noteUnavailable(error: unknown): boolean {
308
+ const status =
309
+ error && typeof error === 'object'
310
+ ? (error as { unavailable?: ChatUnavailableStatus }).unavailable
311
+ : undefined;
312
+ aiUnavailable = status?.reason ? status : null;
313
+ return aiUnavailable !== null;
314
+ }
315
+
296
316
  // Passed to the controller as getters (not direct values) so a later
297
317
  // reassignment of these bound props (e.g. a host swapping the transport or
298
318
  // registry instance) is actually observed, rather than only the value
@@ -605,7 +625,11 @@ async function handleAnswerQuestion(
605
625
  try {
606
626
  await controller.answerQuestion(messageId, question, values);
607
627
  } catch (error) {
608
- controller.setError(error instanceof Error ? error.message : String(error));
628
+ if (noteUnavailable(error)) controller.setError(null);
629
+ else
630
+ controller.setError(
631
+ error instanceof Error ? error.message : String(error),
632
+ );
609
633
  // The form learns it failed, so it stays answerable.
610
634
  throw error;
611
635
  }
@@ -624,8 +648,13 @@ async function handleSend(
624
648
  try {
625
649
  await controller.send(content, attachments);
626
650
  controller.setError(null);
651
+ aiUnavailable = null;
627
652
  } catch (error) {
628
- controller.setError(error instanceof Error ? error.message : String(error));
653
+ if (noteUnavailable(error)) controller.setError(null);
654
+ else
655
+ controller.setError(
656
+ error instanceof Error ? error.message : String(error),
657
+ );
629
658
  throw error;
630
659
  }
631
660
  }
@@ -722,6 +751,9 @@ async function handleConfirmAction(requestId: string) {
722
751
  {/if}
723
752
 
724
753
  <div class="assistant-dock-main">
754
+ {#if aiUnavailable}
755
+ <AiUnavailableNotice status={aiUnavailable} settingsHref={aiSettingsHref} />
756
+ {/if}
725
757
  {#if controller.error}
726
758
  <p class="assistant-dock-error" role="alert">
727
759
  {t(M['chat.assistant_dock.error'], { message: controller.error })}
@@ -166,6 +166,10 @@ export interface Props {
166
166
  /** The reply is being read aloud: hands-free listening pauses meanwhile;
167
167
  * see `AssistantComposer`. */
168
168
  speaking?: boolean;
169
+ /** Host route of its AI settings page (#4757). When a send is refused
170
+ * because AI is off or not set up (`ai_unavailable`), the dock shows
171
+ * "AI is off" with a link here instead of an error. */
172
+ aiSettingsHref?: string;
169
173
  }
170
174
  declare const AssistantDock: Component<Props, {}, "">;
171
175
  type AssistantDock = ReturnType<typeof AssistantDock>;