@happyvertical/smrt-chat 0.61.5 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/AGENTS.md +4 -0
  2. package/agents/assistant-turn-runs.md +74 -0
  3. package/agents/tool-summaries.md +1 -1
  4. package/agents/turn-drivers.md +64 -46
  5. package/dist/assistant-approvals.js +1 -1
  6. package/dist/assistant-approvals.js.map +1 -1
  7. package/dist/assistant-turn-driver.d.ts +11 -8
  8. package/dist/assistant-turn-driver.d.ts.map +1 -1
  9. package/dist/assistant-turn-events.d.ts +1 -1
  10. package/dist/assistant-turn-events.d.ts.map +1 -1
  11. package/dist/assistant-turn.d.ts +34 -3
  12. package/dist/assistant-turn.d.ts.map +1 -1
  13. package/dist/chunks/{ChatService-CeOVzOqN.js → ChatService-CDLAEJms.js} +2 -2
  14. package/dist/chunks/{ChatService-CeOVzOqN.js.map → ChatService-CDLAEJms.js.map} +1 -1
  15. package/dist/chunks/assistant-turn-events-DwdCZzQ0.js.map +1 -1
  16. package/dist/chunks/{chat-stream-5NpFBPe2.js → chat-stream-BJbmqHsu.js} +742 -254
  17. package/dist/chunks/chat-stream-BJbmqHsu.js.map +1 -0
  18. package/dist/engines.d.ts +4 -4
  19. package/dist/engines.d.ts.map +1 -1
  20. package/dist/engines.js +22 -24
  21. package/dist/engines.js.map +1 -1
  22. package/dist/index.d.ts +2 -1
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -3
  25. package/dist/internal/agent-runtime.js +1 -1
  26. package/dist/manifest.json +2 -1
  27. package/dist/smrt-knowledge.json +28 -10
  28. package/dist/smrt-knowledge.okf.md +16 -11
  29. package/dist/svelte/components/assistant/AssistantDock.svelte +2 -2
  30. package/dist/svelte/components/assistant/assistant-http-client.d.ts +2 -2
  31. package/dist/svelte/components/assistant/assistant-http-client.d.ts.map +1 -1
  32. package/dist/svelte/components/assistant/assistant-http-client.js +5 -5
  33. package/dist/svelte/components/assistant/assistant-transport.d.ts +7 -6
  34. package/dist/svelte/components/assistant/assistant-transport.d.ts.map +1 -1
  35. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.d.ts +3 -3
  36. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.d.ts.map +1 -1
  37. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.js +30 -30
  38. package/dist/svelte/i18n.d.ts +1 -1
  39. package/dist/svelte/i18n.js +1 -1
  40. package/dist/svelte/index.d.ts +1 -1
  41. package/dist/svelte/index.d.ts.map +1 -1
  42. package/dist/sveltekit.d.ts +55 -24
  43. package/dist/sveltekit.d.ts.map +1 -1
  44. package/dist/sveltekit.js +109 -44
  45. package/dist/sveltekit.js.map +1 -1
  46. package/dist/tool-loop.d.ts +2 -1
  47. package/dist/tool-loop.d.ts.map +1 -1
  48. package/dist/tool-run-types.d.ts +102 -0
  49. package/dist/tool-run-types.d.ts.map +1 -0
  50. package/dist/turn-tracking.d.ts +246 -0
  51. package/dist/turn-tracking.d.ts.map +1 -0
  52. package/package.json +20 -19
  53. package/dist/chunks/chat-stream-5NpFBPe2.js.map +0 -1
  54. package/dist/work-profile.d.ts +0 -64
  55. package/dist/work-profile.d.ts.map +0 -1
@@ -3,22 +3,23 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-chat",
6
- "packageVersion": "0.61.5",
6
+ "packageVersion": "0.62.0",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "48fd2dbc477259a280d63f7295af3ff6b11620f948b6debd1d2daddc1d7a30e7",
11
- "packageJson": "5efb1246ee0d9c376901bfb5f77d30a83499331abbffc36cf7322fcddd1781cd",
12
- "agents": "fbd94d44959aac77683458b8f097bf398694b84bc40f604346105dddf2c03b8f",
10
+ "manifest": "2933ef9eb4d4b601f2815ce69f04c364f1498f2dcfd260e17b68e2ef99735b25",
11
+ "packageJson": "b48e1cfe0cd933fd1410af7532e933e6ce95fe3079d791086346a127c07f9ed3",
12
+ "agents": "6f17bbd164ff7bb235faea14499df6546d9a994861df91d4741e934dda8e8eaa",
13
13
  "moduleDoc:agents/dev-workbench.md": "f07a428519e8cca4a46371da0a3b33b9c8d3102f1d9056e4c8efba3c0b702048",
14
14
  "moduleDoc:agents/runtime-report-tools.md": "116b6371207cec6bc8ee891a358b3457fc08d3ae86f9c31b428c6c13dfb25a40",
15
15
  "moduleDoc:agents/overview-tools.md": "752a4afb6b57a2e9224f3c65a98b0deb23cda87371f01ac0566f0887e9bb12da",
16
16
  "moduleDoc:agents/tool-loop.md": "0ee8ea63193b9dac32a8719e2afc1bad97f0d88e319ddb00f660fa1720da5e0c",
17
17
  "moduleDoc:agents/token-streaming.md": "016c711f3c269f6e93d156c909923201c2b4e1adbe6ece89d5291959c499a0ca",
18
- "moduleDoc:agents/turn-drivers.md": "fb0e1755457a12aeedba70e3f53b28fd93a3bb7ce32e63082459b0d607601d3e",
18
+ "moduleDoc:agents/turn-drivers.md": "6f5278a7ca79379946fa2c932fd134a92a8b571afdd0bad1a9177ed03b3bd2db",
19
19
  "moduleDoc:agents/owner-approvals.md": "ad8b489636a4849a0191d53988158b24b7ea808dc2905e773260044d58b0172b",
20
- "moduleDoc:agents/tool-summaries.md": "483557180c81a048a629dcec2852e5d68eb22cfee780cc4849662bb7867d8ce1",
20
+ "moduleDoc:agents/tool-summaries.md": "ddf438d307fbb7127f8290cd22046eef3b1d8e41c0d742a040707222b87be1bb",
21
21
  "moduleDoc:agents/runtime-exposure.md": "4a55759e1d2e754d421cfb3b9150818c71b59b3aacc0c011f0f2f45507086b58",
22
+ "moduleDoc:agents/assistant-turn-runs.md": "d7de91fbaab9c7543d88f5e0bc7d4de46a56b3673edca8285ff0a9b24302b17a",
22
23
  "moduleDoc:agents/ai-unavailable.md": "e12b175c932411c4445b59ee8144ae06cc962c430960b6c5a26e0002f2d15369",
23
24
  "moduleDoc:agents/assistant-questions.md": "a0371870b3bc99e313d8287912208f3e315bab7dc4ee138214895031ae79a5b0",
24
25
  "moduleDoc:agents/recipes.md": "89c2c86e4e26cea9ba10d917f8ad71c23a71d4fd8eaacf638a6cd252e2376c07",
@@ -52,6 +53,7 @@
52
53
  "@happyvertical/smrt-assets": "workspace:*",
53
54
  "@happyvertical/smrt-config": "workspace:*",
54
55
  "@happyvertical/smrt-core": "workspace:*",
56
+ "@happyvertical/smrt-prompts": "workspace:*",
55
57
  "@happyvertical/smrt-personas": "workspace:*",
56
58
  "@happyvertical/smrt-profiles": "workspace:*",
57
59
  "@happyvertical/smrt-reports": "workspace:*",
@@ -90,6 +92,7 @@
90
92
  "@happyvertical/smrt-personas",
91
93
  "@happyvertical/smrt-playground",
92
94
  "@happyvertical/smrt-profiles",
95
+ "@happyvertical/smrt-prompts",
93
96
  "@happyvertical/smrt-reports",
94
97
  "@happyvertical/smrt-scanner",
95
98
  "@happyvertical/smrt-tenancy",
@@ -4517,7 +4520,17 @@
4517
4520
  "objectName": "@happyvertical/smrt-chat:VoiceSession"
4518
4521
  }
4519
4522
  ],
4520
- "prompts": [],
4523
+ "prompts": [
4524
+ {
4525
+ "filePath": "src/turn-tracking-child.test.ts"
4526
+ },
4527
+ {
4528
+ "filePath": "src/turn-tracking-decisions.test.ts"
4529
+ },
4530
+ {
4531
+ "filePath": "src/turn-tracking.ts"
4532
+ }
4533
+ ],
4521
4534
  "relationshipsV2": {
4522
4535
  "foreignKeyFields": 14,
4523
4536
  "crossPackageRefFields": 9,
@@ -4526,7 +4539,7 @@
4526
4539
  "polymorphicAssociations": 0,
4527
4540
  "uuidColumns": 78
4528
4541
  },
