@happyvertical/smrt-chat (笑声) (掌声)
聊天室,DMs,线程,以及S-m-r-t框架的代理对话. 支持公共,私人,DM,以及代理类房间,带有线性消息,反应,以及代理会话,带有工具白名单.
安装
pnpm add @happyvertical/smrt-chat
助理转向司机
助手默认使用其已存在的模型/工具循环. 供应a ai
客户端或每家工厂申请模型适配器,或 turnDriver 用于
拥有其循环的外部代理 :
import { mountAssistantRoutes } from '@happyvertical/smrt-chat/sveltekit';
export const { GET, POST } = mountAssistantRoutes({
turnDriver: {
async run(context, progress) {
// A host adapter forwards the agent's callbacks and AbortSignal.
context.signal.throwIfAborted();
progress.text('Hello from your agent.');
progress.done({ text: 'Hello from your agent.' });
},
},
allowedTools: [],
});
resolveTurnDriver(ctx) 每个认证的请求/用户选择一个驱动程序.
聊天保持线程/消息持续, 工具允许列表, 码头的流线
格式并停止行为。 司机收到历史 新的用户信息,
系统引导、线程身份、主线、服务器工具以及中止
信号 等待工具调用/结果调用以编写记录。 这个
approvalNeeded 回调和 waitForApproval 主机钩子保留持久
业主-审批合并;无钩子审批的,不予批准. 持久核准
存储和用户界面不是通过此连接实现的.
见 转动驱动器合同和召回实例, (中文(简体) ), 包括 MCP 授权责任、引擎状态和浏览器 继续限制.
地表桥安全
这个 ./data-surface-bridge 入口是浏览器数据的服务器半个
表面协议。 提供运输适配器 subscribe 回调
提供来自认证连接状态(例如
绑定的 WebSocket 会话或原产地已检查 postMessage ) (中文(简体) ). 从不复制
sessionId 或者说 source 从不可信消息进入元数据和路径
send 只能到认证的对等点.
桥对每个命令、确认和事件进行验证和限制
使用共享标识符限制从
@happyvertical/smrt-ui/data-surface。 。 。 . authorize 继续申请
责任必须结束。 命令范围为配置
会话/ source, 由 TTL 过期, 由命令 ID + 命令 表示
签名; 重放保留被限制, 容量耗尽返回
明确 replay_capacity_exceeded 结果。 无效, stale, 断开, 或
运算失败的工作以协议失败为由解决,而不是
信任浏览器数据或丢出原始传输错误.
使用量
团队聊天食谱
ChatRoomsRecipe 声明 chat.rooms 应用导航和
生成只读的房间、信息、成员、线程和反应视图.
它把聊天室的入口放在团队合作下的团队部分
使用外壳的卡片 users 图标.
主机可以挂载其导出 ChatLayout 时间 /chat/rooms;食谱也
在浏览器安全静态聊天固定器上演示主机 ./playground。 。 。 .
内容 用户帮助 描述如何找到房间和
跟踪对话。 软件包游乐场预览使用静态模拟固定装置;
他们不连接到一个直播聊天服务.
本地 dev 服务器
直接运行聊天包工作台 :
pnpm --dir packages/chat dev
根路由打开一个交互式聊天面,由
src/routes/api/dev-chat/+server.ts如果 SMRT_CHAT_DEV_PROVIDER 编号 :
SMRT_CHAT_DEV_API_KEY 或标准供应商证书,例如:
OPENAI_API_KEY, (中文(简体) ), ANTHROPIC_API_KEY,或 GEMINI_API_KEY 可用
助手转过身来 @happyvertical/ai; 否则使用
确定性局部倒计时. 组件预览可在 /previews。 。 。 .
工作台还具有本地独有的语音对话模式. 写着
SMRT_CHAT_DEV_VOICE_GATEWAY_HTTP_URL 财务报告和审定财务报表
SMRT_CHAT_DEV_VOICE_GATEWAY_WS_URL,获取网关目标
/api/dev-voice/config,流出浏览器的麦克风音频 WS /ws/voice 作为
16千赫时的PCM16单机,附带网关记录/聊天答复,以及
播放返回的 TTS 音频 。 如果网关需要无记名符号, 设置
SMRT_CHAT_DEV_VOICE_GATEWAY_TOKEN; 浏览器 WebSocket 测试也需要
SMRT_CHAT_DEV_VOICE_GATEWAY_EXPOSE_TOKEN=true,因此只用于本地 dev.
会议室和信件
import { ChatService } from '@happyvertical/smrt-chat';
const chat = await ChatService.create({
db: { type: 'sqlite', url: 'chat.db' },
});
// `actorProfileId` is the authenticated principal the route injects. Every
// write takes it explicitly; the caller never supplies a `senderProfileId`,
// `role`, or `createdByProfileId` (S5 #1392).
// Create a public room (the acting actor becomes the owner)
const room = await chat.createRoom({
tenantId: 'tenant-1',
name: 'General',
roomType: 'public',
actorProfileId: 'profile-1',
});
// Send a message (always authored as the actor with role 'user')
const message = await chat.sendMessage({
tenantId: 'tenant-1',
roomId: room.id,
actorProfileId: 'profile-1',
content: 'Hello, world!',
});
// Start a threaded conversation from a message (member-checked)
const thread = await chat.startThread({
tenantId: 'tenant-1',
roomId: room.id,
actorProfileId: 'profile-1',
rootMessageId: message.id,
title: 'Follow-up discussion',
});
// Reply within the thread. The thread (and any reply-to message) must belong
// to the same room and tenant, or the write is rejected.
await chat.sendMessage({
tenantId: 'tenant-1',
roomId: room.id,
actorProfileId: 'profile-2',
content: 'Great point!',
threadId: thread.id,
});
带有工具白列的代理会话
// Create an agent session (auto-creates an agent-type room). The acting actor
// becomes the owning participant; the caller cannot open a session for someone
// else by supplying a participant id.
const { session, room } = await chat.createAgentSession({
tenantId: 'tenant-1',
agentId: 'agent-summarizer',
actorProfileId: 'profile-1',
allowedTools: ['web-search', 'summarize'],
systemPrompt: 'You are a research assistant.',
maxMessages: 100,
});
// Send a USER message within the agent session. The caller must be the
// session participant; the message is always authored as that participant.
await chat.sendAgentUserMessage({
tenantId: 'tenant-1',
agentSessionId: session.id,
actorProfileId: 'profile-1',
content: 'Summarize the latest news',
});
// Emit the agent's reply. This is the INTERNAL trusted authority that authors
// a message AS the agent, so it is intentionally NOT a public ChatService
// method and NOT on the package index. It is reachable only via the dedicated
// `./internal/agent-runtime` subpath, which a normal route/consumer importing
// from '@happyvertical/smrt-chat' cannot reach. Opting into this subpath
// signals the importer IS the trusted in-process agent runtime. Tool calls are
// gated fail-closed against the session's allowedTools.
import { sendAgentReply } from '@happyvertical/smrt-chat/internal/agent-runtime';
await sendAgentReply(chat, {
tenantId: 'tenant-1',
agentSessionId: session.id,
content: 'Here is the summary...',
kind: 'assistant',
});
// Check session limits before allowing more messages
if (session.isActive()) {
// Session has not expired or hit token/message limits
}
商业货币助理工具
经认证的助理Dock主机可以通过
同样的 extraTools 缝合。 仅包括人物可能使用的工具
服务器控制 allowedTools;工具重复允许列表和
引用时进行操作检查.
import { createCommerceMoneyTools } from '@happyvertical/smrt-commerce';
import { mountAssistantRoutes } from '@happyvertical/smrt-chat/sveltekit';
const routes = mountAssistantRoutes({
// The authenticated host resolves allowedTools for each principal.
extraTools: () => createCommerceMoneyTools(),
allowedTools: () => [
'commerce.taxCodes.list',
'commerce.invoice.preview',
'commerce.invoice.line.add',
'commerce.invoice.line.update',
],
// ...the host's principal, database, and AI bindings
});
这些工具通过代码选择税法,并使用商业计算器和 文献-资金协调员。 它们不披露原始数额、税额或 数字税率写作.
语音网关转
smrt-chat 可以曝光浏览器语音输入的网关显示转弯目标.
浏览器只接收短寿命 s-m-r-t 语音会话装订
网关到s-m-r-t 服务无记名符号停留在服务器侧.
import {
createVoiceChatSession,
createVoiceGatewayTurnHandler,
} from '@happyvertical/smrt-chat';
// Authenticated app route: bind the speaking profile to a persona and an
// existing or newly-created agent session.
const voice = await createVoiceChatSession({
chatService: chat,
db,
tenantId: locals.tenantId,
actorProfileId: locals.profileId,
actorUserId: locals.userId,
persona: resolvedPersona,
agentSessionId: session.id, // omit to create/reuse an agent session
ttlSeconds: 600,
});
// Return voice.gatewaySessionId + voice.metadata to the browser/gateway. Do not
// return the gateway service token.
// Gateway target route: configure the deployed voice gateway HTTP target to
// POST here with Authorization: Bearer <SMRT_VOICE_GATEWAY_TOKEN>.
export const POST = ({ request }) =>
createVoiceGatewayTurnHandler({
chatService: chat,
db,
ai,
gatewayToken: process.env.SMRT_VOICE_GATEWAY_TOKEN ?? '',
})(request);
网关发送转录文本转折 :
{
"session_id": "gateway-or-smrt-stable-session-id",
"turn_id": "gateway-generated-turn-id",
"target": "smrt:chat",
"actor": "optional-display-name",
"text": "transcribed user utterance",
"metadata": {
"tenantId": "tenant uuid",
"actorProfileId": "profile id",
"chatRoomId": "room id",
"threadId": "optional thread id",
"agentSessionId": "agent session id",
"personaId": "persona id",
"voiceSessionId": "SMRT-issued voice session id",
"source": "voice-gateway"
}
}
s-m-r-t 验证 metadata.voiceSessionId 反其服务器侧绑定,然后
核对任何提供租户/概况/人/会/线代号
绑定而不是信任网关元数据。 有效的转弯作为
普通用户聊天消息,通过 runPersonaConversationTurn(),则
助理回复作为普通助理信息一直存在。 答复是:
{
"session_id": "same session_id",
"turn_id": "same turn_id",
"text": "assistant response text",
"metadata": {
"tenantId": "tenant id",
"chatRoomId": "room id",
"threadId": null,
"agentSessionId": "agent session id",
"userMessageId": "persisted transcript message id",
"assistantMessageId": "persisted assistant message id",
"personaId": "persona id",
"correlationId": "feedback correlation id",
"voiceSessionId": "SMRT-issued voice session id",
"source": "voice-gateway"
}
}
直接消息
// Get or create a DM room between two profiles. The acting actor must be one
// of the two DM participants.
const dmRoom = await chat.getOrCreateDM({
tenantId: 'tenant-1',
actorProfileId: 'profile-1',
profileId1: 'profile-1',
profileId2: 'profile-2',
});
助理码头和监管运行
AssistantDock 编号 : createAssistantDockController (单位:千美元)@happyvertical/smrt-chat/svelte(中文(简体) )
负责主机运输的页面助理; runAssistantTurn 这是它的
服务器引擎(模式工具、暂停和恢复的浏览器工具、预算)
maxSteps 编号 : maxTurnTokens 编号 : maxTurnMs) (中文(简体) ). "看它工作"主机
控制器受监督 run (目标,目前步骤, running | paused | waiting | done | failed | cancelled),与 pauseRun 编号 : continueRun, (中文(简体) ),
holdForUser 个人作出的选择,a clientToolFilter,则a
settle 钩子 这样在导航后的步骤可以看到新页面的工具.
threadList={false} 省略单对接对接点的对话列表
(然后主机打开一条线程通过) oncontroller) (中文(简体) ). matchesToolAllowList 是导出浏览器安全。 全向导 :
docs/assistant-dock.md。 。 。 .
过 conversations="single" 改为 AssistantDock 用于不让人们看到单独对话的应用程序:它重新使用最新的线程(或创建一条线程),打开有焦点的作曲家,并提供一个只显示图标的清晰动作.
服务器侧挂载在一个路径文件中 。 校长来自
event.locals (单位:千美元)@happyvertical/smrt-users/sveltekit);线程被限制为
(b) 工具为:
已关闭( n)allowedTools,缺席意味着无)和,没有 tools,这是
业务清单 allowedTools 名称. ai 默认为 smrt.config
ai 块。 递递申请 runtime: 每个请求然后使用自己的
数据库runtime.databaseConfig()),并在 database-rls 流线
转弯,它活于请求的交易, 运行在它的交易
拥有同一本金(runtime.runAsPrincipal:
// src/routes/api/assistant/[...path]/+server.ts
import { mountAssistantRoutes } from '@happyvertical/smrt-chat/sveltekit';
import { runtime } from '$lib/server/smrt';
export const { GET, POST } = mountAssistantRoutes({
allowedTools: ['notes.read', 'notes.create'],
runtime,
});
在页面中, createAssistantHttpTransport({ endpoint: '/api/assistant' })
是码头的 transport,以及 createAssistantHttpActionClient 联合国
actionClient 当给出路径时 actions: { adapter }。 。 。 .
食谱
AssistantRecipe (单位:千美元)chat.assistant宣布助理码头的应用和
代理目录: shell 部件 header.end 该挂载 AssistantDock
从 @happyvertical/smrt-chat/svelte,一个 llm 提供者( 主机密钥)
OPENAI_API_KEY, (中文(简体) ), ANTHROPIC_API_KEY 或者说 GEMINI_API_KEY,或浏览器模型
帮助用户。 见 agents/recipes.md。 。 。 .
API 密码
模型
| 导出 | 说明 |
|---|---|
ChatRoom | 有型号的房间(public编号 :private编号 :dm编号 :agent页:1 |
ChatMessage | 信件为 role (用户/助理/系统/工具), messageType (文本/系统/行动/文件/工具-调用/工具-结果),可选线索和答复参考 |
ChatParticipant | 会议室成员 role (所有人/管理人/成员/观众),在线状态,读取跟踪 |
ChatThread | 连接到根信息, 具有解析度/ 重开生命周期的线索对话 |
ChatReaction | Emoji对消息的反应 |
AgentSession | AI 代理会话 allowedTools (JSON字符串阵列), sessionContext 为多回转记忆, systemPrompt,和使用限制(maxTokens编号 :maxMessages编号 :expiresAt(中文(简体) ) |
VoiceSession | 对租户、演员简介、人物和代理人的短寿命语音网关 |
内部收藏
原始收藏类不从软件包索引导出 。 他们被列入名单了
这里作为执行细节;应用代码应当使用 ChatService 财务报告和审定财务报表
语音帮助者.
| 内部类 | 说明 |
|---|---|
ChatRoomCollection | 房间查询, findOrCreateDM() |
ChatMessageCollection | 信件查询和搜索过滤器 |
ChatParticipantCollection | 参与者查询, findMembership() |
ChatThreadCollection | 线索查询 |
ChatReactionCollection | 反应查询 |
AgentSessionCollection | 会话查询, findActiveSession(), (中文(简体) ), findOrCreate() |
VoiceSessionCollection | 语音会话绑定询问和 stale- 过期帮助 |
服务
| 导出 | 说明 |
|---|---|
ChatService | 外观 : createRoom(), (中文(简体) ), sendMessage(), (中文(简体) ), startThread(), (中文(简体) ), addParticipant(), (中文(简体) ), removeParticipant(), (中文(简体) ), updateRoom(), (中文(简体) ), addReaction(), (中文(简体) ), removeReaction(), (中文(简体) ), getOrCreateDM(), (中文(简体) ), createAgentSession(), (中文(简体) ), sendAgentUserMessage(), (中文(简体) ), getRoomMessages(), (中文(简体) ), getRoomForMember(), (中文(简体) ), updateAgentSessionConfig()。每封信都需要服务器提供 actorProfileId。代理作者的回复路径(sendAgentReply)故意不在外观或软件包索引上——它是内部函数,用于: services/ChatService.ts 仅用于信任的处理中代理运行时间(S5#1392). |
createVoiceChatSession() | 创建对已认证的演员和人物的短寿语音约束, 可选择针对现有代理会话 |
handleVoiceGatewayTurn() | 非 Fetch 主机的下级网关转接器 |
createVoiceGatewayTurnHandler() | 为网关目标端点获取兼容的 HTTP 处理器 |
类型
ChatRoomType, (中文(简体) ), ChatRoomStatus, (中文(简体) ), ChatRoomOptions, (中文(简体) ), ChatMessageType, (中文(简体) ), ChatMessageRole, (中文(简体) ), ChatMessageOptions, (中文(简体) ), ChatMessageSearchFilters, (中文(简体) ), ChatParticipantRole, (中文(简体) ), ChatParticipantStatus, (中文(简体) ), ChatParticipantOptions, (中文(简体) ), OnlineStatus, (中文(简体) ), ChatThreadOptions, (中文(简体) ), ChatReactionOptions, (中文(简体) ), AgentSessionStatus, (中文(简体) ), AgentSessionOptions, (中文(简体) ), VoiceSessionStatus, (中文(简体) ), VoiceSessionOptions, (中文(简体) ), VoiceGatewayTurnPayload, (中文(简体) ), VoiceGatewayTurnResponse
常数
CHAT_MODULE_META, (中文(简体) ), CHAT_UI_SLOTS
依赖关系
@happyvertical/smrt-core-- ORM 和代码生成@happyvertical/smrt-tenancy-- 多租户范围界定@happyvertical/smrt-types-- 共同类型定义- 端点( 可选) :
@happyvertical/smrt-agents, (中文(简体) ),@happyvertical/smrt-profiles, (中文(简体) ),@happyvertical/smrt-svelte
贡献者指南
见 AGENTS.md 用于软件包结构、变化、验证、,
和贡献者的指导.
服务器工具的长期核准
mountAssistantRoutes 默认情况下持有破坏性服务器呼叫( 删除/ remove/)
销毁/清洗/投放/冲洗,包括额外工具。 内在的一转
有待其线程、流等批准 approval_needed,结尾
stoppedReason: 'approval'它没有做进一步的模型呼叫。 核准执行
保存工具, 并附带其原始主参数和在允许使用后参数
提供检查,然后写出结果。 否认作者拒绝。 提供型号
approved 值对这个门没有影响.
默认权限使用 App-runtime 的 SQLite 信封适配器, 而不是现有的
smrt-批准分类账;将其模型纳入正常数据库迁移. 供应
approvals 用于另一个商店/托管机构. approvalPolicy.tools 财务报告和审定财务报表
approvalPolicy.operations 明确覆盖每个工具或词条的默认值
操作;例如:. { tools: { 'invoices.update': true } } 也持有更新.
直接 runAssistantTurn 电话供应 createAssistantApprovalBridge页:1
被保护的呼叫没有一个失败关闭 。 这不会改变低水平
runToolLoop 或个人对话政策,仍为主机集成API.
唯一所有者路线 : GET approvals (整个租户待审议摘要), GET threads/:threadId/approvals 财务报告和审定财务报表
POST approvals/:id/decide 与 { approve: boolean }在同一个山下.
线索读取会保留其所有权检查;所有者决定使用被保存的请求者的线程绑定,不能读取任意的线程历史. 租户和变异原产地检查与
其他路线。 他们只归还公众批准预测。 默认所有者
请检查date=中的日期值 (帮助) 需要活动用户主动直接加入 cononical 系统
拥有者角色. 第二个决定是409. 无法重放失败的消耗效果 .
createAssistantHttpTransport 提供批准方法; AssistantDock
自动制作 AssistantApprovalCard 以坚忍的言语发誓,
键盘无障碍批准/丹麦控制并持续取得成果。 外部驱动器
使用现有的 approvalNeeded 调用: 聊天创建 canonial 请求,
并等待同一当局批准.
司机必须尊重拒绝 通过原校长的现场直播执行,
允许约束主机/MCP适配器。 见 核准细节。 。 。 .
运行时间 Cookbook 游戏选择通过 连续运行时间生成 公开行动 保持他们的AOT申报, 但现场提供和呼叫 还必须通过当前租户的烹饪手册和东道主优惠门.
经批准后,可节省的列车电话重新检查运行时间曝光情况。 残疾或 无法读取的模型门记录一个终端拒绝的结果而不运行工具; 批准清单只保留原有的公开搁置摘要.