@happyvertical/smrt-chat 0.61.6 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/AGENTS.md +4 -0
  2. package/agents/assistant-turn-runs.md +74 -0
  3. package/agents/tool-summaries.md +1 -1
  4. package/agents/turn-drivers.md +64 -46
  5. package/dist/assistant-approvals.js +1 -1
  6. package/dist/assistant-approvals.js.map +1 -1
  7. package/dist/assistant-turn-driver.d.ts +11 -8
  8. package/dist/assistant-turn-driver.d.ts.map +1 -1
  9. package/dist/assistant-turn-events.d.ts +1 -1
  10. package/dist/assistant-turn-events.d.ts.map +1 -1
  11. package/dist/assistant-turn.d.ts +34 -3
  12. package/dist/assistant-turn.d.ts.map +1 -1
  13. package/dist/chunks/{ChatService-CeOVzOqN.js → ChatService-CDLAEJms.js} +2 -2
  14. package/dist/chunks/{ChatService-CeOVzOqN.js.map → ChatService-CDLAEJms.js.map} +1 -1
  15. package/dist/chunks/assistant-turn-events-DwdCZzQ0.js.map +1 -1
  16. package/dist/chunks/{chat-stream-Cl8JV-K0.js → chat-stream-BJbmqHsu.js} +742 -254
  17. package/dist/chunks/chat-stream-BJbmqHsu.js.map +1 -0
  18. package/dist/engines.d.ts +4 -4
  19. package/dist/engines.d.ts.map +1 -1
  20. package/dist/engines.js +22 -24
  21. package/dist/engines.js.map +1 -1
  22. package/dist/index.d.ts +2 -1
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -3
  25. package/dist/internal/agent-runtime.js +1 -1
  26. package/dist/manifest.json +2 -1
  27. package/dist/smrt-knowledge.json +28 -10
  28. package/dist/smrt-knowledge.okf.md +16 -11
  29. package/dist/svelte/components/assistant/AssistantDock.svelte +2 -2
  30. package/dist/svelte/components/assistant/assistant-http-client.d.ts +2 -2
  31. package/dist/svelte/components/assistant/assistant-http-client.d.ts.map +1 -1
  32. package/dist/svelte/components/assistant/assistant-http-client.js +5 -5
  33. package/dist/svelte/components/assistant/assistant-transport.d.ts +7 -6
  34. package/dist/svelte/components/assistant/assistant-transport.d.ts.map +1 -1
  35. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.d.ts +3 -3
  36. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.d.ts.map +1 -1
  37. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.js +30 -30
  38. package/dist/svelte/i18n.d.ts +1 -1
  39. package/dist/svelte/i18n.js +1 -1
  40. package/dist/svelte/index.d.ts +1 -1
  41. package/dist/svelte/index.d.ts.map +1 -1
  42. package/dist/sveltekit.d.ts +55 -24
  43. package/dist/sveltekit.d.ts.map +1 -1
  44. package/dist/sveltekit.js +109 -44
  45. package/dist/sveltekit.js.map +1 -1
  46. package/dist/tool-loop.d.ts +2 -1
  47. package/dist/tool-loop.d.ts.map +1 -1
  48. package/dist/tool-run-types.d.ts +102 -0
  49. package/dist/tool-run-types.d.ts.map +1 -0
  50. package/dist/turn-tracking.d.ts +246 -0
  51. package/dist/turn-tracking.d.ts.map +1 -0
  52. package/package.json +20 -19
  53. package/dist/chunks/chat-stream-Cl8JV-K0.js.map +0 -1
  54. package/dist/work-profile.d.ts +0 -64
  55. package/dist/work-profile.d.ts.map +0 -1
@@ -1,34 +1,69 @@
1
- import { a as sendAgentReply } from "./ChatService-CeOVzOqN.js";
1
+ import { a as sendAgentReply } from "./ChatService-CDLAEJms.js";
2
2
  import { requiresOwnerApproval } from "../assistant-approvals.js";
3
3
  import { describeAssistantTool, toolSummary } from "../tool-summary.js";
4
4
  import { a as matchesToolAllowList, n as encodeAssistantTurnEvent } from "./assistant-turn-events-DwdCZzQ0.js";
5
- import { ObjectRegistry, ValidationError, applySyncWritablePolicy, fieldTypeToJsonSchema, resolveDatabase } from "@happyvertical/smrt-core";
5
+ import { AiRunStoppedError, AiRunTrackingDisabledError, DEFAULT_INFERENCE_TIER, ObjectRegistry, ValidationError, aiRunStoppedError, appendAiRunEvent, applySyncWritablePolicy, beginAiRunCall, closeAiRunHandoff, fieldTypeToJsonSchema, finishAiRun, getAiRun, resolveDatabase, stopAiRun, stopAiRunForChild } from "@happyvertical/smrt-core";
6
6
  import { inferenceUnavailableMessage, inferenceUnavailableStatus, isInferenceUnavailableError } from "@happyvertical/smrt-core/inference-availability";
7
7
  import { AsyncLocalStorage } from "node:async_hooks";
8
+ import { randomUUID } from "node:crypto";
8
9
  import { getCurrentTenant, isSuperAdminBypass, isSystemContext, isTenancyEnabled, withTenant } from "@happyvertical/smrt-tenancy";
9
10
  import { DataSurfaceDeniedError, PrincipalToolNotAllowedError, executeAsPrincipal } from "@happyvertical/smrt-agents";
10
11
  import { isRuntimeModelEnabled } from "@happyvertical/smrt-core/runtime-exposure";
11
12
  import { OperationPermissionError, PermissionCatalogService } from "@happyvertical/smrt-users";
12
13
  import { RUNTIME_REPORT_BUCKETS, RUNTIME_REPORT_CHART_TYPES, RUNTIME_REPORT_FILTER_OPS, RUNTIME_REPORT_HAVING_OPS, RUNTIME_REPORT_LIMITS, RUNTIME_REPORT_MEASURE_FNS, RuntimeReport, RuntimeReportError, compileRuntimeReportSpec, describeRuntimeReportSource, getRuntimeReport, listRuntimeReports, parseRuntimeReportSpec, runRuntimeReport, runStoredRuntimeReport, saveRuntimeReport } from "@happyvertical/smrt-reports";
14
+ import { definePrompt, resolvePrompt, trackedPromptCall } from "@happyvertical/smrt-prompts";
13
15
  import { personaLearningMemory, resolvePersonaInstructions } from "@happyvertical/smrt-personas";