4529
- "agentDoc": "# @happyvertical/smrt-chat\n\nChat rooms, threads, and agent sessions with app-controlled tool whitelisting.\n\n## Dev Server\n\n`pnpm --dir packages/chat dev` runs a package-local SvelteKit workbench. The root\nroute separates **Character setup** and **Chat dev** into tabs; switching tabs\nretains the current character rig and chat state. The chat tab is an interactive\nsurface with a dev-only `/api/dev-chat` endpoint:\nit uses `@happyvertical/ai` when local provider credentials are present and\nfalls back to a deterministic local assistant otherwise. `/api/dev-chat-stream`\nis its SSE companion (#1936) — the same provider/local-fallback resolution wired\nthrough `createChatStreamHandler` in plain mode, so an embedded `SmrtChatBackend`\nclient can exercise token streaming locally. `/previews` hosts the shared\ncomponent playground entries from `src/svelte/playground.ts`.\n\nThe root route also drives the **browser inference path**\n(`@happyvertical/smrt-web/ai`: bitgpu, WebLLM, and route backends composed by\n`createInferencePath`) and an **agent-addressable draft form** (`useViewIntent`\nover `src/routes/chat-dev.intents.ts`, #2588). Their dev-config dependencies\n(static optional-peer imports, `workspace-aliases.js` prefix rules, the theme\nstylesheet import) and the stage→apply tool-call gotchas are in\n[agents/dev-workbench.md](agents/dev-workbench.md).\n\nDev-only voice and opt-in local character persistence are documented in\n[agents/dev-workbench.md](agents/dev-workbench.md#voice-and-local-character-persistence).\nThese endpoints are loopback-only demos; production hosts supply authenticated\nprincipals, tenancy, and authorization to the owning services.\n\n## Models\n\nAll seven models expose only generated REST/MCP `list`/`get`; structural tests\ncheck the registry for mutating operations. Writes go through\nmembership/owner-checked `ChatService` or the binding-checked voice adapter.\n\n`ChatService` is a closed facade. Its collections and security-sensitive\nhelpers use ES `#private` fields/methods (TypeScript `private` is erased).\nCollection classes are not exported from the package index. The agent-reply\nbridge is a Symbol-keyed static accessible through a non-exported symbol held\nby the module-local `sendAgentReply` function.\n\n- **ChatRoom**: `roomType` (public/private/dm/agent), `status`, `topic`, `maxParticipants`, `lastMessageAt`. Tenant-scoped (required).\n- **ChatMessage**: shared by users + agents. `role` (user/assistant/system/tool), `messageType` (text/system/action/file/tool_call/tool_result), `toolCallData` JSON. Unified model — no separate agent message type. Tenant-scoped (required).\n- **ChatParticipant**: `role` (owner/admin/member/viewer), `onlineStatus`, `lastReadMessageId`, `isMuted`. Tenant-scoped (required).\n- **ChatThread**: `rootMessageId`, `isResolved`, `messageCount`. Created via `ChatService.startThread()` (member-checked). Tenant-scoped (required).\n- **ChatReaction**: `messageId`, `profileId`, `emoji`. Added/removed via `ChatService.addReaction()`/`removeReaction()` (member-checked, self-keyed). Tenant-scoped (required).\n- **AgentSession**: `agentId` (application slug, string ref, not FK), `agentProfileId` (nullable `crossPackageRef` to `Profile` — the `bot` profile the agent AUTHORS as, #2995), `allowedTools` (JSON string array), `sessionContext` (JSON, sensitive), `systemPrompt`, limits (`maxTokens`/`maxMessages`/`expiresAt`). Optional tenancy.\n- **VoiceSession**: short-lived voice-gateway binding over `(tenant, actorProfileId, personaId, room/thread/agentSession)` plus a persona snapshot, gateway `session_id`, expiry, replay tracking, and metadata. Tenant-scoped (required). Generated surface is read-only; creation and turns go through `createVoiceChatSession()` / `handleVoiceGatewayTurn()`.\n\n## ChatService\n\nPublic writes take server-supplied `actorProfileId`; never trust a request's\n`senderProfileId`, `role`, owner id, or participant id as authority.\n\n| Operation | Authorization and behavior |\n|---|---|\n| `sendMessage()` | Room member; authors as actor with `role: 'user'`; no public membership bypass |\n| `createRoom()` | Actor becomes owner |\n| `startThread()` | Member; optional root message bound to room and tenant |\n| `addParticipant()` / `removeParticipant()` | Owner/admin; self-leave allowed |\n| `updateRoom()` | Owner/admin |\n| `addReaction()` / `removeReaction()` | Member; self-keyed |\n| `getOrCreateDM()` | Actor must be a DM participant |\n| `createAgentSession()` | Actor becomes session participant; existing-session lookup tenant-bound; optional `sessionKey` isolates conversation subjects |\n| `updateAgentSessionConfig()` | Owner; mandatory tenant-bound lookup |\n| `sendAgentUserMessage()` | Actor must be session participant; authored as participant |\n\nRead facade: `getAgentSession({agentSessionId, tenantId})`,\n`findActiveAgentSessions({tenantId, agentId, participantProfileId})`, and\n`getThread({threadId, tenantId})` are tenant-bound; consumers still check\nownership/context. `listRoomThreads({roomId, actorProfileId, tenantId})`,\n`getThreadMessages({threadId, actorProfileId, tenantId, limit?})` (chronological),\n`getRoomMessages({roomId, actorProfileId, tenantId})`, and\n`getRoomForMember(roomId, actorProfileId, tenantId)` additionally require\nmembership of the server-supplied actor, not a caller-selected subject.\n\nTrusted agent runtime imports `sendAgentReply(service, params)` only from\n`@happyvertical/smrt-chat/internal/agent-runtime`. It is not a `ChatService`\nmethod or package-index export. It authors as `session.agentProfileId` — the\nagent's resolved `bot` Profile, NEVER the `agentId` slug (#2995) — accepts a\nsame-room/tenant thread, and enforces `allowedTools` fail-closed.\n\nPrivate `#writeMessage` alone can select arbitrary authors/roles or bypass\nmembership. It binds every supplied `threadId`, `agentSessionId`, and\n`replyToMessageId` to the same room **and** tenant. Internal enrollment supports\nautomatically created rooms, sessions, and participants.\n\n## Agent Tool Whitelisting\n\n`allowedTools` is a JSON array controlled by the consuming app. Fail-closed: an empty/unparseable whitelist permits NO tools. The internal `sendAgentReply(service, params)` function enforces the whitelist before emitting any `tool`/`tool_call` message; a caller cannot supply a `senderProfileId`/`role` to post as the agent, and the function is not reachable from the package index.\n\nPrincipal-bound data discovery and reads are available as `PrincipalTool[]` via\n`createDataSurfaceTools()` (re-exported by the chat package). Pass the tools as\n`extraTools` to the persona conversation/tool loop. They use the same\nfail-closed `allowedTools` offer/execution gates; RBAC, tenant, redaction,\nbounded query results, and audit authority remain in the authenticated\n`PrincipalRun` supplied by `@happyvertical/smrt-agents`.\n\n## Commerce money tools (#3937)\n\nHosts that offer invoice money work must explicitly register\n`createCommerceMoneyTools()` from `@happyvertical/smrt-commerce` in\ntheir authenticated assistant route's `extraTools` (for example, `extraTools: () => createCommerceMoneyTools()`) and\nadd only the desired `commerce.*` slugs to the persona's `allowedTools`.\nThey are not generic manifest CRUD tools: tax codes are selected by code,\npreview is calculator-only, and line writes run through the document-money\ncoordinator. Each execution reasserts the principal allow-list and required\n`Invoice`, `InvoiceLineItem`, `DocumentTax`, and `TaxCode` operations. The\ngenerated MCP invoice `get` serializer remains commerce-owned; use its\nstored-facts integration when that serializer exposes `DocumentTax` rows.\n\n## Runtime report tools (#3711)\n\n`createRuntimeReportTools()` (`runtime-report-tools.ts`) returns the\n`reports.runtime.*` `PrincipalTool`s for the persona `extraTools` seam. Sources\nare a server-owned allow-list; `apply` needs the previewed `specHash` plus a\nhuman `confirmation` host (a model-supplied `confirmed` flag is ignored); a\nstring `collection` is a catalog slug, never a class name; reads and saves run\nunder the principal's tenant. Read before editing:\n[agents/runtime-report-tools.md](agents/runtime-report-tools.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## Assistant seams\n\nExternal turn drivers (`turnDriver`, `resolveTurnDriver`; chat keeps authorization,\nauthoring, SSE and cancellation): [agents/turn-drivers.md](agents/turn-drivers.md).\nDurable owner approvals of destructive server tools: [agents/owner-approvals.md](agents/owner-approvals.md).\nTool summaries and inference engine adapters: [agents/tool-summaries.md](agents/tool-summaries.md).\nLive cookbook exposure of manifest tools: [agents/runtime-exposure.md](agents/runtime-exposure.md).\n\n## AssistantDock (#2904)\n\n`AssistantDock` (`svelte/components/assistant/`, exported from `./svelte`)\nuses a host `DataSurfaceRegistry`'s mounted descriptors (none: plain chat).\nActions: `normalizeDataSurfaceActionRequest` → `AssistantActionClient`\n(preview/apply over a server `DataSurfaceActionAdapter`, not the\n`data-surface-bridge.ts` channel). Generated `ChatThread`/`ChatMessage`\n`list`/`get` are tenant- not member-scoped; the dock never calls them.\n\n**Server routes (#3368).** `./sveltekit` `mountAssistantRoutes()` serves the\ndock from one `[...path]` route; `createAssistantHttp{Transport,ActionClient}`\n(`./svelte`) are its browser half. Principal from `event.locals` or\n`resolvePrincipal`; threads only from the actor's keyed session room in that\ntenant (else 404). `allowedTools` is fail-closed; without `tools` it offers\nthose manifest ops (an unprovided name is an error, #3414). `ai` defaults to\nthe principal's stored inference binding over the config `ai` block (#4756,\n[core inference.md](../core/agents/inference.md#raw-clients-and-binding-source-4756)). Pass `runtime`: a turn never keeps the RLS request tx\n(own `runAsPrincipal` tx). `clientRequestId` makes the row id a UUIDv5\n(`clientRequestMessageId`): the PK is the retry reservation. See\n[docs](../../docs/assistant-dock.md).\n\nAI off / not set up (#4757): routes answer a structured `ai_unavailable` 503;\ndock `aiSettingsHref` ([agents/ai-unavailable.md](agents/ai-unavailable.md)).\n\n#4505: `messageFormat=\"markdown\"` / `renderMessage` ([docs](../../docs/assistant-dock.md));\n`collapseRecoveredFailures` ([tool-loop](agents/tool-loop.md#failed-calls-are-persisted-4383)).\n\nStructured questions and page requests (#4100): [agents/assistant-questions.md](agents/assistant-questions.md).\n\n## Recipes (#3719)\n\n`src/recipes.ts` declares `chat.assistant` (the AssistantDock as a `header.end`\nshell widget, an `llm` provider, runtime `both`; help in\n`src/assistant.recipe.md`). Keep each recipe class self-contained. Details:\n[agents/recipes.md](agents/recipes.md).\n\n## Gotchas\n\n- **sessionContext, not context**: `context` is reserved for slug scoping. Use `getSessionContext()`/`updateSessionContext()` for agent memory.\n- **Agent rooms auto-created**: `roomType: 'agent'`, `maxParticipants` defaults to 2; the agent is enrolled as a member so its replies pass the membership check. `createAgentSession()` re-enrolls the participant AND the agent on the existing-session path, so legacy sessions created before the agent was enrolled self-heal.\n- **The agent's author is a Profile, not `agentId` (#2995)**: `senderProfileId`/`profileId` are `crossPackageRef`s to `Profile` and therefore uuid columns on PostgreSQL, so the slug fails the cast (`22P02`) and no agent reply can persist. `createAgentSession()` resolves the agent's `bot` Profile through `resolveAgentProfile()` in `@happyvertical/smrt-profiles` (created on first use, tenant-bound) and records it as `AgentSession.agentProfileId`; both enrolment and `sendAgentReply` use that uuid. A consumer whose agent already has an acting identity passes `agentProfileId` to skip resolution — the voice path does this with the persona's `actsAsProfileId`, so persona replies stay attributed to the configured acting profile. Like `actorProfileId`, `agentProfileId` is SERVER-supplied, never request input: it selects the author of every later assistant message. It is validated (`#requireAgentProfile`) to exist and be visible in the tenant and to differ from the acting participant, and it can never re-point a session that already resolved one — only a pre-#2995 session with none is backfilled. **Migration**: `agent_profile_id` is an ordinary additive manifest field, so a consumer adopts it the same way as any other — `smrt db:migrate` generates and applies the column from the manifest, and `db:status --parity` verifies it; the framework never creates application schema at runtime. It is nullable and needs no offline DATA backfill — a session created before #2995 resolves and persists its `agentProfileId`, and re-enrols the agent, on its first agent turn after the upgrade. Two pre-#2995 cohorts: a session whose `agentId` is an ordinary slug never committed an author on PostgreSQL (the cast failed), so there is nothing to repair there, while SQLite/DuckDB may hold `chat_messages`/`chat_participants` rows whose id column holds the slug — readable, but not joinable to `profiles`. A session whose `agentId` is already a Profile uuid (the voice path used to collapse a persona's `actsAsProfileId` into it) DID commit on PostgreSQL; that profile is ADOPTED as the author, tenant-checked and never the participant, so the conversation's author does not change and the two-seat room gains no third identity. Known one-time effect: because `voice.ts` no longer derives `agentId` from `actsAsProfileId`, a keyless `createVoiceChatSession()` for such a persona opens a new session and room instead of reusing the legacy one; the old room and its messages stay intact and readable, and resuming with an explicit `agentSessionId` is unaffected.\n- **Only SQLite-backed tests would miss this class of bug**: uuid columns accept any text on SQLite. `src/__tests__/agent-reply-postgres.test.ts` (`pnpm --filter @happyvertical/smrt-chat test:postgres`) pins the agent-reply path against real PostgreSQL. That suite runs in `postgres-tests.yml` on every same-repository PR and merge group (#2659); keep a cheap SQLite assertion alongside it anyway, since the default lane is SQLite-only (`chat-service.test.ts` asserts the author is the profile uuid, not the slug).\n- **Per-subject sessions need `sessionKey`**: `createAgentSession()` reuses ANY active session for the same `(agentId, participantProfileId, tenantId)`. Callers that open separate conversations per subject (e.g. one content-editor session per content id) MUST pass a stable `sessionKey` (stored in `sessionContext.__sessionKey`, read via `AgentSession.getSessionKey()`); otherwise a session opened for one subject is reused and its context overwritten for another, surfacing the wrong room/threads (S5 #1392). A keyed create never reuses a keyless/legacy session.\n- **Session expiry**: check `isActive()` before allowing messages (expiresAt or limit-based)\n- **DM identity**: derived from the deterministic per-tenant `canonicalDmRoomId()` and the authoritative `chat_participants` join, not client metadata; concurrent creates upsert onto one row.\n- **Tenant-bound lookups**: membership/session/DM lookups REQUIRE `tenantId` and always bind it into the WHERE clause (`findActiveMembership`/`isActiveMember`/`findActiveSession` take a required `tenantId`; AgentSession's `null` tenant is an explicit bound scope, not \"any tenant\") so they can never resolve a row from another tenant.\n\n",
4542
+ "agentDoc": "# @happyvertical/smrt-chat\n\nChat rooms, threads, and agent sessions with app-controlled tool whitelisting.\n\n## Dev Server\n\n`pnpm --dir packages/chat dev` runs a package-local SvelteKit workbench. The root\nroute separates **Character setup** and **Chat dev** into tabs; switching tabs\nretains the current character rig and chat state. The chat tab is an interactive\nsurface with a dev-only `/api/dev-chat` endpoint:\nit uses `@happyvertical/ai` when local provider credentials are present and\nfalls back to a deterministic local assistant otherwise. `/api/dev-chat-stream`\nis its SSE companion (#1936) — the same provider/local-fallback resolution wired\nthrough `createChatStreamHandler` in plain mode, so an embedded `SmrtChatBackend`\nclient can exercise token streaming locally. `/previews` hosts the shared\ncomponent playground entries from `src/svelte/playground.ts`.\n\nThe root route also drives the **browser inference path**\n(`@happyvertical/smrt-web/ai`: bitgpu, WebLLM, and route backends composed by\n`createInferencePath`) and an **agent-addressable draft form** (`useViewIntent`\nover `src/routes/chat-dev.intents.ts`, #2588). Their dev-config dependencies\n(static optional-peer imports, `workspace-aliases.js` prefix rules, the theme\nstylesheet import) and the stage→apply tool-call gotchas are in\n[agents/dev-workbench.md](agents/dev-workbench.md).\n\nDev-only voice and opt-in local character persistence are documented in\n[agents/dev-workbench.md](agents/dev-workbench.md#voice-and-local-character-persistence).\nThese endpoints are loopback-only demos; production hosts supply authenticated\nprincipals, tenancy, and authorization to the owning services.\n\n## Models\n\nAll seven models expose only generated REST/MCP `list`/`get`; structural tests\ncheck the registry for mutating operations. Writes go through\nmembership/owner-checked `ChatService` or the binding-checked voice adapter.\n\n`ChatService` is a closed facade. Its collections and security-sensitive\nhelpers use ES `#private` fields/methods (TypeScript `private` is erased).\nCollection classes are not exported from the package index. The agent-reply\nbridge is a Symbol-keyed static accessible through a non-exported symbol held\nby the module-local `sendAgentReply` function.\n\n- **ChatRoom**: `roomType` (public/private/dm/agent), `status`, `topic`, `maxParticipants`, `lastMessageAt`. Tenant-scoped (required).\n- **ChatMessage**: shared by users + agents. `role` (user/assistant/system/tool), `messageType` (text/system/action/file/tool_call/tool_result), `toolCallData` JSON. Unified model — no separate agent message type. Tenant-scoped (required).\n- **ChatParticipant**: `role` (owner/admin/member/viewer), `onlineStatus`, `lastReadMessageId`, `isMuted`. Tenant-scoped (required).\n- **ChatThread**: `rootMessageId`, `isResolved`, `messageCount`. Created via `ChatService.startThread()` (member-checked). Tenant-scoped (required).\n- **ChatReaction**: `messageId`, `profileId`, `emoji`. Added/removed via `ChatService.addReaction()`/`removeReaction()` (member-checked, self-keyed). Tenant-scoped (required).\n- **AgentSession**: `agentId` (application slug, string ref, not FK), `agentProfileId` (nullable `crossPackageRef` to `Profile` — the `bot` profile the agent AUTHORS as, #2995), `allowedTools` (JSON string array), `sessionContext` (JSON, sensitive), `systemPrompt`, limits (`maxTokens`/`maxMessages`/`expiresAt`). Optional tenancy.\n- **VoiceSession**: short-lived voice-gateway binding over `(tenant, actorProfileId, personaId, room/thread/agentSession)` plus a persona snapshot, gateway `session_id`, expiry, replay tracking, and metadata. Tenant-scoped (required). Generated surface is read-only; creation and turns go through `createVoiceChatSession()` / `handleVoiceGatewayTurn()`.\n\n## ChatService\n\nPublic writes take server-supplied `actorProfileId`; never trust a request's\n`senderProfileId`, `role`, owner id, or participant id as authority.\n\n| Operation | Authorization and behavior |\n|---|---|\n| `sendMessage()` | Room member; authors as actor with `role: 'user'`; no public membership bypass |\n| `createRoom()` | Actor becomes owner |\n| `startThread()` | Member; optional root message bound to room and tenant |\n| `addParticipant()` / `removeParticipant()` | Owner/admin; self-leave allowed |\n| `updateRoom()` | Owner/admin |\n| `addReaction()` / `removeReaction()` | Member; self-keyed |\n| `getOrCreateDM()` | Actor must be a DM participant |\n| `createAgentSession()` | Actor becomes session participant; existing-session lookup tenant-bound; optional `sessionKey` isolates conversation subjects |\n| `updateAgentSessionConfig()` | Owner; mandatory tenant-bound lookup |\n| `sendAgentUserMessage()` | Actor must be session participant; authored as participant |\n\nRead facade: `getAgentSession({agentSessionId, tenantId})`,\n`findActiveAgentSessions({tenantId, agentId, participantProfileId})`, and\n`getThread({threadId, tenantId})` are tenant-bound; consumers still check\nownership/context. `listRoomThreads({roomId, actorProfileId, tenantId})`,\n`getThreadMessages({threadId, actorProfileId, tenantId, limit?})` (chronological),\n`getRoomMessages({roomId, actorProfileId, tenantId})`, and\n`getRoomForMember(roomId, actorProfileId, tenantId)` additionally require\nmembership of the server-supplied actor, not a caller-selected subject.\n\nTrusted agent runtime imports `sendAgentReply(service, params)` only from\n`@happyvertical/smrt-chat/internal/agent-runtime`. It is not a `ChatService`\nmethod or package-index export. It authors as `session.agentProfileId` — the\nagent's resolved `bot` Profile, NEVER the `agentId` slug (#2995) — accepts a\nsame-room/tenant thread, and enforces `allowedTools` fail-closed.\n\nPrivate `#writeMessage` alone can select arbitrary authors/roles or bypass\nmembership. It binds every supplied `threadId`, `agentSessionId`, and\n`replyToMessageId` to the same room **and** tenant. Internal enrollment supports\nautomatically created rooms, sessions, and participants.\n\n## Agent Tool Whitelisting\n\n`allowedTools` is a JSON array controlled by the consuming app. Fail-closed: an empty/unparseable whitelist permits NO tools. The internal `sendAgentReply(service, params)` function enforces the whitelist before emitting any `tool`/`tool_call` message; a caller cannot supply a `senderProfileId`/`role` to post as the agent, and the function is not reachable from the package index.\n\nPrincipal-bound data discovery and reads are available as `PrincipalTool[]` via\n`createDataSurfaceTools()` (re-exported by the chat package). Pass the tools as\n`extraTools` to the persona conversation/tool loop. They use the same\nfail-closed `allowedTools` offer/execution gates; RBAC, tenant, redaction,\nbounded query results, and audit authority remain in the authenticated\n`PrincipalRun` supplied by `@happyvertical/smrt-agents`.\n\n## Commerce money tools (#3937)\n\nHosts that offer invoice money work must explicitly register\n`createCommerceMoneyTools()` from `@happyvertical/smrt-commerce` in\ntheir authenticated assistant route's `extraTools` (for example, `extraTools: () => createCommerceMoneyTools()`) and\nadd only the desired `commerce.*` slugs to the persona's `allowedTools`.\nThey are not generic manifest CRUD tools: tax codes are selected by code,\npreview is calculator-only, and line writes run through the document-money\ncoordinator. Each execution reasserts the principal allow-list and required\n`Invoice`, `InvoiceLineItem`, `DocumentTax`, and `TaxCode` operations. The\ngenerated MCP invoice `get` serializer remains commerce-owned; use its\nstored-facts integration when that serializer exposes `DocumentTax` rows.\n\n## Runtime report tools (#3711)\n\n`createRuntimeReportTools()` (`runtime-report-tools.ts`) returns the\n`reports.runtime.*` `PrincipalTool`s for the persona `extraTools` seam. Sources\nare a server-owned allow-list; `apply` needs the previewed `specHash` plus a\nhuman `confirmation` host (a model-supplied `confirmed` flag is ignored); a\nstring `collection` is a catalog slug, never a class name; reads and saves run\nunder the principal's tenant. Read before editing:\n[agents/runtime-report-tools.md](agents/runtime-report-tools.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## Assistant seams\n\nExternal turn drivers (`turnDriver`, `resolveTurnDriver`; chat keeps authorization,\nauthoring, SSE and cancellation): [agents/turn-drivers.md](agents/turn-drivers.md).\nDurable owner approvals of destructive server tools: [agents/owner-approvals.md](agents/owner-approvals.md).\nTool summaries and inference engine adapters: [agents/tool-summaries.md](agents/tool-summaries.md).\nLive cookbook exposure of manifest tools: [agents/runtime-exposure.md](agents/runtime-exposure.md).\n\n## Assistant turns as AI runs (#5005)\n\nEach turn opens one `turn` run and sends every model call through core's tracked client; the system prompt is the registered `chat.assistant.system` prompt. Details: [agents/assistant-turn-runs.md](agents/assistant-turn-runs.md).\n\n## AssistantDock (#2904)\n\n`AssistantDock` (`svelte/components/assistant/`, exported from `./svelte`)\nuses a host `DataSurfaceRegistry`'s mounted descriptors (none: plain chat).\nActions: `normalizeDataSurfaceActionRequest` → `AssistantActionClient`\n(preview/apply over a server `DataSurfaceActionAdapter`, not the\n`data-surface-bridge.ts` channel). Generated `ChatThread`/`ChatMessage`\n`list`/`get` are tenant- not member-scoped; the dock never calls them.\n\n**Server routes (#3368).** `./sveltekit` `mountAssistantRoutes()` serves the\ndock from one `[...path]` route; `createAssistantHttp{Transport,ActionClient}`\n(`./svelte`) are its browser half. Principal from `event.locals` or\n`resolvePrincipal`; threads only from the actor's keyed session room in that\ntenant (else 404). `allowedTools` is fail-closed; without `tools` it offers\nthose manifest ops (an unprovided name is an error, #3414). `ai` defaults to\nthe principal's stored inference binding over the config `ai` block (#4756,\n[core inference.md](../core/agents/inference.md#raw-clients-and-binding-source-4756)). Pass `runtime`: a turn never keeps the RLS request tx\n(own `runAsPrincipal` tx). `clientRequestId` makes the row id a UUIDv5\n(`clientRequestMessageId`): the PK is the retry reservation. See\n[docs](../../docs/assistant-dock.md).\n\nAI off / not set up (#4757): routes answer a structured `ai_unavailable` 503;\ndock `aiSettingsHref` ([agents/ai-unavailable.md](agents/ai-unavailable.md)).\n\n#4505: `messageFormat=\"markdown\"` / `renderMessage` ([docs](../../docs/assistant-dock.md));\n`collapseRecoveredFailures` ([tool-loop](agents/tool-loop.md#failed-calls-are-persisted-4383)).\n\nStructured questions and page requests (#4100): [agents/assistant-questions.md](agents/assistant-questions.md).\n\n## Recipes (#3719)\n\n`src/recipes.ts` declares `chat.assistant` (the AssistantDock as a `header.end`\nshell widget, an `llm` provider, runtime `both`; help in\n`src/assistant.recipe.md`). Keep each recipe class self-contained. Details:\n[agents/recipes.md](agents/recipes.md).\n\n## Gotchas\n\n- **sessionContext, not context**: `context` is reserved for slug scoping. Use `getSessionContext()`/`updateSessionContext()` for agent memory.\n- **Agent rooms auto-created**: `roomType: 'agent'`, `maxParticipants` defaults to 2; the agent is enrolled as a member so its replies pass the membership check. `createAgentSession()` re-enrolls the participant AND the agent on the existing-session path, so legacy sessions created before the agent was enrolled self-heal.\n- **The agent's author is a Profile, not `agentId` (#2995)**: `senderProfileId`/`profileId` are `crossPackageRef`s to `Profile` and therefore uuid columns on PostgreSQL, so the slug fails the cast (`22P02`) and no agent reply can persist. `createAgentSession()` resolves the agent's `bot` Profile through `resolveAgentProfile()` in `@happyvertical/smrt-profiles` (created on first use, tenant-bound) and records it as `AgentSession.agentProfileId`; both enrolment and `sendAgentReply` use that uuid. A consumer whose agent already has an acting identity passes `agentProfileId` to skip resolution — the voice path does this with the persona's `actsAsProfileId`, so persona replies stay attributed to the configured acting profile. Like `actorProfileId`, `agentProfileId` is SERVER-supplied, never request input: it selects the author of every later assistant message. It is validated (`#requireAgentProfile`) to exist and be visible in the tenant and to differ from the acting participant, and it can never re-point a session that already resolved one — only a pre-#2995 session with none is backfilled. **Migration**: `agent_profile_id` is an ordinary additive manifest field, so a consumer adopts it the same way as any other — `smrt db:migrate` generates and applies the column from the manifest, and `db:status --parity` verifies it; the framework never creates application schema at runtime. It is nullable and needs no offline DATA backfill — a session created before #2995 resolves and persists its `agentProfileId`, and re-enrols the agent, on its first agent turn after the upgrade. Two pre-#2995 cohorts: a session whose `agentId` is an ordinary slug never committed an author on PostgreSQL (the cast failed), so there is nothing to repair there, while SQLite/DuckDB may hold `chat_messages`/`chat_participants` rows whose id column holds the slug — readable, but not joinable to `profiles`. A session whose `agentId` is already a Profile uuid (the voice path used to collapse a persona's `actsAsProfileId` into it) DID commit on PostgreSQL; that profile is ADOPTED as the author, tenant-checked and never the participant, so the conversation's author does not change and the two-seat room gains no third identity. Known one-time effect: because `voice.ts` no longer derives `agentId` from `actsAsProfileId`, a keyless `createVoiceChatSession()` for such a persona opens a new session and room instead of reusing the legacy one; the old room and its messages stay intact and readable, and resuming with an explicit `agentSessionId` is unaffected.\n- **Only SQLite-backed tests would miss this class of bug**: uuid columns accept any text on SQLite. `src/__tests__/agent-reply-postgres.test.ts` (`pnpm --filter @happyvertical/smrt-chat test:postgres`) pins the agent-reply path against real PostgreSQL. That suite runs in `postgres-tests.yml` on every same-repository PR and merge group (#2659); keep a cheap SQLite assertion alongside it anyway, since the default lane is SQLite-only (`chat-service.test.ts` asserts the author is the profile uuid, not the slug).\n- **Per-subject sessions need `sessionKey`**: `createAgentSession()` reuses ANY active session for the same `(agentId, participantProfileId, tenantId)`. Callers that open separate conversations per subject (e.g. one content-editor session per content id) MUST pass a stable `sessionKey` (stored in `sessionContext.__sessionKey`, read via `AgentSession.getSessionKey()`); otherwise a session opened for one subject is reused and its context overwritten for another, surfacing the wrong room/threads (S5 #1392). A keyed create never reuses a keyless/legacy session.\n- **Session expiry**: check `isActive()` before allowing messages (expiresAt or limit-based)\n- **DM identity**: derived from the deterministic per-tenant `canonicalDmRoomId()` and the authoritative `chat_participants` join, not client metadata; concurrent creates upsert onto one row.\n- **Tenant-bound lookups**: membership/session/DM lookups REQUIRE `tenantId` and always bind it into the WHERE clause (`findActiveMembership`/`isActiveMember`/`findActiveSession` take a required `tenantId`; AgentSession's `null` tenant is an explicit bound scope, not \"any tenant\") so they can never resolve a row from another tenant.\n\n",
4530
4543
  "moduleDocs": [
4531
4544
  {
4532
4545
  "path": "agents/dev-workbench.md",
@@ -4556,7 +4569,7 @@
4556
4569
  {
4557
4570
  "path": "agents/turn-drivers.md",
4558
4571
  "module": "turn-drivers",
4559
- "content": "# Assistant turn drivers\n\n`mountAssistantRoutes({ turnDriver, resolveTurnDriver })` and\n`runAssistantTurn({ turnDriver })` accept an `AssistantTurnDriver` with\n`run(context, callbacks): Promise<void>`. Types are exported from the package\nroot and `./sveltekit`. No driver means the existing `runToolLoop`, with the\nsame model options, browser suspension/resume, budgets, persistence policy,\nand wire events. An external driver replaces the loop only.\n\nThe route resolves `resolveTurnDriver(ctx)` once per send/resume, before\nstoring the user message. Its context includes the authenticated principal,\nrequest event, validated but untrusted `requestContext`, and selected model.\nAn undefined result falls back to the static `turnDriver`, then the built-in\nloop. Selection belongs to the host; never authorize an engine from request\ninput alone. A resolver may throw the same inference-unavailable error used\nby the model factory to preserve the structured `ai_unavailable` 503 and its\nengine-status/settings response. Other resolver failures become the existing\nsanitized `assistant_unavailable` 503. Refused sends author nothing.\n\nWithout an external driver, `ai` is either an SDK-compatible client or a\nfactory called once per turn with that same authenticated request context.\nThat path supports user-specific model adapters, including adapters that\ntranslate `chat(messages, options)` / `onProgress` and omit unsupported\nsampling, token-limit or streaming options. Chat does not cache the factory's\nresult between requests. External drivers do not resolve `ai` at all.\n\n## External adapter\n\n```ts\nimport {\n mountAssistantRoutes,\n type AssistantTurnDriver,\n} from '@happyvertical/smrt-chat/sveltekit';\n\nconst driver: AssistantTurnDriver = {\n async run(context, callbacks) {\n // Replace this body with the host's CLI/agent adapter.\n // Supply context.signal to its subprocess and MCP transport.\n callbacks.text('I am checking the studio.');\n callbacks.done({ text: 'The studio is ready.' });\n },\n};\n\nexport const { GET, POST } = mountAssistantRoutes({\n turnDriver: driver,\n systemPrompt: 'Help the studio owner.',\n allowedTools: [],\n});\n```\n\n`context` carries server-selected thread/session identity, origin message id,\nprior user/assistant messages (oldest first), the new user message, system\ninstructions/persona guidance, the principal, optional permission ceiling,\nallow-listed manifest/server tools and an `AbortSignal`. The route mirrors\nthat allow-list onto the session for authoring too. External drivers are\ntrusted server integrations: the host must bind their MCP credentials and\nexecution to this same principal, tool set, tenancy and permission ceiling.\nReporting a tool event is not execution authorization. No engine is imported\nby chat, and driver callbacks never execute a tool.\n\nThe callbacks map directly to engine progress:\n\n- `text(delta)` emits the existing `token` preview.\n- `await toolCall({ id, name, args })` emits a server `tool_call` step and\n authors a tool-call row. Names are canonical app slugs, not provider aliases.\n- `await toolResult({ id, ok, result?, error? })` emits the matching result\n step and authors a tool-result row. `result` is serialized text; `error`\n must be user-safe, as it is shown in the step. Unknown, duplicate or\n unoffered calls/results fail the turn without authoring an unauthorized row.\n- `await approvalNeeded({ id, callId, tool, summary })` emits the additive\n `approval_needed` wire event and waits for the host bridge described below.\n- `done({ text, usage? })` selects the final answer and optional aggregate\n `ToolLoopUsage` for `onUsage`. Chat authors the final answer once `run`\n settles. Blank answers use the configured empty-answer fallback.\n- `error(error)` or a thrown error logs detail through `onError`, authors any\n partial text and a sanitized failure row, and emits the existing `error`\n event. A run returning without `done` is also a failure.\n\nCall `done` or `error` once and settle `run`; callbacks after termination or\nabort are ignored. Await tool callbacks to preserve persistence ordering.\nRequest abort and response-body cancellation reach `context.signal`; chat\nsettles as cancelled even if the engine fails to settle. The adapter must\nstop its subprocess and MCP activity when aborted. Partial streamed text is\nsaved on cancellation. All rows are authored by `ChatService` in the turn's\nexisting database lifetime and linked to the originating user message.\nExternal tool-call and result rows are saved by default; the built-in loop's\n`authorInvocation`/failure-collapse policy is unchanged.\n\nExternal loops currently receive server tools only. Browser tool\nsuspension/resume remains owned by the default driver; selecting an external\ndriver on a browser continuation explicitly fails with\n`driver_resume_unsupported`. Do not change engines between the legs of a\nsuspended browser turn. Existing dock token, step, message and terminal event\nhandling renders external progress without a new transport or panel.\n\n## Owner approval bridge\n\n`AssistantApprovalRequest`, `AssistantApprovalDecision` and\n`AssistantApprovalWaiter` define the server-write boundary. Mounted routes default\nto app-runtime's durable owner authority over the canonical smrt-approvals ledger.\nChat rebuilds requests from the pending offered call, authors them to the thread,\nstreams `approval_needed`, and waits for the authenticated owner's exact decision.\nThe driver must await it before executing and honor denial; its host/MCP adapter\nmust execute under the original principal with live permissions and the supplied\nceiling. It must never expose the decision route as a model tool.\n\nAn explicitly supplied `waitForApproval` without `approvals` retains the trusted\nhost callback integration: it must durably store the exact call and authorize the\nowner itself. Direct entry points without any bridge deny. Abort releases the\nwait without granting permission. Durable defaults, policy, routes, card and crash\nlimits: [owner-approvals.md](owner-approvals.md).\n\n## Validation\n\n`src/sveltekit.test.ts` (external turn drivers) covers the authenticated SQLite route,\nstream ordering, tool and text persistence, origin links, safe failures,\nabort propagation, per-user/request driver and model resolution, history,\noffer/ownership gates and approval waits. Existing assistant-turn and dock\nsuites cover the unchanged default loop/wire reader. No live engines,\nproviders, MCP servers or containers are required.\n\nThe behavior-to-test matrix below uses `pnpm --dir packages/chat test` for\nall rows. Each case is route integration on Node/SQLite with fake engines;\n`ChatService` remains the data executor in the existing turn lifetime. There\nare no new SQL statements, schema, transaction boundaries or retries; the\nexisting service/default-loop suites retain those dialect and atomicity\ncontracts. No external engine or durable approval-store implementation is\nclaimed here.\n\n| Behavior/invariant | Reachable trigger | Positive case | Negative/failure case | Actor/context | Executor/transaction | Runtime/dialect | External edge | Level | Command |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Authoring and wire parity | Send with a driver | Text, calls, results, final and origin links saved | Upstream failure saves partial and safe failure | Authenticated owner/thread | ChatService/turn lifetime | Node/SQLite | Engine callbacks → existing SSE reader | Route integration | Package test |\n| Offer and ownership gates | Foreign send or reported tool | Offered canonical tool accepted | Foreign actor 404; unoffered or duplicate call refused | Owner × foreign actor × owned thread | ChatService/turn lifetime | Node/SQLite | Canonical app slugs | Route integration | Package test |\n| Model/driver selection | Context engine selection | Two users get their own adapter/driver; history retained | Unconfigured resolver 503 without a user row | Authenticated request/user | ChatService/no writes on refusal | Node/SQLite | SDK factory and driver resolver | Route integration | Package test |\n| Terminal contract | Engine settles | Done ends once | Missing done, unmatched result and duplicate call become safe errors | Owner/thread | ChatService/turn lifetime | Node/SQLite | Missing or malformed callbacks | Route integration | Package test |\n| Abort/stop | Request abort or body cancel | Signal reaches driver | Never-settling run/approval released; late events ignored | Owner's active turn | ChatService/turn lifetime | Node/SQLite | AbortSignal | Route integration | Package test |\n| Approval seam | Pending tool requests approval | Host decision awaited and event emitted | Missing bridge denies; cancellation denies | Bound principal and pending call | Host hook; durability deferred to C3 | Node/SQLite | Approval request/decision | Route integration | Package test |\n| Default loop | Send with no driver | Existing loop and dock tests unchanged | Existing provider/tool/browser-failure cases retained | Existing principal fixtures | Existing service/loop transactions | Existing package suite runtimes | Existing model and browser wire | Package regression | Package test |\n\n## Reuse audit\n\nAudited against base `06c0b64fe3` using `git diff --stat 06c0b64fe3 HEAD`:\nC1 adds one production helper module and this contract reference; its driver\ntests extend the existing route suite. It adds no component, model, route or\nproduction tool. Existing\n`mountAssistantRoutes`, `runAssistantTurn`, `AssistantTurnOptions`,\n`MountAssistantRoutesOptions` and `AssistantTurnEvent` are extended in place.\n\nThe configured `smrt-dev-mcp` server was available. `review-smrt-project`\nreviewed `packages/chat` with duplicate detection and source evidence;\n`introspect-project` listed the existing chat models, `build-context`\n(architecture) searched for external assistant loops, tool callbacks and\napproval waits, and `build-package-specialist-context` searched chat's\nassistant recipe and tool contracts. This server exposes no dedicated\ncomponent/intent/recipe search tool, so those lookups also read\n`docs/knowledge/intents/index.md`, its human-approvals reference, the recipe\nsources and the source packages with `rg`.\n\nBoth names and purposes were searched in `packages/smrt-ui`, `smrt-svelte`,\n`chat`, `core`, `agents`, `inference`, `approvals`, `app-runtime` and\n`app-shell`: `turn.?driver`, `external.*(agent|loop|turn)`, `toolCall`,\n`AssistantClientToolCall`, `AssistantClientToolResult`, `ToolInvocation`,\n`approval.*(wait|decision)`, `approved: boolean`, `confirmSave`, `consent`,\n`holdForUser`, and `chat.assistant`. The results and decisions are:\n\n| Introduced file/symbols | Existing capability and reuse decision |\n| --- | --- |\n| `src/assistant-turn-driver.ts`: `runExternalAssistantTurn`, its local `persist`, `enqueue`, `active` and abort closures | Reuses `sendAgentReply`/ChatService, `resolveTurnReply`, `replyMetadataFor`, the existing turn reporter, SSE producer and status/step/message contracts. No existing loop-independent bridge fits: `runPersonaConversationTurn` and `streamPersonaConversation` own model loops; shell `runAgentTurn` and `holdForUser` depend on shell models, credentials and event bus. Engine extraction belongs to C2, not this bridge. The queue only orders this driver's callbacks; it is not a durable/background queue. |\n| Same file: `AssistantDriverToolCall`, callback tool-result parameter | Derives the call from `Pick<AssistantClientToolCall, 'id' \\| 'name' \\| 'args'>` and reuses `AssistantClientToolResult` directly. Existing `PendingClientToolCall` adds browser effect; `ToolInvocation` describes completed execution, not a started call. No duplicate field declarations remain. |\n| Same file: `AssistantTurnDriver`, `AssistantTurnDriverContext`, `AssistantTurnDriverCallbacks` | New loop-independent host contract; reuses `AIMessage`, `PrincipalBinding`, `PrincipalTool`, `ManifestTool`, `ToolLoopUsage` and `AbortSignal`; `AssistantTurnOptions.thread` refers to the context's thread type. Existing model-loop options and shell-specific engine dependencies are not interchangeable with a host-owned loop. |\n| Same file: `AssistantApprovalDecision`, `AssistantApprovalWaiter`; existing `src/assistant-turn-events.ts`: `AssistantApprovalRequest` | New transport notification/result and wait-hook contract only. `smrt-approvals` already owns durable `ApprovalRequest`, `ApprovalDecision` (approve/reject/request_changes), `ApprovalService.decide` and `consume`; they are not a callback outcome or chat tool-call notification. C3 must adapt that authority rather than implement another ledger. Shell `HoldOutcome` includes execution results and shell events and cannot serve as a package-neutral wait result. Chat's `RuntimeReportConfirmationHost.confirmSave` accepts only a report spec/hash and rejects to deny; data-surface confirmation is a required/none policy. Neither represents a generic pending tool notification or approval outcome. |\n| Removed `src/sveltekit.turn-driver.test.ts`: its local `Round`, `Actor`, `scriptedAI`, `text`, `discoverTool`, `locals`, `events`, `mount`, `call`, `createThread`, `listMessages`, `send` and setup callbacks | Name/purpose searches found the same private helpers in `src/sveltekit.test.ts`. Moved all 11 driver cases into a nested describe there and deleted the duplicate file. Existing case bodies are unchanged; the new cases now reuse its SQLite/user/tenant fixtures, fake model/tool and SSE reader. No production tool is registered. |\n| `agents/turn-drivers.md` | Contract documentation for the extension of existing `chat.assistant`/`AssistantDock`; no new recipe, UI or model. |\n\nThe review's missing-`smrt-svelte` dependency/shell advisories describe the\nexisting dev workbench, not new driver imports. `workspace-aliases.js`\nexplicitly documents that dev-only source alias: declaring the dependency\nwould introduce the prohibited `chat → smrt-svelte → smrt-content → chat`\ncycle. Production driver code introduces neither that import nor a new\nshell; no dependency change is appropriate for C1.\n\n## Work profiles and design interception\n\n`resolveWorkProfile(context, name?)` selects intelligence from authenticated\nowner settings before authoring the user message. It receives a requested name\nonly on escalation; known design flows select `design` in the initial callback.\nThe resolved profile is forwarded to inference and its budgets govern the loop.\nBackground work must request `background` explicitly. Profile selection never\nchanges principal, tenant, permission ceiling, allow-list or owner approvals.\n\nHosts declare structural tools with `designTools`, or trusted tool metadata\n`annotations.workProfile: 'design'` (core cookbook tools provide this annotation).\nThe built-in loop checks the whole proposed batch before executing any call.\nExternal drivers MUST call `context.beforeToolExecution(canonicalSlug)` at their\n**authenticated MCP execution boundary**, before effects or approval creation.\nA later CLI tool-call stream event is too late. Interception aborts and settles\nthe old pass, then restarts once under design while retaining completed tool\nobservations. The intercepted assist call never executes.\n\nProduction hosts use `onDesignEscalation(context, input)` to enqueue a durable\ndesign job. Returning `{runId, message?}` ends the request with `done.runId` and\nprevents inline restart. Without the hook, the shared bounded turn restarts\ninline once. `resolveWorkProfileRuntime` reselects an engine on that restart.\n`Thinking this through` identifies escalation using the existing status stream.\n\nStored assistant rows contain `metadata.workRun`: profile, engine, actual model\nwhen reported by the engine, effort, cumulative tokens, duration, tool calls and\nfallback. `onWorkRun` receives the same sanitized accounting; the default logs\none line. CLI adapters report observed execution through `callbacks.execution`;\nthis also preserves spent assist work when escalation aborts its attempt.\n\nReuse audit: the developer intent index and MCP build-context architecture\ninventory, plus name/purpose searches in chat/core/inference/smrt-ui/smrt-svelte,\nidentified the existing turn driver, tool-loop and cookbook annotations as the\nowning seams. This extends those APIs; it adds no alternate approval ledger,\nmodel registry, UI component or tool executor.\n\nFor durable jobs, the browser's `createAssistantHttpTransport({designRuns:true})`\nreads `GET /design-runs?threadId=…` and posts `/design-runs/{runId}/stop` or\n`/resume`. Hosts authenticate and owner-scope these routes. Each returns\n`{run?:{runId,pass:{index,count,name},status,note?}}` with a one-based pass index.\nThe dock reloads progress when opening a thread, polls it, and reuses its status\nand Stop controls; stopped/failed jobs offer Resume. Closing/unmounting the dock\nleaves a durable job running. No browser id grants access to a run.\n\n`formatAssistantReply(content, context)` is a trusted host presentation hook for\nstructured pass output. It returns human-facing `content` and optional metadata\nbefore persistence; hosts can keep the validated output under\n`metadata.designOutput` for their durable runner. That output is available only\non the trusted internal pass SSE handoff, never ordinary message wire objects.\nOrdinary replies are unchanged.\n\nKnown design flows set `deferDesignTurn` to queue through that same durable hook\nbefore any model call. Detached passes use the trusted `internalTurn(context)`\ncallback to supply private pass input and the original owner-message id. The\nroute still authenticates ownership and validates that original message against\nthe same thread and actor, but authors no synthetic user message and does not\nrewrite the original send's lifecycle. Private pass bindings belong to the host,\nnot browser request flags. After that callback and the original-message checks,\nthe route records the request in its own WeakSet and stamps every assistant/tool\nwrite with trusted `assistantInternalTurn` provenance via the existing author\nmetadata. This applies to the built-in loop, external driver, errors and tool\nholds. Request headers, body/context fields and user-authored metadata cannot\nselect that provenance. Raw rows remain available to private provider history.\n\nThe ordinary message route requests `ChatService`'s conversation visibility.\nIt excludes marked assistant/tool rows and positively identified legacy assistant\nrows with `designOutput`; user rows are never hidden by metadata. Filtering runs\nbefore the visible limit using ordinary tenant/member-scoped collection pages\nof 200, deterministic timestamp/id ordering, and the existing list-bound resolver.\nReply lookup rejects a hidden root and filters linked replies in the same way.\nRaw service reads retain their previous default. Legacy unmarked tool rows have\nno reliable run/pass linkage and are not deleted or heuristically attributed.\nPublic wire metadata includes only `workRun` and `designRunId`.\n\nHosts may opt into `toolPresentation: 'generic'` on the routes and AssistantDock.\nIt uses `describeAssistantTool` without raw observations, summaries or arguments;\nunknown tool messages receive a fixed person-facing fallback. The same projection\ncovers live SSE messages, steps/status, stored legacy tool messages, and approval\nreferences. The dock also suppresses raw browser-tool name/description/argument\nfallbacks while retaining destructive warnings and the existing decision controls.\nPublic generic streams omit provisional model tokens; the final formatted answer\nremains visible. Trusted internal handoff streams retain their original tokens.\nDefault clients and private provider history keep their existing contracts.\n\nFor meaningful approval previews under generic presentation, the trusted async\n`presentApproval(record)` callback receives the canonical authorized hold and\nreturns only a host-derived business summary. The public summary and explicit\n`presentation.summary` carry that caption; unsafe/unrecognized holds fall back to\n“Review this change.” No raw stored/model summary is promoted by this option.\nThe existing card uses only the explicit presentation in generic mode; polling\nand decisions still use the canonical authority.\n\nThe route tests cover built-in and external actual-tool passes, raw private SSE\nhandoff, reload, forged request flags, hidden-root refusal, legacy app-description\nand ordinary-record tool rows, ordinary human/assistant retention, and 201 internal\nrows ahead of the public page. DOM tests render legacy messages, browser-tool\nconfirmation and approval refresh with malicious raw captions and safe host previews.\nBoth default contracts and opted presentation run in the affected regression suites.\n\nToken accounting is conservative: `workRun.tokens` is omitted if any completion\nomits valid usage, including across escalation and browser continuations. An\nexplicit zero remains zero. `ToolLoopResult.totalTokens` remains the numeric\nknown subtotal; `usageKnown` distinguishes it from complete usage. API model\nmetadata uses a provider-reported model when available; effort describes the\nrequested profile effort, subject to provider support and normalization.\n\nOn durable admission, the intercepted assist turn is recorded separately before\n`done`: a human handoff message carries `metadata.designRunId` and its original\n`workRun` (spent tokens when fully known, elapsed time and calls). The durable\njob's budget begins at its own admission; earlier assist work is not presented\nas part of that job's usage. Missing observed external models remain unknown;\nthe requested profile alias is never substituted as an actual model.\n"
4572
+ "content": "# Assistant turn drivers\n\n`mountAssistantRoutes({ turnDriver, resolveTurnDriver })` and\n`runAssistantTurn({ turnDriver })` accept an `AssistantTurnDriver` with\n`run(context, callbacks): Promise<void>`. Types are exported from the package\nroot and `./sveltekit`. No driver means the existing `runToolLoop`, with the\nsame model options, browser suspension/resume, budgets, persistence policy,\nand wire events. An external driver replaces the loop only.\n\nThe route resolves `resolveTurnDriver(ctx)` once per send/resume, before\nstoring the user message. Its context includes the authenticated principal,\nrequest event, validated but untrusted `requestContext`, and selected model.\nAn undefined result falls back to the static `turnDriver`, then the built-in\nloop. Selection belongs to the host; never authorize an engine from request\ninput alone. A resolver may throw the same inference-unavailable error used\nby the model factory to preserve the structured `ai_unavailable` 503 and its\nengine-status/settings response. Other resolver failures become the existing\nsanitized `assistant_unavailable` 503. Refused sends author nothing.\n\nWithout an external driver, `ai` is either an SDK-compatible client or a\nfactory called once per turn with that same authenticated request context.\nThat path supports user-specific model adapters, including adapters that\ntranslate `chat(messages, options)` / `onProgress` and omit unsupported\nsampling, token-limit or streaming options. Chat does not cache the factory's\nresult between requests. External drivers do not resolve `ai` at all.\n\n## External adapter\n\n```ts\nimport {\n mountAssistantRoutes,\n type AssistantTurnDriver,\n} from '@happyvertical/smrt-chat/sveltekit';\n\nconst driver: AssistantTurnDriver = {\n async run(context, callbacks) {\n // Replace this body with the host's CLI/agent adapter.\n // Supply context.signal to its subprocess and MCP transport.\n callbacks.text('I am checking the studio.');\n callbacks.done({ text: 'The studio is ready.' });\n },\n};\n\nexport const { GET, POST } = mountAssistantRoutes({\n turnDriver: driver,\n systemPrompt: 'Help the studio owner.',\n allowedTools: [],\n});\n```\n\n`context` carries server-selected thread/session identity, origin message id,\nprior user/assistant messages (oldest first), the new user message, system\ninstructions/persona guidance, the principal, optional permission ceiling,\nallow-listed manifest/server tools and an `AbortSignal`. The route mirrors\nthat allow-list onto the session for authoring too. External drivers are\ntrusted server integrations: the host must bind their MCP credentials and\nexecution to this same principal, tool set, tenancy and permission ceiling.\nReporting a tool event is not execution authorization. No engine is imported\nby chat, and driver callbacks never execute a tool.\n\nThe callbacks map directly to engine progress:\n\n- `text(delta)` emits the existing `token` preview.\n- `await toolCall({ id, name, args })` emits a server `tool_call` step and\n authors a tool-call row. Names are canonical app slugs, not provider aliases.\n- `await toolResult({ id, ok, result?, error? })` emits the matching result\n step and authors a tool-result row. `result` is serialized text; `error`\n must be user-safe, as it is shown in the step. Unknown, duplicate or\n unoffered calls/results fail the turn without authoring an unauthorized row.\n- `await approvalNeeded({ id, callId, tool, summary })` emits the additive\n `approval_needed` wire event and waits for the host bridge described below.\n- `done({ text, usage? })` selects the final answer and optional aggregate\n `ToolLoopUsage` for `onUsage`. Chat authors the final answer once `run`\n settles. Blank answers use the configured empty-answer fallback.\n- `error(error)` or a thrown error logs detail through `onError`, authors any\n partial text and a sanitized failure row, and emits the existing `error`\n event. A run returning without `done` is also a failure.\n\nCall `done` or `error` once and settle `run`; callbacks after termination or\nabort are ignored. Await tool callbacks to preserve persistence ordering.\nRequest abort and response-body cancellation reach `context.signal`; chat\nsettles as cancelled even if the engine fails to settle. The adapter must\nstop its subprocess and MCP activity when aborted. Partial streamed text is\nsaved on cancellation. All rows are authored by `ChatService` in the turn's\nexisting database lifetime and linked to the originating user message.\nExternal tool-call and result rows are saved by default; the built-in loop's\n`authorInvocation`/failure-collapse policy is unchanged.\n\nExternal loops currently receive server tools only. Browser tool\nsuspension/resume remains owned by the default driver; selecting an external\ndriver on a browser continuation explicitly fails with\n`driver_resume_unsupported`. Do not change engines between the legs of a\nsuspended browser turn. Existing dock token, step, message and terminal event\nhandling renders external progress without a new transport or panel.\n\n## Owner approval bridge\n\n`AssistantApprovalRequest`, `AssistantApprovalDecision` and\n`AssistantApprovalWaiter` define the server-write boundary. Mounted routes default\nto app-runtime's durable owner authority over the canonical smrt-approvals ledger.\nChat rebuilds requests from the pending offered call, authors them to the thread,\nstreams `approval_needed`, and waits for the authenticated owner's exact decision.\nThe driver must await it before executing and honor denial; its host/MCP adapter\nmust execute under the original principal with live permissions and the supplied\nceiling. It must never expose the decision route as a model tool.\n\nAn explicitly supplied `waitForApproval` without `approvals` retains the trusted\nhost callback integration: it must durably store the exact call and authorize the\nowner itself. Direct entry points without any bridge deny. Abort releases the\nwait without granting permission. Durable defaults, policy, routes, card and crash\nlimits: [owner-approvals.md](owner-approvals.md).\n\n## Validation\n\n`src/sveltekit.test.ts` (external turn drivers) covers the authenticated SQLite route,\nstream ordering, tool and text persistence, origin links, safe failures,\nabort propagation, per-user/request driver and model resolution, history,\noffer/ownership gates and approval waits. Existing assistant-turn and dock\nsuites cover the unchanged default loop/wire reader. No live engines,\nproviders, MCP servers or containers are required.\n\nThe behavior-to-test matrix below uses `pnpm --dir packages/chat test` for\nall rows. Each case is route integration on Node/SQLite with fake engines;\n`ChatService` remains the data executor in the existing turn lifetime. There\nare no new SQL statements, schema, transaction boundaries or retries; the\nexisting service/default-loop suites retain those dialect and atomicity\ncontracts. No external engine or durable approval-store implementation is\nclaimed here.\n\n| Behavior/invariant | Reachable trigger | Positive case | Negative/failure case | Actor/context | Executor/transaction | Runtime/dialect | External edge | Level | Command |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Authoring and wire parity | Send with a driver | Text, calls, results, final and origin links saved | Upstream failure saves partial and safe failure | Authenticated owner/thread | ChatService/turn lifetime | Node/SQLite | Engine callbacks → existing SSE reader | Route integration | Package test |\n| Offer and ownership gates | Foreign send or reported tool | Offered canonical tool accepted | Foreign actor 404; unoffered or duplicate call refused | Owner × foreign actor × owned thread | ChatService/turn lifetime | Node/SQLite | Canonical app slugs | Route integration | Package test |\n| Model/driver selection | Context engine selection | Two users get their own adapter/driver; history retained | Unconfigured resolver 503 without a user row | Authenticated request/user | ChatService/no writes on refusal | Node/SQLite | SDK factory and driver resolver | Route integration | Package test |\n| Terminal contract | Engine settles | Done ends once | Missing done, unmatched result and duplicate call become safe errors | Owner/thread | ChatService/turn lifetime | Node/SQLite | Missing or malformed callbacks | Route integration | Package test |\n| Abort/stop | Request abort or body cancel | Signal reaches driver | Never-settling run/approval released; late events ignored | Owner's active turn | ChatService/turn lifetime | Node/SQLite | AbortSignal | Route integration | Package test |\n| Approval seam | Pending tool requests approval | Host decision awaited and event emitted | Missing bridge denies; cancellation denies | Bound principal and pending call | Host hook; durability deferred to C3 | Node/SQLite | Approval request/decision | Route integration | Package test |\n| Default loop | Send with no driver | Existing loop and dock tests unchanged | Existing provider/tool/browser-failure cases retained | Existing principal fixtures | Existing service/loop transactions | Existing package suite runtimes | Existing model and browser wire | Package regression | Package test |\n\n## Reuse audit\n\nAudited against base `06c0b64fe3` using `git diff --stat 06c0b64fe3 HEAD`:\nC1 adds one production helper module and this contract reference; its driver\ntests extend the existing route suite. It adds no component, model, route or\nproduction tool. Existing\n`mountAssistantRoutes`, `runAssistantTurn`, `AssistantTurnOptions`,\n`MountAssistantRoutesOptions` and `AssistantTurnEvent` are extended in place.\n\nThe configured `smrt-dev-mcp` server was available. `review-smrt-project`\nreviewed `packages/chat` with duplicate detection and source evidence;\n`introspect-project` listed the existing chat models, `build-context`\n(architecture) searched for external assistant loops, tool callbacks and\napproval waits, and `build-package-specialist-context` searched chat's\nassistant recipe and tool contracts. This server exposes no dedicated\ncomponent/intent/recipe search tool, so those lookups also read\n`docs/knowledge/intents/index.md`, its human-approvals reference, the recipe\nsources and the source packages with `rg`.\n\nBoth names and purposes were searched in `packages/smrt-ui`, `smrt-svelte`,\n`chat`, `core`, `agents`, `inference`, `approvals`, `app-runtime` and\n`app-shell`: `turn.?driver`, `external.*(agent|loop|turn)`, `toolCall`,\n`AssistantClientToolCall`, `AssistantClientToolResult`, `ToolInvocation`,\n`approval.*(wait|decision)`, `approved: boolean`, `confirmSave`, `consent`,\n`holdForUser`, and `chat.assistant`. The results and decisions are:\n\n| Introduced file/symbols | Existing capability and reuse decision |\n| --- | --- |\n| `src/assistant-turn-driver.ts`: `runExternalAssistantTurn`, its local `persist`, `enqueue`, `active` and abort closures | Reuses `sendAgentReply`/ChatService, `resolveTurnReply`, `replyMetadataFor`, the existing turn reporter, SSE producer and status/step/message contracts. No existing loop-independent bridge fits: `runPersonaConversationTurn` and `streamPersonaConversation` own model loops; shell `runAgentTurn` and `holdForUser` depend on shell models, credentials and event bus. Engine extraction belongs to C2, not this bridge. The queue only orders this driver's callbacks; it is not a durable/background queue. |\n| Same file: `AssistantDriverToolCall`, callback tool-result parameter | Derives the call from `Pick<AssistantClientToolCall, 'id' \\| 'name' \\| 'args'>` and reuses `AssistantClientToolResult` directly. Existing `PendingClientToolCall` adds browser effect; `ToolInvocation` describes completed execution, not a started call. No duplicate field declarations remain. |\n| Same file: `AssistantTurnDriver`, `AssistantTurnDriverContext`, `AssistantTurnDriverCallbacks` | New loop-independent host contract; reuses `AIMessage`, `PrincipalBinding`, `PrincipalTool`, `ManifestTool`, `ToolLoopUsage` and `AbortSignal`; `AssistantTurnOptions.thread` refers to the context's thread type. Existing model-loop options and shell-specific engine dependencies are not interchangeable with a host-owned loop. |\n| Same file: `AssistantApprovalDecision`, `AssistantApprovalWaiter`; existing `src/assistant-turn-events.ts`: `AssistantApprovalRequest` | New transport notification/result and wait-hook contract only. `smrt-approvals` already owns durable `ApprovalRequest`, `ApprovalDecision` (approve/reject/request_changes), `ApprovalService.decide` and `consume`; they are not a callback outcome or chat tool-call notification. C3 must adapt that authority rather than implement another ledger. Shell `HoldOutcome` includes execution results and shell events and cannot serve as a package-neutral wait result. Chat's `RuntimeReportConfirmationHost.confirmSave` accepts only a report spec/hash and rejects to deny; data-surface confirmation is a required/none policy. Neither represents a generic pending tool notification or approval outcome. |\n| Removed `src/sveltekit.turn-driver.test.ts`: its local `Round`, `Actor`, `scriptedAI`, `text`, `discoverTool`, `locals`, `events`, `mount`, `call`, `createThread`, `listMessages`, `send` and setup callbacks | Name/purpose searches found the same private helpers in `src/sveltekit.test.ts`. Moved all 11 driver cases into a nested describe there and deleted the duplicate file. Existing case bodies are unchanged; the new cases now reuse its SQLite/user/tenant fixtures, fake model/tool and SSE reader. No production tool is registered. |\n| `agents/turn-drivers.md` | Contract documentation for the extension of existing `chat.assistant`/`AssistantDock`; no new recipe, UI or model. |\n\nThe review's missing-`smrt-svelte` dependency/shell advisories describe the\nexisting dev workbench, not new driver imports. `workspace-aliases.js`\nexplicitly documents that dev-only source alias: declaring the dependency\nwould introduce the prohibited `chat → smrt-svelte → smrt-content → chat`\ncycle. Production driver code introduces neither that import nor a new\nshell; no dependency change is appropriate for C1.\n\n## Model selection, budget and workflow-only tools (#5005)\n\n`resolveSelection(context)` returns the turn's `AssistantModelSelection`\n(`engine`, `tier`, `model?`, `effort?`) from authenticated host state before\nthe user message is authored; a request body model is honoured only without\none. The host binds the tier: core for an API key, inference's\n`engineTierModel` for Claude Code, Codex and a ChatGPT plan. The assistant asks\nfor the tier its prompt declares (`chat.assistant.system`, `best`;\n`resolveChatAssistantTier`). The selection's effort is the tier\nbinding's; the assistant prompt's `ai.effort` wins over it, and the route\nhands the result to the built-in loop (`reasoning: { effort }`) and to an\nexternal driver (`context.selection.effort`). A body model is honoured only\nwhere the selection names none (an API key). `turnBudget` (an `AiRunBudget`)\nis stored on the turn's `turn` run (core enforces it on tracked calls; it\ncounts `maxSteps` only for calls with a step index, so the loop enforces a\nturn's steps) and applied to the loop\n(`maxSteps`, `maxTokens` → `maxTurnTokens`, `maxDurationMs` → `maxTurnMs`,\n`callTimeoutMs` → `requestTimeoutMs`); a call core refuses at a budget limit\nends the turn `budget` with a plain reply. `maxTokens` (output per call) and\n`toolResultChars` stay route options and may be per request. A selection never\nchanges principal, tenant, permission ceiling, allow-list or owner approvals.\n\nTools limited to workflow runs carry the trusted annotation\n`annotations.runTypes: ['workflow']` (core cookbook tools provide it); hosts may\nalso list them in `workflowTools`. A chat `turn` run refuses such a call with a\ntyped `ToolRunTypeRefusal` before it executes. The built-in loop checks the\nwhole proposed batch before executing any call. External drivers MUST call\n`context.beforeToolExecution(canonicalSlug)` at their **authenticated MCP\nexecution boundary**, before effects or approval creation. A later CLI\ntool-call stream event is too late. The refused call never executes.\n\nThe owner's assistant settings (`assistantSettings(context)`) decide what\nhappens next. With `escalateToWorkflow` on (the default) and a host\n`onWorkflowEscalation(context, input)`, the request is handed to a workflow run:\nreturning `{runId, message?}` ends the request with `done.runId`. Otherwise the\nturn ends with the user-facing `tool_run_type` error. There is no inline restart\nand no second client: every call of the turn stays on its tracked client.\n`Thinking this through` identifies the handoff using the existing status stream.\n\n`onExecution(context, execution)` receives the turn's `EngineExecution`\n(engine, model when reported, requested model, effort, cumulative tokens when\nfully known, duration, tool calls, fallback) once, when the turn ends or hands\noff. Nothing of it is stored on a message. CLI adapters report observed\nexecution through `callbacks.execution`; this also keeps the work a handed-off\nturn spent. With a database the driver's turn is also a `turn` run: the\nengine's turn is one reserved call of it, settled from that execution, so\n`turnBudget` applies before the engine starts\n([assistant turn runs](assistant-turn-runs.md)).\n\nReuse audit: the developer intent index and MCP build-context architecture\ninventory, plus name/purpose searches in chat/core/inference/smrt-ui/smrt-svelte,\nidentified the existing turn driver, tool-loop and cookbook annotations as the\nowning seams. This extends those APIs; it adds no alternate approval ledger,\nmodel registry, UI component or tool executor.\n\nFor durable jobs, the browser's `createAssistantHttpTransport({workflowRuns:true})`\nreads `GET /runs?threadId=…` and posts `/runs/{runId}/stop` or\n`/resume`. Hosts authenticate and owner-scope these routes. Each returns\n`{run?:{runId,pass:{index,count,name},status,note?}}` with a one-based pass index.\nThe dock reloads progress when opening a thread, polls it, and reuses its status\nand Stop controls; stopped/failed jobs offer Resume. Closing/unmounting the dock\nleaves a durable job running. No browser id grants access to a run.\n\n`formatAssistantReply(content, context)` is a trusted host presentation hook for\nstructured pass output. It returns human-facing `content` and optional metadata\nbefore persistence; hosts can keep the validated output under\n`metadata.workflowOutput` for their durable runner. That output is available only\non the trusted internal pass SSE handoff, never ordinary message wire objects.\nOrdinary replies are unchanged.\n\nKnown design flows set `deferWorkflowTurn` to queue through that same durable hook\nbefore any model call. Detached passes use the trusted `internalTurn(context)`\ncallback to supply private pass input and the original owner-message id. The\nroute still authenticates ownership and validates that original message against\nthe same thread and actor, but authors no synthetic user message and does not\nrewrite the original send's lifecycle. Private pass bindings belong to the host,\nnot browser request flags. After that callback and the original-message checks,\nthe route records the request in its own WeakSet and stamps every assistant/tool\nwrite with trusted `assistantInternalTurn` provenance via the existing author\nmetadata. This applies to the built-in loop, external driver, errors and tool\nholds. Request headers, body/context fields and user-authored metadata cannot\nselect that provenance. Raw rows remain available to private provider history.\n\nThe ordinary message route requests `ChatService`'s conversation visibility.\nIt excludes marked assistant/tool rows and positively identified legacy assistant\nrows with `workflowOutput`; user rows are never hidden by metadata. Filtering runs\nbefore the visible limit using ordinary tenant/member-scoped collection pages\nof 200, deterministic timestamp/id ordering, and the existing list-bound resolver.\nReply lookup rejects a hidden root and filters linked replies in the same way.\nRaw service reads retain their previous default. Legacy unmarked tool rows have\nno reliable run/pass linkage and are not deleted or heuristically attributed.\nPublic wire metadata includes only `runId`.\n\nHosts may opt into `toolPresentation: 'generic'` on the routes and AssistantDock.\nIt uses `describeAssistantTool` without raw observations, summaries or arguments;\nunknown tool messages receive a fixed person-facing fallback. The same projection\ncovers live SSE messages, steps/status, stored legacy tool messages, and approval\nreferences. The dock also suppresses raw browser-tool name/description/argument\nfallbacks while retaining destructive warnings and the existing decision controls.\nPublic generic streams omit provisional model tokens; the final formatted answer\nremains visible. Trusted internal handoff streams retain their original tokens.\nDefault clients and private provider history keep their existing contracts.\n\nFor meaningful approval previews under generic presentation, the trusted async\n`presentApproval(record)` callback receives the canonical authorized hold and\nreturns only a host-derived business summary. The public summary and explicit\n`presentation.summary` carry that caption; unsafe/unrecognized holds fall back to\n“Review this change.” No raw stored/model summary is promoted by this option.\nThe existing card uses only the explicit presentation in generic mode; polling\nand decisions still use the canonical authority.\n\nThe route tests cover built-in and external actual-tool passes, raw private SSE\nhandoff, reload, forged request flags, hidden-root refusal, legacy app-description\nand ordinary-record tool rows, ordinary human/assistant retention, and 201 internal\nrows ahead of the public page. DOM tests render legacy messages, browser-tool\nconfirmation and approval refresh with malicious raw captions and safe host previews.\nBoth default contracts and opted presentation run in the affected regression suites.\n\nToken accounting is conservative: an execution's `tokens` is omitted if any\ncompletion omits valid usage, including across a handoff and browser\ncontinuations. An explicit zero remains zero. `ToolLoopResult.totalTokens`\nremains the numeric known subtotal; `usageKnown` distinguishes it from complete\nusage. The execution's model is a provider-reported one when available; effort\nis the requested effort, subject to provider support and normalization.\n\nOn a workflow handoff, the refused turn is reported through `onExecution`\nbefore `done`, and a human handoff message carries `metadata.runId`. The\nworkflow run's budget begins at its own admission; the turn's work is not\npresented as part of its usage. Missing observed external models remain\nunknown; the requested model is never substituted as an actual model.\n"
4560
4573
  },
4561
4574
  {
4562
4575
  "path": "agents/owner-approvals.md",
@@ -4566,13 +4579,18 @@
4566
4579
  {
4567
4580
  "path": "agents/tool-summaries.md",
4568
4581
  "module": "tool-summaries",
4569
- "content": "# Tool summaries and engine adapters\n\n`describeAssistantTool` / `toolSummary` own human tool words moved from shell.\nThe existing `describeTool(name, args?, outcome?)` seam now receives completed\n`{ ok, observation }` results. Existing two-argument host callbacks still work.\nBoth built-in and external turns use it for result step labels and the default\npersisted tool message (`toolCallData.label` too). Successful built-in results\nare now authored by default; `authorInvocation` can still replace or suppress\nthem. Failure diagnostics and their collapse policy remain intact. The dock\nrenders existing labels/content; no new event type or rendering stack exists.\nOnly a short name/title, bounded list count or safe explicit summary enters a\nlabel. Raw payloads, JSON, machine paths, SQL and credential-shaped text never\nbelong in a chip. Arguments are not used as record names. Unknown offered tools\nget generic words; unoffered calls retain the existing unknown-tool gate.\n\n`@happyvertical/smrt-chat/engines` is Node-only. Chat → inference is acyclic\n(`pnpm check:package-dag`). `createChatGPTAssistantAI(options)` wraps inference's\n`createChatGPTModel` as the SDK `chat` subset accepted by the loop. Tools/raw\nprovider calls, signal, text and total usage survive; inference sends only\n`chat` + `onProgress`, with no sampling/token/reasoning/stream options or key\nfallback. `createInferenceAssistantAdapters({ binding, status, cli, chatgpt,\napi? })` returns `{ resolveTurnDriver, ai }` for `mountAssistantRoutes`. The host\nreads the authenticated user's stored binding, never `requestContext`. Selection\nand status are cached only for that Request; missing binding selects the existing\nconfigured API factory. An unavailable/invalid selected engine refuses before\nwriting and never falls back to another billing path.\n\n`createAgentCliTurnDriver({ tool, bind })` adapts `runAgentTurn`. `bind(context)`\nreturns the host's MCP endpoint, token mint/revoke, private state directory,\nlookup dependencies, exact tool policy and owner/turn-filtered approval observer.\nThe MCP endpoint MUST enforce the original principal, tenant, permission ceiling,\nallow-list and durable approval policy on execution: stream inspection happens\nlater and cannot authorize an effect. Inference retains loopback restrictions,\nkey stripping, private empty working directory, built-in-tool lockdown and process\nand credential cleanup. Chat authors text/tool rows exactly once. Each CLI turn\nstarts fresh with chat history as untrusted context; no credential or CLI session\nstore is added. Full arguments come from inference's append callback rather than\nits intentionally clipped display event. Summaries are computed before result\nclipping and passed through the existing describe result argument; the CLI owns\nthe raw model observation. Optional `canonicalToolName` maps MCP wire aliases to\nchat's offered slugs, while `allowTool` still gates the MCP wire name. A mapper\nreturning undefined denies; aliases never broaden the offered set.\n\nThe driver's optional `waitForApproval` uses the existing trusted host-waiter\ncontract: it OBSERVES the MCP host's existing durable hold, never creates another\nledger, decides, consumes or executes it. Mounting uses that waiter unless an\nexplicit chat approval bridge is configured; do not combine two authorities.\nA pending result is never authored as a successful effect. The driver awaits the\nowner's decision, then asks for a new turn; it cannot automatically restart the\nexited CLI process. Abort releases observation, removes listeners and never grants\napproval. The host must expose its authenticated decision/status endpoint to the\nexisting approval card (or supply its own existing card through the dock slot).\n\n## Validation design\n\nAll tests use Node/SQLite, fake models and inference's stub CLI. No provider,\ncontainer or real login is required. No new database schema, SQL executor,\ntransaction or dialect behavior is introduced.\n\n| Behavior/invariant | Trigger | Positive | Failure | Actor/context | Executor/transaction | Runtime/dialect | Edge | Level | Command |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Summary parity | Built-in/external CRUD/list/unknown | Same step and persisted label | Payload/path/SQL/secret omitted; existing offer gates | Authenticated owned thread | Existing ChatService turn lifetime | Node/SQLite | Model/driver callbacks → existing SSE | Route integration/unit | chat test |\n| CLI adapter | Stub text/tool/hold | Ordered persisted callbacks, full args, shared labels | Abort, failure, unoffered tool; no held success | Bound principal and host owner observer | Existing chat author; MCP host executes | Node/SQLite; subprocess OS | Inference runAgentTurn + token lifetime | Integration | chat test |\n| ChatGPT factory | Fake plan model | Raw calls, progress, usage and signal | No unsupported options or API fallback | Per-request connection | No database writes | Node | Inference createChatGPTModel | Unit | chat test |\n| Per-user selection | Stored binding/status | Each user gets their selected engine | Missing/unknown/unready refused, no fallback | Authenticated Request | Refusal before ChatService writes | Node | Existing resolver hooks | Unit/route regressions | chat test |\n\n## Rebase interaction validation\n\n| Behavior | Positive | Negative | Principal / executor | Boundary / check |\n| --- | --- | --- | --- | --- |\n| External manifest exposure | Enabled tools retain shared summaries | Disabled/unreadable models absent; a live closure refuses callbacks and approval acceptance | Original authenticated tenant; MCP endpoint remains effect authority | Driver bridge and real CLI stubs; chat suite |\n| Saved owner approval | One execution after restart authors the shared outcome label | Refused/denied holds keep diagnostics and cannot replay | Captured principal/permission ceiling; existing durable authority and dispatcher | SQLite mounted routes; chat suite |\n| App replacement and STI | Canonical provider identity gates the effective app class; explicit create subtype survives summary generation | Closed gate prevents dispatch | Original tenant; registry collection dispatcher | Tool-loop integration; chat suite |\n\nConnect AI has no record/reference-picker dependency. It configures inference\nbefore model offerings exist; reference picker source and screen composition are\nunchanged. No artificial picker adapter is introduced.\n\n## Reuse check\n\nConfigured MCP `review_smrt_project` reviewed chat and smrt-svelte; `build_context`\narchitecture query searched tool descriptions, engine adapters and connection\ncomposition. The server exposes architecture/model listings but no standalone\ncomponent/intent/recipe search. Read the intent index and used `rg` name AND purpose\nsearches over smrt-ui, smrt-svelte, chat, core, inference and app-shell for\n`toolSummary`, `summary`, `describeTool`, `ConnectAi`, `connect AI`, sign-in,\n`runAgentTurn`, model factories, approvals, recipes and onboarding/settings.\n\nNew `src/tool-summary.ts` extends existing describe/label events, moving shell's\nsummary purpose to chat; reuses ToolInvocation's result shape. New `src/engines.ts`\nreuses inference's engines, types and fake CLI fixtures, existing turn callbacks,\nChatService, route resolver/factory and trusted approval waiter. No new model,\nroute or tool is registered. Its internal serialization queue only adapts the\nsynchronous inference emitter to awaited chat callbacks. New tests extend the\nexisting SQLite route fixtures, with isolated engine fakes in engines.test.ts.\nNo equivalent shared adapter or summary generator existed in the owning packages.\n\nRebase reuse search: MCP `review_smrt_project` on chat/smrt-svelte and `rg`\n`isManifestToolEnabled|isToolEnabled` plus exposure purpose searches in core,\nchat, smrt-ui and smrt-svelte found core's `isRuntimeModelEnabled` and the four\nexisting chat dispatcher checks. `isManifestToolEnabled` consolidates those\nchecks in their existing owning module; external drivers reuse it. No new file.\n\nManifest create offerings and execution\nnow use core's public `ObjectRegistry.getCreateTargets` / `resolveCreateTarget`\nAPI ([contract](../../core/agents/generators.md#public-collection-create-targets-a1b)).\n`createType` is an optional qualified create target; `_meta_type` is a compatible alias.\nThe model's `type` field remains business data, including on STI families.\nSelection occurs before filtering and uses the selected model's writable policy;\nselectors are not persisted fields. Offerings and execution both use the original\nprincipal's live runtime exposure context. The Profile/Bot assistant canary and\n`src/create-targets.test.ts` cover all four dispatch paths, replacement, labels,\nreadonly fields, malformed/foreign choices and gated children on SQLite.\n\n`./tool-summary` is a browser-safe entry. The optional fourth `toolSummary`\nargument supports `recordLabels: 'generic'` and `plainTextSummary: true` for\nsaved-product wording/replay. All safety guards remain shared; default labels\nare unchanged. Tricia is a thin policy adapter over these options.\n\n## Live-engine failures (R7/R8)\n\n### Next live round: behavior contract\n\n| Behavior / trigger | Positive | Refusal/control | Actor, executor and runtime | Evidence |\n| --- | --- | --- | --- | --- |\n| CLI offerings | Named Customer create exposes inline contact fields and recipe vocabulary | Dependency-only identities and API-only deletes absent; revoked/gated offers cannot resume | Captured user/tenant, original ceiling; existing MCP dispatcher; Node/SQLite | Real host + inference stub, then bounded built-app Claude turn |\n| Held CLI delete | Existing continuation binds thread, original arguments and principal; owner decides once | Repeated decision, revoked offer/permission, foreign owner/tenant and abort cannot replay | Existing OwnerApprovalContinuations/authority CAS, existing collection executor; Node/SQLite | Host route fixture + live exposed-list delete |\n| Capability words | Introduction and model guidance follow selected engine's offered operations | No blanket deletion claim when any named list omits it | Authenticated host; no effect executor | Host introduction and built browser |\n| Startup readiness | Only an explicit successful preflight is ready | Missing/false preflight, signed out, absent CLI and unsupported tool host refuse | CLI's own status, sanitized environment; no model request | Inference/Connect tests + built app |\n| Active stop | Abort while a real app tool is in flight leaves no CLI child and a stopped thread | Never report a pending hold or an interrupted effect as completed | Existing child tree cleanup and ChatService turn state | Stub abort + bounded live read/tool turn |\n\nReuse: repeated MCP `review_smrt_project` on chat, inference, runtime, Svelte and\ntemplate; `build_context` searched turn-bound continuations, hidden prerequisite\nofferings and recipe labels. Intent index and name/purpose `rg` searches across\nUI/Svelte/chat/core/runtime found OwnerApprovalContinuations, buildCookbookShell,\nthe existing describe callback and live MCP identity map. Extend those paths;\nno new approval store, dispatcher, model, route or component is introduced.\n\nEngine binding and unexpected driver failures use inference's safe correlated\nserver diagnostic before replacing exceptions with fixed user words and a\nreference. External failures preserve real partial output but do not persist a\nsecond generic error bubble. The existing pending-send entry owns the transport\nerror and retry. AssistantDock suppresses only the matching duplicate banner and\ntells AssistantComposer to restore the draft without a second send alert;\nstandalone composers retain their default alert and other dock errors stay visible.\nThe same status line also renders the controller's existing idle `Stopped`\nlabel after cancellation; it does not duplicate transport errors or invent a\ncompleted reply for an interrupted turn. A mounted active-tool cancellation\ntest verifies the stopped line, aborted signal, no retry and no error alert.\nTests drive the mounted dock, preserve draft/retry/a11y, and launch both inference\nstub engines under the exact desktop `buildSidecarEnv` composition. No desktop\nproduction environment policy changed. Reuse the desktop environment helper via\na test-only import; no duplicate environment builder is introduced.\n\nS1: canonical dotted `app.describe`, `app.history`, `recipes.search` and `recipes.describe` names use the existing person-facing summary table, including durable design steps. Unknown tool payloads remain hidden. ChatGPT failures pass their cause to inference's existing correlated failure reporter; only allow-listed codes and bounded `req_` or UUID request ids are logged, never exception messages or accounts.\n"
4582
+ "content": "# Tool summaries and engine adapters\n\n`describeAssistantTool` / `toolSummary` own human tool words moved from shell.\nThe existing `describeTool(name, args?, outcome?)` seam now receives completed\n`{ ok, observation }` results. Existing two-argument host callbacks still work.\nBoth built-in and external turns use it for result step labels and the default\npersisted tool message (`toolCallData.label` too). Successful built-in results\nare now authored by default; `authorInvocation` can still replace or suppress\nthem. Failure diagnostics and their collapse policy remain intact. The dock\nrenders existing labels/content; no new event type or rendering stack exists.\nOnly a short name/title, bounded list count or safe explicit summary enters a\nlabel. Raw payloads, JSON, machine paths, SQL and credential-shaped text never\nbelong in a chip. Arguments are not used as record names. Unknown offered tools\nget generic words; unoffered calls retain the existing unknown-tool gate.\n\n`@happyvertical/smrt-chat/engines` is Node-only. Chat → inference is acyclic\n(`pnpm check:package-dag`). `createChatGPTAssistantAI(options)` wraps inference's\n`createChatGPTModel` as the SDK `chat` subset accepted by the loop. Tools/raw\nprovider calls, signal, text and total usage survive; inference sends only\n`chat` + `onProgress`, with no sampling/token/reasoning/stream options or key\nfallback. `createInferenceAssistantAdapters({ binding, status, cli, chatgpt,\napi? })` returns `{ resolveTurnDriver, ai }` for `mountAssistantRoutes`. The host\nreads the authenticated user's stored binding, never `requestContext`. Selection\nand status are cached only for that Request; missing binding selects the existing\nconfigured API factory. An unavailable/invalid selected engine refuses before\nwriting and never falls back to another billing path.\n\n`createAgentCliTurnDriver({ tool, bind })` adapts `runAgentTurn`. `bind(context)`\nreturns the host's MCP endpoint, token mint/revoke, private state directory,\nlookup dependencies, exact tool policy and owner/turn-filtered approval observer.\nThe MCP endpoint MUST enforce the original principal, tenant, permission ceiling,\nallow-list and durable approval policy on execution: stream inspection happens\nlater and cannot authorize an effect. Inference retains loopback restrictions,\nkey stripping, private empty working directory, built-in-tool lockdown and process\nand credential cleanup. Chat authors text/tool rows exactly once. Each CLI turn\nstarts fresh with chat history as untrusted context; no credential or CLI session\nstore is added. Full arguments come from inference's append callback rather than\nits intentionally clipped display event. Summaries are computed before result\nclipping and passed through the existing describe result argument; the CLI owns\nthe raw model observation. Optional `canonicalToolName` maps MCP wire aliases to\nchat's offered slugs, while `allowTool` still gates the MCP wire name. A mapper\nreturning undefined denies; aliases never broaden the offered set.\n\nThe driver's optional `waitForApproval` uses the existing trusted host-waiter\ncontract: it OBSERVES the MCP host's existing durable hold, never creates another\nledger, decides, consumes or executes it. Mounting uses that waiter unless an\nexplicit chat approval bridge is configured; do not combine two authorities.\nA pending result is never authored as a successful effect. The driver awaits the\nowner's decision, then asks for a new turn; it cannot automatically restart the\nexited CLI process. Abort releases observation, removes listeners and never grants\napproval. The host must expose its authenticated decision/status endpoint to the\nexisting approval card (or supply its own existing card through the dock slot).\n\n## Validation design\n\nAll tests use Node/SQLite, fake models and inference's stub CLI. No provider,\ncontainer or real login is required. No new database schema, SQL executor,\ntransaction or dialect behavior is introduced.\n\n| Behavior/invariant | Trigger | Positive | Failure | Actor/context | Executor/transaction | Runtime/dialect | Edge | Level | Command |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Summary parity | Built-in/external CRUD/list/unknown | Same step and persisted label | Payload/path/SQL/secret omitted; existing offer gates | Authenticated owned thread | Existing ChatService turn lifetime | Node/SQLite | Model/driver callbacks → existing SSE | Route integration/unit | chat test |\n| CLI adapter | Stub text/tool/hold | Ordered persisted callbacks, full args, shared labels | Abort, failure, unoffered tool; no held success | Bound principal and host owner observer | Existing chat author; MCP host executes | Node/SQLite; subprocess OS | Inference runAgentTurn + token lifetime | Integration | chat test |\n| ChatGPT factory | Fake plan model | Raw calls, progress, usage and signal | No unsupported options or API fallback | Per-request connection | No database writes | Node | Inference createChatGPTModel | Unit | chat test |\n| Per-user selection | Stored binding/status | Each user gets their selected engine | Missing/unknown/unready refused, no fallback | Authenticated Request | Refusal before ChatService writes | Node | Existing resolver hooks | Unit/route regressions | chat test |\n\n## Rebase interaction validation\n\n| Behavior | Positive | Negative | Principal / executor | Boundary / check |\n| --- | --- | --- | --- | --- |\n| External manifest exposure | Enabled tools retain shared summaries | Disabled/unreadable models absent; a live closure refuses callbacks and approval acceptance | Original authenticated tenant; MCP endpoint remains effect authority | Driver bridge and real CLI stubs; chat suite |\n| Saved owner approval | One execution after restart authors the shared outcome label | Refused/denied holds keep diagnostics and cannot replay | Captured principal/permission ceiling; existing durable authority and dispatcher | SQLite mounted routes; chat suite |\n| App replacement and STI | Canonical provider identity gates the effective app class; explicit create subtype survives summary generation | Closed gate prevents dispatch | Original tenant; registry collection dispatcher | Tool-loop integration; chat suite |\n\nConnect AI has no record/reference-picker dependency. It configures inference\nbefore model offerings exist; reference picker source and screen composition are\nunchanged. No artificial picker adapter is introduced.\n\n## Reuse check\n\nConfigured MCP `review_smrt_project` reviewed chat and smrt-svelte; `build_context`\narchitecture query searched tool descriptions, engine adapters and connection\ncomposition. The server exposes architecture/model listings but no standalone\ncomponent/intent/recipe search. Read the intent index and used `rg` name AND purpose\nsearches over smrt-ui, smrt-svelte, chat, core, inference and app-shell for\n`toolSummary`, `summary`, `describeTool`, `ConnectAi`, `connect AI`, sign-in,\n`runAgentTurn`, model factories, approvals, recipes and onboarding/settings.\n\nNew `src/tool-summary.ts` extends existing describe/label events, moving shell's\nsummary purpose to chat; reuses ToolInvocation's result shape. New `src/engines.ts`\nreuses inference's engines, types and fake CLI fixtures, existing turn callbacks,\nChatService, route resolver/factory and trusted approval waiter. No new model,\nroute or tool is registered. Its internal serialization queue only adapts the\nsynchronous inference emitter to awaited chat callbacks. New tests extend the\nexisting SQLite route fixtures, with isolated engine fakes in engines.test.ts.\nNo equivalent shared adapter or summary generator existed in the owning packages.\n\nRebase reuse search: MCP `review_smrt_project` on chat/smrt-svelte and `rg`\n`isManifestToolEnabled|isToolEnabled` plus exposure purpose searches in core,\nchat, smrt-ui and smrt-svelte found core's `isRuntimeModelEnabled` and the four\nexisting chat dispatcher checks. `isManifestToolEnabled` consolidates those\nchecks in their existing owning module; external drivers reuse it. No new file.\n\nManifest create offerings and execution\nnow use core's public `ObjectRegistry.getCreateTargets` / `resolveCreateTarget`\nAPI ([contract](../../core/agents/generators.md#public-collection-create-targets-a1b)).\n`createType` is an optional qualified create target; `_meta_type` is a compatible alias.\nThe model's `type` field remains business data, including on STI families.\nSelection occurs before filtering and uses the selected model's writable policy;\nselectors are not persisted fields. Offerings and execution both use the original\nprincipal's live runtime exposure context. The Profile/Bot assistant canary and\n`src/create-targets.test.ts` cover all four dispatch paths, replacement, labels,\nreadonly fields, malformed/foreign choices and gated children on SQLite.\n\n`./tool-summary` is a browser-safe entry. The optional fourth `toolSummary`\nargument supports `recordLabels: 'generic'` and `plainTextSummary: true` for\nsaved-product wording/replay. All safety guards remain shared; default labels\nare unchanged. Tricia is a thin policy adapter over these options.\n\n## Live-engine failures (R7/R8)\n\n### Next live round: behavior contract\n\n| Behavior / trigger | Positive | Refusal/control | Actor, executor and runtime | Evidence |\n| --- | --- | --- | --- | --- |\n| CLI offerings | Named Customer create exposes inline contact fields and recipe vocabulary | Dependency-only identities and API-only deletes absent; revoked/gated offers cannot resume | Captured user/tenant, original ceiling; existing MCP dispatcher; Node/SQLite | Real host + inference stub, then bounded built-app Claude turn |\n| Held CLI delete | Existing continuation binds thread, original arguments and principal; owner decides once | Repeated decision, revoked offer/permission, foreign owner/tenant and abort cannot replay | Existing OwnerApprovalContinuations/authority CAS, existing collection executor; Node/SQLite | Host route fixture + live exposed-list delete |\n| Capability words | Introduction and model guidance follow selected engine's offered operations | No blanket deletion claim when any named list omits it | Authenticated host; no effect executor | Host introduction and built browser |\n| Startup readiness | Only an explicit successful preflight is ready | Missing/false preflight, signed out, absent CLI and unsupported tool host refuse | CLI's own status, sanitized environment; no model request | Inference/Connect tests + built app |\n| Active stop | Abort while a real app tool is in flight leaves no CLI child and a stopped thread | Never report a pending hold or an interrupted effect as completed | Existing child tree cleanup and ChatService turn state | Stub abort + bounded live read/tool turn |\n\nReuse: repeated MCP `review_smrt_project` on chat, inference, runtime, Svelte and\ntemplate; `build_context` searched turn-bound continuations, hidden prerequisite\nofferings and recipe labels. Intent index and name/purpose `rg` searches across\nUI/Svelte/chat/core/runtime found OwnerApprovalContinuations, buildCookbookShell,\nthe existing describe callback and live MCP identity map. Extend those paths;\nno new approval store, dispatcher, model, route or component is introduced.\n\nEngine binding and unexpected driver failures use inference's safe correlated\nserver diagnostic before replacing exceptions with fixed user words and a\nreference. External failures preserve real partial output but do not persist a\nsecond generic error bubble. The existing pending-send entry owns the transport\nerror and retry. AssistantDock suppresses only the matching duplicate banner and\ntells AssistantComposer to restore the draft without a second send alert;\nstandalone composers retain their default alert and other dock errors stay visible.\nThe same status line also renders the controller's existing idle `Stopped`\nlabel after cancellation; it does not duplicate transport errors or invent a\ncompleted reply for an interrupted turn. A mounted active-tool cancellation\ntest verifies the stopped line, aborted signal, no retry and no error alert.\nTests drive the mounted dock, preserve draft/retry/a11y, and launch both inference\nstub engines under the exact desktop `buildSidecarEnv` composition. No desktop\nproduction environment policy changed. Reuse the desktop environment helper via\na test-only import; no duplicate environment builder is introduced.\n\nS1: canonical dotted `app.describe`, `app.history`, `recipes.search` and `recipes.describe` names use the existing person-facing summary table, including durable workflow steps. Unknown tool payloads remain hidden. ChatGPT failures pass their cause to inference's existing correlated failure reporter; only allow-listed codes and bounded `req_` or UUID request ids are logged, never exception messages or accounts.\n"
4570
4583
  },
4571
4584
  {
4572
4585
  "path": "agents/runtime-exposure.md",
4573
4586
  "module": "runtime-exposure",
4574
4587
  "content": "# Runtime cookbook exposure\n\nSee [the owning core contract](../../core/agents/runtime-exposure.md) for the\nopt-in gate, trusted tenant selection, failure behavior, notification lifecycle\nand AOT/startup limits. This package reuses that gate in its existing dispatcher;\nit does not implement a second cookbook engine or operation execution path.\n\nThe manifest tool loop filters the offered catalog under `principal.tenantId`\nand checks again before executing either the normal dispatcher or an injected\nexecutor. `invokeManifestTool` independently rechecks using the principal run's\ntenant. The AOT permission catalog remains intact for typo validation. External\ndrivers and CLI adapters reuse the same manifest identity check on\ninitial offerings, live tool callbacks and approval acceptance. Their MCP host\nmust independently gate execution under the original principal: callbacks can\narrive after an effect. Extra tools and browser tools remain host integrations\nand must use core's gate when they expose model operations.\n\nDurably held manifest calls re-enter the same dispatcher on owner approval; a\nmodel disabled in the meantime (or an unreadable enabled set) refuses execution.\nThe existing ledger records terminal `failed` with `result.status: 'refused'`,\nand the transcript records `status: 'refused'`. It cannot be retried by approving\nagain. Approval lists keep their original saved public projection, without\narguments, recovery context, results or current model metadata. The SQLite\nmounted-route regression covers both disabling and store-read failure.\n\nIf a chat-owned external approval has already been consumed when exposure closes,\nthe bridge records terminal `failed` / `result.status: 'refused'` before returning\na denied decision. A host-owned CLI observer never mutates that host's ledger.\n"
4575
4588
  },
4589
+ {
4590
+ "path": "agents/assistant-turn-runs.md",
4591
+ "module": "assistant-turn-runs",
4592
+ "content": "# Assistant turns as AI runs (#5005)\n\n`mountAssistantRoutes` builds a tracked client per turn\n(`createTrackedAiClient`, the principal's tenant on the request's database,\nover the turn's client, `transcript: false` because chat stores the\nconversation) and passes `tracking` to `runAssistantTurn`\n(`turn-tracking.ts`). The turn then opens one `turn` run before its first\nmodel call (`AssistantTurnRun.open`, definition `chat.assistant.turn`), the\ntool loop calls the tracked client (each model call is a reserved, settled\ncall of the run: one usage row and one `call` event, tagged with the prompt\nkey), tool use is an `action` event and its result an `observation` event\nwhose `parent_event_id` is the action, and the run ends `done` (`cancelled`\nfor an abort, `failed` for an error). Messages are never copied into the\ntrajectory: events point at them with `payload_ref` (`chat-message:<id>`).\nA turn that needs an owner approval records a requested `approval` event\n(`payload_ref` `approval:<id>`) and ends `done` with the approval pending; it\ndoes not wait. The decision is recorded as an `approval` event in the NEXT\nturn's run, once, with `parent_event_id` the request in the earlier run\n(`tracking.decisions` reads the thread's decided approvals from the host's\nstore). A chat turn does not run untracked: with usage persistence off it ends\nwith the user-facing error `ai_tracking_disabled` before any call is sent.\nA ChatGPT plan turn is a built-in loop over a host-built client: its calls\nare recorded under the engine (`label` on `createTrackedAiClient`, provider\n`chatgpt`, the bound model unless the response reports one), uncosted, with\n`tier_requested`/`tier_resolved` from the prompt and the selection.\n\n## A turn on an external engine (Claude Code, Codex)\n\nAn external `turnDriver` turn opens the same run. The engine's turn is ONE\ntracked call of it (`AssistantTurnRun.beginEngineCall`, reserved in\n`runExternalAssistantAttempt` before `driver.run`, call id minted first):\nthe engine runs its own loop and reports one result per turn, so its internal\nmodel calls are not seen one by one. The usage row's provider is the engine\nid, its model the one the CLI reported (Claude Code does; Codex does not),\nelse the tier binding's; it carries the prompt key and tiers and is always\nuncosted. Tokens are the CLI's reported usage (`EngineExecution.tokens`,\nsplit into `inputTokens`/`outputTokens`, cache reads and writes in the\ninput); a turn that answered without them is charged what it reserved (ai-runs\nsection 6.4) and its row has NULL token columns. A refused reservation\n(`maxCalls`, `maxTokens`, `maxDurationMs`, or a parent's limit or stop) ends\nthe turn `budget` before the CLI starts; `callTimeoutMs` aborts the CLI and\nfails the turn. A turn that fails, is cancelled or hands off to a workflow is\nsettled with its tokens when the CLI reported them, else released. Limits:\n`maxSteps` cannot bound the CLI's internal rounds (a workflow parent's step\nlimit still refuses the child's call), and a parent stop or cancel during an\nengine turn takes effect at its end, not by interrupting the CLI. Tests:\n`sveltekit.test.ts` (external engine), `engines.test.ts` (real driver over\nthe stub CLI), `turn-tracking-child.test.ts`.\n\nThe system prompt is the registered prompt `chat.assistant.system`\n(`chatAssistantSystemPrompt`): the host's `systemPrompt` option is its runtime\nlayer and an app or tenant override of the key replaces it\n(`resolveChatAssistantPrompt`). The text is sent only when a layer above the\ndefault supplies it, so a host with no `systemPrompt` sends no system message,\nas before. The prompt declares the tier the assistant asks for, `ai.profile: 'best'`;\n`resolveChatAssistantTier({ db, tenantId })` reads it back through\n`resolvePrompt` (so config and stored layers apply) and a host binds the\nturn's model at that tier.\n\n## A workflow step's turn (child run)\n\nA host's trusted `internalTurn` may return `step: { parent, prompt,\nstepIndex, name }` (the template-sveltekit host does, for each workflow step\nit runs through the assistant route). The turn's run is then a CHILD of the\nworkflow run (`parent_run_id`, opened with a `handoff` event in the parent\nnamed after the step, in the same transaction); its calls carry the parent's\nclaim fence and are tracked under the step's registered `prompt` (whose text\nfollows the host's system prompt), so they roll into the parent's inclusive\ntotals and budget. A parent stop or limit stops the child's next call, and\nwhen the turn ends a stopped or cancelled child stops the parent the same way\n(`stopAiRunForChild`); cancelling the parent cancels the child. The turn\ncloses the `handoff` with how the child ended. A step on an external engine\nis the same child run with its one engine call. Tests:\n`turn-tracking-child.test.ts`.\n"
4593
+ },
4576
4594
  {
4577
4595
  "path": "agents/ai-unavailable.md",
4578
4596
  "module": "ai-unavailable",
@@ -5,10 +5,10 @@ description: "Chat rooms, DMs, threads, and agent conversations for the SMRT fra
5
5
  status: "stable"
6
6
  generated:
7
7
  by: "smrt/scripts/generate-knowledge-okf.ts"
8
- at: "2026-11-13T04:10:05Z"
8
+ at: "2026-11-16T07:36:23Z"
9
9
  audience: "internal"
10
10
  evidence_level: "source-inspected"
11
- source_revision: "sha256:29dca37e4d24196b2775d936bb0b398380e8d7fc155a27e129cf3b733fcdd191"
11
+ source_revision: "sha256:1db30214dd6191d94dac322248575c3b48d27a7daed4daa069964eb5af925e0e"
12
12
  sources:
13
13
  - id: "manifest"
14
14
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/package.json"
@@ -23,33 +23,36 @@ sources:
23
23
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/assistant-questions.md"
24
24
  title: "@happyvertical/smrt-chat packages/chat/agents/assistant-questions.md"
25
25
  - id: "agents-4"
26
+ resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/assistant-turn-runs.md"
27
+ title: "@happyvertical/smrt-chat packages/chat/agents/assistant-turn-runs.md"
28
+ - id: "agents-5"
26
29
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/dev-workbench.md"
27
30
  title: "@happyvertical/smrt-chat packages/chat/agents/dev-workbench.md"
28
- - id: "agents-5"
31
+ - id: "agents-6"
29
32
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/overview-tools.md"
30
33
  title: "@happyvertical/smrt-chat packages/chat/agents/overview-tools.md"
31
- - id: "agents-6"
34
+ - id: "agents-7"
32
35
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/owner-approvals.md"
33
36
  title: "@happyvertical/smrt-chat packages/chat/agents/owner-approvals.md"
34
- - id: "agents-7"
37
+ - id: "agents-8"
35
38
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/recipes.md"
36
39
  title: "@happyvertical/smrt-chat packages/chat/agents/recipes.md"
37
- - id: "agents-8"
40
+ - id: "agents-9"
38
41
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/runtime-exposure.md"
39
42
  title: "@happyvertical/smrt-chat packages/chat/agents/runtime-exposure.md"
40
- - id: "agents-9"
43
+ - id: "agents-10"
41
44
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/runtime-report-tools.md"
42
45
  title: "@happyvertical/smrt-chat packages/chat/agents/runtime-report-tools.md"
43
- - id: "agents-10"
46
+ - id: "agents-11"
44
47
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/token-streaming.md"
45
48
  title: "@happyvertical/smrt-chat packages/chat/agents/token-streaming.md"
46
- - id: "agents-11"
49
+ - id: "agents-12"
47
50
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/tool-loop.md"
48
51
  title: "@happyvertical/smrt-chat packages/chat/agents/tool-loop.md"
49
- - id: "agents-12"
52
+ - id: "agents-13"
50
53
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/tool-summaries.md"
51
54
  title: "@happyvertical/smrt-chat packages/chat/agents/tool-summaries.md"
52
- - id: "agents-13"
55
+ - id: "agents-14"
53
56
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/chat/agents/turn-drivers.md"
54
57
  title: "@happyvertical/smrt-chat packages/chat/agents/turn-drivers.md"
55
58
  ---
@@ -68,6 +71,7 @@ sources:
68
71
  - `packages/chat/AGENTS.md`
69
72
  - `packages/chat/agents/ai-unavailable.md`
70
73
  - `packages/chat/agents/assistant-questions.md`
74
+ - `packages/chat/agents/assistant-turn-runs.md`
71
75
  - `packages/chat/agents/dev-workbench.md`
72
76
  - `packages/chat/agents/overview-tools.md`
73
77
  - `packages/chat/agents/owner-approvals.md`
@@ -91,6 +95,7 @@ sources:
91
95
  - [smrt-personas](/components/smrt-personas.md)
92
96
  - [smrt-playground](/components/smrt-playground.md)
93
97
  - [smrt-profiles](/components/smrt-profiles.md)
98
+ - [smrt-prompts](/components/smrt-prompts.md)
94
99
  - [smrt-reports](/components/smrt-reports.md)
95
100
  - [smrt-scanner](/components/smrt-scanner.md)
96
101
  - [smrt-tenancy](/components/smrt-tenancy.md)
@@ -1164,8 +1164,8 @@ async function handleConfirmAction(requestId: string) {
1164
1164
  {#if controller.status.state === 'working' || (controller.status.state === 'idle' && controller.status.label)}
1165
1165
  <div class="smrt-assistant-dock__status" role="status" aria-live="polite">
1166
1166
  <span class="smrt-assistant-dock__status-label">{controller.status.label}</span>
1167
- {#if controller.designRun?.status === 'stopped'}
1168
- <Button type="button" size="sm" variant="ghost" onclick={() => controller.resumeDesignRun()}>{t(M['chat.assistant_dock.resume_design'])}</Button>
1167
+ {#if controller.workflowRun?.status === 'stopped'}
1168
+ <Button type="button" size="sm" variant="ghost" onclick={() => controller.resumeWorkflowRun()}>{t(M['chat.assistant_dock.resume_workflow'])}</Button>
1169
1169
  {/if}
1170
1170
  {#if controller.status.cancellable}
1171
1171
  <Button type="button" size="sm" variant="ghost" onclick={() => controller.cancel()}>
@@ -26,8 +26,8 @@ export interface AssistantHttpOptions {
26
26
  }
27
27
  /** Options for {@link createAssistantHttpTransport}. */
28
28
  export interface AssistantHttpTransportOptions extends AssistantHttpOptions {
29
- /** Enable authenticated host design-run status and control routes. */
30
- designRuns?: boolean;
29
+ /** Enable authenticated host workflow run status and control routes. */
30
+ workflowRuns?: boolean;
31
31
  /** When set, the dock renders `ModelPicker`; the server checks the choice. */
32
32
  models?: ModelOption[];
33
33
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"assistant-http-client.d.ts","sourceRoot":"","sources":["../../../../src/svelte/components/assistant/assistant-http-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EACV,wBAAwB,EAExB,mBAAmB,EACpB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,KAAK,qBAAqB,EAE3B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAQL,KAAK,kBAAkB,EAGvB,KAAK,WAAW,EAIjB,MAAM,0BAA0B,C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EAAE,IAAI,CAAC,mBAAmB,EAAE,SAAS,CAAC,CAAC;IAChD,uDAAuD;IACvD,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,wBAAwB,KAAK,MAAM,GAAG,SAAS,CAAC;CAC9E;AAED;;;;;;;;GAQG;AACH,wBAAgB,+BAA+B,CAC7C,OAAO,EAAE,gCAAgC,GACxC,qBAAqB,CAkEvB"}
1
+ {"version":3,"file":"assistant-http-client.d.ts","sourceRoot":"","sources":["../../../../src/svelte/components/assistant/assistant-http-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EACV,wBAAwB,EAExB,mBAAmB,EACpB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,KAAK,qBAAqB,EAE3B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAOL,KAAK,kBAAkB,EAIvB,KAAK,WAAW,EAIjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,8CAA8C,CAAC;AAE1F,8DAA8D;AAC9D,MAAM,WAAW,oBAAoB;IACnC,sEAAsE;IACtE,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;IACzB,yEAAyE;IACzE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAClE,4DAA4D;IAC5D,WAAW,CAAC,EAAE,kBAAkB,CAAC;CAClC;AAED,wDAAwD;AACxD,MAAM,WAAW,6BAA8B,SAAQ,oBAAoB;IACzE,wEAAwE;IACxE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,8EAA8E;IAC9E,MAAM,CAAC,EAAE,WAAW,EAAE,CAAC;IACvB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACrE;AAED,0EAA0E;AAC1E,qBAAa,kBAAmB,SAAQ,KAAK;IAGzC,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS;IACjC,0EAA0E;IAC1E,QAAQ,CAAC,WAAW,CAAC,EAAE,qBAAqB;gBAJ5C,OAAO,EAAE,MAAM,EACN,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GAAG,SAAS;IACjC,0EAA0E;IACjE,WAAW,CAAC,EAAE,qBAAqB,YAAA;CAK/C;AAmFD;;;;GAIG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,6BAA6B,GACrC,kBAAkB,CAiIpB;AAED,2DAA2D;AAC3D,MAAM,WAAW,gCAAiC,SAAQ,oBAAoB;IAC5E;;;;OAIG;IACH,QAAQ,CAAC,EAAE,IAAI,CAAC,mBAAmB,EAAE,SAAS,CAAC,CAAC;IAChD,uDAAuD;IACvD,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,wBAAwB,KAAK,MAAM,GAAG,SAAS,CAAC;CAC9E;AAED;;;;;;;;GAQG;AACH,wBAAgB,+BAA+B,CAC7C,OAAO,EAAE,gCAAgC,GACxC,qBAAqB,CAkEvB"}
@@ -118,7 +118,7 @@ export function createAssistantHttpTransport(options) {
118
118
  return value ? { context: value } : {};
119
119
  };
120
120
  const threadPath = (threadId, leaf) => `/threads/${encodeURIComponent(threadId)}/${leaf}`;
121
- const readDesignRun = async (response) => {
121
+ const readWorkflowRun = async (response) => {
122
122
  if (!response.ok)
123
123
  throw await failure(response);
124
124
  return (await response.json()).run;
@@ -180,11 +180,11 @@ export function createAssistantHttpTransport(options) {
180
180
  });
181
181
  return {
182
182
  ...transport,
183
- ...(options.designRuns
183
+ ...(options.workflowRuns
184
184
  ? {
185
- designRun: (threadId) => request(`${base}/design-runs?threadId=${encodeURIComponent(threadId)}`).then(readDesignRun),
186
- stopDesignRun: (runId) => postJson(`/design-runs/${encodeURIComponent(runId)}/stop`, {}).then(readDesignRun),
187
- resumeDesignRun: (runId) => postJson(`/design-runs/${encodeURIComponent(runId)}/resume`, {}).then(readDesignRun),
185
+ workflowRun: (threadId) => request(`${base}/runs?threadId=${encodeURIComponent(threadId)}`).then(readWorkflowRun),
186
+ stopWorkflowRun: (runId) => postJson(`/runs/${encodeURIComponent(runId)}/stop`, {}).then(readWorkflowRun),
187
+ resumeWorkflowRun: (runId) => postJson(`/runs/${encodeURIComponent(runId)}/resume`, {}).then(readWorkflowRun),
188
188
  }
189
189
  : {}),
190
190
  async listApprovals(threadId) {
@@ -127,10 +127,11 @@ export interface AssistantSendMessageResult {
127
127
  calls: AssistantClientToolCall[];
128
128
  };
129
129
  }
130
- /** Durable design progress, supplied by an authenticated host. */
131
- export interface AssistantDesignRun {
130
+ /** Durable workflow run progress, supplied by an authenticated host. */
131
+ export interface AssistantWorkflowRun {
132
132
  runId: string;
133
- pass: {
133
+ /** The step the run is on (one-based) and the host's plain name for it. */
134
+ step: {
134
135
  index: number;
135
136
  count: number;
136
137
  name: string;
@@ -139,9 +140,9 @@ export interface AssistantDesignRun {
139
140
  note?: string;
140
141
  }
141
142
  export interface AssistantTransport {
142
- designRun?(threadId: string): Promise<AssistantDesignRun | undefined>;
143
- stopDesignRun?(runId: string): Promise<AssistantDesignRun | undefined>;
144
- resumeDesignRun?(runId: string): Promise<AssistantDesignRun | undefined>;
143
+ workflowRun?(threadId: string): Promise<AssistantWorkflowRun | undefined>;
144
+ stopWorkflowRun?(runId: string): Promise<AssistantWorkflowRun | undefined>;
145
+ resumeWorkflowRun?(runId: string): Promise<AssistantWorkflowRun | undefined>;
145
146
  listApprovals?(threadId?: string): Promise<AssistantApprovalView[]>;
146
147
  decideApproval?(id: string, approve: boolean): Promise<AssistantApprovalView>;
147
148
  listThreads(): Promise<AssistantThreadSummary[]>;
@@ -1 +1 @@
1
- {"version":3,"file":"assistant-trans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CAAC;QACnE;8CACsC;QACtC,UAAU,CAAC,EAAE,CACX,KAAK,EAAE,wBAAwB,KAC5B,OAAO,CAAC,0BAA0B,CAAC,CAAC;KAC1C,CAAC;IACF;;6EAEyE;IACzE,MAAM,CAAC,EAAE,WAAW,EAAE,CAAC;IACvB,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;CAC1B;AAkBD;;;;;;;;GAQG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,6BAA6B,GACrC,kBAAkB,CA2DpB;AAED;;;;;;;GAOG;AACH,wBAAsB,uBAAuB,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACvE,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE;IACP,UAAU,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,gBAAgB,CAAC;IAC1C,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,uBAAuB,KAAK,IAAI,CAAC;CACpD,GACA,OAAO,CAAC,0BAA0B,CAAC,CA2CrC"}
1
+ {"version":3,"file":"assistant-transport.d.ts","sourceRoot":"","sources":["../../../../src/svelte/components/assistant/assistant-transport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EACL,KAAK,qBAAqB,EAC1B,KAAK,uBAAuB,EAC5B,KAAK,8BAA8B,EACnC,KAAK,yBAAyB,EAC9B,KAAK,kBAAkB,EAExB,MAAM,mCAAmC,CAAC;AAC3C;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AAE5E,MAAM,WAAW,sBAAsB;IACrC,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,OAAO,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAAC;CACtC;AAED,MAAM,WAAW,gB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