代码提交

This commit is contained in:
董宏凯 committed 2026-08-30 01:25:20 +08:00
1 parent 4ac7bc21cd
commit 17cf849361
110 files changed
+17007 -518

No files matched your search

@@ -22,6 +22,16 @@ This directory contains detailed documentation for the DeerFlow backend.
| [plan_mode_usage.md](plan_mode_usage.md) | Plan mode with TodoList |
| [AUTO_TITLE_GENERATION.md](AUTO_TITLE_GENERATION.md) | Automatic title generation |
## Workflow Studio
| Document | Description |
|----------|-------------|
| [WORKFLOW_STUDIO_BACKEND_DEV_ZH.md](WORKFLOW_STUDIO_BACKEND_DEV_ZH.md) | 后端开发基线方案 + 各阶段完成状态 |
| [adr/0001-workflow-studio-runtime.md](adr/0001-workflow-studio-runtime.md) | ADR:Coze 只做画布 / ChatDev 只作参考 / 自建 DAG 调度器(LangGraph 仅作智能体内核) |
| [WORKFLOW_SCHEMA_V1_ZH.md](WORKFLOW_SCHEMA_V1_ZH.md) | 内部图 Schema v1.0 |
| [WORKFLOW_SSE_V1_ZH.md](WORKFLOW_SSE_V1_ZH.md) | SSE 事件协议 v1.0 |
| [WORKFLOW_OPENAPI_DRAFT_V1.yaml](WORKFLOW_OPENAPI_DRAFT_V1.yaml) | 接口 OpenAPI 草案 |
## Development
| Document | Description |
@@ -0,0 +1,740 @@
openapi: 3.0.3
info:
title: DeerFlow Workflow Studio API (Draft v1)
version: "1.0.0-draft"
description: |
Wire models: deerflow.workflows.schemas / events / errors.
Paths marked `x-implemented: false` are still sketches; everything else is
mounted today (app/gateway/routers/workflow*.py). Where the phase-0 sketch
and the implementation disagreed, this file follows the implementation.
servers:
- url: http://localhost:8001
description: Local Gateway
tags:
- name: workflows
- name: runs
- name: resources
- name: data-sources
- name: embed
- name: coze-compat
paths:
/api/workflows:
get:
tags: [workflows]
summary: List workflow definitions
responses:
"200":
description: OK
post:
tags: [workflows]
summary: Create workflow definition
responses:
"201":
description: Created
/api/workflows/{workflow_id}:
get:
tags: [workflows]
summary: Get workflow definition
parameters:
- $ref: "#/components/parameters/WorkflowId"
responses:
"200":
description: OK
patch:
tags: [workflows]
summary: Update workflow metadata
parameters:
- $ref: "#/components/parameters/WorkflowId"
responses:
"200":
description: OK
delete:
tags: [workflows]
summary: Soft-delete / archive
parameters:
- $ref: "#/components/parameters/WorkflowId"
responses:
"204":
description: Archived
/api/workflows/{workflow_id}/copy:
post:
tags: [workflows]
summary: Duplicate a workflow as a new draft owned by the caller
parameters:
- $ref: "#/components/parameters/WorkflowId"
responses:
"200":
description: Created copy
/api/workflows/{workflow_id}/draft:
put:
tags: [workflows]
summary: Save draft (optimistic lock)
parameters:
- $ref: "#/components/parameters/WorkflowId"
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [expectedRevision, graph]
properties:
expectedRevision:
type: integer
graph:
$ref: "#/components/schemas/WorkflowGraph"
responses:
"200":
description: Saved
"409":
description: Draft revision conflict
/api/workflows/{workflow_id}/validate:
post:
tags: [workflows]
summary: Validate draft without publishing
parameters:
- $ref: "#/components/parameters/WorkflowId"
responses:
"200":
description: Validation result
/api/workflows/{workflow_id}/publish:
post:
tags: [workflows]
summary: Publish immutable version
parameters:
- $ref: "#/components/parameters/WorkflowId"
responses:
"201":
description: Version created
/api/workflows/{workflow_id}/versions:
get:
tags: [workflows]
summary: List published versions
parameters:
- $ref: "#/components/parameters/WorkflowId"
responses:
"200":
description: OK
/api/workflows/{workflow_id}/versions/{version_id}:
get:
tags: [workflows]
summary: Get one published version snapshot
parameters:
- $ref: "#/components/parameters/WorkflowId"
- $ref: "#/components/parameters/VersionId"
responses:
"200":
description: OK
/api/workflows/node-types:
get:
tags: [resources]
summary: List supported node types
responses:
"200":
description: OK
/api/workflows/resources/agents:
get:
tags: [resources]
summary: Agents available to workflow nodes
responses:
"200":
description: OK
/api/workflows/resources/skills:
get:
tags: [resources]
summary: Skills available to workflow nodes
responses:
"200":
description: OK
/api/workflows/resources/data-sources:
get:
tags: [resources]
summary: Registered read-only data sources
responses:
"200":
description: OK
/api/workflows/resources/subworkflows:
get:
tags: [resources]
summary: Published workflows usable as subworkflows
responses:
"200":
description: OK
/api/workflows/data-sources:
get:
tags: [data-sources]
summary: List data sources visible to the caller (own + shared)
description: |
Never returns the DSN or credential headers — only `masked_target`.
responses:
"200":
description: OK
post:
tags: [data-sources]
summary: Register a data source (`shared: true` is admin-only)
description: |
`kind: sql` requires `dsn`; `kind: http` requires `headers`. The secret
is encrypted on write and only ever decrypted inside the run executor.
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/DataSourceCreate"
responses:
"200":
description: Created (masked view)
"503":
description: WORKFLOW_SECRET_KEY not configured
/api/workflows/data-sources/{id}:
get:
tags: [data-sources]
summary: Get one data source (masked view)
parameters:
- $ref: "#/components/parameters/DataSourceId"
responses:
"200":
description: OK
put:
tags: [data-sources]
summary: Update data source (owner or admin)
parameters:
- $ref: "#/components/parameters/DataSourceId"
responses:
"200":
description: OK
delete:
tags: [data-sources]
summary: Delete data source (owner or admin)
parameters:
- $ref: "#/components/parameters/DataSourceId"
responses:
"200":
description: '{ "deleted": true }'
/api/workflows/data-sources/{id}/introspect:
post:
tags: [data-sources]
summary: Introspect whitelisted schema/table/column metadata
description: Returns the configured table allowlist only. Never returns sample rows or secrets.
parameters:
- $ref: "#/components/parameters/DataSourceId"
responses:
"200":
description: '{ dataSourceId, kind, tables, schemas }'
/api/workflows/data-sources/{id}/validate-query:
post:
tags: [data-sources]
summary: Validate SQL against read-only policy (no execution)
parameters:
- $ref: "#/components/parameters/DataSourceId"
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [statement]
properties:
statement:
type: string
responses:
"200":
description: '{ ok: true, statement }'
"400":
description: WORKFLOW_SQL_POLICY_DENIED
/api/workflows/{workflow_id}/runs:
post:
tags: [runs]
summary: Start a run against a published version
parameters:
- $ref: "#/components/parameters/WorkflowId"
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/StartRunRequest"
responses:
"200":
description: |
Run view plus `created`; `created: false` means the idempotencyKey
matched an existing run (scoped per workflow).
"400":
description: WORKFLOW_INPUT_INVALID / WORKFLOW_VERSION_NOT_FOUND
"429":
description: WORKFLOW_LIMIT_EXCEEDED (per-user concurrent runs)
get:
tags: [runs]
summary: List runs for a workflow
parameters:
- $ref: "#/components/parameters/WorkflowId"
responses:
"200":
description: OK
/api/workflows/runs/{run_id}:
get:
tags: [runs]
summary: Get run status projection plus current node runs
description: |
Never includes `resumeToken` — that is delivered on the event stream only.
parameters:
- $ref: "#/components/parameters/RunId"
responses:
"200":
description: OK
"403":
description: WORKFLOW_FORBIDDEN (not owner, not admin)
"404":
description: WORKFLOW_RUN_NOT_FOUND
/api/workflows/runs/{run_id}/events:
get:
tags: [runs]
summary: Page durable events
parameters:
- $ref: "#/components/parameters/RunId"
- name: after
in: query
description: Exclusive `seq` cursor. `after_seq` is accepted as an alias.
schema:
type: integer
default: 0
- name: after_seq
in: query
schema:
type: integer
- name: limit
in: query
schema:
type: integer
default: 200
maximum: 1000
responses:
"200":
description: '{ "events": [...], "lastSeq": 42 }'
/api/workflows/runs/{run_id}/stream:
get:
tags: [runs]
summary: SSE replay + live tail
description: |
Replays from `Last-Event-ID` (preferred) or `after` / `after_seq`, then
tails live. Closes on the first terminal event; if the run is already
terminal without one, a synthesised terminal frame is emitted so the
client never hangs.
parameters:
- $ref: "#/components/parameters/RunId"
- name: after
in: query
schema:
type: integer
default: 0
- name: after_seq
in: query
schema:
type: integer
- name: Last-Event-ID
in: header
schema:
type: string
responses:
"200":
description: text/event-stream
headers:
X-Workflow-Run-Status:
description: Run status at connection time.
schema:
type: string
content:
text/event-stream:
schema:
type: string
/api/workflows/runs/{run_id}/cancel:
post:
tags: [runs]
summary: Request cancellation (idempotent)
parameters:
- $ref: "#/components/parameters/RunId"
responses:
"200":
description: |
Run view plus `cancelled`; `false` means it was already terminal.
/api/workflows/runs/{run_id}/resume:
post:
tags: [runs]
summary: Resume after human_input
parameters:
- $ref: "#/components/parameters/RunId"
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/ResumeRunRequest"
responses:
"200":
description: Requeued
"409":
description: WORKFLOW_RUN_NOT_RESUMABLE / WORKFLOW_RESUME_TOKEN_INVALID
/api/workflows/runs/{run_id}/retry:
post:
tags: [runs]
summary: Retry a failed run from the first unfinished node
description: |
Creates a new queued run with `retryOfRunId` pointing at the failed
original. Completed `workflow_node_runs` are copied so the engine
resumes from the failed node; if nothing is replayable it is a full
re-run of the same version and inputs. Only `failed` runs are retryable.
parameters:
- $ref: "#/components/parameters/RunId"
responses:
"201":
description: '{ ..., retryOfRunId, created: true }'
"409":
description: WORKFLOW_RUN_NOT_RETRYABLE
"429":
description: WORKFLOW_LIMIT_EXCEEDED
/api/workflows/runs/{run_id}/artifacts:
get:
tags: [runs]
summary: List artifacts for a run
parameters:
- $ref: "#/components/parameters/RunId"
responses:
"200":
description: OK
/api/workflows/embed/tickets:
post:
tags: [embed]
summary: Issue a short-lived iframe ticket (authenticated parent)
description: |
`origin` must exactly match `workflows.embed.allowed_origins`. The
response also carries `frameAncestors` for the host's CSP.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [workflowId, origin]
properties:
workflowId:
type: string
origin:
type: string
responses:
"200":
description: '{ ticket, expiresIn, origin, frameAncestors }'
"403":
description: WORKFLOW_EMBED_ORIGIN_DENIED / WORKFLOW_FORBIDDEN
"503":
description: No signing key configured
/api/workflows/embed/verify:
post:
tags: [embed]
summary: Verify a ticket (single-use, best effort per process)
description: |
A ticket proves "this origin may embed this workflow for this user right
now". It is NOT an API credential — embedded pages still authenticate
their API calls with the normal session.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [ticket]
properties:
ticket:
type: string
origin:
type: string
responses:
"200":
description: '{ ok, workflowId, userId, origin, expiresAt }'
"401":
description: WORKFLOW_EMBED_TICKET_INVALID (expired or replayed)
"403":
description: WORKFLOW_EMBED_ORIGIN_DENIED (origin mismatch)
/api/workflow_api/canvas:
post:
tags: [coze-compat]
summary: Coze canvas load adapter
responses:
"200":
description: Coze DTO
/api/workflow_api/save:
post:
tags: [coze-compat]
summary: Coze canvas save adapter
responses:
"200":
description: Saved
/api/workflow_api/create:
post:
tags: [coze-compat]
summary: Coze create workflow adapter
responses:
"200":
description: Created
/api/workflow_api/node_template_list:
post:
tags: [coze-compat]
summary: Coze node template list adapter
responses:
"200":
description: Templates
components:
parameters:
WorkflowId:
name: workflow_id
in: path
required: true
schema:
type: string
VersionId:
name: version_id
in: path
required: true
schema:
type: string
RunId:
name: run_id
in: path
required: true
schema:
type: string
DataSourceId:
name: id
in: path
required: true
schema:
type: string
schemas:
WorkflowGraph:
type: object
description: Internal standard graph (see WORKFLOW_SCHEMA_V1_ZH.md)
required: [schemaVersion, id, nodes, edges]
properties:
schemaVersion:
type: string
enum: ["1.0"]
id:
type: string
name:
type: string
description:
type: string
inputSchema:
type: object
outputSchema:
type: object
nodes:
type: array
items:
$ref: "#/components/schemas/WorkflowNode"
edges:
type: array
items:
$ref: "#/components/schemas/WorkflowEdge"
settings:
$ref: "#/components/schemas/WorkflowGraphSettings"
WorkflowNode:
type: object
required: [id, type]
properties:
id:
type: string
type:
type: string
enum:
- start
- output
- agent
- skill
- http
- sql_read
- code
- transform
- condition
- merge
- human_input
- subworkflow
- loop
name:
type: string
config:
type: object
WorkflowEdge:
type: object
required: [id, source, target]
properties:
id:
type: string
source:
type: string
target:
type: string
sourcePort:
type: string
nullable: true
WorkflowGraphSettings:
type: object
properties:
runTimeoutSeconds:
type: integer
default: 1800
nodeTimeoutSeconds:
type: integer
default: 300
maxSteps:
type: integer
default: 200
maxLoopIterations:
type: integer
default: 5
maxParallelism:
type: integer
default: 4
NodeResult:
type: object
properties:
data:
type: object
messages:
type: array
items:
type: object
artifacts:
type: array
items:
$ref: "#/components/schemas/ArtifactRef"
metadata:
type: object
warnings:
type: array
items:
type: string
ArtifactRef:
type: object
required: [artifactId, name]
properties:
artifactId:
type: string
name:
type: string
mimeType:
type: string
path:
type: string
sizeBytes:
type: integer
nullable: true
preview:
type: string
nullable: true
StartRunRequest:
type: object
properties:
versionId:
type: string
description: Omit to use the latest published version.
inputs:
type: object
idempotencyKey:
type: string
maxLength: 128
executionMode:
type: string
enum: [normal]
default: normal
ResumeRunRequest:
type: object
required: [resumeToken]
properties:
resumeToken:
type: string
nodeId:
type: string
description: Defaults to the paused node from `pendingInput`.
action:
type: string
default: submit
values:
type: object
DataSourceCreate:
type: object
required: [name]
properties:
name:
type: string
description:
type: string
kind:
type: string
enum: [sql, http]
default: sql
dsn:
type: string
description: Write-only; required for `kind: sql`.
headers:
type: object
additionalProperties:
type: string
description: Write-only; required for `kind: http`.
maxRows:
type: integer
default: 1000
allowedTables:
type: array
items:
type: string
enabled:
type: boolean
default: true
shared:
type: boolean
default: false
description: Admin-only. Shared sources have a null owner.
WorkflowEventEnvelope:
type: object
required: [schemaVersion, runId, workflowId, versionId, seq, event]
properties:
schemaVersion:
type: string
enum: ["1.0"]
runId:
type: string
workflowId:
type: string
versionId:
type: string
seq:
type: integer
event:
type: string
nodeId:
type: string
nullable: true
nodeRunId:
type: string
nullable: true
timestamp:
type: string
format: date-time
data:
type: object
WorkflowErrorBody:
type: object
required: [code, message]
properties:
code:
type: string
message:
type: string
retryable:
type: boolean
nodeId:
type: string
nullable: true
details:
type: object
@@ -0,0 +1,93 @@
# 工作流图 Schema v1.0(冻结)
> 阶段 0 交付。实现源:`packages/harness/deerflow/workflows/schemas.py`
> 样例:`packages/harness/deerflow/workflows/samples/`
> ADR:[`adr/0001-workflow-studio-runtime.md`](adr/0001-workflow-studio-runtime.md)
## 原则
- Coze 画布 DTO **进入 Gateway 后**转换成此内部结构;运行时不依赖 Coze 私有字段。
- Wire JSON 使用 **camelCase**;Python 模型使用 snake_case(`populate_by_name=True`)。
- `schemaVersion` 固定为 `"1.0"`;破坏性变更必须升版本并双写迁移说明。
## 顶层 `WorkflowGraph`
| 字段 | 类型 | 说明 |
|------|------|------|
| `schemaVersion` | `"1.0"` | 协议版本 |
| `id` | string | 工作流逻辑 id(定义侧稳定标识) |
| `name` / `description` | string | 展示用 |
| `inputSchema` / `outputSchema` | JSON Schema object | 开始/输出校验 |
| `nodes` | `WorkflowNode[]` | 节点列表,`id` 唯一 |
| `edges` | `WorkflowEdge[]` | 边列表,`id` 唯一;`source`/`target` 必须引用已有节点 |
| `settings` | object | 见下 |
### `settings`
| 字段 | 默认 | 说明 |
|------|------|------|
| `runTimeoutSeconds` | 1800 | 整 run 超时 |
| `nodeTimeoutSeconds` | 300 | 单节点默认超时 |
| `maxSteps` | 200 | 最大节点步数 |
| `maxLoopIterations` | 5 | 全局循环上限 |
| `maxParallelism` | 4 | 同层并行度 |
发布时仍受系统级配额覆盖(阶段 6)。
## 节点类型(封闭集合)
`start` · `output` · `agent` · `skill` · `http` · `sql_read` · `code` · `transform` · `condition` · `merge` · `human_input` · `subworkflow` · `loop`
每类最小样例见 `workflows/samples/nodes/<type>.json`。
## `NodeResult`(统一节点结果)
```json
{
"data": {},
"messages": [],
"artifacts": [
{
"artifactId": "artifact_01",
"name": "专题报告.md",
"mimeType": "text/markdown",
"path": "/mnt/data/专题报告.md"
}
],
"metadata": {},
"warnings": []
}
```
大文本 / 二进制 / 超大查询结果写入 artifact,事件与 `output_json` 只传引用与有界预览。
## 运行状态
`queued` → `running` → `awaiting_input` | `completed` | `failed` | `cancel_requested` → `cancelled`
终态:`completed` / `failed` / `cancelled`。
## 安全表达式(约定,求值器阶段 2+)
允许只读引用:
- `{{ inputs.<field> }}`
- `{{ nodes.<nodeId>.data... }}`
- `{{ run.id }}`
禁止:`eval`、任意属性反射、字符串拼接构造 SQL/HTTP。条件节点运算符白名单:相等、包含、数值比较、空值、布尔组合。
## `graph_hash`
对规范化 camelCase JSON(`model_dump_json(by_alias=True, exclude_none=True)`)做 SHA-256。发布版本写入 `workflow_versions.graph_hash`;编译缓存可按 hash 做有界缓存,缓存对象不得含用户密钥。
## 样例图
| 文件 | 用途 |
|------|------|
| `samples/report_generation.json` | 专题报告端到端验收基线 |
| `samples/start_output.json` | 最小 start→output(运行骨架) |
| `samples/nodes/*.json` | 各节点最小 config |
| `samples/event_envelope_example.json` | SSE envelope 契约样例 |
加载:`from deerflow.workflows.samples import load_sample_graph`。
@@ -0,0 +1,107 @@
# 工作流 SSE / 事件协议 v1.0(冻结)
> 实现源:`packages/harness/deerflow/workflows/events.py`
> 错误体:`packages/harness/deerflow/workflows/errors.py`
> 事件清单与开发方案对齐:`WORKFLOW_STUDIO_BACKEND_DEV_ZH.md` §9
## 不变式
1. **先持久化,后发布** — 用户可见事件先写入 `workflow_run_events`,提交成功后再 fan-out。
2. **`seq` 严格单调** — 唯一键 `(run_id, seq)`。
3. **可重放** — `Last-Event-ID` 优先于 `after_seq`,否则从 `0`。
4. **增量合并** — 模型 token 建议 30–100ms 或约 1KB 合并落库。
5. **终态停连** — `run.completed` / `run.failed` / `run.cancelled` 且库已补齐后关闭 SSE。
6. **不泄密** — 无凭据、无完整认证头、无 DB 连接串、无隐藏思维链。
## 端点(阶段 2 已实现)
```http
GET /api/workflows/runs/{run_id}/stream?after=128
Accept: text/event-stream
Last-Event-ID: 128
```
实现:`app/gateway/routers/workflow_runs.py`。
- **库是排序的权威来源**:连接先按 `Last-Event-ID`(优先)或 `after` 从 `workflow_run_events` 回放,再挂 `WorkflowLiveHub` 订阅实时帧;`seq` 不大于已回放游标的实时帧被丢弃,下一轮 DB 轮询(0.8s)会带上它。断线重连因此不会看到空洞或乱序。
- **终态必闭**:读到 `run.completed` / `run.failed` / `run.cancelled` 即关闭。若运行已是终态却没有终态事件(例如崩在写事件之前),补发一条 `synthesised: true` 的终态帧再关闭,客户端不会永久挂住。
- **响应头** `X-Workflow-Run-Status` 给出连接建立瞬间的状态。
- Heartbeat:SSE comment `: heartbeat`(**不写库**),15s 静默后发送。
- 同一份事件也可用 `GET /api/workflows/runs/{run_id}/events?after=&limit=` 分页拉取(无长连接场景)。
## Envelope
```json
{
"schemaVersion": "1.0",
"runId": "run_01",
"workflowId": "wf_01",
"versionId": "wv_03",
"seq": 42,
"event": "node.output.delta",
"nodeId": "agent_writer",
"nodeRunId": "nr_09",
"timestamp": "2026-08-26T10:00:00+08:00",
"data": {}
}
```
SSE 帧:
```text
id: 42
event: node.output.delta
data: { ... envelope ... }
```
Python:`WorkflowEventEnvelope.to_sse_frame()`。
## 事件类型(封闭集合)
| 事件 | `data` 要点 |
|------|-------------|
| `run.created` | input 摘要、version |
| `run.queued` | queue 信息 |
| `run.started` | startedAt |
| `node.queued` | node 信息 |
| `node.started` | attempt、输入摘要 |
| `node.progress` | phase、message、percent |
| `node.output.delta` | channel、delta |
| `node.tool.started` | toolCallId、name、input 摘要 |
| `node.tool.finished` | toolCallId、status、output 摘要 |
| `artifact.created` | artifact 元数据 |
| `node.completed` | output 摘要、duration |
| `node.failed` | error code/message/retryable |
| `run.awaiting_input` | formSchema、actions、resumeToken |
| `run.resumed` | action |
| `run.cancel_requested` | requestedBy |
| `run.cancelled` | finishedAt |
| `run.completed` | output、artifacts |
| `run.failed` | error、failedNodeId |
## 统一错误体
```json
{
"code": "WORKFLOW_SQL_POLICY_DENIED",
"message": "SQL 节点只允许单条只读查询",
"retryable": false,
"nodeId": "sql_1",
"details": { "rule": "single_read_statement" }
}
```
完整错误码列表:`ALL_WORKFLOW_ERROR_CODES`(`deerflow.workflows.errors`)。
## `resumeToken` 只走事件流
`run.awaiting_input` 的 `data.resumeToken` 是恢复运行的唯一凭证,**只在事件流里出现**——`GET /api/workflows/runs/{run_id}` 的运行视图不包含它。恢复时 `POST /api/workflows/runs/{run_id}/resume` 携带该 token,服务端以「消费即失效」的方式原子翻转状态(同一个 token 不能恢复两次)。
## 前后端契约测试
前后端共用 fixture:
- `workflows/samples/event_envelope_example.json`
- 本文件事件名表
实现测试:`tests/test_workflow_runs.py`(回放游标、终态关闭、暂停/恢复的事件序列)。
@@ -3,7 +3,16 @@
> 文档状态:开发基线方案
> 适用项目:`offline-backend-20260512/backend`
> 对接前端:Coze Studio 独立工作流页面 `frontend/apps/coze-studio/src/workflow-standalone/`
> 更新时间:2026-08-26
> 更新时间:2026-08-29
> **阶段 0 状态:已完成** — 协议代码 `packages/harness/deerflow/workflows/`;文档见 `WORKFLOW_SCHEMA_V1_ZH.md` / `WORKFLOW_SSE_V1_ZH.md` / `WORKFLOW_OPENAPI_DRAFT_V1.yaml` / `adr/0001-workflow-studio-runtime.md`;契约测试 `tests/test_workflow_schemas.py`
> **阶段 1 状态:已完成** — 定义/版本持久化、草稿乐观锁、validate/publish、节点目录、Coze canvas/save/create/node_template 最小适配;路由 `/api/workflows*` + `/api/workflow_api*`;测试 `tests/test_workflow_definitions.py`(尚不执行运行)
> **阶段 2 状态:已完成** — run/node_run/event/artifact 表 + 迁移 `20260828_02`;幂等启动、租约调度、重启恢复、持久事件日志、SSE 回放/追尾。**编排内核改为自建 DAG 调度器,不再编译成 LangGraph**(理由见 `adr/0001` 阶段 2 修订)
> **阶段 3 状态:已完成** — start/output/transform/condition/merge + 安全表达式引擎;http 节点 SSRF 默认拒内网;sql_read 只读策略 + 数据源登记(密钥加密、只写不读,迁移 `20260828_03`);code 节点加固子进程执行器(**默认关闭**)
> **阶段 4 状态:已完成** — agent / skill 节点走 DeerFlow lead agent,模型增量与工具步骤映射为 `node.output.delta` / `node.tool.*`
> **阶段 5 状态:已完成** — `human_input` 暂停 + 一次性 resume token、子工作流(深度上限 3)、显式循环与 `max_loop_iterations` / `max_steps` 上限
> **阶段 6 状态:已完成** — iframe 票据(origin 白名单 + 60s 一次性 + `frameAncestors`)、按 owner/admin 的运行与数据源鉴权、每用户并发运行上限、结构化审计日志、事件/运行保留期配置与后台清理作业(`WorkflowRetentionCleaner`,每小时扫一次)、失败运行 `POST /retry`(复制已完成节点从失败点续跑,新 run 标 `retry_of_run_id`)、SSE `Last-Event-ID` 优先于 `after`。制品落盘文件仍跟随现有 sandbox/artifact 生命周期,不做工作流专属文件回收。多实例租约竞争 + SSE 重连有单机并发测试(`test_two_dispatchers_only_one_claims_a_run` / `test_sse_reconnect_storm_is_ordered_and_complete`),不是外部分布式压测。
> **审计整改(2026-08-29)状态:功能健壮性项已完成** — 按 `WORKFLOW_STUDIO_BACKEND_REMEDIATION_ZH.md`「0. 整改决策记录」:①人工恢复原子化(`resume_with_payload` 单条件更新 + `set_awaiting_input` 一次写入 checkpoint);②草稿保存 CAS 条件更新(409 带 `currentRevision`)+ 发布版本号计数器 `workflow_definitions.next_version_number`;③事件 seq 计数器 `workflow_runs.next_event_seq`(同事务取号,冲突自愈重试),事件落库失败**丢弃不发布**(删除负序号幽灵事件);④输入/输出完整 JSON Schema 校验(`workflows/schema_validation.py`,路由 400 + 节点错误均带字段路径);⑤测试纳入 Git(`.gitignore` 白名单)+ 新增 SQL 并发回归 `tests/test_workflow_concurrency.py`。迁移 `20260828_04_workflow_counter_columns.py` 增加两个计数器列(存量库由启动列同步自动补齐)。P0-01/02(内网可信环境,不实施)、P1-04/05(安全隔离,暂缓)见整改文档决策记录。
> 运行时测试:`tests/test_workflow_engine.py`(引擎、表达式、节点、安全策略)+ `tests/test_workflow_runs.py`(HTTP 生命周期、SSE、暂停恢复、租约回收、数据源、票据)+ `tests/test_workflow_concurrency.py`(整改并发回归:内存 + 真实 SQLite)
## 1. 目标与结论
@@ -189,6 +198,8 @@ ChatDev 适合参考的源码路径见第 15 节。
画布只保存 `data_source_id`。前端永远拿不到数据库密码,运行事件也不能回传连接串或认证头。
HTTP 接口资源使用同一张表:kind=http 时,base_url 和 allowed_methods 是可展示的非密钥元数据;请求头仍加密放在 credential blob,列表、详情、资源目录和运行事件均不得回显。创建时至少提供一个允许方法,地址只接受不含账户密码、查询参数或片段的 http(s) URL。迁移:20260829_01_workflow_http_source_metadata.py。
### 5.4 iframe 短时票据
如 Coze 页面与 DeerFlow 不同域,新增短时、一次性的嵌入票据:
@@ -581,6 +592,7 @@ DELETE /api/workflows/{workflow_id} # 软删除/归档
PUT /api/workflows/{workflow_id}/draft # draft_revision 乐观锁
POST /api/workflows/{workflow_id}/validate
POST /api/workflows/{workflow_id}/publish
POST /api/workflows/{workflow_id}/copy
GET /api/workflows/{workflow_id}/versions
GET /api/workflows/{workflow_id}/versions/{version_id}
```
@@ -602,18 +614,19 @@ GET /api/workflows/resources/subworkflows
### 10.3 数据源
```text
GET /api/workflow-data-sources
POST /api/workflow-data-sources # 管理员或授权角色
GET /api/workflow-data-sources/{id}
PATCH /api/workflow-data-sources/{id}
DELETE /api/workflow-data-sources/{id}
POST /api/workflow-data-sources/{id}/test
POST /api/workflow-data-sources/{id}/introspect
POST /api/workflow-data-sources/{id}/validate-query
GET /api/workflows/data-sources
POST /api/workflows/data-sources
GET /api/workflows/data-sources/{id}
PUT /api/workflows/data-sources/{id}
DELETE /api/workflows/data-sources/{id}
POST /api/workflows/data-sources/{id}/introspect
POST /api/workflows/data-sources/{id}/validate-query
```
`introspect` 只返回白名单内 schema/table/column 元数据,不返回样例敏感数据。
HTTP 接口资源的创建体使用 kind=http、baseUrl、allowedMethods 和可选 headers;headers 是只写字段,服务端加密后不会出现在响应。资源目录 GET /api/workflows/resources/data-sources 返回前端所需的 dataSourceId、baseUrl、allowedMethods、description 等精简字段。
### 10.4 运行
```text
@@ -743,7 +756,7 @@ POST /api/workflow-embed/tickets/exchange
- SQL 只读:连接临时失败可有限重试;语法/权限错误不重试。
- HTTP:GET/HEAD 可按策略重试;POST 默认不重试,除非配置幂等键。
- 代码:资源不足或代码错误默认不重试。
- 工作流级 retry 建议从失败节点恢复;若 checkpoint 不可靠则创建新 run 并标记 `retry_of_run_id`。
- 工作流级 retry:`POST /api/workflows/runs/{run_id}/retry` 仅接受 `failed` 运行。新 run 复制已完成节点输出并从失败节点续跑;没有任何可回放 checkpoint 时则整图重跑,并标记 `retry_of_run_id`。
### 12.3 取消
@@ -1083,6 +1096,8 @@ tests/test_workflow_migrations.py
- 多 Gateway 实例、租约竞争、数据库短暂失败、SSE 大量重连压测。
- 事件保留、清理和 artifact 生命周期。
阶段 6 已落地:`WorkflowRetentionCleaner` 消费 `workflows.retention.*`;`POST /api/workflows/runs/{run_id}/retry`;SSE `Last-Event-ID`;单机租约竞争与 SSE 重连风暴测试。制品文件仍走 sandbox/artifact,不另做工作流专属文件回收。
### 阶段 7:试点与扩展(持续)
- 选择 1–2 个报告业务真实试点。
@@ -0,0 +1,674 @@
# Workflow Studio 后端审计整改方案
> 文档状态:已按 2026-08-29 决策部分实施(见「0. 整改决策记录」)
> 适用范围:`offline-backend-20260512/backend`
> 审核日期:2026-08-28(决策与实施:2026-08-29)
> 关联文档:[工作流编排与流式执行后端开发方案](./WORKFLOW_STUDIO_BACKEND_DEV_ZH.md)
> 适用对象:后端开发、测试、安全评审、运维发布
## 0. 整改决策记录(2026-08-29)
本轮整改以**功能健壮性**为唯一目标(用户决策:"咱们这次的整改主要是保证功能的健壮"),安全隔离类项目暂缓。逐项状态:
| 项目 | 状态 | 说明 |
|---|---|---|
| P1-01 人工介入恢复原子性 | ✅ 已实施 | `resume_with_payload` 单条件更新,并发恢复恰一个成功 |
| P1-02 草稿乐观锁 + 发布版本号 | ✅ 已实施 | 草稿 CAS 条件更新;`next_version_number` 计数器分配版本号 |
| P1-03 事件序号 + SSE 一致性 | ✅ 已实施 | `next_event_seq` 计数器;落库失败**丢弃不发布**(无幽灵事件) |
| P1-06 测试纳入版本控制 | ✅ 已实施 | `.gitignore` 白名单 + 新增 `tests/test_workflow_concurrency.py`(SQL 并发) |
| P2 §11.1 完整 JSON Schema 校验 | ✅ 已实施 | `schema_validation.py`(Draft202012,中文字段路径错误) |
| P0-01 数据源越权 / HTTP 凭证外泄 | ❌ 不实施 | **内网可信环境**,按 ID 共享数据源、HTTP 节点访问任意内网地址是既有使用方式,加 owner 校验 / host 白名单会直接破坏现网用法,风险由部署方接受 |
| P0-02 子工作流跨用户执行 | ❌ 不实施 | 同上:内网用户间按 ID 引用子工作流是预期用法 |
| P1-04 智能体/技能最小权限 | ⏸ 暂缓 | 安全隔离类,本轮不做(用户决策:"安全性的问题咱们暂时不用做") |
| P1-05 代码节点沙箱化 | ⏸ 暂缓 | 同上;`config.yaml` 中 `workflows.code.enabled` 保持默认 `false`,代码节点不开放 |
| P2 §11.2 iframe Redis nonce | ⏸ 暂缓 | 单实例部署,进程内 replay cache + 60s TTL 足够;多实例化时再引入 Redis |
已实施项的回归测试集中在 `tests/test_workflow_concurrency.py`(内存 + 真实 SQLite 双轨),外加 `tests/test_workflow_runs.py` 的路由级 schema 校验回归;全部 88 个 workflow 测试通过。
## 1. 结论与整改目标
当前 Workflow Studio 的定义、发布、运行、SSE、SQL/HTTP、智能体、技能、人工介入等功能骨架已经具备,且基础测试可运行。但在共享资源授权、凭证使用边界、并发一致性、事件可靠性和代码执行隔离方面存在上线阻断问题。
本次整改的目标不是继续扩展节点功能,而是让现有节点满足以下底线:
1. 一个用户不能通过资源 ID、流程 JSON 或子工作流引用使用别人的私有资源。
2. HTTP 凭证只能发送至管理员明确批准的目标域名,不能被流程编辑者导出到任意 URL。
3. 人工介入恢复、草稿保存、发布版本和事件序号在多请求、多实例条件下保持一致。
4. SSE 中显示的业务事件必须能够从数据库重放;不能出现只在内存短暂存在的“幽灵事件”。
5. 智能体和技能节点只能使用流程配置所授予的能力。
6. 代码节点只有在隔离沙箱中才能开启,不能在 Gateway 宿主机执行用户代码。
在 P0 项全部完成前,生产环境不得向普通用户开放:共享 SQL 数据源、共享 HTTP 凭证、子工作流跨用户引用和工作流编辑/执行权限。
## 2. 总体整改策略
### 2.1 建立运行时资源授权边界
当前 API 层可以识别当前用户,但执行器通常只持有 `source_id`、`workflow_id` 或 `agent_id`。整改后必须将“谁在执行”作为运行时一等参数,从创建运行记录开始贯穿到每一个节点。
新增领域对象,建议放在 `packages/harness/deerflow/workflows/`:
```python
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class WorkflowExecutionPrincipal:
"""工作流运行时的可信执行身份,由 Gateway 创建,不接受前端传入。"""
user_id: str
is_admin: bool = False
tenant_id: str | None = None
```
运行创建时将发起人固化在 `workflow_runs.owner_id`,恢复、重试和子工作流也沿用原始运行的 `owner_id`,不得使用前端请求中的任意 `user_id`。
```python
principal = WorkflowExecutionPrincipal(
user_id=run.owner_id,
is_admin=await permission_service.is_admin(run.owner_id),
tenant_id=run.tenant_id,
)
```
所有需要使用资源的运行时入口必须接收 `principal`:
```python
data_source_store.resolve_for_execution(source_id, principal)
workflow_store.get_published_for_execution(workflow_id, version_id, principal)
agent_store.get_visible(agent_id, principal.user_id)
skill_registry.resolve_allowed(skill_id, principal, agent)
```
资源不存在、无权限、已禁用三种情况对普通用户应统一返回 `RESOURCE_NOT_AVAILABLE`,避免通过 UUID 枚举资源。
### 2.2 采用“发布校验 + 运行时校验”的双层防线
发布时校验是为了尽早提示编辑者;运行时校验是为了防止发布后授权被收回、资源被禁用、恶意请求绕过 UI 或历史版本继续引用资源。
| 阶段 | 应做的事 |
|---|---|
| 保存草稿 | 校验节点结构、字段格式,不因暂时无权限而破坏用户草稿 |
| 发布版本 | 校验每个外部资源对发布者是否可用,并将资源依赖写入版本元数据 |
| 创建运行 | 再次校验工作流版本和根工作流权限 |
| 节点执行 | 每次解析数据源、智能体、技能、子工作流时按 `principal` 校验 |
| 重试/恢复 | 使用原 run 的身份和已发布版本,不重新信任浏览器传参 |
## 3. P0-01:数据源越权与 HTTP 凭证外泄
> **决策(2026-08-29):不实施。** 本部署运行于内网可信环境,用户之间按数据源 ID 共享、HTTP 节点访问任意内网 URL 是既有且必需的使用方式;owner 校验、baseUrl+path 拆分、host 白名单会使现网流程全部失效。风险由部署方明确接受("这个改了我们就没法用了")。
### 3.1 问题说明
当前运行时在 `app/gateway/workflow_executor.py` 中按数据源 ID 直接解析 DSN/凭证;持久化层的 `resolve_dsn` 也没有传入 owner 或授权上下文。HTTP 节点可由流程 JSON 提供任意 URL,再把已解析的认证头附加到该 URL。
因此存在两类风险:
1. 知道或获得他人私有数据源 ID 的用户,可能在自己的流程中引用该数据源。
2. 可使用共享 HTTP 凭证的用户,可能把请求 URL 写为攻击者控制的公网域名,从而收到服务端附带的 API Key、Bearer Token 或 Basic Auth。
### 3.2 数据模型调整
在 `workflow_data_sources` 中增加显式共享与用途约束。字段命名可按现有 ORM 风格调整:
```sql
ALTER TABLE workflow_data_sources
ADD COLUMN visibility VARCHAR(16) NOT NULL DEFAULT 'private',
ADD COLUMN allowed_user_ids JSON NULL,
ADD COLUMN allowed_tenant_ids JSON NULL,
ADD COLUMN allowed_hosts JSON NULL,
ADD COLUMN allowed_methods JSON NULL;
```
字段语义:
| 字段 | 含义 |
|---|---|
| `visibility` | `private`、`shared`、`system` |
| `allowed_user_ids` | 共享给指定用户;第一期可先支持此项 |
| `allowed_tenant_ids` | 多租户部署时按租户共享;单租户可暂不启用 |
| `allowed_hosts` | HTTP 数据源允许请求的 hostname 白名单,必须填写 |
| `allowed_methods` | HTTP 数据源可执行的方法白名单,例如 `GET`、`POST` |
SQL 数据源的数据库账号仍必须由 DBA 创建为只读账号;应用层 SQL 解析和只读 SQL policy 是第二道防线,不能替代数据库权限。
### 3.3 Store 接口调整
将现有无身份的解析接口废弃:
```python
# 禁止继续在节点执行路径使用
resolve_dsn(source_id: str)
```
替换为:
```python
async def resolve_for_execution(
self,
source_id: str,
principal: WorkflowExecutionPrincipal,
expected_kind: Literal["sql", "http"],
) -> WorkflowDataSource:
...
```
实现规则:
1. 资源必须存在且 `enabled=True`。
2. `kind` 必须与节点类型匹配。
3. 允许 owner、被显式共享的用户、同租户授权用户或管理员访问。
4. 禁止仅凭“已发布工作流”绕过资源权限;每一次运行均需检查。
5. 无权限统一抛 `ResourceNotAvailableError`,日志中可记录真实原因和 source ID。
示例伪代码:
```python
def can_execute(source: WorkflowDataSource, principal: WorkflowExecutionPrincipal) -> bool:
if principal.is_admin:
return True
if source.owner_id == principal.user_id:
return True
if source.visibility == "shared" and principal.user_id in source.allowed_user_ids:
return True
if source.visibility == "system" and principal.tenant_id in source.allowed_tenant_ids:
return True
return False
```
需要同步修改:
- `packages/harness/deerflow/persistence/workflow_data_sources/store.py`
- `packages/harness/deerflow/persistence/workflow_data_sources/sql.py`
- 内存 store 实现与测试 fake
- `app/gateway/workflow_executor.py`
- 使用数据源的 SQL / HTTP 节点执行器
### 3.4 HTTP 节点配置改造
不要继续允许流程节点同时填写任意完整 URL 与 `credentialRef`。推荐将 HTTP 数据源定义为受控目标,节点只填写相对路径:
```json
{
"type": "http",
"dataSourceId": "crm-production-api",
"method": "GET",
"path": "/v1/customers",
"query": {
"page": "{{ inputs.page }}"
}
}
```
数据源的机密配置中保存:
```json
{
"baseUrl": "https://api.company.com",
"allowedHosts": ["api.company.com"],
"allowedMethods": ["GET", "POST"],
"auth": {
"type": "bearer",
"secret": "加密存储"
}
}
```
执行顺序必须固定:
1. 读取经授权的数据源。
2. 变量渲染 `path`、query、body。
3. 由 `baseUrl + path` 构造最终 URL,拒绝绝对 URL 和 `//host/path` 形式。
4. 校验最终 host、端口、DNS 解析结果、方法、请求体上限。
5. 最后才注入认证头。
6. 每次重定向重新执行 host/SSRF 校验。
7. 一旦发生跨 origin 重定向,移除 `Authorization`、Cookie、`X-API-Key` 等敏感头;建议默认拒绝跨 origin 重定向。
若业务确实需要任意 URL 调用,应提供另一种**无凭证 HTTP 节点**,并且其网络范围仍受全局 SSRF policy 约束。
### 3.5 验收测试
- 用户 A 创建私有 SQL 数据源;用户 B 使用其 ID 运行,返回 `RESOURCE_NOT_AVAILABLE`。
- 用户 A 发布引用私有数据源的流程后,用户 B 即使复制 JSON 也不能运行。
- 共享 HTTP 数据源只能请求 `allowed_hosts` 中的地址。
- URL 模板渲染为不在白名单中的主机时被拒绝,且认证头没有发送。
- 302/307 跨域跳转时凭证不会跟随;推荐断言请求整体被拒绝。
- SQL 节点使用只读账号执行 `INSERT`、`CALL`、多语句均被数据库和 SQL policy 双重拒绝。
## 4. P0-02:子工作流跨用户执行
> **决策(2026-08-29):不实施。** 内网可信环境下按 workflow/version ID 跨用户引用子工作流是预期用法,运行时沿用原 run 的 `owner_id` 已满足功能正确性;完整 ACL 见 P0-01 同批决策,一并接受风险。
### 4.1 工作流 ACL
在 workflow 主表增加与数据源一致的共享模型:
```sql
ALTER TABLE workflows
ADD COLUMN visibility VARCHAR(16) NOT NULL DEFAULT 'private',
ADD COLUMN allowed_user_ids JSON NULL,
ADD COLUMN allowed_tenant_ids JSON NULL;
```
建议第一期仅实现:`private`、`shared`、`system`。不要把“已发布”当作“所有用户可执行”;发布只代表版本不可变并可被授权对象使用。
### 4.2 接口改动
以下接口均应由 `principal` 过滤:
| 接口能力 | 整改要求 |
|---|---|
| 已发布工作流目录 | 仅返回当前用户可执行的工作流 |
| 获取版本详情 | owner / 被分享对象 / 管理员才可读 |
| 创建根运行 | 检查 workflow 与 version 的 ACL |
| 子工作流节点 | 按父 run 的 principal 再次检查子流程 ACL |
| 复制流程 | 允许复制公开定义不等于允许继承数据源和凭证引用 |
子工作流执行应改为:
```python
child_version = await workflow_store.get_published_for_execution(
workflow_id=node.workflow_id,
version_id=node.version_id,
principal=context.principal,
)
if child_version is None:
raise ResourceNotAvailableError(node.workflow_id)
```
并在 child run 写入:
```python
parent_run_id=parent_run.id
owner_id=parent_run.owner_id
tenant_id=parent_run.tenant_id
```
### 4.3 验收测试
- 用户 B 的资源目录不包含用户 A 的私有已发布流程。
- 用户 B 手工构造 A 的 workflow/version ID 创建运行,被拒绝。
- 用户 B 的父流程引用 A 的子流程,被拒绝。
- A 共享子流程给 B 后,B 可运行;收回授权后,历史草稿仍可保存但新运行失败。
## 5. P1-01:人工介入恢复的原子性
> **状态(2026-08-29):已实施。** Store 新增 `resume_with_payload(run_id, resume_token, payload, *, context=None)`(SQL/memory 双实现),暂停侧 `set_awaiting_input` 扩展 `context` 参数一次性写入 checkpoint。路由 `resume_run` 与执行器 `_pause` 均已切换到单条条件更新;`consume_resume_token` 仅为兼容保留。回归测试 `tests/test_workflow_concurrency.py`(内存 + SQLite 并发恢复、错 token、单 winner)。
### 5.1 问题与目标
当前恢复操作先写 `resume_payload`,再消费 token。两个并发请求可能先后覆盖 payload,最终执行的数据与收到成功响应的请求不一致。
目标是把“校验 token、写入输入、清除 token、变更状态”为单条条件更新。
### 5.2 Store 方法
新增方法,替代 `update_run(...) + consume_resume_token(...)` 组合调用:
```python
async def resume_with_payload(
self,
run_id: str,
resume_token: str,
payload: dict[str, Any],
) -> WorkflowRun | None:
"""成功时返回已恢复的 run,token 无效或已消费时返回 None。"""
```
SQL 示例,JSON 写法按当前数据库方言封装:
```sql
UPDATE workflow_runs
SET
context_json = :new_context_json,
resume_token = NULL,
pending_human_node_id = NULL,
status = 'queued',
updated_at = NOW()
WHERE id = :run_id
AND status = 'awaiting_input'
AND resume_token = :resume_token;
```
应用层规则:
1. `rowcount != 1` 时返回 409,且不得投递调度器。
2. `rowcount == 1` 后再投递调度器。
3. 投递失败时保留 `queued` 状态,由扫描器补投;不要把 token 恢复。
4. 对人工输入 payload 先完成 schema 校验、大小限制和脱敏审计,再进入事务。
暂停节点也应使用单次 store 调用,同时写入:状态、token、等待节点 ID 和上下文,避免执行器后续的独立 `update_run` 覆盖已恢复的数据。
### 5.3 验收测试
- 两个协程并发用同一 token 提交不同 payload,只有一个 200,另一个 409。
- run context 中只存在 200 对应 payload。
- worker 最终读取的 payload 与成功响应一致。
- token 被消费后,多次重试均为 409。
## 6. P1-02:草稿与发布版本并发控制
> **状态(2026-08-29):已实施。** 草稿保存改为 `UPDATE ... WHERE id AND draft_revision = :expected`,rowcount=0 时回读当前 revision 抛 `WorkflowDraftConflictError`(409 带 `currentRevision`)。发布版本号改由 `workflow_definitions.next_version_number` 计数器 CAS 分配(`max(counter, MAX(version)+1)` 兼容存量行),唯一约束兜底、冲突重试而非 500。计数器列由迁移 `20260828_04_workflow_counter_columns.py` 增加(server_default,存量库由启动列同步自动补列)。回归测试:并发草稿双写单 winner、5 并发发布得相邻版本号、存量版本行计数器自愈。
### 6.1 草稿乐观锁
禁止“先读取 revision,再修改 ORM 对象,再 commit”的方式。改为带 revision 的条件更新:
```sql
UPDATE workflows
SET graph_json = :graph_json,
draft_revision = draft_revision + 1,
updated_at = NOW()
WHERE id = :workflow_id
AND draft_revision = :expected_revision;
```
若受影响行数为零,则读取当前 revision,并返回:
```json
{
"code": "WORKFLOW_DRAFT_CONFLICT",
"currentRevision": 18
}
```
前端收到 409 后应提示“流程已被其他编辑者保存”,支持刷新、比较或另存副本;不能静默覆盖。
### 6.2 发布版本号
禁止 `MAX(version_number) + 1`。建议在 workflow 行维护 `next_version_number`,在一个事务内锁定并递增:
```sql
SELECT next_version_number FROM workflows WHERE id = :id FOR UPDATE;
INSERT INTO workflow_versions (..., version_number) VALUES (..., :next_number);
UPDATE workflows
SET next_version_number = next_version_number + 1
WHERE id = :id;
```
若现有数据库不方便 `FOR UPDATE`,可采用具备唯一约束的 sequence/counter 表,捕获唯一冲突后重试;不要将冲突直接抛为 500。
### 6.3 验收测试
- 两个独立 SQLAlchemy session 同时保存同一 revision,严格只有一个成功。
- 两个发布请求同时执行,生成相邻但不同的版本号。
- 冲突被转换为稳定的 409 业务错误,而非数据库异常。
## 7. P1-03:事件持久化、序号和 SSE 一致性
> **状态(2026-08-29):已实施(采用 7.2 计数器方案 + 7.3 的"丢弃不发布"策略)。** `workflow_runs.next_event_seq` 计数器在同一事务内 `UPDATE ... SET next_event_seq = next_event_seq + 1` 后读自增并插入事件,行写锁串行化并发追加(seq 严格递增、唯一、无空洞);唯一约束冲突时 `_resync_counter` 以独立事务回写 `MAX(seq)` 自愈存量行后重试。落库失败的事件**直接丢弃、绝不向 live hub 发布**(原负序号幽灵事件实现已删除),信封带 `eventPersistenceDegraded` 标记、`sink.degraded_count` 计数并记结构化告警日志;SSE 端点对无终态事件的终态 run 合成关闭帧。回归测试:10 并发追加 seq 连续唯一、存量事件计数器自愈、落库失败零发布。
### 7.1 改造原则
业务事件必须遵循:**获得持久序号 → 持久化成功 → 实时发布**。不能生成负序号临时事件,也不能让前端看到无法通过重连补回的事件。
### 7.2 序号分配
不要使用 `MAX(seq) + 1`。在 `workflow_runs` 增加计数器:
```sql
ALTER TABLE workflow_runs
ADD COLUMN next_event_seq BIGINT NOT NULL DEFAULT 1;
```
追加事件时在同一个数据库事务中:
1. 对 run 原子递增 `next_event_seq` 并得到当前 seq。
2. 以该 seq 插入 `workflow_events`。
3. 提交事务。
4. 仅提交成功后调用 `live_hub.publish(event)`。
不同数据库可选择 `UPDATE ... RETURNING` 或者用 run 行锁实现,但不可回退为 `MAX(seq)` 查询。
### 7.3 持久化失败处理
事件库短暂失败时:
1. 在有限次数内重试;
2. 仍失败则将运行标记为 `retryable_failure` 或 `paused_system`;
3. 记录包含 `run_id`、node ID、异常分类的结构化日志和告警;
4. SSE 至少发送一个已成功持久化的终态或系统状态事件;
5. 用户重连后只能从数据库事件日志恢复,不依赖当前进程内存。
不要使用“事件落库失败后仍向 live hub 发负数 seq”的实现,因为按 cursor 追尾的 SSE 客户端通常会忽略它。
### 7.4 验收测试
- 并行节点大量写事件,序号严格递增且无重复。
- 模拟一次插入事件失败,前端不会收到不可回放事件。
- 客户端从 `Last-Event-ID=N` 重连,得到所有 `seq>N` 的事件且顺序一致。
- 多实例下任一实例订阅 SSE,均可通过数据库补放完整事件。
## 8. P1-04:智能体和技能最小权限
> **决策(2026-08-29):暂缓。** 属安全隔离类项目,本轮整改只做功能性优化(用户决策:"P1-04/P1-05 偏安全隔离不用做,安全性的问题咱们暂时不用做,咱们只改功能性的,优化的")。后续若对外开放多租户再评估。
### 8.1 智能体可见性
`agent` 节点收到 `agent_id` 后,必须在 `WorkflowAgentRunner` 内部再次调用可见性查询:
```python
agent = await agent_store.get_visible(
agent_id=node.agent_id,
user_id=context.principal.user_id,
)
if agent is None or not agent.enabled:
raise ResourceNotAvailableError(node.agent_id)
```
不能仅依赖资源目录接口已过滤,也不能仅依赖发布阶段校验。
### 8.2 技能白名单
现有将 `skill_names` 传给 Lead Agent 的方式必须核实是否被真正消费。建议新增语义明确的运行时参数:
```python
configurable["workflow_allowed_skill_ids"] = selected_skill_ids
```
并在 Lead Agent 加载技能、MCP 工具和工具调用路由之前强制过滤:
```python
requested = set(configurable.get("workflow_allowed_skill_ids", []))
available = [skill for skill in all_enabled_skills if skill.id in requested]
```
还应校验:
1. 选中的 skill 对当前用户可见。
2. skill 是否允许在 workflow 场景执行。
3. skill 的网络、数据库、文件权限是否与工作流 principal 相兼容。
4. 系统级高风险 skill 是否只能由管理员在数据源/策略中启用。
### 8.3 验收测试
- 用户手工填写不可见 agent ID,运行被拒绝。
- 未选中的技能不出现在模型可调用工具列表中。
- 提示词诱导模型调用未选技能,调用被拒绝且记录审计事件。
- 选中的技能正常可执行,节点事件中仅暴露必要的脱敏参数。
## 9. P1-05:代码节点沙箱化
> **决策(2026-08-29):暂缓,保持现状即安全。** 本轮不迁移到容器沙箱;`config.yaml` 中 `workflows.code.enabled` 保持默认 `false`(代码节点全局关闭,`tests/test_workflow_engine.py::test_code_node_disabled_by_default` 已锁定该默认值),如需启用由运维在受限宿主上自行开启。现有 `code_runner.py` 子进程加固(净化环境、临时目录、rlimit、断网、超时杀进程组)在可信内网下作为过渡方案。
### 9.1 上线策略
在 DeerFlow 沙箱实现并通过安全验证前,保持:
```yaml
workflows:
code:
enabled: false
```
不得以本地 `exec`、`subprocess` 或 monkey-patch `socket` 作为生产隔离方案。用户代码可借助原生扩展、子进程、文件系统或环境变量绕过此类限制。
### 9.2 目标接口
代码节点改为只调用现有 DeerFlow sandbox 抽象,而不自行启动宿主解释器:
```python
result = await sandbox.run(
code=rendered_code,
language="python",
timeout_seconds=30,
memory_limit_mb=256,
cpu_limit=1,
max_processes=8,
network_enabled=False,
writable_paths=["/mnt/user-data/workflows/{run_id}"],
)
```
沙箱最低要求:
- 独立容器或受限命名空间,不能读取 Gateway 项目、环境变量与宿主文件。
- 默认无网络;若未来允许网络,也需复用 HTTP 节点的数据源、SSRF 和凭证策略。
- CPU、内存、执行时长、磁盘、进程数和文件数限制。
- stdout/stderr 使用流式读取并在读取中截断,例如各 1MB;禁止 `communicate()` 后再截断。
- 制品只能输出到工作流专属目录,并通过既有 artifact 机制登记。
- 记录代码 hash、镜像版本、资源消耗、退出码,日志不得泄露源代码中的密钥。
### 9.3 验收测试
- 代码读取 `/etc`、项目目录、环境变量失败。
- 导入 socket、创建子进程、连接外网失败。
- 死循环超时结束,运行正确失败或可重试。
- 大量 stdout/stderr 不造成 Gateway 内存膨胀。
- 制品只能写入限定目录。
## 10. P1-06:测试纳入版本控制与 CI
> **状态(2026-08-29):已实施。** 采用方案 1(白名单):仓库根 `.gitignore` 对 `tests/test_workflow_{schemas,definitions,engine,runs}.py` 逐个 `!` 白名单,并新增 `tests/test_workflow_concurrency.py`(本轮整改的内存 + 真实 SQLite 并发回归,含 P1-01/02/03 与 schema 校验)。CI 需在该清单基础上加 `tests/test_workflow_concurrency.py`。
当前工作流测试文件位于后端 `tests/`,但仓库根目录的 `.gitignore` 规则会忽略这一目录内容。必须在合并前处理,否则本地通过的测试不会进入提交和 CI。
推荐方案:
1. 调整 `.gitignore`,仅忽略真正的生成物,不要忽略后端测试源码;或
2. 若忽略规则短期不能改,使用 `git add -f` 纳入现有测试文件,但仍应补充注释说明原因;
3. CI 显式执行:
```bash
cd offline-backend-20260512/backend
PYTHONPATH=. uv run pytest \
tests/test_workflow_schemas.py \
tests/test_workflow_definitions.py \
tests/test_workflow_engine.py \
tests/test_workflow_runs.py -v
```
4. 新增 SQL 集成测试 job,至少覆盖真实事务并发;不能只依赖 memory store。
## 11. P2:契约校验与 iframe 票据
> **状态(2026-08-29):§11.1 已实施;§11.2 暂缓**(单实例部署,进程内 replay cache + 60s TTL 足够,多实例化时再引入 Redis)。
### 11.1 完整 JSON Schema 校验
> **实施说明(2026-08-29)**:新增纯函数模块 `packages/harness/deerflow/workflows/schema_validation.py` 的 `schema_issues(value, schema)`(Draft202012,中文短消息、字段路径、去重、上限 20 条、schema 本身非法时返回友好错误而非 500)。接入点:路由 `start_run`(启动前 400 `WORKFLOW_INPUT_INVALID` + `details.errors`)、引擎 Start/Output 节点(`WORKFLOW_INPUT_INVALID` / `WORKFLOW_OUTPUT_SCHEMA_MISMATCH`)。空 schema 不强制(未声明即不校验)。回归测试见 `tests/test_workflow_concurrency.py` 与 `tests/test_workflow_runs.py::test_typed_input_schema_violations_return_structured_400`。
输入节点和输出节点不应只校验 `required` 字段。应使用完整 JSON Schema validator,至少支持:`type`、`enum`、`items`、`properties`、`required`、`additionalProperties`、嵌套对象和数组。
```python
from jsonschema import Draft202012Validator
validator = Draft202012Validator(schema)
errors = sorted(validator.iter_errors(value), key=lambda item: list(item.path))
if errors:
raise WorkflowSchemaValidationError(
errors=[{"path": list(err.path), "message": err.message} for err in errors]
)
```
错误响应需要包含节点 ID、字段路径和可展示的消息;不应把内部 Python trace 返回给前端。
### 11.2 iframe 一次性票据
“一次性”语义不能使用单进程内存字典。若部署多实例,应使用 Redis 或数据库的原子写入:
```text
SET workflow_embed_nonce:{jti} consumed NX EX 60
```
只有返回成功的实例可以继续验证。服务端还必须读取真实请求 `Origin`,并要求以下三者一致:
1. ticket 签发时绑定的 origin;
2. 浏览器请求头中的 `Origin`;
3. 后台 `workflows.embed.allowed_origins` 白名单。
不能只比较前端 body/query 参数中的 origin。
## 12. 建议实施顺序与分批发布
> 2026-08-29 实况:第二批全部落地;第四批仅 §11.1 落地(§11.2 暂缓);第一批(P0-01/02)经部署方决策不实施;第三批(P1-04/05)暂缓。
### 第一批:安全阻断项
范围:资源 principal、数据源授权、HTTP host 绑定、子工作流 ACL。
发布策略:先迁移数据库字段,默认所有历史资源为 `private`;只允许管理员手工将必要资源改为 shared。此批完成并通过越权测试后,才允许开放 SQL/HTTP/子工作流节点。
### 第二批:一致性与可靠性
范围:人工恢复原子操作、草稿 CAS、发布版本锁、事件序号与持久化失败策略。
发布策略:需要停写窗口或兼容性迁移时,先双写/双读一版;对运行中的旧 run 保持旧 schema 可读,新增 run 使用新序号和新恢复逻辑。
### 第三批:能力隔离
范围:agent 可见性、skill 白名单、代码节点沙箱。
发布策略:代码节点继续全局关闭;先灰度给管理员和测试租户。技能节点在完成真实白名单前,不得宣称“只调用所选技能”。
### 第四批:契约与嵌入完善
范围:JSON Schema 完整校验、iframe Redis nonce、接口错误码统一、运维监控。
## 13. 发布准入清单
> 2026-08-29 更新:本清单按原始审计口径保留。结合「0. 整改决策记录」,P0 两项经部署方决策**不实施**(内网可信环境,风险已接受),与 P0 相关的准入项在内网部署中视为豁免;✅ 为本轮已达成项。
以下条件全部满足才可开放给普通用户:
- [ ] 所有资源解析接口都需要 `WorkflowExecutionPrincipal`。(❌ 不实施——内网可信环境,见 §3/§4 决策)
- [ ] 私有数据源、私有工作流、私有智能体均有跨用户拒绝测试。(❌ 不实施——同上)
- [ ] HTTP 凭证绑定 host/method,跨域重定向不携带敏感认证头。(❌ 不实施——内网需访问任意地址,见 §3 决策)
- [ ] SQL 数据源使用数据库只读账号,且连接/查询审计可追踪到 run ID。(部分:SQL 只读校验已有;账号隔离不在本轮范围)
- [ ] 子工作流按运行身份校验 ACL。(❌ 不实施——见 §4 决策)
- [x] 人工输入恢复是单事务条件更新,并发测试通过。(✅ `test_workflow_concurrency.py`)
- [x] 草稿保存和发布版本具备数据库级并发保护。(✅ 同上)
- [x] 事件序号单调、唯一、可重放;没有负序号临时事件。(✅ 同上)
- [ ] agent / skill 白名单在实际工具加载链路生效。(⏸ 暂缓——P1-04)
- [x] 代码节点运行在受限 sandbox;否则保持关闭。(✅ 保持关闭:`workflows.code.enabled: false` 为默认且被测试锁定)
- [x] 所有 workflow 测试文件已纳入 Git 与 CI。(✅ `.gitignore` 白名单 + 新增并发回归)
- [x] 安全测试、SQL 并发集成测试、SSE 重连测试全部通过。(✅ 88 个 workflow 测试全绿;安全类测试随 P0/P1-04 决策豁免)
## 14. 相关代码入口
| 主题 | 当前主要代码入口 |
|---|---|
| 路由与运行 API | `app/gateway/routers/workflow_runs.py` |
| 工作流执行与依赖装配 | `app/gateway/workflow_executor.py` |
| 智能体/技能运行 | `app/gateway/workflow_agent_runner.py` |
| 数据源 API | `app/gateway/routers/workflow_data_sources.py` |
| 工作流资源目录 | `app/gateway/routers/workflow_resources.py` |
| iframe ticket | `app/gateway/routers/workflow_embed.py` |
| 数据源持久化 | `packages/harness/deerflow/persistence/workflow_data_sources/` |
| 工作流/版本持久化 | `packages/harness/deerflow/persistence/workflows/` |
| 运行与租约持久化 | `packages/harness/deerflow/persistence/workflow_runs/` |
| 事件持久化 | `packages/harness/deerflow/persistence/workflow_events/` |
| SQL/HTTP 节点 | `packages/harness/deerflow/workflows/nodes/integrations.py` |
| 事件 sink | `packages/harness/deerflow/workflows/runtime/sink.py` |
| 代码节点运行器 | `packages/harness/deerflow/workflows/runtime/code_runner.py` |
| 工作流安全策略 | `packages/harness/deerflow/workflows/security/` |
| 数据库迁移 | `packages/harness/deerflow/persistence/migrations/` |
| 现有工作流测试 | `tests/test_workflow_*.py` |
## 15. 非目标与注意事项
- 本整改不改变 Coze Studio 画布的基础交互,也不要求先改前端;前端仅需后续适配资源权限失败、409 冲突和结构化 schema 错误。
- 不要把资源密钥、数据库 DSN、人工输入 token 或工具原始参数写入前端 SSE 事件。
- 不要依赖“前端资源选择器只显示可见资源”作为授权机制;浏览器请求和画布 JSON 均视为不可信输入。
- 新字段上线后,历史资源默认按私有处理,避免一次迁移导致所有历史凭证意外共享。
- 每项整改完成后都要更新 `WORKFLOW_STUDIO_BACKEND_DEV_ZH.md` 中对应的“已完成”状态,避免文档声明与实际安全边界不一致。
@@ -0,0 +1,486 @@
# Workflow Studio:Coze 独立前端对接 DeerFlow 后端适配开发文档
> 状态:待实施
> 日期:2026-08-29
> 前端范围:F:/react01/code-stutsiu/frontend/apps/coze-studio/src/workflow-standalone/
> 后端范围:offline-backend-20260512/backend/
> 关联文档:
>
> - docs/WORKFLOW_STUDIO_BACKEND_DEV_ZH.md:工作流运行时总体设计与已有能力。
> - docs/WORKFLOW_STUDIO_BACKEND_REMEDIATION_ZH.md:安全、并发、租约与事件持久化整改。
>
> 本文只处理“当前独立 Coze 页面与真实 DeerFlow 后端之间”的适配,不重新设计工作流运行内核。
## 1. 目标与结论
当前独立页的交互、三栏布局、资源卡、运行历史、SSE reducer 与 mock 演示已可用,但其保存、校验、发布和部分运行事件仍使用 mock 协议。真实 DeerFlow 后端采用 WorkflowGraph v1.0 和持久化运行时,两者不能直接互换。
本次适配目标:
1. Coze 画布能够保存、重新加载、校验、发布,并由 DeerFlow 运行。
2. 画布上的 Agent、Skill、SQL、HTTP、Code、Input、Output 节点都有真实、可审计的执行配置。
3. 左侧对话运行和右侧执行过程能从同一条 DeerFlow SSE 事件流稳定恢复工具步骤、人工介入与文件制品。
4. 不把 Coze 的内部数值节点类型、任意画布 JSON、凭据明文或完整工具参数泄漏到运行时协议中。
结论:不能仅在现有 POST /api/workflows/{id}/runs 中增加几个兼容字段。必须先建立“画布表示”和“执行图表示”的明确边界;否则保存成功的流程仍无法发布或运行。
## 2. 当前差异清单
| 编号 | 当前独立页行为 | DeerFlow 当前行为 | 影响 | 所属 |
| --- | --- | --- | --- | --- |
| A01 | 保存 body 为 schemaJson,读取 workflowId / draftRevision / schemaJson | 草稿接口要求 graph,读取返回 id / draft_graph / draft_revision | 自动保存、冲突恢复、发布均无法真实联调 | 前端主改,后端提供工作室 DTO |
| A02 | 校验期待 valid 字段 | 后端返回 ok 字段 | 前端始终判定校验不通过 | 前后端契约统一 |
| A03 | Coze JSON 被原样持久化 | 后端运行时只接受 WorkflowGraph v1.0 | Coze 数值节点类型不可执行 | 前端编译,后端持久化与验证 |
| A04 | 拖入资源只预填节点标题 | Agent / Skill 执行器要求 agentId、skillNames、promptTemplate 等 | 资源卡看起来可用,真实运行必失败 | 前端表单 + 后端发布校验 |
| A05 | 工具事件读取 name、status | 后端发送 toolName、ok | 工具步骤丢失,失败状态错误 | 后端规范化,前端兼容旧字段 |
| A06 | 人工介入读取顶层 prompt / formSchema | 后端放在 pendingInput 内 | 介入卡没有问题文本和表单 | 后端事件扁平化,前端兼容 |
| A07 | 文件预览请求单个 artifact 内容接口 | 后端只提供制品列表 | 文件卡可见但无法打开或下载 | 后端新增制品内容接口 |
| A08 | 资源 hook 请求 credentials 目录 | 后端没有该路由 | 整个资源加载 Promise.all 可能显示失败 | 后端补只读引用目录,或前端暂停请求 |
| A09 | UI 可选“当前草稿试运行”和 mock 场景 | 后端忽略 target / scenario,只运行发布版本 | 用户以为执行草稿,实际执行旧版本 | 前端先隐藏;后端后续可实现草稿快照 |
| A10 | 连续输入会创建新的 run | 后端无 conversation / turn 模型 | 不是 ChatDev 式多轮会话 | 二期可选能力 |
## 3. 必须冻结的总体设计
### 3.1 两种表示,两个职责
同一工作流必须保留两份有明确用途的数据,不能让任何一份冒充另一份。
| 数据 | 责任方 | 用途 | 是否可直接执行 |
| --- | --- | --- | --- |
| canvasSchemaJson | Coze 前端产生;后端仅作为受限 JSON 文档保存 | 画布恢复、节点位置、Coze 表单内部字段、编辑体验 | 否 |
| executionGraph | 前端适配器编译;后端以 WorkflowGraph 校验并版本化 | 发布校验、权限检查、调度、恢复、SSE、审计 | 是 |
约束:
1. DeerFlow harness 只接收 executionGraph,绝不解析 Coze StandardNodeType 或 Coze 内部服务字段。
2. canvasSchemaJson 不进入 SSE,不进入运行快照,不作为表达式或节点配置来源。
3. 发布版本至少冻结 executionGraph;建议同时保存其来源 canvasSchemaJson 的哈希,便于审计与排错。
4. Coze 到 WorkflowGraph 的逐节点转换放在前端 adapters/coze-canvas-adapter.ts 或其同级编译器中。后端不耦合 Coze 的数值节点类型。
5. 后端应拒绝“只有 canvasSchemaJson、没有合法 executionGraph”的发布请求,不能静默将其当作空图。
### 3.2 推荐的工作室适配层
保持现有 /api/workflows 的标准运行时 API 语义,不在其核心请求中混入 Coze 专属字段。新增一层仅面向独立页的 studio facade:
GET /api/workflows/{workflow_id}/studio-document
PUT /api/workflows/{workflow_id}/studio-draft
POST /api/workflows/{workflow_id}/studio-validate
POST /api/workflows/{workflow_id}/studio-publish
现有以下端点继续作为运行时和其他客户端的标准接口:
POST /api/workflows/{workflow_id}/runs
GET /api/workflows/{workflow_id}/runs
GET /api/workflows/runs/{run_id}/events
GET /api/workflows/runs/{run_id}/stream
这样既避免污染通用 API,也让前端能获得它需要的 camelCase DTO。
## 4. Studio facade API 契约
### 4.1 获取文档
请求:
GET /api/workflows/{workflow_id}/studio-document
响应:
{
"workflowId": "wf_001",
"name": "周报生成",
"draftRevision": 12,
"publishedVersionId": "ver_009",
"canvasSchemaJson": "{...}",
"executionGraph": { "schemaVersion": "1.0", "id": "wf_001", "nodes": [], "edges": [] },
"updatedAt": "2026-08-29T10:00:00+08:00"
}
要求:
- 从现有 definition 的 id、draft_revision、draft_graph、published_version_id 等字段适配生成。
- canvasSchemaJson 为空时返回空画布 JSON,而不是 null。
- 权限沿用现有 owner/admin 规则。
- 不返回 DSN、HTTP 请求头、resume token、完整 agent 配置或任何私密字段。
### 4.2 保存草稿
请求:
PUT /api/workflows/{workflow_id}/studio-draft
{
"expectedRevision": 12,
"canvasSchemaJson": "{...}",
"executionGraph": {
"schemaVersion": "1.0",
"id": "wf_001",
"nodes": [],
"edges": []
}
}
响应:
{ "revision": 13, "updatedAt": "2026-08-29T10:01:00+08:00" }
规则:
1. 先做 WorkflowGraph 结构解析;无法解析返回 400,错误码 WORKFLOW_SCHEMA_INVALID。
2. 画布 JSON 只做大小、JSON 格式、深度和危险字段控制,不做执行解释。
3. canvasSchemaJson 与 executionGraph 必须在同一次 CAS 更新中落库,不能出现画布和执行图不同 revision。
4. revision 冲突返回 409:
{
"code": "WORKFLOW_DRAFT_CONFLICT",
"message": "草稿版本冲突,请刷新后重试或另存副本",
"currentRevision": 13
}
5. 不建议让旧 PUT /draft 同时接受 schemaJson 与 graph。若为灰度必须暂时兼容,兼容逻辑只能位于 facade 路由,且必须在一个发布周期后删除。
### 4.3 校验与发布
校验请求:
POST /api/workflows/{workflow_id}/studio-validate
{ "executionGraph": { ... } }
校验响应:
{
"valid": false,
"issues": [
{
"code": "WORKFLOW_RESOURCE_MISSING",
"nodeId": "agent_writer",
"field": "config.agentId",
"message": "未选择可访问的智能体"
}
],
"graphHash": null
}
发布请求:
POST /api/workflows/{workflow_id}/studio-publish
{ "expectedRevision": 13, "changeNote": "配置报告智能体" }
发布响应:
{ "versionId": "ver_010", "publishedAt": "2026-08-29T10:02:00+08:00" }
发布必须复用标准发布版本表和不可变 graph 快照。facade 只负责 DTO 命名、画布关联和调用标准发布服务,不能复制一套版本逻辑。
## 5. 后端实施项
### 5.1 持久化 canvas schema 与草稿原子更新
现有 workflow_definitions 只有 draft_graph_json。新增独立字段,例如 draft_canvas_schema_json;不要把 Coze 画布塞进 draft_graph_json。
需要修改:
| 路径 | 改动 |
| --- | --- |
| packages/harness/deerflow/persistence/workflows/model.py | WorkflowDefinitionRow 增加 draft_canvas_schema_json;如需审计可增加 published_canvas_schema_hash |
| packages/harness/deerflow/persistence/migrations/versions/ | 新增 Alembic migration,存量行默认 {} |
| packages/harness/deerflow/persistence/workflows/base.py | save_studio_draft 或扩展 save_draft 的原子接口,输入两份文档和 expected_revision |
| packages/harness/deerflow/persistence/workflows/sql.py | 单条 CAS UPDATE 同时更新两份文档、revision、updated_at |
| packages/harness/deerflow/persistence/workflows/memory.py | 同步实现,保证测试环境语义一致 |
禁止:
- 先保存 canvas、后保存 graph 的两次写入。
- 在 SQL store 之外用“先读 revision、再无条件写”的方式实现 CAS。
- 把 canvasSchemaJson 输出到运行事件或 run context。
### 5.2 Studio facade 路由与 DTO
新增 app/gateway/routers/workflow_studio.py,负责:
1. studio-document、studio-draft、studio-validate、studio-publish 四个端点。
2. camelCase DTO 与现有 persistence snake_case 字段之间的映射。
3. 统一错误结构和 owner/admin 鉴权。
4. 调用通用 WorkflowGraph 结构校验与 app 层资源校验。
在 app/gateway/app.py 或当前工作流 router 注册位置挂载该 router。不要让 packages/harness/deerflow 导入 app.gateway。
前端移交项:
- api/workflows.ts 改为调用 studio facade。
- coze-canvas-adapter.ts 产出 executionGraph,不再只做 JSON.stringify。
- 画布新增或修改节点时,同时更新可编译的节点配置。
### 5.3 发布前资源和权限校验
现有 validator 支持 resource_checker 钩子,但通用 harness 不应直接导入应用层的 agent、skill、data-source store。应在 app 层构造 checker 后传入。
在 studio-validate、studio-publish 和标准 publish 入口都执行:
| 节点 | 必检字段 | 后端校验 |
| --- | --- | --- |
| agent | agentId、promptTemplate、responseSchema | 智能体存在、调用者可见、提示词非空、输出 schema 合法 |
| skill | mode、agentId、skillNames、promptTemplate | 技能存在且启用;agent_skill 必须属于智能体白名单;callable_skill 未开放时明确拒绝 |
| sql_read | dataSourceId、queryTemplate、parameters | 数据源可见、只读、表白名单、SQL 解析与 maxRows 上限 |
| http | dataSourceId 或 credentialRef、method、path、headers 映射 | 资源可见、方法白名单、URL/内网策略、凭据引用可用 |
| code | language、source、timeoutSeconds、output mapping | 沙箱已启用、语言白名单、超时和输出目录限制 |
| output | schema、field mapping | 输出字段可解析,输出 schema 可校验 |
| subworkflow | workflowId、versionId | 子工作流已发布、调用者有权限、深度限制 |
校验必须返回 nodeId 与字段路径,便于前端定位 Coze 节点表单。运行时仍保留二次校验,防止资源被禁用或权限在发布后撤销。
### 5.4 资源目录与凭据引用
保留现有:
- app/gateway/routers/workflow_resources.py:Agent、Skill、数据源目录。
- app/gateway/routers/workflow_data_sources.py:SQL/HTTP 数据源创建、加密与只读策略。
补充:
GET /api/workflows/resources/credentials
响应只允许:
{
"credentials": [
{
"credentialId": "http_source_001",
"name": "CRM 接口密钥",
"type": "http_headers",
"sourceKind": "http"
}
]
}
绝不返回 headers、token、DSN、加密密文或可逆提示。若一期 UI 没有凭据选择器,前端必须停止请求该端点,不能让一个 404 使整个资源面板显示“加载失败”。
### 5.5 运行目标、输入 schema 与草稿试运行
一期决策:
1. POST /runs 只接受发布版本或明确的 versionId。
2. 前端隐藏“当前草稿(试运行快照)”和 mock scenario 选择器。
3. 后端若收到 target=draft,返回 422 WORKFLOW_DRAFT_RUN_UNSUPPORTED,禁止静默回退到发布版本。
二期若需要草稿试运行,新增明确的 test-run API,而不是篡改正式 runs:
POST /api/workflows/{workflow_id}/test-runs
流程为:CAS 读取草稿 → 生成不可变 test snapshot → 记录 snapshot id → 运行 → 保留期清理。运行记录必须注明 test=true,不能被误认为发布版本运行。
运行输入:
- studio-document 响应必须带 inputSchema。
- 前端根据 inputSchema 渲染输入,而非永远发送 input.query。
- POST /runs 继续使用后端 JSON Schema 验证;错误返回 field/path/expected,前端在表单附近展示。
### 5.6 SSE 事件契约收敛
后端事件是前端执行过程唯一事实来源。所有事件须先持久化再广播,seq 单调递增且可 REST 重放。
规范化以下 payload:
node.tool.started
{
"name": "web_search",
"toolCallId": "call_001",
"title": "联网检索",
"args": { "path": "/mnt/user-data/outputs/report.md" }
}
node.tool.finished
{
"name": "web_search",
"toolCallId": "call_001",
"status": "succeeded",
"summary": "获得 12 条结果"
}
run.awaiting_input
{
"resumeToken": "one-time-token",
"nodeId": "review",
"prompt": "请确认是否发布",
"formSchema": { "type": "object", "properties": {} },
"actions": ["approve", "reject"]
}
artifact.created
{
"artifactId": "artifact_001",
"name": "weekly-report.docx",
"kind": "file",
"mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"sizeBytes": 1234
}
规则:
- 工具字段统一为 name;不要只发 toolName。
- 失败工具必须明确 status=failed 与脱敏 error。
- pendingInput 可以继续存储在数据库,但对外事件须扁平化为 prompt、formSchema、actions。
- agent 节点继续发送安全展示元数据 agent、parallelGroupId、roundIndex;不发送系统提示词、技能白名单、凭据和完整配置。
- 不将每个模型 token 当作 aria/live 或持久化事件;继续使用节流后的 node.output.delta。
- 事件类型表若仍不含 node.tool.input_delta,应从前端 mock 中删除该依赖,或后端正式实现该事件;不能只有 mock 有。
涉及路径:
| 路径 | 改动 |
| --- | --- |
| packages/harness/deerflow/workflows/nodes/agents.py | on_tool 输出 name、status、最小安全 args |
| app/gateway/workflow_executor.py | run.awaiting_input 对外 payload 扁平化 |
| packages/harness/deerflow/workflows/events.py | 冻结事件类型与 payload schema 样例 |
| app/gateway/routers/workflow_runs.py | REST 重放与 SSE 输出保持同一 envelope |
| packages/harness/deerflow/workflows/runtime/engine.py | 保持 node.started 的 agent / parallelGroupId / roundIndex 安全投影 |
### 5.7 制品内容、预览和下载
新增:
GET /api/workflows/runs/{run_id}/artifacts/{artifact_id}
GET /api/workflows/runs/{run_id}/artifacts/{artifact_id}/download
内容接口返回受限预览:
{
"artifactId": "artifact_001",
"name": "weekly-report.md",
"kind": "markdown",
"mimeType": "text/markdown",
"text": "# 周报",
"sizeBytes": 2048
}
策略:
1. 每次读取先校验 run owner/admin,再校验 artifact 属于该 run。
2. 文本、JSON、表格只返回大小受限预览;大文件返回 truncated=true。
3. 二进制文件不塞入 JSON;download 接口以附件或受控 inline 响应流返回。
4. 路径只能从已登记的 artifact id 解析,禁止接收任意 sandbox 路径。
5. 制品存储生命周期沿用现有 sandbox/artifact 机制;工作流表只存引用与元数据。
涉及路径:
- app/gateway/routers/workflow_runs.py:新增两个路由。
- packages/harness/deerflow/persistence/workflow_runs/*:按 run_id + artifact_id 查询的 store 方法。
- app/gateway/routers/artifacts.py:仅可参考现有 thread artifact 的鉴权和文件响应,不可直接跨 thread 复用。
### 5.8 取消状态和事件游标
统一运行状态:
| 后端状态 | 前端显示 | 说明 |
| --- | --- | --- |
| queued | 排队中 | 已入队未领取 |
| running | 运行中 | 正在执行 |
| awaiting_input | 等待人工介入 | 暂停并持有一次性 token |
| cancel_requested | 取消中 | 等待运行器确认,非终态 |
| completed / failed / cancelled | 终态 | SSE 停止重连 |
后端工作:
1. _public_run 输出 lastSeq 时映射 persistence 的 next_event_seq,不能读取不存在的 last_seq。
2. 前端 RunStatus 类型和 RunStatusBadge 增加 cancel_requested;后端不应把它伪装为 cancelled。
3. list events 空页必须返回请求 cursor,防止前端游标回退。
### 5.9 连续对话运行(二期,可选)
当前“对话运行”是单个 run 的视图投影:每次发送创建一个新 run。若业务要 ChatDev 式连续问答,需要独立设计,不能复用 run_id 作为会话 id。
建议新增:
workflow_conversations
workflow_conversation_turns
workflow_runs.conversation_id (nullable)
接口:
POST /api/workflows/{workflow_id}/conversations
GET /api/workflows/{workflow_id}/conversations
POST /api/workflows/conversations/{conversation_id}/turns
每个 turn 创建一个 run,并记录输入、run id、可展示摘要和制品引用。默认不把完整模型上下文拼接给每个节点;由 graph 明确配置哪些字段、哪些历史摘要可见。
## 6. 推荐实施顺序
### 阶段 A:真实保存与发布闭环(阻断项)
1. 增加 canvas schema 持久化迁移和 store 原子接口。
2. 实现 studio facade 四个端点。
3. 前端实现 Coze JSON 到 WorkflowGraph 编译,并改接 facade。
4. 完成输入/输出、代码、Agent、Skill、SQL、HTTP 的最小节点配置表单。
5. 加入发布前 app 层资源检查。
验收:编辑一个“Input → SQL → Agent → Output”流程,刷新后画布与配置不丢失,发布后执行的是同一版本的标准图。
### 阶段 B:真实执行过程闭环
1. 统一工具、人工介入、制品的 SSE payload。
2. 实现制品内容与下载接口。
3. 修复 lastSeq、cancel_requested。
4. 增加跨 REST 重放、SSE 断线重连、人工介入恢复的契约测试。
验收:报告工作流在 iframe 刷新后能恢复步骤、工具摘要、文件卡和人工介入状态。
### 阶段 C:草稿试运行与连续会话
1. 先由产品确认是否真的需要草稿试运行;需要时实现独立 test-run snapshot。
2. 再由业务确认是否需要跨 run 的上下文记忆;需要时实现 conversation/turn。
在阶段 C 前,前端必须隐藏对应入口,禁止用“看似可点、实际忽略”的体验替代能力。
## 7. 测试与验收
### 7.1 后端新增测试
建议新增:
| 文件 | 重点场景 |
| --- | --- |
| tests/test_workflow_studio_facade.py | studio DTO、camelCase、CAS、错误结构、owner/admin 鉴权 |
| tests/test_workflow_studio_graph_contract.py | Coze 编译产物可被 WorkflowGraph 接受;非法 graph 被拒绝 |
| tests/test_workflow_resource_validation.py | Agent/Skill/SQL/HTTP/Code/Output 配置与权限校验 |
| tests/test_workflow_event_contract.py | tool、awaiting_input、artifact、parallel agent payload 与 REST/SSE 一致 |
| tests/test_workflow_artifact_content.py | 文本预览、二进制下载、越权、路径穿越、超大文件 |
| tests/test_workflow_runs.py | target=draft 显式拒绝、cancel_requested、lastSeq |
保留并扩展:
- tests/test_workflow_engine.py:并行、循环、节点 started 元数据。
- tests/test_workflow_runs.py:运行、取消、恢复、SSE、重放。
- tests/test_workflow_data_sources.py:SQL 只读、HTTP allowlist、秘密不回显。
### 7.2 前后端契约 fixture
在 backend/tests/fixtures/workflow_studio/ 固化 JSON fixture,并让前端测试复制或通过生成脚本消费:
1. studio-document。
2. 保存成功与 409 冲突。
3. 资源缺失校验。
4. Agent 工具 started/finished。
5. human_input 暂停与恢复。
6. markdown/json/table/docx 制品。
7. 并行三智能体与取消中状态。
禁止前后端各自手写近似 mock 事件。fixture 变更必须同时更新双方测试。
### 7.3 发布准入
- [ ] Coze 画布和 executionGraph 采用两份数据、一次 CAS 保存。
- [ ] 真实后端不再依赖 schemaJson、valid 等 mock 专用字段。
- [ ] 所有可拖入资源都能在 graph 中找到真实绑定字段。
- [ ] 发布前可定位到节点和字段的资源/权限错误。
- [ ] 工具、人工介入、制品在 SSE 与 REST replay 中字段一致。
- [ ] 制品内容和下载经过 run 级鉴权,不能按任意路径读取。
- [ ] target=draft 不会被静默执行为发布版本。
- [ ] typecheck、后端 pytest、ruff 与至少一条 iframe E2E 全部通过。
## 8. 明确不做的事项
1. 不把整个 Coze Go 后端或 ChatDev 后端迁入 DeerFlow。
2. 不在 DeerFlow harness 中导入 app.gateway 或 Coze 前端类型。
3. 不为了兼容 mock 而让标准 WorkflowGraph API 永久接受任意 schemaJson。
4. 不向浏览器返回数据库 DSN、HTTP headers、token、resume token、沙箱真实文件路径或模型隐藏思维链。
5. 不在未实现草稿快照、连续会话前保留误导性的 UI 入口。
@@ -0,0 +1,54 @@
# ADR 0001:工作流编排运行时边界
- **状态**:Accepted(阶段 0 冻结;决策 3 已按阶段 2 实现修订,见文末修订记录)
- **日期**:2026-08-28
- **关联**:`docs/WORKFLOW_STUDIO_BACKEND_DEV_ZH.md`
## 背景
需要在 DeerFlow 中支持可持久化、可恢复、可审计的工作流运行,并用 Coze Studio 独立画布作为编辑器。可选路径包括:整包接入 Coze 后端、整包接入 ChatDev 2.0、或在 DeerFlow 内自建运行时。
## 决策
1. **Coze Studio 只负责画布与节点配置 UI**
不复用其完整后端协议、内置试运行、Trace/Debug。Gateway 仅提供薄兼容层(canvas/save/create/node_template)。
2. **ChatDev 2.0 只作语义参考**
可参考 DAG、并行、循环、动态边、会话执行边界;**不**引入其 WebSocket、SQLite 存储、宿主机 `subprocess` 代码执行、自有 Agent/模型 runtime。
3. **执行内核 = DeerFlow 自建 DAG 调度器;LangGraph 只作智能体内核**
见下方「阶段 2 修订」。智能体 / 技能 / 沙箱 / 模型 / 制品全部复用现有 harness 能力。`deerflow.workflows` 不得导入 `app.*`。
4. **流式协议 = 持久事件日志 + SSE**
先写 `workflow_run_events`,再推 live;断线用 `Last-Event-ID` / `after_seq` 补放。不与 ChatDev WebSocket 并存。
## 阶段 0 配套确认
| 议题 | 结论 |
|------|------|
| SQL 节点驱动 | 首期仅 **MySQL 和/或 PostgreSQL**(与项目实际库一致);不抽象全数据库 |
| 凭据存储 | 画布只存 `credentialRef` / `dataSourceId`;明文密钥进服务端凭据存储,不进 JSON / SSE / 日志 |
| iframe 域名 | 由 `config.yaml` → `workflows.embed.allowed_origins`(阶段 6 落地配置项);票据绑定 origin + workflow + user + actions,约 60s 一次性兑换 |
| 应用库 vs 业务查询库 | DeerFlow 自身业务库 **不得**直接暴露给 SQL 节点;必须管理员登记独立只读数据源 |
## 阶段 2 修订:工作流级编排不编译成 LangGraph
阶段 0 原定「标准图编译为 `StateGraph`」。实现阶段 2 时改为**自建 DAG 调度器**(`deerflow/workflows/runtime/engine.py`),LangGraph 退到**单个 `agent` / `skill` 节点内部**继续做智能体内核。
**原因**:运行状态必须只有一个权威来源。工作流的可恢复性建立在 `workflow_node_runs`(已完成节点的输出)+ `workflow_run_events`(事件日志)之上——重新租约或人工恢复时,执行器从这两张表回放,只跑缺失的节点。若同时用 LangGraph checkpoint 保存工作流级状态,就会出现两份状态需要保持一致(checkpoint 与 node_runs 谁说了算?租约被抢走后 checkpoint 归谁?),恢复语义无法自证。此外 `human_input` 的暂停需要把 `resume_token` 与 `pending_input` 暴露到 HTTP/SSE 层,条件分支需要「未选中的端口整条子图跳过」的显式边状态,循环需要按 `bodyEntry` 精确失效 body 内的 node_runs——这些都要求调度器直接读写运行存储。
**代价**:调度、并行度、重试、超时、循环上限这些机制要自己实现和测试(`tests/test_workflow_engine.py`、`tests/test_workflow_runs.py`)。**收益**:崩溃恢复、取消、暂停/恢复都只有一条真相路径,且不需要为工作流额外引入一套 checkpoint 生命周期。
调度规则本身很小:每条边有 `pending` / `active` / `pruned` 三态,节点在「非回边入边都已定型且至少一条 `active`」时就绪,全部 `pruned` 则跳过并继续下推剪枝。`loop` 节点的 `continue` 回边是唯一允许的环,不参与就绪判定。
## 后果
- 短期需自建 schema / store / dispatcher / SSE,工作量高于“整包移植”。
- 长期只维护一套模型调用、鉴权、沙箱与审计,避免双运行时分叉。
- 前端时间线必须与本仓库冻结的事件 envelope(`deerflow.workflows.events`)契约一致。
## 否决方案
- 把 Coze `workflow_api` 全量试运行当作执行引擎。
- 把 ChatDev `python_executor.py`(宿主机 subprocess)当作代码节点。
- 在画布 JSON 或 URL query 中传递 JWT / DB 密码 / API Key。