14
- //#region src/work-profile.ts
15
- var WorkProfileEscalation = class extends Error {
16
- constructor(tool) {
17
- super("Thinking this through");
16
+ //#region src/tool-run-types.ts
17
+ var ToolRunTypeRefusal = class extends Error {
18
+ constructor(tool, runTypes) {
19
+ super(`The tool ${tool} runs only in a workflow run.`);
18
20
  this.tool = tool;
19
- this.name = "WorkProfileEscalation";
21
+ this.runTypes = runTypes;
22
+ this.name = "ToolRunTypeRefusal";
20
23
  }
21
24
  tool;
25
+ runTypes;
26
+ code = "tool_run_type";
27
+ /** The conversation up to the refused call, for the workflow run. */
22
28
  messages;
23
- workRun;
29
+ /** What the turn had used when it was refused. */
30
+ execution;
24
31
  };
25
- var WORK_RUN_ACCOUNTING = /* @__PURE__ */ Symbol("workRunAccounting");
26
- function assertWorkProfileTool(options, tool) {
27
- if ((options.workProfile?.name ?? "assist") === "assist" && options.workProfile?.autoEscalate !== false && (options.designTools?.includes(tool.slug) || tool.annotations?.workProfile === "design")) throw new WorkProfileEscalation(tool.slug);
32
+ var TURN_ACCOUNTING = /* @__PURE__ */ Symbol("turnAccounting");
33
+ function toolRunTypes(options, tool) {
34
+ return tool.annotations?.runTypes ?? (options.workflowTools?.includes(tool.slug) ? ["workflow"] : void 0);
35
+ }
36
+ function assertToolRunType(options, tool) {
37
+ const runTypes = toolRunTypes(options, tool);
38
+ if (runTypes && !runTypes.includes("turn")) throw new ToolRunTypeRefusal(tool.slug, runTypes);
39
+ }
40
+ function mayEscalateToWorkflow(options) {
41
+ return options.assistantSettings?.escalateToWorkflow !== false && typeof options.onWorkflowEscalation === "function";
42
+ }
43
+ function turnExecution(options, accounting, observed) {
44
+ const selection = options.selection;
45
+ if (!selection || !accounting) return void 0;
46
+ const model = accounting.model ?? observed?.model;
47
+ return {
48
+ engine: selection.engine,
49
+ ...model ? { model } : {},
50
+ ...observed?.requestedModel ?? selection.model ? { requestedModel: observed?.requestedModel ?? selection.model } : {},
51
+ ...selection.effort ? { effort: selection.effort } : {},
52
+ durationMs: Date.now() - accounting.startedAt,
53
+ ...accounting.usageKnown ? { tokens: accounting.tokens } : {},
54
+ toolCalls: accounting.toolCalls,
55
+ ...observed?.fallback ? { fallback: observed.fallback } : {}
56
+ };
57
+ }
58
+ function reportExecution(options, execution) {
59
+ if (!execution || !options.onExecution) return;
60
+ try {
61
+ options.onExecution(execution);
62
+ } catch {}
28
63
  }
29
64
  //#endregion
30
65
  //#region src/__smrt-register__.ts
31
- ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-chat","packageVersion":"0.61.6","objects":{"@happyvertical/smrt-chat:AgentSessionCollection":{"name":"agentsessioncollection","className":"AgentSessionCollection","qualifiedName":"@happyvertical/smrt-chat:AgentSessionCollection","collection":"agentsessions","filePath":"src/collections/AgentSessionCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"findActiveByParticipant":{"name":"findActiveByParticipant","async":true,"parameters":[{"name":"participantProfileId","type":"string","optional":false}],"returnType":"Promise<AgentSession[]>","isStatic":false,"isPublic":true},"findActiveSession":{"name":"findActiveSession","async":true,"parameters":[{"name":"agentId","type":"string","optional":false},{"name":"participantProfileId","type":"string","optional":false},{"name":"tenantId","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]},{"name":"sessionKey","type":"string | null","optional":true,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<AgentSession | null>","isStatic":false,"isPublic":true},"findOrCreate":{"name":"findOrCreate","async":true,"parameters":[{"name":"params","type":"object","optional":false,"memberTypes":["string","string | null","string[]"]}],"returnType":"Promise<AgentSession>","isStatic":false,"isPublic":true},"findByAgent":{"name":"findByAgent","async":true,"parameters":[{"name":"agentId","type":"string","optional":false}],"returnType":"Promise<AgentSession[]>","isStatic":false,"isPublic":true},"expireStale":{"name":"expireStale","async":true,"parameters":[{"name":"olderThan","type":"Date","optional":false},{"name":"scope","type":"object","optional":true,"memberTypes":["string | null","string"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"agent_sessions","api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"AgentSession","exportName":"AgentSessionCollection","collectionExportName":"AgentSessionCollectionCollection","collectionOf":"@happyvertical/smrt-chat:AgentSession","inheritedExposure":["api","mcp"],"schema":{"tableName":"agent_sessions","ddl":"CREATE TABLE IF NOT EXISTS \\"agent_sessions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"agent_id\\" TEXT NOT NULL DEFAULT '',\\n \\"agent_profile_id\\" UUID,\\n \\"participant_profile_id\\" UUID NOT NULL,\\n \\"chat_room_id\\" UUID,\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"allowed_tools\\" TEXT DEFAULT '[]',\\n \\"session_context\\" TEXT DEFAULT '{}',\\n \\"system_prompt\\" TEXT DEFAULT '',\\n \\"message_count\\" INTEGER DEFAULT 0,\\n \\"total_tokens_used\\" INTEGER DEFAULT 0,\\n \\"max_tokens\\" INTEGER DEFAULT 0,\\n \\"max_messages\\" INTEGER DEFAULT 0,\\n \\"last_message_at\\" TIMESTAMP,\\n \\"expires_at\\" TIMESTAMP,\\n \\"closed_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"agent_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"agent_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"participant_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"chat_room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"allowed_tools":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"session_context":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"system_prompt":{"type":"TEXT","notNull":false,"unique":false,"default":""},"message_count":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"total_tokens_used":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"max_tokens":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"max_messages":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"last_message_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"closed_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"agent_sessions_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"agent_sessions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"agent_sessions_agent_profile_id_idx","columns":["agent_profile_id"]},{"name":"agent_sessions_participant_profile_id_idx","columns":["participant_profile_id"]},{"name":"agent_sessions_chat_room_id_idx","columns":["chat_room_id"]}],"version":"0a330023"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatMessageCollection":{"name":"chatmessagecollection","className":"ChatMessageCollection","qualifiedName":"@happyvertical/smrt-chat:ChatMessageCollection","collection":"chatmessages","filePath":"src/collections/ChatMessageCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"getByRoom":{"name":"getByRoom","async":true,"parameters":[{"name":"roomId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false},{"name":"options","type":"object","optional":true,"typeUnresolved":true,"memberTypes":["number","string"]}],"returnType":"Promise<ChatMessage[]>","isStatic":false,"isPublic":true},"getByThread":{"name":"getByThread","async":true,"parameters":[{"name":"threadId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<ChatMessage[]>","isStatic":false,"isPublic":true},"getByAgentSession":{"name":"getByAgentSession","async":true,"parameters":[{"name":"agentSessionId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<ChatMessage[]>","isStatic":false,"isPublic":true},"search":{"name":"search","async":true,"parameters":[{"name":"filters","type":"any","optional":false,"typeUnresolved":true}],"returnType":"Promise<ChatMessage[]>","isStatic":false,"isPublic":true},"getUnreadCount":{"name":"getUnreadCount","async":true,"parameters":[{"name":"roomId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false},{"name":"lastReadMessageId","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"getLatestPerRoom":{"name":"getLatestPerRoom","async":true,"parameters":[{"name":"roomIds","type":"string[]","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Map<string, ChatMessage>>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_messages","api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"ChatMessage","exportName":"ChatMessageCollection","collectionExportName":"ChatMessageCollectionCollection","collectionOf":"@happyvertical/smrt-chat:ChatMessage","inheritedExposure":["api","mcp"],"schema":{"tableName":"chat_messages","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_messages\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"room_id\\" UUID NOT NULL,\\n \\"thread_id\\" UUID,\\n \\"sender_profile_id\\" UUID NOT NULL,\\n \\"agent_session_id\\" UUID,\\n \\"content\\" TEXT DEFAULT '',\\n \\"message_type\\" TEXT NOT NULL DEFAULT 'text',\\n \\"role\\" TEXT NOT NULL DEFAULT 'user',\\n \\"is_edited\\" BOOLEAN DEFAULT FALSE,\\n \\"edited_at\\" TIMESTAMP,\\n \\"is_deleted\\" BOOLEAN DEFAULT FALSE,\\n \\"reply_to_message_id\\" UUID,\\n \\"metadata\\" TEXT DEFAULT '{}',\\n \\"tool_call_data\\" TEXT,\\n \\"attachments\\" TEXT DEFAULT '[]'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"thread_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_threads","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"sender_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"agent_session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"agent_sessions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"content":{"type":"TEXT","notNull":false,"unique":false,"default":""},"message_type":{"type":"TEXT","notNull":true,"unique":false,"default":"text"},"role":{"type":"TEXT","notNull":true,"unique":false,"default":"user"},"is_edited":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"edited_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"is_deleted":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"reply_to_message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"tool_call_data":{"type":"TEXT","notNull":false,"unique":false},"attachments":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"}},"indexes":[{"name":"chat_messages_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_messages_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_messages_room_id_idx","columns":["room_id"]},{"name":"chat_messages_thread_id_idx","columns":["thread_id"]},{"name":"chat_messages_sender_profile_id_idx","columns":["sender_profile_id"]},{"name":"chat_messages_agent_session_id_idx","columns":["agent_session_id"]},{"name":"chat_messages_reply_to_message_id_idx","columns":["reply_to_message_id"]}],"version":"83f829da"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatParticipantCollection":{"name":"chatparticipantcollection","className":"ChatParticipantCollection","qualifiedName":"@happyvertical/smrt-chat:ChatParticipantCollection","collection":"chatparticipants","filePath":"src/collections/ChatParticipantCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"getByRoom":{"name":"getByRoom","async":true,"parameters":[{"name":"roomId","type":"string","optional":false}],"returnType":"Promise<ChatParticipant[]>","isStatic":false,"isPublic":true},"getByProfile":{"name":"getByProfile","async":true,"parameters":[{"name":"profileId","type":"string","optional":false}],"returnType":"Promise<ChatParticipant[]>","isStatic":false,"isPublic":true},"findMembership":{"name":"findMembership","async":true,"parameters":[{"name":"roomId","type":"string","optional":false},{"name":"profileId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":true}],"returnType":"Promise<ChatParticipant | null>","isStatic":false,"isPublic":true},"findActiveMembership":{"name":"findActiveMembership","async":true,"parameters":[{"name":"roomId","type":"string","optional":false},{"name":"profileId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<ChatParticipant | null>","isStatic":false,"isPublic":true},"isActiveMember":{"name":"isActiveMember","async":true,"parameters":[{"name":"roomId","type":"string","optional":false},{"name":"profileId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"getOnlineInRoom":{"name":"getOnlineInRoom","async":true,"parameters":[{"name":"roomId","type":"string","optional":false}],"returnType":"Promise<ChatParticipant[]>","isStatic":false,"isPublic":true},"getAdminsInRoom":{"name":"getAdminsInRoom","async":true,"parameters":[{"name":"roomId","type":"string","optional":false}],"returnType":"Promise<ChatParticipant[]>","isStatic":false,"isPublic":true},"countInRoom":{"name":"countInRoom","async":true,"parameters":[{"name":"roomId","type":"string","optional":false}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_participants","api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"ChatParticipant","exportName":"ChatParticipantCollection","collectionExportName":"ChatParticipantCollectionCollection","collectionOf":"@happyvertical/smrt-chat:ChatParticipant","inheritedExposure":["api","mcp"],"schema":{"tableName":"chat_participants","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_participants\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"room_id\\" UUID NOT NULL,\\n \\"profile_id\\" UUID NOT NULL,\\n \\"role\\" TEXT NOT NULL DEFAULT 'member',\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"online_status\\" TEXT NOT NULL DEFAULT 'offline',\\n \\"last_read_message_id\\" UUID,\\n \\"last_seen_at\\" TIMESTAMP,\\n \\"joined_at\\" TIMESTAMP,\\n \\"nickname\\" TEXT DEFAULT '',\\n \\"is_muted\\" BOOLEAN DEFAULT FALSE,\\n \\"is_pinned\\" BOOLEAN DEFAULT FALSE\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"role":{"type":"TEXT","notNull":true,"unique":false,"default":"member"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"online_status":{"type":"TEXT","notNull":true,"unique":false,"default":"offline"},"last_read_message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"last_seen_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"joined_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"nickname":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_muted":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"is_pinned":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false}},"indexes":[{"name":"chat_participants_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_participants_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_participants_room_id_idx","columns":["room_id"]},{"name":"chat_participants_profile_id_idx","columns":["profile_id"]},{"name":"chat_participants_last_read_message_id_idx","columns":["last_read_message_id"]}],"version":"166a9740"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatReactionCollection":{"name":"chatreactioncollection","className":"ChatReactionCollection","qualifiedName":"@happyvertical/smrt-chat:ChatReactionCollection","collection":"chatreactions","filePath":"src/collections/ChatReactionCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"getByMessage":{"name":"getByMessage","async":true,"parameters":[{"name":"messageId","type":"string","optional":false}],"returnType":"Promise<ChatReaction[]>","isStatic":false,"isPublic":true},"getReactionCounts":{"name":"getReactionCounts","async":true,"parameters":[{"name":"messageId","type":"string","optional":false}],"returnType":"Promise<Map<string, object>>","isStatic":false,"isPublic":true},"toggle":{"name":"toggle","async":true,"parameters":[{"name":"messageId","type":"string","optional":false},{"name":"profileId","type":"string","optional":false},{"name":"emoji","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<object>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_reactions","api":{"include":["list"]},"mcp":{"include":["list"]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"ChatReaction","exportName":"ChatReactionCollection","collectionExportName":"ChatReactionCollectionCollection","collectionOf":"@happyvertical/smrt-chat:ChatReaction","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"chat_reactions","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_reactions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"message_id\\" UUID NOT NULL,\\n \\"profile_id\\" UUID NOT NULL,\\n \\"emoji\\" TEXT NOT NULL DEFAULT ''\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"emoji":{"type":"TEXT","notNull":true,"unique":false,"default":""}},"indexes":[{"name":"chat_reactions_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_reactions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_reactions_message_id_idx","columns":["message_id"]},{"name":"chat_reactions_profile_id_idx","columns":["profile_id"]}],"version":"635cdbec"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatRoomCollection":{"name":"chatroomcollection","className":"ChatRoomCollection","qualifiedName":"@happyvertical/smrt-chat:ChatRoomCollection","collection":"chatrooms","filePath":"src/collections/ChatRoomCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"findByType":{"name":"findByType","async":true,"parameters":[{"name":"roomType","type":"ChatRoomType","optional":false}],"returnType":"Promise<ChatRoom[]>","isStatic":false,"isPublic":true},"findPublic":{"name":"findPublic","async":true,"parameters":[],"returnType":"Promise<ChatRoom[]>","isStatic":false,"isPublic":true},"findDMs":{"name":"findDMs","async":true,"parameters":[],"returnType":"Promise<ChatRoom[]>","isStatic":false,"isPublic":true},"findAgentRooms":{"name":"findAgentRooms","async":true,"parameters":[],"returnType":"Promise<ChatRoom[]>","isStatic":false,"isPublic":true},"search":{"name":"search","async":true,"parameters":[{"name":"query","type":"string","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["number"]}],"returnType":"Promise<ChatRoom[]>","isStatic":false,"isPublic":true},"findOrCreateDM":{"name":"findOrCreateDM","async":true,"parameters":[{"name":"profileId1","type":"string","optional":false},{"name":"profileId2","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false},{"name":"participants","type":"ChatParticipantCollection","optional":false}],"returnType":"Promise<ChatRoom>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_rooms","api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"ChatRoom","exportName":"ChatRoomCollection","collectionExportName":"ChatRoomCollectionCollection","collectionOf":"@happyvertical/smrt-chat:ChatRoom","inheritedExposure":["api","mcp"],"schema":{"tableName":"chat_rooms","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_rooms\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT '',\\n \\"room_type\\" TEXT NOT NULL DEFAULT 'public',\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"topic\\" TEXT DEFAULT '',\\n \\"avatar_url\\" TEXT DEFAULT '',\\n \\"is_archived\\" BOOLEAN DEFAULT FALSE,\\n \\"max_participants\\" INTEGER DEFAULT 0,\\n \\"metadata\\" TEXT DEFAULT '{}',\\n \\"created_by_profile_id\\" UUID,\\n \\"last_message_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"room_type":{"type":"TEXT","notNull":true,"unique":false,"default":"public"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"topic":{"type":"TEXT","notNull":false,"unique":false,"default":""},"avatar_url":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_archived":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"max_participants":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"created_by_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"last_message_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"chat_rooms_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_rooms_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_rooms_created_by_profile_id_idx","columns":["created_by_profile_id"]}],"version":"8093a86b"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatThreadCollection":{"name":"chatthreadcollection","className":"ChatThreadCollection","qualifiedName":"@happyvertical/smrt-chat:ChatThreadCollection","collection":"chatthreads","filePath":"src/collections/ChatThreadCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"getByRoom":{"name":"getByRoom","async":true,"parameters":[{"name":"roomId","type":"string","optional":false}],"returnType":"Promise<ChatThread[]>","isStatic":false,"isPublic":true},"getActive":{"name":"getActive","async":true,"parameters":[{"name":"roomId","type":"string","optional":false}],"returnType":"Promise<ChatThread[]>","isStatic":false,"isPublic":true},"getUnresolved":{"name":"getUnresolved","async":true,"parameters":[],"returnType":"Promise<ChatThread[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_threads","api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"ChatThread","exportName":"ChatThreadCollection","collectionExportName":"ChatThreadCollectionCollection","collectionOf":"@happyvertical/smrt-chat:ChatThread","inheritedExposure":["api","mcp"],"schema":{"tableName":"chat_threads","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_threads\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"room_id\\" UUID NOT NULL,\\n \\"root_message_id\\" UUID,\\n \\"title\\" TEXT DEFAULT '',\\n \\"is_resolved\\" BOOLEAN DEFAULT FALSE,\\n \\"message_count\\" INTEGER DEFAULT 0,\\n \\"last_message_at\\" TIMESTAMP,\\n \\"participant_count\\" INTEGER DEFAULT 0\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"root_message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"title":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_resolved":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"message_count":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"last_message_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"participant_count":{"type":"INTEGER","notNull":false,"unique":false,"default":0}},"indexes":[{"name":"chat_threads_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_threads_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_threads_room_id_idx","columns":["room_id"]},{"name":"chat_threads_root_message_id_idx","columns":["root_message_id"]}],"version":"a24026da"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:VoiceGatewayTurnCollection":{"name":"voicegatewayturncollection","className":"VoiceGatewayTurnCollection","qualifiedName":"@happyvertical/smrt-chat:VoiceGatewayTurnCollection","collection":"voicegatewayturns","filePath":"src/collections/VoiceGatewayTurnCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"reserveTurn":{"name":"reserveTurn","async":true,"parameters":[{"name":"input","type":"object","optional":false,"memberTypes":["string"]}],"returnType":"Promise<VoiceGatewayTurn>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"voice_gateway_turns","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"VoiceGatewayTurn","exportName":"VoiceGatewayTurnCollection","collectionExportName":"VoiceGatewayTurnCollectionCollection","collectionOf":"@happyvertical/smrt-chat:VoiceGatewayTurn","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"voice_gateway_turns","ddl":"CREATE TABLE IF NOT EXISTS \\"voice_gateway_turns\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"voice_session_id\\" UUID NOT NULL,\\n \\"gateway_session_id\\" TEXT DEFAULT '',\\n \\"gateway_turn_id\\" TEXT NOT NULL DEFAULT '',\\n \\"target\\" TEXT NOT NULL DEFAULT 'smrt:chat',\\n \\"status\\" TEXT NOT NULL DEFAULT 'processing',\\n \\"completed_at\\" TIMESTAMP,\\n \\"failed_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"voice_session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"voice_sessions","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"gateway_session_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"gateway_turn_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"target":{"type":"TEXT","notNull":true,"unique":false,"default":"smrt:chat"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"processing"},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"failed_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"voice_gateway_turns_voice_session_id_gateway_turn_id_idx","columns":["voice_session_id","gateway_turn_id"],"unique":true},{"name":"voice_gateway_turns_slug_context_idx","columns":["slug","context"]},{"name":"voice_gateway_turns_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"c27610cd"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:VoiceSessionCollection":{"name":"voicesessioncollection","className":"VoiceSessionCollection","qualifiedName":"@happyvertical/smrt-chat:VoiceSessionCollection","collection":"voicesessions","filePath":"src/collections/VoiceSessionCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"getActiveById":{"name":"getActiveById","async":true,"parameters":[{"name":"id","type":"string","optional":false},{"name":"target","type":"any","optional":true,"default":"smrt:chat"}],"returnType":"Promise<VoiceSession | null>","isStatic":false,"isPublic":true},"expireStale":{"name":"expireStale","async":true,"parameters":[{"name":"olderThan","type":"Date","optional":true},{"name":"scope","type":"object","optional":true,"memberTypes":["string"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"voice_sessions","api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"VoiceSession","exportName":"VoiceSessionCollection","collectionExportName":"VoiceSessionCollectionCollection","collectionOf":"@happyvertical/smrt-chat:VoiceSession","inheritedExposure":["api","mcp"],"schema":{"tableName":"voice_sessions","ddl":"CREATE TABLE IF NOT EXISTS \\"voice_sessions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"gateway_session_id\\" TEXT NOT NULL DEFAULT '',\\n \\"actor_profile_id\\" UUID NOT NULL,\\n \\"actor_user_id\\" UUID,\\n \\"persona_id\\" UUID NOT NULL,\\n \\"agent_session_id\\" UUID NOT NULL,\\n \\"chat_room_id\\" UUID NOT NULL,\\n \\"thread_id\\" UUID,\\n \\"target\\" TEXT NOT NULL DEFAULT 'smrt:chat',\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"expires_at\\" TIMESTAMP NOT NULL,\\n \\"last_turn_at\\" TIMESTAMP,\\n \\"last_gateway_turn_id\\" TEXT,\\n \\"persona_snapshot\\" TEXT DEFAULT '{}',\\n \\"metadata\\" TEXT DEFAULT '{}',\\n \\"processed_turn_ids\\" TEXT DEFAULT '[]'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"gateway_session_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"actor_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"actor_user_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"persona_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"agent_session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"agent_sessions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"chat_room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"thread_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_threads","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"target":{"type":"TEXT","notNull":true,"unique":false,"default":"smrt:chat"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"expires_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"last_turn_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_gateway_turn_id":{"type":"TEXT","notNull":false,"unique":false},"persona_snapshot":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"processed_turn_ids":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"}},"indexes":[{"name":"voice_sessions_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"voice_sessions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"voice_sessions_actor_profile_id_idx","columns":["actor_profile_id"]},{"name":"voice_sessions_actor_user_id_idx","columns":["actor_user_id"]},{"name":"voice_sessions_persona_id_idx","columns":["persona_id"]},{"name":"voice_sessions_agent_session_id_idx","columns":["agent_session_id"]},{"name":"voice_sessions_chat_room_id_idx","columns":["chat_room_id"]},{"name":"voice_sessions_thread_id_idx","columns":["thread_id"]}],"version":"848752a1"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:AgentSession":{"name":"agentsession","className":"AgentSession","qualifiedName":"@happyvertical/smrt-chat:AgentSession","collection":"agentsessions","description":"Agent conversation session.","filePath":"src/models/AgentSession.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","nullable","__tenancy","required"],"sqlType":"UUID","nullable":true,"required":false},"required":false},"agentId":{"type":"text","_meta":{"__statedOptions":["required","requiredFor","default"],"required":true,"requiredFor":"identity"},"required":true,"default":""},"agentProfileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["related"]},"required":false,"related":"@happyvertical/smrt-profiles:Profile"},"participantProfileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["required","requiredFor","related"],"required":true,"requiredFor":"identity"},"required":true,"related":"@happyvertical/smrt-profiles:Profile"},"chatRoomId":{"type":"foreignKey","_meta":{"__statedOptions":["related"]},"required":false,"related":"ChatRoom"},"status":{"type":"text","_meta":{"__statedOptions":["required","default","enum"],"required":true},"required":true,"default":"active","enum":["active","closed","expired"]},"allowedTools":{"type":"text","_meta":{"__statedOptions":["default"]},"required":false,"default":"[]"},"sessionContext":{"type":"text","_meta":{"__statedOptions":["sensitive","default"],"sensitive":true},"required":false,"default":"{}","sensitive":true},"systemPrompt":{"type":"text","_meta":{"__statedOptions":["default"]},"required":false,"default":""},"messageCount":{"type":"integer","_meta":{"__statedOptions":["default"]},"required":false,"default":0},"totalTokensUsed":{"type":"integer","_meta":{"__statedOptions":["default"]},"required":false,"default":0},"maxTokens":{"type":"integer","_meta":{"__statedOptions":["default"]},"required":false,"default":0},"maxMessages":{"type":"integer","_meta":{"__statedOptions":["default"]},"required":false,"default":0},"lastMessageAt":{"type":"datetime","_meta":{"__statedOptions":[]},"required":false},"expiresAt":{"type":"datetime","_meta":{"__statedOptions":[]},"required":false},"closedAt":{"type":"datetime","_meta":{"__statedOptions":[]},"required":false}},"methods":{"getAllowedTools":{"name":"getAllowedTools","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"setAllowedTools":{"name":"setAllowedTools","async":false,"parameters":[{"name":"tools","type":"string[]","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"isToolAllowed":{"name":"isToolAllowed","async":false,"parameters":[{"name":"toolName","type":"string","optional":false}],"returnType":"boolean","isStatic":false,"isPublic":true},"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isExpired":{"name":"isExpired","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"close":{"name":"close","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"expire":{"name":"expire","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"getSessionContext":{"name":"getSessionContext","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true},"setSessionContext":{"name":"setSessionContext","async":false,"parameters":[{"name":"ctx","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getSessionKey":{"name":"getSessionKey","async":false,"parameters":[],"returnType":"string | null","isStatic":false,"isPublic":true},"updateSessionContext":{"name":"updateSessionContext","async":true,"parameters":[{"name":"updates","type":"Record<string, unknown>","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"recordMessage":{"name":"recordMessage","async":true,"parameters":[{"name":"tokensUsed","type":"number","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"agent_sessions","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"AgentSession","collectionExportName":"AgentSessionCollection","validationRules":[{"field":"agentId","rule":"required","fieldType":"text"},{"field":"participantProfileId","rule":"required","fieldType":"crossPackageRef"},{"field":"status","rule":"required","fieldType":"text"}],"schema":{"tableName":"agent_sessions","ddl":"CREATE TABLE IF NOT EXISTS \\"agent_sessions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"agent_id\\" TEXT NOT NULL DEFAULT '',\\n \\"agent_profile_id\\" UUID,\\n \\"participant_profile_id\\" UUID NOT NULL,\\n \\"chat_room_id\\" UUID,\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"allowed_tools\\" TEXT DEFAULT '[]',\\n \\"session_context\\" TEXT DEFAULT '{}',\\n \\"system_prompt\\" TEXT DEFAULT '',\\n \\"message_count\\" INTEGER DEFAULT 0,\\n \\"total_tokens_used\\" INTEGER DEFAULT 0,\\n \\"max_tokens\\" INTEGER DEFAULT 0,\\n \\"max_messages\\" INTEGER DEFAULT 0,\\n \\"last_message_at\\" TIMESTAMP,\\n \\"expires_at\\" TIMESTAMP,\\n \\"closed_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"agent_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"agent_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"participant_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"chat_room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"allowed_tools":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"session_context":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"system_prompt":{"type":"TEXT","notNull":false,"unique":false,"default":""},"message_count":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"total_tokens_used":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"max_tokens":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"max_messages":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"last_message_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"closed_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"agent_sessions_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"agent_sessions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"agent_sessions_agent_profile_id_idx","columns":["agent_profile_id"]},{"name":"agent_sessions_participant_profile_id_idx","columns":["participant_profile_id"]},{"name":"agent_sessions_chat_room_id_idx","columns":["chat_room_id"]}],"version":"0a330023"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatMessage":{"name":"chatmessage","className":"ChatMessage","qualifiedName":"@happyvertical/smrt-chat:ChatMessage","collection":"chatmessages","description":"Chat message. Internal model \u2014 all mutations must go through the membership-checked ChatService (S5 #1392).","filePath":"src/models/ChatMessage.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"roomId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The room in which this message was sent.","requiredFor":"identity"},"required":true,"related":"ChatRoom","description":"The room in which this message was sent."},"threadId":{"type":"foreignKey","_meta":{"__statedOptions":["description","related"],"description":"The discussion thread containing this message, when there is one."},"required":false,"related":"ChatThread","description":"The discussion thread containing this message, when there is one."},"senderProfileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The person or assistant who sent this message.","requiredFor":"identity"},"required":true,"related":"@happyvertical/smrt-profiles:Profile","description":"The person or assistant who sent this message."},"agentSessionId":{"type":"foreignKey","_meta":{"__statedOptions":["description","related"],"description":"The assistant conversation associated with this message, when applicable."},"required":false,"related":"AgentSession","description":"The assistant conversation associated with this message, when applicable."},"content":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"The text of the message shared with the conversation."},"required":false,"default":"","description":"The text of the message shared with the conversation."},"messageType":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"The kind of message, such as text, a file, or an activity notice."},"required":true,"default":"text","description":"The kind of message, such as text, a file, or an activity notice.","enum":["text","system","action","file","tool_call","tool_result"]},"role":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"Whether this message comes from a person, an assistant, or an automated action."},"required":true,"default":"user","description":"Whether this message comes from a person, an assistant, or an automated action.","enum":["user","assistant","system","tool"]},"isEdited":{"type":"boolean","_meta":{"__statedOptions":["description","default"],"description":"Whether the message has changed since it was sent."},"required":false,"default":false,"description":"Whether the message has changed since it was sent."},"editedAt":{"type":"datetime","_meta":{"__statedOptions":["description"],"description":"When the message was most recently edited."},"required":false,"description":"When the message was most recently edited."},"isDeleted":{"type":"boolean","_meta":{"__statedOptions":["description","default"],"description":"Whether this message has been removed from the conversation."},"required":false,"default":false,"description":"Whether this message has been removed from the conversation."},"replyToMessageId":{"type":"foreignKey","_meta":{"__statedOptions":["description","related"],"description":"The earlier message this reply responds to."},"required":false,"related":"ChatMessage","description":"The earlier message this reply responds to."},"metadata":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"Additional message details maintained by the application."},"required":false,"default":"{}","description":"Additional message details maintained by the application."},"toolCallData":{"type":"text","_meta":{"__statedOptions":["description"],"description":"Details of an automated action associated with this message."},"required":false,"description":"Details of an automated action associated with this message."},"attachments":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"Files shared alongside the text of this message."},"required":false,"default":"[]","description":"Files shared alongside the text of this message."}},"methods":{"getAttachments":{"name":"getAttachments","async":false,"parameters":[],"returnType":"Array<object>","isStatic":false,"isPublic":true},"setAttachments":{"name":"setAttachments","async":false,"parameters":[{"name":"items","type":"Array<object>","optional":false,"memberTypes":["string","number"]}],"returnType":"void","isStatic":false,"isPublic":true},"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"data","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getToolCallData":{"name":"getToolCallData","async":false,"parameters":[],"returnType":"Record<string, unknown> | null","isStatic":false,"isPublic":true},"setToolCallData":{"name":"setToolCallData","async":false,"parameters":[{"name":"data","type":"Record<string, unknown> | null","optional":false,"unionBranches":[{"type":"Record<string, unknown>"},{"type":"null"}]}],"returnType":"void","isStatic":false,"isPublic":true},"hasAttachments":{"name":"hasAttachments","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isToolCall":{"name":"isToolCall","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isToolResult":{"name":"isToolResult","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isFromAgent":{"name":"isFromAgent","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isSystemMessage":{"name":"isSystemMessage","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"edit":{"name":"edit","async":true,"parameters":[{"name":"newContent","type":"string","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"softDelete":{"name":"softDelete","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"getPreview":{"name":"getPreview","async":false,"parameters":[{"name":"maxLength","type":"any","optional":true}],"returnType":"string","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_messages","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"ChatMessage","collectionExportName":"ChatMessageCollection","validationRules":[{"field":"roomId","rule":"required","fieldType":"foreignKey"},{"field":"senderProfileId","rule":"required","fieldType":"crossPackageRef"},{"field":"messageType","rule":"required","fieldType":"text"},{"field":"role","rule":"required","fieldType":"text"}],"schema":{"tableName":"chat_messages","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_messages\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"room_id\\" UUID NOT NULL,\\n \\"thread_id\\" UUID,\\n \\"sender_profile_id\\" UUID NOT NULL,\\n \\"agent_session_id\\" UUID,\\n \\"content\\" TEXT DEFAULT '',\\n \\"message_type\\" TEXT NOT NULL DEFAULT 'text',\\n \\"role\\" TEXT NOT NULL DEFAULT 'user',\\n \\"is_edited\\" BOOLEAN DEFAULT FALSE,\\n \\"edited_at\\" TIMESTAMP,\\n \\"is_deleted\\" BOOLEAN DEFAULT FALSE,\\n \\"reply_to_message_id\\" UUID,\\n \\"metadata\\" TEXT DEFAULT '{}',\\n \\"tool_call_data\\" TEXT,\\n \\"attachments\\" TEXT DEFAULT '[]'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"thread_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_threads","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"sender_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"agent_session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"agent_sessions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"content":{"type":"TEXT","notNull":false,"unique":false,"default":""},"message_type":{"type":"TEXT","notNull":true,"unique":false,"default":"text"},"role":{"type":"TEXT","notNull":true,"unique":false,"default":"user"},"is_edited":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"edited_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"is_deleted":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"reply_to_message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"tool_call_data":{"type":"TEXT","notNull":false,"unique":false},"attachments":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"}},"indexes":[{"name":"chat_messages_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_messages_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_messages_room_id_idx","columns":["room_id"]},{"name":"chat_messages_thread_id_idx","columns":["thread_id"]},{"name":"chat_messages_sender_profile_id_idx","columns":["sender_profile_id"]},{"name":"chat_messages_agent_session_id_idx","columns":["agent_session_id"]},{"name":"chat_messages_reply_to_message_id_idx","columns":["reply_to_message_id"]}],"version":"83f829da"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatParticipant":{"name":"chatparticipant","className":"ChatParticipant","qualifiedName":"@happyvertical/smrt-chat:ChatParticipant","collection":"chatparticipants","description":"Room membership row. Internal model \u2014 membership must be established and mutated only through the membership/owner-checked ChatService (S5 #1392).","filePath":"src/models/ChatParticipant.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"roomId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The room to which this membership belongs.","requiredFor":"identity"},"required":true,"related":"ChatRoom","description":"The room to which this membership belongs."},"profileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The person or assistant participating in the room.","requiredFor":"identity"},"required":true,"related":"@happyvertical/smrt-profiles:Profile","description":"The person or assistant participating in the room."},"role":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"The member role that determines what they can do in the room."},"required":true,"default":"member","description":"The member role that determines what they can do in the room.","enum":["owner","admin","member","viewer"]},"status":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"Whether this member is active, has left, was removed, or is banned."},"required":true,"default":"active","description":"Whether this member is active, has left, was removed, or is banned.","enum":["active","left","kicked","banned"]},"onlineStatus":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"The availability shown for this member, such as online or away."},"required":true,"default":"offline","description":"The availability shown for this member, such as online or away.","enum":["online","away","dnd","offline"]},"lastReadMessageId":{"type":"foreignKey","_meta":{"__statedOptions":["description","related"],"description":"The most recent message this member has read."},"required":false,"related":"ChatMessage","description":"The most recent message this member has read."},"lastSeenAt":{"type":"datetime","_meta":{"__statedOptions":["description"],"description":"When this member was last seen in the conversation."},"required":false,"description":"When this member was last seen in the conversation."},"joinedAt":{"type":"datetime","_meta":{"__statedOptions":["description"],"description":"When this member joined the room."},"required":false,"description":"When this member joined the room."},"nickname":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"The display name this member uses within the room."},"required":false,"default":"","description":"The display name this member uses within the room."},"isMuted":{"type":"boolean","_meta":{"__statedOptions":["description","default"],"description":"Whether notifications for this room are muted for this member."},"required":false,"default":false,"description":"Whether notifications for this room are muted for this member."},"isPinned":{"type":"boolean","_meta":{"__statedOptions":["description","default"],"description":"Whether this room is pinned for this member."},"required":false,"default":false,"description":"Whether this room is pinned for this member."}},"methods":{"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isOwner":{"name":"isOwner","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isAdmin":{"name":"isAdmin","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"markRead":{"name":"markRead","async":true,"parameters":[{"name":"messageId","type":"string","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"leave":{"name":"leave","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"setOnline":{"name":"setOnline","async":true,"parameters":[{"name":"status","type":"OnlineStatus","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_participants","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"ChatParticipant","collectionExportName":"ChatParticipantCollection","validationRules":[{"field":"roomId","rule":"required","fieldType":"foreignKey"},{"field":"profileId","rule":"required","fieldType":"crossPackageRef"},{"field":"role","rule":"required","fieldType":"text"},{"field":"status","rule":"required","fieldType":"text"},{"field":"onlineStatus","rule":"required","fieldType":"text"}],"schema":{"tableName":"chat_participants","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_participants\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"room_id\\" UUID NOT NULL,\\n \\"profile_id\\" UUID NOT NULL,\\n \\"role\\" TEXT NOT NULL DEFAULT 'member',\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"online_status\\" TEXT NOT NULL DEFAULT 'offline',\\n \\"last_read_message_id\\" UUID,\\n \\"last_seen_at\\" TIMESTAMP,\\n \\"joined_at\\" TIMESTAMP,\\n \\"nickname\\" TEXT DEFAULT '',\\n \\"is_muted\\" BOOLEAN DEFAULT FALSE,\\n \\"is_pinned\\" BOOLEAN DEFAULT FALSE\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"role":{"type":"TEXT","notNull":true,"unique":false,"default":"member"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"online_status":{"type":"TEXT","notNull":true,"unique":false,"default":"offline"},"last_read_message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"last_seen_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"joined_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"nickname":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_muted":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"is_pinned":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false}},"indexes":[{"name":"chat_participants_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_participants_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_participants_room_id_idx","columns":["room_id"]},{"name":"chat_participants_profile_id_idx","columns":["profile_id"]},{"name":"chat_participants_last_read_message_id_idx","columns":["last_read_message_id"]}],"version":"166a9740"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatReaction":{"name":"chatreaction","className":"ChatReaction","qualifiedName":"@happyvertical/smrt-chat:ChatReaction","collection":"chatreactions","description":"Message reaction. Internal model \u2014 reactions must be added/removed only through the membership-checked ChatService (S5 #1392).","filePath":"src/models/ChatReaction.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"messageId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The message to which this reaction was added.","requiredFor":"identity"},"required":true,"related":"ChatMessage","description":"The message to which this reaction was added."},"profileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The person who added this reaction.","requiredFor":"identity"},"required":true,"related":"@happyvertical/smrt-profiles:Profile","description":"The person who added this reaction."},"emoji":{"type":"text","_meta":{"__statedOptions":["required","requiredFor","description","default"],"required":true,"description":"The symbol chosen to express a response to the message.","requiredFor":"identity"},"required":true,"default":"","description":"The symbol chosen to express a response to the message."}},"methods":{},"decoratorConfig":{"tableName":"chat_reactions","api":{"include":["list"]},"mcp":{"include":["list"]},"cli":false,"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"ChatReaction","collectionExportName":"ChatReactionCollection","validationRules":[{"field":"messageId","rule":"required","fieldType":"foreignKey"},{"field":"profileId","rule":"required","fieldType":"crossPackageRef"},{"field":"emoji","rule":"required","fieldType":"text"}],"schema":{"tableName":"chat_reactions","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_reactions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"message_id\\" UUID NOT NULL,\\n \\"profile_id\\" UUID NOT NULL,\\n \\"emoji\\" TEXT NOT NULL DEFAULT ''\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"emoji":{"type":"TEXT","notNull":true,"unique":false,"default":""}},"indexes":[{"name":"chat_reactions_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_reactions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_reactions_message_id_idx","columns":["message_id"]},{"name":"chat_reactions_profile_id_idx","columns":["profile_id"]}],"version":"635cdbec"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatRoom":{"name":"chatroom","className":"ChatRoom","qualifiedName":"@happyvertical/smrt-chat:ChatRoom","collection":"chatrooms","description":"Chat room supporting public channels, private groups, DMs, and agent conversations.","filePath":"src/models/ChatRoom.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"name":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"A recognizable name that helps teammates find this room."},"required":false,"default":"","description":"A recognizable name that helps teammates find this room."},"description":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"Explain the purpose of the room and who should join."},"required":false,"default":"","description":"Explain the purpose of the room and who should join."},"roomType":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"Whether the room is public, private, a direct message, or an assistant conversation."},"required":true,"default":"public","description":"Whether the room is public, private, a direct message, or an assistant conversation.","enum":["public","private","dm","agent"]},"status":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"Whether this room is active, archived, or deleted."},"required":true,"default":"active","description":"Whether this room is active, archived, or deleted.","enum":["active","archived","deleted"]},"topic":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"The current subject or focus of the room."},"required":false,"default":"","description":"The current subject or focus of the room."},"avatarUrl":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"The address of the image used to represent this room."},"required":false,"default":"","description":"The address of the image used to represent this room."},"isArchived":{"type":"boolean","_meta":{"__statedOptions":["description","default"],"description":"Whether the room has been archived from active conversations."},"required":false,"default":false,"description":"Whether the room has been archived from active conversations."},"maxParticipants":{"type":"integer","_meta":{"__statedOptions":["description","default"],"description":"The maximum number of members; zero means no configured limit."},"required":false,"default":0,"description":"The maximum number of members; zero means no configured limit."},"metadata":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"Additional room details maintained by the application."},"required":false,"default":"{}","description":"Additional room details maintained by the application."},"createdByProfileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["description","related"],"description":"The person who originally created this room."},"required":false,"related":"@happyvertical/smrt-profiles:Profile","description":"The person who originally created this room."},"lastMessageAt":{"type":"datetime","_meta":{"__statedOptions":["description"],"description":"When the most recent message was sent in this room."},"required":false,"description":"When the most recent message was sent in this room."}},"methods":{"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"ChatRoomMetadata","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"data","type":"ChatRoomMetadata","optional":false,"resolvedType":"Record<string, unknown>"}],"returnType":"void","isStatic":false,"isPublic":true},"updateMetadata":{"name":"updateMetadata","async":false,"parameters":[{"name":"updates","type":"ChatRoomMetadata","optional":false,"resolvedType":"Record<string, unknown>"}],"returnType":"void","isStatic":false,"isPublic":true},"isDM":{"name":"isDM","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isAgentRoom":{"name":"isAgentRoom","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isPublic":{"name":"isPublic","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"archive":{"name":"archive","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"unarchive":{"name":"unarchive","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_rooms","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"ChatRoom","collectionExportName":"ChatRoomCollection","displayLabelField":"name","validationRules":[{"field":"roomType","rule":"required","fieldType":"text"},{"field":"status","rule":"required","fieldType":"text"}],"schema":{"tableName":"chat_rooms","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_rooms\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT '',\\n \\"room_type\\" TEXT NOT NULL DEFAULT 'public',\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"topic\\" TEXT DEFAULT '',\\n \\"avatar_url\\" TEXT DEFAULT '',\\n \\"is_archived\\" BOOLEAN DEFAULT FALSE,\\n \\"max_participants\\" INTEGER DEFAULT 0,\\n \\"metadata\\" TEXT DEFAULT '{}',\\n \\"created_by_profile_id\\" UUID,\\n \\"last_message_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"room_type":{"type":"TEXT","notNull":true,"unique":false,"default":"public"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"topic":{"type":"TEXT","notNull":false,"unique":false,"default":""},"avatar_url":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_archived":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"max_participants":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"created_by_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"last_message_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"chat_rooms_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_rooms_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_rooms_created_by_profile_id_idx","columns":["created_by_profile_id"]}],"version":"8093a86b"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatThread":{"name":"chatthread","className":"ChatThread","qualifiedName":"@happyvertical/smrt-chat:ChatThread","collection":"chatthreads","description":"Conversation thread. Internal model \u2014 threads must be created/mutated only through the membership-checked ChatService (S5 #1392).","filePath":"src/models/ChatThread.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"roomId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The room containing this discussion thread.","requiredFor":"identity"},"required":true,"related":"ChatRoom","description":"The room containing this discussion thread."},"rootMessageId":{"type":"foreignKey","_meta":{"__statedOptions":["nullable","description","related","required"],"description":"The message that started this thread, when it began as a reply.","nullable":true,"required":false},"required":false,"related":"ChatMessage","description":"The message that started this thread, when it began as a reply."},"title":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"A short title describing the subject of this thread."},"required":false,"default":"","description":"A short title describing the subject of this thread."},"isResolved":{"type":"boolean","_meta":{"__statedOptions":["description","default"],"description":"Whether the discussion has reached a resolution."},"required":false,"default":false,"description":"Whether the discussion has reached a resolution."},"messageCount":{"type":"integer","_meta":{"__statedOptions":["description","default"],"description":"The number of messages in this thread."},"required":false,"default":0,"description":"The number of messages in this thread."},"lastMessageAt":{"type":"datetime","_meta":{"__statedOptions":["description"],"description":"When the most recent message was sent in this thread."},"required":false,"description":"When the most recent message was sent in this thread."},"participantCount":{"type":"integer","_meta":{"__statedOptions":["description","default"],"description":"The number of people participating in this thread."},"required":false,"default":0,"description":"The number of people participating in this thread."}},"methods":{"resolve":{"name":"resolve","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"reopen":{"name":"reopen","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_threads","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"ChatThread","collectionExportName":"ChatThreadCollection","displayLabelField":"title","validationRules":[{"field":"roomId","rule":"required","fieldType":"foreignKey"}],"schema":{"tableName":"chat_threads","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_threads\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"room_id\\" UUID NOT NULL,\\n \\"root_message_id\\" UUID,\\n \\"title\\" TEXT DEFAULT '',\\n \\"is_resolved\\" BOOLEAN DEFAULT FALSE,\\n \\"message_count\\" INTEGER DEFAULT 0,\\n \\"last_message_at\\" TIMESTAMP,\\n \\"participant_count\\" INTEGER DEFAULT 0\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"root_message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"title":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_resolved":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"message_count":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"last_message_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"participant_count":{"type":"INTEGER","notNull":false,"unique":false,"default":0}},"indexes":[{"name":"chat_threads_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_threads_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_threads_room_id_idx","columns":["room_id"]},{"name":"chat_threads_root_message_id_idx","columns":["root_message_id"]}],"version":"a24026da"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:VoiceGatewayTurn":{"name":"voicegatewayturn","className":"VoiceGatewayTurn","qualifiedName":"@happyvertical/smrt-chat:VoiceGatewayTurn","collection":"voicegatewayturns","description":"Durable reservation for a gateway turn. The natural key makes turn_id replay checks concurrency-safe before transcript messages are written.","filePath":"src/models/VoiceGatewayTurn.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"voiceSessionId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","related"],"required":true,"requiredFor":"idempotency"},"required":true,"related":"VoiceSession"},"gatewaySessionId":{"type":"text","_meta":{"__statedOptions":["default"]},"required":false,"default":""},"gatewayTurnId":{"type":"text","_meta":{"__statedOptions":["required","requiredFor","default"],"required":true,"requiredFor":"idempotency"},"required":true,"default":""},"target":{"type":"text","_meta":{"__statedOptions":["required","default"],"required":true},"required":true,"default":"smrt:chat"},"status":{"type":"text","_meta":{"__statedOptions":["required","default","enum"],"required":true},"required":true,"default":"processing","enum":["processing","completed","failed"]},"completedAt":{"type":"datetime","_meta":{"__statedOptions":[]},"required":false},"failedAt":{"type":"datetime","_meta":{"__statedOptions":[]},"required":false}},"methods":{"complete":{"name":"complete","async":true,"parameters":[{"name":"now","type":"Date","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"fail":{"name":"fail","async":true,"parameters":[{"name":"now","type":"Date","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"voice_gateway_turns","conflictColumns":["voice_session_id","gateway_turn_id"],"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":false,"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"VoiceGatewayTurn","collectionExportName":"VoiceGatewayTurnCollection","validationRules":[{"field":"voiceSessionId","rule":"required","fieldType":"foreignKey"},{"field":"gatewayTurnId","rule":"required","fieldType":"text"},{"field":"target","rule":"required","fieldType":"text"},{"field":"status","rule":"required","fieldType":"text"}],"schema":{"tableName":"voice_gateway_turns","ddl":"CREATE TABLE IF NOT EXISTS \\"voice_gateway_turns\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"voice_session_id\\" UUID NOT NULL,\\n \\"gateway_session_id\\" TEXT DEFAULT '',\\n \\"gateway_turn_id\\" TEXT NOT NULL DEFAULT '',\\n \\"target\\" TEXT NOT NULL DEFAULT 'smrt:chat',\\n \\"status\\" TEXT NOT NULL DEFAULT 'processing',\\n \\"completed_at\\" TIMESTAMP,\\n \\"failed_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"voice_session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"voice_sessions","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"gateway_session_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"gateway_turn_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"target":{"type":"TEXT","notNull":true,"unique":false,"default":"smrt:chat"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"processing"},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"failed_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"voice_gateway_turns_voice_session_id_gateway_turn_id_idx","columns":["voice_session_id","gateway_turn_id"],"unique":true},{"name":"voice_gateway_turns_slug_context_idx","columns":["slug","context"]},{"name":"voice_gateway_turns_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"c27610cd"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:VoiceSession":{"name":"voicesession","className":"VoiceSession","qualifiedName":"@happyvertical/smrt-chat:VoiceSession","collection":"voicesessions","description":"Short-lived binding proving a voice gateway turn belongs to an authenticated SMRT actor, persona, and chat session.","filePath":"src/models/VoiceSession.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"gatewaySessionId":{"type":"text","_meta":{"__statedOptions":["required","requiredFor","default"],"required":true,"requiredFor":"identity"},"required":true,"default":""},"actorProfileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["required","requiredFor","related"],"required":true,"requiredFor":"identity"},"required":true,"related":"@happyvertical/smrt-profiles:Profile"},"actorUserId":{"type":"crossPackageRef","_meta":{"__statedOptions":["nullable","related","required"],"nullable":true,"required":false},"required":false,"related":"@happyvertical/smrt-users:User"},"personaId":{"type":"crossPackageRef","_meta":{"__statedOptions":["required","requiredFor","related"],"required":true,"requiredFor":"identity"},"required":true,"related":"@happyvertical/smrt-personas:AgentPersona"},"agentSessionId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","related"],"required":true,"requiredFor":"identity"},"required":true,"related":"AgentSession"},"chatRoomId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","related"],"required":true,"requiredFor":"identity"},"required":true,"related":"ChatRoom"},"threadId":{"type":"foreignKey","_meta":{"__statedOptions":["related"]},"required":false,"related":"ChatThread"},"target":{"type":"text","_meta":{"__statedOptions":["required","default"],"required":true},"required":true,"default":"smrt:chat"},"status":{"type":"text","_meta":{"__statedOptions":["required","default","enum"],"required":true},"required":true,"default":"active","enum":["active","expired","revoked"]},"expiresAt":{"type":"datetime","_meta":{"__statedOptions":["required"],"required":true},"required":true},"lastTurnAt":{"type":"datetime","_meta":{"__statedOptions":[]},"required":false},"lastGatewayTurnId":{"type":"text","_meta":{"__statedOptions":[]},"required":false},"personaSnapshot":{"type":"text","_meta":{"__statedOptions":["default"]},"required":false,"default":"{}"},"metadata":{"type":"text","_meta":{"__statedOptions":["default"]},"required":false,"default":"{}"},"processedTurnIds":{"type":"text","_meta":{"__statedOptions":["default"]},"required":false,"default":"[]"}},"methods":{"isActive":{"name":"isActive","async":false,"parameters":[{"name":"now","type":"Date","optional":true}],"returnType":"boolean","isStatic":false,"isPublic":true},"isExpired":{"name":"isExpired","async":false,"parameters":[{"name":"now","type":"Date","optional":true}],"returnType":"boolean","isStatic":false,"isPublic":true},"expire":{"name":"expire","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"revoke":{"name":"revoke","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"getPersonaSnapshot":{"name":"getPersonaSnapshot","async":false,"parameters":[],"returnType":"ConversationPersona","isStatic":false,"isPublic":true},"setPersonaSnapshot":{"name":"setPersonaSnapshot","async":false,"parameters":[{"name":"persona","type":"ConversationPersona","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"metadata","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getProcessedTurnIds":{"name":"getProcessedTurnIds","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"hasProcessedTurn":{"name":"hasProcessedTurn","async":false,"parameters":[{"name":"turnId","type":"string","optional":false}],"returnType":"boolean","isStatic":false,"isPublic":true},"recordGatewayTurn":{"name":"recordGatewayTurn","async":false,"parameters":[{"name":"turnId","type":"string","optional":false},{"name":"maxRememberedTurns","type":"any","optional":true}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"voice_sessions","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"VoiceSession","collectionExportName":"VoiceSessionCollection","validationRules":[{"field":"gatewaySessionId","rule":"required","fieldType":"text"},{"field":"actorProfileId","rule":"required","fieldType":"crossPackageRef"},{"field":"personaId","rule":"required","fieldType":"crossPackageRef"},{"field":"agentSessionId","rule":"required","fieldType":"foreignKey"},{"field":"chatRoomId","rule":"required","fieldType":"foreignKey"},{"field":"target","rule":"required","fieldType":"text"},{"field":"status","rule":"required","fieldType":"text"},{"field":"expiresAt","rule":"required","fieldType":"datetime"}],"schema":{"tableName":"voice_sessions","ddl":"CREATE TABLE IF NOT EXISTS \\"voice_sessions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"gateway_session_id\\" TEXT NOT NULL DEFAULT '',\\n \\"actor_profile_id\\" UUID NOT NULL,\\n \\"actor_user_id\\" UUID,\\n \\"persona_id\\" UUID NOT NULL,\\n \\"agent_session_id\\" UUID NOT NULL,\\n \\"chat_room_id\\" UUID NOT NULL,\\n \\"thread_id\\" UUID,\\n \\"target\\" TEXT NOT NULL DEFAULT 'smrt:chat',\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"expires_at\\" TIMESTAMP NOT NULL,\\n \\"last_turn_at\\" TIMESTAMP,\\n \\"last_gateway_turn_id\\" TEXT,\\n \\"persona_snapshot\\" TEXT DEFAULT '{}',\\n \\"metadata\\" TEXT DEFAULT '{}',\\n \\"processed_turn_ids\\" TEXT DEFAULT '[]'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"gateway_session_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"actor_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"actor_user_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"persona_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"agent_session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"agent_sessions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"chat_room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"thread_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_threads","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"target":{"type":"TEXT","notNull":true,"unique":false,"default":"smrt:chat"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"expires_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"last_turn_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_gateway_turn_id":{"type":"TEXT","notNull":false,"unique":false},"persona_snapshot":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"processed_turn_ids":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"}},"indexes":[{"name":"voice_sessions_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"voice_sessions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"voice_sessions_actor_profile_id_idx","columns":["actor_profile_id"]},{"name":"voice_sessions_actor_user_id_idx","columns":["actor_user_id"]},{"name":"voice_sessions_persona_id_idx","columns":["persona_id"]},{"name":"voice_sessions_agent_session_id_idx","columns":["agent_session_id"]},{"name":"voice_sessions_chat_room_id_idx","columns":["chat_room_id"]},{"name":"voice_sessions_thread_id_idx","columns":["thread_id"]}],"version":"848752a1"},"importPath":"@happyvertical/smrt-chat"}},"moduleType":"smrt","recipes":[{"id":"chat.assistant","className":"AssistantRecipe","label":"Assistant","summary":"Ask an AI assistant about the page you are on, from a dock in the app shell.","synonyms":["ai assistant","ai chat","copilot","chatbot","ask ai","helper"],"models":["@happyvertical/smrt-chat:AgentSession","@happyvertical/smrt-chat:ChatRoom","@happyvertical/smrt-chat:ChatParticipant","@happyvertical/smrt-chat:ChatThread","@happyvertical/smrt-chat:ChatMessage"],"nav":[],"requires":[],"help":{"markdown":"## Overview\\n\\nThe assistant is a chat panel that opens from a button in the app's top bar. It\\nsees the page you are on, so you can ask about what is in front of you and get\\nan answer without leaving it.\\n\\nYou can keep several conversations and come back to them later. The assistant\\nonly reaches the data and actions the app owner allows, and it works with your\\nown permissions: it cannot show you anything you could not open yourself.\\n\\n## Tasks\\n\\n### Ask a question\\n\\n1. Choose the assistant button in the top bar to open the panel.\\n2. Type your question and send it.\\n3. Read the reply as it arrives. Open the panel again from any page to carry on.\\n\\n### Start a new conversation\\n\\n1. Open the panel and choose the conversation list.\\n2. Start a new conversation, or pick an earlier one to carry on.\\n\\n### Approve a change\\n\\nWhen the assistant proposes a change, it shows what will happen and waits.\\n\\n1. Read the proposed change.\\n2. Confirm it to go ahead, or reject it. Nothing changes until you confirm.\\n\\n### Choose a model\\n\\nIf the app offers more than one model, pick one from the list in the panel\\nbefore you send a message.\\n\\n## What the app owner sets up\\n\\n- A model. Hosted models need the service key their provider issues, stored as\\n a secret in the app (\`OPENAI_API_KEY\`, \`ANTHROPIC_API_KEY\` or\\n \`GEMINI_API_KEY\`); only the key for the model the app uses is needed. Models\\n that run in the browser need no key.\\n- The tools the assistant may use. It is offered nothing unless the app lists\\n it, so an empty list means conversation only.\\n- Optionally, report tools. An app can let the assistant draft a report from a\\n request, preview it, and save it only after a person approves that exact\\n report.\\n","fieldRefs":[]},"surfaces":[{"kind":"shell-widget","slot":"header.end","export":"@happyvertical/smrt-chat/svelte#AssistantDock","label":"Assistant","icon":"bot"}],"providers":[{"id":"llm","kind":"llm","options":["openai","anthropic","gemini","webllm","bitgpu"],"required":true,"secrets":["OPENAI_API_KEY","ANTHROPIC_API_KEY","GEMINI_API_KEY"],"browserOptions":["webllm","bitgpu"]}],"runtime":"both","demo":{"mode":"server","reasons":["Needs a server because its package does not build for a browser: node:crypto + node:async_hooks; and its package depends on @happyvertical/smrt-agents, @happyvertical/smrt-images, @happyvertical/smrt-jobs, @happyvertical/smrt-profiles, @happyvertical/smrt-reports, @happyvertical/smrt-secrets, @happyvertical/smrt-tenancy, @happyvertical/smrt-users, which do not build for a browser (#3615, #3617, #3624, #3625, #3626, #3627, #3628).","Provider llm has an in-browser option (webllm, bitgpu)."]}},{"id":"chat.rooms","className":"ChatRoomsRecipe","label":"Team Chat","summary":"Organize team conversations in rooms with threads and reactions.","synonyms":["team chat","channels","group chat","conversations"],"models":["@happyvertical/smrt-chat:ChatRoom","@happyvertical/smrt-chat:ChatMessage","@happyvertical/smrt-chat:ChatParticipant","@happyvertical/smrt-chat:ChatThread","@happyvertical/smrt-chat:ChatReaction"],"nav":[{"label":"Chat rooms","model":"@happyvertical/smrt-chat:ChatRoom","icon":"users","description":"Team conversations organized by topic or audience.","noun":"chat room"}],"requires":[],"group":{"id":"team-collaboration","label":"Team collaboration","summary":"Keep conversations and shared work in one place."},"section":{"id":"team","label":"Team","icon":"users","description":"People and the conversations that keep them aligned."},"options":{"@happyvertical/smrt-chat:ChatRoom":{"fields":{"metadata":{"visibility":"hidden"},"createdByProfileId":{"visibility":"hidden"},"lastMessageAt":{"label":"Last message","order":1}}},"@happyvertical/smrt-chat:ChatMessage":{"fields":{"metadata":{"visibility":"hidden"},"toolCallData":{"visibility":"hidden"},"attachments":{"visibility":"advanced"}}},"@happyvertical/smrt-chat:ChatParticipant":{"fields":{"lastReadMessageId":{"visibility":"hidden"},"lastSeenAt":{"visibility":"advanced"}}}},"help":{"markdown":"## Overview\\n\\nTeam Chat keeps conversations in rooms so people can find the right discussion,\\nfollow threads, and see reactions without mixing unrelated work together. The\\nroom and message lists are read-only generated views. Create rooms, manage\\nmembers, and send messages through the app's authorized chat workflow.\\n\\n## Tasks\\n\\n### Find the right room\\n\\n1. Open **Chat rooms** from the navigation.\\n2. Search for a room by its **{field:ChatRoom.name}**, or use its\\n **{field:ChatRoom.topic}** to tell similar rooms apart.\\n3. Open the room and check **{field:ChatRoom.lastMessageAt}** to see where the\\n most recent discussion happened.\\n\\n### Follow a conversation\\n\\n1. Read the room messages and open a thread when you need the discussion in\\n one place.\\n2. Use the thread **{field:ChatThread.title}** to describe the subject when\\n your app supplies one.\\n3. Add a reaction by choosing the **{field:ChatReaction.emoji}** that best\\n communicates your response.\\n\\n### Keep a room useful\\n\\n1. Give the room a clear **{field:ChatRoom.name}** and a short\\n **{field:ChatRoom.description}**.\\n2. Set **{field:ChatRoom.roomType}** deliberately: public for broad team\\n discussion, private for restricted groups, and direct messages for one-to-one\\n conversations.\\n3. Use a focused **{field:ChatMessage.content}** so teammates can scan the\\n conversation and reply in context.\\n","fieldRefs":["ChatMessage.content","ChatReaction.emoji","ChatRoom.description","ChatRoom.lastMessageAt","ChatRoom.name","ChatRoom.roomType","ChatRoom.topic","ChatThread.title"]},"surfaces":[{"kind":"route","path":"/chat/rooms","export":"@happyvertical/smrt-chat/svelte#ChatLayout","label":"Team chat"}],"runtime":"both","demoSeed":{"export":"@happyvertical/smrt-chat/playground#chatRoomsFixture"},"demo":{"mode":"server","reasons":["Needs a server because its package does not build for a browser: node:crypto + node:async_hooks; and its package depends on @happyvertical/smrt-agents, @happyvertical/smrt-images, @happyvertical/smrt-jobs, @happyvertical/smrt-profiles, @happyvertical/smrt-reports, @happyvertical/smrt-secrets, @happyvertical/smrt-tenancy, @happyvertical/smrt-users, which do not build for a browser (#3615, #3617, #3624, #3625, #3626, #3627, #3628)."]}}],"smrtDependencies":["@happyvertical/smrt-agents","@happyvertical/smrt-app-runtime","@happyvertical/smrt-assets","@happyvertical/smrt-core","@happyvertical/smrt-images","@happyvertical/smrt-inference","@happyvertical/smrt-personas","@happyvertical/smrt-profiles","@happyvertical/smrt-reports","@happyvertical/smrt-tenancy","@happyvertical/smrt-users"],"browser":{"status":"server-only","issues":["#3615","#3617","#3624","#3625","#3626","#3627","#3628"],"reason":"node:crypto + node:async_hooks","via":["@happyvertical/smrt-agents","@happyvertical/smrt-images","@happyvertical/smrt-jobs","@happyvertical/smrt-profiles","@happyvertical/smrt-reports","@happyvertical/smrt-secrets","@happyvertical/smrt-tenancy","@happyvertical/smrt-users"]},"stampsConstructors":true}`));
66
+ ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-chat","packageVersion":"0.62.0","objects":{"@happyvertical/smrt-chat:AgentSessionCollection":{"name":"agentsessioncollection","className":"AgentSessionCollection","qualifiedName":"@happyvertical/smrt-chat:AgentSessionCollection","collection":"agentsessions","filePath":"src/collections/AgentSessionCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"findActiveByParticipant":{"name":"findActiveByParticipant","async":true,"parameters":[{"name":"participantProfileId","type":"string","optional":false}],"returnType":"Promise<AgentSession[]>","isStatic":false,"isPublic":true},"findActiveSession":{"name":"findActiveSession","async":true,"parameters":[{"name":"agentId","type":"string","optional":false},{"name":"participantProfileId","type":"string","optional":false},{"name":"tenantId","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]},{"name":"sessionKey","type":"string | null","optional":true,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<AgentSession | null>","isStatic":false,"isPublic":true},"findOrCreate":{"name":"findOrCreate","async":true,"parameters":[{"name":"params","type":"object","optional":false,"memberTypes":["string","string | null","string[]"]}],"returnType":"Promise<AgentSession>","isStatic":false,"isPublic":true},"findByAgent":{"name":"findByAgent","async":true,"parameters":[{"name":"agentId","type":"string","optional":false}],"returnType":"Promise<AgentSession[]>","isStatic":false,"isPublic":true},"expireStale":{"name":"expireStale","async":true,"parameters":[{"name":"olderThan","type":"Date","optional":false},{"name":"scope","type":"object","optional":true,"memberTypes":["string | null","string"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"agent_sessions","api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"AgentSession","exportName":"AgentSessionCollection","collectionExportName":"AgentSessionCollectionCollection","collectionOf":"@happyvertical/smrt-chat:AgentSession","inheritedExposure":["api","mcp"],"schema":{"tableName":"agent_sessions","ddl":"CREATE TABLE IF NOT EXISTS \\"agent_sessions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"agent_id\\" TEXT NOT NULL DEFAULT '',\\n \\"agent_profile_id\\" UUID,\\n \\"participant_profile_id\\" UUID NOT NULL,\\n \\"chat_room_id\\" UUID,\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"allowed_tools\\" TEXT DEFAULT '[]',\\n \\"session_context\\" TEXT DEFAULT '{}',\\n \\"system_prompt\\" TEXT DEFAULT '',\\n \\"message_count\\" INTEGER DEFAULT 0,\\n \\"total_tokens_used\\" INTEGER DEFAULT 0,\\n \\"max_tokens\\" INTEGER DEFAULT 0,\\n \\"max_messages\\" INTEGER DEFAULT 0,\\n \\"last_message_at\\" TIMESTAMP,\\n \\"expires_at\\" TIMESTAMP,\\n \\"closed_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"agent_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"agent_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"participant_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"chat_room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"allowed_tools":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"session_context":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"system_prompt":{"type":"TEXT","notNull":false,"unique":false,"default":""},"message_count":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"total_tokens_used":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"max_tokens":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"max_messages":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"last_message_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"closed_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"agent_sessions_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"agent_sessions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"agent_sessions_agent_profile_id_idx","columns":["agent_profile_id"]},{"name":"agent_sessions_participant_profile_id_idx","columns":["participant_profile_id"]},{"name":"agent_sessions_chat_room_id_idx","columns":["chat_room_id"]}],"version":"0a330023"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatMessageCollection":{"name":"chatmessagecollection","className":"ChatMessageCollection","qualifiedName":"@happyvertical/smrt-chat:ChatMessageCollection","collection":"chatmessages","filePath":"src/collections/ChatMessageCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"getByRoom":{"name":"getByRoom","async":true,"parameters":[{"name":"roomId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false},{"name":"options","type":"object","optional":true,"typeUnresolved":true,"memberTypes":["number","string"]}],"returnType":"Promise<ChatMessage[]>","isStatic":false,"isPublic":true},"getByThread":{"name":"getByThread","async":true,"parameters":[{"name":"threadId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<ChatMessage[]>","isStatic":false,"isPublic":true},"getByAgentSession":{"name":"getByAgentSession","async":true,"parameters":[{"name":"agentSessionId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<ChatMessage[]>","isStatic":false,"isPublic":true},"search":{"name":"search","async":true,"parameters":[{"name":"filters","type":"any","optional":false,"typeUnresolved":true}],"returnType":"Promise<ChatMessage[]>","isStatic":false,"isPublic":true},"getUnreadCount":{"name":"getUnreadCount","async":true,"parameters":[{"name":"roomId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false},{"name":"lastReadMessageId","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"getLatestPerRoom":{"name":"getLatestPerRoom","async":true,"parameters":[{"name":"roomIds","type":"string[]","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<Map<string, ChatMessage>>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_messages","api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"ChatMessage","exportName":"ChatMessageCollection","collectionExportName":"ChatMessageCollectionCollection","collectionOf":"@happyvertical/smrt-chat:ChatMessage","inheritedExposure":["api","mcp"],"schema":{"tableName":"chat_messages","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_messages\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"room_id\\" UUID NOT NULL,\\n \\"thread_id\\" UUID,\\n \\"sender_profile_id\\" UUID NOT NULL,\\n \\"agent_session_id\\" UUID,\\n \\"content\\" TEXT DEFAULT '',\\n \\"message_type\\" TEXT NOT NULL DEFAULT 'text',\\n \\"role\\" TEXT NOT NULL DEFAULT 'user',\\n \\"is_edited\\" BOOLEAN DEFAULT FALSE,\\n \\"edited_at\\" TIMESTAMP,\\n \\"is_deleted\\" BOOLEAN DEFAULT FALSE,\\n \\"reply_to_message_id\\" UUID,\\n \\"metadata\\" TEXT DEFAULT '{}',\\n \\"tool_call_data\\" TEXT,\\n \\"attachments\\" TEXT DEFAULT '[]'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"thread_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_threads","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"sender_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"agent_session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"agent_sessions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"content":{"type":"TEXT","notNull":false,"unique":false,"default":""},"message_type":{"type":"TEXT","notNull":true,"unique":false,"default":"text"},"role":{"type":"TEXT","notNull":true,"unique":false,"default":"user"},"is_edited":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"edited_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"is_deleted":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"reply_to_message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"tool_call_data":{"type":"TEXT","notNull":false,"unique":false},"attachments":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"}},"indexes":[{"name":"chat_messages_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_messages_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_messages_room_id_idx","columns":["room_id"]},{"name":"chat_messages_thread_id_idx","columns":["thread_id"]},{"name":"chat_messages_sender_profile_id_idx","columns":["sender_profile_id"]},{"name":"chat_messages_agent_session_id_idx","columns":["agent_session_id"]},{"name":"chat_messages_reply_to_message_id_idx","columns":["reply_to_message_id"]}],"version":"83f829da"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatParticipantCollection":{"name":"chatparticipantcollection","className":"ChatParticipantCollection","qualifiedName":"@happyvertical/smrt-chat:ChatParticipantCollection","collection":"chatparticipants","filePath":"src/collections/ChatParticipantCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"getByRoom":{"name":"getByRoom","async":true,"parameters":[{"name":"roomId","type":"string","optional":false}],"returnType":"Promise<ChatParticipant[]>","isStatic":false,"isPublic":true},"getByProfile":{"name":"getByProfile","async":true,"parameters":[{"name":"profileId","type":"string","optional":false}],"returnType":"Promise<ChatParticipant[]>","isStatic":false,"isPublic":true},"findMembership":{"name":"findMembership","async":true,"parameters":[{"name":"roomId","type":"string","optional":false},{"name":"profileId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":true}],"returnType":"Promise<ChatParticipant | null>","isStatic":false,"isPublic":true},"findActiveMembership":{"name":"findActiveMembership","async":true,"parameters":[{"name":"roomId","type":"string","optional":false},{"name":"profileId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<ChatParticipant | null>","isStatic":false,"isPublic":true},"isActiveMember":{"name":"isActiveMember","async":true,"parameters":[{"name":"roomId","type":"string","optional":false},{"name":"profileId","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"getOnlineInRoom":{"name":"getOnlineInRoom","async":true,"parameters":[{"name":"roomId","type":"string","optional":false}],"returnType":"Promise<ChatParticipant[]>","isStatic":false,"isPublic":true},"getAdminsInRoom":{"name":"getAdminsInRoom","async":true,"parameters":[{"name":"roomId","type":"string","optional":false}],"returnType":"Promise<ChatParticipant[]>","isStatic":false,"isPublic":true},"countInRoom":{"name":"countInRoom","async":true,"parameters":[{"name":"roomId","type":"string","optional":false}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_participants","api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"ChatParticipant","exportName":"ChatParticipantCollection","collectionExportName":"ChatParticipantCollectionCollection","collectionOf":"@happyvertical/smrt-chat:ChatParticipant","inheritedExposure":["api","mcp"],"schema":{"tableName":"chat_participants","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_participants\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"room_id\\" UUID NOT NULL,\\n \\"profile_id\\" UUID NOT NULL,\\n \\"role\\" TEXT NOT NULL DEFAULT 'member',\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"online_status\\" TEXT NOT NULL DEFAULT 'offline',\\n \\"last_read_message_id\\" UUID,\\n \\"last_seen_at\\" TIMESTAMP,\\n \\"joined_at\\" TIMESTAMP,\\n \\"nickname\\" TEXT DEFAULT '',\\n \\"is_muted\\" BOOLEAN DEFAULT FALSE,\\n \\"is_pinned\\" BOOLEAN DEFAULT FALSE\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"role":{"type":"TEXT","notNull":true,"unique":false,"default":"member"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"online_status":{"type":"TEXT","notNull":true,"unique":false,"default":"offline"},"last_read_message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"last_seen_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"joined_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"nickname":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_muted":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"is_pinned":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false}},"indexes":[{"name":"chat_participants_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_participants_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_participants_room_id_idx","columns":["room_id"]},{"name":"chat_participants_profile_id_idx","columns":["profile_id"]},{"name":"chat_participants_last_read_message_id_idx","columns":["last_read_message_id"]}],"version":"166a9740"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatReactionCollection":{"name":"chatreactioncollection","className":"ChatReactionCollection","qualifiedName":"@happyvertical/smrt-chat:ChatReactionCollection","collection":"chatreactions","filePath":"src/collections/ChatReactionCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"getByMessage":{"name":"getByMessage","async":true,"parameters":[{"name":"messageId","type":"string","optional":false}],"returnType":"Promise<ChatReaction[]>","isStatic":false,"isPublic":true},"getReactionCounts":{"name":"getReactionCounts","async":true,"parameters":[{"name":"messageId","type":"string","optional":false}],"returnType":"Promise<Map<string, object>>","isStatic":false,"isPublic":true},"toggle":{"name":"toggle","async":true,"parameters":[{"name":"messageId","type":"string","optional":false},{"name":"profileId","type":"string","optional":false},{"name":"emoji","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false}],"returnType":"Promise<object>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_reactions","api":{"include":["list"]},"mcp":{"include":["list"]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"ChatReaction","exportName":"ChatReactionCollection","collectionExportName":"ChatReactionCollectionCollection","collectionOf":"@happyvertical/smrt-chat:ChatReaction","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"chat_reactions","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_reactions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"message_id\\" UUID NOT NULL,\\n \\"profile_id\\" UUID NOT NULL,\\n \\"emoji\\" TEXT NOT NULL DEFAULT ''\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"emoji":{"type":"TEXT","notNull":true,"unique":false,"default":""}},"indexes":[{"name":"chat_reactions_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_reactions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_reactions_message_id_idx","columns":["message_id"]},{"name":"chat_reactions_profile_id_idx","columns":["profile_id"]}],"version":"635cdbec"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatRoomCollection":{"name":"chatroomcollection","className":"ChatRoomCollection","qualifiedName":"@happyvertical/smrt-chat:ChatRoomCollection","collection":"chatrooms","filePath":"src/collections/ChatRoomCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"findByType":{"name":"findByType","async":true,"parameters":[{"name":"roomType","type":"ChatRoomType","optional":false}],"returnType":"Promise<ChatRoom[]>","isStatic":false,"isPublic":true},"findPublic":{"name":"findPublic","async":true,"parameters":[],"returnType":"Promise<ChatRoom[]>","isStatic":false,"isPublic":true},"findDMs":{"name":"findDMs","async":true,"parameters":[],"returnType":"Promise<ChatRoom[]>","isStatic":false,"isPublic":true},"findAgentRooms":{"name":"findAgentRooms","async":true,"parameters":[],"returnType":"Promise<ChatRoom[]>","isStatic":false,"isPublic":true},"search":{"name":"search","async":true,"parameters":[{"name":"query","type":"string","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["number"]}],"returnType":"Promise<ChatRoom[]>","isStatic":false,"isPublic":true},"findOrCreateDM":{"name":"findOrCreateDM","async":true,"parameters":[{"name":"profileId1","type":"string","optional":false},{"name":"profileId2","type":"string","optional":false},{"name":"tenantId","type":"string","optional":false},{"name":"participants","type":"ChatParticipantCollection","optional":false}],"returnType":"Promise<ChatRoom>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_rooms","api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"ChatRoom","exportName":"ChatRoomCollection","collectionExportName":"ChatRoomCollectionCollection","collectionOf":"@happyvertical/smrt-chat:ChatRoom","inheritedExposure":["api","mcp"],"schema":{"tableName":"chat_rooms","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_rooms\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT '',\\n \\"room_type\\" TEXT NOT NULL DEFAULT 'public',\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"topic\\" TEXT DEFAULT '',\\n \\"avatar_url\\" TEXT DEFAULT '',\\n \\"is_archived\\" BOOLEAN DEFAULT FALSE,\\n \\"max_participants\\" INTEGER DEFAULT 0,\\n \\"metadata\\" TEXT DEFAULT '{}',\\n \\"created_by_profile_id\\" UUID,\\n \\"last_message_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"room_type":{"type":"TEXT","notNull":true,"unique":false,"default":"public"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"topic":{"type":"TEXT","notNull":false,"unique":false,"default":""},"avatar_url":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_archived":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"max_participants":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"created_by_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"last_message_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"chat_rooms_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_rooms_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_rooms_created_by_profile_id_idx","columns":["created_by_profile_id"]}],"version":"8093a86b"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatThreadCollection":{"name":"chatthreadcollection","className":"ChatThreadCollection","qualifiedName":"@happyvertical/smrt-chat:ChatThreadCollection","collection":"chatthreads","filePath":"src/collections/ChatThreadCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"getByRoom":{"name":"getByRoom","async":true,"parameters":[{"name":"roomId","type":"string","optional":false}],"returnType":"Promise<ChatThread[]>","isStatic":false,"isPublic":true},"getActive":{"name":"getActive","async":true,"parameters":[{"name":"roomId","type":"string","optional":false}],"returnType":"Promise<ChatThread[]>","isStatic":false,"isPublic":true},"getUnresolved":{"name":"getUnresolved","async":true,"parameters":[],"returnType":"Promise<ChatThread[]>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_threads","api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"ChatThread","exportName":"ChatThreadCollection","collectionExportName":"ChatThreadCollectionCollection","collectionOf":"@happyvertical/smrt-chat:ChatThread","inheritedExposure":["api","mcp"],"schema":{"tableName":"chat_threads","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_threads\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"room_id\\" UUID NOT NULL,\\n \\"root_message_id\\" UUID,\\n \\"title\\" TEXT DEFAULT '',\\n \\"is_resolved\\" BOOLEAN DEFAULT FALSE,\\n \\"message_count\\" INTEGER DEFAULT 0,\\n \\"last_message_at\\" TIMESTAMP,\\n \\"participant_count\\" INTEGER DEFAULT 0\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"root_message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"title":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_resolved":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"message_count":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"last_message_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"participant_count":{"type":"INTEGER","notNull":false,"unique":false,"default":0}},"indexes":[{"name":"chat_threads_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_threads_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_threads_room_id_idx","columns":["room_id"]},{"name":"chat_threads_root_message_id_idx","columns":["root_message_id"]}],"version":"a24026da"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:VoiceGatewayTurnCollection":{"name":"voicegatewayturncollection","className":"VoiceGatewayTurnCollection","qualifiedName":"@happyvertical/smrt-chat:VoiceGatewayTurnCollection","collection":"voicegatewayturns","filePath":"src/collections/VoiceGatewayTurnCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"reserveTurn":{"name":"reserveTurn","async":true,"parameters":[{"name":"input","type":"object","optional":false,"memberTypes":["string"]}],"returnType":"Promise<VoiceGatewayTurn>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"voice_gateway_turns","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":false},"extends":"SmrtCollection","extendsTypeArg":"VoiceGatewayTurn","exportName":"VoiceGatewayTurnCollection","collectionExportName":"VoiceGatewayTurnCollectionCollection","collectionOf":"@happyvertical/smrt-chat:VoiceGatewayTurn","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"voice_gateway_turns","ddl":"CREATE TABLE IF NOT EXISTS \\"voice_gateway_turns\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"voice_session_id\\" UUID NOT NULL,\\n \\"gateway_session_id\\" TEXT DEFAULT '',\\n \\"gateway_turn_id\\" TEXT NOT NULL DEFAULT '',\\n \\"target\\" TEXT NOT NULL DEFAULT 'smrt:chat',\\n \\"status\\" TEXT NOT NULL DEFAULT 'processing',\\n \\"completed_at\\" TIMESTAMP,\\n \\"failed_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"voice_session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"voice_sessions","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"gateway_session_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"gateway_turn_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"target":{"type":"TEXT","notNull":true,"unique":false,"default":"smrt:chat"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"processing"},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"failed_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"voice_gateway_turns_voice_session_id_gateway_turn_id_idx","columns":["voice_session_id","gateway_turn_id"],"unique":true},{"name":"voice_gateway_turns_slug_context_idx","columns":["slug","context"]},{"name":"voice_gateway_turns_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"c27610cd"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:VoiceSessionCollection":{"name":"voicesessioncollection","className":"VoiceSessionCollection","qualifiedName":"@happyvertical/smrt-chat:VoiceSessionCollection","collection":"voicesessions","filePath":"src/collections/VoiceSessionCollection.ts","packageName":"@happyvertical/smrt-chat","fields":{},"methods":{"getActiveById":{"name":"getActiveById","async":true,"parameters":[{"name":"id","type":"string","optional":false},{"name":"target","type":"any","optional":true,"default":"smrt:chat"}],"returnType":"Promise<VoiceSession | null>","isStatic":false,"isPublic":true},"expireStale":{"name":"expireStale","async":true,"parameters":[{"name":"olderThan","type":"Date","optional":true},{"name":"scope","type":"object","optional":true,"memberTypes":["string"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"voice_sessions","api":{"include":["list","get"]},"mcp":{"include":["list","get"]}},"extends":"SmrtCollection","extendsTypeArg":"VoiceSession","exportName":"VoiceSessionCollection","collectionExportName":"VoiceSessionCollectionCollection","collectionOf":"@happyvertical/smrt-chat:VoiceSession","inheritedExposure":["api","mcp"],"schema":{"tableName":"voice_sessions","ddl":"CREATE TABLE IF NOT EXISTS \\"voice_sessions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"gateway_session_id\\" TEXT NOT NULL DEFAULT '',\\n \\"actor_profile_id\\" UUID NOT NULL,\\n \\"actor_user_id\\" UUID,\\n \\"persona_id\\" UUID NOT NULL,\\n \\"agent_session_id\\" UUID NOT NULL,\\n \\"chat_room_id\\" UUID NOT NULL,\\n \\"thread_id\\" UUID,\\n \\"target\\" TEXT NOT NULL DEFAULT 'smrt:chat',\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"expires_at\\" TIMESTAMP NOT NULL,\\n \\"last_turn_at\\" TIMESTAMP,\\n \\"last_gateway_turn_id\\" TEXT,\\n \\"persona_snapshot\\" TEXT DEFAULT '{}',\\n \\"metadata\\" TEXT DEFAULT '{}',\\n \\"processed_turn_ids\\" TEXT DEFAULT '[]'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"gateway_session_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"actor_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"actor_user_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"persona_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"agent_session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"agent_sessions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"chat_room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"thread_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_threads","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"target":{"type":"TEXT","notNull":true,"unique":false,"default":"smrt:chat"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"expires_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"last_turn_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_gateway_turn_id":{"type":"TEXT","notNull":false,"unique":false},"persona_snapshot":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"processed_turn_ids":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"}},"indexes":[{"name":"voice_sessions_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"voice_sessions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"voice_sessions_actor_profile_id_idx","columns":["actor_profile_id"]},{"name":"voice_sessions_actor_user_id_idx","columns":["actor_user_id"]},{"name":"voice_sessions_persona_id_idx","columns":["persona_id"]},{"name":"voice_sessions_agent_session_id_idx","columns":["agent_session_id"]},{"name":"voice_sessions_chat_room_id_idx","columns":["chat_room_id"]},{"name":"voice_sessions_thread_id_idx","columns":["thread_id"]}],"version":"848752a1"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:AgentSession":{"name":"agentsession","className":"AgentSession","qualifiedName":"@happyvertical/smrt-chat:AgentSession","collection":"agentsessions","description":"Agent conversation session.","filePath":"src/models/AgentSession.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","nullable","__tenancy","required"],"sqlType":"UUID","nullable":true,"required":false},"required":false},"agentId":{"type":"text","_meta":{"__statedOptions":["required","requiredFor","default"],"required":true,"requiredFor":"identity"},"required":true,"default":""},"agentProfileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["related"]},"required":false,"related":"@happyvertical/smrt-profiles:Profile"},"participantProfileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["required","requiredFor","related"],"required":true,"requiredFor":"identity"},"required":true,"related":"@happyvertical/smrt-profiles:Profile"},"chatRoomId":{"type":"foreignKey","_meta":{"__statedOptions":["related"]},"required":false,"related":"ChatRoom"},"status":{"type":"text","_meta":{"__statedOptions":["required","default","enum"],"required":true},"required":true,"default":"active","enum":["active","closed","expired"]},"allowedTools":{"type":"text","_meta":{"__statedOptions":["default"]},"required":false,"default":"[]"},"sessionContext":{"type":"text","_meta":{"__statedOptions":["sensitive","default"],"sensitive":true},"required":false,"default":"{}","sensitive":true},"systemPrompt":{"type":"text","_meta":{"__statedOptions":["default"]},"required":false,"default":""},"messageCount":{"type":"integer","_meta":{"__statedOptions":["default"]},"required":false,"default":0},"totalTokensUsed":{"type":"integer","_meta":{"__statedOptions":["default"]},"required":false,"default":0},"maxTokens":{"type":"integer","_meta":{"__statedOptions":["default"]},"required":false,"default":0},"maxMessages":{"type":"integer","_meta":{"__statedOptions":["default"]},"required":false,"default":0},"lastMessageAt":{"type":"datetime","_meta":{"__statedOptions":[]},"required":false},"expiresAt":{"type":"datetime","_meta":{"__statedOptions":[]},"required":false},"closedAt":{"type":"datetime","_meta":{"__statedOptions":[]},"required":false}},"methods":{"getAllowedTools":{"name":"getAllowedTools","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"setAllowedTools":{"name":"setAllowedTools","async":false,"parameters":[{"name":"tools","type":"string[]","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"isToolAllowed":{"name":"isToolAllowed","async":false,"parameters":[{"name":"toolName","type":"string","optional":false}],"returnType":"boolean","isStatic":false,"isPublic":true},"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isExpired":{"name":"isExpired","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"close":{"name":"close","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"expire":{"name":"expire","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"getSessionContext":{"name":"getSessionContext","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true},"setSessionContext":{"name":"setSessionContext","async":false,"parameters":[{"name":"ctx","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getSessionKey":{"name":"getSessionKey","async":false,"parameters":[],"returnType":"string | null","isStatic":false,"isPublic":true},"updateSessionContext":{"name":"updateSessionContext","async":true,"parameters":[{"name":"updates","type":"Record<string, unknown>","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"recordMessage":{"name":"recordMessage","async":true,"parameters":[{"name":"tokensUsed","type":"number","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"agent_sessions","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"AgentSession","collectionExportName":"AgentSessionCollection","validationRules":[{"field":"agentId","rule":"required","fieldType":"text"},{"field":"participantProfileId","rule":"required","fieldType":"crossPackageRef"},{"field":"status","rule":"required","fieldType":"text"}],"schema":{"tableName":"agent_sessions","ddl":"CREATE TABLE IF NOT EXISTS \\"agent_sessions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"agent_id\\" TEXT NOT NULL DEFAULT '',\\n \\"agent_profile_id\\" UUID,\\n \\"participant_profile_id\\" UUID NOT NULL,\\n \\"chat_room_id\\" UUID,\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"allowed_tools\\" TEXT DEFAULT '[]',\\n \\"session_context\\" TEXT DEFAULT '{}',\\n \\"system_prompt\\" TEXT DEFAULT '',\\n \\"message_count\\" INTEGER DEFAULT 0,\\n \\"total_tokens_used\\" INTEGER DEFAULT 0,\\n \\"max_tokens\\" INTEGER DEFAULT 0,\\n \\"max_messages\\" INTEGER DEFAULT 0,\\n \\"last_message_at\\" TIMESTAMP,\\n \\"expires_at\\" TIMESTAMP,\\n \\"closed_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"agent_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"agent_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"participant_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"chat_room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"allowed_tools":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"},"session_context":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"system_prompt":{"type":"TEXT","notNull":false,"unique":false,"default":""},"message_count":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"total_tokens_used":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"max_tokens":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"max_messages":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"last_message_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"closed_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"agent_sessions_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"agent_sessions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"agent_sessions_agent_profile_id_idx","columns":["agent_profile_id"]},{"name":"agent_sessions_participant_profile_id_idx","columns":["participant_profile_id"]},{"name":"agent_sessions_chat_room_id_idx","columns":["chat_room_id"]}],"version":"0a330023"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatMessage":{"name":"chatmessage","className":"ChatMessage","qualifiedName":"@happyvertical/smrt-chat:ChatMessage","collection":"chatmessages","description":"Chat message. Internal model \u2014 all mutations must go through the membership-checked ChatService (S5 #1392).","filePath":"src/models/ChatMessage.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"roomId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The room in which this message was sent.","requiredFor":"identity"},"required":true,"related":"ChatRoom","description":"The room in which this message was sent."},"threadId":{"type":"foreignKey","_meta":{"__statedOptions":["description","related"],"description":"The discussion thread containing this message, when there is one."},"required":false,"related":"ChatThread","description":"The discussion thread containing this message, when there is one."},"senderProfileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The person or assistant who sent this message.","requiredFor":"identity"},"required":true,"related":"@happyvertical/smrt-profiles:Profile","description":"The person or assistant who sent this message."},"agentSessionId":{"type":"foreignKey","_meta":{"__statedOptions":["description","related"],"description":"The assistant conversation associated with this message, when applicable."},"required":false,"related":"AgentSession","description":"The assistant conversation associated with this message, when applicable."},"content":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"The text of the message shared with the conversation."},"required":false,"default":"","description":"The text of the message shared with the conversation."},"messageType":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"The kind of message, such as text, a file, or an activity notice."},"required":true,"default":"text","description":"The kind of message, such as text, a file, or an activity notice.","enum":["text","system","action","file","tool_call","tool_result"]},"role":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"Whether this message comes from a person, an assistant, or an automated action."},"required":true,"default":"user","description":"Whether this message comes from a person, an assistant, or an automated action.","enum":["user","assistant","system","tool"]},"isEdited":{"type":"boolean","_meta":{"__statedOptions":["description","default"],"description":"Whether the message has changed since it was sent."},"required":false,"default":false,"description":"Whether the message has changed since it was sent."},"editedAt":{"type":"datetime","_meta":{"__statedOptions":["description"],"description":"When the message was most recently edited."},"required":false,"description":"When the message was most recently edited."},"isDeleted":{"type":"boolean","_meta":{"__statedOptions":["description","default"],"description":"Whether this message has been removed from the conversation."},"required":false,"default":false,"description":"Whether this message has been removed from the conversation."},"replyToMessageId":{"type":"foreignKey","_meta":{"__statedOptions":["description","related"],"description":"The earlier message this reply responds to."},"required":false,"related":"ChatMessage","description":"The earlier message this reply responds to."},"metadata":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"Additional message details maintained by the application."},"required":false,"default":"{}","description":"Additional message details maintained by the application."},"toolCallData":{"type":"text","_meta":{"__statedOptions":["description"],"description":"Details of an automated action associated with this message."},"required":false,"description":"Details of an automated action associated with this message."},"attachments":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"Files shared alongside the text of this message."},"required":false,"default":"[]","description":"Files shared alongside the text of this message."}},"methods":{"getAttachments":{"name":"getAttachments","async":false,"parameters":[],"returnType":"Array<object>","isStatic":false,"isPublic":true},"setAttachments":{"name":"setAttachments","async":false,"parameters":[{"name":"items","type":"Array<object>","optional":false,"memberTypes":["string","number"]}],"returnType":"void","isStatic":false,"isPublic":true},"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"data","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getToolCallData":{"name":"getToolCallData","async":false,"parameters":[],"returnType":"Record<string, unknown> | null","isStatic":false,"isPublic":true},"setToolCallData":{"name":"setToolCallData","async":false,"parameters":[{"name":"data","type":"Record<string, unknown> | null","optional":false,"unionBranches":[{"type":"Record<string, unknown>"},{"type":"null"}]}],"returnType":"void","isStatic":false,"isPublic":true},"hasAttachments":{"name":"hasAttachments","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isToolCall":{"name":"isToolCall","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isToolResult":{"name":"isToolResult","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isFromAgent":{"name":"isFromAgent","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isSystemMessage":{"name":"isSystemMessage","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"edit":{"name":"edit","async":true,"parameters":[{"name":"newContent","type":"string","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"softDelete":{"name":"softDelete","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"getPreview":{"name":"getPreview","async":false,"parameters":[{"name":"maxLength","type":"any","optional":true}],"returnType":"string","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_messages","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"ChatMessage","collectionExportName":"ChatMessageCollection","validationRules":[{"field":"roomId","rule":"required","fieldType":"foreignKey"},{"field":"senderProfileId","rule":"required","fieldType":"crossPackageRef"},{"field":"messageType","rule":"required","fieldType":"text"},{"field":"role","rule":"required","fieldType":"text"}],"schema":{"tableName":"chat_messages","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_messages\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"room_id\\" UUID NOT NULL,\\n \\"thread_id\\" UUID,\\n \\"sender_profile_id\\" UUID NOT NULL,\\n \\"agent_session_id\\" UUID,\\n \\"content\\" TEXT DEFAULT '',\\n \\"message_type\\" TEXT NOT NULL DEFAULT 'text',\\n \\"role\\" TEXT NOT NULL DEFAULT 'user',\\n \\"is_edited\\" BOOLEAN DEFAULT FALSE,\\n \\"edited_at\\" TIMESTAMP,\\n \\"is_deleted\\" BOOLEAN DEFAULT FALSE,\\n \\"reply_to_message_id\\" UUID,\\n \\"metadata\\" TEXT DEFAULT '{}',\\n \\"tool_call_data\\" TEXT,\\n \\"attachments\\" TEXT DEFAULT '[]'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"thread_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_threads","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"sender_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"agent_session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"agent_sessions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"content":{"type":"TEXT","notNull":false,"unique":false,"default":""},"message_type":{"type":"TEXT","notNull":true,"unique":false,"default":"text"},"role":{"type":"TEXT","notNull":true,"unique":false,"default":"user"},"is_edited":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"edited_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"is_deleted":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"reply_to_message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"tool_call_data":{"type":"TEXT","notNull":false,"unique":false},"attachments":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"}},"indexes":[{"name":"chat_messages_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_messages_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_messages_room_id_idx","columns":["room_id"]},{"name":"chat_messages_thread_id_idx","columns":["thread_id"]},{"name":"chat_messages_sender_profile_id_idx","columns":["sender_profile_id"]},{"name":"chat_messages_agent_session_id_idx","columns":["agent_session_id"]},{"name":"chat_messages_reply_to_message_id_idx","columns":["reply_to_message_id"]}],"version":"83f829da"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatParticipant":{"name":"chatparticipant","className":"ChatParticipant","qualifiedName":"@happyvertical/smrt-chat:ChatParticipant","collection":"chatparticipants","description":"Room membership row. Internal model \u2014 membership must be established and mutated only through the membership/owner-checked ChatService (S5 #1392).","filePath":"src/models/ChatParticipant.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"roomId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The room to which this membership belongs.","requiredFor":"identity"},"required":true,"related":"ChatRoom","description":"The room to which this membership belongs."},"profileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The person or assistant participating in the room.","requiredFor":"identity"},"required":true,"related":"@happyvertical/smrt-profiles:Profile","description":"The person or assistant participating in the room."},"role":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"The member role that determines what they can do in the room."},"required":true,"default":"member","description":"The member role that determines what they can do in the room.","enum":["owner","admin","member","viewer"]},"status":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"Whether this member is active, has left, was removed, or is banned."},"required":true,"default":"active","description":"Whether this member is active, has left, was removed, or is banned.","enum":["active","left","kicked","banned"]},"onlineStatus":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"The availability shown for this member, such as online or away."},"required":true,"default":"offline","description":"The availability shown for this member, such as online or away.","enum":["online","away","dnd","offline"]},"lastReadMessageId":{"type":"foreignKey","_meta":{"__statedOptions":["description","related"],"description":"The most recent message this member has read."},"required":false,"related":"ChatMessage","description":"The most recent message this member has read."},"lastSeenAt":{"type":"datetime","_meta":{"__statedOptions":["description"],"description":"When this member was last seen in the conversation."},"required":false,"description":"When this member was last seen in the conversation."},"joinedAt":{"type":"datetime","_meta":{"__statedOptions":["description"],"description":"When this member joined the room."},"required":false,"description":"When this member joined the room."},"nickname":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"The display name this member uses within the room."},"required":false,"default":"","description":"The display name this member uses within the room."},"isMuted":{"type":"boolean","_meta":{"__statedOptions":["description","default"],"description":"Whether notifications for this room are muted for this member."},"required":false,"default":false,"description":"Whether notifications for this room are muted for this member."},"isPinned":{"type":"boolean","_meta":{"__statedOptions":["description","default"],"description":"Whether this room is pinned for this member."},"required":false,"default":false,"description":"Whether this room is pinned for this member."}},"methods":{"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isOwner":{"name":"isOwner","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isAdmin":{"name":"isAdmin","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"markRead":{"name":"markRead","async":true,"parameters":[{"name":"messageId","type":"string","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"leave":{"name":"leave","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"setOnline":{"name":"setOnline","async":true,"parameters":[{"name":"status","type":"OnlineStatus","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_participants","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"ChatParticipant","collectionExportName":"ChatParticipantCollection","validationRules":[{"field":"roomId","rule":"required","fieldType":"foreignKey"},{"field":"profileId","rule":"required","fieldType":"crossPackageRef"},{"field":"role","rule":"required","fieldType":"text"},{"field":"status","rule":"required","fieldType":"text"},{"field":"onlineStatus","rule":"required","fieldType":"text"}],"schema":{"tableName":"chat_participants","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_participants\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"room_id\\" UUID NOT NULL,\\n \\"profile_id\\" UUID NOT NULL,\\n \\"role\\" TEXT NOT NULL DEFAULT 'member',\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"online_status\\" TEXT NOT NULL DEFAULT 'offline',\\n \\"last_read_message_id\\" UUID,\\n \\"last_seen_at\\" TIMESTAMP,\\n \\"joined_at\\" TIMESTAMP,\\n \\"nickname\\" TEXT DEFAULT '',\\n \\"is_muted\\" BOOLEAN DEFAULT FALSE,\\n \\"is_pinned\\" BOOLEAN DEFAULT FALSE\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"role":{"type":"TEXT","notNull":true,"unique":false,"default":"member"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"online_status":{"type":"TEXT","notNull":true,"unique":false,"default":"offline"},"last_read_message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"last_seen_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"joined_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"nickname":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_muted":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"is_pinned":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false}},"indexes":[{"name":"chat_participants_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_participants_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_participants_room_id_idx","columns":["room_id"]},{"name":"chat_participants_profile_id_idx","columns":["profile_id"]},{"name":"chat_participants_last_read_message_id_idx","columns":["last_read_message_id"]}],"version":"166a9740"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatReaction":{"name":"chatreaction","className":"ChatReaction","qualifiedName":"@happyvertical/smrt-chat:ChatReaction","collection":"chatreactions","description":"Message reaction. Internal model \u2014 reactions must be added/removed only through the membership-checked ChatService (S5 #1392).","filePath":"src/models/ChatReaction.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"messageId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The message to which this reaction was added.","requiredFor":"identity"},"required":true,"related":"ChatMessage","description":"The message to which this reaction was added."},"profileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The person who added this reaction.","requiredFor":"identity"},"required":true,"related":"@happyvertical/smrt-profiles:Profile","description":"The person who added this reaction."},"emoji":{"type":"text","_meta":{"__statedOptions":["required","requiredFor","description","default"],"required":true,"description":"The symbol chosen to express a response to the message.","requiredFor":"identity"},"required":true,"default":"","description":"The symbol chosen to express a response to the message."}},"methods":{},"decoratorConfig":{"tableName":"chat_reactions","api":{"include":["list"]},"mcp":{"include":["list"]},"cli":false,"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"ChatReaction","collectionExportName":"ChatReactionCollection","validationRules":[{"field":"messageId","rule":"required","fieldType":"foreignKey"},{"field":"profileId","rule":"required","fieldType":"crossPackageRef"},{"field":"emoji","rule":"required","fieldType":"text"}],"schema":{"tableName":"chat_reactions","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_reactions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"message_id\\" UUID NOT NULL,\\n \\"profile_id\\" UUID NOT NULL,\\n \\"emoji\\" TEXT NOT NULL DEFAULT ''\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"emoji":{"type":"TEXT","notNull":true,"unique":false,"default":""}},"indexes":[{"name":"chat_reactions_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_reactions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_reactions_message_id_idx","columns":["message_id"]},{"name":"chat_reactions_profile_id_idx","columns":["profile_id"]}],"version":"635cdbec"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatRoom":{"name":"chatroom","className":"ChatRoom","qualifiedName":"@happyvertical/smrt-chat:ChatRoom","collection":"chatrooms","description":"Chat room supporting public channels, private groups, DMs, and agent conversations.","filePath":"src/models/ChatRoom.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"name":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"A recognizable name that helps teammates find this room."},"required":false,"default":"","description":"A recognizable name that helps teammates find this room."},"description":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"Explain the purpose of the room and who should join."},"required":false,"default":"","description":"Explain the purpose of the room and who should join."},"roomType":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"Whether the room is public, private, a direct message, or an assistant conversation."},"required":true,"default":"public","description":"Whether the room is public, private, a direct message, or an assistant conversation.","enum":["public","private","dm","agent"]},"status":{"type":"text","_meta":{"__statedOptions":["required","description","default","enum"],"required":true,"description":"Whether this room is active, archived, or deleted."},"required":true,"default":"active","description":"Whether this room is active, archived, or deleted.","enum":["active","archived","deleted"]},"topic":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"The current subject or focus of the room."},"required":false,"default":"","description":"The current subject or focus of the room."},"avatarUrl":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"The address of the image used to represent this room."},"required":false,"default":"","description":"The address of the image used to represent this room."},"isArchived":{"type":"boolean","_meta":{"__statedOptions":["description","default"],"description":"Whether the room has been archived from active conversations."},"required":false,"default":false,"description":"Whether the room has been archived from active conversations."},"maxParticipants":{"type":"integer","_meta":{"__statedOptions":["description","default"],"description":"The maximum number of members; zero means no configured limit."},"required":false,"default":0,"description":"The maximum number of members; zero means no configured limit."},"metadata":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"Additional room details maintained by the application."},"required":false,"default":"{}","description":"Additional room details maintained by the application."},"createdByProfileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["description","related"],"description":"The person who originally created this room."},"required":false,"related":"@happyvertical/smrt-profiles:Profile","description":"The person who originally created this room."},"lastMessageAt":{"type":"datetime","_meta":{"__statedOptions":["description"],"description":"When the most recent message was sent in this room."},"required":false,"description":"When the most recent message was sent in this room."}},"methods":{"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"ChatRoomMetadata","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"data","type":"ChatRoomMetadata","optional":false,"resolvedType":"Record<string, unknown>"}],"returnType":"void","isStatic":false,"isPublic":true},"updateMetadata":{"name":"updateMetadata","async":false,"parameters":[{"name":"updates","type":"ChatRoomMetadata","optional":false,"resolvedType":"Record<string, unknown>"}],"returnType":"void","isStatic":false,"isPublic":true},"isDM":{"name":"isDM","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isAgentRoom":{"name":"isAgentRoom","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isPublic":{"name":"isPublic","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"isActive":{"name":"isActive","async":false,"parameters":[],"returnType":"boolean","isStatic":false,"isPublic":true},"archive":{"name":"archive","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"unarchive":{"name":"unarchive","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_rooms","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"ChatRoom","collectionExportName":"ChatRoomCollection","displayLabelField":"name","validationRules":[{"field":"roomType","rule":"required","fieldType":"text"},{"field":"status","rule":"required","fieldType":"text"}],"schema":{"tableName":"chat_rooms","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_rooms\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"name\\" TEXT DEFAULT '',\\n \\"description\\" TEXT DEFAULT '',\\n \\"room_type\\" TEXT NOT NULL DEFAULT 'public',\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"topic\\" TEXT DEFAULT '',\\n \\"avatar_url\\" TEXT DEFAULT '',\\n \\"is_archived\\" BOOLEAN DEFAULT FALSE,\\n \\"max_participants\\" INTEGER DEFAULT 0,\\n \\"metadata\\" TEXT DEFAULT '{}',\\n \\"created_by_profile_id\\" UUID,\\n \\"last_message_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"name":{"type":"TEXT","notNull":false,"unique":false,"default":""},"description":{"type":"TEXT","notNull":false,"unique":false,"default":""},"room_type":{"type":"TEXT","notNull":true,"unique":false,"default":"public"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"topic":{"type":"TEXT","notNull":false,"unique":false,"default":""},"avatar_url":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_archived":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"max_participants":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"created_by_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"last_message_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"chat_rooms_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_rooms_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_rooms_created_by_profile_id_idx","columns":["created_by_profile_id"]}],"version":"8093a86b"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:ChatThread":{"name":"chatthread","className":"ChatThread","qualifiedName":"@happyvertical/smrt-chat:ChatThread","collection":"chatthreads","description":"Conversation thread. Internal model \u2014 threads must be created/mutated only through the membership-checked ChatService (S5 #1392).","filePath":"src/models/ChatThread.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"roomId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","description","related"],"required":true,"description":"The room containing this discussion thread.","requiredFor":"identity"},"required":true,"related":"ChatRoom","description":"The room containing this discussion thread."},"rootMessageId":{"type":"foreignKey","_meta":{"__statedOptions":["nullable","description","related","required"],"description":"The message that started this thread, when it began as a reply.","nullable":true,"required":false},"required":false,"related":"ChatMessage","description":"The message that started this thread, when it began as a reply."},"title":{"type":"text","_meta":{"__statedOptions":["description","default"],"description":"A short title describing the subject of this thread."},"required":false,"default":"","description":"A short title describing the subject of this thread."},"isResolved":{"type":"boolean","_meta":{"__statedOptions":["description","default"],"description":"Whether the discussion has reached a resolution."},"required":false,"default":false,"description":"Whether the discussion has reached a resolution."},"messageCount":{"type":"integer","_meta":{"__statedOptions":["description","default"],"description":"The number of messages in this thread."},"required":false,"default":0,"description":"The number of messages in this thread."},"lastMessageAt":{"type":"datetime","_meta":{"__statedOptions":["description"],"description":"When the most recent message was sent in this thread."},"required":false,"description":"When the most recent message was sent in this thread."},"participantCount":{"type":"integer","_meta":{"__statedOptions":["description","default"],"description":"The number of people participating in this thread."},"required":false,"default":0,"description":"The number of people participating in this thread."}},"methods":{"resolve":{"name":"resolve","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"reopen":{"name":"reopen","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"chat_threads","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"ChatThread","collectionExportName":"ChatThreadCollection","displayLabelField":"title","validationRules":[{"field":"roomId","rule":"required","fieldType":"foreignKey"}],"schema":{"tableName":"chat_threads","ddl":"CREATE TABLE IF NOT EXISTS \\"chat_threads\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"room_id\\" UUID NOT NULL,\\n \\"root_message_id\\" UUID,\\n \\"title\\" TEXT DEFAULT '',\\n \\"is_resolved\\" BOOLEAN DEFAULT FALSE,\\n \\"message_count\\" INTEGER DEFAULT 0,\\n \\"last_message_at\\" TIMESTAMP,\\n \\"participant_count\\" INTEGER DEFAULT 0\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"root_message_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_messages","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"title":{"type":"TEXT","notNull":false,"unique":false,"default":""},"is_resolved":{"type":"BOOLEAN","notNull":false,"unique":false,"default":false},"message_count":{"type":"INTEGER","notNull":false,"unique":false,"default":0},"last_message_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"participant_count":{"type":"INTEGER","notNull":false,"unique":false,"default":0}},"indexes":[{"name":"chat_threads_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"chat_threads_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"chat_threads_room_id_idx","columns":["room_id"]},{"name":"chat_threads_root_message_id_idx","columns":["root_message_id"]}],"version":"a24026da"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:VoiceGatewayTurn":{"name":"voicegatewayturn","className":"VoiceGatewayTurn","qualifiedName":"@happyvertical/smrt-chat:VoiceGatewayTurn","collection":"voicegatewayturns","description":"Durable reservation for a gateway turn. The natural key makes turn_id replay checks concurrency-safe before transcript messages are written.","filePath":"src/models/VoiceGatewayTurn.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"voiceSessionId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","related"],"required":true,"requiredFor":"idempotency"},"required":true,"related":"VoiceSession"},"gatewaySessionId":{"type":"text","_meta":{"__statedOptions":["default"]},"required":false,"default":""},"gatewayTurnId":{"type":"text","_meta":{"__statedOptions":["required","requiredFor","default"],"required":true,"requiredFor":"idempotency"},"required":true,"default":""},"target":{"type":"text","_meta":{"__statedOptions":["required","default"],"required":true},"required":true,"default":"smrt:chat"},"status":{"type":"text","_meta":{"__statedOptions":["required","default","enum"],"required":true},"required":true,"default":"processing","enum":["processing","completed","failed"]},"completedAt":{"type":"datetime","_meta":{"__statedOptions":[]},"required":false},"failedAt":{"type":"datetime","_meta":{"__statedOptions":[]},"required":false}},"methods":{"complete":{"name":"complete","async":true,"parameters":[{"name":"now","type":"Date","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"fail":{"name":"fail","async":true,"parameters":[{"name":"now","type":"Date","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"voice_gateway_turns","conflictColumns":["voice_session_id","gateway_turn_id"],"api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":false,"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"VoiceGatewayTurn","collectionExportName":"VoiceGatewayTurnCollection","validationRules":[{"field":"voiceSessionId","rule":"required","fieldType":"foreignKey"},{"field":"gatewayTurnId","rule":"required","fieldType":"text"},{"field":"target","rule":"required","fieldType":"text"},{"field":"status","rule":"required","fieldType":"text"}],"schema":{"tableName":"voice_gateway_turns","ddl":"CREATE TABLE IF NOT EXISTS \\"voice_gateway_turns\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"voice_session_id\\" UUID NOT NULL,\\n \\"gateway_session_id\\" TEXT DEFAULT '',\\n \\"gateway_turn_id\\" TEXT NOT NULL DEFAULT '',\\n \\"target\\" TEXT NOT NULL DEFAULT 'smrt:chat',\\n \\"status\\" TEXT NOT NULL DEFAULT 'processing',\\n \\"completed_at\\" TIMESTAMP,\\n \\"failed_at\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"voice_session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"voice_sessions","column":"id","onDelete":"CASCADE","onUpdate":"CASCADE"}},"gateway_session_id":{"type":"TEXT","notNull":false,"unique":false,"default":""},"gateway_turn_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"target":{"type":"TEXT","notNull":true,"unique":false,"default":"smrt:chat"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"processing"},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"failed_at":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"voice_gateway_turns_voice_session_id_gateway_turn_id_idx","columns":["voice_session_id","gateway_turn_id"],"unique":true},{"name":"voice_gateway_turns_slug_context_idx","columns":["slug","context"]},{"name":"voice_gateway_turns_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"c27610cd"},"importPath":"@happyvertical/smrt-chat"},"@happyvertical/smrt-chat:VoiceSession":{"name":"voicesession","className":"VoiceSession","qualifiedName":"@happyvertical/smrt-chat:VoiceSession","collection":"voicesessions","description":"Short-lived binding proving a voice gateway turn belongs to an authenticated SMRT actor, persona, and chat session.","filePath":"src/models/VoiceSession.ts","packageName":"@happyvertical/smrt-chat","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"gatewaySessionId":{"type":"text","_meta":{"__statedOptions":["required","requiredFor","default"],"required":true,"requiredFor":"identity"},"required":true,"default":""},"actorProfileId":{"type":"crossPackageRef","_meta":{"__statedOptions":["required","requiredFor","related"],"required":true,"requiredFor":"identity"},"required":true,"related":"@happyvertical/smrt-profiles:Profile"},"actorUserId":{"type":"crossPackageRef","_meta":{"__statedOptions":["nullable","related","required"],"nullable":true,"required":false},"required":false,"related":"@happyvertical/smrt-users:User"},"personaId":{"type":"crossPackageRef","_meta":{"__statedOptions":["required","requiredFor","related"],"required":true,"requiredFor":"identity"},"required":true,"related":"@happyvertical/smrt-personas:AgentPersona"},"agentSessionId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","related"],"required":true,"requiredFor":"identity"},"required":true,"related":"AgentSession"},"chatRoomId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","related"],"required":true,"requiredFor":"identity"},"required":true,"related":"ChatRoom"},"threadId":{"type":"foreignKey","_meta":{"__statedOptions":["related"]},"required":false,"related":"ChatThread"},"target":{"type":"text","_meta":{"__statedOptions":["required","default"],"required":true},"required":true,"default":"smrt:chat"},"status":{"type":"text","_meta":{"__statedOptions":["required","default","enum"],"required":true},"required":true,"default":"active","enum":["active","expired","revoked"]},"expiresAt":{"type":"datetime","_meta":{"__statedOptions":["required"],"required":true},"required":true},"lastTurnAt":{"type":"datetime","_meta":{"__statedOptions":[]},"required":false},"lastGatewayTurnId":{"type":"text","_meta":{"__statedOptions":[]},"required":false},"personaSnapshot":{"type":"text","_meta":{"__statedOptions":["default"]},"required":false,"default":"{}"},"metadata":{"type":"text","_meta":{"__statedOptions":["default"]},"required":false,"default":"{}"},"processedTurnIds":{"type":"text","_meta":{"__statedOptions":["default"]},"required":false,"default":"[]"}},"methods":{"isActive":{"name":"isActive","async":false,"parameters":[{"name":"now","type":"Date","optional":true}],"returnType":"boolean","isStatic":false,"isPublic":true},"isExpired":{"name":"isExpired","async":false,"parameters":[{"name":"now","type":"Date","optional":true}],"returnType":"boolean","isStatic":false,"isPublic":true},"expire":{"name":"expire","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"revoke":{"name":"revoke","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"getPersonaSnapshot":{"name":"getPersonaSnapshot","async":false,"parameters":[],"returnType":"ConversationPersona","isStatic":false,"isPublic":true},"setPersonaSnapshot":{"name":"setPersonaSnapshot","async":false,"parameters":[{"name":"persona","type":"ConversationPersona","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getMetadata":{"name":"getMetadata","async":false,"parameters":[],"returnType":"Record<string, unknown>","isStatic":false,"isPublic":true},"setMetadata":{"name":"setMetadata","async":false,"parameters":[{"name":"metadata","type":"Record<string, unknown>","optional":false}],"returnType":"void","isStatic":false,"isPublic":true},"getProcessedTurnIds":{"name":"getProcessedTurnIds","async":false,"parameters":[],"returnType":"string[]","isStatic":false,"isPublic":true},"hasProcessedTurn":{"name":"hasProcessedTurn","async":false,"parameters":[{"name":"turnId","type":"string","optional":false}],"returnType":"boolean","isStatic":false,"isPublic":true},"recordGatewayTurn":{"name":"recordGatewayTurn","async":false,"parameters":[{"name":"turnId","type":"string","optional":false},{"name":"maxRememberedTurns","type":"any","optional":true}],"returnType":"void","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"voice_sessions","api":{"include":["list","get"]},"mcp":{"include":["list","get"]},"cli":{"skipApiCheck":true},"tenantScoped":{"mode":"required"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"VoiceSession","collectionExportName":"VoiceSessionCollection","validationRules":[{"field":"gatewaySessionId","rule":"required","fieldType":"text"},{"field":"actorProfileId","rule":"required","fieldType":"crossPackageRef"},{"field":"personaId","rule":"required","fieldType":"crossPackageRef"},{"field":"agentSessionId","rule":"required","fieldType":"foreignKey"},{"field":"chatRoomId","rule":"required","fieldType":"foreignKey"},{"field":"target","rule":"required","fieldType":"text"},{"field":"status","rule":"required","fieldType":"text"},{"field":"expiresAt","rule":"required","fieldType":"datetime"}],"schema":{"tableName":"voice_sessions","ddl":"CREATE TABLE IF NOT EXISTS \\"voice_sessions\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"gateway_session_id\\" TEXT NOT NULL DEFAULT '',\\n \\"actor_profile_id\\" UUID NOT NULL,\\n \\"actor_user_id\\" UUID,\\n \\"persona_id\\" UUID NOT NULL,\\n \\"agent_session_id\\" UUID NOT NULL,\\n \\"chat_room_id\\" UUID NOT NULL,\\n \\"thread_id\\" UUID,\\n \\"target\\" TEXT NOT NULL DEFAULT 'smrt:chat',\\n \\"status\\" TEXT NOT NULL DEFAULT 'active',\\n \\"expires_at\\" TIMESTAMP NOT NULL,\\n \\"last_turn_at\\" TIMESTAMP,\\n \\"last_gateway_turn_id\\" TEXT,\\n \\"persona_snapshot\\" TEXT DEFAULT '{}',\\n \\"metadata\\" TEXT DEFAULT '{}',\\n \\"processed_turn_ids\\" TEXT DEFAULT '[]'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"gateway_session_id":{"type":"TEXT","notNull":true,"unique":false,"default":""},"actor_profile_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"actor_user_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":false,"unique":false},"persona_id":{"type":"UUID","referenceKind":"crossPackageRef","notNull":true,"unique":false},"agent_session_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"agent_sessions","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"chat_room_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false,"foreignKey":{"table":"chat_rooms","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"thread_id":{"type":"UUID","referenceKind":"foreignKey","notNull":false,"unique":false,"foreignKey":{"table":"chat_threads","column":"id","onDelete":"NO ACTION","onUpdate":"CASCADE"}},"target":{"type":"TEXT","notNull":true,"unique":false,"default":"smrt:chat"},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"active"},"expires_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"last_turn_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_gateway_turn_id":{"type":"TEXT","notNull":false,"unique":false},"persona_snapshot":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"metadata":{"type":"TEXT","notNull":false,"unique":false,"default":"{}"},"processed_turn_ids":{"type":"TEXT","notNull":false,"unique":false,"default":"[]"}},"indexes":[{"name":"voice_sessions_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true},{"name":"voice_sessions_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"voice_sessions_actor_profile_id_idx","columns":["actor_profile_id"]},{"name":"voice_sessions_actor_user_id_idx","columns":["actor_user_id"]},{"name":"voice_sessions_persona_id_idx","columns":["persona_id"]},{"name":"voice_sessions_agent_session_id_idx","columns":["agent_session_id"]},{"name":"voice_sessions_chat_room_id_idx","columns":["chat_room_id"]},{"name":"voice_sessions_thread_id_idx","columns":["thread_id"]}],"version":"848752a1"},"importPath":"@happyvertical/smrt-chat"}},"moduleType":"smrt","recipes":[{"id":"chat.assistant","className":"AssistantRecipe","label":"Assistant","summary":"Ask an AI assistant about the page you are on, from a dock in the app shell.","synonyms":["ai assistant","ai chat","copilot","chatbot","ask ai","helper"],"models":["@happyvertical/smrt-chat:AgentSession","@happyvertical/smrt-chat:ChatRoom","@happyvertical/smrt-chat:ChatParticipant","@happyvertical/smrt-chat:ChatThread","@happyvertical/smrt-chat:ChatMessage"],"nav":[],"requires":[],"help":{"markdown":"## Overview\\n\\nThe assistant is a chat panel that opens from a button in the app's top bar. It\\nsees the page you are on, so you can ask about what is in front of you and get\\nan answer without leaving it.\\n\\nYou can keep several conversations and come back to them later. The assistant\\nonly reaches the data and actions the app owner allows, and it works with your\\nown permissions: it cannot show you anything you could not open yourself.\\n\\n## Tasks\\n\\n### Ask a question\\n\\n1. Choose the assistant button in the top bar to open the panel.\\n2. Type your question and send it.\\n3. Read the reply as it arrives. Open the panel again from any page to carry on.\\n\\n### Start a new conversation\\n\\n1. Open the panel and choose the conversation list.\\n2. Start a new conversation, or pick an earlier one to carry on.\\n\\n### Approve a change\\n\\nWhen the assistant proposes a change, it shows what will happen and waits.\\n\\n1. Read the proposed change.\\n2. Confirm it to go ahead, or reject it. Nothing changes until you confirm.\\n\\n### Choose a model\\n\\nIf the app offers more than one model, pick one from the list in the panel\\nbefore you send a message.\\n\\n## What the app owner sets up\\n\\n- A model. Hosted models need the service key their provider issues, stored as\\n a secret in the app (\`OPENAI_API_KEY\`, \`ANTHROPIC_API_KEY\` or\\n \`GEMINI_API_KEY\`); only the key for the model the app uses is needed. Models\\n that run in the browser need no key.\\n- The tools the assistant may use. It is offered nothing unless the app lists\\n it, so an empty list means conversation only.\\n- Optionally, report tools. An app can let the assistant draft a report from a\\n request, preview it, and save it only after a person approves that exact\\n report.\\n","fieldRefs":[]},"surfaces":[{"kind":"shell-widget","slot":"header.end","export":"@happyvertical/smrt-chat/svelte#AssistantDock","label":"Assistant","icon":"bot"}],"providers":[{"id":"llm","kind":"llm","options":["openai","anthropic","gemini","webllm","bitgpu"],"required":true,"secrets":["OPENAI_API_KEY","ANTHROPIC_API_KEY","GEMINI_API_KEY"],"browserOptions":["webllm","bitgpu"]}],"runtime":"both","demo":{"mode":"server","reasons":["Needs a server because its package does not build for a browser: node:crypto + node:async_hooks; and its package depends on @happyvertical/smrt-agents, @happyvertical/smrt-images, @happyvertical/smrt-jobs, @happyvertical/smrt-profiles, @happyvertical/smrt-reports, @happyvertical/smrt-secrets, @happyvertical/smrt-tenancy, @happyvertical/smrt-users, which do not build for a browser (#3615, #3617, #3624, #3625, #3626, #3627, #3628).","Provider llm has an in-browser option (webllm, bitgpu)."]}},{"id":"chat.rooms","className":"ChatRoomsRecipe","label":"Team Chat","summary":"Organize team conversations in rooms with threads and reactions.","synonyms":["team chat","channels","group chat","conversations"],"models":["@happyvertical/smrt-chat:ChatRoom","@happyvertical/smrt-chat:ChatMessage","@happyvertical/smrt-chat:ChatParticipant","@happyvertical/smrt-chat:ChatThread","@happyvertical/smrt-chat:ChatReaction"],"nav":[{"label":"Chat rooms","model":"@happyvertical/smrt-chat:ChatRoom","icon":"users","description":"Team conversations organized by topic or audience.","noun":"chat room"}],"requires":[],"group":{"id":"team-collaboration","label":"Team collaboration","summary":"Keep conversations and shared work in one place."},"section":{"id":"team","label":"Team","icon":"users","description":"People and the conversations that keep them aligned."},"options":{"@happyvertical/smrt-chat:ChatRoom":{"fields":{"metadata":{"visibility":"hidden"},"createdByProfileId":{"visibility":"hidden"},"lastMessageAt":{"label":"Last message","order":1}}},"@happyvertical/smrt-chat:ChatMessage":{"fields":{"metadata":{"visibility":"hidden"},"toolCallData":{"visibility":"hidden"},"attachments":{"visibility":"advanced"}}},"@happyvertical/smrt-chat:ChatParticipant":{"fields":{"lastReadMessageId":{"visibility":"hidden"},"lastSeenAt":{"visibility":"advanced"}}}},"help":{"markdown":"## Overview\\n\\nTeam Chat keeps conversations in rooms so people can find the right discussion,\\nfollow threads, and see reactions without mixing unrelated work together. The\\nroom and message lists are read-only generated views. Create rooms, manage\\nmembers, and send messages through the app's authorized chat workflow.\\n\\n## Tasks\\n\\n### Find the right room\\n\\n1. Open **Chat rooms** from the navigation.\\n2. Search for a room by its **{field:ChatRoom.name}**, or use its\\n **{field:ChatRoom.topic}** to tell similar rooms apart.\\n3. Open the room and check **{field:ChatRoom.lastMessageAt}** to see where the\\n most recent discussion happened.\\n\\n### Follow a conversation\\n\\n1. Read the room messages and open a thread when you need the discussion in\\n one place.\\n2. Use the thread **{field:ChatThread.title}** to describe the subject when\\n your app supplies one.\\n3. Add a reaction by choosing the **{field:ChatReaction.emoji}** that best\\n communicates your response.\\n\\n### Keep a room useful\\n\\n1. Give the room a clear **{field:ChatRoom.name}** and a short\\n **{field:ChatRoom.description}**.\\n2. Set **{field:ChatRoom.roomType}** deliberately: public for broad team\\n discussion, private for restricted groups, and direct messages for one-to-one\\n conversations.\\n3. Use a focused **{field:ChatMessage.content}** so teammates can scan the\\n conversation and reply in context.\\n","fieldRefs":["ChatMessage.content","ChatReaction.emoji","ChatRoom.description","ChatRoom.lastMessageAt","ChatRoom.name","ChatRoom.roomType","ChatRoom.topic","ChatThread.title"]},"surfaces":[{"kind":"route","path":"/chat/rooms","export":"@happyvertical/smrt-chat/svelte#ChatLayout","label":"Team chat"}],"runtime":"both","demoSeed":{"export":"@happyvertical/smrt-chat/playground#chatRoomsFixture"},"demo":{"mode":"server","reasons":["Needs a server because its package does not build for a browser: node:crypto + node:async_hooks; and its package depends on @happyvertical/smrt-agents, @happyvertical/smrt-images, @happyvertical/smrt-jobs, @happyvertical/smrt-profiles, @happyvertical/smrt-reports, @happyvertical/smrt-secrets, @happyvertical/smrt-tenancy, @happyvertical/smrt-users, which do not build for a browser (#3615, #3617, #3624, #3625, #3626, #3627, #3628)."]}}],"smrtDependencies":["@happyvertical/smrt-agents","@happyvertical/smrt-app-runtime","@happyvertical/smrt-assets","@happyvertical/smrt-core","@happyvertical/smrt-images","@happyvertical/smrt-inference","@happyvertical/smrt-personas","@happyvertical/smrt-profiles","@happyvertical/smrt-prompts","@happyvertical/smrt-reports","@happyvertical/smrt-tenancy","@happyvertical/smrt-users"],"browser":{"status":"server-only","issues":["#3615","#3617","#3624","#3625","#3626","#3627","#3628"],"reason":"node:crypto + node:async_hooks","via":["@happyvertical/smrt-agents","@happyvertical/smrt-images","@happyvertical/smrt-jobs","@happyvertical/smrt-profiles","@happyvertical/smrt-reports","@happyvertical/smrt-secrets","@happyvertical/smrt-tenancy","@happyvertical/smrt-users"]},"stampsConstructors":true}`));
32
67
  //#endregion
33
68
  //#region src/ai-unavailable.ts
34
69
  var CHAT_AI_UNAVAILABLE_CODE = "ai_unavailable";
@@ -1045,7 +1080,7 @@ async function runToolLoop(options) {
1045
1080
  if (tool) options.beforeToolExecution?.(tool);
1046
1081
  }
1047
1082
  } catch (error) {
1048
- if (error instanceof WorkProfileEscalation) error.messages = [...working];
1083
+ if (error instanceof ToolRunTypeRefusal) error.messages = [...working];
1049
1084
  throw error;
1050
1085
  }
1051
1086
  working.push({
@@ -1569,7 +1604,403 @@ function toolErrorObservation(error, kind) {
1569
1604
  };
1570
1605
  }
1571
1606
  //#endregion
1607
+ //#region src/turn-tracking.ts
1608
+ var CHAT_ASSISTANT_PROMPT_KEY = "chat.assistant.system";
1609
+ var CHAT_TURN_DEFINITION_KEY = "chat.assistant.turn";
1610
+ var chatAssistantSystemPrompt = definePrompt({
1611
+ key: CHAT_ASSISTANT_PROMPT_KEY,
1612
+ template: "You are the assistant of this app. Use only the tools you are offered, and say plainly when you cannot do something.",
1613
+ ai: { profile: "best" },
1614
+ editable: {
1615
+ template: true,
1616
+ profile: false,
1617
+ model: false,
1618
+ params: false
1619
+ }
1620
+ });
1621
+ async function resolveChatAssistantPrompt(options) {
1622
+ const override = options.systemPrompt?.trim() ? { template: options.systemPrompt } : void 0;
1623
+ try {
1624
+ return await resolvePrompt(CHAT_ASSISTANT_PROMPT_KEY, {
1625
+ ...options.db ? { db: options.db } : {},
1626
+ tenantId: options.tenantId,
1627
+ ...override ? { override } : {}
1628
+ });
1629
+ } catch (error) {
1630
+ if (!options.db) throw error;
1631
+ return resolvePrompt(CHAT_ASSISTANT_PROMPT_KEY, {
1632
+ tenantId: options.tenantId,
1633
+ ...override ? { override } : {}
1634
+ });
1635
+ }
1636
+ }
1637
+ async function resolveChatAssistantTier(options) {
1638
+ const { ai } = await resolveChatAssistantPrompt(options);
1639
+ return ai.tier && ai.tier !== "auto" ? ai.tier : DEFAULT_INFERENCE_TIER;
1640
+ }
1641
+ function chatAssistantSystemText(prompt) {
1642
+ return prompt.ai.usageTags.promptLayer === "default" ? void 0 : prompt.text;
1643
+ }
1644
+ function chatClientForTracking(ai) {
1645
+ if (typeof ai.embed === "function") return ai;
1646
+ return new Proxy(ai, { get(target, property, receiver) {
1647
+ if (property === "embed") return () => {
1648
+ throw new Error("The assistant client does not embed.");
1649
+ };
1650
+ const value = Reflect.get(target, property, receiver);
1651
+ return typeof value === "function" ? value.bind(target) : value;
1652
+ } });
1653
+ }
1654
+ var TURN_RUN = /* @__PURE__ */ Symbol("turnRun");
1655
+ function engineUsage(report, fallbackModel) {
1656
+ const count = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
1657
+ const total = count(report?.tokens);
1658
+ const input = count(report?.inputTokens);
1659
+ const output = count(report?.outputTokens);
1660
+ const model = report?.model ?? report?.requestedModel ?? fallbackModel;
1661
+ return {
1662
+ ...model ? { model } : {},
1663
+ ...total !== void 0 ? { usage: {
1664
+ ...input !== void 0 && output !== void 0 ? {
1665
+ promptTokens: input,
1666
+ completionTokens: output
1667
+ } : {},
1668
+ totalTokens: total
1669
+ } } : {},
1670
+ ...count(report?.durationMs) !== void 0 ? { duration: report?.durationMs } : {}
1671
+ };
1672
+ }
1673
+ function messageRef(prefix, id) {
1674
+ return typeof id === "string" && id !== "" ? `${prefix}:${id}` : null;
1675
+ }
1676
+ var DECISION_LOOKUP_CHUNK = 200;
1677
+ function approvalRef(id) {
1678
+ return `approval:${id}`;
1679
+ }
1680
+ function rowsOf(result) {
1681
+ if (Array.isArray(result)) return result;
1682
+ const rows = result?.rows;
1683
+ return Array.isArray(rows) ? rows : [];
1684
+ }
1685
+ var AssistantTurnRun = class AssistantTurnRun {
1686
+ constructor(tracking, context, runId, handoffEventId = null) {
1687
+ this.tracking = tracking;
1688
+ this.context = context;
1689
+ this.runId = runId;
1690
+ this.handoffEventId = handoffEventId;
1691
+ }
1692
+ tracking;
1693
+ context;
1694
+ runId;
1695
+ handoffEventId;
1696
+ actions = /* @__PURE__ */ new Map();
1697
+ requests = /* @__PURE__ */ new Map();
1698
+ ended = false;
1699
+ /**
1700
+ * Open the run, then record the decisions made since the last turn.
1701
+ * Throws `AiRunTrackingDisabledError` while usage persistence is off: a
1702
+ * chat turn does not run untracked.
1703
+ */
1704
+ static async open(tracking, input = {}) {
1705
+ const parent = tracking.parent;
1706
+ const handoffEventId = parent ? randomUUID() : null;
1707
+ const { run, context } = await tracking.tracked.openRun({
1708
+ ...parent ? {
1709
+ parentRunId: parent.context.runId,
1710
+ handoff: {
1711
+ eventId: handoffEventId,
1712
+ name: parent.name ?? null,
1713
+ stepIndex: parent.stepIndex ?? parent.context.stepIndex ?? null
1714
+ }
1715
+ } : {},
1716
+ type: "turn",
1717
+ definitionKey: tracking.definitionKey ?? "chat.assistant.turn",
1718
+ promptKey: tracking.prompt.key,
1719
+ templateHash: tracking.prompt.ai.usageTags.templateHash,
1720
+ tags: {
1721
+ ...tracking.threadId ? { threadId: tracking.threadId } : {},
1722
+ ...tracking.agentSessionId ? { agentSessionId: tracking.agentSessionId } : {}
1723
+ },
1724
+ ...tracking.budget ? { budget: tracking.budget } : {}
1725
+ });
1726
+ const turn = new AssistantTurnRun(tracking, parent?.context.fence ? {
1727
+ ...context,
1728
+ fence: parent.context.fence
1729
+ } : context, run.id, handoffEventId);
1730
+ const ref = messageRef(turn.refPrefix, input.originMessageId);
1731
+ if (ref) await turn.append({
1732
+ type: "observation",
1733
+ name: "user_message",
1734
+ status: "ok",
1735
+ payloadRef: ref
1736
+ });
1737
+ await turn.recordDecisions();
1738
+ return turn;
1739
+ }
1740
+ get refPrefix() {
1741
+ return this.tracking.messageRefPrefix ?? "chat-message";
1742
+ }
1743
+ /**
1744
+ * The prompt's tracked client for this turn's calls. With the host's
1745
+ * selection, its calls also carry the tier asked for and bound.
1746
+ */
1747
+ client(selection) {
1748
+ return this.tracking.tracked.client(trackedPromptCall(this.tracking.prompt, { usageTags: this.tierTags(selection) }), { runContext: this.context });
1749
+ }
1750
+ /**
1751
+ * The tracked prompt of the turn's calls, the one {@link client} carries.
1752
+ * An engine call made outside the client (Claude Code, Codex) records
1753
+ * under it.
1754
+ */
1755
+ promptCall(selection) {
1756
+ return trackedPromptCall(this.tracking.prompt, { usageTags: this.tierTags(selection) });
1757
+ }
1758
+ /** The tier the prompt asks for and the tier the host bound the turn at. */
1759
+ tierTags(selection) {
1760
+ const asked = this.tracking.prompt.ai.tier;
1761
+ const requested = asked && asked !== "auto" ? asked : selection?.tier;
1762
+ return {
1763
+ ...requested ? { tierRequested: String(requested) } : {},
1764
+ ...selection?.tier ? { tierResolved: String(selection.tier) } : {}
1765
+ };
1766
+ }
1767
+ /**
1768
+ * Reserve one external engine turn (a Claude Code or Codex session) as one
1769
+ * call of this run, before the engine starts (ai-runs section 6.4): the
1770
+ * call id is minted first, the run's and its ancestors' limits apply, and a
1771
+ * refused reservation stops the run and throws `AiRunStoppedError`. The
1772
+ * engine reports one result per turn, so its internal model calls are
1773
+ * recorded as this one call. The usage row names the engine as provider
1774
+ * and the model it reported (else the tier binding's), carries the prompt
1775
+ * key and the tiers, and is uncosted (an engine has no price).
1776
+ */
1777
+ async beginEngineCall(input) {
1778
+ const { selection } = input;
1779
+ const prompt = this.promptCall(selection);
1780
+ const model = selection?.model;
1781
+ const fallback = {
1782
+ provider: selection?.engine ?? "external",
1783
+ model: model ?? "unknown",
1784
+ operation: "chat",
1785
+ className: "AssistantTurn",
1786
+ tenantId: this.tracking.tracked.tenantId,
1787
+ tags: {
1788
+ ...prompt.usageTags ?? {},
1789
+ promptKey: prompt.promptKey,
1790
+ ...prompt.templateHash ? { templateHash: prompt.templateHash } : {}
1791
+ }
1792
+ };
1793
+ const handle = await beginAiRunCall(this.context, {
1794
+ inputChars: input.inputChars,
1795
+ rate: null,
1796
+ fallbackUsage: fallback,
1797
+ ...input.signal ? { signal: input.signal } : {}
1798
+ });
1799
+ const callTimeout = handle.invocation.signal;
1800
+ let timedOut = false;
1801
+ if (handle.reservation.callTimeoutMs !== null && callTimeout) callTimeout.addEventListener("abort", () => {
1802
+ if (!input.signal?.aborted) timedOut = true;
1803
+ }, { once: true });
1804
+ return {
1805
+ signal: callTimeout,
1806
+ get timedOut() {
1807
+ return timedOut;
1808
+ },
1809
+ answered: (report) => handle.succeed(engineUsage(report, model)),
1810
+ ended: (error, report) => {
1811
+ const observed = engineUsage(report, model);
1812
+ if (observed.usage) handle.invocation.capture({
1813
+ ...fallback,
1814
+ model: observed.model ?? fallback.model,
1815
+ usage: observed.usage,
1816
+ duration: observed.duration ?? 0,
1817
+ timestamp: /* @__PURE__ */ new Date()
1818
+ });
1819
+ return handle.fail(error);
1820
+ }
1821
+ };
1822
+ }
1823
+ async append(event) {
1824
+ try {
1825
+ const { id } = await appendAiRunEvent(this.tracking.tracked.db, this.runId, event);
1826
+ return id;
1827
+ } catch {
1828
+ return null;
1829
+ }
1830
+ }
1831
+ /** Record this turn's tool use from the tool loop's step events. */
1832
+ async step(event) {
1833
+ if (this.ended) return;
1834
+ if (event.type === "tool_call" && event.callId) {
1835
+ const id = await this.append({
1836
+ type: "action",
1837
+ name: event.slug ?? null,
1838
+ status: "ok",
1839
+ payload: {
1840
+ callId: event.callId,
1841
+ location: event.location ?? null
1842
+ }
1843
+ });
1844
+ if (id) this.actions.set(event.callId, id);
1845
+ } else if (event.type === "tool_result" && event.callId) await this.append({
1846
+ type: "observation",
1847
+ name: event.slug ?? null,
1848
+ status: event.ok ? "ok" : "error",
1849
+ parentEventId: this.actions.get(event.callId) ?? null,
1850
+ payload: {
1851
+ callId: event.callId,
1852
+ ok: event.ok === true,
1853
+ ...event.error ? { error: event.error } : {}
1854
+ }
1855
+ });
1856
+ }
1857
+ /** An owner approval was requested: the turn will end with it pending. */
1858
+ async approvalRequested(request, callId) {
1859
+ if (this.ended) return;
1860
+ const id = await this.append({
1861
+ type: "approval",
1862
+ name: request.tool,
1863
+ status: "requested",
1864
+ parentEventId: this.actions.get(callId) ?? null,
1865
+ payloadRef: approvalRef(request.id)
1866
+ });
1867
+ if (id) this.requests.set(request.id, id);
1868
+ }
1869
+ /**
1870
+ * An approval requested in this same turn was decided while the turn
1871
+ * waited on it (a host that holds the turn in process): the decision is an
1872
+ * event of this run, pointing at its request.
1873
+ */
1874
+ async approvalDecided(approvalId, status) {
1875
+ const request = this.requests.get(approvalId);
1876
+ if (!request || this.ended) return;
1877
+ await this.append({
1878
+ type: "approval",
1879
+ status,
1880
+ parentEventId: request,
1881
+ payloadRef: approvalRef(approvalId)
1882
+ });
1883
+ }
1884
+ /** The reply the turn stored, referenced and never copied. */
1885
+ async replied(messageId) {
1886
+ const ref = messageRef(this.refPrefix, messageId);
1887
+ if (!ref || this.ended) return;
1888
+ await this.append({
1889
+ type: "observation",
1890
+ name: "assistant_reply",
1891
+ status: "ok",
1892
+ payloadRef: ref
1893
+ });
1894
+ }
1895
+ /**
1896
+ * Decisions made since the last turn, each recorded once with its request
1897
+ * as `parent_event_id`. Only the approvals this thread asked for are read:
1898
+ * one query per {@link DECISION_LOOKUP_CHUNK} of them, through the
1899
+ * `payload_ref` index, finds their recorded requests and decisions. The
1900
+ * approval store is opened only when one of those requests still waits
1901
+ * for its decision; a request that was never recorded (a pruned or foreign
1902
+ * approval) is left alone. An approval of this thread that is never
1903
+ * decided keeps opening the store on its thread's turns until it leaves
1904
+ * the window of messages the host reads its ids from.
1905
+ */
1906
+ async recordDecisions() {
1907
+ const source = this.tracking.decisions;
1908
+ if (!source) return;
1909
+ const { db, tenantId } = this.tracking.tracked;
1910
+ let asked;
1911
+ try {
1912
+ asked = [...new Set(await source.asked())].filter((id) => typeof id === "string" && id !== "");
1913
+ } catch {
1914
+ return;
1915
+ }
1916
+ const waiting = /* @__PURE__ */ new Map();
1917
+ for (let at = 0; at < asked.length; at += DECISION_LOOKUP_CHUNK) {
1918
+ const refs = asked.slice(at, at + DECISION_LOOKUP_CHUNK).map(approvalRef);
1919
+ const marks = refs.map((_, i) => `$${i + 1}`).join(", ");
1920
+ const tenant = tenantId === null ? "IS NULL" : `= $${refs.length + 1}`;
1921
+ let events;
1922
+ try {
1923
+ events = rowsOf(await db.query(`SELECT e.id AS id, e.name AS name, e.status AS status,
1924
+ e.payload_ref AS payload_ref
1925
+ FROM _smrt_ai_run_events e
1926
+ JOIN _smrt_ai_runs r ON r.id = e.run_id
1927
+ WHERE e.payload_ref IN (${marks})
1928
+ AND e.type = 'approval'
1929
+ AND r.tenant_id ${tenant}
1930
+ ORDER BY e.created_at, e.id`, ...refs, ...tenantId === null ? [] : [tenantId]));
1931
+ } catch {
1932
+ continue;
1933
+ }
1934
+ const decidedRefs = new Set(events.filter((event) => event.status !== "requested").map((event) => String(event.payload_ref)));
1935
+ for (const event of events) {
1936
+ const ref = String(event.payload_ref);
1937
+ if (event.status === "requested" && !decidedRefs.has(ref) && !waiting.has(ref)) waiting.set(ref, event);
1938
+ }
1939
+ }
1940
+ if (waiting.size === 0) return;
1941
+ let decided;
1942
+ try {
1943
+ decided = await source.decided();
1944
+ } catch {
1945
+ return;
1946
+ }
1947
+ for (const decision of decided) {
1948
+ const ref = approvalRef(decision.approvalId);
1949
+ const request = waiting.get(ref);
1950
+ if (!request) continue;
1951
+ waiting.delete(ref);
1952
+ await this.append({
1953
+ type: "approval",
1954
+ name: typeof request.name === "string" ? request.name : null,
1955
+ status: decision.status,
1956
+ parentEventId: String(request.id),
1957
+ payloadRef: ref
1958
+ });
1959
+ }
1960
+ }
1961
+ /**
1962
+ * End the run. A turn that ends for any reason but a cancellation or a
1963
+ * failure is `done`, an approval still pending included.
1964
+ */
1965
+ async finish(outcome, options = {}) {
1966
+ if (this.ended) return;
1967
+ this.ended = true;
1968
+ const { db } = this.tracking.tracked;
1969
+ try {
1970
+ if (outcome === "cancelled") await stopAiRun(db, this.runId, { reason: "interrupted" });
1971
+ else if (outcome === "failed") await finishAiRun(db, this.runId, {
1972
+ status: "failed",
1973
+ stopReason: "error"
1974
+ });
1975
+ else await finishAiRun(db, this.runId, {
1976
+ status: "done",
1977
+ ...options.degraded ? { degraded: true } : {}
1978
+ });
1979
+ } catch {}
1980
+ await this.closeHandoff();
1981
+ }
1982
+ /** End the parent's `handoff` with how this child run actually ended. */
1983
+ async closeHandoff() {
1984
+ const parent = this.tracking.parent;
1985
+ if (!parent || !this.handoffEventId) return;
1986
+ try {
1987
+ const run = await getAiRun(this.tracking.tracked.db, this.runId);
1988
+ const status = run?.status === "done" ? "done" : run?.status === "cancelled" ? "cancelled" : run?.status === "failed" ? "failed" : "stopped";
1989
+ await closeAiRunHandoff(parent.context.db, parent.context.runId, this.handoffEventId, status);
1990
+ if (run && (run.status === "stopped" || run.status === "cancelled")) await stopAiRunForChild(parent.context.db, parent.context.runId, aiRunStoppedError(run));
1991
+ } catch {}
1992
+ }
1993
+ };
1994
+ //#endregion
1572
1995
  //#region src/assistant-turn-driver.ts
1996
+ function engineInputChars(systemPrompt, history, userMessage) {
1997
+ let chars = (systemPrompt ?? "").length + userMessage.length;
1998
+ for (const message of history) chars += typeof message.content === "string" ? message.content.length : JSON.stringify(message.content ?? "").length;
1999
+ return chars;
2000
+ }
2001
+ function cancelled() {
2002
+ return Object.assign(/* @__PURE__ */ new Error("The turn was cancelled."), { name: "AbortError" });
2003
+ }
1573
2004
  async function runExternalAssistantAttempt(options, emit, serialize, describe, report) {
1574
2005
  if (options.resume) throw new AssistantTurnUserError("External turns cannot resume browser tool calls.", "driver_resume_unsupported");
1575
2006
  const userMessage = options.userMessage?.trim();
@@ -1578,10 +2009,15 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1578
2009
  if (!driver) throw new Error("An external turn needs a driver.");
1579
2010
  if (driver.waitForApproval && options.approvals) throw new Error("A host-owned approval observer cannot be combined with another approval authority.");
1580
2011
  const attempt = new AbortController();
1581
- const signal = options.signal ? AbortSignal.any([options.signal, attempt.signal]) : attempt.signal;
2012
+ const callTimeout = new AbortController();
2013
+ const signal = AbortSignal.any([
2014
+ options.signal,
2015
+ attempt.signal,
2016
+ callTimeout.signal
2017
+ ].filter((value) => value !== void 0));
1582
2018
  let escalation;
1583
2019
  const completedHistory = [];
1584
- const accounting = options[WORK_RUN_ACCOUNTING] ?? {
2020
+ const accounting = options[TURN_ACCOUNTING] ?? {
1585
2021
  startedAt: Date.now(),
1586
2022
  tokens: 0,
1587
2023
  usageKnown: true,
@@ -1589,10 +2025,9 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1589
2025
  };
1590
2026
  options = {
1591
2027
  ...options,
1592
- [WORK_RUN_ACCOUNTING]: accounting
2028
+ [TURN_ACCOUNTING]: accounting
1593
2029
  };
1594
2030
  let observed;
1595
- const startedAt = accounting.startedAt;
1596
2031
  const allowed = new Set(options.principal.allowedTools ?? []);
1597
2032
  const context = {
1598
2033
  thread: options.thread,
@@ -1605,14 +2040,14 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1605
2040
  tools: (options.tools ?? []).filter((tool) => allowed.has(tool.slug) && isManifestToolEnabled(tool, options.principal.tenantId)),
1606
2041
  extraTools: (options.extraTools ?? []).filter((tool) => allowed.has(tool.slug)),
1607
2042
  signal,
1608
- workProfile: options.workProfile,
2043
+ ...options.selection ? { selection: options.selection } : {},
1609
2044
  beforeToolExecution(name) {
1610
2045
  const tool = [...context.tools, ...context.extraTools].find((tool2) => tool2.slug === name);
1611
2046
  if (!tool) throw new Error("The tool is not offered to this turn.");
1612
2047
  try {
1613
- assertWorkProfileTool(options, tool);
2048
+ assertToolRunType(options, tool);
1614
2049
  } catch (error) {
1615
- if (error instanceof WorkProfileEscalation) {
2050
+ if (error instanceof ToolRunTypeRefusal) {
1616
2051
  escalation = error;
1617
2052
  attempt.abort();
1618
2053
  }
@@ -1672,8 +2107,8 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1672
2107
  return wire;
1673
2108
  };
1674
2109
  const callbacks = {
1675
- execution(metadata) {
1676
- observed = metadata;
2110
+ execution(execution) {
2111
+ observed = execution;
1677
2112
  },
1678
2113
  text(delta) {
1679
2114
  if (!active() || !delta) return;
@@ -1683,16 +2118,16 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1683
2118
  text: delta
1684
2119
  });
1685
2120
  },
1686
- toolCall: (call) => enqueue(async () => {
1687
- if (!offered.has(call.name) || !enabled(call.name) || calls.has(call.id)) throw new Error("The external driver reported an unoffered or duplicate tool call.");
1688
- calls.set(call.id, structuredClone(call));
1689
- const label = describe(call.name, call.args);
2121
+ toolCall: (call2) => enqueue(async () => {
2122
+ if (!offered.has(call2.name) || !enabled(call2.name) || calls.has(call2.id)) throw new Error("The external driver reported an unoffered or duplicate tool call.");
2123
+ calls.set(call2.id, structuredClone(call2));
2124
+ const label = describe(call2.name, call2.args);
1690
2125
  emit({
1691
2126
  type: "step",
1692
2127
  step: {
1693
2128
  kind: "tool_call",
1694
- callId: call.id,
1695
- tool: call.name,
2129
+ callId: call2.id,
2130
+ tool: call2.name,
1696
2131
  label,
1697
2132
  location: "server"
1698
2133
  }
@@ -1706,32 +2141,32 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1706
2141
  }
1707
2142
  });
1708
2143
  await persist(label, "tool_call", {
1709
- id: call.id,
1710
- name: call.name,
1711
- args: call.args
2144
+ id: call2.id,
2145
+ name: call2.name,
2146
+ args: call2.args
1712
2147
  });
1713
2148
  }),
1714
2149
  toolResult: (result) => enqueue(async () => {
1715
- const call = calls.get(result.id);
1716
- if (!call || completed.has(result.id)) throw new Error("The external driver reported an unmatched tool result.");
1717
- if (result.ok && !enabled(call.name)) throw new Error("The external tool model is no longer enabled.");
1718
- if (result.ok && context.requiresApproval(call.name, call.args) && !approved.has(call.id)) throw new Error("A protected tool result requires an owner decision.");
2150
+ const call2 = calls.get(result.id);
2151
+ if (!call2 || completed.has(result.id)) throw new Error("The external driver reported an unmatched tool result.");
2152
+ if (result.ok && !enabled(call2.name)) throw new Error("The external tool model is no longer enabled.");
2153
+ if (result.ok && context.requiresApproval(call2.name, call2.args) && !approved.has(call2.id)) throw new Error("A protected tool result requires an owner decision.");
1719
2154
  completed.add(result.id);
1720
2155
  completedHistory.push({
1721
2156
  role: "assistant",
1722
2157
  content: "",
1723
2158
  tool_calls: [{
1724
- id: call.id,
2159
+ id: call2.id,
1725
2160
  type: "function",
1726
2161
  function: {
1727
- name: call.name,
1728
- arguments: JSON.stringify(call.args)
2162
+ name: call2.name,
2163
+ arguments: JSON.stringify(call2.args)
1729
2164
  }
1730
2165
  }]
1731
2166
  }, {
1732
2167
  role: "tool",
1733
- tool_call_id: call.id,
1734
- name: call.name,
2168
+ tool_call_id: call2.id,
2169
+ name: call2.name,
1735
2170
  content: result.result ?? result.error ?? ""
1736
2171
  });
1737
2172
  const approval = approvals.get(result.id);
@@ -1740,9 +2175,9 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1740
2175
  type: "step",
1741
2176
  step: {
1742
2177
  kind: "tool_result",
1743
- callId: call.id,
1744
- tool: call.name,
1745
- label: describe(call.name, call.args, {
2178
+ callId: call2.id,
2179
+ tool: call2.name,
2180
+ label: describe(call2.name, call2.args, {
1746
2181
  ok: result.ok,
1747
2182
  observation: result.result
1748
2183
  }),
@@ -1750,14 +2185,14 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1750
2185
  ...result.error ? { error: result.error } : {}
1751
2186
  }
1752
2187
  });
1753
- const label = describe(call.name, call.args, {
2188
+ const label = describe(call2.name, call2.args, {
1754
2189
  ok: result.ok,
1755
2190
  observation: result.result
1756
2191
  });
1757
2192
  await persist(label, "tool_result", {
1758
- id: call.id,
1759
- name: call.name,
1760
- args: call.args,
2193
+ id: call2.id,
2194
+ name: call2.name,
2195
+ args: call2.args,
1761
2196
  status: result.ok ? "success" : "error",
1762
2197
  label
1763
2198
  });
@@ -1768,24 +2203,24 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1768
2203
  approved: false,
1769
2204
  reason: "cancelled"
1770
2205
  };
1771
- const call = calls.get(request.callId);
1772
- if (!call || call.name !== request.tool || completed.has(call.id) || approvalRequested.has(call.id)) throw new Error("The external driver requested approval for an unmatched tool call.");
1773
- approvalRequested.add(call.id);
1774
- const tool = [...context.tools, ...context.extraTools].find((tool2) => tool2.slug === call.name);
1775
- if (!tool || !enabled(call.name)) throw new Error("Approval requires an enabled offered tool.");
1776
- const bridge = options.approvals && context.requiresApproval(call.name, call.args) ? options.approvals : void 0;
2206
+ const call2 = calls.get(request.callId);
2207
+ if (!call2 || call2.name !== request.tool || completed.has(call2.id) || approvalRequested.has(call2.id)) throw new Error("The external driver requested approval for an unmatched tool call.");
2208
+ approvalRequested.add(call2.id);
2209
+ const tool = [...context.tools, ...context.extraTools].find((tool2) => tool2.slug === call2.name);
2210
+ if (!tool || !enabled(call2.name)) throw new Error("Approval requires an enabled offered tool.");
2211
+ const bridge = options.approvals && context.requiresApproval(call2.name, call2.args) ? options.approvals : void 0;
1777
2212
  const approval = bridge ? await bridge.request({
1778
- id: call.id,
2213
+ id: call2.id,
1779
2214
  tool,
1780
- args: call.args,
2215
+ args: call2.args,
1781
2216
  ...context.permissions ? { permissions: context.permissions } : {},
1782
2217
  ...options.originMessageId ? { originMessageId: options.originMessageId } : {}
1783
2218
  }) : request;
1784
- if (bridge) approvals.set(call.id, approval);
2219
+ if (bridge) approvals.set(call2.id, approval);
1785
2220
  await persist(approval.summary, "tool_call", {
1786
- id: call.id,
1787
- name: call.name,
1788
- args: call.args,
2221
+ id: call2.id,
2222
+ name: call2.name,
2223
+ args: call2.args,
1789
2224
  approval
1790
2225
  });
1791
2226
  emit({
@@ -1801,7 +2236,7 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1801
2236
  approved: false,
1802
2237
  reason: "cancelled"
1803
2238
  }))]);
1804
- if (decision.approved && !enabled(call.name)) {
2239
+ if (decision.approved && !enabled(call2.name)) {
1805
2240
  await bridge?.complete?.(approval, false, {
1806
2241
  status: "refused",
1807
2242
  error: "The approved tool is no longer enabled."
@@ -1811,7 +2246,7 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1811
2246
  reason: "model_disabled"
1812
2247
  };
1813
2248
  }
1814
- if (decision.approved) approved.add(call.id);
2249
+ if (decision.approved) approved.add(call2.id);
1815
2250
  return decision;
1816
2251
  },
1817
2252
  done(value) {
@@ -1826,6 +2261,23 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1826
2261
  terminal = true;
1827
2262
  }
1828
2263
  };
2264
+ let call;
2265
+ const turnRun = options[TURN_RUN];
2266
+ if (turnRun) {
2267
+ try {
2268
+ call = await turnRun.beginEngineCall({
2269
+ ...options.selection ? { selection: options.selection } : {},
2270
+ inputChars: engineInputChars(options.systemPrompt, options.history ?? [], userMessage),
2271
+ ...options.signal ? { signal: options.signal } : {}
2272
+ });
2273
+ } catch (error) {
2274
+ if (!isRunBudgetStop(error)) throw error;
2275
+ return endAtBudget(options, emit, serialize, report);
2276
+ }
2277
+ const limit = call.signal;
2278
+ if (limit?.aborted) callTimeout.abort();
2279
+ else limit?.addEventListener("abort", () => callTimeout.abort(), { once: true });
2280
+ }
1829
2281
  let onAbort = () => {};
1830
2282
  const aborted = new Promise((resolve) => {
1831
2283
  onAbort = resolve;
@@ -1851,12 +2303,43 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1851
2303
  failed = true;
1852
2304
  }
1853
2305
  }
1854
- const tokens = observed?.tokens ?? final?.workRun?.tokens ?? final?.usage?.totalTokens;
2306
+ if (call) {
2307
+ const seen2 = observed ?? final?.execution;
2308
+ const usage = final?.usage;
2309
+ const split = usage && usage.promptTokens + usage.completionTokens === usage.totalTokens ? {
2310
+ inputTokens: usage.promptTokens,
2311
+ outputTokens: usage.completionTokens
2312
+ } : {};
2313
+ const engineReport = {
2314
+ ...seen2?.model ? { model: seen2.model } : {},
2315
+ ...seen2?.requestedModel ? { requestedModel: seen2.requestedModel } : {},
2316
+ ...seen2?.tokens !== void 0 ? {
2317
+ tokens: seen2.tokens,
2318
+ ...seen2.inputTokens !== void 0 && seen2.outputTokens !== void 0 ? {
2319
+ inputTokens: seen2.inputTokens,
2320
+ outputTokens: seen2.outputTokens
2321
+ } : {}
2322
+ } : usage ? {
2323
+ tokens: usage.totalTokens,
2324
+ ...split
2325
+ } : {},
2326
+ ...seen2 ? { durationMs: seen2.durationMs } : {}
2327
+ };
2328
+ if (final && !failed && !signal.aborted && !escalation) await call.answered(engineReport);
2329
+ else {
2330
+ const timedOut = call.timedOut;
2331
+ const ended = await call.ended(failed && !signal.aborted ? failure : cancelled(), engineReport);
2332
+ if (timedOut) throw ended;
2333
+ }
2334
+ }
2335
+ const tokens = observed?.tokens ?? final?.execution?.tokens ?? final?.usage?.totalTokens;
1855
2336
  if (typeof tokens !== "number" || !Number.isFinite(tokens) || tokens < 0) accounting.usageKnown = false;
1856
2337
  else accounting.tokens += tokens;
1857
2338
  accounting.toolCalls += observed?.toolCalls ?? completed.size;
2339
+ const seen = observed ?? final?.execution;
2340
+ if (seen?.model) accounting.model = seen.model;
1858
2341
  if (escalation) {
1859
- escalation.workRun = observed ?? final?.workRun;
2342
+ escalation.execution = observed ?? final?.execution;
1860
2343
  escalation.messages = [
1861
2344
  ...context.history,
1862
2345
  {
@@ -1898,24 +2381,10 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1898
2381
  const formatted = !reply.fallback ? options.formatAssistantReply?.(reply.content) : void 0;
1899
2382
  const content = formatted?.content ?? reply.content;
1900
2383
  const stoppedReason = reply.fallback ? "empty" : "stop";
1901
- const { tokens: _tokens, ...observedMetadata } = observed ?? final.workRun ?? {};
1902
- const workRun = options.workProfile ? {
1903
- ...observedMetadata,
1904
- profile: options.workProfile.name,
1905
- engine: options.workProfile.engine,
1906
- effort: options.workProfile.effort,
1907
- durationMs: Date.now() - startedAt,
1908
- ...observed?.model ?? final.workRun?.model ? { model: observed?.model ?? final.workRun?.model } : {},
1909
- ...accounting.usageKnown ? { tokens: accounting.tokens } : {},
1910
- toolCalls: accounting.toolCalls
1911
- } : void 0;
1912
- if (workRun) try {
1913
- (options.onWorkRun ?? ((value) => console.info("assistant.workRun", value)))(workRun);
1914
- } catch {}
2384
+ reportExecution(options, turnExecution(options, accounting, observed ?? final.execution));
1915
2385
  const message = await persist(content, "text", void 0, {
1916
2386
  ...replyMetadataFor({ stoppedReason }, reply),
1917
- ...formatted?.metadata,
1918
- ...workRun ? { workRun } : {}
2387
+ ...formatted?.metadata
1919
2388
  });
1920
2389
  if (final.usage) try {
1921
2390
  options.onUsage?.(final.usage);
@@ -1939,24 +2408,49 @@ async function runExternalAssistantAttempt(options, emit, serialize, describe, r
1939
2408
  originMessageId: options.originMessageId
1940
2409
  };
1941
2410
  }
1942
- async function recordDesignHandoff(options, accepted, emit, serialize, observed) {
2411
+ async function endAtBudget(options, emit, serialize, report) {
2412
+ let message;
2413
+ const author = options.author;
2414
+ if (author) {
2415
+ message = serialize(await sendAgentReply(author.chatService, {
2416
+ tenantId: author.tenantId,
2417
+ agentSessionId: author.agentSessionId,
2418
+ threadId: author.threadId ?? null,
2419
+ replyToMessageId: options.originMessageId ?? null,
2420
+ kind: "assistant",
2421
+ content: TURN_BUDGET_REPLY,
2422
+ metadata: {
2423
+ ...replyMetadataFor({ stoppedReason: "budget" }, { content: TURN_BUDGET_REPLY }),
2424
+ ...author.metadata
2425
+ }
2426
+ }));
2427
+ emit({
2428
+ type: "message",
2429
+ message
2430
+ });
2431
+ }
2432
+ await report("completed");
2433
+ emit({
2434
+ type: "done",
2435
+ ...message ? { message } : {},
2436
+ stoppedReason: "budget"
2437
+ });
2438
+ emit({
2439
+ type: "status",
2440
+ status: {
2441
+ state: "done",
2442
+ label: "Done"
2443
+ }
2444
+ });
2445
+ return {
2446
+ stoppedReason: "budget",
2447
+ content: TURN_BUDGET_REPLY,
2448
+ originMessageId: options.originMessageId
2449
+ };
2450
+ }
2451
+ async function recordWorkflowHandoff(options, accepted, emit, serialize, observed) {
1943
2452
  const content = accepted.message ?? "Thinking this through";
1944
- const accounting = options[WORK_RUN_ACCOUNTING];
1945
- const profile = options.workProfile;
1946
- const model = observed?.model ?? accounting?.model;
1947
- const workRun = profile && accounting ? {
1948
- profile: profile.name,
1949
- engine: profile.engine,
1950
- effort: profile.effort,
1951
- ...model ? { model } : {},
1952
- ...observed?.fallback ? { fallback: observed.fallback } : {},
1953
- durationMs: Date.now() - accounting.startedAt,
1954
- toolCalls: accounting.toolCalls,
1955
- ...accounting.usageKnown ? { tokens: accounting.tokens } : {}
1956
- } : void 0;
1957
- if (workRun) try {
1958
- (options.onWorkRun ?? ((value) => console.info("assistant.workRun", value)))(workRun);
1959
- } catch {}
2453
+ reportExecution(options, turnExecution(options, options[TURN_ACCOUNTING], observed));
1960
2454
  let message;
1961
2455
  if (options.author) {
1962
2456
  const author = options.author;
@@ -1969,8 +2463,7 @@ async function recordDesignHandoff(options, accepted, emit, serialize, observed)
1969
2463
  content,
1970
2464
  metadata: {
1971
2465
  ...author.metadata,
1972
- designRunId: accepted.runId,
1973
- ...workRun ? { workRun } : {}
2466
+ runId: accepted.runId
1974
2467
  }
1975
2468
  }));
1976
2469
  emit({
@@ -1986,7 +2479,7 @@ async function recordDesignHandoff(options, accepted, emit, serialize, observed)
1986
2479
  async function runExternalAssistantTurn(options, emit, serialize, describe, report) {
1987
2480
  options = {
1988
2481
  ...options,
1989
- [WORK_RUN_ACCOUNTING]: options[WORK_RUN_ACCOUNTING] ?? {
2482
+ [TURN_ACCOUNTING]: options[TURN_ACCOUNTING] ?? {
1990
2483
  startedAt: Date.now(),
1991
2484
  tokens: 0,
1992
2485
  usageKnown: true,
@@ -1996,62 +2489,37 @@ async function runExternalAssistantTurn(options, emit, serialize, describe, repo
1996
2489
  try {
1997
2490
  return await runExternalAssistantAttempt(options, emit, serialize, describe, report);
1998
2491
  } catch (error) {
1999
- if (!(error instanceof WorkProfileEscalation) || !options.resolveWorkProfile && !options.onDesignEscalation) throw error;
2000
- if (options.onDesignEscalation) {
2001
- const accepted = await options.onDesignEscalation({
2002
- tool: error.tool,
2003
- history: error.messages ?? options.history ?? [],
2004
- userMessage: options.userMessage,
2005
- thread: options.thread,
2006
- originMessageId: options.originMessageId
2007
- });
2008
- const { content, message } = await recordDesignHandoff(options, accepted, emit, serialize, error.workRun);
2009
- emit({
2010
- type: "status",
2011
- status: {
2012
- state: "working",
2013
- label: content,
2014
- cancellable: true
2015
- }
2016
- });
2017
- await report("completed");
2018
- emit({
2019
- type: "done",
2020
- stoppedReason: "stop",
2021
- runId: accepted.runId,
2022
- ...message ? { message } : {}
2023
- });
2024
- return {
2025
- content,
2026
- stoppedReason: "stop",
2027
- originMessageId: options.originMessageId,
2028
- runId: accepted.runId
2029
- };
2030
- }
2031
- const workProfile = await options.resolveWorkProfile("design");
2032
- if (workProfile.name !== "design") throw new Error("Design escalation requires the design profile.");
2492
+ if (!(error instanceof ToolRunTypeRefusal)) throw error;
2493
+ if (!mayEscalateToWorkflow(options)) throw refusedInTurn(error);
2494
+ const accepted = await options.onWorkflowEscalation({
2495
+ tool: error.tool,
2496
+ history: error.messages ?? options.history ?? [],
2497
+ userMessage: options.userMessage,
2498
+ thread: options.thread,
2499
+ originMessageId: options.originMessageId
2500
+ });
2501
+ const { content, message } = await recordWorkflowHandoff(options, accepted, emit, serialize, error.execution);
2033
2502
  emit({
2034
2503
  type: "status",
2035
2504
  status: {
2036
2505
  state: "working",
2037
- label: "Thinking this through",
2506
+ label: content,
2038
2507
  cancellable: true
2039
2508
  }
2040
2509
  });
2041
- const runtime = await options.resolveWorkProfileRuntime?.(workProfile);
2042
- const next = {
2043
- ...options,
2044
- ...runtime,
2045
- workProfile,
2046
- history: error.messages ?? options.history
2510
+ await report("completed");
2511
+ emit({
2512
+ type: "done",
2513
+ stoppedReason: "stop",
2514
+ runId: accepted.runId,
2515
+ ...message ? { message } : {}
2516
+ });
2517
+ return {
2518
+ content,
2519
+ stoppedReason: "stop",
2520
+ originMessageId: options.originMessageId,
2521
+ runId: accepted.runId
2047
2522
  };
2048
- if (next.turnDriver) return runExternalAssistantAttempt(next, emit, serialize, describe, report);
2049
- const turn = runAssistantTurn(next);
2050
- while (true) {
2051
- const item = await turn.next();
2052
- if (item.done) return item.value;
2053
- emit(item.value);
2054
- }
2055
2523
  }
2056
2524
  }
2057
2525
  //#endregion
@@ -2176,6 +2644,25 @@ function providerErrorReplyText(error, fallback, signal) {
2176
2644
  }
2177
2645
  return typeof text === "string" && text.trim() ? text.trim() : void 0;
2178
2646
  }
2647
+ async function observeTurnRunEvent(run, event) {
2648
+ if (event.type === "step") {
2649
+ const { step } = event;
2650
+ if (step.kind === "tool_call") await run.step({
2651
+ type: "tool_call",
2652
+ slug: step.tool,
2653
+ callId: step.callId,
2654
+ location: step.location
2655
+ });
2656
+ else if (step.kind === "tool_result") await run.step({
2657
+ type: "tool_result",
2658
+ slug: step.tool,
2659
+ callId: step.callId,
2660
+ ok: step.ok,
2661
+ ...step.error ? { error: step.error } : {}
2662
+ });
2663
+ } else if (event.type === "approval_needed") await run.approvalRequested(event.approval, event.approval.callId);
2664
+ else if (event.type === "done") await run.replied(event.message?.id);
2665
+ }
2179
2666
  function defaultSerialize(message) {
2180
2667
  const candidate = message;
2181
2668
  return typeof candidate?.toJSON === "function" ? candidate.toJSON() : message;
@@ -2241,9 +2728,44 @@ async function* runAssistantTurn(options) {
2241
2728
  };
2242
2729
  const report = reporter(options, leg);
2243
2730
  const work = (async () => {
2731
+ let turnRun = null;
2732
+ let tracked = Promise.resolve();
2244
2733
  try {
2245
- result = await runTurn(options, emit, status, serialize, describe, leg);
2734
+ let runOptions = options;
2735
+ let runEmit = emit;
2736
+ if (options.tracking && (options.ai || options.turnDriver)) {
2737
+ try {
2738
+ turnRun = await AssistantTurnRun.open(options.budget ? {
2739
+ ...options.tracking,
2740
+ budget: options.budget
2741
+ } : options.tracking, { ...leg.originMessageId ? { originMessageId: leg.originMessageId } : {} });
2742
+ } catch (error) {
2743
+ if (error instanceof AiRunTrackingDisabledError) throw new AssistantTurnUserError("The assistant is unavailable: AI usage tracking is turned off.", "ai_tracking_disabled");
2744
+ throw error;
2745
+ }
2746
+ const run = turnRun;
2747
+ runOptions = options.turnDriver ? {
2748
+ ...options,
2749
+ [TURN_RUN]: run
2750
+ } : {
2751
+ ...options,
2752
+ ai: await run.client(options.selection)
2753
+ };
2754
+ runEmit = (event) => {
2755
+ tracked = tracked.then(() => observeTurnRunEvent(run, event));
2756
+ emit(event);
2757
+ };
2758
+ }
2759
+ result = await runTurn(runOptions, runEmit, status, serialize, describe, leg);
2760
+ if (turnRun) {
2761
+ await tracked;
2762
+ await turnRun.finish(result.stoppedReason === "cancelled" ? "cancelled" : result.stoppedReason === "error" ? "failed" : "done");
2763
+ }
2246
2764
  } catch (error) {
2765
+ if (turnRun) {
2766
+ await tracked;
2767
+ await turnRun.finish("failed");
2768
+ }
2247
2769
  const wire = wireError(error, options.onError ?? defaultLogError);
2248
2770
  if (leg.started) await report("failed");
2249
2771
  emit({
@@ -2299,28 +2821,17 @@ function reporter(options, leg) {
2299
2821
  };
2300
2822
  }
2301
2823
  async function runTurn(options, emit, status, serialize, describe, leg) {
2302
- if (options.workProfile) {
2303
- const profile = options.workProfile;
2304
- options = {
2305
- ...options,
2306
- model: profile.model,
2307
- maxSteps: profile.budgets.maxSteps,
2308
- maxTokens: profile.budgets.maxTokens,
2309
- maxTurnTokens: profile.budgets.maxTurnTokens,
2310
- maxTurnMs: profile.budgets.turnTimeoutMs,
2311
- requestTimeoutMs: profile.budgets.requestTimeoutMs
2312
- };
2313
- }
2824
+ options = applyTurnBudget(options);
2314
2825
  options = {
2315
2826
  ...options,
2316
- [WORK_RUN_ACCOUNTING]: options[WORK_RUN_ACCOUNTING] ?? {
2827
+ [TURN_ACCOUNTING]: options[TURN_ACCOUNTING] ?? {
2317
2828
  startedAt: Date.now(),
2318
2829
  tokens: 0,
2319
2830
  usageKnown: true,
2320
2831
  toolCalls: 0
2321
2832
  }
2322
2833
  };
2323
- const accounting = options[WORK_RUN_ACCOUNTING];
2834
+ const accounting = options[TURN_ACCOUNTING];
2324
2835
  const { principal, author } = options;
2325
2836
  const report = reporter(options, leg);
2326
2837
  const now = options.now ?? (() => Date.now());
@@ -2330,16 +2841,16 @@ async function runTurn(options, emit, status, serialize, describe, leg) {
2330
2841
  label: "Thinking…",
2331
2842
  cancellable: true
2332
2843
  }));
2333
- if (options.deferDesignTurn && options.workProfile?.name === "design" && options.onDesignEscalation && !options.resume) {
2844
+ if (options.deferWorkflowTurn && options.onWorkflowEscalation && !options.resume) {
2334
2845
  await report("running");
2335
- const accepted = await options.onDesignEscalation({
2846
+ const accepted = await options.onWorkflowEscalation({
2336
2847
  tool: "",
2337
2848
  history: options.history ?? [],
2338
2849
  userMessage: options.userMessage,
2339
2850
  thread: options.thread,
2340
2851
  originMessageId: options.originMessageId
2341
2852
  });
2342
- const { content: content2, message } = await recordDesignHandoff(options, accepted, emit, serialize);
2853
+ const { content: content2, message } = await recordWorkflowHandoff(options, accepted, emit, serialize);
2343
2854
  emit(status({
2344
2855
  state: "working",
2345
2856
  label: content2,
@@ -2438,7 +2949,7 @@ async function runTurn(options, emit, status, serialize, describe, leg) {
2438
2949
  };
2439
2950
  const registered = /* @__PURE__ */ new Set();
2440
2951
  const resultLabels = /* @__PURE__ */ new Map();
2441
- const sendAgentReply = author ? (await import("./ChatService-CeOVzOqN.js").then((n) => n.r)).sendAgentReply : null;
2952
+ const sendAgentReply = author ? (await import("./ChatService-CDLAEJms.js").then((n) => n.r)).sendAgentReply : null;
2442
2953
  const collapseRecovered = author?.collapseRecoveredFailures === true;
2443
2954
  const heldFailures = [];
2444
2955
  const persistInvocation = async (invocation, failure) => {
@@ -2498,13 +3009,13 @@ async function runTurn(options, emit, status, serialize, describe, leg) {
2498
3009
  };
2499
3010
  const runLoop = () => runToolLoop({
2500
3011
  ai: options.ai,
2501
- toolResultChars: options.workProfile?.budgets.toolResultChars,
2502
- ...options.workProfile ? { reasoning: { effort: options.workProfile.effort } } : {},
3012
+ toolResultChars: options.toolResultChars,
3013
+ ...turnEffort(options) ? { reasoning: { effort: turnEffort(options) } } : {},
2503
3014
  messages,
2504
3015
  tools: options.tools ?? [],
2505
3016
  extraTools,
2506
3017
  clientTools,
2507
- beforeToolExecution: (tool) => assertWorkProfileTool(options, tool),
3018
+ beforeToolExecution: (tool) => assertToolRunType(options, tool),
2508
3019
  holdTool: async ({ id, tool, args, permissions, authorize }) => {
2509
3020
  if (!requiresOwnerApproval(tool, args, options.approvals?.policy ?? options.approvalPolicy)) return;
2510
3021
  await authorize();
@@ -2665,64 +3176,37 @@ async function runTurn(options, emit, status, serialize, describe, leg) {
2665
3176
  try {
2666
3177
  loop2 = await runLoop();
2667
3178
  } catch (error) {
2668
- if (!(error instanceof WorkProfileEscalation) || !options.resolveWorkProfile && !options.onDesignEscalation) throw error;
2669
- if (options.onDesignEscalation) {
2670
- const accepted = await options.onDesignEscalation({
2671
- tool: error.tool,
2672
- history: error.messages ?? options.history ?? [],
2673
- userMessage: options.userMessage,
2674
- thread: options.thread,
2675
- originMessageId: options.originMessageId
2676
- });
2677
- const { content: content2, message } = await recordDesignHandoff(options, accepted, emit, serialize);
2678
- emit({
2679
- type: "status",
2680
- status: {
2681
- state: "working",
2682
- label: content2,
2683
- cancellable: true
2684
- }
2685
- });
2686
- await report("completed");
2687
- emit({
2688
- type: "done",
2689
- stoppedReason: "stop",
2690
- runId: accepted.runId,
2691
- ...message ? { message } : {}
2692
- });
2693
- return {
2694
- content: content2,
2695
- stoppedReason: "stop",
2696
- originMessageId: options.originMessageId,
2697
- runId: accepted.runId
2698
- };
2699
- }
2700
- const profile = await options.resolveWorkProfile("design");
2701
- if (profile.name !== "design") throw new Error("Design escalation requires the design profile.");
2702
- const runtime = await options.resolveWorkProfileRuntime?.(profile);
2703
- options = {
2704
- ...options,
2705
- ...runtime,
2706
- workProfile: profile,
2707
- model: profile.model,
2708
- maxSteps: profile.budgets.maxSteps,
2709
- maxTokens: profile.budgets.maxTokens,
2710
- maxTurnTokens: profile.budgets.maxTurnTokens,
2711
- maxTurnMs: profile.budgets.turnTimeoutMs,
2712
- requestTimeoutMs: profile.budgets.requestTimeoutMs
3179
+ if (!(error instanceof ToolRunTypeRefusal)) throw error;
3180
+ if (!mayEscalateToWorkflow(options)) throw refusedInTurn(error);
3181
+ const accepted = await options.onWorkflowEscalation({
3182
+ tool: error.tool,
3183
+ history: error.messages ?? options.history ?? [],
3184
+ userMessage: options.userMessage,
3185
+ thread: options.thread,
3186
+ originMessageId: options.originMessageId
3187
+ });
3188
+ const { content: content2, message } = await recordWorkflowHandoff(options, accepted, emit, serialize);
3189
+ emit({
3190
+ type: "status",
3191
+ status: {
3192
+ state: "working",
3193
+ label: content2,
3194
+ cancellable: true
3195
+ }
3196
+ });
3197
+ await report("completed");
3198
+ emit({
3199
+ type: "done",
3200
+ stoppedReason: "stop",
3201
+ runId: accepted.runId,
3202
+ ...message ? { message } : {}
3203
+ });
3204
+ return {
3205
+ content: content2,
3206
+ stoppedReason: "stop",
3207
+ originMessageId: options.originMessageId,
3208
+ runId: accepted.runId
2713
3209
  };
2714
- messages = error.messages ?? messages;
2715
- initialTokens = accounting.tokens;
2716
- emit(status({
2717
- state: "working",
2718
- label: "Thinking this through",
2719
- cancellable: true
2720
- }));
2721
- if (options.turnDriver) return runExternalAssistantTurn({
2722
- ...options,
2723
- history: messages
2724
- }, emit, serialize, describe, report);
2725
- loop2 = await runLoop();
2726
3210
  }
2727
3211
  outcome = { loop: loop2 };
2728
3212
  } catch (failure) {
@@ -2730,9 +3214,11 @@ async function runTurn(options, emit, status, serialize, describe, leg) {
2730
3214
  }
2731
3215
  for (const held of heldFailures.splice(0)) await persistInvocation(held.invocation, held.failure);
2732
3216
  if ("failure" in outcome) {
2733
- const text = providerErrorReplyText(outcome.failure, options.providerErrorFallback, options.signal);
3217
+ const budgetStop = isRunBudgetStop(outcome.failure);
3218
+ const stoppedReason = budgetStop ? "budget" : "provider_error";
3219
+ const text = budgetStop ? TURN_BUDGET_REPLY : providerErrorReplyText(outcome.failure, options.providerErrorFallback, options.signal);
2734
3220
  if (text === void 0) throw outcome.failure;
2735
- try {
3221
+ if (!budgetStop) try {
2736
3222
  (options.onError ?? defaultLogError)(outcome.failure);
2737
3223
  } catch {}
2738
3224
  let finalMessage2;
@@ -2745,7 +3231,7 @@ async function runTurn(options, emit, status, serialize, describe, leg) {
2745
3231
  kind: "assistant",
2746
3232
  content: text,
2747
3233
  metadata: {
2748
- ...replyMetadataFor({ stoppedReason: "provider_error" }, {
3234
+ ...budgetStop ? replyMetadataFor({ stoppedReason }, { content: text }) : replyMetadataFor({ stoppedReason: "provider_error" }, {
2749
3235
  content: text,
2750
3236
  fallback: "provider_error"
2751
3237
  }),
@@ -2761,14 +3247,14 @@ async function runTurn(options, emit, status, serialize, describe, leg) {
2761
3247
  emit({
2762
3248
  type: "done",
2763
3249
  ...finalMessage2 ? { message: finalMessage2 } : {},
2764
- stoppedReason: "provider_error"
3250
+ stoppedReason
2765
3251
  });
2766
3252
  emit(status({
2767
3253
  state: "done",
2768
3254
  label: "Done"
2769
3255
  }));
2770
3256
  return {
2771
- stoppedReason: "provider_error",
3257
+ stoppedReason,
2772
3258
  content: text,
2773
3259
  ...originMessageId ? { originMessageId } : {}
2774
3260
  };
@@ -2837,26 +3323,7 @@ async function runTurn(options, emit, status, serialize, describe, leg) {
2837
3323
  ...replyMetadataFor(loop, reply),
2838
3324
  ...formatted?.metadata
2839
3325
  };
2840
- if (options.workProfile) {
2841
- const workRun = {
2842
- profile: options.workProfile.name,
2843
- engine: options.workProfile.engine,
2844
- ...accounting.model ? { model: accounting.model } : {},
2845
- effort: options.workProfile.effort,
2846
- durationMs: Date.now() - accounting.startedAt,
2847
- ...accounting.usageKnown ? { tokens: accounting.tokens } : {},
2848
- toolCalls: accounting.toolCalls
2849
- };
2850
- const observed = options.ai?.getWorkRunMetadata?.();
2851
- if (observed) Object.assign(workRun, {
2852
- model: accounting.model ?? observed.model,
2853
- fallback: observed.fallback
2854
- });
2855
- replyMetadata.workRun = workRun;
2856
- try {
2857
- (options.onWorkRun ?? ((value) => console.info("assistant.workRun", value)))(workRun);
2858
- } catch {}
2859
- }
3326
+ reportExecution(options, turnExecution(options, accounting, options.ai?.getEngineExecution?.()));
2860
3327
  let finalMessage;
2861
3328
  if (author && sendAgentReply) {
2862
3329
  finalMessage = serialize(await sendAgentReply(author.chatService, {
@@ -2952,6 +3419,27 @@ function createAssistantTurnResponse(events, options = {}) {
2952
3419
  headers
2953
3420
  });
2954
3421
  }
3422
+ function applyTurnBudget(options) {
3423
+ const budget = options.budget;
3424
+ if (!budget) return options;
3425
+ return {
3426
+ ...options,
3427
+ ...budget.maxSteps !== void 0 ? { maxSteps: budget.maxSteps } : {},
3428
+ ...budget.maxTokens !== void 0 ? { maxTurnTokens: budget.maxTokens } : {},
3429
+ ...budget.maxDurationMs !== void 0 ? { maxTurnMs: budget.maxDurationMs } : {},
3430
+ ...budget.callTimeoutMs !== void 0 ? { requestTimeoutMs: budget.callTimeoutMs } : {}
3431
+ };
3432
+ }
3433
+ function turnEffort(options) {
3434
+ return options.tracking?.prompt.ai.effort ?? options.selection?.effort;
3435
+ }
3436
+ function refusedInTurn(error) {
3437
+ return new AssistantTurnUserError("This change needs a workflow run, and chat cannot start one here. Turn on handing changes to a workflow run in the assistant settings, then ask again.", error.code);
3438
+ }
3439
+ var TURN_BUDGET_REPLY = "I reached the limit for this turn before finishing. Ask again to continue.";
3440
+ function isRunBudgetStop(error) {
3441
+ return error instanceof AiRunStoppedError && error.status === "stopped" && typeof error.stopReason === "string" && error.stopReason.startsWith("max_");
3442
+ }
2955
3443
  //#endregion
2956
3444
  //#region src/persona-conversation.ts
2957
3445
  function conversationPersonaFromResolved(resolved) {
@@ -3105,7 +3593,7 @@ async function bindPersonaToSession(options) {
3105
3593
  });
3106
3594
  }
3107
3595
  async function authorConversationReply(input) {
3108
- const { sendAgentReply } = await import("./ChatService-CeOVzOqN.js").then((n) => n.r);
3596
+ const { sendAgentReply } = await import("./ChatService-CDLAEJms.js").then((n) => n.r);
3109
3597
  const toolMessages = [];
3110
3598
  for (const invocation of input.result.invocations) {
3111
3599
  if (!invocation.ok) {
@@ -3566,6 +4054,6 @@ function corsHeaders(request, allowedOrigins, allowCredentials) {
3566
4054
  return headers;
3567
4055
  }
3568
4056
  //#endregion
3569
- export { isFallbackReply as $, DEFAULT_EMPTY_ANSWER_FALLBACK as A, MAX_SERVER_TOOL_OBSERVATION_CHARS as B, DEFAULT_CONTINUATION_TTL_MS as C, createSessionContinuationStore as D, createMemoryContinuationStore as E, MAX_CLIENT_TOOLS as F, TOOL_CALL_DEDUPED_REJECTED_NOTE as G, MAX_TOOL_LOOP_REASONING_CHARS as H, MAX_CLIENT_TOOL_RESULT_CHARS as I, TOOL_LOOP_REPEATED_CALLS_INSTRUCTION as J, TOOL_EXECUTION_ERROR_HINT as K, MAX_CLIENT_TOOL_SCHEMA_BYTES as L, DEFAULT_MAX_STEPS as M, FALLBACK_HISTORY_PLACEHOLDER as N, runAssistantTurn as O, FALLBACK_REPLY_METADATA_KEY as P, invokeManifestTool as Q, MAX_DEDUPED_CALLS_PER_TURN as R, DEFAULT_ASSISTANT_TURN_HEARTBEAT_MS as S, assertWorkProfileTool as St, createAssistantTurnResponse as T, SERVER_TOOL_OBSERVATION_TRUNCATED_MARKER as U, MAX_TOOL_FAILURE_ARGS_CHARS as V, TOOL_CALL_DEDUPED_NOTE as W, buildManifestToolCatalog as X, appendClientToolResults as Y, classifyToolError as Z, resolveConversationInstructions as _, createRuntimeReportTools as _t, DEFAULT_CHAT_STREAM_HEARTBEAT_MS as a, runToolLoop as at, AssistantTurnUserError as b, chatUnconfiguredBody as bt, createChatStreamHandler as c, toolFailureRecord as ct, bindPersonaToSession as d, RUNTIME_REPORT_LIST_FUNCTION_NAME as dt, isManifestToolEnabled as et, conversationPersonaFromAgentPersona as f, RUNTIME_REPORT_LIST_TOOL_SLUG as ft, recallPersonaMemory as g, RUNTIME_REPORT_SOURCES_TOOL_SLUG as gt, principalBindingFor as h, RUNTIME_REPORT_SOURCES_FUNCTION_NAME as ht, ChatStreamUnauthorizedError as i, resolveTurnReply as it, DEFAULT_MAX_REPEATED_CALLS as j, CLIENT_TOOL_RESULT_GUIDANCE as k, encodeChatStreamEvent as l, RUNTIME_REPORT_DEFINE_FUNCTION_NAME as lt, formatRecalledMemory as m, RUNTIME_REPORT_RUN_TOOL_SLUG as mt, ChatStreamBadRequestError as n, replyContentFor as nt, MAX_CHAT_STREAM_CONTENT_LENGTH as o, sanitizeClientToolDeclarations as ot, conversationPersonaFromResolved as p, RUNTIME_REPORT_RUN_FUNCTION_NAME as pt, TOOL_LOOP_ANSWER_NOW_INSTRUCTION as q, ChatStreamError as r, replyMetadataFor as rt, MAX_CHAT_STREAM_MESSAGES as s, toolFailureAuditMetadata as st, CHAT_STREAM_TIMEOUT_ERROR as t, manifestToolToAITool as tt, runChatConversationStream as u, RUNTIME_REPORT_DEFINE_TOOL_SLUG as ut, runPersonaConversationTurn as v, CHAT_AI_UNAVAILABLE_CODE as vt, SESSION_CONTINUATIONS_FIELD as w, CONTINUATION_CLAIM_TTL_MS as x, WorkProfileEscalation as xt, ASSISTANT_TURN_GENERIC_ERROR as y, chatUnavailableBody as yt, MAX_REPEATED_CALLS_LIMIT as z };
4057
+ export { TOOL_CALL_DEDUPED_REJECTED_NOTE as $, CHAT_ASSISTANT_PROMPT_KEY as A, assertToolRunType as At, DEFAULT_MAX_STEPS as B, DEFAULT_CONTINUATION_TTL_MS as C, RUNTIME_REPORT_SOURCES_FUNCTION_NAME as Ct, createSessionContinuationStore as D, chatUnavailableBody as Dt, createMemoryContinuationStore as E, CHAT_AI_UNAVAILABLE_CODE as Et, resolveChatAssistantPrompt as F, MAX_CLIENT_TOOL_SCHEMA_BYTES as G, FALLBACK_REPLY_METADATA_KEY as H, resolveChatAssistantTier as I, MAX_SERVER_TOOL_OBSERVATION_CHARS as J, MAX_DEDUPED_CALLS_PER_TURN as K, CLIENT_TOOL_RESULT_GUIDANCE as L, chatAssistantSystemPrompt as M, chatAssistantSystemText as N, runAssistantTurn as O, chatUnconfiguredBody as Ot, chatClientForTracking as P, TOOL_CALL_DEDUPED_NOTE as Q, DEFAULT_EMPTY_ANSWER_FALLBACK as R, DEFAULT_ASSISTANT_TURN_HEARTBEAT_MS as S, RUNTIME_REPORT_RUN_TOOL_SLUG as St, createAssistantTurnResponse as T, createRuntimeReportTools as Tt, MAX_CLIENT_TOOLS as U, FALLBACK_HISTORY_PLACEHOLDER as V, MAX_CLIENT_TOOL_RESULT_CHARS as W, MAX_TOOL_LOOP_REASONING_CHARS as X, MAX_TOOL_FAILURE_ARGS_CHARS as Y, SERVER_TOOL_OBSERVATION_TRUNCATED_MARKER as Z, resolveConversationInstructions as _, RUNTIME_REPORT_DEFINE_FUNCTION_NAME as _t, DEFAULT_CHAT_STREAM_HEARTBEAT_MS as a, classifyToolError as at, AssistantTurnUserError as b, RUNTIME_REPORT_LIST_TOOL_SLUG as bt, createChatStreamHandler as c, isManifestToolEnabled as ct, bindPersonaToSession as d, replyMetadataFor as dt, TOOL_EXECUTION_ERROR_HINT as et, conversationPersonaFromAgentPersona as f, resolveTurnReply as ft, recallPersonaMemory as g, toolFailureRecord as gt, principalBindingFor as h, toolFailureAuditMetadata as ht, ChatStreamUnauthorizedError as i, buildManifestToolCatalog as it, CHAT_TURN_DEFINITION_KEY as j, toolRunTypes as jt, AssistantTurnRun as k, ToolRunTypeRefusal as kt, encodeChatStreamEvent as l, manifestToolToAITool as lt, formatRecalledMemory as m, sanitizeClientToolDeclarations as mt, ChatStreamBadRequestError as n, TOOL_LOOP_REPEATED_CALLS_INSTRUCTION as nt, MAX_CHAT_STREAM_CONTENT_LENGTH as o, invokeManifestTool as ot, conversationPersonaFromResolved as p, runToolLoop as pt, MAX_REPEATED_CALLS_LIMIT as q, ChatStreamError as r, appendClientToolResults as rt, MAX_CHAT_STREAM_MESSAGES as s, isFallbackReply as st, CHAT_STREAM_TIMEOUT_ERROR as t, TOOL_LOOP_ANSWER_NOW_INSTRUCTION as tt, runChatConversationStream as u, replyContentFor as ut, runPersonaConversationTurn as v, RUNTIME_REPORT_DEFINE_TOOL_SLUG as vt, SESSION_CONTINUATIONS_FIELD as w, RUNTIME_REPORT_SOURCES_TOOL_SLUG as wt, CONTINUATION_CLAIM_TTL_MS as x, RUNTIME_REPORT_RUN_FUNCTION_NAME as xt, ASSISTANT_TURN_GENERIC_ERROR as y, RUNTIME_REPORT_LIST_FUNCTION_NAME as yt, DEFAULT_MAX_REPEATED_CALLS as z };
3570
4058
 
3571
- //# sourceMappingURL=chat-stream-Cl8JV-K0.js.map
4059
+ //# sourceMappingURL=chat-stream-BJbmqHsu.js.map