@happyvertical/smrt-chat 0.60.18 → 0.61.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 (86) hide show
  1. package/AGENTS.md +16 -22
  2. package/README.md +78 -0
  3. package/agents/owner-approvals.md +161 -0
  4. package/agents/runtime-exposure.md +28 -0
  5. package/agents/runtime-report-tools.md +26 -0
  6. package/agents/token-streaming.md +6 -0
  7. package/agents/tool-loop.md +13 -0
  8. package/agents/tool-summaries.md +155 -0
  9. package/agents/turn-drivers.md +293 -0
  10. package/dist/assistant-approvals.d.ts +45 -0
  11. package/dist/assistant-approvals.d.ts.map +1 -0
  12. package/dist/assistant-approvals.js +83 -0
  13. package/dist/assistant-approvals.js.map +1 -0
  14. package/dist/assistant-turn-driver.d.ts +73 -0
  15. package/dist/assistant-turn-driver.d.ts.map +1 -0
  16. package/dist/assistant-turn-events.d.ts +28 -1
  17. package/dist/assistant-turn-events.d.ts.map +1 -1
  18. package/dist/assistant-turn-events.js +2 -2
  19. package/dist/assistant-turn.d.ts +24 -37
  20. package/dist/assistant-turn.d.ts.map +1 -1
  21. package/dist/chunks/{ChatService-BGBAqmZq.js → ChatService-C1UBz0MR.js} +684 -657
  22. package/dist/chunks/ChatService-C1UBz0MR.js.map +1 -0
  23. package/dist/chunks/{assistant-turn-events-BbZUf-Ju.js → assistant-turn-events-DwdCZzQ0.js} +15 -2
  24. package/dist/chunks/assistant-turn-events-DwdCZzQ0.js.map +1 -0
  25. package/dist/chunks/chat-stream-mTbNV3kt.js +3571 -0
  26. package/dist/chunks/chat-stream-mTbNV3kt.js.map +1 -0
  27. package/dist/engines.d.ts +34 -0
  28. package/dist/engines.d.ts.map +1 -0
  29. package/dist/engines.js +260 -0
  30. package/dist/engines.js.map +1 -0
  31. package/dist/index.d.ts +4 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +8 -6
  34. package/dist/index.js.map +1 -1
  35. package/dist/internal/agent-runtime.js +1 -1
  36. package/dist/manifest.json +3 -1
  37. package/dist/persona-conversation.d.ts.map +1 -1
  38. package/dist/runtime-report-tools.d.ts.map +1 -1
  39. package/dist/services/ChatService.d.ts +3 -13
  40. package/dist/services/ChatService.d.ts.map +1 -1
  41. package/dist/smrt-knowledge.json +46 -9
  42. package/dist/smrt-knowledge.okf.md +29 -4
  43. package/dist/svelte/components/assistant/AssistantApprovalCard.svelte +198 -0
  44. package/dist/svelte/components/assistant/AssistantApprovalCard.svelte.d.ts +34 -0
  45. package/dist/svelte/components/assistant/AssistantApprovalCard.svelte.d.ts.map +1 -0
  46. package/dist/svelte/components/assistant/AssistantComposer.svelte +6 -3
  47. package/dist/svelte/components/assistant/AssistantComposer.svelte.d.ts +2 -0
  48. package/dist/svelte/components/assistant/AssistantComposer.svelte.d.ts.map +1 -1
  49. package/dist/svelte/components/assistant/AssistantDock.svelte +66 -17
  50. package/dist/svelte/components/assistant/AssistantDock.svelte.d.ts +2 -0
  51. package/dist/svelte/components/assistant/AssistantDock.svelte.d.ts.map +1 -1
  52. package/dist/svelte/components/assistant/assistant-http-client.d.ts +2 -0
  53. package/dist/svelte/components/assistant/assistant-http-client.d.ts.map +1 -1
  54. package/dist/svelte/components/assistant/assistant-http-client.js +28 -1
  55. package/dist/svelte/components/assistant/assistant-transport.d.ts +18 -1
  56. package/dist/svelte/components/assistant/assistant-transport.d.ts.map +1 -1
  57. package/dist/svelte/components/assistant/assistant-transport.js +2 -0
  58. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.d.ts +5 -1
  59. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.d.ts.map +1 -1
  60. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.js +80 -4
  61. package/dist/svelte/i18n.d.ts +14 -0
  62. package/dist/svelte/i18n.d.ts.map +1 -1
  63. package/dist/svelte/i18n.js +14 -0
  64. package/dist/svelte/i18n.messages.d.ts +13 -0
  65. package/dist/svelte/i18n.messages.d.ts.map +1 -1
  66. package/dist/svelte/i18n.messages.js +13 -0
  67. package/dist/svelte/index.d.ts +2 -1
  68. package/dist/svelte/index.d.ts.map +1 -1
  69. package/dist/svelte/index.js +1 -0
  70. package/dist/sveltekit.d.ts +72 -4
  71. package/dist/sveltekit.d.ts.map +1 -1
  72. package/dist/sveltekit.js +439 -21
  73. package/dist/sveltekit.js.map +1 -1
  74. package/dist/tool-loop.d.ts +36 -3
  75. package/dist/tool-loop.d.ts.map +1 -1
  76. package/dist/tool-summary.d.ts +15 -0
  77. package/dist/tool-summary.d.ts.map +1 -0
  78. package/dist/tool-summary.js +95 -0
  79. package/dist/tool-summary.js.map +1 -0
  80. package/dist/work-profile.d.ts +64 -0
  81. package/dist/work-profile.d.ts.map +1 -0
  82. package/package.json +36 -22
  83. package/dist/chunks/ChatService-BGBAqmZq.js.map +0 -1
  84. package/dist/chunks/assistant-turn-events-BbZUf-Ju.js.map +0 -1
  85. package/dist/chunks/chat-stream-Blri3lj0.js +0 -2743
  86. package/dist/chunks/chat-stream-Blri3lj0.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-report-tools.d.ts","sourceRoot":"","sources":["../src/runtime-report-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAGH,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,aAAa,EAEnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAiBL,KAAK,6BAA6B,EAClC,KAAK,iBAAiB,EAIvB,MAAM,6BAA6B,CAAC;AAQrC,OAAO,KAAK,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AAGpF,6EAA6E;AAC7E,eAAO,MAAM,gCAAgC,4BAA4B,CAAC;AAC1E,yEAAyE;AACzE,eAAO,MAAM,+BAA+B,2BAA2B,CAAC;AACxE,oDAAoD;AACpD,eAAO,MAAM,6BAA6B,yBAAyB,CAAC;AACpE,qDAAqD;AACrD,eAAO,MAAM,4BAA4B,wBAAwB,CAAC;AAElE,k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oD;AACpD,MAAM,WAAW,yBAAyB;IACxC,uEAAuE;IACvE,OAAO,EACH,SAAS,uBAAuB,EAAE,GAClC,CAAC,CACC,GAAG,EAAE,YAAY,KAEf,SAAS,uBAAuB,EAAE,GAClC,OAAO,CAAC,SAAS,uBAAuB,EAAE,CAAC,CAAC,CAAC;IACrD,qFAAqF;IACrF,YAAY,CAAC,EAAE,6BAA6B,CAAC;IAC7C,mDAAmD;IACnD,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,uBAAuB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACjE;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,kCAAkC,CAAC;IACvD,8CAA8C;IAC9C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,wDAAwD;IACxD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAoTD;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,yBAAyB,GACjC,aAAa,EAAE,CAkQjB"}
@@ -399,25 +399,14 @@ export declare class ChatService {
399
399
  actorProfileId: string;
400
400
  tenantId: string;
401
401
  }): Promise<ChatThread[]>;
402
- /**
403
- * Read messages within a thread, tenant- and membership-bound (S5 #1392).
404
- *
405
- * The thread is resolved tenant-bound; the caller must be an active member of
406
- * the thread's room. Messages are returned oldest-first (chronological).
407
- * Replaces direct `messages.list({ where: { threadId } })` reach-ins that
408
- * could read another tenant's/room's thread history by raw id.
409
- *
410
- * `roles` (non-empty) keeps only those roles, in SQL, so `limit` counts
411
- * them alone: a history builder passes the roles it replays and gets the
412
- * newest `limit` of those, however many tool rows sit between (#4458).
413
- * Omitted or empty reads every role.
414
- */
415
402
  getThreadMessages(params: {
416
403
  threadId: string;
417
404
  actorProfileId: string;
418
405
  tenantId: string;
419
406
  limit?: number;
420
407
  roles?: readonly ChatMessageRole[];
408
+ /** Trusted presentation query only. Raw provider history remains the default. */
409
+ visibility?: 'conversation';
421
410
  }): Promise<ChatMessage[]>;
