@happyvertical/smrt-chat 0.57.44 → 0.57.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +3 -0
- package/agents/tool-loop.md +11 -0
- package/dist/assistant-turn.d.ts +11 -0
- package/dist/assistant-turn.d.ts.map +1 -1
- package/dist/chunks/{chat-stream-Co_jCIyx.js → chat-stream-CL2kxpWo.js} +66 -43
- package/dist/chunks/chat-stream-CL2kxpWo.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/manifest.json +1 -1
- package/dist/smrt-knowledge.json +7 -7
- package/dist/svelte/components/assistant/AssistantDock.svelte +93 -2
- package/dist/svelte/components/assistant/AssistantDock.svelte.d.ts +17 -0
- package/dist/svelte/components/assistant/AssistantDock.svelte.d.ts.map +1 -1
- package/dist/svelte/components/assistant/assistant-markdown.d.ts +24 -0
- package/dist/svelte/components/assistant/assistant-markdown.d.ts.map +1 -0
- package/dist/svelte/components/assistant/assistant-markdown.js +197 -0
- package/dist/svelte/index.d.ts +1 -0
- package/dist/svelte/index.d.ts.map +1 -1
- package/dist/svelte/index.js +2 -0
- package/dist/sveltekit.d.ts +7 -0
- package/dist/sveltekit.d.ts.map +1 -1
- package/dist/sveltekit.js +3 -2
- package/dist/sveltekit.js.map +1 -1
- package/dist/tool-loop.d.ts +6 -0
- package/dist/tool-loop.d.ts.map +1 -1
- package/package.json +17 -17
- package/dist/chunks/chat-stream-Co_jCIyx.js.map +0 -1
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-
|
|
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-CL2kxpWo.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";
|
package/dist/manifest.json
CHANGED
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,16 +3,16 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-chat",
|
|
6
|
-
"packageVersion": "0.57.
|
|
6
|
+
"packageVersion": "0.57.46",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "0768597bd095973a16cdbe07a4f9c3b5daf31f2db2d6f6ce02b16d5ab5e21e64",
|
|
11
|
+
"packageJson": "9e262b414bd0ea780224ef8554b6228b82f41fd6d026febbc8e24519464edf49",
|
|
12
|
+
"agents": "44b54fd3a94f6f255b66032c138c81f120d4d8ba9fe219b45c5d926b3f22fcb3",
|
|
13
13
|
"moduleDoc:agents/dev-workbench.md": "f07a428519e8cca4a46371da0a3b33b9c8d3102f1d9056e4c8efba3c0b702048",
|
|
14
14
|
"moduleDoc:agents/overview-tools.md": "752a4afb6b57a2e9224f3c65a98b0deb23cda87371f01ac0566f0887e9bb12da",
|
|
15
|
-
"moduleDoc:agents/tool-loop.md": "
|
|
15
|
+
"moduleDoc:agents/tool-loop.md": "81ec1de9c5fac66b526ae8b2feeda8f33f1916cff19c4060f09989ce79b2acc1",
|
|
16
16
|
"moduleDoc:agents/token-streaming.md": "e92a28a8702d111a3751a86b8cdff30cb5146cc115fed86c227402bef1c683fd",
|
|
17
17
|
"moduleDoc:agents/assistant-questions.md": "a0371870b3bc99e313d8287912208f3e315bab7dc4ee138214895031ae79a5b0",
|
|
18
18
|
"moduleDoc:agents/recipes.md": "89c2c86e4e26cea9ba10d917f8ad71c23a71d4fd8eaacf638a6cd252e2376c07",
|
|
@@ -4513,7 +4513,7 @@
|
|
|
4513
4513
|
"polymorphicAssociations": 0,
|
|
4514
4514
|
"uuidColumns": 78
|
|
4515
4515
|
},
|
|
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\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",
|
|
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
4517
|
"moduleDocs": [
|
|
4518
4518
|
{
|
|
4519
4519
|
"path": "agents/dev-workbench.md",
|
|
@@ -4528,7 +4528,7 @@
|
|
|
4528
4528
|
{
|
|
4529
4529
|
"path": "agents/tool-loop.md",
|
|
4530
4530
|
"module": "tool-loop",
|
|
4531
|
-
"content": "# Tool loop termination and tool-call hygiene\n\n`runToolLoop()` (`src/tool-loop.ts`) runs one bounded\n`tool_call → observe → respond` turn. Both `runPersonaConversationTurn()` and\n`runAssistantTurn()` go through it, so every rule below holds for both.\n\n## Termination\n\n- Rounds that execute tools are capped by `maxSteps`\n (`DEFAULT_MAX_STEPS = 8`; `initialSteps` counts earlier legs of a resumed\n turn). `maxTotalTokens` (with `initialTokens`) and `deadline` end the turn\n early with `stoppedReason: 'budget'`.\n- **Forced final call (#4378).** At the cap, once the budget is spent, or\n after repeated calls (below, #4391), the next round is offered no tools (`tools: undefined`, `toolChoice: 'none'`),\n and any tool calls the model still emits are discarded. That call alone gets\n the fixed `TOOL_LOOP_ANSWER_NOW_INSTRUCTION` as a temporary `user`\n instruction. If the transcript already ends with a user turn, it is added\n to a copy of that turn's text or multimodal content instead of introducing\n consecutive user roles that strict templates reject. Otherwise it is a new\n user message. It never enters the returned `messages` transcript; input\n messages, stored conversations, and continuations stay unchanged.\n\n## Blank answers and timeouts (#4379)\n\n- **Retry once, within budget.** A final round with blank content and no\n usable tool calls (none made, or discarded on a no-tools round) is retried\n once without tools, with `TOOL_LOOP_ANSWER_NOW_INSTRUCTION` appended to\n that call only, and `emptyRetried: true`. The retry is skipped when the\n token budget (`maxTotalTokens`) or `deadline` is already spent: the turn\n goes straight to `empty`. The forced final call itself is one uncapped\n call, so a spent budget still gets one answer attempt; only the retry is\n budget-gated. Each blank round emits an `empty_round` step event (no model\n text; `retry` says whether a retry follows). `runAssistantTurn` does not\n show it as a dock step.\n- **Report.** Still blank: `stoppedReason: 'empty'`, `content: ''`. A model\n call that throws a timeout (`AI_TIMEOUT`, `TIMEOUT`, `REQUEST_TIMEOUT`,\n `TimeoutError`, or an `AbortError` the caller's signal did not cause) ends\n `stoppedReason: 'timeout'` instead of failing or passing as an empty\n success; other errors still throw. When the final round was the forced\n no-tools call, `capReason` (`max_steps` | `budget` | `repeated_calls`)\n keeps that cause alongside `empty`/`timeout`.\n- **Quiet stream ends (older SDKs).** SDKs <= 0.108.0 can end a timed-out\n stream quietly: no text, no tool calls, no finish reason. That shape is a\n suspected timeout only for an AI boundary that has already reported a\n finish reason in this process (so its absence is anomalous), and only when\n the retry ends the same way; then the turn is `timeout`. A boundary that\n never reports finish reasons, or a blank reply that has one, is `empty`.\n The \"has reported\" flag is kept per AI client object for the process\n lifetime, so one client that routes to providers with and without finish\n reasons can mislabel an `empty` turn as `timeout` (or the reverse).\n- **Timeouts are configurable, not derived.** `requestTimeoutMs` is\n forwarded as the per-call `timeout` (default: the provider's 120 s). It is\n not derived from `deadline`/`maxTurnMs`: those only stop new tool rounds\n and gate the retry.\n- **Fallback text.** Both callers store `resolveTurnReply(result,\n fallback)`: the content trimmed at its outer edges only (both paths\n alike; persona replies were stored untrimmed before), or\n `emptyAnswerFallback` / `DEFAULT_EMPTY_ANSWER_FALLBACK` when blank.\n `runPersonaConversationTurn` returns it as `reply` (plus `replyFallback`);\n voice and the chat stream use it. `runAssistantTurn` replaces its old\n `'Done.'`. The plain chat-stream path retries a blank stream once, then\n sends the fallback, or `CHAT_STREAM_TIMEOUT_ERROR` only under the\n quiet-end rule above.\n- **Provider errors (#4454).** A model call that throws is not answered by\n default (an `error` event, nothing stored). `runAssistantTurn` /\n `mountAssistantRoutes` take `providerErrorFallback`: text, or\n `(code, error) => text | undefined` (blank or `undefined` declines and the\n turn fails as before). The text is stored as the assistant row with\n `metadata.fallback: 'provider_error'` (so `isFallbackReply` is true and\n history skips it), the turn ends `stoppedReason: 'provider_error'`, and the\n error still goes to `onError`. A cancelled turn is never answered this way.\n- **Stored metadata.** Every authored assistant reply carries\n `replyMetadataFor(result, reply)`: `metadata.stoppedReason` (enum),\n `metadata.capReason` when set, and `metadata.fallback` (`empty` |\n `timeout` | `provider_error`) when the content is the fallback. Hosts read the stop reason\n from `turn.result.stoppedReason` (persona), `AssistantTurnResult` / the\n `done` event's `stoppedReason` and `capReason` (assistant), or the stored\n message's metadata. `isFallbackReply(message)` tells a fallback apart; the\n assistant route's and voice's history builders skip fallback replies so\n they are never replayed to the model as answers. The chat-stream paths\n (plain and persona) take history from the browser, which sends no\n metadata, so they recognise an assistant message whose text exactly\n equals the configured or default fallback text. All three replay the\n fixed `FALLBACK_HISTORY_PLACEHOLDER` in its place rather than dropping\n it: a drop would leave two user messages in a row, which strict chat\n templates (Gemma, Anthropic) reject. Hosts should hide feedback\n controls (thumbs, corrections) on a message where `isFallbackReply` is\n true: there is no model answer to rate.\n- **History budget (#4458).** `historyLimit` counts replayed turns, not\n raw rows, so persisted tool rows (`authorInvocation`, failed calls) never\n take a slot. The assistant route and voice pass `roles` to\n `getThreadMessages` / `getRoomMessages`, which filter in SQL: the read\n returns at most `limit` rows whatever the thread holds. A fallback reply\n is one replayed turn (its marker). The chat-stream paths cap the\n browser's array at `MAX_CHAT_STREAM_MESSAGES` kept messages, scanning\n back at most 10× that many entries. Threads holding only replayed roles\n see the same history as before.\n- **Dock.** The `done` event's `capReason` reaches the dock, which offers\n Continue for a `max_steps`/`budget` capped turn even when it ended `empty`\n or `timeout` (never for `repeated_calls`, #4391).\n- **Reasoning.** `AIResponse.reasoning` (newer SDKs, sdk#1459) is read\n defensively, capped at `MAX_TOOL_LOOP_REASONING_CHARS` code points, passed\n to `onReasoning` (forwarded by both callers; a throw is ignored) and\n returned as `result.reasoning` (the retry's, else the first round's).\n Reasoning can quote documents and tool results: send it only to logs with\n the same protection as the conversation. It is never persisted and never\n the answer unless the host opts in with `answerFromReasoning` — which\n stores raw chain-of-thought as the reply (`contentFromReasoning: true`).\n- **Budgets on the persona path.** `runPersonaConversationTurn` forwards\n `maxTotalTokens`, `deadline`, `toolChoice` and `requestTimeoutMs`\n (`runAssistantTurn` exposes them as `maxTurnTokens`/`maxTurnMs`).\n\n## Observation bounds\n\n- A server tool observation is serialized and capped at\n `MAX_SERVER_TOOL_OBSERVATION_CHARS` (16,000, the same bound as\n `MAX_CLIENT_TOOL_RESULT_CHARS` for browser results) before it enters the\n transcript (#4378). A longer one is cut and gets the fixed\n `SERVER_TOOL_OBSERVATION_TRUNCATED_MARKER`, which says the result is\n incomplete and tells the model to narrow the request (filter, fewer fields,\n a smaller page, or a count). The marker carries no tool output.\n- The cut never splits a surrogate pair (it keeps one unit fewer instead);\n browser results (`appendClientToolResults`) are cut the same way.\n- Only the model's copy is capped: `ToolInvocation.observation` (handed to\n `onInvocation`, persisted as tool messages, audited) keeps the full value.\n- A tool returning `undefined` observes `null`; an unserializable result\n observes `{\"error\":\"unserializable_result\"}` instead of throwing.\n\n## Argument hygiene (#4378)\n\nArguments the model sends are never dropped silently; each case below is an\n`invalid_request` observation the model can correct and retry. Messages are\nvalue-free: they name the accepted shape, never the model's values.\n\n- **Malformed JSON.** Raw arguments that do not parse to a JSON object\n (malformed JSON, an array, a scalar) fail with code\n `TOOL_ARGUMENTS_MALFORMED`; the tool does not run and the invocation's\n `args` is `{}`. Blank or `null` arguments are a no-argument call. A browser\n tool call with malformed arguments is answered in the transcript and never\n suspends the turn.\n- **Manifest `read`.** Accepts only `id` (string), `where` (object of\n equality filters), `limit` (integer >= 1) and `offset` (integer >= 0). This\n is stricter than before, where these were dropped or defaulted silently:\n an unknown key such as `filter`, a numeric `id`, a non-object `where`, and\n a fractional, zero or string `limit` (or a negative or fractional `offset`)\n now fail with a retryable `invalid_request` (`TOOL_ARGUMENTS_INVALID`)\n instead of listing every row. The offered schema says\n `additionalProperties: false` with `integer` `limit`/`offset` minimums.\n- **`data.query`** (`@happyvertical/smrt-agents`). With a `request` object,\n the only other top-level key allowed is `surfaceId`; a sibling such as\n `filter` fails with `DataSurfaceRequestError` reason\n `DATA_QUERY_ARGUMENTS_UNEXPECTED`, naming only misplaced grammar keys. The\n flat form (request keys beside `surfaceId`, no `request`) still works.\n- **`surfaceId` placement** (`data.query`, `data.inspect`). A\n `request.surfaceId` string is lifted to the top level and removed from\n `request`; a `query` object standing in for `request`, or one that is\n `request`'s only key, is unwrapped (its keys are then validated as usual,\n so nothing is dropped; unwrapping was chosen over rejecting because the\n intent is unambiguous). Two different ids are\n `DATA_QUERY_SURFACE_ID_CONFLICT`; no id at all is a 400\n `DATA_QUERY_SURFACE_ID_REQUIRED` with an example. Only an id naming no\n visible surface gets the generic \"not available\" denial. A filter `kind`\n that is an operator (`in`) or a logical word (`or`) gets a targeted hint.\n- **Valid examples.** Every `data.query` request error ends with a one-line\n `Valid example: {\"surfaceId\":…,\"request\":{…}}` for that surface, in the\n failed request's mode (count, rows or facets), built from the surface id\n and caller-visible field ids with `<value>` placeholders — never the\n caller's own values. Row examples cap page size at the surface’s\n `maxPageLimit`.\n\n## Dedupe of identical read-only calls (#4382)\n\nWithin one `runToolLoop` call, a server call that repeats an earlier one —\nsame tool, same arguments after canonicalization (object keys sorted) — is\nnot executed again. Its invocation has `deduped: true`, mirrors the earlier\n`ok`/`error`, and observes the fixed `TOOL_CALL_DEDUPED_NOTE` instead of a\nsecond copy of the result.\n\n- Only read-only, idempotent tools qualify: manifest `read`, and\n `data.discover`, `data.inspect`, `data.query`. Mutating tools,\n `agents.invoke`, other extra tools and browser tools never do; nor do\n malformed-argument calls.\n- **Invalidation.** Any resolved server call that is not on that allow-list\n (a write, `agents.invoke`, any other extra tool), whatever its result,\n clears every remembered read, so a read after a write always runs fresh.\n- A repeat of a rejected or refused call observes\n `TOOL_CALL_DEDUPED_REJECTED_NOTE` (repeating it will not work; fix the\n arguments) instead of the plain pointer note.\n- An earlier `execution_error` is not reused: a transient server failure\n may be retried. Arguments over 4,000 canonical characters are never keyed.\n- The cache holds at most `MAX_DEDUPED_CALLS_PER_TURN` (64) calls and lives\n only inside that `runToolLoop` call: never across turns (an assistant\n resume leg starts a fresh cache).\n- Deduped calls count toward the step cap: a round of repeats is still a\n round, so a model stuck repeating a call still stops at `maxSteps`.\n- The note points at the earlier result and says to change the arguments\n (for example, add a filter), because a repeat returns the same result.\n\n## Repeated calls end the tool phase (#4391)\n\nA model stuck on one call (an unfiltered count, sent again and again) used\nto burn every step to `maxSteps`. Now, once a single dedupe key (same tool,\nsame canonical arguments) has been deduped `maxRepeatedCalls` times in one\n`runToolLoop` call, the rest of that round still runs — every tool call gets\nits tool result — and the next model call is the forced no-tools call with\n`TOOL_LOOP_ANSWER_NOW_INSTRUCTION` plus, on this path only (and its blank\nretry), `TOOL_LOOP_REPEATED_CALLS_INSTRUCTION`: if the results do not match\nwhat was asked (a total where a filtered count was asked), say the figure\ncould not be got rather than presenting the result as the answer.\n\n- **Option.** `maxRepeatedCalls` on `runToolLoop`, `runAssistantTurn`,\n `runPersonaConversationTurn` and `mountAssistantRoutes`. Default\n `DEFAULT_MAX_REPEATED_CALLS` (2); `0` (or less) turns it off; otherwise it\n is floored and capped at `MAX_REPEATED_CALLS_LIMIT` (16). Non-numbers use\n the default.\n- **What counts.** Only deduped repeats, counted per key: a different\n argument is a different key, mutating and other non-dedupable calls never\n count, and a non-read-only call clears the counts with the dedupe cache.\n Counts live inside one `runToolLoop` call; an assistant resume leg starts\n at zero.\n- **Report.** `stoppedReason: 'repeated_calls'` and `capReason:\n 'repeated_calls'`; `capReason` stays when the forced call then ends `empty`\n or `timeout`. When the step cap or budget is reached in the same round,\n `repeated_calls` wins: more steps would only repeat the call. Stored\n replies carry it in `metadata.stoppedReason`/`metadata.capReason`, like the\n other caps; the `done` event carries both.\n- **Dock: no Continue.** The dock records `run.stoppedReason:\n 'repeated_calls'` but does not offer Continue (`waitingFor` stays null):\n the model already had the result it kept asking for, so another leg would\n repeat the call. Continue stays for `max_steps` and `budget` only. Hosts\n with their own UI should do the same.\n- The audit sink gets `action: 'chat.tool_call_deduped'` (not a fresh\n execution or failure); the persona path's tool row carries\n `toolCallData.deduped: true`.\n\n## Failed calls are persisted (#4383)\n\nEvery tool invocation records `modelContent`, the exact (capped) text the\nmodel was shown. `toolFailureRecord(invocation)` turns a failed, rejected or\ndenied call into a bounded record: `name`, `args` (over\n`MAX_TOOL_FAILURE_ARGS_CHARS` = 2,000 serialized characters they become\n`{ truncated: true }`; unserializable ones `{ unserializable: true }`;\nmalformed-JSON calls carry `{}`), `status` (`rejected` | `error`),\n`errorKind`, `errorCode` (the error's own stable `A-Z0-9_` code, else the\nkind) and `shown`. Like a successful call's row it carries the arguments\nand shown text, so it is not value-free. A deduped repeat has no record.\n\n- `runPersonaConversationTurn` authors each failed call as a `tool_result`\n row: content = `shown`, `toolCallData` `{ name, args, status, errorCode }`,\n `metadata` `{ toolStatus, errorKind, errorCode }`.\n- `runAssistantTurn` now does the same **by default** when an `author` is\n set — a behaviour change: before, failed calls were never persisted.\n `author.authorFailedInvocation` overrides the row or returns `null` to\n skip it; `authorInvocation` sees successful calls only (never a failed or\n deduped-failed one). A failed row's write error is not a dock step.\n- `runToolLoop` sends the audit sink `action: 'chat.tool_call_failed'` with\n only `toolFailureAuditMetadata(record)`: `name`, `status`, `errorKind`,\n `errorCode`, `argsChars`, `shownChars` — never the arguments or the shown\n text, which can hold user data or raw server errors. A sink throw never\n fails the turn.\n- A browser tool call with malformed arguments is recorded the same way (an\n invocation, an audit entry, `onInvocation`), besides being answered in\n the transcript.\n- Gap: a call to a tool the session does not allow-list cannot be a tool row\n — `sendAgentReply`'s authoring gate refuses the name, and that gate is\n unchanged — so it reaches the audit sink only.\n\n## Tool errors\n\nA thrown tool error is classified by `classifyToolError`: permission denials\nand 401/403 are `not_permitted` (reported as a rejection); a `ValidationError`\nor 400/404/409/422 is `invalid_request` (observation: the actionable message,\n`publicMessage` first, its `code`, and a fix-and-retry hint); everything else,\nincluding 429, is `execution_error`. An `execution_error` observation\ncarries the error's message, its stable `code` when it has one (e.g.\n`DATA_SURFACE_QUERY_FAILED`), and the fixed `TOOL_EXECUTION_ERROR_HINT`:\nthe failure is the server's, so the model should not resend the same call\nbut answer with what it has or tell the user (#4378).\n"
|
|
4531
|
+
"content": "# Tool loop termination and tool-call hygiene\n\n`runToolLoop()` (`src/tool-loop.ts`) runs one bounded\n`tool_call → observe → respond` turn. Both `runPersonaConversationTurn()` and\n`runAssistantTurn()` go through it, so every rule below holds for both.\n\n## Termination\n\n- Rounds that execute tools are capped by `maxSteps`\n (`DEFAULT_MAX_STEPS = 8`; `initialSteps` counts earlier legs of a resumed\n turn). `maxTotalTokens` (with `initialTokens`) and `deadline` end the turn\n early with `stoppedReason: 'budget'`.\n- **Forced final call (#4378).** At the cap, once the budget is spent, or\n after repeated calls (below, #4391), the next round is offered no tools (`tools: undefined`, `toolChoice: 'none'`),\n and any tool calls the model still emits are discarded. That call alone gets\n the fixed `TOOL_LOOP_ANSWER_NOW_INSTRUCTION` as a temporary `user`\n instruction. If the transcript already ends with a user turn, it is added\n to a copy of that turn's text or multimodal content instead of introducing\n consecutive user roles that strict templates reject. Otherwise it is a new\n user message. It never enters the returned `messages` transcript; input\n messages, stored conversations, and continuations stay unchanged.\n\n## Blank answers and timeouts (#4379)\n\n- **Retry once, within budget.** A final round with blank content and no\n usable tool calls (none made, or discarded on a no-tools round) is retried\n once without tools, with `TOOL_LOOP_ANSWER_NOW_INSTRUCTION` appended to\n that call only, and `emptyRetried: true`. The retry is skipped when the\n token budget (`maxTotalTokens`) or `deadline` is already spent: the turn\n goes straight to `empty`. The forced final call itself is one uncapped\n call, so a spent budget still gets one answer attempt; only the retry is\n budget-gated. Each blank round emits an `empty_round` step event (no model\n text; `retry` says whether a retry follows). `runAssistantTurn` does not\n show it as a dock step.\n- **Report.** Still blank: `stoppedReason: 'empty'`, `content: ''`. A model\n call that throws a timeout (`AI_TIMEOUT`, `TIMEOUT`, `REQUEST_TIMEOUT`,\n `TimeoutError`, or an `AbortError` the caller's signal did not cause) ends\n `stoppedReason: 'timeout'` instead of failing or passing as an empty\n success; other errors still throw. When the final round was the forced\n no-tools call, `capReason` (`max_steps` | `budget` | `repeated_calls`)\n keeps that cause alongside `empty`/`timeout`.\n- **Quiet stream ends (older SDKs).** SDKs <= 0.108.0 can end a timed-out\n stream quietly: no text, no tool calls, no finish reason. That shape is a\n suspected timeout only for an AI boundary that has already reported a\n finish reason in this process (so its absence is anomalous), and only when\n the retry ends the same way; then the turn is `timeout`. A boundary that\n never reports finish reasons, or a blank reply that has one, is `empty`.\n The \"has reported\" flag is kept per AI client object for the process\n lifetime, so one client that routes to providers with and without finish\n reasons can mislabel an `empty` turn as `timeout` (or the reverse).\n- **Timeouts are configurable, not derived.** `requestTimeoutMs` is\n forwarded as the per-call `timeout` (default: the provider's 120 s). It is\n not derived from `deadline`/`maxTurnMs`: those only stop new tool rounds\n and gate the retry.\n- **Fallback text.** Both callers store `resolveTurnReply(result,\n fallback)`: the content trimmed at its outer edges only (both paths\n alike; persona replies were stored untrimmed before), or\n `emptyAnswerFallback` / `DEFAULT_EMPTY_ANSWER_FALLBACK` when blank.\n `runPersonaConversationTurn` returns it as `reply` (plus `replyFallback`);\n voice and the chat stream use it. `runAssistantTurn` replaces its old\n `'Done.'`. The plain chat-stream path retries a blank stream once, then\n sends the fallback, or `CHAT_STREAM_TIMEOUT_ERROR` only under the\n quiet-end rule above.\n- **Provider errors (#4454).** A model call that throws is not answered by\n default (an `error` event, nothing stored). `runAssistantTurn` /\n `mountAssistantRoutes` take `providerErrorFallback`: text, or\n `(code, error) => text | undefined` (blank or `undefined` declines and the\n turn fails as before). The text is stored as the assistant row with\n `metadata.fallback: 'provider_error'` (so `isFallbackReply` is true and\n history skips it), the turn ends `stoppedReason: 'provider_error'`, and the\n error still goes to `onError`. A cancelled turn is never answered this way.\n- **Stored metadata.** Every authored assistant reply carries\n `replyMetadataFor(result, reply)`: `metadata.stoppedReason` (enum),\n `metadata.capReason` when set, and `metadata.fallback` (`empty` |\n `timeout` | `provider_error`) when the content is the fallback. Hosts read the stop reason\n from `turn.result.stoppedReason` (persona), `AssistantTurnResult` / the\n `done` event's `stoppedReason` and `capReason` (assistant), or the stored\n message's metadata. `isFallbackReply(message)` tells a fallback apart; the\n assistant route's and voice's history builders skip fallback replies so\n they are never replayed to the model as answers. The chat-stream paths\n (plain and persona) take history from the browser, which sends no\n metadata, so they recognise an assistant message whose text exactly\n equals the configured or default fallback text. All three replay the\n fixed `FALLBACK_HISTORY_PLACEHOLDER` in its place rather than dropping\n it: a drop would leave two user messages in a row, which strict chat\n templates (Gemma, Anthropic) reject. Hosts should hide feedback\n controls (thumbs, corrections) on a message where `isFallbackReply` is\n true: there is no model answer to rate.\n- **History budget (#4458).** `historyLimit` counts replayed turns, not\n raw rows, so persisted tool rows (`authorInvocation`, failed calls) never\n take a slot. The assistant route and voice pass `roles` to\n `getThreadMessages` / `getRoomMessages`, which filter in SQL: the read\n returns at most `limit` rows whatever the thread holds. A fallback reply\n is one replayed turn (its marker). The chat-stream paths cap the\n browser's array at `MAX_CHAT_STREAM_MESSAGES` kept messages, scanning\n back at most 10× that many entries. Threads holding only replayed roles\n see the same history as before.\n- **Dock.** The `done` event's `capReason` reaches the dock, which offers\n Continue for a `max_steps`/`budget` capped turn even when it ended `empty`\n or `timeout` (never for `repeated_calls`, #4391).\n- **Reasoning.** `AIResponse.reasoning` (newer SDKs, sdk#1459) is read\n defensively, capped at `MAX_TOOL_LOOP_REASONING_CHARS` code points, passed\n to `onReasoning` (forwarded by both callers; a throw is ignored) and\n returned as `result.reasoning` (the retry's, else the first round's).\n Reasoning can quote documents and tool results: send it only to logs with\n the same protection as the conversation. It is never persisted and never\n the answer unless the host opts in with `answerFromReasoning` — which\n stores raw chain-of-thought as the reply (`contentFromReasoning: true`).\n- **Budgets on the persona path.** `runPersonaConversationTurn` forwards\n `maxTotalTokens`, `deadline`, `toolChoice` and `requestTimeoutMs`\n (`runAssistantTurn` exposes them as `maxTurnTokens`/`maxTurnMs`).\n\n## Observation bounds\n\n- A server tool observation is serialized and capped at\n `MAX_SERVER_TOOL_OBSERVATION_CHARS` (16,000, the same bound as\n `MAX_CLIENT_TOOL_RESULT_CHARS` for browser results) before it enters the\n transcript (#4378). A longer one is cut and gets the fixed\n `SERVER_TOOL_OBSERVATION_TRUNCATED_MARKER`, which says the result is\n incomplete and tells the model to narrow the request (filter, fewer fields,\n a smaller page, or a count). The marker carries no tool output.\n- The cut never splits a surrogate pair (it keeps one unit fewer instead);\n browser results (`appendClientToolResults`) are cut the same way.\n- Only the model's copy is capped: `ToolInvocation.observation` (handed to\n `onInvocation`, persisted as tool messages, audited) keeps the full value.\n- A tool returning `undefined` observes `null`; an unserializable result\n observes `{\"error\":\"unserializable_result\"}` instead of throwing.\n\n## Argument hygiene (#4378)\n\nArguments the model sends are never dropped silently; each case below is an\n`invalid_request` observation the model can correct and retry. Messages are\nvalue-free: they name the accepted shape, never the model's values.\n\n- **Malformed JSON.** Raw arguments that do not parse to a JSON object\n (malformed JSON, an array, a scalar) fail with code\n `TOOL_ARGUMENTS_MALFORMED`; the tool does not run and the invocation's\n `args` is `{}`. Blank or `null` arguments are a no-argument call. A browser\n tool call with malformed arguments is answered in the transcript and never\n suspends the turn.\n- **Manifest `read`.** Accepts only `id` (string), `where` (object of\n equality filters), `limit` (integer >= 1) and `offset` (integer >= 0). This\n is stricter than before, where these were dropped or defaulted silently:\n an unknown key such as `filter`, a numeric `id`, a non-object `where`, and\n a fractional, zero or string `limit` (or a negative or fractional `offset`)\n now fail with a retryable `invalid_request` (`TOOL_ARGUMENTS_INVALID`)\n instead of listing every row. The offered schema says\n `additionalProperties: false` with `integer` `limit`/`offset` minimums.\n- **`data.query`** (`@happyvertical/smrt-agents`). With a `request` object,\n the only other top-level key allowed is `surfaceId`; a sibling such as\n `filter` fails with `DataSurfaceRequestError` reason\n `DATA_QUERY_ARGUMENTS_UNEXPECTED`, naming only misplaced grammar keys. The\n flat form (request keys beside `surfaceId`, no `request`) still works.\n- **`surfaceId` placement** (`data.query`, `data.inspect`). A\n `request.surfaceId` string is lifted to the top level and removed from\n `request`; a `query` object standing in for `request`, or one that is\n `request`'s only key, is unwrapped (its keys are then validated as usual,\n so nothing is dropped; unwrapping was chosen over rejecting because the\n intent is unambiguous). Two different ids are\n `DATA_QUERY_SURFACE_ID_CONFLICT`; no id at all is a 400\n `DATA_QUERY_SURFACE_ID_REQUIRED` with an example. Only an id naming no\n visible surface gets the generic \"not available\" denial. A filter `kind`\n that is an operator (`in`) or a logical word (`or`) gets a targeted hint.\n- **Valid examples.** Every `data.query` request error ends with a one-line\n `Valid example: {\"surfaceId\":…,\"request\":{…}}` for that surface, in the\n failed request's mode (count, rows or facets), built from the surface id\n and caller-visible field ids with `<value>` placeholders — never the\n caller's own values. Row examples cap page size at the surface’s\n `maxPageLimit`.\n\n## Dedupe of identical read-only calls (#4382)\n\nWithin one `runToolLoop` call, a server call that repeats an earlier one —\nsame tool, same arguments after canonicalization (object keys sorted) — is\nnot executed again. Its invocation has `deduped: true`, mirrors the earlier\n`ok`/`error`, and observes the fixed `TOOL_CALL_DEDUPED_NOTE` instead of a\nsecond copy of the result.\n\n- Only read-only, idempotent tools qualify: manifest `read`, and\n `data.discover`, `data.inspect`, `data.query`. Mutating tools,\n `agents.invoke`, other extra tools and browser tools never do; nor do\n malformed-argument calls.\n- **Invalidation.** Any resolved server call that is not on that allow-list\n (a write, `agents.invoke`, any other extra tool), whatever its result,\n clears every remembered read, so a read after a write always runs fresh.\n- A repeat of a rejected or refused call observes\n `TOOL_CALL_DEDUPED_REJECTED_NOTE` (repeating it will not work; fix the\n arguments) instead of the plain pointer note.\n- An earlier `execution_error` is not reused: a transient server failure\n may be retried. Arguments over 4,000 canonical characters are never keyed.\n- The cache holds at most `MAX_DEDUPED_CALLS_PER_TURN` (64) calls and lives\n only inside that `runToolLoop` call: never across turns (an assistant\n resume leg starts a fresh cache).\n- Deduped calls count toward the step cap: a round of repeats is still a\n round, so a model stuck repeating a call still stops at `maxSteps`.\n- The note points at the earlier result and says to change the arguments\n (for example, add a filter), because a repeat returns the same result.\n\n## Repeated calls end the tool phase (#4391)\n\nA model stuck on one call (an unfiltered count, sent again and again) used\nto burn every step to `maxSteps`. Now, once a single dedupe key (same tool,\nsame canonical arguments) has been deduped `maxRepeatedCalls` times in one\n`runToolLoop` call, the rest of that round still runs — every tool call gets\nits tool result — and the next model call is the forced no-tools call with\n`TOOL_LOOP_ANSWER_NOW_INSTRUCTION` plus, on this path only (and its blank\nretry), `TOOL_LOOP_REPEATED_CALLS_INSTRUCTION`: if the results do not match\nwhat was asked (a total where a filtered count was asked), say the figure\ncould not be got rather than presenting the result as the answer.\n\n- **Option.** `maxRepeatedCalls` on `runToolLoop`, `runAssistantTurn`,\n `runPersonaConversationTurn` and `mountAssistantRoutes`. Default\n `DEFAULT_MAX_REPEATED_CALLS` (2); `0` (or less) turns it off; otherwise it\n is floored and capped at `MAX_REPEATED_CALLS_LIMIT` (16). Non-numbers use\n the default.\n- **What counts.** Only deduped repeats, counted per key: a different\n argument is a different key, mutating and other non-dedupable calls never\n count, and a non-read-only call clears the counts with the dedupe cache.\n Counts live inside one `runToolLoop` call; an assistant resume leg starts\n at zero.\n- **Report.** `stoppedReason: 'repeated_calls'` and `capReason:\n 'repeated_calls'`; `capReason` stays when the forced call then ends `empty`\n or `timeout`. When the step cap or budget is reached in the same round,\n `repeated_calls` wins: more steps would only repeat the call. Stored\n replies carry it in `metadata.stoppedReason`/`metadata.capReason`, like the\n other caps; the `done` event carries both.\n- **Dock: no Continue.** The dock records `run.stoppedReason:\n 'repeated_calls'` but does not offer Continue (`waitingFor` stays null):\n the model already had the result it kept asking for, so another leg would\n repeat the call. Continue stays for `max_steps` and `budget` only. Hosts\n with their own UI should do the same.\n- The audit sink gets `action: 'chat.tool_call_deduped'` (not a fresh\n execution or failure); the persona path's tool row carries\n `toolCallData.deduped: true`.\n\n## Failed calls are persisted (#4383)\n\nEvery tool invocation records `modelContent`, the exact (capped) text the\nmodel was shown. `toolFailureRecord(invocation)` turns a failed, rejected or\ndenied call into a bounded record: `name`, `args` (over\n`MAX_TOOL_FAILURE_ARGS_CHARS` = 2,000 serialized characters they become\n`{ truncated: true }`; unserializable ones `{ unserializable: true }`;\nmalformed-JSON calls carry `{}`), `status` (`rejected` | `error`),\n`errorKind`, `errorCode` (the error's own stable `A-Z0-9_` code, else the\nkind) and `shown`. Like a successful call's row it carries the arguments\nand shown text, so it is not value-free. A deduped repeat has no record.\nA validation-class failure — `errorKind` `invalid_request` on a call that was\nnot a denial, i.e. the tool refused arguments the model can fix (#4505) —\nalso carries `recoverable: true`; both authoring paths copy it onto the row's\n`toolCallData` and `metadata`. Other failures omit it.\n\n- `runPersonaConversationTurn` authors each failed call as a `tool_result`\n row: content = `shown`, `toolCallData` `{ name, args, status, errorCode }`,\n `metadata` `{ toolStatus, errorKind, errorCode }`.\n- `runAssistantTurn` now does the same **by default** when an `author` is\n set — a behaviour change: before, failed calls were never persisted.\n `author.authorFailedInvocation` overrides the row or returns `null` to\n skip it; `authorInvocation` sees successful calls only (never a failed or\n deduped-failed one). A failed row's write error is not a dock step.\n- `author.collapseRecoveredFailures` (`mountAssistantRoutes`\n `collapseRecoveredFailures`; default `false`, #4505) holds each\n `recoverable` failure until the tool loop ends, drops it when a later call\n of the same tool in the same turn succeeded, and otherwise persists it then,\n in call order, before the reply. Denials and execution errors are never\n held; the audit sink still gets every failure; the dock's live tool steps\n are unchanged. The persona path is not affected.\n- `runToolLoop` sends the audit sink `action: 'chat.tool_call_failed'` with\n only `toolFailureAuditMetadata(record)`: `name`, `status`, `errorKind`,\n `errorCode`, `argsChars`, `shownChars` — never the arguments or the shown\n text, which can hold user data or raw server errors. A sink throw never\n fails the turn.\n- A browser tool call with malformed arguments is recorded the same way (an\n invocation, an audit entry, `onInvocation`), besides being answered in\n the transcript.\n- Gap: a call to a tool the session does not allow-list cannot be a tool row\n — `sendAgentReply`'s authoring gate refuses the name, and that gate is\n unchanged — so it reaches the audit sink only.\n\n## Tool errors\n\nA thrown tool error is classified by `classifyToolError`: permission denials\nand 401/403 are `not_permitted` (reported as a rejection); a `ValidationError`\nor 400/404/409/422 is `invalid_request` (observation: the actionable message,\n`publicMessage` first, its `code`, and a fix-and-retry hint); everything else,\nincluding 429, is `execution_error`. An `execution_error` observation\ncarries the error's message, its stable `code` when it has one (e.g.\n`DATA_SURFACE_QUERY_FAILED`), and the fixed `TOOL_EXECUTION_ERROR_HINT`:\nthe failure is the server's, so the model should not resend the same call\nbut answer with what it has or tell the user (#4378).\n"
|
|
4532
4532
|
},
|
|
4533
4533
|
{
|
|
4534
4534
|
"path": "agents/token-streaming.md",
|
|
@@ -38,6 +38,7 @@ import AssistantQuestionForm from './AssistantQuestionForm.svelte';
|
|
|
38
38
|
import AssistantThreadList from './AssistantThreadList.svelte';
|
|
39
39
|
import { toolCallStatusForAction } from './action-status.js';
|
|
40
40
|
import type { AssistantChoiceSourceRegistry } from './assistant-choices.svelte.js';
|
|
41
|
+
import { renderAssistantMarkdown } from './assistant-markdown.js';
|
|
41
42
|
import {
|
|
42
43
|
type AssistantQuestion,
|
|
43
44
|
type AssistantQuestionAnswer,
|
|
@@ -157,6 +158,20 @@ export interface Props {
|
|
|
157
158
|
toolResultComponent?: (
|
|
158
159
|
message: AssistantMessage,
|
|
159
160
|
) => Component<{ message: AssistantMessage }> | undefined;
|
|
161
|
+
/** How an assistant message's text renders (#4505). `'text'` (default)
|
|
162
|
+
* shows it verbatim, as before. `'markdown'` renders paragraphs, headings
|
|
163
|
+
* (`#`–`###`), lists, fenced and inline code, bold/italic and http(s) links
|
|
164
|
+
* through the package's escaping renderer (`renderAssistantMarkdown`): all
|
|
165
|
+
* input HTML is escaped, so model text can never inject markup. Applies to
|
|
166
|
+
* stored assistant messages and the streaming reply; user, system and tool
|
|
167
|
+
* messages stay plain text. */
|
|
168
|
+
messageFormat?: 'text' | 'markdown';
|
|
169
|
+
/** Host renderer for an assistant message's text (#4505), used instead of
|
|
170
|
+
* `messageFormat` inside the message bubble. `streaming` is `true` for the
|
|
171
|
+
* in-progress reply, whose `message` is a stand-in with the text so far
|
|
172
|
+
* (`id` `'assistant-dock-streaming'`). Attachments, question forms and the
|
|
173
|
+
* `toolCall` region still render around it. */
|
|
174
|
+
renderMessage?: Snippet<[{ message: AssistantMessage; streaming: boolean }]>;
|
|
160
175
|
/** Hands the host this dock's own controller once, on mount (#2989), so it
|
|
161
176
|
* can propose an action with `controller.previewAction(request)`. The
|
|
162
177
|
* proposal renders with Confirm/Reject like any other; everything else
|
|
@@ -250,6 +265,8 @@ const {
|
|
|
250
265
|
threadList = true,
|
|
251
266
|
toolCall,
|
|
252
267
|
toolResultComponent,
|
|
268
|
+
messageFormat = 'text',
|
|
269
|
+
renderMessage,
|
|
253
270
|
oncontroller,
|
|
254
271
|
onactionapplied,
|
|
255
272
|
onactionsettled,
|
|
@@ -658,6 +675,20 @@ async function handleConfirmAction(requestId: string) {
|
|
|
658
675
|
}
|
|
659
676
|
</script>
|
|
660
677
|
|
|
678
|
+
{#snippet assistantText(message: AssistantMessage, streaming: boolean)}
|
|
679
|
+
{#if renderMessage}
|
|
680
|
+
{@render renderMessage({ message, streaming })}
|
|
681
|
+
{:else if messageFormat === 'markdown'}
|
|
682
|
+
<!-- Only the escaping renderer's output is injected (#4505): it escapes
|
|
683
|
+
all input HTML and emits a fixed tag set with checked http(s) hrefs. -->
|
|
684
|
+
<div class="assistant-dock-message-content assistant-dock-markdown">
|
|
685
|
+
{@html renderAssistantMarkdown(message.content)}
|
|
686
|
+
</div>
|
|
687
|
+
{:else}
|
|
688
|
+
<p class="assistant-dock-message-content">{message.content}</p>
|
|
689
|
+
{/if}
|
|
690
|
+
{/snippet}
|
|
691
|
+
|
|
661
692
|
<div class="assistant-dock" data-smrt-component="AssistantDock">
|
|
662
693
|
<div
|
|
663
694
|
class="assistant-dock-layout"
|
|
@@ -841,7 +872,11 @@ async function handleConfirmAction(requestId: string) {
|
|
|
841
872
|
own={message.role === 'user'}
|
|
842
873
|
>
|
|
843
874
|
{#snippet children()}
|
|
844
|
-
|
|
875
|
+
{#if message.role === 'assistant'}
|
|
876
|
+
{@render assistantText(message, false)}
|
|
877
|
+
{:else}
|
|
878
|
+
<p class="assistant-dock-message-content">{message.content}</p>
|
|
879
|
+
{/if}
|
|
845
880
|
{#if message.attachments && message.attachments.length > 0}
|
|
846
881
|
<ul
|
|
847
882
|
class="assistant-dock-attachments"
|
|
@@ -904,7 +939,16 @@ async function handleConfirmAction(requestId: string) {
|
|
|
904
939
|
>
|
|
905
940
|
<MessageBubble variant="agent" own={false}>
|
|
906
941
|
{#snippet children()}
|
|
907
|
-
|
|
942
|
+
{@render assistantText(
|
|
943
|
+
{
|
|
944
|
+
id: 'assistant-dock-streaming',
|
|
945
|
+
threadId: controller.activeThreadId ?? '',
|
|
946
|
+
role: 'assistant',
|
|
947
|
+
content: controller.streamingText,
|
|
948
|
+
createdAt: '',
|
|
949
|
+
},
|
|
950
|
+
true,
|
|
951
|
+
)}
|
|
908
952
|
{/snippet}
|
|
909
953
|
</MessageBubble>
|
|
910
954
|
</div>
|
|
@@ -1360,6 +1404,53 @@ async function handleConfirmAction(requestId: string) {
|
|
|
1360
1404
|
white-space: pre-wrap;
|
|
1361
1405
|
}
|
|
1362
1406
|
|
|
1407
|
+
/* Markdown answers (#4505): block spacing comes from the elements, and the
|
|
1408
|
+
rendered HTML is not scoped, so its rules are :global under the wrapper. */
|
|
1409
|
+
.assistant-dock-markdown {
|
|
1410
|
+
white-space: normal;
|
|
1411
|
+
overflow-wrap: anywhere;
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
.assistant-dock-markdown :global(:is(p, ul, ol, pre, h1, h2, h3)) {
|
|
1415
|
+
margin: 0 0 var(--smrt-spacing-2);
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
.assistant-dock-markdown :global(:is(p, ul, ol, pre, h1, h2, h3):last-child) {
|
|
1419
|
+
margin-bottom: 0;
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
.assistant-dock-markdown :global(:is(h1, h2, h3)) {
|
|
1423
|
+
font-size: 1em;
|
|
1424
|
+
font-weight: var(--smrt-typography-weight-semibold, 600);
|
|
1425
|
+
line-height: inherit;
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
.assistant-dock-markdown :global(h1) {
|
|
1429
|
+
font-size: 1.15em;
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
.assistant-dock-markdown :global(:is(ul, ol)) {
|
|
1433
|
+
padding-inline-start: 1.25em;
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
.assistant-dock-markdown :global(code) {
|
|
1437
|
+
font-family: var(--smrt-font-family-mono, ui-monospace, monospace);
|
|
1438
|
+
font-size: 0.9em;
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
.assistant-dock-markdown :global(pre) {
|
|
1442
|
+
overflow-x: auto;
|
|
1443
|
+
white-space: pre;
|
|
1444
|
+
padding: var(--smrt-spacing-2);
|
|
1445
|
+
border-radius: var(--smrt-radius-sm);
|
|
1446
|
+
background: var(--smrt-color-surface-container-low);
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
.assistant-dock-markdown :global(a) {
|
|
1450
|
+
color: inherit;
|
|
1451
|
+
text-decoration: underline;
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1363
1454
|
.assistant-dock-attachments {
|
|
1364
1455
|
list-style: none;
|
|
1365
1456
|
margin: var(--smrt-spacing-2) 0 0;
|
|
@@ -77,6 +77,23 @@ export interface Props {
|
|
|
77
77
|
toolResultComponent?: (message: AssistantMessage) => Component<{
|
|
78
78
|
message: AssistantMessage;
|
|
79
79
|
}> | undefined;
|
|
80
|
+
/** How an assistant message's text renders (#4505). `'text'` (default)
|
|
81
|
+
* shows it verbatim, as before. `'markdown'` renders paragraphs, headings
|
|
82
|
+
* (`#`–`###`), lists, fenced and inline code, bold/italic and http(s) links
|
|
83
|
+
* through the package's escaping renderer (`renderAssistantMarkdown`): all
|
|
84
|
+
* input HTML is escaped, so model text can never inject markup. Applies to
|
|
85
|
+
* stored assistant messages and the streaming reply; user, system and tool
|
|
86
|
+
* messages stay plain text. */
|
|
87
|
+
messageFormat?: 'text' | 'markdown';
|
|
88
|
+
/** Host renderer for an assistant message's text (#4505), used instead of
|
|
89
|
+
* `messageFormat` inside the message bubble. `streaming` is `true` for the
|
|
90
|
+
* in-progress reply, whose `message` is a stand-in with the text so far
|
|
91
|
+
* (`id` `'assistant-dock-streaming'`). Attachments, question forms and the
|
|
92
|
+
* `toolCall` region still render around it. */
|
|
93
|
+
renderMessage?: Snippet<[{
|
|
94
|
+
message: AssistantMessage;
|
|
95
|
+
streaming: boolean;
|
|
96
|
+
}]>;
|
|
80
97
|
/** Hands the host this dock's own controller once, on mount (#2989), so it
|
|
81
98
|
* can propose an action with `controller.previewAction(request)`. The
|
|
82
99
|
* proposal renders with Confirm/Reject like any other; everything else
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantDock.svelte.d.ts","sourceRoot":"","sources":["../../../../src/svelte/components/assistant/AssistantDock.svelte.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,wBAAwB,EACxB,uBAAuB,EACvB,mBAAmB,EACnB,mBAAmB,EACpB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,KAAK,EACV,uBAAuB,EACvB,mBAAmB,EACnB,uBAAuB,EACvB,mBAAmB,EACpB,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EAAE,KAAK,SAAS,EAAE,KAAK,OAAO,EAAiB,MAAM,QAAQ,CAAC;AACrE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AASzE,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"AssistantDock.svelte.d.ts","sourceRoot":"","sources":["../../../../src/svelte/components/assistant/AssistantDock.svelte.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,wBAAwB,EACxB,uBAAuB,EACvB,mBAAmB,EACnB,mBAAmB,EACpB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,KAAK,EACV,uBAAuB,EACvB,mBAAmB,EACnB,uBAAuB,EACvB,mBAAmB,EACpB,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EAAE,KAAK,SAAS,EAAE,KAAK,OAAO,EAAiB,MAAM,QAAQ,CAAC;AACrE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AASzE,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AAOnF,OAAO,KAAK,EAEV,gBAAgB,EAChB,kBAAkB,EACnB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAC9B,KAAK,yBAAyB,EAE/B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,EAC3B,KAAK,uBAAuB,EAC5B,KAAK,YAAY,EAElB,MAAM,8CAA8C,CAAC;AAGtD,MAAM,WAAW,KAAK;IACpB,kFAAkF;IAClF,WAAW,CAAC,EAAE,SAAS;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC3D,kEAAkE;IAClE,SAAS,EAAE,kBAAkB,CAAC;IAC9B;;qBAEiB;IACjB,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;2EAEuE;IACvE,WAAW,CAAC,EAAE,eAAe,GAAG,QAAQ,CAAC;IACzC;qEACiE;IACjE,YAAY,CAAC,EAAE,qBAAqB,CAAC;IACrC;;;;;;;;gEAQ4D;IAC5D,QAAQ,CAAC,EAAE,mBAAmB,EAAE,CAAC;IACjC,yEAAyE;IACzE,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;IACnC;;;;;;;;kBAQc;IACd,aAAa,CAAC,EAAE,UAAU,GAAG,QAAQ,CAAC;IACtC;;;;;;;;;;;qCAWiC;IACjC,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;0EAIsE;IACtE,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC;IACvC;;mFAE+E;IAC/E,mBAAmB,CAAC,EAAE,CACpB,OAAO,EAAE,gBAAgB,KACtB,SAAS,CAAC;QAAE,OAAO,EAAE,gBAAgB,CAAA;KAAE,CAAC,GAAG,SAAS,CAAC;IAC1D;;;;;;mCAM+B;IAC/B,aAAa,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;IACpC;;;;mDAI+C;IAC/C,aAAa,CAAC,EAAE,OAAO,CAAC,CAAC;QAAE,OAAO,EAAE,gBAAgB,CAAC;QAAC,SAAS,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC,CAAC;IAC7E;;;yEAGqE;IACrE,YAAY,CAAC,EAAE,CAAC,UAAU,EAAE,uBAAuB,KAAK,IAAI,CAAC;IAC7D;2DACuD;IACvD,eAAe,CAAC,EAAE,CAChB,OAAO,EAAE,wBAAwB,EACjC,MAAM,EAAE,uBAAuB,KAC5B,IAAI,CAAC;IACV;;2DAEuD;IACvD,eAAe,CAAC,EAAE,CAChB,OAAO,EAAE,wBAAwB,EACjC,OAAO,EAAE,sBAAsB,KAC5B,IAAI,CAAC;IACV;;;0DAGsD;IACtD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;qCACiC;IACjC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,4EAA4E;IAC5E,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;;;2EAGuE;IACvE,SAAS,CAAC,EAAE,yBAAyB,CAAC;IACtC;wCACoC;IACpC,gBAAgB,CAAC,EAAE,CAAC,IAAI,EAAE,mBAAmB,KAAK,yBAAyB,CAAC;IAC5E;0EACsE;IACtE,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,CAAC;IAC7C;wEACoE;IACpE,MAAM,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACpC;0EACsE;IACtE,gBAAgB,CAAC,EAAE,CAAC,IAAI,EAAE,mBAAmB,KAAK,OAAO,CAAC;IAC1D,sEAAsE;IACtE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;uCACmC;IACnC,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,YAAY,GAAG,IAAI,KAAK,IAAI,CAAC;IAC3C,+DAA+D;IAC/D,iBAAiB,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,KAAK,IAAI,CAAC;IAChD;;yCAEqC;IACrC,aAAa,CAAC,EAAE,6BAA6B,CAAC;IAC9C;+EAC2E;IAC3E,SAAS,CAAC,EAAE,uBAAuB,GAAG,IAAI,CAAC;IAC3C;;kCAE8B;IAC9B,UAAU,CAAC,EAAE,mBAAmB,GAAG,IAAI,CAAC;IACxC;2DACuD;IACvD,aAAa,CAAC,EAAE,MAAM,GAAG,YAAY,CAAC;IACtC;8EAC0E;IAC1E,gBAAgB,CAAC,EAAE,uBAAuB,GAAG,IAAI,CAAC;IAClD,4EAA4E;IAC5E,YAAY,CAAC,EAAE,mBAAmB,CAAC;IACnC,gFAAgF;IAChF,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,mEAAmE;IACnE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;kCAC8B;IAC9B,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AA8xBD,QAAA,MAAM,aAAa,0BAAwC,CAAC;AAC5D,KAAK,aAAa,GAAG,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC;AACtD,eAAe,aAAa,CAAC"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal, escaping Markdown renderer for assistant answers (#4505).
|
|
3
|
+
*
|
|
4
|
+
* The output is meant for `{@html}`, so the contract is safety first: every
|
|
5
|
+
* character of the input is HTML-escaped before any markup is produced, and
|
|
6
|
+
* the only tags emitted are the fixed set below with no attributes except a
|
|
7
|
+
* validated `href` (http/https only, with `rel="noopener noreferrer"` and
|
|
8
|
+
* `target="_blank"`), an ordered list's numeric `start`, and a code block's
|
|
9
|
+
* `language-*` class from a restricted alphabet. Raw HTML in the input is
|
|
10
|
+
* shown as text, never interpreted.
|
|
11
|
+
*
|
|
12
|
+
* Supported: paragraphs (single newlines become `<br>`), `#`/`##`/`###`
|
|
13
|
+
* headings, `-`/`*`/`+` and `1.`/`1)` lists (one level), fenced code blocks
|
|
14
|
+
* (``` or ~~~), inline `code`, `**bold**`/`__bold__`, `*italic*`/`_italic_`,
|
|
15
|
+
* and `[text](https://…)` links. Anything else renders as literal text.
|
|
16
|
+
*/
|
|
17
|
+
/** Escape text for an HTML text node or a double-quoted attribute value. */
|
|
18
|
+
export declare function escapeHtml(text: string): string;
|
|
19
|
+
/**
|
|
20
|
+
* Render assistant Markdown to sanitized HTML. Safe for `{@html}`: see the
|
|
21
|
+
* module comment for the exact output vocabulary.
|
|
22
|
+
*/
|
|
23
|
+
export declare function renderAssistantMarkdown(source: string): string;
|
|
24
|
+
//# sourceMappingURL=assistant-markdown.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"assistant-markdown.d.ts","sourceRoot":"","sources":["../../../../src/svelte/components/assistant/assistant-markdown.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAUH,4EAA4E;AAC5E,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C;AAgGD;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAmG9D"}
|