Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cmd/agentflow/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ func main() {
readyStatus := "serving"
switch role {
case "worker":
httpapi.ConfigureWorkerSOPSandboxSelection(s, e)
e.ConfigureControl(engine.ControlConfig{Role: role, URL: endpoints.ControlURL, Token: endpoints.ControlToken, APIURL: endpoints.APIBase})
e.StartInstanceHeartbeat(claimCtx)
srv = &http.Server{Addr: endpoints.ListenAddr, Handler: workerHandler(e), ReadHeaderTimeout: 10 * time.Second}
Expand Down
13 changes: 12 additions & 1 deletion docs/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2685,6 +2685,12 @@ paths:
projectId:
type: string
description: Target project. Empty or omitted retains the source project; generic templates require a target project.
sandboxProfileId:
type: string
description: Use this fixed sandbox in the copy.
autoSelectSandbox:
type: boolean
description: Choose a sandbox at runtime. With neither option supplied, inherit the source SOP setting.
responses:
"201":
$ref: "#/components/responses/Workflow"
Expand Down Expand Up @@ -4681,6 +4687,7 @@ components:
properties:
id: {type: string}
name: {type: string}
toolchain: {type: string, description: Tool and version hints used when an Agent chooses a sandbox}
projectId: {type: string, description: Owning project (required)}
shared: {type: boolean, description: Visible to every project}
driver: {type: string, enum: [native, docker]}
Expand Down Expand Up @@ -5382,7 +5389,7 @@ components:
description: Run once in the task workspace or once per repository checkout.
WorkflowDefinition:
type: object
required: [id, name, sandboxProfileId, nodes, edges]
required: [id, name, nodes, edges]
additionalProperties: true
properties:
notifications: {type: array, maxItems: 1, items: {$ref: "#/components/schemas/NotificationBinding"}, description: Single SOP Bot; all nodes automatically notify waiting/failed and SOP completion. Template and AI instruction customize completion only}
Expand All @@ -5407,6 +5414,10 @@ components:
type: string
sandboxProfileId:
type: string
description: Required for a fixed workflow. A run snapshot contains the concrete profile ID.
autoSelectSandbox:
type: boolean
description: Select a sandbox for each new run from the target project's own and shared profiles.
generic:
type: boolean
description: >-
Expand Down
4 changes: 3 additions & 1 deletion docs/api/orchestration.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

### `PUT /api/workflows`

按 `id` 保存。`id` 和 `sandboxProfileId` 必填;`version=0` 时改为 `1`。成功 `200` 返回保存后的 SOP;revision 冲突返回 `409`,其他校验/存储错误 `400`。`id` 命中通用模板时返回 `409`(通用模板只读)。
按 `id` 保存。固定环境填写 `sandboxProfileId`。由 Agent 选择时填写 `autoSelectSandbox: true`,沙箱在每次运行启动时决定,实际 ID 保存在 `workflowSnapshot.sandboxProfileId`。`version=0` 时改为 `1`。成功 `200` 返回保存后的 SOP;revision 冲突返回 `409`,其他校验/存储错误 `400`。`id` 命中通用模板时返回 `409`(通用模板只读)。

```bash
curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -X PUT \
Expand Down Expand Up @@ -71,6 +71,8 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -X PUT \

`id`、`name` 必填。副本固定为 `draft`、`version=1`、`revision=0`,成功 `201`;字段/存储错误 `400`,源 SOP 不存在 `404`。

可用 `sandboxProfileId` 为副本指定固定沙箱,或用 `autoSelectSandbox: true` 让 Agent 选择。省略两项时继承来源 SOP 的设置。

源 SOP 是通用模板时,复制会同时把模板引用的角色创建到 `projectId` 指定的项目(已存在的同名角色直接复用),并把节点上的 `agentId` 重写到本项目角色,因此复制出的 SOP 可直接运行;此时 `projectId` 必填,缺失返回 `400`。模板声明的 `requirements` 会保留在副本上,Studio 继续据此提示依赖(例如发起 MR 节点需要工蜂 Git Token / 工蜂 MCP)。

## 运行
Expand Down
2 changes: 1 addition & 1 deletion docs/api/registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ docker 沙箱的 Dockerfile 存在沙箱里,随沙箱一起共享,没有单

### `GET /api/sandboxes`

返回 `SandboxProfile[]`,`200`。字段为 `id`、`name`、`driver`(`native|docker`;保存 `seatbelt` 或 `bwrap` 会归一成 `native`,运行时在 macOS 解析为 seatbelt、在 Linux 解析为 bwrap;尚未迁移的 `local` 行读出时也是 `native`)、`dockerfile`、`readOnlyRootFS`、`environment`。`dockerfile` 为 `{content, files}`,`files` 是构建上下文文件(相对路径 → 内容)。
返回 `SandboxProfile[]`,`200`。字段为 `id`、`name`、`driver`(`native|docker`;保存 `seatbelt` 或 `bwrap` 会归一成 `native`,运行时在 macOS 解析为 seatbelt、在 Linux 解析为 bwrap;尚未迁移的 `local` 行读出时也是 `native`)、`dockerfile`、`readOnlyRootFS`、`environment` 和可选的 `toolchain`。`toolchain` 记录沙箱内的工具和版本,供 Agent 选择沙箱。`dockerfile` 为 `{content, files}`,`files` 是构建上下文文件(相对路径 → 内容)。

### `PUT /api/sandboxes`

Expand Down
2 changes: 2 additions & 0 deletions docs/conversation-workspaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@

从项目对话调用 `issues_dispatch` 或 `runs_start` 时,如果当前绑定的是本对话开启的工作区,SOP 会在原执行机器上用自己的沙箱挂载这个目录。模型调用、自动草稿和用户确认的草稿都使用这条路径。聊天页确认草稿时用 `X-AgentFlow-Chat-Session` 带上会话 ID。SOP 会等待本轮对话释放工作区,并在目录已回收时恢复快照。同一工作区一次只能交给一个尚未结束的 SOP,SOP 执行期间对话仍可在平台模式查看进度。

SOP 的「运行沙箱环境」可以设为「由 Agent 选择」。每次启动时,Agent 根据项目说明、登记的仓库名称、任务和沙箱的「工具链说明」,从目标项目自有或已共享的沙箱中挑选。信息不足或模型不可用时,优先沿用可用的对话或父 SOP 沙箱,其次使用可用的 `generic-docker`。运行详情显示最终选中的沙箱,重试和恢复使用本次运行的沙箱快照。

SOP 在自己配置的沙箱中按 origin 识别工作区根目录及下方两层已经检出的绑定仓库,并在同一沙箱里准备工作分支。生成新工作分支时,从已有检出的本地 HEAD 创建,保留未推送的提交和未提交的改动。尚无可用对话工作区时,SOP 按常规流程准备工作区。

升级平台时,请同步把执行机器升级到 Runner 0.12.3 或更高版本。较旧版本派发需要复用对话检出的 SOP 时,会收到升级提示。
Expand Down
1 change: 1 addition & 0 deletions internal/domain/assets.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ type DockerfileDefinition struct {
type SandboxProfile struct {
ID string `json:"id"`
Name string `json:"name"`
Toolchain string `json:"toolchain,omitempty"`
ProjectID string `json:"projectId,omitempty"`
Shared bool `json:"shared,omitempty"`
Driver string `json:"driver"` // native, docker (seatbelt / bwrap are resolved native values)
Expand Down
12 changes: 12 additions & 0 deletions internal/domain/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,18 @@ func (r Runner) SupportsConversationCLI() bool {
return versionAtLeast(r.RunnerVersion, RunnerVersionConversationCLI)
}

// SupportsNativeSandbox checks the isolation driver against the Runner's OS
// and its reported ability to start a native sandbox.
func (r Runner) SupportsNativeSandbox(driver string) bool {
if !r.NativeSandboxAvailable {
return false
}
os := strings.ToLower(strings.TrimSpace(r.OS))
resolved, err := ResolveSandboxDriver(driver, os)
return err == nil && (resolved == SandboxDriverSeatbelt && os == "darwin" ||
resolved == SandboxDriverBwrap && os == "linux")
}

func (r Runner) SupportsConversationWorkspace() bool {
return versionAtLeast(r.RunnerVersion, RunnerVersionConversationWorkspace)
}
Expand Down
2 changes: 2 additions & 0 deletions internal/domain/workflow.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ type WorkflowDefinition struct {
Tags []string `json:"tags,omitempty"`
Description string `json:"description"`
SandboxProfileID string `json:"sandboxProfileId"`
// AutoSelectSandbox resolves a sandbox for each new run in its target project.
AutoSelectSandbox bool `json:"autoSelectSandbox,omitempty"`

ProjectCredentialIDs []string `json:"projectCredentialIds,omitempty"`
// MetricCategory 是受控的统计标签(需求开发/Bug 修复/…),用于交付指标归类。
Expand Down
3 changes: 2 additions & 1 deletion internal/engine/chat_workspace.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package engine

import (
"context"
"fmt"
"strings"

Expand All @@ -25,5 +26,5 @@ func (e *Engine) StartConversationWorkspace(input string, actor domain.Telemetry
return domain.Run{}, err
}
wf := domain.WorkflowDefinition{ID: domain.ConversationWorkspaceWorkflowID, Name: "对话工作区", Version: 1, ProjectID: actor.ProjectID, SandboxProfileID: sandboxID, Nodes: []domain.WorkflowNode{}, Edges: []domain.WorkflowEdge{}}
return e.startWorkflowDefinition(wf, input, nil, actor, true)
return e.startWorkflowDefinition(context.Background(), wf, input, nil, actor, true)
}
14 changes: 12 additions & 2 deletions internal/engine/cloud_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"math/rand"
"slices"
"strings"
"time"

Expand Down Expand Up @@ -82,8 +83,13 @@ func (pool CloudRunnerPool) serves(projectID string) bool {
return pool.Label != "" && cloudPoolServes(pool.Projects, projectID)
}

func (e *Engine) pickPoolRunner(label string) (domain.Runner, bool) {
func (e *Engine) pickPoolRunner(label string, nativeDriver ...string) (domain.Runner, bool) {
candidates := e.eligiblePoolRunners(label)
if len(nativeDriver) > 0 && nativeDriver[0] != "" {
candidates = slices.DeleteFunc(candidates, func(runner domain.Runner) bool {
return !runner.SupportsNativeSandbox(nativeDriver[0])
})
}
if len(candidates) == 0 {
return domain.Runner{}, false
}
Expand Down Expand Up @@ -210,11 +216,15 @@ func (e *Engine) bindPoolRunner(ctx context.Context, run domain.Run, nodeID stri
return run, errors.New("云端执行池未配置,无法为该运行分配执行机器")
}
deadline := time.Now().Add(poolBindWait)
var nativeDriver string
if snapshot := run.WorkflowSnapshot.SandboxSnapshot; run.WorkflowSnapshot.AutoSelectSandbox && snapshot != nil && snapshot.Profile.Driver != domain.SandboxDriverDocker {
nativeDriver = snapshot.Profile.Driver
}
var runner domain.Runner
announced := false
for {
var ok bool
if runner, ok = e.pickPoolRunner(label); ok {
if runner, ok = e.pickPoolRunner(label, nativeDriver); ok {
break
}
if time.Now().After(deadline) {
Expand Down
1 change: 1 addition & 0 deletions internal/engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ type Engine struct {

WorkspaceActive func(domain.Run) bool
WorkspaceCheckpointTransport func(context.Context, domain.Run, domain.RunnerWorkspaceRequest) (domain.RunnerWorkspaceResponse, error)
SelectSOPSandbox func(context.Context, SOPSandboxSelection) string
maintenanceOnce sync.Once
}

Expand Down
1 change: 1 addition & 0 deletions internal/engine/run_ops.go
Original file line number Diff line number Diff line change
Expand Up @@ -843,6 +843,7 @@ func (e *Engine) RefreshRunSOP(runID string) error {
// A graph/role update must not silently replace the environment underneath
// an existing workspace. A new Run will pick up the latest sandbox asset.
latest.SandboxProfileID = r.WorkflowSnapshot.SandboxProfileID
latest.AutoSelectSandbox = r.WorkflowSnapshot.AutoSelectSandbox
latest.SandboxSnapshot = r.WorkflowSnapshot.SandboxSnapshot
latest, err := configureBaselineAlignCLI(latest)
if err != nil {
Expand Down
88 changes: 60 additions & 28 deletions internal/engine/run_start.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,16 @@ func (e *Engine) StartWithExecutionContext(workflowID, input string, repository
}

// StartWithRepositoriesContext starts a run with one or more repositories.
// All repositories are equals: each is checked out into a first-level
// Each repository is checked out into a first-level
// sub-directory, gets the same work branch and, on scheduled runs, its own
// integration merge and MR. SOP deliverables stay at the run workspace root.
func (e *Engine) StartWithRepositoriesContext(workflowID, input string, repositories []domain.RepositoryContext, executionContext domain.TelemetryContext) (domain.Run, error) {
return e.startWorkflow(workflowID, input, repositories, executionContext, false)
return e.StartWithRepositories(context.Background(), workflowID, input, repositories, executionContext)
}

func (e *Engine) startWorkflow(workflowID, input string, repositories []domain.RepositoryContext, executionContext domain.TelemetryContext, workspace bool) (domain.Run, error) {
// StartWithRepositories allows cancellation while resolving an automatic
// sandbox. Once admitted, the run continues independently of the caller.
func (e *Engine) StartWithRepositories(ctx context.Context, workflowID, input string, repositories []domain.RepositoryContext, executionContext domain.TelemetryContext) (domain.Run, error) {
wf, ok := e.repo.Workflow(workflowID)
if !ok {
return domain.Run{}, fmt.Errorf("workflow not found")
Expand Down Expand Up @@ -86,12 +88,12 @@ func (e *Engine) startWorkflow(workflowID, input string, repositories []domain.R
return domain.Run{}, fmt.Errorf("SOP 不在共享任务的引用范围内")
}
}
return e.startWorkflowDefinition(wf, input, repositories, executionContext, workspace)
return e.startWorkflowDefinition(ctx, wf, input, repositories, executionContext, false)
}

// startWorkflowDefinition also accepts a run-only conversation workspace definition.
// It never writes a template to the catalog.
func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input string, repositories []domain.RepositoryContext, executionContext domain.TelemetryContext, workspace bool) (domain.Run, error) {
func (e *Engine) startWorkflowDefinition(ctx context.Context, wf domain.WorkflowDefinition, input string, repositories []domain.RepositoryContext, executionContext domain.TelemetryContext, workspace bool) (domain.Run, error) {
workflowID := wf.ID
repositories = normalizeRepositories(repositories)
if executionContext.ParentRunID == "" || !executionContext.ExecutionPinned || executionContext.WorkspaceRunID == "" {
Expand All @@ -118,6 +120,14 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str
return domain.Run{}, fmt.Errorf("项目 %q 不存在,请刷新后重试", executionContext.ProjectID)
}
}
if wf.AutoSelectSandbox && !wf.Shared && !wf.Generic && wf.ProjectID != "" {
if executionContext.ProjectID == "" {
executionContext.ProjectID = wf.ProjectID
}
if executionContext.ProjectID != wf.ProjectID {
return domain.Run{}, apperr.New(apperr.Forbidden, "只能在当前项目运行其私有 SOP")
}
}
wf = defaultWorkflowSandboxProfile(wf)
wf, err := configureBaselineAlignCLI(wf)
if err != nil {
Expand All @@ -130,23 +140,13 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str
if err := validate(wf); err != nil {
return domain.Run{}, err
}
profile, ok := e.repo.Sandbox(wf.SandboxProfileID)
if !ok {
return domain.Run{}, fmt.Errorf("sandbox profile %q not found", wf.SandboxProfileID)
}
if workspace {
if _, err := e.repo.ConversationSandbox(executionContext.ProjectID, profile.ID); err != nil {
return domain.Run{}, err
}
}
sandbox, err := resolveSandbox(profile)
if err != nil {
return domain.Run{}, err
}
if executionContext.SharedScheduleID != "" {
if err := e.validateSharedScheduleWorkflow(wf, executionContext.ProjectID, profile); err != nil {
return domain.Run{}, err
var workspaceSandboxID string
if wf.AutoSelectSandbox && executionContext.ParentRunID != "" {
parent, ok := e.repo.RunState(executionContext.ParentRunID)
if !ok {
return domain.Run{}, fmt.Errorf("父 SOP 运行不存在")
}
workspaceSandboxID = parent.WorkflowSnapshot.SandboxProfileID
}
if !workspace && executionContext.ParentRunID == "" && executionContext.WorkspaceRunID != "" {
owner, err := e.sopConversationWorkspace(executionContext)
Expand All @@ -156,6 +156,7 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str
if domain.TerminalRunStatus(owner.Status) || owner.CancelRequested {
return domain.Run{}, fmt.Errorf("对话工作区已结束")
}
workspaceSandboxID = owner.WorkflowSnapshot.SandboxProfileID
executionContext.ExecutionRunnerID = e.defaultExecutionRunner(owner)
if executionContext.ExecutionRunnerID != "" {
runner, ok := e.repo.Runner(executionContext.ExecutionRunnerID)
Expand All @@ -173,6 +174,9 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str
executionContext.ExecutionPool = ""
}
e.selectSOPExecutionTarget(&executionContext)
if err := e.requireRunnerRepositoryCapabilities(executionContext.ExecutionRunnerID, repositories); err != nil {
return domain.Run{}, err
}
if len(wf.ProjectCredentialIDs) > 0 {
if _, err := e.ResolveRunProjectCredentialEnv(context.Background(), domain.Run{WorkflowSnapshot: wf, ExecutionContext: executionContext}); err != nil {
return domain.Run{}, err
Expand All @@ -191,6 +195,34 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str
if _, err := workflowSandboxRequirements(e.repo, wf); err != nil {
return domain.Run{}, err
}
var profile domain.SandboxProfile
var sandboxSelection string
switch {
case workspace:
profile, err = e.repo.ConversationSandbox(executionContext.ProjectID, wf.SandboxProfileID)
case wf.AutoSelectSandbox:
profile, sandboxSelection, err = e.selectSOPSandbox(ctx, wf, executionContext, repositories, input, workspaceSandboxID)
default:
var ok bool
if profile, ok = e.repo.Sandbox(wf.SandboxProfileID); !ok {
err = fmt.Errorf("sandbox profile %q not found", wf.SandboxProfileID)
}
}
if err != nil {
return domain.Run{}, err
}
sandbox, err := resolveSandbox(profile)
if err != nil {
return domain.Run{}, err
}
if executionContext.SharedScheduleID != "" {
if err := e.validateSharedScheduleWorkflow(wf, executionContext.ProjectID, profile); err != nil {
return domain.Run{}, err
}
}
if wf.AutoSelectSandbox {
wf.SandboxProfileID = profile.ID
}
now := time.Now().UTC()
id := fmt.Sprintf("run-%d", now.UnixNano())
assignWorkBranches(repositories, func() string {
Expand All @@ -207,9 +239,6 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str
firstRepository = repositories[0]
}
executionContext.RunID, executionContext.TraceID, executionContext.WorkflowID, executionContext.WorkflowVersion = id, id, workflowID, wf.Version
if err := e.requireRunnerRepositoryCapabilities(executionContext.ExecutionRunnerID, repositories); err != nil {
return domain.Run{}, err
}
wf.SandboxSnapshot = sandbox
r := domain.Run{
ID: id, WorkflowID: workflowID, WorkflowSnapshot: wf, Status: "running", Input: input,
Expand All @@ -223,8 +252,8 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str
r.Nodes[n.ID] = &domain.NodeRun{NodeID: n.ID, Status: "pending"}
}
if executionContext.ParentRunID != "" {
parent, exists := e.repo.RunState(executionContext.ParentRunID)
if !exists {
parent, ok := e.repo.RunState(executionContext.ParentRunID)
if !ok {
return domain.Run{}, fmt.Errorf("父 SOP 运行不存在")
}
if err := inheritSOPHandoff(parent, &r); err != nil {
Expand All @@ -239,6 +268,9 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str
e.event(&r, "", "workspace.created", "对话工作区已创建")
} else {
e.event(&r, "", "run.started", "流水线开始执行")
if sandboxSelection != "" {
e.event(&r, "", "sandbox.selected", sandboxSelection)
}
if borrowsConversationWorkspace(r) {
e.event(&r, "", "workspace.shared", "复用对话工作区 "+workspaceRunID(r))
}
Expand All @@ -263,12 +295,12 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str
if !executeHere || r.Status == "queued" {
return r, nil
}
ctx, cancel := context.WithCancel(context.Background())
runCtx, cancel := context.WithCancel(context.Background())
if !e.claimRunning(id, cancel) {
cancel()
return r, nil
}
go e.execute(ctx, id)
go e.execute(runCtx, id)
return r, nil
}

Expand Down
Loading
Loading