WeKnora/website-docs/04-api/02-api-chat.md

443 lines
19 KiB
Markdown
Raw Normal View History

# API 参考:会话、消息与聊天
创建和管理会话,读取消息与临时附件,并通过 SSE 获取知识问答或智能体回答。
会话为“用户私有”资源,handler 内部强制归属校验;路由层为 Viewer+。API key:会话/聊天需 `chat` capability(或 full-access);消息搜索需 `message_history`;知识检索需 `retrieve`。
## 会话(/api/v1/sessions)
### POST /api/v1/sessions
用途:创建会话。Handler: `internal/handler/session/handler.go`
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `title` | string | 否 | 标题 |
| `description` | string | 否 | 描述 |
响应:201 `{"success":true,"data":{Session}}`(`id,title,description,tenant_id,user_id,is_pinned,last_request_state,created_at,...`)
```bash
curl -X POST $BASE/api/v1/sessions -H "X-API-Key: $API_KEY" \
-H 'Content-Type: application/json' -d '{"title":"新对话"}'
```
### GET /api/v1/sessions
用途:会话列表。Handler: `internal/handler/session/handler.go`
| 查询参数 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `page` / `page_size` | int | 否 | 分页 |
| `keyword` | string | 否 | 标题模糊搜索 |
| `source` | string | 否 | 来源过滤(web/embed/api/feishu/wechat/slack/...) |
| `agent_id` | string | 否 | 按 Agent 过滤(IM 会话) |
响应:200 `{"success":true,"data":[SessionListItem],"total","page","page_size"}`
```bash
curl "$BASE/api/v1/sessions?page=1" -H "Authorization: Bearer $TOKEN"
```
### GET /api/v1/sessions/:id
用途:会话详情。
响应:200 `{"success":true,"data":{Session}}`
```bash
curl $BASE/api/v1/sessions/s-1 -H "Authorization: Bearer $TOKEN"
```
### PUT /api/v1/sessions/:id
用途:更新会话(标题/描述/置顶)。请求体:`title`、`description`、`is_pinned`(均可选)。
响应:200 `{"success":true,"data":{Session}}`
```bash
curl -X PUT $BASE/api/v1/sessions/s-1 -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"title":"重命名"}'
```
### DELETE /api/v1/sessions/:id
用途:删除会话。
响应:200 `{"success":true,"message":"Session deleted successfully"}`
```bash
curl -X DELETE $BASE/api/v1/sessions/s-1 -H "Authorization: Bearer $TOKEN"
```
### DELETE /api/v1/sessions/batch
用途:批量删除会话。请求体:`{"ids":["s-1"],"delete_all":false}`(二选一:`ids` 或 `delete_all:true`)。
响应:200 `{"success":true,"message":"Sessions deleted successfully"}`
```bash
curl -X DELETE $BASE/api/v1/sessions/batch -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"ids":["s-1","s-2"]}'
```
### DELETE /api/v1/sessions/:id/messages
用途:清空会话消息。
响应:200 `{"success":true,"message":"Session messages cleared successfully"}`
```bash
curl -X DELETE $BASE/api/v1/sessions/s-1/messages -H "Authorization: Bearer $TOKEN"
```
### POST /api/v1/sessions/:session_id/generate_title
用途:根据上下文消息生成会话标题。Handler: `internal/handler/session/title.go`
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `messages` | []Message | 是(`binding:"required"`) | 用作上下文的消息 |
响应:200 `{"success":true,"data":"生成的标题"}`
```bash
curl -X POST $BASE/api/v1/sessions/s-1/generate_title -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"messages":[{"role":"user","content":"介绍下产品"}]}'
```
### POST /api/v1/sessions/:session_id/stop
用途:停止正在生成的回答。Handler: `internal/handler/session/stream.go`
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `message_id` | string | 是(`binding:"required"`) | 助手消息 ID |
响应:200 `{"success":true,"message":"Generation stopped"}`
```bash
curl -X POST $BASE/api/v1/sessions/s-1/stop -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"message_id":"m-1"}'
```
### POST /api/v1/sessions/:session_id/pin 与 DELETE /api/v1/sessions/:id/pin
用途:置顶 / 取消置顶会话。无请求体。Handler: `internal/handler/session/handler.go`
响应:200 `{"success":true,"is_pinned":true|false}`
```bash
curl -X POST $BASE/api/v1/sessions/s-1/pin -H "Authorization: Bearer $TOKEN"
curl -X DELETE $BASE/api/v1/sessions/s-1/pin -H "Authorization: Bearer $TOKEN"
```
### GET /api/v1/sessions/continue-stream/:session_id
用途:断线续传活跃流(重放历史事件 + 100ms 轮询新增量)。Handler: `internal/handler/session/stream.go`
| 查询参数 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `message_id` | string | 是 | 要续传的助手消息 ID |
响应:200 SSE(`text/event-stream`,事件格式见总览“流式接口协议”)。
```bash
curl -N "$BASE/api/v1/sessions/continue-stream/s-1?message_id=m-1" -H "Authorization: Bearer $TOKEN"
```
## 会话附件(临时文档)
Handler: `internal/handler/session/temporary_document.go`
### POST /api/v1/sessions/:session_id/attachments
fix(security): close the low-severity shared-space findings (#3416) * fix(security): close the low-severity shared-space findings Verified and fixed from the shared-space permission review: - Embed channels kept knowledge_ids, tag_ids, mentioned_items, skill_names and summary_model_id from anonymous visitors. Mentions are only scoped for shared agents, so a visitor could query any KB (and pick any model) of the channel workspace by ID. The payload now drops them; the widget never sends them. - PUT /knowledgebase/:kb_id/wiki/issues/:issue_id/status updated any issue by ID. The update is now scoped to the path's KB (404 otherwise). - A direct org invite let the inviter attach any user of the target workspace (or any user by ID) as its representative, whose username and email the roster then showed to all members. Direct adds attach no representative, and the roster returns emails only for the caller's own workspace. - COS and KS3 dropped the bucket (and COS the region) segment when turning a path into an object key, while the tenant check scans every segment: cos://42/<region>/prefix/7/... passed as tenant 42 and read tenant 7's object from a shared bucket. Both must now match the service's config. - Shared agent listings returned the full agent to receivers. Prompts and the creator's user ID are withheld; capabilities and scope stay visible. - Temporary document uploads let the caller pick the parser engine (and its credentials) of a shared agent's workspace; only the agent's rules choose one there now. - Suggested questions used request / message-snapshot knowledge_ids without a permission check. Each document is now resolved to its KB and checked like KB IDs, including a shared agent's scope. - IM channels accepted any knowledge_base_id (and any agent ID on create). Both must belong to the channel's workspace, the KB also to a restricted API key's allow-list. - KB-restricted API keys could list org-shared KBs outside their allow-list in the organization views; those listings are now filtered. - With enable_rbac=false, RequireKBAccess let cross-workspace denials through. That switch is for roles inside a workspace; the guard now always denies another workspace's KB, since handlers behind it load by ID without a tenant filter. - The org member limit was counted before and enforced apart from the insert; it is now checked in the insert's transaction with the organization row locked (SQLite serializes writers instead). - The UpdateOrganization route comment and API doc said owner-only; the service and UI allow org admins. Comment and doc corrected. Documented, not changed: issued /r/ and presigned links stay valid until they expire after a share is revoked. * fix(security): address review of the low-severity shared-space fixes - Embed payloads also drop question_origin. It selects a KB like an @mention for agents that retrieve only when mentioned, and the widget never sends it; the selection stays inside the agent's scope, but an anonymous visitor should not pick among its KBs. suggestion_attribution is kept (the widget sends it and it is validated). - The receiver view of a shared agent also withholds the follow-up suggestion instruction, a prompt like the others. Starter questions are shown to receivers anyway, and the sharer's name is displayed by design. - Follow-up suggestion generation moves into the agent's workspace with types.WithExecutionTenant instead of a bare tenant rewrite, so the caller is pinned before the document permission check runs. The auth middleware and the shared run already pinned it; this removes the dependency on that. - KS3 CopyFile copies only from the service's own bucket (as COS and S3 do); another bucket's path is a cross-backend copy. Tests cover the dropped question_origin, the follow-up instruction and the /shared-agents listing, a follow-up context with the tenant switched, a repeated wiki issue status update, and the KS3 copy source.
2026-09-18 14:58:46 +00:00
用途:上传会话级临时文档(异步解析)。multipart 字段:`file`(必填)、`agent_id`(可选,决定解析引擎/ASR 模型)、`parser_engine`(可选;使用共享智能体时忽略,由智能体的解析规则决定)。
响应:202 `{"success":true,"data":{TemporaryDocument}}`(`id,session_id,file_name,file_type,file_size,status(uploaded/processing/ready/failed),resource_ref,...`)
```bash
curl -X POST $BASE/api/v1/sessions/s-1/attachments -H "Authorization: Bearer $TOKEN" -F 'file=@notes.pdf'
```
### GET /api/v1/sessions/:id/attachments
用途:附件列表。
响应:200 `{"success":true,"data":[TemporaryDocument]}`
```bash
curl $BASE/api/v1/sessions/s-1/attachments -H "Authorization: Bearer $TOKEN"
```
### GET /api/v1/sessions/:id/attachments/:attachment_id
用途:附件详情(含解析状态)。
响应:200 `{"success":true,"data":{TemporaryDocument}}`
```bash
curl $BASE/api/v1/sessions/s-1/attachments/a-1 -H "Authorization: Bearer $TOKEN"
```
### GET /api/v1/sessions/:id/attachments/:attachment_id/preview
用途:附件原文件预览。
响应:200 文件流(`Content-Disposition: inline|attachment`,`Cache-Control: private`)。
```bash
curl $BASE/api/v1/sessions/s-1/attachments/a-1/preview -H "Authorization: Bearer $TOKEN" -o preview.pdf
```
### DELETE /api/v1/sessions/:id/attachments/:attachment_id
用途:删除附件。
响应:204 No Content
```bash
curl -X DELETE $BASE/api/v1/sessions/s-1/attachments/a-1 -H "Authorization: Bearer $TOKEN"
```
## 回答建议(Suggestions)
Handler: `internal/handler/message_suggestion.go`
### GET /api/v1/sessions/:id/messages/:message_id/suggestions
用途:读取某助手消息的追问建议。
响应:200 `{"success":true,"data":{MessageSuggestionSet}}`(`status(generating/ready/suppressed/failed),questions:[{id,text,category,source,knowledge_base_ids}],allow_regenerate,...`)
```bash
curl $BASE/api/v1/sessions/s-1/messages/m-1/suggestions -H "Authorization: Bearer $TOKEN"
```
### POST /api/v1/sessions/:session_id/messages/:message_id/suggestions
用途:确保生成建议(幂等触发)。请求体:`{"regenerate":true}`(可选,强制重新生成)。
响应:200(就绪)或 202(生成中)`{"success":true,"data":{MessageSuggestionSet|null}}`
```bash
curl -X POST $BASE/api/v1/sessions/s-1/messages/m-1/suggestions -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{}'
```
### POST /api/v1/sessions/:session_id/suggestion-events
用途:上报建议交互事件(埋点)。
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `suggestion_set_id` | string | 是(`binding:"required"`) | 建议集 ID |
| `question_id` | string | 否 | click/regenerate 时必填 |
| `event_type` | string | 是(`binding:"required"`) | `impression/click/dismiss/regenerate` |
响应:204 No Content
```bash
curl -X POST $BASE/api/v1/sessions/s-1/suggestion-events -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"suggestion_set_id":"ss-1","event_type":"impression"}'
```
## 聊天与检索
Handler: `internal/handler/session/qa.go`。API key:聊天需 `chat`/full;`knowledge-search` 需 `retrieve`/full。
### POST /api/v1/knowledge-chat/:session_id
用途:知识库问答(SSE 流式)。
请求体(KnowledgeQA/AgentQA 共用):
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `query` | string | 是(`binding:"required"`) | 用户问题 |
| `knowledge_base_ids` | []string | 否 | 检索的 KB |
| `knowledge_ids` | []string | 否 | 限定知识文件 |
| `agent_enabled` | bool | 否 | 是否启用 Agent 模式 |
| `agent_id` | string | 否 | 自定义 Agent ID |
fix(security): close cross-workspace access paths in shared spaces (#3408) * fix(security): close cross-workspace access paths in shared spaces A review of how shared-space (organization) members reach each other's resources found six paths that bypass the org-share permission model: - presigned-preview signed any resource handle or storage path, turning a known resource:// handle into an anonymous /r/ URL that outlives share revocation. It now requires the path to belong to the caller's tenant, like /files. - POST /initialization/initialize let a shared-KB editor rewrite the owner workspace's models (base URL, API key) in place. Only the KB's own workspace may call it, and rewriting a stored model needs the same authority as PUT /models/:id. - KB JSON carried the legacy inline credentials (storage_config secret_id/secret_key, which initialization fills with the MinIO env keys, and vlm_config api_key) to every share receiver. They are withheld from JSON; their DB columns are unchanged. - A chat without agent_source_tenant_id resolved shares before the caller's own agent, so a member sharing a same-ID built-in agent took over other workspaces' default agent. Own agents now win, built-in agents can no longer be shared (existing such shares no longer resolve), and embed channels drop a visitor-supplied source workspace. - Any org-admin tenant (even a tenant Viewer inside it) could raise another workspace's KB share to editor/admin, and the route guard was bypassable via an unrelated :id. Share management is now: the sharer from the source tenant (Contributor+), source-tenant Admin+, or an org-admin tenant's Admin+ that may only remove or lower. share_id must belong to :id. - Wiki write tools were registered for every wiki KB in the search targets, which only need read access, so a viewer share (e.g. via the built-in wiki fixer) could edit or delete another workspace's wiki pages. They now act only on KBs the caller may edit. * fix(security): close the KB settings path and owner details for share receivers Follow-up to the shared-space review: - PUT /initialization/config shares the route guard that admits share editors, so an editor could still rebind the owner's KB models, chunking and storage, and storage backends resolved against the caller's workspace let it bind the owner's KB to its own backend. Another workspace now needs an admin share (the only share level the frontend offers settings to) and may not change the storage binding at all. - GET /initialization/config showed model base URLs and bucket locations to any admin of the caller's own workspace, including share receivers. They now only see whether credentials are configured. - Wiki write tools on the caller's own KBs had no role floor, so a tenant Viewer (and the IM, embed and MCP endpoint principals that run as Viewer) could write through an agent what the HTTP routes deny. Writes now need Contributor+, or the ingest capability for a scoped API key, following the RBAC rollout switch. - resolveAgent logs the share lookup error instead of a nil own-agent error when a shared selector fails. * fix(security): close the medium shared-space access findings Follow-up to the high-risk fixes, from the same review: - Wiki fixer moved into a shared KB's workspace ran with the caller's own config there: an unset MCP mode registered all of the owner's MCP services, and an "all" KB scope reached the owner's other KBs. The scoped run now uses the built-in config pinned to that one KB, without MCP, skills, sandbox or web search, and falls back to the KB's own model. - An unset MCP mode means "all" at runtime but is shown as none in the share scope; shared runs now treat it as none. - Quick-answer mode used the request's web_search_enabled alone, so a receiver could turn on search the agent disables and spend the owner's provider quota. It now requires the agent setting too, as agent mode does. - summary_model_id picked any model of the workspace a run executes in. It is ignored for shared agents and the relocated wiki fixer. - A workspace that left or was removed from an organization kept sharing its KBs and agents. Its shares are revoked on departure, and share queries and permission checks require the source workspace's membership and a live organization, which also covers rows left behind earlier. - Sharing an agent exposes its KB scope to all members, so a Contributor could share colleagues' KBs (or "all") through an agent. The sharer must now be able to share each KB directly (creator or Admin+; "all" needs Admin+), also when a shared agent's scope is widened later. - A scoped API key with manage_channels could mint an MCP endpoint token wider than itself. Endpoints it creates, updates or rotates must stay within its KB allow-list and capabilities. - A shared agent's run indexed the receiver's Q&A into the owner's chat history KB; indexing now uses the session owner's configuration. - Sharing an agent with skills keeps injecting the owner's skill environment values (product decision); the share panel now warns that members can read them. Preview of originals through read-only shares is kept as designed and documented.
2026-09-18 14:00:02 +00:00
| `web_search_enabled` | bool | 否 | 联网搜索;只在智能体本身开启联网搜索时生效 |
| `summary_model_id` | string | 否 | 总结模型;使用共享智能体时忽略,始终使用智能体配置的模型 |
| `mcp_service_ids` | []string | 否 | @提及的 MCP 服务 |
| `skill_names` | []string | 否 | @提及的技能 |
| `tag_ids` | []string | 否 | 标签过滤 |
| `mentioned_items` | []object | 否 | @提及项(type/kb_id/kb_name/service_id/skill_name) |
| `disable_title` | bool | 否 | 禁用自动标题 |
| `images` | []object | 否 | 图片(`data` base64 / `url` / `caption`) |
| `attachment_uploads` | []object | 否 | 内联附件(`data` base64、`file_name`、`file_size`) |
| `attachment_ids` | []string | 否 | 已上传的会话附件 ID |
| `channel` | string | 否 | 来源渠道 |
| `suggestion_attribution` | object | 否 | 点击建议的归因信息 |
响应:200 SSE 流,`event: message` + `data: StreamResponse`(见总览),以 `complete` 事件结束。
```bash
curl -N -X POST $BASE/api/v1/knowledge-chat/s-1 -H "X-API-Key: $API_KEY" \
-H 'Content-Type: application/json' \
-d '{"query":"退款政策是什么?","knowledge_base_ids":["kb-1"]}'
```
### POST /api/v1/agent-chat/:session_id
用途:Agent 问答(SSE 流式,含 `thinking/tool_call/tool_result/tool_approval_required/mcp_oauth_required` 等事件)。请求体同上。
```bash
curl -N -X POST $BASE/api/v1/agent-chat/s-1 -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"query":"分析上季度数据","agent_id":"agent-1"}'
```
### POST /api/v1/knowledge-search
用途:无会话知识检索(非流式)。Handler: `internal/handler/session/qa.go` 的 `SearchKnowledge`。
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `query` | string | 是(`binding:"required"`) | 查询 |
| `knowledge_base_id` | string | 否 | 单 KB(兼容旧版) |
| `knowledge_base_ids` | []string | 否 | 多 KB |
| `knowledge_ids` | []string | 否 | 限定文件 |
| `tag_ids` | []string | 否 | 标签过滤 |
| `mentioned_items` | []object | 否 | 带 KB 范围的标签提及 |
响应:200 `{"success":true,"data":[SearchResult]}`(`id,content,knowledge_id,knowledge_title,score,chunk_type,knowledge_base_id,...`)
```bash
curl -X POST $BASE/api/v1/knowledge-search -H "X-API-Key: $API_KEY" \
-H 'Content-Type: application/json' -d '{"query":"部署要求","knowledge_base_ids":["kb-1"]}'
```
## 消息(/api/v1/messages)
Handler: `internal/handler/message.go`
### POST /api/v1/messages/search
用途:聊天历史搜索。权限:Viewer+;API key `message_history`/full。
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `query` | string | 是(`binding:"required"`) | 查询 |
| `mode` | string | 否 | `keyword/vector/hybrid`(默认 hybrid) |
| `limit` | int | 否 | 默认 20 |
| `session_ids` | []string | 否 | 限定会话 |
响应:200 `{"success":true,"data":{"total":N,"results":[{session_id,message_id,role,content,created_at,score}]}}`
```bash
curl -X POST $BASE/api/v1/messages/search -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{"query":"报价"}'
```
### GET /api/v1/messages/chat-history-stats
用途:聊天历史索引统计。权限:Viewer+;API key `message_history`/full。
响应:200 `{"success":true,"data":{indexed_message_count,knowledge_base_size,last_indexed_at,...}}`
```bash
curl $BASE/api/v1/messages/chat-history-stats -H "Authorization: Bearer $TOKEN"
```
### GET /api/v1/messages/:session_id/load
用途:加载会话消息(时间游标向前翻页)。权限:Viewer+;API key `chat`/full。
| 查询参数 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `limit` | int | 否 | 默认 20 |
| `before_time` | string | 否 | RFC3339/RFC3339Nano 时间戳 |
响应:200 `{"success":true,"data":[Message]}`(`id,session_id,role,content,is_completed,images,attachments,agent_steps,...`)
```bash
curl "$BASE/api/v1/messages/s-1/load?limit=20" -H "X-API-Key: $API_KEY"
```
### DELETE /api/v1/messages/:session_id/:id
用途:删除单条消息。权限:Viewer+(handler 校验会话归属);API key `chat`/full。
响应:200 `{"success":true,"message":"Message deleted successfully"}`
```bash
curl -X DELETE $BASE/api/v1/messages/s-1/m-1 -H "Authorization: Bearer $TOKEN"
```
## 会话生成文件
以下接口要求 Viewer+,API Key 需 chat 或 full-access,并按会话归属校验。不存在或不可访问的会话返回 404。
| 方法 | 路径 | 响应 |
| --- | --- | --- |
| GET | `/api/v1/sessions/:id/artifacts` | 200 `{success:true,data:[Artifact]}`,汇总会话文件 |
| GET | `/api/v1/sessions/:id/messages/:message_id/artifacts` | 同上,仅本条消息文件 |
| GET | `/api/v1/sessions/:id/messages/:message_id/artifacts/:index/download` | 200 文件流,Content-Disposition: attachment |
feat(artifacts): let users delete generated files (#3447) * feat(artifacts): let users delete generated files 技能生成的文件此前只能列出、预览和下载,没有任何删除入口,后端 handler/service/repository 三层都没有实现。DeleteSession 里那句注释 ("a dedicated GC job or explicit hard-delete API is the right place to reclaim storage") 留的就是这个位置。 Tombstone, not a row delete. message_artifacts 新增 deleted_at,删除只 打标记不删行。position 是下载接口寻址用的下标(msg.Artifacts[index]), 物理删掉中间一行会让它后面的文件整体前移,已有链接下到错的文件;而 ArtifactCollector 的去重集就是从这张表读的,行没了之后沙箱里 mtime 未变 的同名文件下一轮就会被重新采集回来,删了又出现。墓碑同时挡住这两条。 loadArtifactsByMessage 因此刻意保留墓碑,展示侧用 MessageArtifacts.Live 过滤;NewMessageArtifactRecords 带上 DeletedAt,任何一次消息重写都能把 墓碑原样写回去。 Bytes. 字节是真回收的,走 catalog.Release 引用计数:一份文件可能同时被 知识库条目和后续回答持有,只有所有持有者都放手才 DeleteFile。删多个版本 时同一个对象可能来自多条消息,每条消息的绑定都要释放,字节只删一次。 回收发生在打标记之后,且只针对本次调用真正认领到的行——并发的第二次删除 认领不到任何行,也就不会去动别人正在回收的对象。释放失败一律保留字节: 留个孤儿 blob 以后还能靠墓碑上的 url 回收,删错了则是别人的文档里的图片 凭空消失。 Scope. 会话内面板每个版本单独一行,删的就是点的那一版;产物库一行代表 一个文件(带版本数),默认连同该文件在这个会话里的所有版本一起删,否则 删完这一行还在、只是显示上一版。权限比下载严一档:下载认共享智能体的 只读访问,删除只认会话归属人。 Inline references. 正文里的 resource:// 引用渲染成置灰加删除线的卡片, 不可点击,和「模型引用了不存在的文件」的 --pending 态区分开。图片类产物 也降级成卡片:走 renderImage 只会拉取失败,留下一张永远加载不出来的图。 墓碑必须留在传给渲染器的产物列表里——句柄形式与知识库图片同形,过滤掉 之后句柄对不上本条回答,会被当成外部受保护图片去拉一个已经不存在的 blob,结果是裂图。组件里因此拆出 liveArtifacts 只给计数和文件列表用。 Also: 产物库是 offset 分页的无限列表,删一行会让后续页整体前移漏掉一条, 改成按已显示行数取下一页并按 key 去重;access.ResolveMessageArtifact 与 MessageReferencesFile 不再让墓碑授权访问;SessionArtifacts 过滤墓碑, 避免新回答把引用绑到已删文件上;版本澄清文案不再把已删版本算进版本数。 docs/swagger.* 未重新生成:仓库里那份已经落后若干功能,重生成会带进约 1000 行无关漂移,另开 PR 同步。 * fix(artifacts): close the delete holes found in review Regeneration. loadKnownSet 把墓碑的 ContentHash 也放进了去重集,于是 knownSameContent 会把「删除后技能重新生成、字节恰好相同」当成 fork checkout 那种 restore:不上传、不挂回本轮回答,文件再也回不来。墓碑现在 只登记 (path, mtime),不进 hash 也不进 byPath —— 前者才是「沙箱文件没动 过就别复活」需要的键,后者是「同内容恢复」的短路,两件事不该共用。 RecordRestoredArtifactMtime 也不再改墓碑:它的 mtime 就是那把锁。 Message file proxy. /sessions/:id/messages/:message_id/files 走 MessageReferencesFile,而正文检查在最前面且无条件为真。删除不会重写回答, resource:// 句柄还留在正文里,于是这条代理会继续把已删文件交出去——包括 交给共享智能体的只读访客,也包括「字节因为知识库还持有而没被回收」的情形。 现在先看 artifacts:命中本条消息的墓碑直接 false,命中 live 直接 true, 其余(知识库图、附件)才回落到正文。同一文件挂在多个位置时只要还有一个 live 就仍然可取。 Cross-session bytes. CreateForked 复制产物行时连同存储 URL 一起复制,但 不会给副本重新 Bind,所以 catalog 的引用计数看不到分叉。在父会话里删除会 把分叉还在用的字节删掉。无 catalog 部署、以及存的是裸 provider 路径的行, 同样不在计数覆盖内。回收前新增一道 CountLiveArtifactsByURL:只要还有任何 未删除的行指向同一对象就保留字节,查不出来也保留。配套加了 url 的部分索引。 Atomicity. SoftDeleteSessionArtifacts 原来逐条 UPDATE 不带事务,删多版本 时中途失败会留下「一部分已隐藏、字节没回收、接口 500、用户重试 404」。 现在整批放进一个事务。writeMessageArtifacts 是整表替换,拿着删除前快照的 并发写会让墓碑复活而字节已在回收,现在按 position 把已存在的 deleted_at 合并回去——删除是唯一不允许被过期写覆盖的属性。 all_versions 两个路由改用同一个解析器(strconv.ParseBool),此前一个是 == "true"、另一个是 != "false",显式传 1/TRUE 在两边语义不同;缺省值仍 按路由区分。 测试:收集器三条(未动不复活 / 重新生成要回来 / live 的同内容恢复仍短路)、 access 三条(正文不能复活已删授权、多副本只要有 live 就可取、非产物引用 仍走正文)、service 七条(归属人校验、他人会话拒绝、并发认领为空、live 行仍在则保留字节、guard 失败保留字节、多版本按对象归并 owner、无 source_path 不扫全会话)、repository 三条(墓碑抗过期写、事务回滚、跨会话 URL 计数)、handler 一条(两个路由的 all_versions 解析矩阵)。其中 「重新生成要回来」在改回旧实现时确认会失败。 client/ 没有 artifacts 相关 API(只有一个 SSE 事件类型常量),无需同步。
2026-09-20 05:01:46 +00:00
| DELETE | `/api/v1/sessions/:id/messages/:message_id/artifacts/:index` | 200 `{success:true,data:{file_name,deleted}}`,删除该文件 |
Artifact 字段:index、handle(可选 resource:// 引用)、file_name、file_type、file_size、source_path、mod_time、created_at。响应不返回底层对象存储 URL。下载 index 从 0 开始,必须使用对应消息列表的索引,不能拿会话汇总索引直接拼消息下载地址。非法索引返回 400,越界或文件不存在返回 404。
```bash
curl "$BASE/api/v1/sessions/session-1/messages/message-1/artifacts" \
-H "Authorization: Bearer $TOKEN"
curl "$BASE/api/v1/sessions/session-1/messages/message-1/artifacts/0/download" \
-H "Authorization: Bearer $TOKEN" -o result.pdf
```
feat(artifacts): let users delete generated files (#3447) * feat(artifacts): let users delete generated files 技能生成的文件此前只能列出、预览和下载,没有任何删除入口,后端 handler/service/repository 三层都没有实现。DeleteSession 里那句注释 ("a dedicated GC job or explicit hard-delete API is the right place to reclaim storage") 留的就是这个位置。 Tombstone, not a row delete. message_artifacts 新增 deleted_at,删除只 打标记不删行。position 是下载接口寻址用的下标(msg.Artifacts[index]), 物理删掉中间一行会让它后面的文件整体前移,已有链接下到错的文件;而 ArtifactCollector 的去重集就是从这张表读的,行没了之后沙箱里 mtime 未变 的同名文件下一轮就会被重新采集回来,删了又出现。墓碑同时挡住这两条。 loadArtifactsByMessage 因此刻意保留墓碑,展示侧用 MessageArtifacts.Live 过滤;NewMessageArtifactRecords 带上 DeletedAt,任何一次消息重写都能把 墓碑原样写回去。 Bytes. 字节是真回收的,走 catalog.Release 引用计数:一份文件可能同时被 知识库条目和后续回答持有,只有所有持有者都放手才 DeleteFile。删多个版本 时同一个对象可能来自多条消息,每条消息的绑定都要释放,字节只删一次。 回收发生在打标记之后,且只针对本次调用真正认领到的行——并发的第二次删除 认领不到任何行,也就不会去动别人正在回收的对象。释放失败一律保留字节: 留个孤儿 blob 以后还能靠墓碑上的 url 回收,删错了则是别人的文档里的图片 凭空消失。 Scope. 会话内面板每个版本单独一行,删的就是点的那一版;产物库一行代表 一个文件(带版本数),默认连同该文件在这个会话里的所有版本一起删,否则 删完这一行还在、只是显示上一版。权限比下载严一档:下载认共享智能体的 只读访问,删除只认会话归属人。 Inline references. 正文里的 resource:// 引用渲染成置灰加删除线的卡片, 不可点击,和「模型引用了不存在的文件」的 --pending 态区分开。图片类产物 也降级成卡片:走 renderImage 只会拉取失败,留下一张永远加载不出来的图。 墓碑必须留在传给渲染器的产物列表里——句柄形式与知识库图片同形,过滤掉 之后句柄对不上本条回答,会被当成外部受保护图片去拉一个已经不存在的 blob,结果是裂图。组件里因此拆出 liveArtifacts 只给计数和文件列表用。 Also: 产物库是 offset 分页的无限列表,删一行会让后续页整体前移漏掉一条, 改成按已显示行数取下一页并按 key 去重;access.ResolveMessageArtifact 与 MessageReferencesFile 不再让墓碑授权访问;SessionArtifacts 过滤墓碑, 避免新回答把引用绑到已删文件上;版本澄清文案不再把已删版本算进版本数。 docs/swagger.* 未重新生成:仓库里那份已经落后若干功能,重生成会带进约 1000 行无关漂移,另开 PR 同步。 * fix(artifacts): close the delete holes found in review Regeneration. loadKnownSet 把墓碑的 ContentHash 也放进了去重集,于是 knownSameContent 会把「删除后技能重新生成、字节恰好相同」当成 fork checkout 那种 restore:不上传、不挂回本轮回答,文件再也回不来。墓碑现在 只登记 (path, mtime),不进 hash 也不进 byPath —— 前者才是「沙箱文件没动 过就别复活」需要的键,后者是「同内容恢复」的短路,两件事不该共用。 RecordRestoredArtifactMtime 也不再改墓碑:它的 mtime 就是那把锁。 Message file proxy. /sessions/:id/messages/:message_id/files 走 MessageReferencesFile,而正文检查在最前面且无条件为真。删除不会重写回答, resource:// 句柄还留在正文里,于是这条代理会继续把已删文件交出去——包括 交给共享智能体的只读访客,也包括「字节因为知识库还持有而没被回收」的情形。 现在先看 artifacts:命中本条消息的墓碑直接 false,命中 live 直接 true, 其余(知识库图、附件)才回落到正文。同一文件挂在多个位置时只要还有一个 live 就仍然可取。 Cross-session bytes. CreateForked 复制产物行时连同存储 URL 一起复制,但 不会给副本重新 Bind,所以 catalog 的引用计数看不到分叉。在父会话里删除会 把分叉还在用的字节删掉。无 catalog 部署、以及存的是裸 provider 路径的行, 同样不在计数覆盖内。回收前新增一道 CountLiveArtifactsByURL:只要还有任何 未删除的行指向同一对象就保留字节,查不出来也保留。配套加了 url 的部分索引。 Atomicity. SoftDeleteSessionArtifacts 原来逐条 UPDATE 不带事务,删多版本 时中途失败会留下「一部分已隐藏、字节没回收、接口 500、用户重试 404」。 现在整批放进一个事务。writeMessageArtifacts 是整表替换,拿着删除前快照的 并发写会让墓碑复活而字节已在回收,现在按 position 把已存在的 deleted_at 合并回去——删除是唯一不允许被过期写覆盖的属性。 all_versions 两个路由改用同一个解析器(strconv.ParseBool),此前一个是 == "true"、另一个是 != "false",显式传 1/TRUE 在两边语义不同;缺省值仍 按路由区分。 测试:收集器三条(未动不复活 / 重新生成要回来 / live 的同内容恢复仍短路)、 access 三条(正文不能复活已删授权、多副本只要有 live 就可取、非产物引用 仍走正文)、service 七条(归属人校验、他人会话拒绝、并发认领为空、live 行仍在则保留字节、guard 失败保留字节、多版本按对象归并 owner、无 source_path 不扫全会话)、repository 三条(墓碑抗过期写、事务回滚、跨会话 URL 计数)、handler 一条(两个路由的 all_versions 解析矩阵)。其中 「重新生成要回来」在改回旧实现时确认会失败。 client/ 没有 artifacts 相关 API(只有一个 SSE 事件类型常量),无需同步。
2026-09-20 05:01:46 +00:00
### 删除生成的文件
删除会回收对象存储中的字节,**不可恢复**。与下载不同,删除只对会话归属人开放:通过共享智能体获得的只读访问可以下载文件,但不能删除 —— 不属于自己的会话一律按 404 处理(不区分「不存在」和「无权限」,与其余会话接口一致)。已删除的文件返回 404,重复删除同样返回 404。
字节只有在没有任何其他持有者时才会真正回收:同一份文件被存入知识库、被后续回答重新引用,或者所在会话被分叉出副本,都会让它保留下来。回收失败不影响删除结果(接口仍返回 200),文件在各处列表中都已消失。
删除后该文件在列表接口和产物库中都不再出现,但它在消息中的**位置会被保留**:`index` 就是下载地址,如果后面的文件依次前移,已有的下载链接就会指向错的文件。同一原因,沙箱里的同名文件不会在下一轮采集时被重新收录 —— 它的 mtime 并没有因为用户删除而改变。
只有当没有其他持有者仍然引用该对象时才会真正删除字节:同一份文件如果被存入知识库、或被后续回答重新引用,都会各自持有一份引用,删除其中一处不会动到底层数据。
| 参数 | 说明 |
| --- | --- |
| `all_versions` | 连同本会话中同一 `source_path` 的所有历史版本一并删除。布尔值,默认 `false` |
```bash
curl -X DELETE "$BASE/api/v1/sessions/session-1/messages/message-1/artifacts/0" \
-H "Authorization: Bearer $TOKEN"
```
feat(artifacts): artifacts library page backed by a message_artifacts table (#3384) * feat(artifacts): add an artifacts library with its own message_artifacts table Skill-generated files were only reachable from inside the conversation that produced them. This adds a sidebar entry and a page that lists them across every conversation the user can see. Storage: artifacts move out of the messages.artifacts JSONB column into a new message_artifacts table (PostgreSQL 000103, SQLite 000023), backfilled on upgrade. The table is now the only source of truth; the old column is kept and the down migration writes the table back into it. The message repository loads artifacts for every message it returns and writes them on create, update (when non-nil) and fork, so callers still use Message.Artifacts. mod_time is stored as RFC 3339 text because the collector matches files on nanosecond mtimes, which PostgreSQL timestamps would truncate. API: GET /api/v1/artifacts lists the latest version of each file (grouped by session + source path, with version_count), scoped like the session list, with keyword / file type filters and paging. Downloads keep using the per-session endpoint. Frontend: "产物/Artifacts" sidebar entry (hidden without sandbox support), a library page with type tabs, search, date groups, infinite loading, preview drawer, download and jump-to-conversation; strings in all five locales. The sidebar's top-menu paths are now one shared list. * fix(artifacts): keep the restore hash guard and count versions by URL RecordRestoredArtifactMtime again only stamps rows whose content hash matches the restored content (and ignores empty hashes), and never rewrites the hash, matching MessageArtifacts.WithRestoredMtime. Without the guard a restore of v1's content also moved v2's mtime and relabelled v2 with v1's hash. The library's version_count now counts distinct URLs per (session, source path). A later answer that references an earlier file stores another row with the same URL, which COUNT(*) reported as an extra version. * fix(artifacts): scope the library to web chats and clear the legacy column The library used the session list's default scope, which counts sessions without an owner as legacy tenant-level rows. IM sessions are created without an owner, so every member saw the file names and titles of every IM chat (downloads then 404 for non-admins). The library now applies the same "web" bucket predicate as the home sidebar, extracted from QueryPaged so the two cannot drift: no IM mapping (including cleared ones), no embed marker, no API-key owner. Migrations 000103 / SQLite 000023 now clear messages.artifacts after the backfill. Message loads still SELECT *, so the stale copy was read on every history load. Only rows that carried artifacts are rewritten; the column stays for instances on the old binary during a rolling upgrade, and the down migration still rebuilds it from the table. * fix(migrations): keep the 000103 backfill alive on malformed artifact JSON A single file_size that is not an integer ("12.5", "") or a created_at that does not parse ("garbage", month 13) raised a cast error and failed the whole migration, blocking startup. Casts now go through pg_temp helpers that return NULL on bad input, falling back to 0 and the message's created_at; valid rows are unchanged. SQLite casts never raise; its migration test now covers the same malformed values. * docs(artifacts): describe the web-only library scope and the cleared legacy column
2026-09-18 04:10:19 +00:00
### 跨会话产物列表
`GET /api/v1/artifacts` 列出当前用户网页对话中的所有生成文件,供首页侧栏「产物」页使用。范围与会话列表的 `source=web` 一致:本人会话及历史上无归属的租户级网页会话;IM 渠道、网页挂件(embed)和 API Key 会话一律不含,即使 IM 会话在库中没有归属人。同一会话中 `source_path` 相同的文件视为同一文件的多个版本,只返回最新一版,`version_count` 给出版本数。已删除的会话或消息中的文件不返回。权限要求与上表相同。
| 参数 | 说明 |
| --- | --- |
| `keyword` | 按文件名过滤,不区分大小写 |
| `file_types` | 逗号分隔的扩展名,如 `.pdf,.pptx`(可省略点号) |
| `page` / `page_size` | 分页,`page_size` 最大 100,默认 20 |
响应 `{success, data:[LibraryArtifact], total, page, page_size}`,按生成时间倒序。LibraryArtifact 字段:session_id、session_title、message_id、index、handle(可选)、file_name、file_type、file_size、source_path、created_at、version_count。下载时用其中的 session_id、message_id、index 调用上表的下载接口。
```bash
curl "$BASE/api/v1/artifacts?file_types=.pptx,.pdf&keyword=报告&page=1&page_size=30" \
-H "Authorization: Bearer $TOKEN"
```
feat(artifacts): let users delete generated files (#3447) * feat(artifacts): let users delete generated files 技能生成的文件此前只能列出、预览和下载,没有任何删除入口,后端 handler/service/repository 三层都没有实现。DeleteSession 里那句注释 ("a dedicated GC job or explicit hard-delete API is the right place to reclaim storage") 留的就是这个位置。 Tombstone, not a row delete. message_artifacts 新增 deleted_at,删除只 打标记不删行。position 是下载接口寻址用的下标(msg.Artifacts[index]), 物理删掉中间一行会让它后面的文件整体前移,已有链接下到错的文件;而 ArtifactCollector 的去重集就是从这张表读的,行没了之后沙箱里 mtime 未变 的同名文件下一轮就会被重新采集回来,删了又出现。墓碑同时挡住这两条。 loadArtifactsByMessage 因此刻意保留墓碑,展示侧用 MessageArtifacts.Live 过滤;NewMessageArtifactRecords 带上 DeletedAt,任何一次消息重写都能把 墓碑原样写回去。 Bytes. 字节是真回收的,走 catalog.Release 引用计数:一份文件可能同时被 知识库条目和后续回答持有,只有所有持有者都放手才 DeleteFile。删多个版本 时同一个对象可能来自多条消息,每条消息的绑定都要释放,字节只删一次。 回收发生在打标记之后,且只针对本次调用真正认领到的行——并发的第二次删除 认领不到任何行,也就不会去动别人正在回收的对象。释放失败一律保留字节: 留个孤儿 blob 以后还能靠墓碑上的 url 回收,删错了则是别人的文档里的图片 凭空消失。 Scope. 会话内面板每个版本单独一行,删的就是点的那一版;产物库一行代表 一个文件(带版本数),默认连同该文件在这个会话里的所有版本一起删,否则 删完这一行还在、只是显示上一版。权限比下载严一档:下载认共享智能体的 只读访问,删除只认会话归属人。 Inline references. 正文里的 resource:// 引用渲染成置灰加删除线的卡片, 不可点击,和「模型引用了不存在的文件」的 --pending 态区分开。图片类产物 也降级成卡片:走 renderImage 只会拉取失败,留下一张永远加载不出来的图。 墓碑必须留在传给渲染器的产物列表里——句柄形式与知识库图片同形,过滤掉 之后句柄对不上本条回答,会被当成外部受保护图片去拉一个已经不存在的 blob,结果是裂图。组件里因此拆出 liveArtifacts 只给计数和文件列表用。 Also: 产物库是 offset 分页的无限列表,删一行会让后续页整体前移漏掉一条, 改成按已显示行数取下一页并按 key 去重;access.ResolveMessageArtifact 与 MessageReferencesFile 不再让墓碑授权访问;SessionArtifacts 过滤墓碑, 避免新回答把引用绑到已删文件上;版本澄清文案不再把已删版本算进版本数。 docs/swagger.* 未重新生成:仓库里那份已经落后若干功能,重生成会带进约 1000 行无关漂移,另开 PR 同步。 * fix(artifacts): close the delete holes found in review Regeneration. loadKnownSet 把墓碑的 ContentHash 也放进了去重集,于是 knownSameContent 会把「删除后技能重新生成、字节恰好相同」当成 fork checkout 那种 restore:不上传、不挂回本轮回答,文件再也回不来。墓碑现在 只登记 (path, mtime),不进 hash 也不进 byPath —— 前者才是「沙箱文件没动 过就别复活」需要的键,后者是「同内容恢复」的短路,两件事不该共用。 RecordRestoredArtifactMtime 也不再改墓碑:它的 mtime 就是那把锁。 Message file proxy. /sessions/:id/messages/:message_id/files 走 MessageReferencesFile,而正文检查在最前面且无条件为真。删除不会重写回答, resource:// 句柄还留在正文里,于是这条代理会继续把已删文件交出去——包括 交给共享智能体的只读访客,也包括「字节因为知识库还持有而没被回收」的情形。 现在先看 artifacts:命中本条消息的墓碑直接 false,命中 live 直接 true, 其余(知识库图、附件)才回落到正文。同一文件挂在多个位置时只要还有一个 live 就仍然可取。 Cross-session bytes. CreateForked 复制产物行时连同存储 URL 一起复制,但 不会给副本重新 Bind,所以 catalog 的引用计数看不到分叉。在父会话里删除会 把分叉还在用的字节删掉。无 catalog 部署、以及存的是裸 provider 路径的行, 同样不在计数覆盖内。回收前新增一道 CountLiveArtifactsByURL:只要还有任何 未删除的行指向同一对象就保留字节,查不出来也保留。配套加了 url 的部分索引。 Atomicity. SoftDeleteSessionArtifacts 原来逐条 UPDATE 不带事务,删多版本 时中途失败会留下「一部分已隐藏、字节没回收、接口 500、用户重试 404」。 现在整批放进一个事务。writeMessageArtifacts 是整表替换,拿着删除前快照的 并发写会让墓碑复活而字节已在回收,现在按 position 把已存在的 deleted_at 合并回去——删除是唯一不允许被过期写覆盖的属性。 all_versions 两个路由改用同一个解析器(strconv.ParseBool),此前一个是 == "true"、另一个是 != "false",显式传 1/TRUE 在两边语义不同;缺省值仍 按路由区分。 测试:收集器三条(未动不复活 / 重新生成要回来 / live 的同内容恢复仍短路)、 access 三条(正文不能复活已删授权、多副本只要有 live 就可取、非产物引用 仍走正文)、service 七条(归属人校验、他人会话拒绝、并发认领为空、live 行仍在则保留字节、guard 失败保留字节、多版本按对象归并 owner、无 source_path 不扫全会话)、repository 三条(墓碑抗过期写、事务回滚、跨会话 URL 计数)、handler 一条(两个路由的 all_versions 解析矩阵)。其中 「重新生成要回来」在改回旧实现时确认会失败。 client/ 没有 artifacts 相关 API(只有一个 SSE 事件类型常量),无需同步。
2026-09-20 05:01:46 +00:00
`DELETE /api/v1/artifacts` 删除产物库中的一个文件,用 query 参数 `session_id`、`message_id`、`index` 定位,语义与上面的会话内删除一致。区别只在于 `all_versions` 缺省时视为 `true`(显式传值时两个接口的解析规则相同):产物库一行代表一个文件(`version_count` 给出版本数)而不是某一次生成,只删最新一版会让这一行继续留在列表里、显示上一版。传 `all_versions=false` 可只删当前这一版。
```bash
curl -X DELETE "$BASE/api/v1/artifacts?session_id=session-1&message_id=message-1&index=0" \
-H "Authorization: Bearer $TOKEN"
```
### 回答中的图片和文件引用
`GET /api/v1/sessions/:id/messages/:message_id/files?file_path=...` 是消息级鉴权代理。file_path 传该消息引用的资源句柄或受支持的存储引用,客户端应 URL 编码。后端校验消息访问权、资源与消息的绑定及知识库/共享 Agent 的当前访问权;任意文件路径不能凭会话 ID 访问。授权撤销后旧消息引用也会被拒绝。适用于共享 Agent、组织共享库回答图片与消息产物,详见[文件访问](../03-features/21-file-access.md)。
### 每轮用量
消息返回持久化的 usage,Agent 完成事件携带 turn_usage;包含本轮各用途模型调用聚合结果。工具调用自身并不都产生 Token,用量以提供商返回或后端已采集的记录为准。字段见[可观测性](../03-features/16-observability.md)。
## 实现参考
路由注册:`internal/router/router.go` 的 `RegisterSessionRoutes`、`RegisterChatRoutes`、`RegisterMessageRoutes`。Handler:`internal/handler/session/`(handler.go、qa.go、stream.go、title.go、temporary_document.go)、`internal/handler/message.go`、`internal/handler/message_suggestion.go`。