422
411
  /**
423
412
  * A stored message and the replies linked to it (`replyToMessageId`),
@@ -432,6 +421,7 @@ export declare class ChatService {
432
421
  actorProfileId: string;
433
422
  tenantId: string;
434
423
  limit?: number;
424
+ visibility?: 'conversation';
435
425
  }): Promise<{
436
426
  message: ChatMessage;
437
427
  replies: ChatMessage[];
@@ -1 +1 @@
1
- {"version":3,"file":"ChatService.d.ts","sourceRoot":"","sources":["../../src/services/ChatService.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,KAAK,iBAAiB,EACvB,MAAM,0BAA0B,CAAC;AAYlC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,mBAAmB,EACnB,cAAc,EACd,YAAY,EACb,MAAM,aAAa,CAAC;AA2BrB;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,WAAW,GAAG,MAAM,CAAC;IAC5B,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAC9C;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CAC3C;AAED;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IACpC,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,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AO,CAAC,OAAO,CAAC;IAuFpB;;;;;;;OAOG;IACG,wBAAwB,CAAC,MAAM,EAAE;QACrC,cAAc,EAAE,MAAM,CAAC;QACvB,cAAc,EAAE,MAAM,CAAC;QACvB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;QACxB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;QACxB,YAAY,CAAC,EAAE,MAAM,CAAC;KACvB;IA8ED;;;;;;;;;;OAUG;IACH,MAAM,CAAC,CAAC,eAAe,CAAC,CACtB,OAAO,EAAE,iBAAiB,EAC1B,MAAM,EAAE,gBAAgB;CAO3B;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;AAEhE;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,cAAc,CAC5B,OAAO,EAAE,iBAAiB,EAC1B,MAAM,EAAE,gBAAgB,wBAGzB"}
@@ -3,17 +3,22 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-chat",
6
- "packageVersion": "0.60.18",
6
+ "packageVersion": "0.61.0",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "39e56027d878cde13f1398116dc79908032286f7a64d0773db5e19d14ff7fe13",
11
- "packageJson": "ee35fe9d14fee0ec60816c2433c1d938a648be1d23eb1b86646cb8420721611b",
12
- "agents": "ee0c14eaf728ecdb3379451fe8b8172be6a2617092418128744a48d3a72ee176",
10
+ "manifest": "80c86c622457f4bcd30db3e7aa18a68fed9c942e079a47fca8240e7ea5c0e585",
11
+ "packageJson": "f518fd03bcef8ef572c90d6e348e7ec0309efbb38a520265e4bd1eb991c6a160",
12
+ "agents": "fbd94d44959aac77683458b8f097bf398694b84bc40f604346105dddf2c03b8f",
13
13
  "moduleDoc:agents/dev-workbench.md": "f07a428519e8cca4a46371da0a3b33b9c8d3102f1d9056e4c8efba3c0b702048",
14
+ "moduleDoc:agents/runtime-report-tools.md": "116b6371207cec6bc8ee891a358b3457fc08d3ae86f9c31b428c6c13dfb25a40",
14
15
  "moduleDoc:agents/overview-tools.md": "752a4afb6b57a2e9224f3c65a98b0deb23cda87371f01ac0566f0887e9bb12da",
15
- "moduleDoc:agents/tool-loop.md": "81ec1de9c5fac66b526ae8b2feeda8f33f1916cff19c4060f09989ce79b2acc1",
16
- "moduleDoc:agents/token-streaming.md": "e92a28a8702d111a3751a86b8cdff30cb5146cc115fed86c227402bef1c683fd",
16
+ "moduleDoc:agents/tool-loop.md": "0ee8ea63193b9dac32a8719e2afc1bad97f0d88e319ddb00f660fa1720da5e0c",
17
+ "moduleDoc:agents/token-streaming.md": "016c711f3c269f6e93d156c909923201c2b4e1adbe6ece89d5291959c499a0ca",
18
+ "moduleDoc:agents/turn-drivers.md": "fb0e1755457a12aeedba70e3f53b28fd93a3bb7ce32e63082459b0d607601d3e",
19
+ "moduleDoc:agents/owner-approvals.md": "ad8b489636a4849a0191d53988158b24b7ea808dc2905e773260044d58b0172b",
20
+ "moduleDoc:agents/tool-summaries.md": "483557180c81a048a629dcec2852e5d68eb22cfee780cc4849662bb7867d8ce1",
21
+ "moduleDoc:agents/runtime-exposure.md": "4a55759e1d2e754d421cfb3b9150818c71b59b3aacc0c011f0f2f45507086b58",
17
22
  "moduleDoc:agents/ai-unavailable.md": "e12b175c932411c4445b59ee8144ae06cc962c430960b6c5a26e0002f2d15369",
18
23
  "moduleDoc:agents/assistant-questions.md": "a0371870b3bc99e313d8287912208f3e315bab7dc4ee138214895031ae79a5b0",
19
24
  "moduleDoc:agents/recipes.md": "89c2c86e4e26cea9ba10d917f8ad71c23a71d4fd8eaacf638a6cd252e2376c07",
@@ -21,10 +26,12 @@
21
26
  },
22
27
  "exports": [
23
28
  ".",
29
+ "./assistant-approvals",
24
30
  "./assistant-turn",
25
31
  "./client",
26
32
  "./data-surface",
27
33
  "./data-surface-bridge",
34
+ "./engines",
28
35
  "./helper-preferences",
29
36
  "./internal/agent-runtime",
30
37
  "./manifest",
@@ -32,6 +39,7 @@
32
39
  "./playground",
33
40
  "./svelte",
34
41
  "./sveltekit",
42
+ "./tool-summary",
35
43
  "./ui"
36
44
  ],
37
45
  "dependencies": {
@@ -39,6 +47,7 @@
39
47
  "@happyvertical/ai": "catalog:",
40
48
  "@happyvertical/speech": "catalog:",
41
49
  "@happyvertical/smrt-images": "workspace:*",
50
+ "@happyvertical/smrt-app-runtime": "workspace:*",
42
51
  "@happyvertical/smrt-agents": "workspace:*",
43
52
  "@happyvertical/smrt-assets": "workspace:*",
44
53
  "@happyvertical/smrt-config": "workspace:*",
@@ -53,6 +62,7 @@
53
62
  "@happyvertical/sql": "catalog:",
54
63
  "@happyvertical/images": "catalog:",
55
64
  "gsap": "^3.13.0",
65
+ "@happyvertical/smrt-inference": "workspace:*",
56
66
  "@happyvertical/smrt-playground": "workspace:*",
57
67
  "@happyvertical/smrt-scanner": "workspace:*",
58
68
  "@happyvertical/smrt-vitest": "workspace:*",
@@ -71,10 +81,12 @@
71
81
  },
72
82
  "smrtDependencies": [
73
83
  "@happyvertical/smrt-agents",
84
+ "@happyvertical/smrt-app-runtime",
74
85
  "@happyvertical/smrt-assets",
75
86
  "@happyvertical/smrt-config",
76
87
  "@happyvertical/smrt-core",
77
88
  "@happyvertical/smrt-images",
89
+ "@happyvertical/smrt-inference",
78
90
  "@happyvertical/smrt-personas",
79
91
  "@happyvertical/smrt-playground",
80
92
  "@happyvertical/smrt-profiles",
@@ -4514,13 +4526,18 @@
4514
4526
  "polymorphicAssociations": 0,
4515
4527
  "uuidColumns": 78
4516
4528
  },
4517
- "agentDoc": "# @happyvertical/smrt-chat\n\nChat rooms, threads, and agent sessions with app-controlled tool whitelisting.\n\n## Dev Server\n\n`pnpm --dir packages/chat dev` runs a package-local SvelteKit workbench. The root\nroute separates **Character setup** and **Chat dev** into tabs; switching tabs\nretains the current character rig and chat state. The chat tab is an interactive\nsurface with a dev-only `/api/dev-chat` endpoint:\nit uses `@happyvertical/ai` when local provider credentials are present and\nfalls back to a deterministic local assistant otherwise. `/api/dev-chat-stream`\nis its SSE companion (#1936) — the same provider/local-fallback resolution wired\nthrough `createChatStreamHandler` in plain mode, so an embedded `SmrtChatBackend`\nclient can exercise token streaming locally. `/previews` hosts the shared\ncomponent playground entries from `src/svelte/playground.ts`.\n\nThe root route also drives the **browser inference path**\n(`@happyvertical/smrt-web/ai`: bitgpu, WebLLM, and route backends composed by\n`createInferencePath`) and an **agent-addressable draft form** (`useViewIntent`\nover `src/routes/chat-dev.intents.ts`, #2588). Their dev-config dependencies\n(static optional-peer imports, `workspace-aliases.js` prefix rules, the theme\nstylesheet import) and the stage→apply tool-call gotchas are in\n[agents/dev-workbench.md](agents/dev-workbench.md).\n\nDev-only voice and opt-in local character persistence are documented in\n[agents/dev-workbench.md](agents/dev-workbench.md#voice-and-local-character-persistence).\nThese endpoints are loopback-only demos; production hosts supply authenticated\nprincipals, tenancy, and authorization to the owning services.\n\n## Models\n\nAll seven models expose only generated REST/MCP `list`/`get`; structural tests\ncheck the registry for mutating operations. Writes go through\nmembership/owner-checked `ChatService` or the binding-checked voice adapter.\n\n`ChatService` is a closed facade. Its collections and security-sensitive\nhelpers use ES `#private` fields/methods (TypeScript `private` is erased).\nCollection classes are not exported from the package index. The agent-reply\nbridge is a Symbol-keyed static accessible through a non-exported symbol held\nby the module-local `sendAgentReply` function.\n\n- **ChatRoom**: `roomType` (public/private/dm/agent), `status`, `topic`, `maxParticipants`, `lastMessageAt`. Tenant-scoped (required).\n- **ChatMessage**: shared by users + agents. `role` (user/assistant/system/tool), `messageType` (text/system/action/file/tool_call/tool_result), `toolCallData` JSON. Unified model — no separate agent message type. Tenant-scoped (required).\n- **ChatParticipant**: `role` (owner/admin/member/viewer), `onlineStatus`, `lastReadMessageId`, `isMuted`. Tenant-scoped (required).\n- **ChatThread**: `rootMessageId`, `isResolved`, `messageCount`. Created via `ChatService.startThread()` (member-checked). Tenant-scoped (required).\n- **ChatReaction**: `messageId`, `profileId`, `emoji`. Added/removed via `ChatService.addReaction()`/`removeReaction()` (member-checked, self-keyed). Tenant-scoped (required).\n- **AgentSession**: `agentId` (application slug, string ref, not FK), `agentProfileId` (nullable `crossPackageRef` to `Profile` — the `bot` profile the agent AUTHORS as, #2995), `allowedTools` (JSON string array), `sessionContext` (JSON, sensitive), `systemPrompt`, limits (`maxTokens`/`maxMessages`/`expiresAt`). Optional tenancy.\n- **VoiceSession**: short-lived voice-gateway binding over `(tenant, actorProfileId, personaId, room/thread/agentSession)` plus a persona snapshot, gateway `session_id`, expiry, replay tracking, and metadata. Tenant-scoped (required). Generated surface is read-only; creation and turns go through `createVoiceChatSession()` / `handleVoiceGatewayTurn()`.\n\n## ChatService\n\nPublic writes take server-supplied `actorProfileId`; never trust a request's\n`senderProfileId`, `role`, owner id, or participant id as authority.\n\n| Operation | Authorization and behavior |\n|---|---|\n| `sendMessage()` | Room member; authors as actor with `role: 'user'`; no public membership bypass |\n| `createRoom()` | Actor becomes owner |\n| `startThread()` | Member; optional root message bound to room and tenant |\n| `addParticipant()` / `removeParticipant()` | Owner/admin; self-leave allowed |\n| `updateRoom()` | Owner/admin |\n| `addReaction()` / `removeReaction()` | Member; self-keyed |\n| `getOrCreateDM()` | Actor must be a DM participant |\n| `createAgentSession()` | Actor becomes session participant; existing-session lookup tenant-bound; optional `sessionKey` isolates conversation subjects |\n| `updateAgentSessionConfig()` | Owner; mandatory tenant-bound lookup |\n| `sendAgentUserMessage()` | Actor must be session participant; authored as participant |\n\nRead facade: `getAgentSession({agentSessionId, tenantId})`,\n`findActiveAgentSessions({tenantId, agentId, participantProfileId})`, and\n`getThread({threadId, tenantId})` are tenant-bound; consumers still check\nownership/context. `listRoomThreads({roomId, actorProfileId, tenantId})`,\n`getThreadMessages({threadId, actorProfileId, tenantId, limit?})` (chronological),\n`getRoomMessages({roomId, actorProfileId, tenantId})`, and\n`getRoomForMember(roomId, actorProfileId, tenantId)` additionally require\nmembership of the server-supplied actor, not a caller-selected subject.\n\nTrusted agent runtime imports `sendAgentReply(service, params)` only from\n`@happyvertical/smrt-chat/internal/agent-runtime`. It is not a `ChatService`\nmethod or package-index export. It authors as `session.agentProfileId` — the\nagent's resolved `bot` Profile, NEVER the `agentId` slug (#2995) — accepts a\nsame-room/tenant thread, and enforces `allowedTools` fail-closed.\n\nPrivate `#writeMessage` alone can select arbitrary authors/roles or bypass\nmembership. It binds every supplied `threadId`, `agentSessionId`, and\n`replyToMessageId` to the same room **and** tenant. Internal enrollment supports\nautomatically created rooms, sessions, and participants.\n\n## Agent Tool Whitelisting\n\n`allowedTools` is a JSON array controlled by the consuming app. Fail-closed: an empty/unparseable whitelist permits NO tools. The internal `sendAgentReply(service, params)` function enforces the whitelist before emitting any `tool`/`tool_call` message; a caller cannot supply a `senderProfileId`/`role` to post as the agent, and the function is not reachable from the package index.\n\nPrincipal-bound data discovery and reads are available as `PrincipalTool[]` via\n`createDataSurfaceTools()` (re-exported by the chat package). Pass the tools as\n`extraTools` to the persona conversation/tool loop. They use the same\nfail-closed `allowedTools` offer/execution gates; RBAC, tenant, redaction,\nbounded query results, and audit authority remain in the authenticated\n`PrincipalRun` supplied by `@happyvertical/smrt-agents`.\n\n## Commerce money tools (#3937)\n\nHosts that offer invoice money work must explicitly register\n`createCommerceMoneyTools()` from `@happyvertical/smrt-commerce` in\ntheir authenticated assistant route's `extraTools` (for example, `extraTools: () => createCommerceMoneyTools()`) and\nadd only the desired `commerce.*` slugs to the persona's `allowedTools`.\nThey are not generic manifest CRUD tools: tax codes are selected by code,\npreview is calculator-only, and line writes run through the document-money\ncoordinator. Each execution reasserts the principal allow-list and required\n`Invoice`, `InvoiceLineItem`, `DocumentTax`, and `TaxCode` operations. The\ngenerated MCP invoice `get` serializer remains commerce-owned; use its\nstored-facts integration when that serializer exposes `DocumentTax` rows.\n\n## Runtime report tools (#3711)\n\n`createRuntimeReportTools()` (`runtime-report-tools.ts`) returns four\n`PrincipalTool`s for the persona `extraTools` seam: `reports.runtime.sources`,\n`reports.runtime.define` (`preview` / `apply`), `reports.runtime.list`, and\n`reports.runtime.run`. The model supplies only a declarative\n`RuntimeReportSpec` from `@happyvertical/smrt-reports`; sources are a\nserver-owned allow-list gated by `run.assertOperation(collection, 'read')`, and\nfield policy, `readPermission`, and tenancy are enforced by the compiler against\nthe live run on every compile and every stored-report run. `apply` needs the\n`specHash` of the previewed spec plus an app-owned `confirmation` host that\nresolves only after a human approved that exact spec; with no host apply returns an `awaiting_confirmation` proposal for the\nsame-origin browser confirm route and stores nothing and a model-supplied `confirmed` flag is ignored. Saving also needs\n`create` on the `RuntimeReport` collection, and `list`/`run` need `read`; the\ndefault `reportsCollection` is the `RuntimeReport` class itself, which resolves\nto the catalog slug. A string `collection`/`reportsCollection` is used verbatim\nas a catalog slug (never a class name); tests must run the tools under the real\n`assertOperationPermission` guard so a wrong slug fails. A stored report is\nwritten only by this confirmed `apply`: the model layer refuses every other\ninsert/spec change, and the generic manifest tools (`buildManifestToolCatalog`,\n`invokeManifestTool`) never offer or run a `RuntimeReport` write. Stored-report\nreads/saves run under the principal's tenant (`withPrincipalTenant`), refuse a\nmismatching ambient tenant (checked before `confirmSave`), and filter by the principal tenant explicitly. Contract and authority model:\n[`packages/reports/agents/runtime-reports.md`](../reports/agents/runtime-reports.md).\n\n## Overview tools (#3727)\n\n`createOverviewTools({ host })` (`overview-tools.ts`) returns\n`overviews.describe`, `overviews.apply` (an atomic batch of structured widget\noperations) and `overviews.undo` (single step, keyed by tenant, user and page).\nThe host opens a page per `PrincipalRun` (smrt-svelte's\n`createOverviewAssistantSurface`, typed structurally here); validation and\n`canCustomize` are the surface's. Contract:\n[agents/overview-tools.md](agents/overview-tools.md).\n\n## Conversational Harness (L3, #1891)\n\nThe `AgentSession` runtime depends on personas, agents, and users. Keep those\nedges acyclic: none of those packages may depend back on chat.\n\n- **`runToolLoop(options)`** (`tool-loop.ts`) — a bounded `tool_call → observe → respond` loop. Tools are **manifest operations** of installed packages: `buildManifestToolCatalog({ allowedTools })` reads the `PermissionCatalogService` catalog and keeps only the `(collection, action)` entries named in the persona's allow-list (the **offer gate**; absent/empty ⇒ NO tools). The loop runs inside one `executeAsPrincipal` context, and `invokeManifestTool` executes each op **in-process (\"side door\")** against `run.context.database` (the RLS tx when Postgres RLS is on), after re-asserting the fail-closed allow-list (`run.assertToolAllowed`) AND the catalog permission (`run.assertOperation`) — the **execution gate**. Bounded by `DEFAULT_MAX_STEPS = 8`, an optional token budget and a deadline. Termination, the forced final call, observation caps, argument validation and tool-error classification: [agents/tool-loop.md](agents/tool-loop.md).\n- **`runPersonaConversationTurn(options)`** (`persona-conversation.ts`) — binds a conversation to an `AgentPersona`/`ResolvedPersona`: runs as its principal (`runAsUserId`), offers only its `allowedTools`, speaks its instructions (`resolvePersonaInstructions`, layering approved learned directives), and injects its **recalled learning memory** (`personaLearningMemory`, isolated per `memoryScope`) into the system prompt. `bindPersonaToSession()` mirrors the persona's `allowedTools`/instructions onto the `AgentSession` so the chat authoring gate agrees with the loop's offer gate. Authors the reply (and each executed tool) via the internal `sendAgentReply` bridge. Tools run with the run-as user's **live** permissions unless the host passes a `permissions` snapshot (#2978), which `runToolLoop` forwards to `executeAsPrincipal` so a narrowed principal (e.g. a shared station) cannot reach grants — such as `readPermission`-gated data-surface fields — beyond that snapshot, including through `agents.invoke` delegation (the snapshot becomes the worker's permission ceiling).\n- **Agent orchestration** (L3, #1892) — the loop accepts non-manifest **`extraTools`** (`PrincipalTool[]`, from `@happyvertical/smrt-agents`), gated by the *same* fail-closed allow-list. The standard **`invoke-agent`** tool (`createInvokeAgentTool`, slug `agents.invoke`) lets a conversational agent delegate to a **worker agent under its own principal** — the worker runs via `executeAsPrincipal` as the originating user (never its own authority), the principal is immutable along the chain, and its completion is surfaced back into the conversation. `runPersonaConversationTurn` filters `extraTools` by the persona's `allowedTools` (offer gate); the tool's `execute` re-asserts `assertToolAllowed` (execution gate). See `@happyvertical/smrt-agents` for the delegation envelope + transports.\n- **Chat feedback capture** (`chat-feedback.ts`) — `captureChatFeedback()` + `acceptAppliedChange`/`rejectAppliedChange`/`correctResponse`/`rateResponse`/`thumbsUp`/`thumbsDown` write a `Feedback` row (personas) carrying the conversation's **correlation-id**, and (by default) reinforce the persona's learning memory (`reinforceFromFeedback`). So an in-chat reject decays a strategy below the reuse floor and it stops being recalled; a correction supersedes its stored value.\n\n## Voice Gateway Turns (#1910)\n\nVoice is an input mode for the existing persona chat harness, not a separate chat runtime. `createVoiceChatSession()` creates a short-lived `VoiceSession` for an authenticated actor/profile, binding tenant, persona, agent session, room, and optional thread. `handleVoiceGatewayTurn()` resolves that binding from `metadata.voiceSessionId`, checks the gateway's `session_id` and any supplied tenant/profile/persona/session/thread metadata against the server-side binding, persists the transcript through `ChatService.sendAgentUserMessage()`, runs `runPersonaConversationTurn()`, stamps voice/correlation metadata onto the persisted user/assistant/tool messages, records the gateway `turn_id`, and returns the gateway response contract. The Fetch-compatible `createVoiceGatewayTurnHandler()` adds the coarse gateway bearer-token check.\n\nThe gateway bearer token proves only \"this request came from the gateway\"; it never authorizes the end user. The short-lived `VoiceSession` binding is the user/session proof, and untrusted gateway metadata must be validated against that binding before any chat write or tool loop. Tool execution remains fail-closed through the persona allow-list mirrored onto `AgentSession` by `bindPersonaToSession()`.\n\n## Token streaming\n\n`chat-stream.ts` serves browser-safe SSE through `./client`. The host's\n`authorize(request, body)` is the sole trust boundary: resolve identity, tenant,\ncapabilities, and generation limits server-side; never authorize from request\nsession metadata. Persona turns reuse the principal and fail-closed tool gates.\nThe engine and browser-safe `SmrtChatBackend` keep custom-tool resolution\nserver-side. See [agents/token-streaming.md](agents/token-streaming.md) for the\nevent contract, CORS policy, and streaming behavior.\n\n## Streamed assistant turns with browser tools (#2908)\n\n`runAssistantTurn()` (`assistant-turn.ts`) is the host-route engine for the\nAssistantDock: one turn over `runToolLoop` with server tools (offer-gated by\n`principal.allowedTools`), browser tools (validated by\n`sanitizeClientToolDeclarations` + a server allow-list), `maxSteps`, `signal`,\nand `onUsage`. A browser tool call SUSPENDS the turn (`stoppedReason:\n'client_tools'`); the transcript waits in an `AssistantContinuationStore`\n(single-use, 15-minute TTL; `createSessionContinuationStore` keeps it in the\nAgentSession's `sessionContext`) and the browser resumes it with results,\nwhich reach the model wrapped `untrusted`. `createAssistantTurnResponse`\nserves the events as SSE; `assistant-turn-events.ts` is the browser-safe wire\ncontract (`./assistant-turn` subpath, also a vite library entry because the\nSvelte dock imports it). The dock decides whether a browser call runs or waits\nfor the user from the page registry, never the server's echo; destructive\nalways waits. Details: [`docs/assistant-dock.md`](../../docs/assistant-dock.md).\n\n## AssistantDock (#2904)\n\n`AssistantDock` (`svelte/components/assistant/`, exported from `./svelte`)\nuses a host `DataSurfaceRegistry`'s mounted descriptors (none: plain chat).\nActions: `normalizeDataSurfaceActionRequest` → `AssistantActionClient`\n(preview/apply over a server `DataSurfaceActionAdapter`, not the\n`data-surface-bridge.ts` channel). Generated `ChatThread`/`ChatMessage`\n`list`/`get` are tenant- not member-scoped; the dock never calls them.\n\n**Server routes (#3368).** `./sveltekit` `mountAssistantRoutes()` serves the\ndock from one `[...path]` route; `createAssistantHttp{Transport,ActionClient}`\n(`./svelte`) are its browser half. Principal from `event.locals` or\n`resolvePrincipal`; threads only from the actor's keyed session room in that\ntenant (else 404). `allowedTools` is fail-closed; without `tools` it offers\nthose manifest ops (an unprovided name is an error, #3414). `ai` defaults to\nthe principal's stored inference binding over the config `ai` block (#4756,\n[core inference.md](../core/agents/inference.md#raw-clients-and-binding-source-4756)). Pass `runtime`: a turn never keeps the RLS request tx\n(own `runAsPrincipal` tx). `clientRequestId` makes the row id a UUIDv5\n(`clientRequestMessageId`): the PK is the retry reservation. See\n[docs](../../docs/assistant-dock.md).\n\nAI off / not set up (#4757): routes answer a structured `ai_unavailable` 503;\ndock `aiSettingsHref` ([agents/ai-unavailable.md](agents/ai-unavailable.md)).\n\n#4505: `messageFormat=\"markdown\"` / `renderMessage` ([docs](../../docs/assistant-dock.md));\n`collapseRecoveredFailures` ([tool-loop](agents/tool-loop.md#failed-calls-are-persisted-4383)).\n\nStructured questions and page requests (#4100): [agents/assistant-questions.md](agents/assistant-questions.md).\n\n## Recipes (#3719)\n\n`src/recipes.ts` declares `chat.assistant` (the AssistantDock as a `header.end`\nshell widget, an `llm` provider, runtime `both`; help in\n`src/assistant.recipe.md`). Keep each recipe class self-contained. Details:\n[agents/recipes.md](agents/recipes.md).\n\n## Gotchas\n\n- **sessionContext, not context**: `context` is reserved for slug scoping. Use `getSessionContext()`/`updateSessionContext()` for agent memory.\n- **Agent rooms auto-created**: `roomType: 'agent'`, `maxParticipants` defaults to 2; the agent is enrolled as a member so its replies pass the membership check. `createAgentSession()` re-enrolls the participant AND the agent on the existing-session path, so legacy sessions created before the agent was enrolled self-heal.\n- **The agent's author is a Profile, not `agentId` (#2995)**: `senderProfileId`/`profileId` are `crossPackageRef`s to `Profile` and therefore uuid columns on PostgreSQL, so the slug fails the cast (`22P02`) and no agent reply can persist. `createAgentSession()` resolves the agent's `bot` Profile through `resolveAgentProfile()` in `@happyvertical/smrt-profiles` (created on first use, tenant-bound) and records it as `AgentSession.agentProfileId`; both enrolment and `sendAgentReply` use that uuid. A consumer whose agent already has an acting identity passes `agentProfileId` to skip resolution — the voice path does this with the persona's `actsAsProfileId`, so persona replies stay attributed to the configured acting profile. Like `actorProfileId`, `agentProfileId` is SERVER-supplied, never request input: it selects the author of every later assistant message. It is validated (`#requireAgentProfile`) to exist and be visible in the tenant and to differ from the acting participant, and it can never re-point a session that already resolved one — only a pre-#2995 session with none is backfilled. **Migration**: `agent_profile_id` is an ordinary additive manifest field, so a consumer adopts it the same way as any other — `smrt db:migrate` generates and applies the column from the manifest, and `db:status --parity` verifies it; the framework never creates application schema at runtime. It is nullable and needs no offline DATA backfill — a session created before #2995 resolves and persists its `agentProfileId`, and re-enrols the agent, on its first agent turn after the upgrade. Two pre-#2995 cohorts: a session whose `agentId` is an ordinary slug never committed an author on PostgreSQL (the cast failed), so there is nothing to repair there, while SQLite/DuckDB may hold `chat_messages`/`chat_participants` rows whose id column holds the slug — readable, but not joinable to `profiles`. A session whose `agentId` is already a Profile uuid (the voice path used to collapse a persona's `actsAsProfileId` into it) DID commit on PostgreSQL; that profile is ADOPTED as the author, tenant-checked and never the participant, so the conversation's author does not change and the two-seat room gains no third identity. Known one-time effect: because `voice.ts` no longer derives `agentId` from `actsAsProfileId`, a keyless `createVoiceChatSession()` for such a persona opens a new session and room instead of reusing the legacy one; the old room and its messages stay intact and readable, and resuming with an explicit `agentSessionId` is unaffected.\n- **Only SQLite-backed tests would miss this class of bug**: uuid columns accept any text on SQLite. `src/__tests__/agent-reply-postgres.test.ts` (`pnpm --filter @happyvertical/smrt-chat test:postgres`) pins the agent-reply path against real PostgreSQL. That suite runs in `postgres-tests.yml` on every same-repository PR and merge group (#2659); keep a cheap SQLite assertion alongside it anyway, since the default lane is SQLite-only (`chat-service.test.ts` asserts the author is the profile uuid, not the slug).\n- **Per-subject sessions need `sessionKey`**: `createAgentSession()` reuses ANY active session for the same `(agentId, participantProfileId, tenantId)`. Callers that open separate conversations per subject (e.g. one content-editor session per content id) MUST pass a stable `sessionKey` (stored in `sessionContext.__sessionKey`, read via `AgentSession.getSessionKey()`); otherwise a session opened for one subject is reused and its context overwritten for another, surfacing the wrong room/threads (S5 #1392). A keyed create never reuses a keyless/legacy session.\n- **Session expiry**: check `isActive()` before allowing messages (expiresAt or limit-based)\n- **DM identity**: derived from the deterministic per-tenant `canonicalDmRoomId()` and the authoritative `chat_participants` join, not client metadata; concurrent creates upsert onto one row.\n- **Tenant-bound lookups**: membership/session/DM lookups REQUIRE `tenantId` and always bind it into the WHERE clause (`findActiveMembership`/`isActiveMember`/`findActiveSession` take a required `tenantId`; AgentSession's `null` tenant is an explicit bound scope, not \"any tenant\") so they can never resolve a row from another tenant.\n",
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",
4518
4530
  "moduleDocs": [
4519
4531
  {
4520
4532
  "path": "agents/dev-workbench.md",
4521
4533
  "module": "dev-workbench",
4522
4534
  "content": "# Chat dev workbench: browser inference and draft form\n\nReference for the `pnpm --dir packages/chat dev` workbench root route\n(`src/routes/+page.svelte`). Linked from [../AGENTS.md](../AGENTS.md).\n\n## Browser inference path\n\nThe root route drives the **browser inference path**\n(`@happyvertical/smrt-web/ai`) end to end, which is what the workbench exists to\nexercise now: THREE backends — `createBitGpuInferenceBackend()` (Bonsai 1.7B,\n~237 MB, the dev-loop default), `createWebLlmInferenceBackend()`, and\n`createRouteInferenceBackend()` over `/api/dev-chat-stream` — composed by\n`createInferencePath({ backends: [bitgpu, local, route] })`. The local backends\nare listed first, so `auto` prefers one whenever it is READY; the route backend is\nalways ready, so `auto` always has somewhere to land. The status panel's Inference\nselector pins `auto` / `bitgpu` / `local` / `route`, it renders a\n`ModelStatusControl` per local backend, and the reply is rendered as it streams.\n`/api/dev-chat` is retained as the non-streaming reference endpoint; the workbench\nno longer calls it.\n\nFour dev-config facts this depends on:\n\n- The workbench injects `loadModule: () => import('@mlc-ai/web-llm')` and, for\n bitgpu, `loadBitGpu`/`loadChat` as `() => import('bitgpu')` /\n `() => import('bitgpu/chat')`. A browser resolves only STATIC specifiers — the\n adapters' own optional-import helpers use variable ones — so without these the\n optional peers fail to load and (for WebLLM) the error misreports the package as\n \"not installed\".\n- bitgpu's per-model `manifest.json` + `.aux.bin` come from its repo via jsDelivr;\n the Bonsai GGUF streams from the Hub; the tokenizer comes from\n `onnx-community/Bonsai-1.7B-ONNX` because `prism-ml/Bonsai-1.7B-gguf` ships no\n `tokenizer.json`.\n- `workspace-aliases.js` must list every deep `@happyvertical/smrt-ui/*` subpath\n a consumer reaches. A string alias is a PREFIX match, so the bare\n `@happyvertical/smrt-ui` entry rewrites any unlisted subpath under it into a\n bogus path under `src/index.ts`. That includes STYLESHEETS:\n `@happyvertical/smrt-ui/themes/styles/all.css` needs its own entry or the app\n renders with no theme variables at all.\n- The workbench imports `@happyvertical/smrt-ui/themes/styles/{all,fonts}.css`.\n `ThemeProvider` for a BUILT-IN preset only sets `data-theme` /\n `data-color-scheme` on its wrapper — it deliberately emits no inline variables,\n because built-ins ship their palette as static CSS. Without the import the\n attributes are present, `--smrt-color-*` resolves to nothing, and every themed\n surface paints transparent (which reads as \"dark mode is broken\" in a dark\n scheme). `smrt-workbench/host` is the reference for this.\n\n## Agent-addressable draft form\n\nThe workbench also carries an **agent-addressable draft form**: an `Input` inside\na `Form`, bound by `useViewIntent` to the intent declared in\n`src/routes/chat-dev.intents.ts` (#2588). It is the end-to-end demonstration of the\ncontrol-interaction stack — an agent stages, a human applies. Four things about it\nare non-obvious and cost time to find:\n\n- **No `<Provider>` here, so both seams must be explicit.** `useViewIntent` is a\n documented silent no-op without a Provider ancestor, so the binding passes\n `controlRegistry` directly; and `effects: ['read', 'write']` supplies the\n exposure policy, because the default is read-only and would exclude a `stage`.\n- **`inputSchema` on the declaration is REQUIRED for the tool to be callable.**\n `compileViewIntentToolSpec` passes it through verbatim, but\n `buildControlCommand` throws `IntentArgumentError('value')` for a `stage` with\n no `value`. Without it the tool registers, advertises\n `{\"type\":\"object\",\"properties\":{}}`, and fails at call time with Chrome's\n `UnknownError: Failed to parse input arguments`.\n- **`document.modelContext.executeTool(tool, args)` takes the tool OBJECT from\n `getTools()` and the arguments as a JSON STRING** — an object as the second\n argument fails the same way.\n- **Apply needs a genuinely trusted gesture.** The registry refuses a\n programmatic `element.click()` (`event.isTrusted === false`) for `apply`, which\n is the stage→apply consent split doing its job. Verification must use a real\n input event, not `evaluate(() => button.click())`.\n\n## Voice and local character persistence\n\nThe root workbench also has a dev-only voice conversation mode. It reads voice\ngateway connection details through `/api/dev-voice/config`, streams browser mic\naudio to `WS /ws/voice` as PCM16 mono, appends gateway transcripts/responses to\nthe chat, and plays returned TTS audio. Exposing\n`SMRT_CHAT_DEV_VOICE_GATEWAY_TOKEN` to the browser requires\n`SMRT_CHAT_DEV_VOICE_GATEWAY_EXPOSE_TOKEN=true`; keep that local-only.\n\n### Local character persistence\n\n`/api/dev-character-persistence` is an opt-in loopback-only demo bridge for\nthe photographic character workbench. It is disabled unless\n`SMRT_CHAT_DEV_CHARACTER_PERSISTENCE=true`; it accepts neither actor, tenant,\nnor profile ids from the browser. Its server configuration names one\npre-provisioned profile and tenant plus a temporary SQLite database and asset\ndirectory, all under the operating system temporary directory. First run\n`DATABASE_URL=<the same SQLite path> pnpm smrt db:migrate`, then run\n`pnpm exec tsx src/scripts/provision-dev-character-persistence.ts` with the\n`SMRT_CHAT_DEV_CHARACTER_*` variables set. The route never creates schema.\nUse fresh UUIDs for `SMRT_CHAT_DEV_CHARACTER_PROFILE_ID` and\n`SMRT_CHAT_DEV_CHARACTER_TENANT_ID`; keep the database and asset directory in\nthe OS temporary directory, for example `/tmp/smrt-character-setup/` on Linux\nor the path reported by `node -p \"require('node:os').tmpdir()\"` on macOS.\n\nThis is not production authentication. A production host must provide its\nauthenticated principal, tenant, and authorization policy to\n`PhotoCutoutProfileStore`; it must not copy this fixed local identity pattern.\n\n### Local helper control panel\n\n`/api/dev-helper` uses the same loopback-only identity and durable Profile\nmetadata store. Provisioning also creates its application-scoped metafield;\nthe route never creates schema or accepts actor, tenant, policy, provider, or\nasset URL fields from the browser. It resolves the current gallery, allowed\nvoice, and helper policy on every load/save/reset. Its whole-value persistence\nsemantic is last-successful-write-wins, so a production host with concurrent\neditors must serialize writes per profile/application or supply a stronger\nadapter. The speech route resolves the saved offered voice server-side; clients\nsubmit only text. Helper preference loading never starts audio or a microphone.\n\n### Character conversation lifecycle\n\nThe Character conversation tab refreshes the persisted rig each time it becomes\nactive, retaining its AssistantDock controller and history. Leaving the tab stops\nmicrophone input and reply playback; listening mode requires an explicit restart.\nAn outstanding turn keeps both the listening input and full dock composer busy\nacross mode changes and restarts until it settles. Both inputs share the retained\ncontroller’s pending-send state; microphone Stop remains reachable. Polling\nretains active sends until their transport completes, even when older history\ncontains the same message text.\nLate persistence loads and cancelled speech responses cannot replace the current\nrig or audio. Spoken captions begin only when SDK playback actually starts.\nListening mode also keeps the newest assistant reply in a dedicated reply\nregion, so a muted or failed spoken reply is still readable while history stays\nhidden. A speech failure is shown beside the conversation controls; disabling\nspoken replies aborts its outstanding request and playback. While the tab is\ninactive, its fixed dock is hidden and polling is paused.\n\nThe development workbench links the SDK speech and animation packages from\nsibling worktrees. Keep those worktrees available until their released package\nversions replace the links; a fresh browser or Vite load cannot resolve a\nlinked package whose sibling checkout is absent.\n\nThe development transport sends at most 24 context messages within a 16 KiB UTF-8\nJSON body, dropping oldest context first. Failed turns are not committed to its\nhistory, so retrying does not duplicate them. Draft proposals use one shared\n200-character limit in the model tool, route, preview, and execution boundary.\n"
4523
4535
  },
4536
+ {
4537
+ "path": "agents/runtime-report-tools.md",
4538
+ "module": "runtime-report-tools",
4539
+ "content": "# Runtime report tools (#3711)\n\nMoved from `packages/chat/AGENTS.md` to keep the instruction chain under the 32 KB cap.\n\n`createRuntimeReportTools()` (`runtime-report-tools.ts`) returns four\n`PrincipalTool`s for the persona `extraTools` seam: `reports.runtime.sources`,\n`reports.runtime.define` (`preview` / `apply`), `reports.runtime.list`, and\n`reports.runtime.run`. The model supplies only a declarative\n`RuntimeReportSpec` from `@happyvertical/smrt-reports`; sources are a\nserver-owned allow-list gated by `run.assertOperation(collection, 'read')`, and\nfield policy, `readPermission`, and tenancy are enforced by the compiler against\nthe live run on every compile and every stored-report run. `apply` needs the\n`specHash` of the previewed spec plus an app-owned `confirmation` host that\nresolves only after a human approved that exact spec; with no host apply returns an `awaiting_confirmation` proposal for the\nsame-origin browser confirm route and stores nothing and a model-supplied `confirmed` flag is ignored. Saving also needs\n`create` on the `RuntimeReport` collection, and `list`/`run` need `read`; the\ndefault `reportsCollection` is the `RuntimeReport` class itself, which resolves\nto the catalog slug. A string `collection`/`reportsCollection` is used verbatim\nas a catalog slug (never a class name); tests must run the tools under the real\n`assertOperationPermission` guard so a wrong slug fails. A stored report is\nwritten only by this confirmed `apply`: the model layer refuses every other\ninsert/spec change, and the generic manifest tools (`buildManifestToolCatalog`,\n`invokeManifestTool`) never offer or run a `RuntimeReport` write. Stored-report\nreads/saves run under the principal's tenant (`withPrincipalTenant`), refuse a\nmismatching ambient tenant (checked before `confirmSave`), and filter by the principal tenant explicitly. Contract and authority model:\n[`packages/reports/agents/runtime-reports.md`](../../reports/agents/runtime-reports.md).\n"
4540
+ },
4524
4541
  {
4525
4542
  "path": "agents/overview-tools.md",
4526
4543
  "module": "overview-tools",
@@ -4529,12 +4546,32 @@
4529
4546
  {
4530
4547
  "path": "agents/tool-loop.md",
4531
4548
  "module": "tool-loop",
4532
- "content": "# Tool loop termination and tool-call hygiene\n\n`runToolLoop()` (`src/tool-loop.ts`) runs one bounded\n`tool_call → observe → respond` turn. Both `runPersonaConversationTurn()` and\n`runAssistantTurn()` go through it, so every rule below holds for both.\n\n## Termination\n\n- Rounds that execute tools are capped by `maxSteps`\n (`DEFAULT_MAX_STEPS = 8`; `initialSteps` counts earlier legs of a resumed\n turn). `maxTotalTokens` (with `initialTokens`) and `deadline` end the turn\n early with `stoppedReason: 'budget'`.\n- **Forced final call (#4378).** At the cap, once the budget is spent, or\n after repeated calls (below, #4391), the next round is offered no tools (`tools: undefined`, `toolChoice: 'none'`),\n and any tool calls the model still emits are discarded. That call alone gets\n the fixed `TOOL_LOOP_ANSWER_NOW_INSTRUCTION` as a temporary `user`\n instruction. If the transcript already ends with a user turn, it is added\n to a copy of that turn's text or multimodal content instead of introducing\n consecutive user roles that strict templates reject. Otherwise it is a new\n user message. It never enters the returned `messages` transcript; input\n messages, stored conversations, and continuations stay unchanged.\n\n## Blank answers and timeouts (#4379)\n\n- **Retry once, within budget.** A final round with blank content and no\n usable tool calls (none made, or discarded on a no-tools round) is retried\n once without tools, with `TOOL_LOOP_ANSWER_NOW_INSTRUCTION` appended to\n that call only, and `emptyRetried: true`. The retry is skipped when the\n token budget (`maxTotalTokens`) or `deadline` is already spent: the turn\n goes straight to `empty`. The forced final call itself is one uncapped\n call, so a spent budget still gets one answer attempt; only the retry is\n budget-gated. Each blank round emits an `empty_round` step event (no model\n text; `retry` says whether a retry follows). `runAssistantTurn` does not\n show it as a dock step.\n- **Report.** Still blank: `stoppedReason: 'empty'`, `content: ''`. A model\n call that throws a timeout (`AI_TIMEOUT`, `TIMEOUT`, `REQUEST_TIMEOUT`,\n `TimeoutError`, or an `AbortError` the caller's signal did not cause) ends\n `stoppedReason: 'timeout'` instead of failing or passing as an empty\n success; other errors still throw. When the final round was the forced\n no-tools call, `capReason` (`max_steps` | `budget` | `repeated_calls`)\n keeps that cause alongside `empty`/`timeout`.\n- **Quiet stream ends (older SDKs).** SDKs <= 0.108.0 can end a timed-out\n stream quietly: no text, no tool calls, no finish reason. That shape is a\n suspected timeout only for an AI boundary that has already reported a\n finish reason in this process (so its absence is anomalous), and only when\n the retry ends the same way; then the turn is `timeout`. A boundary that\n never reports finish reasons, or a blank reply that has one, is `empty`.\n The \"has reported\" flag is kept per AI client object for the process\n lifetime, so one client that routes to providers with and without finish\n reasons can mislabel an `empty` turn as `timeout` (or the reverse).\n- **Timeouts are configurable, not derived.** `requestTimeoutMs` is\n forwarded as the per-call `timeout` (default: the provider's 120 s). It is\n not derived from `deadline`/`maxTurnMs`: those only stop new tool rounds\n and gate the retry.\n- **Fallback text.** Both callers store `resolveTurnReply(result,\n fallback)`: the content trimmed at its outer edges only (both paths\n alike; persona replies were stored untrimmed before), or\n `emptyAnswerFallback` / `DEFAULT_EMPTY_ANSWER_FALLBACK` when blank.\n `runPersonaConversationTurn` returns it as `reply` (plus `replyFallback`);\n voice and the chat stream use it. `runAssistantTurn` replaces its old\n `'Done.'`. The plain chat-stream path retries a blank stream once, then\n sends the fallback, or `CHAT_STREAM_TIMEOUT_ERROR` only under the\n quiet-end rule above.\n- **Provider errors (#4454).** A model call that throws is not answered by\n default (an `error` event, nothing stored). `runAssistantTurn` /\n `mountAssistantRoutes` take `providerErrorFallback`: text, or\n `(code, error) => text | undefined` (blank or `undefined` declines and the\n turn fails as before). The text is stored as the assistant row with\n `metadata.fallback: 'provider_error'` (so `isFallbackReply` is true and\n history skips it), the turn ends `stoppedReason: 'provider_error'`, and the\n error still goes to `onError`. A cancelled turn is never answered this way.\n- **Stored metadata.** Every authored assistant reply carries\n `replyMetadataFor(result, reply)`: `metadata.stoppedReason` (enum),\n `metadata.capReason` when set, and `metadata.fallback` (`empty` |\n `timeout` | `provider_error`) when the content is the fallback. Hosts read the stop reason\n from `turn.result.stoppedReason` (persona), `AssistantTurnResult` / the\n `done` event's `stoppedReason` and `capReason` (assistant), or the stored\n message's metadata. `isFallbackReply(message)` tells a fallback apart; the\n assistant route's and voice's history builders skip fallback replies so\n they are never replayed to the model as answers. The chat-stream paths\n (plain and persona) take history from the browser, which sends no\n metadata, so they recognise an assistant message whose text exactly\n equals the configured or default fallback text. All three replay the\n fixed `FALLBACK_HISTORY_PLACEHOLDER` in its place rather than dropping\n it: a drop would leave two user messages in a row, which strict chat\n templates (Gemma, Anthropic) reject. Hosts should hide feedback\n controls (thumbs, corrections) on a message where `isFallbackReply` is\n true: there is no model answer to rate.\n- **History budget (#4458).** `historyLimit` counts replayed turns, not\n raw rows, so persisted tool rows (`authorInvocation`, failed calls) never\n take a slot. The assistant route and voice pass `roles` to\n `getThreadMessages` / `getRoomMessages`, which filter in SQL: the read\n returns at most `limit` rows whatever the thread holds. A fallback reply\n is one replayed turn (its marker). The chat-stream paths cap the\n browser's array at `MAX_CHAT_STREAM_MESSAGES` kept messages, scanning\n back at most 10× that many entries. Threads holding only replayed roles\n see the same history as before.\n- **Dock.** The `done` event's `capReason` reaches the dock, which offers\n Continue for a `max_steps`/`budget` capped turn even when it ended `empty`\n or `timeout` (never for `repeated_calls`, #4391).\n- **Reasoning.** `AIResponse.reasoning` (newer SDKs, sdk#1459) is read\n defensively, capped at `MAX_TOOL_LOOP_REASONING_CHARS` code points, passed\n to `onReasoning` (forwarded by both callers; a throw is ignored) and\n returned as `result.reasoning` (the retry's, else the first round's).\n Reasoning can quote documents and tool results: send it only to logs with\n the same protection as the conversation. It is never persisted and never\n the answer unless the host opts in with `answerFromReasoning` — which\n stores raw chain-of-thought as the reply (`contentFromReasoning: true`).\n- **Budgets on the persona path.** `runPersonaConversationTurn` forwards\n `maxTotalTokens`, `deadline`, `toolChoice` and `requestTimeoutMs`\n (`runAssistantTurn` exposes them as `maxTurnTokens`/`maxTurnMs`).\n\n## Observation bounds\n\n- A server tool observation is serialized and capped at\n `MAX_SERVER_TOOL_OBSERVATION_CHARS` (16,000, the same bound as\n `MAX_CLIENT_TOOL_RESULT_CHARS` for browser results) before it enters the\n transcript (#4378). A longer one is cut and gets the fixed\n `SERVER_TOOL_OBSERVATION_TRUNCATED_MARKER`, which says the result is\n incomplete and tells the model to narrow the request (filter, fewer fields,\n a smaller page, or a count). The marker carries no tool output.\n- The cut never splits a surrogate pair (it keeps one unit fewer instead);\n browser results (`appendClientToolResults`) are cut the same way.\n- Only the model's copy is capped: `ToolInvocation.observation` (handed to\n `onInvocation`, persisted as tool messages, audited) keeps the full value.\n- A tool returning `undefined` observes `null`; an unserializable result\n observes `{\"error\":\"unserializable_result\"}` instead of throwing.\n\n## Argument hygiene (#4378)\n\nArguments the model sends are never dropped silently; each case below is an\n`invalid_request` observation the model can correct and retry. Messages are\nvalue-free: they name the accepted shape, never the model's values.\n\n- **Malformed JSON.** Raw arguments that do not parse to a JSON object\n (malformed JSON, an array, a scalar) fail with code\n `TOOL_ARGUMENTS_MALFORMED`; the tool does not run and the invocation's\n `args` is `{}`. Blank or `null` arguments are a no-argument call. A browser\n tool call with malformed arguments is answered in the transcript and never\n suspends the turn.\n- **Manifest `read`.** Accepts only `id` (string), `where` (object of\n equality filters), `limit` (integer >= 1) and `offset` (integer >= 0). This\n is stricter than before, where these were dropped or defaulted silently:\n an unknown key such as `filter`, a numeric `id`, a non-object `where`, and\n a fractional, zero or string `limit` (or a negative or fractional `offset`)\n now fail with a retryable `invalid_request` (`TOOL_ARGUMENTS_INVALID`)\n instead of listing every row. The offered schema says\n `additionalProperties: false` with `integer` `limit`/`offset` minimums.\n- **`data.query`** (`@happyvertical/smrt-agents`). With a `request` object,\n the only other top-level key allowed is `surfaceId`; a sibling such as\n `filter` fails with `DataSurfaceRequestError` reason\n `DATA_QUERY_ARGUMENTS_UNEXPECTED`, naming only misplaced grammar keys. The\n flat form (request keys beside `surfaceId`, no `request`) still works.\n- **`surfaceId` placement** (`data.query`, `data.inspect`). A\n `request.surfaceId` string is lifted to the top level and removed from\n `request`; a `query` object standing in for `request`, or one that is\n `request`'s only key, is unwrapped (its keys are then validated as usual,\n so nothing is dropped; unwrapping was chosen over rejecting because the\n intent is unambiguous). Two different ids are\n `DATA_QUERY_SURFACE_ID_CONFLICT`; no id at all is a 400\n `DATA_QUERY_SURFACE_ID_REQUIRED` with an example. Only an id naming no\n visible surface gets the generic \"not available\" denial. A filter `kind`\n that is an operator (`in`) or a logical word (`or`) gets a targeted hint.\n- **Valid examples.** Every `data.query` request error ends with a one-line\n `Valid example: {\"surfaceId\":…,\"request\":{…}}` for that surface, in the\n failed request's mode (count, rows or facets), built from the surface id\n and caller-visible field ids with `<value>` placeholders — never the\n caller's own values. Row examples cap page size at the surface’s\n `maxPageLimit`.\n\n## Dedupe of identical read-only calls (#4382)\n\nWithin one `runToolLoop` call, a server call that repeats an earlier one —\nsame tool, same arguments after canonicalization (object keys sorted) — is\nnot executed again. Its invocation has `deduped: true`, mirrors the earlier\n`ok`/`error`, and observes the fixed `TOOL_CALL_DEDUPED_NOTE` instead of a\nsecond copy of the result.\n\n- Only read-only, idempotent tools qualify: manifest `read`, and\n `data.discover`, `data.inspect`, `data.query`. Mutating tools,\n `agents.invoke`, other extra tools and browser tools never do; nor do\n malformed-argument calls.\n- **Invalidation.** Any resolved server call that is not on that allow-list\n (a write, `agents.invoke`, any other extra tool), whatever its result,\n clears every remembered read, so a read after a write always runs fresh.\n- A repeat of a rejected or refused call observes\n `TOOL_CALL_DEDUPED_REJECTED_NOTE` (repeating it will not work; fix the\n arguments) instead of the plain pointer note.\n- An earlier `execution_error` is not reused: a transient server failure\n may be retried. Arguments over 4,000 canonical characters are never keyed.\n- The cache holds at most `MAX_DEDUPED_CALLS_PER_TURN` (64) calls and lives\n only inside that `runToolLoop` call: never across turns (an assistant\n resume leg starts a fresh cache).\n- Deduped calls count toward the step cap: a round of repeats is still a\n round, so a model stuck repeating a call still stops at `maxSteps`.\n- The note points at the earlier result and says to change the arguments\n (for example, add a filter), because a repeat returns the same result.\n\n## Repeated calls end the tool phase (#4391)\n\nA model stuck on one call (an unfiltered count, sent again and again) used\nto burn every step to `maxSteps`. Now, once a single dedupe key (same tool,\nsame canonical arguments) has been deduped `maxRepeatedCalls` times in one\n`runToolLoop` call, the rest of that round still runs — every tool call gets\nits tool result — and the next model call is the forced no-tools call with\n`TOOL_LOOP_ANSWER_NOW_INSTRUCTION` plus, on this path only (and its blank\nretry), `TOOL_LOOP_REPEATED_CALLS_INSTRUCTION`: if the results do not match\nwhat was asked (a total where a filtered count was asked), say the figure\ncould not be got rather than presenting the result as the answer.\n\n- **Option.** `maxRepeatedCalls` on `runToolLoop`, `runAssistantTurn`,\n `runPersonaConversationTurn` and `mountAssistantRoutes`. Default\n `DEFAULT_MAX_REPEATED_CALLS` (2); `0` (or less) turns it off; otherwise it\n is floored and capped at `MAX_REPEATED_CALLS_LIMIT` (16). Non-numbers use\n the default.\n- **What counts.** Only deduped repeats, counted per key: a different\n argument is a different key, mutating and other non-dedupable calls never\n count, and a non-read-only call clears the counts with the dedupe cache.\n Counts live inside one `runToolLoop` call; an assistant resume leg starts\n at zero.\n- **Report.** `stoppedReason: 'repeated_calls'` and `capReason:\n 'repeated_calls'`; `capReason` stays when the forced call then ends `empty`\n or `timeout`. When the step cap or budget is reached in the same round,\n `repeated_calls` wins: more steps would only repeat the call. Stored\n replies carry it in `metadata.stoppedReason`/`metadata.capReason`, like the\n other caps; the `done` event carries both.\n- **Dock: no Continue.** The dock records `run.stoppedReason:\n 'repeated_calls'` but does not offer Continue (`waitingFor` stays null):\n the model already had the result it kept asking for, so another leg would\n repeat the call. Continue stays for `max_steps` and `budget` only. Hosts\n with their own UI should do the same.\n- The audit sink gets `action: 'chat.tool_call_deduped'` (not a fresh\n execution or failure); the persona path's tool row carries\n `toolCallData.deduped: true`.\n\n## Failed calls are persisted (#4383)\n\nEvery tool invocation records `modelContent`, the exact (capped) text the\nmodel was shown. `toolFailureRecord(invocation)` turns a failed, rejected or\ndenied call into a bounded record: `name`, `args` (over\n`MAX_TOOL_FAILURE_ARGS_CHARS` = 2,000 serialized characters they become\n`{ truncated: true }`; unserializable ones `{ unserializable: true }`;\nmalformed-JSON calls carry `{}`), `status` (`rejected` | `error`),\n`errorKind`, `errorCode` (the error's own stable `A-Z0-9_` code, else the\nkind) and `shown`. Like a successful call's row it carries the arguments\nand shown text, so it is not value-free. A deduped repeat has no record.\nA validation-class failure — `errorKind` `invalid_request` on a call that was\nnot a denial, i.e. the tool refused arguments the model can fix (#4505) —\nalso carries `recoverable: true`; both authoring paths copy it onto the row's\n`toolCallData` and `metadata`. Other failures omit it.\n\n- `runPersonaConversationTurn` authors each failed call as a `tool_result`\n row: content = `shown`, `toolCallData` `{ name, args, status, errorCode }`,\n `metadata` `{ toolStatus, errorKind, errorCode }`.\n- `runAssistantTurn` now does the same **by default** when an `author` is\n set — a behaviour change: before, failed calls were never persisted.\n `author.authorFailedInvocation` overrides the row or returns `null` to\n skip it; `authorInvocation` sees successful calls only (never a failed or\n deduped-failed one). A failed row's write error is not a dock step.\n- `author.collapseRecoveredFailures` (`mountAssistantRoutes`\n `collapseRecoveredFailures`; default `false`, #4505) holds each\n `recoverable` failure until the tool loop ends, drops it when a later call\n of the same tool in the same turn succeeded, and otherwise persists it then,\n in call order, before the reply. Denials and execution errors are never\n held; the audit sink still gets every failure; the dock's live tool steps\n are unchanged. The persona path is not affected.\n- `runToolLoop` sends the audit sink `action: 'chat.tool_call_failed'` with\n only `toolFailureAuditMetadata(record)`: `name`, `status`, `errorKind`,\n `errorCode`, `argsChars`, `shownChars` — never the arguments or the shown\n text, which can hold user data or raw server errors. A sink throw never\n fails the turn.\n- A browser tool call with malformed arguments is recorded the same way (an\n invocation, an audit entry, `onInvocation`), besides being answered in\n the transcript.\n- Gap: a call to a tool the session does not allow-list cannot be a tool row\n — `sendAgentReply`'s authoring gate refuses the name, and that gate is\n unchanged — so it reaches the audit sink only.\n\n## Tool errors\n\nA thrown tool error is classified by `classifyToolError`: permission denials\nand 401/403 are `not_permitted` (reported as a rejection); a `ValidationError`\nor 400/404/409/422 is `invalid_request` (observation: the actionable message,\n`publicMessage` first, its `code`, and a fix-and-retry hint); everything else,\nincluding 429, is `execution_error`. An `execution_error` observation\ncarries the error's message, its stable `code` when it has one (e.g.\n`DATA_SURFACE_QUERY_FAILED`), and the fixed `TOOL_EXECUTION_ERROR_HINT`:\nthe failure is the server's, so the model should not resend the same call\nbut answer with what it has or tell the user (#4378).\n"
4549
+ "content": "# Tool loop termination and tool-call hygiene\n\n`runToolLoop()` (`src/tool-loop.ts`) runs one bounded\n`tool_call → observe → respond` turn. Both `runPersonaConversationTurn()` and\n`runAssistantTurn()` go through it, so every rule below holds for both.\n\n## Termination\n\n- Rounds that execute tools are capped by `maxSteps`\n (`DEFAULT_MAX_STEPS = 8`; `initialSteps` counts earlier legs of a resumed\n turn). `maxTotalTokens` (with `initialTokens`) and `deadline` end the turn\n early with `stoppedReason: 'budget'`.\n- **Forced final call (#4378).** At the cap, once the budget is spent, or\n after repeated calls (below, #4391), the next round is offered no tools (`tools: undefined`, `toolChoice: 'none'`),\n and any tool calls the model still emits are discarded. That call alone gets\n the fixed `TOOL_LOOP_ANSWER_NOW_INSTRUCTION` as a temporary `user`\n instruction. If the transcript already ends with a user turn, it is added\n to a copy of that turn's text or multimodal content instead of introducing\n consecutive user roles that strict templates reject. Otherwise it is a new\n user message. It never enters the returned `messages` transcript; input\n messages, stored conversations, and continuations stay unchanged.\n\n## Blank answers and timeouts (#4379)\n\n- **Retry once, within budget.** A final round with blank content and no\n usable tool calls (none made, or discarded on a no-tools round) is retried\n once without tools, with `TOOL_LOOP_ANSWER_NOW_INSTRUCTION` appended to\n that call only, and `emptyRetried: true`. The retry is skipped when the\n token budget (`maxTotalTokens`) or `deadline` is already spent: the turn\n goes straight to `empty`. The forced final call itself is one uncapped\n call, so a spent budget still gets one answer attempt; only the retry is\n budget-gated. Each blank round emits an `empty_round` step event (no model\n text; `retry` says whether a retry follows). `runAssistantTurn` does not\n show it as a dock step.\n- **Report.** Still blank: `stoppedReason: 'empty'`, `content: ''`. A model\n call that throws a timeout (`AI_TIMEOUT`, `TIMEOUT`, `REQUEST_TIMEOUT`,\n `TimeoutError`, or an `AbortError` the caller's signal did not cause) ends\n `stoppedReason: 'timeout'` instead of failing or passing as an empty\n success; other errors still throw. When the final round was the forced\n no-tools call, `capReason` (`max_steps` | `budget` | `repeated_calls`)\n keeps that cause alongside `empty`/`timeout`.\n- **Quiet stream ends (older SDKs).** SDKs <= 0.108.0 can end a timed-out\n stream quietly: no text, no tool calls, no finish reason. That shape is a\n suspected timeout only for an AI boundary that has already reported a\n finish reason in this process (so its absence is anomalous), and only when\n the retry ends the same way; then the turn is `timeout`. A boundary that\n never reports finish reasons, or a blank reply that has one, is `empty`.\n The \"has reported\" flag is kept per AI client object for the process\n lifetime, so one client that routes to providers with and without finish\n reasons can mislabel an `empty` turn as `timeout` (or the reverse).\n- **Timeouts are configurable, not derived.** `requestTimeoutMs` is\n forwarded as the per-call `timeout` (default: the provider's 120 s). It is\n not derived from `deadline`/`maxTurnMs`: those only stop new tool rounds\n and gate the retry.\n- **Fallback text.** Both callers store `resolveTurnReply(result,\n fallback)`: the content trimmed at its outer edges only (both paths\n alike; persona replies were stored untrimmed before), or\n `emptyAnswerFallback` / `DEFAULT_EMPTY_ANSWER_FALLBACK` when blank.\n `runPersonaConversationTurn` returns it as `reply` (plus `replyFallback`);\n voice and the chat stream use it. `runAssistantTurn` replaces its old\n `'Done.'`. The plain chat-stream path retries a blank stream once, then\n sends the fallback, or `CHAT_STREAM_TIMEOUT_ERROR` only under the\n quiet-end rule above.\n- **Provider errors (#4454).** A model call that throws is not answered by\n default (an `error` event, nothing stored). `runAssistantTurn` /\n `mountAssistantRoutes` take `providerErrorFallback`: text, or\n `(code, error) => text | undefined` (blank or `undefined` declines and the\n turn fails as before). The text is stored as the assistant row with\n `metadata.fallback: 'provider_error'` (so `isFallbackReply` is true and\n history skips it), the turn ends `stoppedReason: 'provider_error'`, and the\n error still goes to `onError`. A cancelled turn is never answered this way.\n- **Stored metadata.** Every authored assistant reply carries\n `replyMetadataFor(result, reply)`: `metadata.stoppedReason` (enum),\n `metadata.capReason` when set, and `metadata.fallback` (`empty` |\n `timeout` | `provider_error`) when the content is the fallback. Hosts read the stop reason\n from `turn.result.stoppedReason` (persona), `AssistantTurnResult` / the\n `done` event's `stoppedReason` and `capReason` (assistant), or the stored\n message's metadata. `isFallbackReply(message)` tells a fallback apart; the\n assistant route's and voice's history builders skip fallback replies so\n they are never replayed to the model as answers. The chat-stream paths\n (plain and persona) take history from the browser, which sends no\n metadata, so they recognise an assistant message whose text exactly\n equals the configured or default fallback text. All three replay the\n fixed `FALLBACK_HISTORY_PLACEHOLDER` in its place rather than dropping\n it: a drop would leave two user messages in a row, which strict chat\n templates (Gemma, Anthropic) reject. Hosts should hide feedback\n controls (thumbs, corrections) on a message where `isFallbackReply` is\n true: there is no model answer to rate.\n- **History budget (#4458).** `historyLimit` counts replayed turns, not\n raw rows, so persisted tool rows (`authorInvocation`, failed calls) never\n take a slot. The assistant route and voice pass `roles` to\n `getThreadMessages` / `getRoomMessages`, which filter in SQL: the read\n returns at most `limit` rows whatever the thread holds. A fallback reply\n is one replayed turn (its marker). The chat-stream paths cap the\n browser's array at `MAX_CHAT_STREAM_MESSAGES` kept messages, scanning\n back at most 10× that many entries. Threads holding only replayed roles\n see the same history as before.\n- **Dock.** The `done` event's `capReason` reaches the dock, which offers\n Continue for a `max_steps`/`budget` capped turn even when it ended `empty`\n or `timeout` (never for `repeated_calls`, #4391).\n- **Reasoning.** `AIResponse.reasoning` (newer SDKs, sdk#1459) is read\n defensively, capped at `MAX_TOOL_LOOP_REASONING_CHARS` code points, passed\n to `onReasoning` (forwarded by both callers; a throw is ignored) and\n returned as `result.reasoning` (the retry's, else the first round's).\n Reasoning can quote documents and tool results: send it only to logs with\n the same protection as the conversation. It is never persisted and never\n the answer unless the host opts in with `answerFromReasoning` — which\n stores raw chain-of-thought as the reply (`contentFromReasoning: true`).\n- **Budgets on the persona path.** `runPersonaConversationTurn` forwards\n `maxTotalTokens`, `deadline`, `toolChoice` and `requestTimeoutMs`\n (`runAssistantTurn` exposes them as `maxTurnTokens`/`maxTurnMs`).\n\n## Observation bounds\n\n- A server tool observation is serialized and capped at\n `MAX_SERVER_TOOL_OBSERVATION_CHARS` (16,000, the same bound as\n `MAX_CLIENT_TOOL_RESULT_CHARS` for browser results) before it enters the\n transcript (#4378). A longer one is cut and gets the fixed\n `SERVER_TOOL_OBSERVATION_TRUNCATED_MARKER`, which says the result is\n incomplete and tells the model to narrow the request (filter, fewer fields,\n a smaller page, or a count). The marker carries no tool output.\n- The cut never splits a surrogate pair (it keeps one unit fewer instead);\n browser results (`appendClientToolResults`) are cut the same way.\n- Only the model's copy is capped: `ToolInvocation.observation` (handed to\n `onInvocation`, persisted as tool messages, audited) keeps the full value.\n- A tool returning `undefined` observes `null`; an unserializable result\n observes `{\"error\":\"unserializable_result\"}` instead of throwing.\n\n## Argument hygiene (#4378)\n\nArguments the model sends are never dropped silently; each case below is an\n`invalid_request` observation the model can correct and retry. Messages are\nvalue-free: they name the accepted shape, never the model's values.\n\n- **Malformed JSON.** Raw arguments that do not parse to a JSON object\n (malformed JSON, an array, a scalar) fail with code\n `TOOL_ARGUMENTS_MALFORMED`; the tool does not run and the invocation's\n `args` is `{}`. Blank or `null` arguments are a no-argument call. A browser\n tool call with malformed arguments is answered in the transcript and never\n suspends the turn.\n- **Manifest `read`.** Accepts only `id` (string), `where` (object of\n equality filters), `limit` (integer >= 1) and `offset` (integer >= 0). This\n is stricter than before, where these were dropped or defaulted silently:\n an unknown key such as `filter`, a numeric `id`, a non-object `where`, and\n a fractional, zero or string `limit` (or a negative or fractional `offset`)\n now fail with a retryable `invalid_request` (`TOOL_ARGUMENTS_INVALID`)\n instead of listing every row. The offered schema says\n `additionalProperties: false` with `integer` `limit`/`offset` minimums.\n- **`data.query`** (`@happyvertical/smrt-agents`). With a `request` object,\n the only other top-level key allowed is `surfaceId`; a sibling such as\n `filter` fails with `DataSurfaceRequestError` reason\n `DATA_QUERY_ARGUMENTS_UNEXPECTED`, naming only misplaced grammar keys. The\n flat form (request keys beside `surfaceId`, no `request`) still works.\n- **`surfaceId` placement** (`data.query`, `data.inspect`). A\n `request.surfaceId` string is lifted to the top level and removed from\n `request`; a `query` object standing in for `request`, or one that is\n `request`'s only key, is unwrapped (its keys are then validated as usual,\n so nothing is dropped; unwrapping was chosen over rejecting because the\n intent is unambiguous). Two different ids are\n `DATA_QUERY_SURFACE_ID_CONFLICT`; no id at all is a 400\n `DATA_QUERY_SURFACE_ID_REQUIRED` with an example. Only an id naming no\n visible surface gets the generic \"not available\" denial. A filter `kind`\n that is an operator (`in`) or a logical word (`or`) gets a targeted hint.\n- **Valid examples.** Every `data.query` request error ends with a one-line\n `Valid example: {\"surfaceId\":…,\"request\":{…}}` for that surface, in the\n failed request's mode (count, rows or facets), built from the surface id\n and caller-visible field ids with `<value>` placeholders — never the\n caller's own values. Row examples cap page size at the surface’s\n `maxPageLimit`.\n\n## Dedupe of identical read-only calls (#4382)\n\nWithin one `runToolLoop` call, a server call that repeats an earlier one —\nsame tool, same arguments after canonicalization (object keys sorted) — is\nnot executed again. Its invocation has `deduped: true`, mirrors the earlier\n`ok`/`error`, and observes the fixed `TOOL_CALL_DEDUPED_NOTE` instead of a\nsecond copy of the result.\n\n- Only read-only, idempotent tools qualify: manifest `read`, and\n `data.discover`, `data.inspect`, `data.query`. Mutating tools,\n `agents.invoke`, other extra tools and browser tools never do; nor do\n malformed-argument calls.\n- **Invalidation.** Any resolved server call that is not on that allow-list\n (a write, `agents.invoke`, any other extra tool), whatever its result,\n clears every remembered read, so a read after a write always runs fresh.\n- A repeat of a rejected or refused call observes\n `TOOL_CALL_DEDUPED_REJECTED_NOTE` (repeating it will not work; fix the\n arguments) instead of the plain pointer note.\n- An earlier `execution_error` is not reused: a transient server failure\n may be retried. Arguments over 4,000 canonical characters are never keyed.\n- The cache holds at most `MAX_DEDUPED_CALLS_PER_TURN` (64) calls and lives\n only inside that `runToolLoop` call: never across turns (an assistant\n resume leg starts a fresh cache).\n- Deduped calls count toward the step cap: a round of repeats is still a\n round, so a model stuck repeating a call still stops at `maxSteps`.\n- The note points at the earlier result and says to change the arguments\n (for example, add a filter), because a repeat returns the same result.\n\n## Repeated calls end the tool phase (#4391)\n\nA model stuck on one call (an unfiltered count, sent again and again) used\nto burn every step to `maxSteps`. Now, once a single dedupe key (same tool,\nsame canonical arguments) has been deduped `maxRepeatedCalls` times in one\n`runToolLoop` call, the rest of that round still runs — every tool call gets\nits tool result — and the next model call is the forced no-tools call with\n`TOOL_LOOP_ANSWER_NOW_INSTRUCTION` plus, on this path only (and its blank\nretry), `TOOL_LOOP_REPEATED_CALLS_INSTRUCTION`: if the results do not match\nwhat was asked (a total where a filtered count was asked), say the figure\ncould not be got rather than presenting the result as the answer.\n\n- **Option.** `maxRepeatedCalls` on `runToolLoop`, `runAssistantTurn`,\n `runPersonaConversationTurn` and `mountAssistantRoutes`. Default\n `DEFAULT_MAX_REPEATED_CALLS` (2); `0` (or less) turns it off; otherwise it\n is floored and capped at `MAX_REPEATED_CALLS_LIMIT` (16). Non-numbers use\n the default.\n- **What counts.** Only deduped repeats, counted per key: a different\n argument is a different key, mutating and other non-dedupable calls never\n count, and a non-read-only call clears the counts with the dedupe cache.\n Counts live inside one `runToolLoop` call; an assistant resume leg starts\n at zero.\n- **Report.** `stoppedReason: 'repeated_calls'` and `capReason:\n 'repeated_calls'`; `capReason` stays when the forced call then ends `empty`\n or `timeout`. When the step cap or budget is reached in the same round,\n `repeated_calls` wins: more steps would only repeat the call. Stored\n replies carry it in `metadata.stoppedReason`/`metadata.capReason`, like the\n other caps; the `done` event carries both.\n- **Dock: no Continue.** The dock records `run.stoppedReason:\n 'repeated_calls'` but does not offer Continue (`waitingFor` stays null):\n the model already had the result it kept asking for, so another leg would\n repeat the call. Continue stays for `max_steps` and `budget` only. Hosts\n with their own UI should do the same.\n- The audit sink gets `action: 'chat.tool_call_deduped'` (not a fresh\n execution or failure); the persona path's tool row carries\n `toolCallData.deduped: true`.\n\n## Failed calls are persisted (#4383)\n\nEvery tool invocation records `modelContent`, the exact (capped) text the\nmodel was shown. `toolFailureRecord(invocation)` turns a failed, rejected or\ndenied call into a bounded record: `name`, `args` (over\n`MAX_TOOL_FAILURE_ARGS_CHARS` = 2,000 serialized characters they become\n`{ truncated: true }`; unserializable ones `{ unserializable: true }`;\nmalformed-JSON calls carry `{}`), `status` (`rejected` | `error`),\n`errorKind`, `errorCode` (the error's own stable `A-Z0-9_` code, else the\nkind) and `shown`. Like a successful call's row it carries the arguments\nand shown text, so it is not value-free. A deduped repeat has no record.\nA validation-class failure — `errorKind` `invalid_request` on a call that was\nnot a denial, i.e. the tool refused arguments the model can fix (#4505) —\nalso carries `recoverable: true`; both authoring paths copy it onto the row's\n`toolCallData` and `metadata`. Other failures omit it.\n\n- `runPersonaConversationTurn` authors each failed call as a `tool_result`\n row: content = `shown`, `toolCallData` `{ name, args, status, errorCode }`,\n `metadata` `{ toolStatus, errorKind, errorCode }`.\n- `runAssistantTurn` now does the same **by default** when an `author` is\n set — a behaviour change: before, failed calls were never persisted.\n `author.authorFailedInvocation` overrides the row or returns `null` to\n skip it; `authorInvocation` sees successful calls only (never a failed or\n deduped-failed one). A failed row's write error is not a dock step.\n- `author.collapseRecoveredFailures` (`mountAssistantRoutes`\n `collapseRecoveredFailures`; default `false`, #4505) holds each\n `recoverable` failure until the tool loop ends, drops it when a later call\n of the same tool in the same turn succeeded, and otherwise persists it then,\n in call order, before the reply. Denials and execution errors are never\n held; the audit sink still gets every failure; the dock's live tool steps\n are unchanged. The persona path is not affected.\n- `runToolLoop` sends the audit sink `action: 'chat.tool_call_failed'` with\n only `toolFailureAuditMetadata(record)`: `name`, `status`, `errorKind`,\n `errorCode`, `argsChars`, `shownChars` — never the arguments or the shown\n text, which can hold user data or raw server errors. A sink throw never\n fails the turn.\n- A browser tool call with malformed arguments is recorded the same way (an\n invocation, an audit entry, `onInvocation`), besides being answered in\n the transcript.\n- Gap: a call to a tool the session does not allow-list cannot be a tool row\n — `sendAgentReply`'s authoring gate refuses the name, and that gate is\n unchanged — so it reaches the audit sink only.\n\n## Tool errors\n\nA thrown tool error is classified by `classifyToolError`: permission denials\nand 401/403 are `not_permitted` (reported as a rejection); a `ValidationError`\nor 400/404/409/422 is `invalid_request` (observation: the actionable message,\n`publicMessage` first, its `code`, and a fix-and-retry hint); everything else,\nincluding 429, is `execution_error`. An `execution_error` observation\ncarries the error's message, its stable `code` when it has one (e.g.\n`DATA_SURFACE_QUERY_FAILED`), and the fixed `TOOL_EXECUTION_ERROR_HINT`:\nthe failure is the server's, so the model should not resend the same call\nbut answer with what it has or tell the user (#4378).\n\nA trusted host may set `ManifestTool.functionName` to its app-facing vocabulary.\n`manifestToolToAITool` and the loop use that provider-safe alias for discovery,\ncall resolution and browser-tool collision protection. The canonical `slug`\ncontinues to govern permissions, approval envelopes, transcripts and dispatch;\nan alias grants no operation. The real SQLite alias test retains the negative\nallow-list control and the canonical invocation record.\n\nManifest read operations request the collection's existing displayLabel projection\nfor point and list reads, matching REST's inline contact/display contract. This\nuses the original principal and ordinary public JSON filtering; it does not load\nidentity lists as extra tools. The host regression creates a typed contact, then\nchecks name/email/phone in actual item and list tool observations.\n"
4533
4550
  },
4534
4551
  {
4535
4552
  "path": "agents/token-streaming.md",
4536
4553
  "module": "token-streaming",
4537
- "content": "# Token Streaming (SSE, #1936)\n\nReference linked from [../AGENTS.md](../AGENTS.md). This contract was moved from\n`packages/chat/AGENTS.md` to keep the instruction chain under the 32 KB cap\n(`pnpm check:agents-chain`); AGENTS.md retains the cap-oriented summary.\n\n`chat-stream.ts` is the SSE seam for embeddable conversational UIs (first consumer: the Happy chat widget, `animation#5`): a client POSTs the conversation so far and receives a `text/event-stream` of `data: <json>` frames — `token` deltas as the model generates, then a final `done` frame with the message. The wire `ChatStreamEvent` union also declares `emotion` and `control` (#1921 host-page control commands) lanes for forward compatibility; the v1 engine emits `token`/`done`/`error`.\n\n- **`runChatConversationStream({ context, messages })`** — the transport-agnostic engine (an `AsyncGenerator<ChatStreamEvent>`). Dispatches on `context.binding`: **persona-bound** runs the full `runPersonaConversationTurn` with a token sink wired through the tool loop (`onToken` → `ai.chat({ stream: true, onProgress })`), then persists via `ChatService` and emits the persisted message as `done`; **plain/unbound** streams `ai.stream()` directly and emits a synthesized (unpersisted) `done`. Streamed tokens are a live PREVIEW (a tool-call round may narrate before acting); the `done` message is authoritative. Failures surface as an in-band `error` event, never a throw (the 200 has already committed once streaming starts).\n- **`createChatStreamHandler({ authorize, allowedOrigins?, allowCredentials? })`** — a Fetch-compatible handler returning `text/event-stream` (mirrors `createVoiceGatewayTurnHandler`). `authorize(request, body)` is the SOLE trust boundary and works exactly like the voice gateway: this module NEVER authorizes from the request's `session` metadata — the app validates the caller (bearer session id / cookie / same-origin) and the claimed ids against the authenticated principal, and returns an already-authorized `ChatStreamContext`. Generation caps (`model`/`maxTokens`/`maxSteps`) live on the context (server-resolved), never on the request. Cross-origin embedding uses the same fail-closed CORS posture as core `_events` (#1861): the `Origin` is echoed only when allow-listed (never `*`), credentials only when opted in.\n- **`SmrtChatBackend` (`@happyvertical/smrt-chat/client`)** — the consume side of the same contract: a browser SSE client (`src/client.ts`) that POSTs the conversation and dispatches `token`/`emotion`/`done`/`error` frames to streaming handlers, tolerating heartbeat comments and frames split across chunks. The subpath is BROWSER-SAFE and dependency-free (no server runtime, no workspace imports — keep it that way), and its widget-facing types are structurally identical to `@happyvertical/animation`'s `ChatBackend` contract so an instance plugs straight into the floating chat widget. `src/client.contract.ts` carries the compile-time locks pinning it to `chat-stream.ts`'s `ChatStreamEvent`/`ChatStreamSession` — a NON-test module precisely so `pnpm typecheck` actually enforces them (`tsconfig.typecheck.json` excludes `.test.ts` files, and Vitest transpiles without typechecking). A clean close without a `done` frame surfaces as an error (never an empty reply), and a settled turn cancels the reader so the connection is released promptly.\n- **Persona path reuses the harness's own gates unchanged** — persona principal, fail-closed `allowedTools` offer+execution gates, tenant binding. `onToken` is best-effort telemetry threaded through `runToolLoop`; it never changes what the loop persists or authorizes.\n- **Custom tools stream via `binding.extraTools`** — the persona binding threads an optional `extraTools?: PrincipalTool[]` down to `runPersonaConversationTurn`, so a *streamed* persona chat can offer non-manifest, service-backed tools (the persona messaging tool `messages.send`, or an assistance-request/lead-ticket tool wrapping a `@smrt({ api:false, mcp:false })` service) and thus *act*, not only answer — matching the non-streaming persona path. It is resolved server-side by `authorize` (trusted), never from request input, and stays fully gated: each tool is filtered by the persona's `allowedTools` (offer gate) and re-asserts the bound principal's authority in `execute` (execution gate). Offering a tool is not authorizing it.\n"
4554
+ "content": "# Token Streaming (SSE, #1936)\n\nReference linked from [../AGENTS.md](../AGENTS.md). This contract was moved from\n`packages/chat/AGENTS.md` to keep the instruction chain under the 32 KB cap\n(`pnpm check:agents-chain`); AGENTS.md retains the cap-oriented summary.\n\n`chat-stream.ts` is the SSE seam for embeddable conversational UIs (first consumer: the Happy chat widget, `animation#5`): a client POSTs the conversation so far and receives a `text/event-stream` of `data: <json>` frames — `token` deltas as the model generates, then a final `done` frame with the message. The wire `ChatStreamEvent` union also declares `emotion` and `control` (#1921 host-page control commands) lanes for forward compatibility; the v1 engine emits `token`/`done`/`error`.\n\n- **`runChatConversationStream({ context, messages })`** — the transport-agnostic engine (an `AsyncGenerator<ChatStreamEvent>`). Dispatches on `context.binding`: **persona-bound** runs the full `runPersonaConversationTurn` with a token sink wired through the tool loop (`onToken` → `ai.chat({ stream: true, onProgress })`), then persists via `ChatService` and emits the persisted message as `done`; **plain/unbound** streams `ai.stream()` directly and emits a synthesized (unpersisted) `done`. Streamed tokens are a live PREVIEW (a tool-call round may narrate before acting); the `done` message is authoritative. Failures surface as an in-band `error` event, never a throw (the 200 has already committed once streaming starts).\n- **`createChatStreamHandler({ authorize, allowedOrigins?, allowCredentials? })`** — a Fetch-compatible handler returning `text/event-stream` (mirrors `createVoiceGatewayTurnHandler`). `authorize(request, body)` is the SOLE trust boundary and works exactly like the voice gateway: this module NEVER authorizes from the request's `session` metadata — the app validates the caller (bearer session id / cookie / same-origin) and the claimed ids against the authenticated principal, and returns an already-authorized `ChatStreamContext`. Generation caps (`model`/`maxTokens`/`maxSteps`) live on the context (server-resolved), never on the request. Cross-origin embedding uses the same fail-closed CORS posture as core `_events` (#1861): the `Origin` is echoed only when allow-listed (never `*`), credentials only when opted in.\n- **`SmrtChatBackend` (`@happyvertical/smrt-chat/client`)** — the consume side of the same contract: a browser SSE client (`src/client.ts`) that POSTs the conversation and dispatches `token`/`emotion`/`done`/`error` frames to streaming handlers, tolerating heartbeat comments and frames split across chunks. The subpath is BROWSER-SAFE and dependency-free (no server runtime, no workspace imports — keep it that way), and its widget-facing types are structurally identical to `@happyvertical/animation`'s `ChatBackend` contract so an instance plugs straight into the floating chat widget. `src/client.contract.ts` carries the compile-time locks pinning it to `chat-stream.ts`'s `ChatStreamEvent`/`ChatStreamSession` — a NON-test module precisely so `pnpm typecheck` actually enforces them (`tsconfig.typecheck.json` excludes `.test.ts` files, and Vitest transpiles without typechecking). A clean close without a `done` frame surfaces as an error (never an empty reply), and a settled turn cancels the reader so the connection is released promptly.\n- **Persona path reuses the harness's own gates unchanged** — persona principal, fail-closed `allowedTools` offer+execution gates, tenant binding. `onToken` is best-effort telemetry threaded through `runToolLoop`; it never changes what the loop persists or authorizes.\n- **Custom tools stream via `binding.extraTools`** — the persona binding threads an optional `extraTools?: PrincipalTool[]` down to `runPersonaConversationTurn`, so a *streamed* persona chat can offer non-manifest, service-backed tools (the persona messaging tool `messages.send`, or an assistance-request/lead-ticket tool wrapping a `@smrt({ api:false, mcp:false })` service) and thus *act*, not only answer — matching the non-streaming persona path. It is resolved server-side by `authorize` (trusted), never from request input, and stays fully gated: each tool is filtered by the persona's `allowedTools` (offer gate) and re-asserts the bound principal's authority in `execute` (execution gate). Offering a tool is not authorizing it.\n\nThe PostgreSQL post-handler transaction regression expects all persisted public\nturn rows: user, tool result, assistant reply. It checks the tool call identity,\nsuccess state, reply linkage and tenant alongside the reply and idempotent retry.\nOrdinary tool results remain visible in conversation history; only trusted\ninternal-turn provenance is filtered out.\n"
4555
+ },
4556
+ {
4557
+ "path": "agents/turn-drivers.md",
4558
+ "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"
4560
+ },
4561
+ {
4562
+ "path": "agents/owner-approvals.md",
4563
+ "module": "owner-approvals",
4564
+ "content": "# Durable assistant approvals\n\nRead `src/assistant-approvals.ts` for policy and the adapter over app-runtime's\n`OwnerApprovalAuthority`. Reuse the typed approval wire contract and existing\nexternal driver callbacks, tool-loop execution seam, ChatService authoring gate,\nroute auth/origin/thread checks, HTTP transport and smrt-ui Button/Card/i18n.\nNo duplicate approval model, ledger, generated CRUD route or provider integration.\n\nDefault policy uses canonical manifest action / extra-tool slug; destructive\narguments on a multiplexed tool can only add a hold, never downgrade a destructive\nslug. Host per-tool override precedes per-operation override. Client declarations,\nengine-selected approval ids and summaries, or `approved` arguments never grant\npermission. External requests are rebuilt from the pending, offered canonical\ncall and host summary. Explicit `waitForApproval` without `approvals` preserves the\nlegacy trusted host callback contract; it must itself supply durability/owner auth.\nThe default bridge uses the app-runtime authority, including across processes.\n\nBuilt-in holds stop after the tool round (`approval`). The envelope saves the\noriginal actor, tenant, allow-list, permission ceiling, session, thread and origin\nmessage. Decide re-resolves offerings and permissions and intersects the saved\nceiling; it never substitutes the deciding owner as executor. It consumes once\nbefore execution, completes before authoring, and writes a tool result/refusal to\nthe same thread. A tenant owner may decide another requester's hold without receiving their thread history. A crash after consumption cannot safely be retried automatically;\n`executing` is an explicit unknown-outcome state for reconciliation. Pending\nrequests survive restart; external engine processes do not resume automatically.\nA restored pending external hold may be denied/expire, but approval without its\nlive driver cannot restart that driver. The low-level engine/MCP adapter still\nowns enforcement of live tool permissions for external effects.\n\nThe SQLite default uses migrated smrt-approvals application schema plus a runtime\nsystem envelope table. Do not create approval model schema on request. Other\nstorage engines require a host authority/store integration and its own tests.\n\n## Test design\n\nCommands: package `test`, `typecheck`, filtered dependency `build`; root `lint`,\n`format-check`, `knowledge:check --strict`. All new tests are Node/SQLite plus\njsdom components, scripted models, fake external drivers, no provider/container.\n\n| Behavior/invariant | Reachable trigger | Positive case | Negative/failure | Actor/context | Executor/transaction | Runtime/dialect | External edge | Level | Command |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Built-in hold | Model calls server delete | Persisted/streamed pending; no execution | Model approved flag cannot bypass | Original principal/owned thread | Existing tool-loop principal context + canonical authority | Node/SQLite | Tool call + SSE | Route integration | Package test |\n| Decision/resumption | Owner posts decision | Original args/principal run once; result authored | Deny, repeat, malformed, foreign origin/tenant/non-owner | Owner × owned/foreign thread × tenant | Authority consume before executeAsPrincipal; ChatService author | Node/SQLite | HTTP decision | Route integration | Package test |\n| Permission ceiling | Decision after grants/offer changes | Live intersection preserves allowed action | Revoked tool/permission cannot run | Original actor, never decider | Existing PermissionResolver + execution gate | Node/SQLite | Host extra tools | Route integration | Package test |\n| External wait | Driver requests approval | Same durable authority releases wait | Denial/abort never grants approval | Bound driver principal/call | Canonical gate + live host execution contract | Node/SQLite | Driver callbacks | Route integration | Package test |\n| UI projection | Persisted tool call mounted | Accessible translated controls/outcome; reload terminal status | No verified pending state: disabled; HTTP failure alert | Authenticated browser/owned thread | HTTP transport; no browser decision authority | jsdom | Transport optional methods | Component | Package test |\n| Default regressions | Ordinary read/no driver | Existing suites remain green | Existing browser/loop failure gates | Existing fixtures | Existing transactions | Existing package runtimes | Existing SSE/driver contract | Regression | Full package test |\n\nReuse search evidence: MCP `review_smrt_project` on app-runtime and chat;\n`build_context` architecture query for durable owner approvals/holds/cards; intent\nindex `Human approval steps`; name and purpose `rg` searches across smrt-ui,\nsmrt-svelte, chat, core, app-runtime, approvals and app-shell. Existing generic\n`ApprovalService` and primitives were reused. ConfirmDialog is modal and cannot\nrepresent a durable inline thread card; app-shell's ApprovalCard is tied to shell\nobject/action/draft types and shell styling, so the shared chat card composes the\nexisting primitives while shell remains untouched.\n\nThe integration rebase audit repeated MCP package-specialist context for\n`approvals` and the architecture query for a reusable Svelte decision card,\nthen inspected package exports and all approval/decision/confirmation Svelte\nsources. `smrt-approvals` exports the gate/ledger and no Svelte UI.\nProjects' ApprovalActions/PreviewApprovalPanel require project workflow states\nor preview identities; timesheets' queue requires time-entry rows; commerce's\nPricingVersionDecision requires a pricing version; reports' ReportConfirmation\nrequires a report proposal and save operation. Those domain contracts cannot\nrepresent a server-tool hold without fabricating domain data. Card/Button remain\nthe reusable UI layer for AssistantApprovalCard.\n\n| New production file | Reuse search and result |\n| --- | --- |\n| `app-runtime/src/owner-approvals.ts` | MCP review/context + intent index; `rg` approval/hold/owner/decision in runtime, approvals, users, core and shell. Extends ApprovalService with tool execution envelopes; uses canonical owner-role membership APIs. No new approval model. |\n| `chat/src/assistant-approvals.ts` | MCP review/context; `rg` approval/policy/destructive/wait in chat, runtime, shell and inference. Adapts the existing tool/driver callbacks to OwnerApprovalAuthority; no existing host-neutral durable tool adapter fit. |\n| `chat/src/svelte/components/assistant/AssistantApprovalCard.svelte` | MCP review, architecture and approvals specialist context; `rg` by approval/decision/confirmation names and purpose across packages. Reuses smrt-ui Card/Button/i18n; domain widgets above do not accept tool holds. |\n\nThe browser-free `./assistant-approvals` entry exports `observeAssistantApproval`\nfor hosts that already execute approved actions. It observes the same authority\nuntil completion, with abort/timeout cleanup, without consuming or executing.\n`AssistantApprovalCard` optionally accepts a host-authorized `presentation` and\n`detail` snippet for an existing decision endpoint and server-loaded view.\nTricia supplies its builder/draft preview through that snippet; the shared card\nowns headings, status, controls and messages. The normal transport-verified card\nkeeps its existing behavior and polling.\n## Holds outside a thread\n\nPass `approvalContinuations` alongside the same `approvals` authority to\n`mountAssistantRoutes`. The existing owner approvals list includes persisted\nnon-thread records and outcomes. Its same-origin decision route delegates only\nrecords with a trusted continuation binding; ordinary thread holds retain their\nexisting thread/session checks. `AssistantApprovalCard` accepts no `threadId` for\nthis owner list, reusing the existing HTTP transport. No parallel approval route\nor UI is added. The template host tests exercise the real decision route after\nrecreating the host and its authority, including an external MCP delete and a\nnative cookbook disable.\n\nAuthenticated thread message reads also project native continuation approvals\nthrough the existing `AssistantApprovalCard` wire shape. The message and\napproval-list routes share one owned-thread reader: tenant, requesting user,\ntrusted human profile and thread must all match, and the authority rechecks\nlive ownership. Missing/malformed principal bindings are excluded. A revoked\nowner can still read their ordinary conversation, without native hold projections.\nSynthetic message ids are `approval:<public approval id>`; timestamps come from\nthe canonical record. Persisted cards are deduplicated by approval id. Native\npublic views use that same public id for `callId` and omit arguments, recovery\ncontext/keys and raw results; decisions still use the existing continuation rail.\nGeneric tool presentation uses a fixed safe caption unless the trusted async\n`presentApproval(record)` callback derives a business preview from the canonical\nhold. That caption appears in both the public summary and explicit presentation;\nthe generic card never promotes a raw stored/model summary. See\n[turn presentation](turn-drivers.md) for private pass provenance and public paging.\nProjection is enabled by either an explicit approval authority or configured\ncontinuations using the default database-backed live-owner authority. Ordinary\nchat without either option does not query the owner ledger.\n\nThe existing message route has no cursor: it loads at most 200 persisted messages.\nRecent terminal native references share a 200-item historical bound with those\nmessages and are excluded when older than the persisted page. Unsettled native\nholds remain visible even when older, then the merged response is chronological.\nThe underlying owner authority list remains unbounded; this projection does not\nintroduce a second store or claim storage pagination. Route recreation and thread\nswitches reconstruct the same ids and current canonical status without writes.\n\nThe existing route suite covers real SQLite native holds, malformed/foreign\nuser/profile/tenant/thread bindings, revoked owner access, persisted-card dedupe,\nreload, safe succeeded/denied outcomes, and the 201-message boundary. Existing\nbuilt-in holds retain their correlation ids and authored transcript behavior.\n\nD1 second-rebase compatibility: transport mode also works without `threadId`,\nusing the existing transport's owner-list endpoint. It still verifies persisted\nstate before enabling controls and reports failures. Presentation/detail mode\nkeeps precedence, exact legacy labels and no transport polling. The card's\nparameterized DOM cases cover thread and owner-list success/refusal; restoring\nthe old thread-only render/poll guards makes both owner-list cases fail. The\nunchanged app-shell suites exercise Tricia's presentation/detail and connection\ncontracts. No duplicate card or decision route is introduced.\n\nOverlapping browser reads use the public browser-safe\n`reconcileAssistantApprovalView(current, next)` beside the existing wire type.\nSame-hold presentation advances pending → approved → executing → terminal; equal\nor forward active views take current canonical data, while the first terminal\nview is retained. Different hold ids never merge. AssistantApprovalCard, cookbook\nclient completion observation and Settings reuse this one policy so a delayed\npending poll cannot re-enable buttons after a newer decision. Verification and\nexecution authority remain server-owned. Tests release an actual deferred card\npoll after approved/executing/terminal decision responses and preserve the\nnewer caption, status and disabled decision state.\n\n## Owner removal preference\n\n`AssistantApprovalPolicy.allowRemovalsInChat` is trusted host input, resolved per authenticated turn, never from model arguments. Default is a hold. A true value waives only a canonical manifest `delete` with a nonempty single-record `id` and trusted host `annotations.recordDeletion: true`. The host may declare this only for an app-data record, never identity, credentials, roles, tenants, settings or installation objects. Names and model arguments cannot supply this classification; unclassified manifest tools, extra/custom tools, design-class tools, purge/drop/truncate/destroy and unknown destructive hints remain held. Canonical security/control package identities (including registered ancestry and replacement provenance) and declared `sensitive` models cannot receive the setting waiver even if incorrectly marked. The cookbook host marks only canonical deletes for its placed app-data lists. Other hosts must explicitly classify their data tools or retain the hold. Native cookbook tools retain their own authority and independent design-preview checks. The host must never pass the opt-out for an outside MCP/plugin/local-credential request. The normal dispatch and change-history paths still execute; the preference is not an approval decision. Tests cover forged tool flags, purge effects and the CLI host's chat/outside distinction.\n\nIn-flight removal settings: the MCP boundary honors both the current owner preference and the running turn's existing `requiresApproval` gate. Tightening can add a hold immediately; relaxing never waives a hold already bound to that request. This prevents an effect from running and then being rejected by result authoring. CLI host tests flip the preference just before MCP execution and still require the original owner decision exactly once.\n\nReview regression evidence: before the fix, name-only security/custom deletions with the opt-out failed the negative test. Head tests cover explicit record metadata with destructive hints, missing/invalid ids, forged argument metadata, design metadata, security/unknown names and bulk/custom operations. Real SQLite built-in turns prove the opt-out deletes a declared business record and emits the existing principal audit event, while the default preserves the record and ledger hold; route tests preserve a hold for unclassified extra-tool deletion. The existing real CLI host cases cover both engines/modes, audited chat deletion, outside MCP holds and mid-turn policy tightening/relaxing.\n\n| Review behavior/invariant | Reachable trigger and positive case | Negative/failure case | Actor/context | Executor/transaction; runtime | External edge and level | Validation |\n| --- | --- | --- | --- | --- | --- | --- |\n| Structural approval floor | Call removeField/removeList/undo/recipe disable on either surface or durable Apply; native pending hold | Four setting combinations and permissive host policy cannot mutate or append history | Existing live owner, tenant-bound native context; existing suites retain non-owner/foreign-tenant refusal | Existing editor/approval executor and journal; SQLite (same regression file supports optional PGlite) | MCP/assistant/native Apply; integration | core full test |\n| Record-only waiver | Opted-out owner deletes one explicitly classified business record | Default on, unknown/security/control/sensitive/derived model, design metadata, invalid id, bulk/custom tool or forged classification stays held | Original in-app principal; trusted tool metadata, never model args | Existing principal dispatch and audit sink; real SQLite | Built-in turn + canonical policy; integration/unit | chat full test |\n| CLI/outside parity | Existing real host fixture deletes app record and records change feed with opt-out | Outside MCP and policy change while a turn runs still hold and execute once after decision | Same live owner/grant ceiling; protected/native engine states | Existing host MCP, scoped token, approval continuation and SQLite | Both stub CLI engines; host integration | template-sveltekit full test |\n\nToken exposure documentation was verified against command construction, credentials, the host's offered/scoped binding and the local-token verifier. No live CLI/provider call or credential read was needed for this review.\n"
4565
+ },
4566
+ {
4567
+ "path": "agents/tool-summaries.md",
4568
+ "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"
4570
+ },
4571
+ {
4572
+ "path": "agents/runtime-exposure.md",
4573
+ "module": "runtime-exposure",
4574
+ "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"
4538
4575
  },
4539
4576
  {
4540
4577
  "path": "agents/ai-unavailable.md",