diff --git a/cmd/agentflow-runner/a2a_config.go b/cmd/agentflow-runner/a2a_config.go new file mode 100644 index 000000000..cd459939d --- /dev/null +++ b/cmd/agentflow-runner/a2a_config.go @@ -0,0 +1,51 @@ +package main + +import ( + "encoding/json" + "errors" + "io" + "os" + "path/filepath" + "strings" + + "agentflow/internal/managedagent" +) + +func configuredExternalAgent() (managedagent.TextAgent, error) { + config := managedagent.A2AConfig{ + Endpoint: strings.TrimSpace(os.Getenv("AGENTFLOW_RUNNER_A2A_ENDPOINT")), + Token: os.Getenv("AGENTFLOW_RUNNER_A2A_TOKEN"), + Loopback: true, + } + if config.Endpoint != "" { + return managedagent.NewA2A(config, nil) + } + path := os.Getenv("AGENTFLOW_RUNNER_A2A_CONFIG") + implicit := path == "" + if implicit { + home, err := os.UserHomeDir() + if err != nil { + return nil, nil + } + path = filepath.Join(home, ".agentflow-runner", "a2a.json") + } + file, err := os.Open(path) + if implicit && errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + defer file.Close() + var local struct { + Endpoint string `json:"endpoint"` + Token string `json:"token,omitempty"` + } + decoder := json.NewDecoder(io.LimitReader(file, 64<<10)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&local); err != nil || decoder.Decode(new(json.RawMessage)) != io.EOF { + return nil, errors.New("invalid Runner A2A configuration") + } + config.Endpoint, config.Token = local.Endpoint, local.Token + return managedagent.NewA2A(config, nil) +} diff --git a/cmd/agentflow-runner/main.go b/cmd/agentflow-runner/main.go index 12db709be..97509609d 100644 --- a/cmd/agentflow-runner/main.go +++ b/cmd/agentflow-runner/main.go @@ -57,6 +57,12 @@ func main() { cfg.MaxConcurrency = concurrencyFromEnv(cfg.MaxConcurrency) cfg.Labels = parseLabels(*labels) + var err error + cfg.ExternalAgent, err = configuredExternalAgent() + if err != nil { + log.Fatal(err) + } + daemon, err := runner.New(cfg) if err != nil { log.Fatal(err) diff --git a/cmd/agentflow/main.go b/cmd/agentflow/main.go index 6ec582989..e0797e1d3 100644 --- a/cmd/agentflow/main.go +++ b/cmd/agentflow/main.go @@ -191,6 +191,9 @@ func main() { // of pool projects: they wait for, or move to, a pool runner. Required: strings.EqualFold(strings.TrimSpace(os.Getenv("AGENTFLOW_LOCAL_EXECUTION")), "false"), }) + if err := configureOptionalExecution(e); err != nil { + log.Fatal(err) + } attachPreviewStore(e, s) log.Printf("engine instance=%s role=%s execute_runs=%t run_lease_ttl=%s", instanceID, role, executeRuns, leaseTTL) claimCtx, stopClaim := context.WithCancel(context.Background()) diff --git a/cmd/agentflow/optional_execution.go b/cmd/agentflow/optional_execution.go new file mode 100644 index 000000000..983b86ec7 --- /dev/null +++ b/cmd/agentflow/optional_execution.go @@ -0,0 +1,131 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + "strconv" + "strings" + + "agentflow/internal/domain" + "agentflow/internal/engine" + "agentflow/internal/managedagent" + "agentflow/internal/opensandbox" +) + +func configureOptionalExecution(e *engine.Engine) error { + if project := strings.TrimSpace(os.Getenv("AGENTFLOW_WMA_PROJECT")); project != "" { + userID, err := strconv.ParseInt(os.Getenv("AGENTFLOW_WMA_USER_ID"), 10, 64) + if err != nil || userID <= 0 { + return errors.New("AGENTFLOW_WMA_USER_ID must be a positive LoopForge user ID") + } + config := managedagent.Config{ + Endpoint: os.Getenv("AGENTFLOW_WMA_ENDPOINT"), + EnterpriseID: os.Getenv("AGENTFLOW_WMA_ENTERPRISE_ID"), + AgentID: os.Getenv("AGENTFLOW_WMA_AGENT_ID"), + SessionID: os.Getenv("AGENTFLOW_WMA_SESSION_ID"), + APIKey: os.Getenv("AGENTFLOW_WMA_API_KEY"), + ACPOrigin: os.Getenv("AGENTFLOW_WMA_ACP_ORIGIN"), + } + secretID, secretKey := os.Getenv("AGENTFLOW_WMA_SECRET_ID"), os.Getenv("AGENTFLOW_WMA_SECRET_KEY") + if secretID != "" || secretKey != "" { + config.TencentCloud = &managedagent.TencentCloudConfig{ + SecretID: secretID, SecretKey: secretKey, + Token: os.Getenv("AGENTFLOW_WMA_SECURITY_TOKEN"), Region: os.Getenv("AGENTFLOW_WMA_REGION"), + } + } + client, err := managedagent.NewWMA(config, nil) + if err != nil { + return err + } + if err := e.ConfigureManagedAgent(domain.WMAExecutorID, project, userID, client); err != nil { + return err + } + } + if file := strings.TrimSpace(os.Getenv("AGENTFLOW_A2A_BINDINGS_FILE")); file != "" { + if err := configureA2ABindings(e, file); err != nil { + return err + } + } + if path := strings.TrimSpace(os.Getenv("AGENTFLOW_OPENSANDBOX_BINDINGS_FILE")); path != "" { + if err := configureOpenSandboxBackends(e, path); err != nil { + return err + } + } + if projects := engine.ParseCloudRunnerProjects(os.Getenv("AGENTFLOW_OPENSANDBOX_PROJECTS")); len(projects) > 0 { + client, err := opensandbox.New(opensandbox.Config{ + Endpoint: os.Getenv("AGENTFLOW_OPENSANDBOX_ENDPOINT"), + APIKey: os.Getenv("AGENTFLOW_OPENSANDBOX_API_KEY"), + RunnerURL: os.Getenv("AGENTFLOW_OPENSANDBOX_RUNNER_URL"), + RunnerImage: os.Getenv("AGENTFLOW_OPENSANDBOX_RUNNER_IMAGE"), + Scope: os.Getenv("AGENTFLOW_OPENSANDBOX_SCOPE"), + RunnerSigningKey: os.Getenv("AGENTFLOW_OPENSANDBOX_RUNNER_SIGNING_KEY"), + }, nil) + if err != nil { + return err + } + if err := e.ConfigureOpenSandbox(engine.DefaultOpenSandboxBackend, client, projects); err != nil { + return err + } + } + return nil +} + +func readExecutionBindings(path string, bindings any) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + decoder := json.NewDecoder(io.LimitReader(file, 1<<20)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(bindings); err != nil || decoder.Decode(new(json.RawMessage)) != io.EOF { + return errors.New("expected one JSON array with the supported fields") + } + return nil +} + +func configureOpenSandboxBackends(e *engine.Engine, path string) error { + var bindings []struct { + ID string `json:"id"` + ProjectIDs []string `json:"projectIds"` + opensandbox.Config + } + if err := readExecutionBindings(path, &bindings); err != nil { + return fmt.Errorf("OpenSandbox bindings: %w", err) + } + for _, binding := range bindings { + client, err := opensandbox.New(binding.Config, nil) + if err != nil { + return fmt.Errorf("OpenSandbox backend %q: %w", binding.ID, err) + } + if err := e.ConfigureOpenSandbox(binding.ID, client, binding.ProjectIDs); err != nil { + return err + } + } + return nil +} + +func configureA2ABindings(e *engine.Engine, path string) error { + var bindings []struct { + ProjectID string `json:"projectId"` + ResponsibleUserID int64 `json:"responsibleUserId"` + Endpoint string `json:"endpoint"` + Token string `json:"token,omitempty"` + } + if err := readExecutionBindings(path, &bindings); err != nil { + return fmt.Errorf("A2A bindings: %w", err) + } + for i, binding := range bindings { + client, err := managedagent.NewA2A(managedagent.A2AConfig{Endpoint: binding.Endpoint, Token: binding.Token}, nil) + if err != nil { + return fmt.Errorf("A2A binding %d: %w", i+1, err) + } + if err := e.ConfigureManagedAgent(domain.A2AExecutorID, binding.ProjectID, binding.ResponsibleUserID, client); err != nil { + return err + } + } + return nil +} diff --git a/deploy/opensandbox-runner.Dockerfile b/deploy/opensandbox-runner.Dockerfile new file mode 100644 index 000000000..940c14c71 --- /dev/null +++ b/deploy/opensandbox-runner.Dockerfile @@ -0,0 +1,14 @@ +FROM debian:bookworm-slim + +RUN apt-get update \ + && apt-get install --yes --no-install-recommends ca-certificates git \ + && rm -rf /var/lib/apt/lists/* \ + && groupadd --gid 10001 runner \ + && useradd --uid 10001 --gid 10001 --create-home runner \ + && install -d -o runner -g runner /home/runner/workspace + +COPY --chmod=0755 agentflow-runner /usr/local/bin/agentflow-runner +ENV HOME=/home/runner +USER 10001:10001 +WORKDIR /home/runner/workspace +ENTRYPOINT ["/usr/local/bin/agentflow-runner"] diff --git a/docs/architecture.md b/docs/architecture.md index 1decc2a24..caf3a09d9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -19,3 +19,87 @@ The platform keeps the upstream Go module name `agentflow`, package boundaries a The public edition adds account/password login and GitHub adapters. These feed the existing user, token, repository and delivery contracts; there is no separate public engine or in-memory production store. A remote repository identity beginning `github:` distinguishes GitHub owner/repository names from legacy tracker identities. The upstream `gongfengProjectId` JSON field carries this identity for compatibility. The CLI's Classic and Portable workflow assets remain separate from each other and from platform role definitions. Sharing behavior contracts is preferable to copying runtime assets. No classic host bundle is required by a platform worker. + +## Managed Agents and execution environments + +An LOOP role chooses an executor. A CLI role runs in the workspace selected for the run. A WorkBuddy Managed Agent or A2A role sends a text turn to a configured Agent and publishes the reply as `result.md`. Downstream nodes get that artifact through the existing artifact handoff. A remote Agent keeps its own workspace and tool configuration. + +| Role executor | Target | How the target is selected | +| --- | --- | --- | +| Existing CLI | Personal Runner | The project or personal default machine, frozen when the run starts | +| Existing CLI | OpenSandbox | The project's configured Docker or Kubernetes lifecycle server, when the run has no default machine and uses an explicit `native` sandbox profile | +| Existing CLI | Existing local runtime or cloud Runner pool | The existing scheduling rules for runs outside OpenSandbox | +| WorkBuddy Managed Agent | Existing WMA session | A server binding for the project and responsible user | +| External A2A Agent | User machine or CVM | The responsible user's personal Runner, which calls its configured loopback service | +| External A2A Agent | Cloud HTTPS service | A server binding for the project and responsible user, explicitly selected on the role | + +Managed Agent dispatch records its attempt before sending the turn. An attempt with an unknown remote outcome — an interrupted turn or one that ran past its budget — requires an explicit retry. The node fails instead of consuming its remaining attempts. One WMA or A2A turn may run for up to five minutes; the connector then cancels the remote task, fails the node with a timeout and, because cancellation is only advisory, does not resend the turn on its own. The CLI and sandbox paths retain their normal task leases, workspace handoff, and result handling. + +### WorkBuddy Managed Agents + +Choose **WorkBuddy Managed Agent** in an LOOP role or set `"executorId":"wma"` through `PUT /api/agents`. Configure the model, tools, and access on the Agent version in WMA. Use a dedicated existing session. [WorkBuddy Agent access guide](https://cloud.tencent.com/document/product/1831/140759) + +| Server environment variable | Value | +| --- | --- | +| AGENTFLOW_WMA_PROJECT | LoopForge project ID | +| AGENTFLOW_WMA_USER_ID | LoopForge responsible user ID | +| AGENTFLOW_WMA_AGENT_ID | Published Agent ID | +| AGENTFLOW_WMA_SESSION_ID | Existing dedicated session ID | +| AGENTFLOW_WMA_ACP_ORIGIN | Optional exact HTTPS origin for an approved private ACP gateway | +| AGENTFLOW_WMA_SECRET_ID, AGENTFLOW_WMA_SECRET_KEY | Tencent Cloud credentials for the enterprise identity | +| AGENTFLOW_WMA_REGION | Tencent Cloud region, default `ap-beijing` | +| AGENTFLOW_WMA_SECURITY_TOKEN | Optional token for temporary Tencent Cloud credentials | +| AGENTFLOW_WMA_ENTERPRISE_ID, AGENTFLOW_WMA_API_KEY | WorkBuddy enterprise ID and `ck_` or `pt_` key, for WorkBuddy OpenAPI authentication | +| AGENTFLOW_WMA_ENDPOINT | OpenAPI control-plane origin for a dedicated tenant. SaaS defaults to `https://www.workbuddy.cn`. | + +Choose one control-plane authentication method. Both methods use the returned ACP endpoint and an access token for the data plane. The configured session is reused. A worker serializes prompts to the session until each request settles. + +### External A2A Agents + +Choose **自带 Agent(A2A)** in the LOOP role and select the personal Runner or cloud HTTPS target. Through the role API, use `"executorId":"a2a"` and `"externalAgentTarget":"runner"` or `"remote"`. The default A2A target is the personal Runner. The service uses the A2A v0.3 JSON-RPC binding. The connector sends a text message, follows asynchronous tasks with `tasks/get`, and requests cancellation when it knows the task ID. [A2A v0.3 specification](https://a2a-protocol.org/v0.3.0/specification/) + +For a user's machine or cloud VM, bind the LoopForge Runner, share it with the project and make it the responsible user's execution machine. Place the following configuration at `~/.agentflow-runner/a2a.json` and restart the Runner. The endpoint uses a literal loopback address, so the Agent can stay on a local port. An optional `token` is sent only to this endpoint. `AGENTFLOW_RUNNER_A2A_ENDPOINT` and `AGENTFLOW_RUNNER_A2A_TOKEN` can set the same values in a service environment. + +```json +{"endpoint":"http://127.0.0.1:9000/a2a"} +``` + +For a cloud HTTPS Agent, set `AGENTFLOW_A2A_BINDINGS_FILE` to a deployment-managed JSON file. A binding applies to one project and responsible user. The file can contain multiple entries. Include an optional `token` when the service requires bearer authentication. + +```json +[ + { + "projectId": "pilot-project", + "responsibleUserId": 42, + "endpoint": "https://agent.example.com/a2a" + } +] +``` + +Managed text roles can reference earlier node replies with `{{upstream}}` or `{{node..output}}`. Their model and tools are set in the Agent service. Use a CLI role for worktree operations, verification gates, per-repository execution, and file-based artifact contracts. + +### OpenSandbox on Docker and Kubernetes + +Run an OpenSandbox lifecycle server for each backend. Both runtimes expose the same lifecycle API to LoopForge. [Docker runtime configuration](https://github.com/opensandbox-group/OpenSandbox/blob/release-1.2.0/server/README.md) · [Kubernetes Helm deployment](https://github.com/opensandbox-group/OpenSandbox/blob/release-1.2.0/manifests/HELM-DEPLOYMENT.md) + +Prepare a Runner image with Git and the CLI tools used by the projects. The base image below can run script-only workflows. + +```sh +runner_context=$(mktemp -d) +CGO_ENABLED=0 go build -o "$runner_context/agentflow-runner" ./cmd/agentflow-runner +docker build -t loopforge-opensandbox-runner:pilot -f deploy/opensandbox-runner.Dockerfile "$runner_context" +``` + +Use `AGENTFLOW_OPENSANDBOX_BINDINGS_FILE` to configure both backends in one deployment. Each entry has `id`, `projectIds`, `endpoint`, `apiKey`, `runnerUrl`, `runnerImage`, `scope`, and `runnerSigningKey`. Use a stable backend ID and a distinct scope for each deployment and backend. The signing key must be at least 32 bytes and match on the LoopForge API and worker processes. The Runner URL must be reachable from sandbox containers. Assign each project to one backend. + +In a configured project, select a `native` profile explicitly on the LOOP. OpenSandbox handles its workspace when the project has no default machine and uses fixed placement. The Runner inherits environment variables from the selected profile. Use the backend deployment to set the container image and resource policies. + +A single-backend deployment can use `AGENTFLOW_OPENSANDBOX_PROJECTS`, `AGENTFLOW_OPENSANDBOX_ENDPOINT`, `AGENTFLOW_OPENSANDBOX_API_KEY`, `AGENTFLOW_OPENSANDBOX_RUNNER_URL`, `AGENTFLOW_OPENSANDBOX_RUNNER_IMAGE`, `AGENTFLOW_OPENSANDBOX_SCOPE`, and `AGENTFLOW_OPENSANDBOX_RUNNER_SIGNING_KEY`. + +LoopForge persists the chosen backend, reserves one sandbox per shared LOOP workspace, and waits for the workspace-scoped Runner to register. The container provides isolation. The dedicated Runner executes inside it. The backend releases the sandbox after artifact collection on successful runs and during cancellation cleanup. Failed and paused runs can reuse their original workspace before the provider's two-hour expiration. The workspace is ephemeral. Long-lived workspaces require persistent storage and recovery policies. + +The integration tests use the lifecycle HTTP contract and the real Runner. To run a mixed LOOP against a disposable Docker or Kubernetes backend, set `LF_OPENSANDBOX_E2E_URL`, `LF_OPENSANDBOX_E2E_API_KEY`, `LF_OPENSANDBOX_E2E_IMAGE`, and `LF_OPENSANDBOX_E2E_BIND_HOST`. The bind host is the isolated test network interface that the Runner can reach. Set `LF_WMA_E2E_AGENT_ID` and `LF_WMA_E2E_SESSION_ID` with the WMA Tencent Cloud environment variables to run a real turn in the mixed LOOP. For A2A, the tests can use services configured through `LF_A2A_E2E_RUNNER_URL` and `LF_A2A_E2E_REMOTE_URL` with their matching `_TOKEN` and `_CA` variables. + +```sh +go test ./internal/managedagent ./internal/runner -run 'TestWMA|TestA2A|TestExternalA2ASOP|TestOpenSandboxMixedSOP' +``` diff --git a/internal/domain/agent.go b/internal/domain/agent.go index 337d7c061..348fea9b8 100644 --- a/internal/domain/agent.go +++ b/internal/domain/agent.go @@ -84,16 +84,17 @@ type AgentDefinition struct { // KnowledgeBase binds the reserved read-only agentflow-knowledge MCP and // the built-in knowledge usage rule. Upstream credentials stay on the // platform; the role only receives a short-lived project-scoped token. - KnowledgeBase bool `json:"knowledgeBase,omitempty"` - Hooks []AgentHook `json:"hooks,omitempty"` - ExecutorID string `json:"executorId,omitempty"` - Model string `json:"model,omitempty"` - Effort string `json:"effort,omitempty"` - Loop AgentLoopPolicy `json:"loop"` - Interventions []HumanInterventionPoint `json:"interventions,omitempty"` - ArtifactOutputs []ArtifactContract `json:"artifactOutputs,omitempty"` - Verification []VerificationGate `json:"verification"` - UpdatedAt time.Time `json:"updatedAt"` + KnowledgeBase bool `json:"knowledgeBase,omitempty"` + Hooks []AgentHook `json:"hooks,omitempty"` + ExecutorID string `json:"executorId,omitempty"` + ExternalAgentTarget string `json:"externalAgentTarget,omitempty"` // a2a: runner (default) or remote + Model string `json:"model,omitempty"` + Effort string `json:"effort,omitempty"` + Loop AgentLoopPolicy `json:"loop"` + Interventions []HumanInterventionPoint `json:"interventions,omitempty"` + ArtifactOutputs []ArtifactContract `json:"artifactOutputs,omitempty"` + Verification []VerificationGate `json:"verification"` + UpdatedAt time.Time `json:"updatedAt"` } // AgentHook is a role-scoped lifecycle script. The runtime compiles the common @@ -134,6 +135,40 @@ type HumanInterventionPoint struct { Instructions string `json:"instructions,omitempty"` } +const ( + WMAExecutorID = "wma" + A2AExecutorID = "a2a" + ExternalAgentRunner = "runner" + ExternalAgentRemote = "remote" +) + +func IsManagedAgentExecutor(provider string) bool { + return provider == WMAExecutorID || provider == A2AExecutorID +} + +func UsesPersonalAgentRunner(provider, target string) bool { + return provider == A2AExecutorID && target != ExternalAgentRemote +} + +func (a AgentDefinition) ValidateManagedExecutor(provider string) error { + target := a.ExternalAgentTarget + if target != "" && (provider != A2AExecutorID || (target != ExternalAgentRunner && target != ExternalAgentRemote)) { + return errors.New("externalAgentTarget 仅适用于 A2A 角色,可选 runner 或 remote") + } + if !IsManagedAgentExecutor(provider) { + return nil + } + if len(a.ArtifactOutputs) > 0 || len(a.Verification) > 0 || len(a.Interventions) > 0 || a.Loop.Enabled { + return errors.New("托管 Agent 角色仅支持文本结果。工作区产物、门禁和自修正需要 CLI") + } + if len(a.Rules) > 0 || len(a.Skills) > 0 || len(a.MCPServers) > 0 || len(a.Hooks) > 0 || + a.PlatformMCP || a.KnowledgeBase || + strings.TrimSpace(a.Model) != "" || strings.TrimSpace(a.Effort) != "" { + return errors.New("请在托管 Agent 的服务端配置模型、角色资产和工具") + } + return nil +} + type ExecutorDefinition struct { ID string `json:"id"` Name string `json:"name"` diff --git a/internal/domain/observability.go b/internal/domain/observability.go index 2b89fee18..7127a1bda 100644 --- a/internal/domain/observability.go +++ b/internal/domain/observability.go @@ -24,6 +24,8 @@ type TelemetrySource struct { } // TelemetryContext correlates all three platform layers plus product context. +const ExecutionPoolOpenSandbox = "opensandbox" + type TelemetryContext struct { ExecutionPinned bool `json:"executionPinned,omitempty"` ProjectID string `json:"projectId,omitempty"` @@ -41,7 +43,10 @@ type TelemetryContext struct { ExecutionRunnerID string `json:"executionRunnerId,omitempty"` // ExecutionPool records cloud-pool or automatic project assignment. // A project-auto run without an ExecutionMode still awaits assignment. - ExecutionPool string `json:"executionPool,omitempty"` + ExecutionPool string `json:"executionPool,omitempty"` + ExecutionProviderID string `json:"executionProviderId,omitempty"` + ExecutionResourceID string `json:"executionResourceId,omitempty"` + ExecutionResourcePending bool `json:"executionResourcePending,omitempty"` // RunnerWorkspaceLayout freezes how a self-hosted runner maps workflow // nodes to disk. Empty is the legacy per-node layout; shared gives every // node in a new Run the same repository and Git index. diff --git a/internal/domain/run.go b/internal/domain/run.go index 6595dc7e6..302867a5b 100644 --- a/internal/domain/run.go +++ b/internal/domain/run.go @@ -178,6 +178,9 @@ type NodeRun struct { StartedAt time.Time `json:"startedAt,omitzero"` FinishedAt time.Time `json:"finishedAt,omitzero"` + // ManagedPromptAttempt marks a non-idempotent remote prompt before dispatch. + ManagedPromptAttempt int `json:"managedPromptAttempt,omitempty"` + // Stream cursors are message-scoped; pending usage is already included in // Usage until a session result replaces it with authoritative totals. UsageStreamCursors map[string]TokenUsage `json:"usageStreamCursors,omitempty"` diff --git a/internal/domain/runner.go b/internal/domain/runner.go index 1daae95a8..68eaedf32 100644 --- a/internal/domain/runner.go +++ b/internal/domain/runner.go @@ -1,6 +1,8 @@ package domain import ( + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -67,6 +69,7 @@ const ( const ( RunnerTaskDesiredCancel = "cancel" RunnerTaskActionCleanupRun = "cleanup_run" + RunnerTaskActionExternalAgent = "external_agent" RunnerTaskActionArchivePreview = "archive_preview" RunnerTaskActionPullWorkBranch = "pull_work_branch" RunnerTaskActionPushWorkBranch = "push_work_branch" @@ -261,6 +264,14 @@ const RunnerVersionEvolutionReplay = "0.13.1" const RunnerResultReportError = "执行结果回传失败" +// RunnerTaskUncertainOutcome is a structured failure code reported by runners +// when a task handed work to an external Agent and the Agent's outcome is +// unknown (the turn ran past its budget, so the advisory cancel may not have +// stopped it). The prompt already reached the Agent, so the control plane must +// not resend it automatically; the error text alone cannot carry this, since +// it crosses the completion API as an opaque string. +const RunnerTaskUncertainOutcome = "outcome_unknown" + func (r Runner) SupportsArtifactTransfer() bool { return versionAtLeast(r.RunnerVersion, RunnerVersionArtifactTransfer) } @@ -291,6 +302,17 @@ const RunnerVersionExistingWorkBranch = "0.7.0" // branch out instead. const RunnerVersionCreateNewWorkBranch = "0.9.1" +const openSandboxRunnerPrefix = "osrunner-" + +func OpenSandboxRunnerID(workspaceRunID string) string { + id := sha256.Sum256([]byte(workspaceRunID)) + return openSandboxRunnerPrefix + hex.EncodeToString(id[:16]) +} + +func IsOpenSandboxRunner(id string) bool { + return strings.HasPrefix(id, openSandboxRunnerPrefix) +} + type Runner struct { ID string `json:"id"` Name string `json:"name"` @@ -527,10 +549,13 @@ type RunnerTask struct { ExitCode *int `json:"exitCode,omitempty"` Result string `json:"result,omitempty"` Error string `json:"error,omitempty"` - StartedAt *time.Time `json:"startedAt,omitempty"` - CompletedAt *time.Time `json:"completedAt,omitempty"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` + // Code is a structured failure code from the runner (see + // RunnerTaskUncertainOutcome). Error stays human-readable. + Code string `json:"code,omitempty"` + StartedAt *time.Time `json:"startedAt,omitempty"` + CompletedAt *time.Time `json:"completedAt,omitempty"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` // RunID/NodeID link a task to a workflow execution. Runner events for a // linked task are bridged into the run timeline (adapter runner-v1). RunID string `json:"runId,omitempty"` diff --git a/internal/engine/cloud_pool.go b/internal/engine/cloud_pool.go index db8e9f381..5c89d200e 100644 --- a/internal/engine/cloud_pool.go +++ b/internal/engine/cloud_pool.go @@ -116,7 +116,7 @@ func poolRunnerCapable(runner domain.Runner, label string) bool { // Pool runners receive every user's credentials, so only runners // registered with the platform bootstrap token (no owner) qualify; // a user's own machine cannot join by labelling itself. - if runner.OwnerUserID != 0 || !runner.SupportsReportedOutputs() || !runner.SupportsIntegrate() { + if runner.OwnerUserID != 0 || domain.IsOpenSandboxRunner(runner.ID) || !runner.SupportsReportedOutputs() || !runner.SupportsIntegrate() { return false } for _, runnerLabel := range runner.Labels { @@ -199,6 +199,9 @@ func isPoolRun(run domain.Run) bool { // machine to return before continuing. Runs on a user's own machine are left // alone. func (e *Engine) bindPoolRunner(ctx context.Context, run domain.Run, nodeID string) (domain.Run, error) { + if isOpenSandboxRun(run) { + return e.bindOpenSandboxRunner(ctx, run, nodeID) + } if run.ExecutionContext.ExecutionPool == domain.ExecutionPoolProjectAuto { // Even a pool-backed auto assignment has a frozen workspace target. return run, e.validateAutoAssignBinding(run) diff --git a/internal/engine/engine.go b/internal/engine/engine.go index bd54b93a3..6a4ad480d 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -12,6 +12,8 @@ import ( "agentflow/internal/domain" "agentflow/internal/knowledge" + "agentflow/internal/managedagent" + "agentflow/internal/opensandbox" "agentflow/internal/preview" "agentflow/internal/repo" "agentflow/internal/runtime" @@ -48,6 +50,10 @@ type Engine struct { draining bool claimKick chan struct{} + managedAgents map[managedAgentBinding]managedagent.TextAgent + openSandboxBackends map[string]*opensandbox.Client + openSandboxProjects map[string]string + // MergeIntoBranch creates or reuses a Gongfeng MR from source→target and // merges it (merge commit, source branch kept). Scheduled LOOP uses this // to land each issue work branch on the integrate baseline. Nil means diff --git a/internal/engine/evolution_replay.go b/internal/engine/evolution_replay.go index 463f87ae5..b8379682b 100644 --- a/internal/engine/evolution_replay.go +++ b/internal/engine/evolution_replay.go @@ -44,6 +44,9 @@ func (e *Engine) validateEvolutionReplayDefinition(wf domain.WorkflowDefinition, if !ok { return fmt.Errorf("agent %q not found", node.AgentID) } + if managedAgentProvider(node, agent) != "" { + return fmt.Errorf("进化回放暂不支持角色「%s」调用托管 Agent", agent.ID) + } if len(agent.Hooks) > 0 { return fmt.Errorf("进化回放暂不支持角色「%s」的生命周期脚本", agent.ID) } diff --git a/internal/engine/managed_agent.go b/internal/engine/managed_agent.go new file mode 100644 index 000000000..d96fbc72e --- /dev/null +++ b/internal/engine/managed_agent.go @@ -0,0 +1,248 @@ +package engine + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "strings" + "time" + + "agentflow/internal/domain" + "agentflow/internal/managedagent" + "agentflow/internal/runtime" +) + +// errManagedTurnUnknown marks a managed Agent attempt whose prompt was already +// sent before the engine lost track of it. Retrying would send the same turn +// again, so the node fails and waits for an explicit retry. +var errManagedTurnUnknown = errors.New("托管 Agent 上一次发送结果未知") + +type managedAgentBinding struct { + provider string + project string + user int64 +} + +func managedAgentProvider(node domain.WorkflowNode, role domain.AgentDefinition) string { + provider := role.ExecutorID + if provider == "" { + provider = node.ExecutorID + } + if domain.IsManagedAgentExecutor(provider) { + return provider + } + return "" +} + +// ConfigureManagedAgent binds a control-plane connection to a project and +// responsible user before the server starts accepting runs. +func (e *Engine) ConfigureManagedAgent(provider, project string, user int64, client managedagent.TextAgent) error { + if !domain.IsManagedAgentExecutor(provider) || strings.TrimSpace(project) == "" || user <= 0 || client == nil { + return errors.New("managed Agent binding requires a provider, project, responsible user and client") + } + key := managedAgentBinding{provider: provider, project: project, user: user} + if e.managedAgents == nil { + e.managedAgents = make(map[managedAgentBinding]managedagent.TextAgent) + } + if _, exists := e.managedAgents[key]; exists { + return fmt.Errorf("duplicate %s Agent binding for project %q and user %d", provider, project, user) + } + e.managedAgents[key] = client + return nil +} + +func (e *Engine) managedAgentClient(provider string, ec domain.TelemetryContext) managedagent.TextAgent { + return e.managedAgents[managedAgentBinding{provider: provider, project: ec.ProjectID, user: ec.ResponsibleUserID}] +} + +func (e *Engine) personalAgentRunner(ec domain.TelemetryContext) bool { + runner, exists := e.repo.Runner(ec.ExecutionRunnerID) + return exists && ec.ResponsibleUserID > 0 && runner.OwnerUserID == ec.ResponsibleUserID && + runner.Status == domain.RunnerStatusOnline && runner.SupportsProvider(domain.A2AExecutorID) && + e.repo.CanUseRunner(runner, ec.ProjectID, ec.ResponsibleUserID) +} + +// ManagedAgentAvailable reports role-editor availability without disclosing +// the service's endpoint, session, or credentials. +func (e *Engine) ManagedAgentAvailable(projectID string, userID int64, provider string) bool { + ec := domain.TelemetryContext{ProjectID: projectID, ResponsibleUserID: userID} + if e.managedAgentClient(provider, ec) != nil { + return true + } + if provider != domain.A2AExecutorID { + return false + } + ec.ExecutionRunnerID = e.repo.ResolveRunnerDefaults(userID, projectID).Runner.ID + return e.personalAgentRunner(ec) +} + +// managedNodeKnowledgeUnsupported rejects knowledge bindings a managed Agent +// turn cannot honour. resolveNodeAssets only runs on the CLI path, so without +// this guard a node/run-level KnowledgeRef would be saved, a run would +// succeed, and the managed Agent would answer without the connector's catalog +// or retrieval instructions — the silent drop the role-level toggle avoids by +// refusing KnowledgeBase. +func managedNodeKnowledgeUnsupported(node domain.WorkflowNode, provider string, runRefs *[]domain.KnowledgeRef) error { + effector := func(refs []domain.KnowledgeRef) string { + ids := make([]string, 0, len(refs)) + for _, ref := range refs { + ids = append(ids, ref.ConnectorID) + } + return strings.Join(ids, "、") + } + if len(node.KnowledgeRefs) > 0 { + return fmt.Errorf("%s 节点 %q 关联了知识库连接器 %s,但托管 Agent 不支持知识库绑定,该绑定不会生效;请改用 CLI 执行器,或在该节点的角色上移除知识库关联", + provider, node.Name, effector(node.KnowledgeRefs)) + } + if runRefs != nil && len(*runRefs) > 0 { + return fmt.Errorf("%s 节点 %q 无法使用本次运行指定的知识库连接器 %s:托管 Agent 不支持知识库绑定;请启动运行时不指定知识库,或把该节点改用 CLI 执行器", + provider, node.Name, effector(*runRefs)) + } + return nil +} + +// errManagedAgentConfiguration marks a managed-Agent node the frozen run +// snapshot can never execute (role assets, knowledge bindings, evolution +// replay, workspace outputs). These checks run before dispatch and read only +// the snapshot, so every further attempt fails identically; nodeFailedAt +// fails the node at once instead of burning MaxAttempts or auto-rejecting +// upstream work that cannot change the outcome. +var errManagedAgentConfiguration = errors.New("托管 Agent 节点配置不受支持") + +type managedConfigurationError struct{ err error } + +func (e managedConfigurationError) Error() string { return e.err.Error() } +func (e managedConfigurationError) Unwrap() error { return e.err } +func (e managedConfigurationError) Is(target error) bool { + return target == errManagedAgentConfiguration +} + +// managedConfiguration keeps the original message (shown on the node) while +// tagging it as deterministic. +func managedConfiguration(err error) error { + if err == nil { + return nil + } + return managedConfigurationError{err: err} +} + +func (e *Engine) executeManagedAgentNode(ctx context.Context, wf domain.WorkflowDefinition, run domain.Run, node domain.WorkflowNode, agent domain.AgentDefinition, provider string, generation, attempt int) error { + if err := agent.ValidateManagedExecutor(provider); err != nil { + return managedConfiguration(err) + } + // Check before the dispatch fence below: a rejected node never sends a + // turn, so an explicit retry must not be told a turn is already in flight. + if err := managedNodeKnowledgeUnsupported(node, provider, run.ExecutionContext.KnowledgeRefs); err != nil { + return managedConfiguration(err) + } + if run.ExecutionContext.IsEvolutionReplay() { + return managedConfiguration(errors.New("进化回放暂不支持托管 Agent")) + } + if len(node.ArtifactOutputs) > 0 || normalizeExecutionScope(node.ExecutionScope) == domain.ExecutionScopeRepositories || + len(node.CredentialEnv) > 0 { + return managedConfiguration(fmt.Errorf("%s 节点 %q 的工作区产物和逐仓库执行需要 CLI", provider, node.Name)) + } + var runnerID string + var client managedagent.TextAgent + if domain.UsesPersonalAgentRunner(provider, agent.ExternalAgentTarget) { + if !e.personalAgentRunner(run.ExecutionContext) { + return errors.New("A2A 节点需要责任人的在线个人执行器,且执行器已配置本机 A2A Agent") + } + runnerID = run.ExecutionContext.ExecutionRunnerID + } else { + client = e.managedAgentClient(provider, run.ExecutionContext) + if client == nil { + return fmt.Errorf("当前项目和运行责任人未配置 %s Agent", provider) + } + } + + // Fence a non-idempotent turn before dispatch. Recovery never sends the + // same attempt a second time when the first request's outcome is unknown. + dispatch := false + if err := e.updateRunErr(run.ID, func(current *domain.Run) { + nr := current.Nodes[node.ID] + if !shouldCommitNodeOutcome(*current, nr, generation, attempt, false) { + return + } + if nr.ManagedPromptAttempt != attempt { + nr.ManagedPromptAttempt = attempt + nr.Provider = provider + dispatch = true + return + } + // The fenced attempt cannot be resumed. Drop the "waiting to resume" + // marker so an explicit retry starts a new attempt instead of + // continuing this one and hitting the fence again. + nr.Activity = "托管 Agent 上一次发送结果未知,确认后可重试" + }); err != nil { + return err + } + if !dispatch { + return fmt.Errorf("%w:%s 节点本次执行已发起或终止,请确认原执行结果后重试", errManagedTurnUnknown, provider) + } + if err := ctx.Err(); err != nil { + return err + } + prompt := strings.ReplaceAll(renderPromptWithStore(e.repo, wf, node, run), "{{artifacts}}", "") + sink := func(event domain.TelemetryEvent) { e.observe(run.ID, node.ID, event) } + var output string + var err error + if runnerID != "" { + output, err = e.dispatchExternalAgent(ctx, run.ID, node.ID, runnerID, prompt, attempt, sink) + } else { + output, err = client.Run(ctx, prompt, func(text string) { + sink(domain.TelemetryEvent{Category: "output", Name: "agent.output", Phase: "progress", Message: text, Provider: provider}) + }) + } + if err != nil { + return err + } + if strings.TrimSpace(output) == "" { + return fmt.Errorf("%s Agent 结束时没有返回文本", provider) + } + if err := ctx.Err(); err != nil { + return err + } + artifact := newArtifact(run.ID, node.ID, attempt, "result", "result.md", "text/markdown", []byte(output)) + return e.updateRunErr(run.ID, func(current *domain.Run) { + nr := current.Nodes[node.ID] + if !shouldCommitNodeOutcome(*current, nr, generation, attempt, true) { + return + } + current.Artifacts = append(current.Artifacts, artifact) + nr.Output, nr.Error, nr.Status, nr.FinishedAt = output, "", "succeeded", time.Now().UTC() + e.event(current, node.ID, "node.succeeded", node.Name+" 已完成") + }) +} + +func (e *Engine) dispatchExternalAgent(ctx context.Context, runID, nodeID, runnerID, prompt string, attempt int, sink runtime.EventSink) (string, error) { + key := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%d", runID, nodeID, attempt))) + task := domain.RunnerTask{ + ID: fmt.Sprintf("rt-a2a-%x", key[:16]), + RunnerID: runnerID, RunID: runID, NodeID: nodeID, Provider: domain.A2AExecutorID, + Action: domain.RunnerTaskActionExternalAgent, Prompt: prompt, Status: domain.RunnerTaskQueued, MaxAttempts: 1, + } + if err := e.repo.PutRunnerTask(task); err != nil { + return "", err + } + e.notifyRunnerDispatch(task.Provider) + completed, err := e.awaitRunnerTask(ctx, task.ID, sink) + if err != nil { + return "", err + } + if completed.Status == domain.RunnerTaskSuccess { + return completed.Result, nil + } + // A turn the personal Runner handed to the Agent and could not confirm is + // the same unknown outcome the direct path reports. Keep the runner's + // explanation, but restore the sentinel the completion API cannot carry: + // an unknown outcome never consumes another attempt. + if completed.Code == domain.RunnerTaskUncertainOutcome { + return "", &managedagent.UnknownTurnError{Message: strings.TrimSpace(completed.Error)} + } + if completed.Error != "" { + return "", errors.New(completed.Error) + } + return "", fmt.Errorf("个人执行器 A2A 任务结束于 %s", completed.Status) +} diff --git a/internal/engine/managed_knowledge_refs_test.go b/internal/engine/managed_knowledge_refs_test.go new file mode 100644 index 000000000..3e2a1422d --- /dev/null +++ b/internal/engine/managed_knowledge_refs_test.go @@ -0,0 +1,249 @@ +package engine + +import ( + "context" + "strings" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/repo" + "agentflow/internal/runtime" +) + +// recordingManagedAgent reports whether the turn reached the provider and what +// prompt it carried, so tests can prove a rejected node never dispatches. +type recordingManagedAgent struct { + runs int + prompts []string +} + +func (a *recordingManagedAgent) Run(_ context.Context, prompt string, onText func(string)) (string, error) { + a.runs++ + a.prompts = append(a.prompts, prompt) + onText("managed-answer") + return "managed-answer", nil +} + +func TestManagedNodeKnowledgeRefsNotSilentlyDropped(t *testing.T) { + refs := []domain.KnowledgeRef{{ConnectorID: "kc-rv1469", Mode: "all"}} + cases := []struct { + name string + provider string + node domain.WorkflowNode + runRefs *[]domain.KnowledgeRef + wantErr []string + }{ + { + name: "managed node with an existing connector binding is rejected", + provider: domain.A2AExecutorID, + node: domain.WorkflowNode{ID: "n1", Name: "A2A", Type: "agent", KnowledgeRefs: refs}, + wantErr: []string{"知识库", "kc-rv1469", "托管 Agent"}, + }, + { + name: "run-level pin is rejected on a managed node", + provider: domain.WMAExecutorID, + node: domain.WorkflowNode{ID: "n1", Name: "WMA", Type: "agent"}, + runRefs: &[]domain.KnowledgeRef{{ConnectorID: "kc-run", Mode: "all"}}, + wantErr: []string{"知识库", "kc-run", "托管 Agent"}, + }, + { + name: "explicit empty knowledgeRefs override is not a binding", + provider: domain.A2AExecutorID, + node: domain.WorkflowNode{ID: "n1", Name: "A2A", Type: "agent"}, + runRefs: &[]domain.KnowledgeRef{}, + }, + { + name: "managed node without knowledge bindings stays allowed", + provider: domain.WMAExecutorID, + node: domain.WorkflowNode{ID: "n1", Name: "WMA", Type: "agent"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := managedNodeKnowledgeUnsupported(tc.node, tc.provider, tc.runRefs) + if len(tc.wantErr) == 0 { + if err != nil { + t.Fatalf("managedNodeKnowledgeUnsupported() = %v, want nil", err) + } + return + } + if err == nil { + t.Fatal("managedNodeKnowledgeUnsupported() = nil, want an explicit rejection") + } + for _, want := range tc.wantErr { + if !strings.Contains(err.Error(), want) { + t.Fatalf("error %q missing %q", err.Error(), want) + } + } + }) + } +} + +// TestReview1469ManagedNodeKnowledgeRefs mirrors the reviewer's repro: the same +// connector reference bound to a managed node must fail loudly instead of being +// dropped, while a managed node without knowledge bindings still runs. +func TestReview1469ManagedNodeKnowledgeRefs(t *testing.T) { + store, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + + role := domain.AgentDefinition{ + ID: "rv1469-a2a", Name: "A2A role", ProjectID: "default", + ExecutorID: domain.A2AExecutorID, ExternalAgentTarget: domain.ExternalAgentRemote, + Prompt: "answer the question", + } + if err := store.PutAgent(role); err != nil { + t.Fatal(err) + } + agent := &recordingManagedAgent{} + eng := New(store, runtime.NewManagerWithLimit(t.TempDir(), 1)) + if err := eng.ConfigureManagedAgent(domain.A2AExecutorID, "default", 42, agent); err != nil { + t.Fatal(err) + } + + execute := func(runID string, node domain.WorkflowNode, runRefs *[]domain.KnowledgeRef) (domain.Run, string) { + t.Helper() + wf := domain.WorkflowDefinition{ + ID: "wf-rv1469-" + runID, Name: "wf", ProjectID: "default", + SandboxProfileID: "test-native", + Nodes: []domain.WorkflowNode{node}, + } + run := domain.Run{ + ID: runID, Status: "running", WorkflowID: wf.ID, WorkflowSnapshot: wf, + ExecutionContext: domain.TelemetryContext{ProjectID: "default", ResponsibleUserID: 42, KnowledgeRefs: runRefs}, + Nodes: map[string]*domain.NodeRun{node.ID: {NodeID: node.ID, Status: "pending"}}, + } + if err := store.PutRun(run); err != nil { + t.Fatal(err) + } + if _, err := eng.acquireLease(run); err != nil { + t.Fatal(err) + } + eng.executeNode(context.Background(), run.ID, wf, node) + got, ok := store.Run(run.ID) + if !ok { + t.Fatalf("run %s not found", run.ID) + } + return got, got.Nodes[node.ID].Error + } + + managedWithKB := domain.WorkflowNode{ + ID: "n1", Name: "Managed with KB", Type: "agent", AgentID: role.ID, + KnowledgeRefs: []domain.KnowledgeRef{{ConnectorID: "kc-rv1469", Mode: "all"}}, + } + got, nodeErr := execute("rv1469-managed-existing-connector", managedWithKB, nil) + if got.Nodes["n1"].Status != "failed" { + t.Fatalf("managed node with knowledge refs status = %q, want failed (error=%q)", got.Nodes["n1"].Status, nodeErr) + } + if !strings.Contains(nodeErr, "kc-rv1469") || !strings.Contains(nodeErr, "知识库") { + t.Fatalf("node error %q should name the dropped connector and the knowledge binding", nodeErr) + } + if agent.runs != 0 { + t.Fatalf("provider was called %d times for a node whose knowledge binding cannot be honoured", agent.runs) + } + if len(got.Artifacts) != 0 { + t.Fatalf("rejected node produced artifacts: %+v", got.Artifacts) + } + + got, nodeErr = execute("rv1469-managed-run-level-pin", domain.WorkflowNode{ID: "n1", Name: "Managed pinned", Type: "agent", AgentID: role.ID}, + &[]domain.KnowledgeRef{{ConnectorID: "kc-run", Mode: "all"}}) + if got.Nodes["n1"].Status != "failed" || !strings.Contains(nodeErr, "kc-run") { + t.Fatalf("run-level pin on managed node: status=%q error=%q, want failed naming kc-run", got.Nodes["n1"].Status, nodeErr) + } + if agent.runs != 0 { + t.Fatalf("provider was called %d times for a run-level pin the managed node cannot honour", agent.runs) + } + + got, nodeErr = execute("rv1469-managed-no-knowledge", domain.WorkflowNode{ID: "n1", Name: "Managed plain", Type: "agent", AgentID: role.ID}, nil) + if got.Nodes["n1"].Status != "succeeded" || nodeErr != "" { + t.Fatalf("managed node without knowledge bindings: status=%q error=%q, want succeeded", got.Nodes["n1"].Status, nodeErr) + } + if agent.runs != 1 || !strings.Contains(agent.prompts[0], "answer the question") { + t.Fatalf("managed node without knowledge bindings should dispatch once, runs=%d prompts=%q", agent.runs, agent.prompts) + } +} + +// TestManagedNodeConfigurationFailureIsNotRetried covers the 3819f1c9 review: +// the knowledge check (and the other snapshot-only managed checks) fail the +// same way on every attempt, so a node with MaxAttempts>1 must fail at once +// instead of looping to MaxAttempts. A transient precondition — no managed +// client configured yet — keeps the normal retry. +func TestManagedNodeConfigurationFailureIsNotRetried(t *testing.T) { + store, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + for _, role := range []domain.AgentDefinition{ + {ID: "nr-a2a", Name: "A2A", ProjectID: "default", ExecutorID: domain.A2AExecutorID, ExternalAgentTarget: domain.ExternalAgentRemote, Prompt: "answer"}, + {ID: "nr-a2a-model", Name: "A2A model", ProjectID: "default", ExecutorID: domain.A2AExecutorID, ExternalAgentTarget: domain.ExternalAgentRemote, Prompt: "answer", Model: "pinned"}, + {ID: "nr-wma", Name: "WMA", ProjectID: "default", ExecutorID: domain.WMAExecutorID, Prompt: "answer"}, + } { + if err := store.PutAgent(role); err != nil { + t.Fatal(err) + } + } + agent := &recordingManagedAgent{} + eng := New(store, runtime.NewManagerWithLimit(t.TempDir(), 1)) + if err := eng.ConfigureManagedAgent(domain.A2AExecutorID, "default", 42, agent); err != nil { + t.Fatal(err) + } + execute := func(runID string, node domain.WorkflowNode) domain.Run { + t.Helper() + wf := domain.WorkflowDefinition{ID: "wf-" + runID, Name: "wf", ProjectID: "default", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{node}} + run := domain.Run{ + ID: runID, Status: "running", WorkflowID: wf.ID, WorkflowSnapshot: wf, + ExecutionContext: domain.TelemetryContext{ProjectID: "default", ResponsibleUserID: 42}, + Nodes: map[string]*domain.NodeRun{node.ID: {NodeID: node.ID, Status: "pending"}}, + } + if err := store.PutRun(run); err != nil { + t.Fatal(err) + } + if _, err := eng.acquireLease(run); err != nil { + t.Fatal(err) + } + eng.executeNode(context.Background(), run.ID, wf, node) + got, ok := store.Run(run.ID) + if !ok { + t.Fatalf("run %s not found", run.ID) + } + return got + } + retried := func(r domain.Run) bool { + for _, ev := range r.Events { + if ev.Type == "node.retry" { + return true + } + } + return false + } + kb := []domain.KnowledgeRef{{ConnectorID: "kc-nr", Mode: "all"}} + for _, tc := range []struct { + name, runID string + node domain.WorkflowNode + }{ + {"knowledge binding", "nr-kb", domain.WorkflowNode{ID: "n1", Name: "KB", Type: "agent", AgentID: "nr-a2a", MaxAttempts: 3, KnowledgeRefs: kb}}, + {"role assets", "nr-model", domain.WorkflowNode{ID: "n1", Name: "Model", Type: "agent", AgentID: "nr-a2a-model", MaxAttempts: 3}}, + {"workspace outputs", "nr-outputs", domain.WorkflowNode{ID: "n1", Name: "Outputs", Type: "agent", AgentID: "nr-a2a", MaxAttempts: 3, + ArtifactOutputs: []domain.ArtifactContract{{Name: "out", Path: "out.md"}}}}, + } { + t.Run(tc.name, func(t *testing.T) { + got := execute(tc.runID, tc.node) + nr := got.Nodes["n1"] + if nr.Status != "failed" || retried(got) { + t.Fatalf("deterministic managed configuration failure: status=%q retried=%v error=%q, want failed without retry", nr.Status, retried(got), nr.Error) + } + if agent.runs != 0 { + t.Fatalf("provider dispatched %d turns for a rejected node", agent.runs) + } + }) + } + t.Run("missing managed client still retries", func(t *testing.T) { + got := execute("nr-no-client", domain.WorkflowNode{ID: "n1", Name: "WMA", Type: "agent", AgentID: "nr-wma", MaxAttempts: 3}) + if nr := got.Nodes["n1"]; nr.Status != "pending" || !retried(got) { + t.Fatalf("transient managed precondition: status=%q retried=%v error=%q, want pending retry", nr.Status, retried(got), nr.Error) + } + }) +} diff --git a/internal/engine/misc_helpers_cases_test.go b/internal/engine/misc_helpers_cases_test.go index 7da9ba8e1..e3bc9024d 100644 --- a/internal/engine/misc_helpers_cases_test.go +++ b/internal/engine/misc_helpers_cases_test.go @@ -3,6 +3,7 @@ package engine import ( "context" "errors" + "fmt" "os" "os/exec" "path/filepath" @@ -11,6 +12,7 @@ import ( "time" "agentflow/internal/domain" + "agentflow/internal/managedagent" "agentflow/internal/observability" "agentflow/internal/runtime" ) @@ -260,6 +262,12 @@ func TestNodeOutcomeDecisionAndTransitionBranches(t *testing.T) { if shouldRetryFailedAttempt(domain.WorkflowNode{MaxAttempts: 3}, 1, errors.New("verification failed")) { t.Fatal("verification failure retried") } + if shouldRetryFailedAttempt(domain.WorkflowNode{MaxAttempts: 3}, 1, fmt.Errorf("%w:a2a 节点本次执行已发起或终止", errManagedTurnUnknown)) { + t.Fatal("a managed Agent turn with an unknown outcome must not be sent again automatically") + } + if shouldRetryFailedAttempt(domain.WorkflowNode{MaxAttempts: 3}, 1, fmt.Errorf("A2A Agent 未在 5m0s 内完成本轮,已请求取消:%w", managedagent.ErrTurnTimedOut)) { + t.Fatal("a timed-out managed Agent turn must not be sent again automatically") + } if !shouldRetryFailedAttempt(domain.WorkflowNode{MaxAttempts: 3}, 1, errors.New("ordinary")) { t.Fatal("ordinary failure not retried") } diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.go index 73dd97748..91369b114 100644 --- a/internal/engine/node_execute.go +++ b/internal/engine/node_execute.go @@ -442,6 +442,15 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl return } current, _ := e.repo.RunProgress(runID) + if node.Type != "script" && node.Type != "command" { + if agent, ok := workflowAgent(e.repo, wf, node.AgentID); ok { + provider := managedAgentProvider(node, agent) + if provider != "" { + failNode(e.executeManagedAgentNode(ctx, wf, current, node, agent, provider, executionGeneration, executionAttempt), nodeRejects(node)) + return + } + } + } current, err := e.bindPoolRunner(ctx, current, node.ID) if err != nil { failNode(err, false) diff --git a/internal/engine/node_outcome.go b/internal/engine/node_outcome.go index 478a471a4..37fab117b 100644 --- a/internal/engine/node_outcome.go +++ b/internal/engine/node_outcome.go @@ -8,6 +8,8 @@ import ( "time" "agentflow/internal/domain" + "agentflow/internal/managedagent" + "agentflow/internal/opensandbox" "agentflow/internal/repo" "agentflow/internal/runtime" @@ -53,7 +55,7 @@ func shouldCommitNodeOutcome(r domain.Run, nr *domain.NodeRun, generation, attem func (e *Engine) nodeFailedAt(runID string, node domain.WorkflowNode, attempt, generation int, err error, allowReject bool) { var rejectFrom NodeExpectation - configurationFailure := errors.Is(err, ErrWorkspaceControlConfiguration) + configurationFailure := errors.Is(err, ErrWorkspaceControlConfiguration) || errors.Is(err, errManagedAgentConfiguration) storeFailure := func(r *domain.Run) { nr := r.Nodes[node.ID] if !shouldCommitNodeOutcome(*r, nr, generation, attempt, false) { @@ -134,12 +136,19 @@ var errNodeArtifactCommit = errors.New("保存节点终态和产物失败") func shouldRetryFailedAttempt(node domain.WorkflowNode, attempt int, err error) bool { // A failed artifact write follows a completed execution, which may have side effects. - if errors.Is(err, ErrWorkspaceControlConfiguration) || errors.Is(err, errSOPArtifactWrite) || errors.Is(err, errNodeArtifactCommit) || isArtifactHandoffFailure(err) { + if errors.Is(err, ErrWorkspaceControlConfiguration) || errors.Is(err, errManagedAgentConfiguration) || errors.Is(err, errManagedTurnUnknown) || errors.Is(err, managedagent.ErrTurnTimedOut) || errors.Is(err, errSOPArtifactWrite) || errors.Is(err, errNodeArtifactCommit) || isArtifactHandoffFailure(err) { return false } if err != nil && (isMaxTurnsErr(err) || strings.Contains(err.Error(), "verification ") || runtime.IsCwdMountFailure(err)) { return false } + // A provider that refused a create with a definitive 4xx (and had no + // sandbox to find) will refuse the identical request again; retrying only + // repeats the POST. Unknown outcomes (timeout, 5xx) are not this type. + var rejected *opensandbox.RejectedError + if errors.As(err, &rejected) { + return false + } return attempt < max(1, node.MaxAttempts) } diff --git a/internal/engine/opensandbox.go b/internal/engine/opensandbox.go new file mode 100644 index 000000000..d30d1fe58 --- /dev/null +++ b/internal/engine/opensandbox.go @@ -0,0 +1,271 @@ +package engine + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "agentflow/internal/domain" + "agentflow/internal/opensandbox" + "agentflow/internal/repo" +) + +const openSandboxStartupTimeout = 2 * time.Minute + +const DefaultOpenSandboxBackend = "default" + +// ErrExecutionResourceRelease marks a provider-side release (OpenSandbox +// DELETE, lookup of a pending create, or a missing backend) that did not +// complete. Callers keep the run: its ExecutionResourceID and Runner +// registration are the only handle on the still-live sandbox, so dropping the +// record would leak the Pod until the provider TTL with nothing left to retry +// from. The HTTP layer answers 503 so the client retries the delete. +var ErrExecutionResourceRelease = errors.New("OpenSandbox 执行环境释放失败") + +// ConfigureOpenSandbox installs a lifecycle backend before accepting runs. +// Each project resolves to one backend, which is frozen on the root run. +func (e *Engine) ConfigureOpenSandbox(backend string, client *opensandbox.Client, projects []string) error { + if backend == "" || backend != strings.TrimSpace(backend) || client == nil || len(projects) == 0 { + return errors.New("OpenSandbox backend requires an ID, lifecycle client and explicit project IDs") + } + if e.openSandboxBackends[backend] != nil { + return fmt.Errorf("duplicate OpenSandbox backend %q", backend) + } + seen := make(map[string]bool, len(projects)) + for _, project := range projects { + if project == "" || project == "*" || project != strings.TrimSpace(project) { + return errors.New("OpenSandbox requires explicit project IDs") + } + if e.openSandboxProjects[project] != "" || seen[project] { + return fmt.Errorf("project %q has multiple OpenSandbox bindings", project) + } + seen[project] = true + } + if e.openSandboxBackends == nil { + e.openSandboxBackends = make(map[string]*opensandbox.Client) + e.openSandboxProjects = make(map[string]string) + } + e.openSandboxBackends[backend] = client + for project := range seen { + e.openSandboxProjects[project] = backend + } + return nil +} + +func (e *Engine) openSandboxForRun(run domain.Run) *opensandbox.Client { + backend := run.ExecutionContext.ExecutionProviderID + if backend == "" { + backend = DefaultOpenSandboxBackend + } + return e.openSandboxBackends[backend] +} + +func isOpenSandboxRun(run domain.Run) bool { + return run.ExecutionContext.ExecutionPool == domain.ExecutionPoolOpenSandbox +} + +func openSandboxSupportsProfile(profile domain.SandboxProfile) bool { + return profile.Driver == domain.SandboxDriverNative && !profile.Privileged && !profile.ReadOnlyRootFS && !profile.HasResourceLimits() +} + +// OpenSandboxRegistrant validates that an issued bootstrap token is still +// bound to a live workspace. It cannot register an ordinary or unrelated Runner. +func (e *Engine) OpenSandboxRegistrant(token string) (string, bool) { + id, ok := opensandbox.WorkspaceFromBootstrap(token) + if !ok { + return "", false + } + run, ok := e.repo.RunState(id) + if !ok { + return "", false + } + ec := run.ExecutionContext + client := e.openSandboxForRun(run) + if !isLiveStatus(run.Status) || !isOpenSandboxRun(run) || sharesWorkspace(run) || + client == nil || !client.ValidBootstrap(token, id) || (!ec.ExecutionResourcePending && ec.ExecutionResourceID == "") || + ec.ExecutionRunnerID != domain.OpenSandboxRunnerID(id) { + return "", false + } + return ec.ExecutionRunnerID, true +} + +// bindOpenSandboxRunner waits for both the sandbox and its dedicated Runner. +// Child SOPs inherit the owner's binding and do not provision new resources. +func (e *Engine) bindOpenSandboxRunner(ctx context.Context, run domain.Run, nodeID string) (domain.Run, error) { + ownerID := workspaceRunID(run) + unlock := e.lockPoolBinding(ownerID) + defer unlock() + + ctx, cancel := context.WithTimeout(ctx, openSandboxStartupTimeout) + defer cancel() + owner, ok := e.repo.RunState(ownerID) + if !ok || !isOpenSandboxRun(owner) || owner.ExecutionContext.ProjectID != run.ExecutionContext.ProjectID || + owner.ExecutionContext.ExecutionProviderID != run.ExecutionContext.ExecutionProviderID { + return run, errors.New("OpenSandbox 工作区绑定不存在") + } + client := e.openSandboxForRun(owner) + if client == nil { + return run, errors.New("此运行绑定的 OpenSandbox 未配置") + } + runnerID := domain.OpenSandboxRunnerID(ownerID) + if owner.ExecutionContext.ExecutionRunnerID != runnerID || run.ExecutionContext.ExecutionRunnerID != runnerID { + return run, errors.New("OpenSandbox Runner 与工作区绑定不符") + } + externalID := owner.ExecutionContext.ExecutionResourceID + if externalID == "" { + if sharesWorkspace(run) || !e.ownsRun(owner) { + return run, errors.New("等待所属运行分配 OpenSandbox") + } + var err error + externalID, err = e.provisionOpenSandbox(ctx, client, owner, nodeID) + if err != nil { + return run, err + } + } + for { + sandbox, err := client.Inspect(ctx, ownerID, externalID) + if errors.Is(err, opensandbox.ErrNotFound) { + return run, errors.New("OpenSandbox 已回收,原工作区不可用,请新建运行") + } + if err != nil { + return run, err + } + switch sandbox.Status.State { + case "Running": + runner, ok := e.repo.Runner(runnerID) + if ok && runner.Status == domain.RunnerStatusOnline && runner.SupportsIntegrate() && runner.SupportsReportedOutputs() { + if fresh, ok := e.repo.RunProgress(run.ID); ok { + return fresh, e.requireRunnerRepositoryCapabilities(runnerID, fresh.RepositoryContexts()) + } + return run, errors.New("运行已不存在") + } + case "Failed", "Terminated", "Deleting", "Stopping", "Paused": + return run, fmt.Errorf("OpenSandbox 不可执行,状态为 %s", sandbox.Status.State) + } + select { + case <-ctx.Done(): + return run, fmt.Errorf("等待 OpenSandbox Runner 就绪: %w", ctx.Err()) + case <-time.After(time.Second): + } + } +} + +func (e *Engine) provisionOpenSandbox(ctx context.Context, client *opensandbox.Client, owner domain.Run, nodeID string) (string, error) { + sandbox, err := client.Find(ctx, owner.ID) + if errors.Is(err, opensandbox.ErrNotFound) { + // Persist the create intent before POST. After a response is lost or a + // worker restarts, retry only the lookup, which cannot start another Pod. + recorded := false + updateErr := e.updateRunErr(owner.ID, func(current *domain.Run) { + ec := ¤t.ExecutionContext + if e.ownsRun(*current) && isLiveStatus(current.Status) && !ec.ExecutionResourcePending && ec.ExecutionResourceID == "" { + ec.ExecutionResourcePending = true + recorded = true + e.event(current, nodeID, "execution.waiting", "正在创建 OpenSandbox 执行环境") + } + }) + if updateErr != nil { + return "", updateErr + } + if !recorded { + return "", errors.New("OpenSandbox 创建结果待确认,请检查原申请或新建运行") + } + sandbox, err = client.Create(ctx, owner.ID) + var rejected *opensandbox.RejectedError + if errors.As(err, &rejected) { + // A provider can answer a duplicate create with 409 although the + // sandbox exists. Look it up before dropping the intent: a run + // deleted before the next attempt would otherwise lose its only + // handle and leak the sandbox until the provider TTL. + if found, findErr := client.Find(ctx, owner.ID); findErr == nil { + sandbox, err = found, nil + } else if !errors.Is(findErr, opensandbox.ErrNotFound) { + // The lookup failed for another reason, so this attempt's + // outcome is unknown. Keep the pending flag for the next one. + return "", findErr + } + } + if err != nil && !errors.As(err, &rejected) { + // A timeout or 5xx leaves the outcome unknown: keep the pending flag + // for lookup-only recovery on the next attempt. + return "", err + } + if err != nil { + // The provider refused the request and the lookup found nothing, so + // nothing was created. Clear the create intent, otherwise every + // further attempt reads the pending flag as an unknown outcome and + // the run can never recover from an invalid image or resource + // request. + clearErr := e.updateRunErr(owner.ID, func(current *domain.Run) { + ec := ¤t.ExecutionContext + if e.ownsRun(*current) && isLiveStatus(current.Status) && ec.ExecutionResourcePending && ec.ExecutionResourceID == "" { + ec.ExecutionResourcePending = false + e.event(current, nodeID, "execution.failed", "OpenSandbox 拒绝了创建请求,未创建执行环境") + } + }) + if clearErr != nil { + return "", clearErr + } + } + } + if err != nil { + return "", err + } + bound := false + updateErr := e.updateRunErr(owner.ID, func(current *domain.Run) { + ec := ¤t.ExecutionContext + if e.ownsRun(*current) && isLiveStatus(current.Status) && (ec.ExecutionResourceID == "" || ec.ExecutionResourceID == sandbox.ID) { + ec.ExecutionResourceID = sandbox.ID + ec.ExecutionResourcePending = false + bound = true + e.event(current, nodeID, "execution.bound", "已绑定 OpenSandbox 执行环境") + } + }) + if updateErr != nil { + return "", updateErr + } + if !bound { + return "", errors.New("运行租约已变更,无法绑定 OpenSandbox") + } + return sandbox.ID, nil +} + +func (e *Engine) releaseOpenSandbox(run domain.Run) error { + ec := run.ExecutionContext + id := ec.ExecutionResourceID + if id == "" && !ec.ExecutionResourcePending { + return nil + } + client := e.openSandboxForRun(run) + if client == nil { + return errors.New("此运行绑定的 OpenSandbox 未配置") + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + if id == "" { + sandbox, err := client.Find(ctx, run.ID) + if errors.Is(err, opensandbox.ErrNotFound) { + return nil // any create accepted later still expires at the provider TTL + } + if err != nil { + return err + } + id = sandbox.ID + } + if err := client.Release(ctx, run.ID, id); err != nil { + return err + } + // Deregister the runner even when the run never recorded its ID: the run + // start path registers it under the derived name, and leaving the record + // online would keep listing a Runner whose sandbox is gone. + runnerID := ec.ExecutionRunnerID + if runnerID == "" { + runnerID = domain.OpenSandboxRunnerID(run.ID) + } + if err := e.repo.DeregisterRunner(runnerID, time.Now().UTC()); err != nil && !errors.Is(err, repo.ErrRunnerNotFound) { + return err + } + return nil +} diff --git a/internal/engine/opensandbox_delete_test.go b/internal/engine/opensandbox_delete_test.go new file mode 100644 index 000000000..73558dd78 --- /dev/null +++ b/internal/engine/opensandbox_delete_test.go @@ -0,0 +1,450 @@ +package engine + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "agentflow/internal/domain" + "agentflow/internal/opensandbox" + "agentflow/internal/repo" + "agentflow/internal/runtime" +) + +// TestDeleteRunKeepsRunWhenOpenSandboxReleaseFails covers the 3819f1c9 review: +// a provider DELETE failure must keep the run (its ExecutionResourceID is the +// only handle on the live sandbox) and surface a retryable error, and a later +// delete must release the sandbox and remove the run. +func TestDeleteRunKeepsRunWhenOpenSandboxReleaseFails(t *testing.T) { + const scope, runID, sandboxID = "del-test", "run-os-delete", "sbx-del-1" + sum := sha256.Sum256([]byte(scope + "/" + runID)) + binding := hex.EncodeToString(sum[:24]) + var deletes, failDeletes atomic.Int32 + failDeletes.Store(1) + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/sandboxes/"+sandboxID { + http.NotFound(w, r) + return + } + switch r.Method { + case http.MethodGet: + _ = json.NewEncoder(w).Encode(map[string]any{"id": sandboxID, "metadata": map[string]string{"loopforge-binding": binding}}) + case http.MethodDelete: + deletes.Add(1) + if failDeletes.Add(-1) >= 0 { + http.Error(w, "provider down", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusNoContent) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + })) + t.Cleanup(provider.Close) + + store, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + client, err := opensandbox.New(opensandbox.Config{ + Endpoint: provider.URL, APIKey: "opensandbox-test", RunnerURL: "https://loopforge.example.test", + RunnerImage: "runner:test", Scope: scope, RunnerSigningKey: strings.Repeat("testing", 5), + }, provider.Client()) + if err != nil { + t.Fatal(err) + } + eng := New(store, runtime.NewManagerWithLimit(t.TempDir(), 1)) + if err := eng.ConfigureOpenSandbox(DefaultOpenSandboxBackend, client, []string{"default"}); err != nil { + t.Fatal(err) + } + wf := domain.WorkflowDefinition{ID: "wf-os-delete", Name: "wf", ProjectID: "default", SandboxProfileID: "test-native"} + run := domain.Run{ + ID: runID, Status: "failed", WorkflowID: wf.ID, WorkflowSnapshot: wf, + ExecutionContext: domain.TelemetryContext{ + ProjectID: "default", ExecutionPool: domain.ExecutionPoolOpenSandbox, + ExecutionResourceID: sandboxID, ExecutionRunnerID: domain.OpenSandboxRunnerID(runID), + }, + Nodes: map[string]*domain.NodeRun{}, + } + if err := store.PutRun(run); err != nil { + t.Fatal(err) + } + + err = eng.DeleteRun(runID) + if !errors.Is(err, ErrExecutionResourceRelease) { + t.Fatalf("DeleteRun with a failing provider = %v, want ErrExecutionResourceRelease", err) + } + if !strings.Contains(err.Error(), "HTTP 500") || !strings.Contains(err.Error(), "重试") { + t.Fatalf("error %q should carry the provider failure and a retry hint", err) + } + kept, ok := store.RunState(runID) + if !ok { + t.Fatal("run was deleted although its sandbox was not released") + } + if kept.ExecutionContext.ExecutionResourceID != sandboxID { + t.Fatalf("sandbox handle lost after failed release: %+v", kept.ExecutionContext) + } + + if err := eng.DeleteRun(runID); err != nil { + t.Fatalf("retried DeleteRun after the provider recovered = %v", err) + } + if _, ok := store.RunState(runID); ok { + t.Fatal("retried delete did not remove the run") + } + if got := deletes.Load(); got != 2 { + t.Fatalf("provider DELETE calls = %d, want 2 (failed + retried)", got) + } +} + +// A provider that answers a create with a definitive 4xx created nothing. The +// create intent must be cleared, so a retry provisions a sandbox instead of +// reading the pending flag as an unknown outcome forever. +func TestOpenSandboxCreateRejectionClearsPendingIntent(t *testing.T) { + const scope, runID = "reject-test", "run-os-reject" + var items atomic.Int32 + var creates atomic.Int32 + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/v1/sandboxes" && r.Method == http.MethodGet: + _ = json.NewEncoder(w).Encode(map[string]any{"items": []any{}, "pagination": map[string]any{"hasNextPage": false, "totalItems": items.Load()}}) + case r.URL.Path == "/v1/sandboxes" && r.Method == http.MethodPost: + if creates.Add(1) == 1 { + http.Error(w, "invalid image", http.StatusBadRequest) + return + } + items.Store(1) + _ = json.NewEncoder(w).Encode(map[string]any{"id": "sbx-reject-ok", "metadata": map[string]string{}}) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(provider.Close) + store, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + client, err := opensandbox.New(opensandbox.Config{ + Endpoint: provider.URL, APIKey: "opensandbox-test", RunnerURL: "https://loopforge.example.test", + RunnerImage: "runner:test", Scope: scope, RunnerSigningKey: strings.Repeat("testing", 5), + }, provider.Client()) + if err != nil { + t.Fatal(err) + } + eng := New(store, runtime.NewManagerWithLimit(t.TempDir(), 1)) + if err := eng.ConfigureOpenSandbox(DefaultOpenSandboxBackend, client, []string{"reject-project"}); err != nil { + t.Fatal(err) + } + wf := domain.WorkflowDefinition{ID: "wf-os-reject", Name: "wf", ProjectID: "reject-project", SandboxProfileID: "test-native"} + run := domain.Run{ + ID: runID, Status: "running", WorkflowID: wf.ID, WorkflowSnapshot: wf, OwnerInstanceID: eng.instanceID, + Generation: 1, LeaseUntil: time.Now().UTC().Add(time.Minute), + ExecutionContext: domain.TelemetryContext{ + ProjectID: "reject-project", ExecutionPool: domain.ExecutionPoolOpenSandbox, + ExecutionProviderID: DefaultOpenSandboxBackend, ExecutionRunnerID: domain.OpenSandboxRunnerID(runID), + }, + Nodes: map[string]*domain.NodeRun{}, + } + if err := store.PutRun(run); err != nil { + t.Fatal(err) + } + owner, _ := store.RunState(runID) + if _, err := eng.provisionOpenSandbox(context.Background(), client, owner, "n1"); err == nil { + t.Fatal("a definitive create rejection must fail the attempt") + } + after, _ := store.RunState(runID) + if after.ExecutionContext.ExecutionResourcePending { + t.Fatal("a rejected create left the pending flag set; the run can never provision again") + } + if after.ExecutionContext.ExecutionResourceID != "" { + t.Fatalf("a rejected create bound a sandbox: %+v", after.ExecutionContext) + } + owner, _ = store.RunState(runID) + id, err := eng.provisionOpenSandbox(context.Background(), client, owner, "n1") + if err != nil || id != "sbx-reject-ok" { + t.Fatalf("retry after a rejected create = %q, %v; want the created sandbox", id, err) + } + if creates.Load() != 2 { + t.Fatalf("provider create calls = %d, want 2 (rejected + retried)", creates.Load()) + } +} + +// A run whose runner registration is already gone must still delete once the +// sandbox is released, instead of failing the whole delete with a 503. +func TestDeleteRunWithoutRunnerRegistrationReleasesSandbox(t *testing.T) { + const scope, runID, sandboxID = "no-runner", "run-os-norunner", "sbx-norunner" + sum := sha256.Sum256([]byte(scope + "/" + runID)) + binding := hex.EncodeToString(sum[:24]) + var deletes atomic.Int32 + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/sandboxes/"+sandboxID { + http.NotFound(w, r) + return + } + switch r.Method { + case http.MethodGet: + _ = json.NewEncoder(w).Encode(map[string]any{"id": sandboxID, "metadata": map[string]string{"loopforge-binding": binding}}) + case http.MethodDelete: + deletes.Add(1) + w.WriteHeader(http.StatusNoContent) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + })) + t.Cleanup(provider.Close) + store, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + client, err := opensandbox.New(opensandbox.Config{ + Endpoint: provider.URL, APIKey: "opensandbox-test", RunnerURL: "https://loopforge.example.test", + RunnerImage: "runner:test", Scope: scope, RunnerSigningKey: strings.Repeat("testing", 5), + }, provider.Client()) + if err != nil { + t.Fatal(err) + } + eng := New(store, runtime.NewManagerWithLimit(t.TempDir(), 1)) + if err := eng.ConfigureOpenSandbox(DefaultOpenSandboxBackend, client, []string{"norunner"}); err != nil { + t.Fatal(err) + } + wf := domain.WorkflowDefinition{ID: "wf-os-norunner", Name: "wf", ProjectID: "norunner", SandboxProfileID: "test-native"} + run := domain.Run{ + ID: runID, Status: "failed", WorkflowID: wf.ID, WorkflowSnapshot: wf, + ExecutionContext: domain.TelemetryContext{ + ProjectID: "norunner", ExecutionPool: domain.ExecutionPoolOpenSandbox, + ExecutionResourceID: sandboxID, + }, + Nodes: map[string]*domain.NodeRun{}, + } + if err := store.PutRun(run); err != nil { + t.Fatal(err) + } + if err := eng.DeleteRun(runID); err != nil { + t.Fatalf("DeleteRun with no runner registration = %v, want success", err) + } + if _, ok := store.RunState(runID); ok { + t.Fatal("run was kept although the sandbox was released") + } + if deletes.Load() != 1 { + t.Fatalf("provider DELETE calls = %d, want 1", deletes.Load()) + } +} + +// A provider can answer a duplicate create with 409 while the sandbox exists. +// The attempt must adopt the existing sandbox instead of losing the only +// handle, so a delete can still release it. +func TestOpenSandboxCreateRejectionAdoptsExistingSandbox(t *testing.T) { + const scope, runID, sandboxID = "adopt-test", "run-os-adopt", "sbx-adopt-1" + sum := sha256.Sum256([]byte(scope + "/" + runID)) + binding := hex.EncodeToString(sum[:24]) + var creates, finds atomic.Int32 + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/v1/sandboxes" && r.Method == http.MethodGet: + items := []any{} + // The first lookup (before the create) sees nothing; the lookup + // after the 409 sees the sandbox the provider had already made. + if finds.Add(1) > 1 { + items = append(items, map[string]any{"id": sandboxID, "metadata": map[string]string{"loopforge-binding": binding}}) + } + _ = json.NewEncoder(w).Encode(map[string]any{"items": items, "pagination": map[string]any{"hasNextPage": false, "totalItems": len(items)}}) + case r.URL.Path == "/v1/sandboxes" && r.Method == http.MethodPost: + creates.Add(1) + http.Error(w, "sandbox already exists", http.StatusConflict) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(provider.Close) + store, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + client, err := opensandbox.New(opensandbox.Config{ + Endpoint: provider.URL, APIKey: "opensandbox-test", RunnerURL: "https://loopforge.example.test", + RunnerImage: "runner:test", Scope: scope, RunnerSigningKey: strings.Repeat("testing", 5), + }, provider.Client()) + if err != nil { + t.Fatal(err) + } + eng := New(store, runtime.NewManagerWithLimit(t.TempDir(), 1)) + if err := eng.ConfigureOpenSandbox(DefaultOpenSandboxBackend, client, []string{"adopt-project"}); err != nil { + t.Fatal(err) + } + wf := domain.WorkflowDefinition{ID: "wf-os-adopt", Name: "wf", ProjectID: "adopt-project", SandboxProfileID: "test-native"} + run := domain.Run{ + ID: runID, Status: "running", WorkflowID: wf.ID, WorkflowSnapshot: wf, OwnerInstanceID: eng.instanceID, + Generation: 1, LeaseUntil: time.Now().UTC().Add(time.Minute), + ExecutionContext: domain.TelemetryContext{ + ProjectID: "adopt-project", ExecutionPool: domain.ExecutionPoolOpenSandbox, + ExecutionProviderID: DefaultOpenSandboxBackend, ExecutionRunnerID: domain.OpenSandboxRunnerID(runID), + }, + Nodes: map[string]*domain.NodeRun{}, + } + if err := store.PutRun(run); err != nil { + t.Fatal(err) + } + owner, _ := store.RunState(runID) + id, err := eng.provisionOpenSandbox(context.Background(), client, owner, "n1") + if err != nil || id != sandboxID { + t.Fatalf("provision after a 409 with an existing sandbox = %q, %v; want %q", id, err, sandboxID) + } + after, _ := store.RunState(runID) + if after.ExecutionContext.ExecutionResourceID != sandboxID || after.ExecutionContext.ExecutionResourcePending { + t.Fatalf("existing sandbox not bound: %+v", after.ExecutionContext) + } + if creates.Load() != 1 { + t.Fatalf("provider create calls = %d, want 1", creates.Load()) + } +} + +// 408, 429 and 5xx leave the create outcome unknown, so the pending flag must +// stay for lookup-only recovery instead of letting a retry POST again. +func TestOpenSandboxCreateUncertainOutcomeKeepsPending(t *testing.T) { + for _, status := range []int{http.StatusInternalServerError, http.StatusRequestTimeout, http.StatusTooManyRequests} { + t.Run(http.StatusText(status), func(t *testing.T) { + const scope, runID = "uncertain-test", "run-os-uncertain" + var creates atomic.Int32 + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/v1/sandboxes" && r.Method == http.MethodGet: + _ = json.NewEncoder(w).Encode(map[string]any{"items": []any{}, "pagination": map[string]any{"hasNextPage": false, "totalItems": 0}}) + case r.URL.Path == "/v1/sandboxes" && r.Method == http.MethodPost: + creates.Add(1) + http.Error(w, "provider busy", status) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(provider.Close) + store, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + client, err := opensandbox.New(opensandbox.Config{ + Endpoint: provider.URL, APIKey: "opensandbox-test", RunnerURL: "https://loopforge.example.test", + RunnerImage: "runner:test", Scope: scope, RunnerSigningKey: strings.Repeat("testing", 5), + }, provider.Client()) + if err != nil { + t.Fatal(err) + } + eng := New(store, runtime.NewManagerWithLimit(t.TempDir(), 1)) + if err := eng.ConfigureOpenSandbox(DefaultOpenSandboxBackend, client, []string{"uncertain-project"}); err != nil { + t.Fatal(err) + } + wf := domain.WorkflowDefinition{ID: "wf-os-uncertain", Name: "wf", ProjectID: "uncertain-project", SandboxProfileID: "test-native"} + run := domain.Run{ + ID: runID, Status: "running", WorkflowID: wf.ID, WorkflowSnapshot: wf, OwnerInstanceID: eng.instanceID, + Generation: 1, LeaseUntil: time.Now().UTC().Add(time.Minute), + ExecutionContext: domain.TelemetryContext{ + ProjectID: "uncertain-project", ExecutionPool: domain.ExecutionPoolOpenSandbox, + ExecutionProviderID: DefaultOpenSandboxBackend, ExecutionRunnerID: domain.OpenSandboxRunnerID(runID), + }, + Nodes: map[string]*domain.NodeRun{}, + } + if err := store.PutRun(run); err != nil { + t.Fatal(err) + } + owner, _ := store.RunState(runID) + if _, err := eng.provisionOpenSandbox(context.Background(), client, owner, "n1"); err == nil { + t.Fatal("an uncertain create must fail the attempt") + } + after, _ := store.RunState(runID) + if !after.ExecutionContext.ExecutionResourcePending { + t.Fatalf("HTTP %d cleared the pending flag; a retry would POST again instead of looking up the outcome", status) + } + owner, _ = store.RunState(runID) + if _, err := eng.provisionOpenSandbox(context.Background(), client, owner, "n1"); err == nil { + t.Fatal("a second attempt while the outcome is unknown must not provision") + } + if got := creates.Load(); got != 1 { + t.Fatalf("provider create calls = %d, want 1 (the unknown outcome must not be re-posted)", got) + } + }) + } +} + +// A definitive 4xx is not retried: the identical request would be refused +// again, and the engine already cleared the create intent for the next run. +func TestShouldRetryFailedAttemptSkipsRejectedCreate(t *testing.T) { + node := domain.WorkflowNode{ID: "n1", MaxAttempts: 3} + rejected := fmt.Errorf("provision: %w", &opensandbox.RejectedError{Method: http.MethodPost, Status: http.StatusBadRequest}) + if shouldRetryFailedAttempt(node, 1, rejected) { + t.Fatal("a rejected OpenSandbox create was scheduled for another attempt") + } + uncertain := errors.New("OpenSandbox POST: HTTP 503") + if !shouldRetryFailedAttempt(node, 1, uncertain) { + t.Fatal("an unknown create outcome must stay retryable") + } +} + +// The run start path registers the sandbox Runner under a derived ID. A run +// that never recorded ExecutionRunnerID must still deregister it on delete, +// otherwise a Runner with no sandbox stays listed as online. +func TestDeleteRunDeregistersDerivedOpenSandboxRunner(t *testing.T) { + const scope, runID, sandboxID = "derived-runner", "run-os-derived", "sbx-derived" + sum := sha256.Sum256([]byte(scope + "/" + runID)) + binding := hex.EncodeToString(sum[:24]) + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/v1/sandboxes/"+sandboxID && r.Method == http.MethodGet: + _ = json.NewEncoder(w).Encode(map[string]any{"id": sandboxID, "metadata": map[string]string{"loopforge-binding": binding}}) + case r.URL.Path == "/v1/sandboxes/"+sandboxID && r.Method == http.MethodDelete: + w.WriteHeader(http.StatusNoContent) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(provider.Close) + store, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + derived := domain.OpenSandboxRunnerID(runID) + if err := store.PutRunner(domain.Runner{ID: derived, OwnerUserID: 1, Name: "sandbox runner", Status: domain.RunnerStatusOnline}); err != nil { + t.Fatal(err) + } + client, err := opensandbox.New(opensandbox.Config{ + Endpoint: provider.URL, APIKey: "opensandbox-test", RunnerURL: "https://loopforge.example.test", + RunnerImage: "runner:test", Scope: scope, RunnerSigningKey: strings.Repeat("testing", 5), + }, provider.Client()) + if err != nil { + t.Fatal(err) + } + eng := New(store, runtime.NewManagerWithLimit(t.TempDir(), 1)) + if err := eng.ConfigureOpenSandbox(DefaultOpenSandboxBackend, client, []string{"derived-project"}); err != nil { + t.Fatal(err) + } + wf := domain.WorkflowDefinition{ID: "wf-os-derived", Name: "wf", ProjectID: "derived-project", SandboxProfileID: "test-native"} + run := domain.Run{ + ID: runID, Status: "failed", WorkflowID: wf.ID, WorkflowSnapshot: wf, + ExecutionContext: domain.TelemetryContext{ + ProjectID: "derived-project", ExecutionPool: domain.ExecutionPoolOpenSandbox, + ExecutionResourceID: sandboxID, + }, + Nodes: map[string]*domain.NodeRun{}, + } + if err := store.PutRun(run); err != nil { + t.Fatal(err) + } + if err := eng.DeleteRun(runID); err != nil { + t.Fatalf("DeleteRun = %v, want success", err) + } + if _, ok := store.Runner(derived); ok { + t.Fatalf("runner %s still registered after its sandbox was released", derived) + } +} diff --git a/internal/engine/opensandbox_test.go b/internal/engine/opensandbox_test.go new file mode 100644 index 000000000..3563a6ef4 --- /dev/null +++ b/internal/engine/opensandbox_test.go @@ -0,0 +1,45 @@ +package engine + +import ( + "strings" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/opensandbox" +) + +func TestOpenSandboxBackendBinding(t *testing.T) { + makeClient := func(scope string) *opensandbox.Client { + t.Helper() + client, err := opensandbox.New(opensandbox.Config{ + Endpoint: "http://127.0.0.1:1337", APIKey: "opensandbox-test", RunnerURL: "https://loopforge.example.test", + RunnerImage: "runner:test", Scope: scope, RunnerSigningKey: strings.Repeat("testing", 5), + }, nil) + if err != nil { + t.Fatal(err) + } + return client + } + e := &Engine{} + docker, kube := makeClient("docker-test"), makeClient("kube-test") + if err := e.ConfigureOpenSandbox(DefaultOpenSandboxBackend, docker, []string{"docker-project"}); err != nil { + t.Fatal(err) + } + if err := e.ConfigureOpenSandbox("kube", kube, []string{"kube-project"}); err != nil { + t.Fatal(err) + } + if err := e.ConfigureOpenSandbox("duplicate", kube, []string{"docker-project"}); err == nil { + t.Fatal("a project cannot route to multiple backends") + } + if e.openSandboxProjects["docker-project"] != DefaultOpenSandboxBackend || e.openSandboxProjects["kube-project"] != "kube" { + t.Fatal("backend registration changed existing project bindings") + } + run := domain.Run{ExecutionContext: domain.TelemetryContext{ExecutionProviderID: "kube", ProjectID: "docker-project"}} + if e.openSandboxForRun(run) != kube { + t.Fatal("a run followed the current project instead of its pinned backend") + } + run.ExecutionContext.ExecutionProviderID = "" + if e.openSandboxForRun(run) != docker { + t.Fatal("a run without a provider ID did not use the original default backend") + } +} diff --git a/internal/engine/run_start.go b/internal/engine/run_start.go index 9198b444b..a8f0727bd 100644 --- a/internal/engine/run_start.go +++ b/internal/engine/run_start.go @@ -153,7 +153,14 @@ func (e *Engine) startWorkflowDefinitionSeeded(ctx context.Context, wf domain.Wo } var workspaceSandboxID string var parent domain.Run - if executionContext.ParentRunID != "" { + if executionContext.ParentRunID == "" { + executionContext.ExecutionProviderID = "" + executionContext.ExecutionResourceID = "" + executionContext.ExecutionResourcePending = false + if executionContext.ExecutionPool == domain.ExecutionPoolOpenSandbox { + executionContext.ExecutionPool = "" + } + } else { var ok bool parent, ok = e.repo.RunState(executionContext.ParentRunID) if !ok { @@ -162,11 +169,12 @@ func (e *Engine) startWorkflowDefinitionSeeded(ctx context.Context, wf domain.Wo if wf.AutoSelectSandbox { workspaceSandboxID = parent.WorkflowSnapshot.SandboxProfileID } - if target := parent.ExecutionContext; target.ExecutionPool == domain.ExecutionPoolProjectAuto { + if target := parent.ExecutionContext; target.ExecutionPool == domain.ExecutionPoolProjectAuto || isOpenSandboxRun(parent) { executionContext.ExecutionPool = target.ExecutionPool executionContext.ExecutionMode = target.ExecutionMode executionContext.ExecutionRunnerID = target.ExecutionRunnerID executionContext.RunnerWorkspaceLayout = target.RunnerWorkspaceLayout + executionContext.ExecutionProviderID = target.ExecutionProviderID } } if !workspace && executionContext.ParentRunID == "" && executionContext.WorkspaceRunID != "" { @@ -206,6 +214,8 @@ func (e *Engine) startWorkflowDefinitionSeeded(ctx context.Context, wf domain.Wo switch { case workspace: profile, err = e.repo.ConversationSandbox(executionContext.ProjectID, wf.SandboxProfileID) + case isOpenSandboxRun(parent) && wf.AutoSelectSandbox: + profile, _, err = e.workspaceSandboxProfile(parent) case autoAssign: candidates, profile, sandboxSelection, err = e.prepareAutoAssign(ctx, wf, executionContext, repositories, input) case wf.AutoSelectSandbox: @@ -219,6 +229,23 @@ func (e *Engine) startWorkflowDefinitionSeeded(ctx context.Context, wf domain.Wo if err != nil { return domain.Run{}, err } + if backend := e.openSandboxProjects[executionContext.ProjectID]; backend != "" && + executionContext.ParentRunID == "" && !executionContext.ExecutionPinned && !workspace && + !autoAssign && !wf.AutoSelectSandbox && !executionContext.IsEvolutionReplay() && + (executionContext.ExecutionRunnerID == "" || executionContext.ExecutionPool == domain.ExecutionModeCloud) && + openSandboxSupportsProfile(profile) { + executionContext.ExecutionPool = domain.ExecutionPoolOpenSandbox + executionContext.ExecutionProviderID = backend + executionContext.ExecutionRunnerID = "" + executionContext.ExecutionMode = domain.ExecutionModeRunner + executionContext.RunnerWorkspaceLayout = domain.RunnerWorkspaceLayoutShared + } + if executionContext.ExecutionPool == domain.ExecutionPoolOpenSandbox && !openSandboxSupportsProfile(profile) { + return domain.Run{}, fmt.Errorf("OpenSandbox 工作区需要使用 native 沙箱配置") + } + if domain.IsOpenSandboxRunner(executionContext.ExecutionRunnerID) && executionContext.ExecutionPool != domain.ExecutionPoolOpenSandbox { + return domain.Run{}, fmt.Errorf("OpenSandbox Runner 仅供关联工作区使用") + } sandbox, err := resolveSandbox(profile) if err != nil { return domain.Run{}, err @@ -257,6 +284,9 @@ func (e *Engine) startWorkflowDefinitionSeeded(ctx context.Context, wf domain.Wo } now := time.Now().UTC() id := fmt.Sprintf("run-%d", now.UnixNano()) + if executionContext.ParentRunID == "" && executionContext.ExecutionPool == domain.ExecutionPoolOpenSandbox { + executionContext.ExecutionRunnerID = domain.OpenSandboxRunnerID(id) + } var firstRepository domain.RepositoryContext if len(repositories) > 0 { firstRepository = repositories[0] diff --git a/internal/engine/runner_dispatch.go b/internal/engine/runner_dispatch.go index 6aa1482eb..86e75810e 100644 --- a/internal/engine/runner_dispatch.go +++ b/internal/engine/runner_dispatch.go @@ -179,6 +179,11 @@ func (e *Engine) runnerSandboxSpec(run domain.Run) (*domain.RunnerSandboxSpec, e return nil, err } spec := resolvedSandboxSnapshot(profile, resources) + if isOpenSandboxRun(run) && runnerID == domain.OpenSandboxRunnerID(workspaceRunID(run)) { + // The assigned container is the isolation boundary. Only its dedicated + // Runner receives the process-level driver with the profile environment. + spec.Profile.Driver = domain.SandboxDriverLocal + } var codexLoginRelay bool if profile.Driver == domain.SandboxDriverDocker && runnerID != "" { runner, ok := e.repo.Runner(runnerID) @@ -573,10 +578,23 @@ func (e *Engine) defaultExecutionRunner(run domain.Run) string { // same validation to cover a disconnect between this check and execution. func (e *Engine) validateExecutionReconnect(run domain.Run, nodeID string) error { runnerID := e.defaultExecutionRunner(run) - if runnerID == "" || isPoolRun(run) { + if runnerID == "" || isPoolRun(run) || isOpenSandboxRun(run) { // A pool run is rebound to another pool runner when its node starts. return nil } + frozen := run.WorkflowSnapshot + for _, node := range frozen.Nodes { + if node.ID != nodeID { + continue + } + if agent, ok := workflowAgent(e.repo, frozen, node.AgentID); ok { + ex, err := workflowNodeExecutor(e.repo, frozen, node, agent) + if err == nil && domain.IsManagedAgentExecutor(ex.Kind) && !domain.UsesPersonalAgentRunner(ex.Kind, agent.ExternalAgentTarget) { + return nil + } + } + break + } if run.ExecutionContext.ExecutionPool == domain.ExecutionPoolProjectAuto { if err := e.validateAutoAssignBinding(run); err != nil { return err @@ -621,6 +639,12 @@ func (e *Engine) validateExecutionReconnect(run domain.Run, nodeID string) error // explicit deletion also calls it for failed/cancelled runs. The deterministic // task ID makes those paths idempotent without resetting active/completed work. func (e *Engine) queueRunnerRunCleanup(run domain.Run) error { + if isOpenSandboxRun(run) && !sharesWorkspace(run) { + if err := e.releaseOpenSandbox(run); err != nil { + return fmt.Errorf("%w:%v", ErrExecutionResourceRelease, err) + } + return nil + } runnerID := e.defaultExecutionRunner(run) if runnerID == "" { return nil diff --git a/internal/engine/sop_executors.go b/internal/engine/sop_executors.go index e37ae74ea..9dc834b6c 100644 --- a/internal/engine/sop_executors.go +++ b/internal/engine/sop_executors.go @@ -86,7 +86,7 @@ func (e *Engine) ExecutorCredentials(userID int64, projectID string) func(kind s } func sopRunnerAuthMode(ec domain.TelemetryContext, runner domain.Runner, provider string) string { - if ec.ExecutionPool == domain.ExecutionPoolProjectAuto && runner.OwnerUserID == 0 { + if (ec.ExecutionPool == domain.ExecutionPoolProjectAuto || ec.ExecutionPool == domain.ExecutionPoolOpenSandbox) && runner.OwnerUserID == 0 { return domain.RuntimeAuthPersonal } // A conversation allocated to a platform runner keeps using the @@ -236,7 +236,7 @@ func (e *Engine) planSOPExecutors(wf domain.WorkflowDefinition, ec domain.Teleme defaults := access.defaults() selected := make(map[string]domain.AssistantDefaults) requirements := make([]SOPExecutorRequirement, 0) - seen := make(map[string]bool) + seen := make(map[string]int) for _, node := range wf.Nodes { if node.Type != "agent" { continue @@ -263,10 +263,20 @@ func (e *Engine) planSOPExecutors(wf domain.WorkflowDefinition, ec domain.Teleme return nil, nil, err } } - if preflight && !seen[ex.Kind] { - seen[ex.Kind] = true + if preflight { + configured := ex.Kind != "" && access.configured(ex.Kind) + if domain.UsesPersonalAgentRunner(ex.Kind, role.ExternalAgentTarget) { + configured = e.personalAgentRunner(ec) + } else if domain.IsManagedAgentExecutor(ex.Kind) { + configured = e.managedAgentClient(ex.Kind, ec) != nil + } + if i, exists := seen[ex.Kind]; exists { + requirements[i].Configured = requirements[i].Configured && configured + continue + } + seen[ex.Kind] = len(requirements) requirements = append(requirements, SOPExecutorRequirement{ - Kind: ex.Kind, Name: ex.Name, Configured: ex.Kind != "" && access.configured(ex.Kind), + Kind: ex.Kind, Name: ex.Name, Configured: configured, }) } } diff --git a/internal/engine/sop_idle_reclaim_test.go b/internal/engine/sop_idle_reclaim_test.go index 59065c36e..3103358f5 100644 --- a/internal/engine/sop_idle_reclaim_test.go +++ b/internal/engine/sop_idle_reclaim_test.go @@ -634,7 +634,7 @@ func TestSOPIdleReclaimPromotedRunnerRestoresBeforeDispatch(t *testing.T) { if err != nil { status, message = domain.RunnerTaskFailed, err.Error() } - if err := s.CompleteRunnerTask(task.ID, runner.ID, status, nil, string(output), message, nil, nil, time.Now().UTC()); err != nil { + if err := s.CompleteRunnerTask(task.ID, runner.ID, status, nil, string(output), message, "", nil, nil, time.Now().UTC()); err != nil { t.Error(err) } } diff --git a/internal/engine/workspace_cleanup.go b/internal/engine/workspace_cleanup.go index d309311ba..a206518fd 100644 --- a/internal/engine/workspace_cleanup.go +++ b/internal/engine/workspace_cleanup.go @@ -4,6 +4,7 @@ import ( "agentflow/internal/domain" "agentflow/internal/repo" "context" + "errors" "fmt" "log" "os" @@ -425,6 +426,9 @@ func (e *Engine) DeleteRun(runID string) error { } } if err := e.queueRunnerRunCleanup(run); err != nil { + if errors.Is(err, ErrExecutionResourceRelease) { + return fmt.Errorf("%w;运行记录已保留,请稍后重试删除", err) + } return fmt.Errorf("queue runner workspace cleanup: %w", err) } if err := e.releaseRunEnvironment(runID, true); err != nil { diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go index 2150cff4d..de09c6a04 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -422,6 +422,9 @@ func validateCatalogAgentExecutor(agent *domain.AgentDefinition) error { agent.ExecutorID = strings.TrimSpace(agent.ExecutorID) agent.Model = strings.TrimSpace(agent.Model) agent.Effort = strings.TrimSpace(agent.Effort) + if err := agent.ValidateManagedExecutor(agent.ExecutorID); err != nil { + return err + } if agent.ExecutorID == "" { if (agent.Model == "" || agent.Model == "default") && agent.Effort == "" { agent.Model = "" @@ -1074,6 +1077,10 @@ func (h *catalogHandlers) workflows(c *gin.Context) { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return } + if err := validateWorkflowManagedKnowledge(h.repo, v); err != nil { + c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) + return + } if err := domain.ValidateWorkflowMetricStages(v); err != nil { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return @@ -1241,6 +1248,13 @@ func (h *catalogHandlers) workflow(c *gin.Context) { if !h.validateWorkflowProjectCredentials(c, restored) { return } + // Restoring writes the old node graph back as-is; a revision saved + // before the role switched to a managed Agent would otherwise bring + // back a knowledge binding the save path now refuses. + if err := validateWorkflowManagedKnowledge(h.repo, restored); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } if v.Shared && !restored.Shared && h.sharedScheduleReferences("sop", id) { c.JSON(http.StatusConflict, map[string]string{"error": "该 LOOP 仍被共享任务引用,不能取消共享"}) return @@ -1360,6 +1374,18 @@ func (h *catalogHandlers) workflow(c *gin.Context) { if !h.requireProjectWriter(c, req.ProjectID, taken.ProjectID) { return } + // A clone copies every node binding verbatim, so a source saved before + // its role became a managed Agent (or a template whose packaged role + // is managed) must not mint a new LOOP the save path would refuse. + // Checked before adoption so a rejected clone creates no roles. + probe := v + if !v.Generic { + probe.ProjectID = req.ProjectID // roles resolve in the copy's project + } + if err := validateWorkflowManagedKnowledge(h.repo, probe); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } if req.AutoSelectSandbox { v.AutoSelectSandbox, v.SandboxProfileID = true, "" } else if req.SandboxProfileID != "" { diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.go index 691407136..411849f5c 100644 --- a/internal/httpapi/executor_models.go +++ b/internal/httpapi/executor_models.go @@ -241,6 +241,11 @@ func (h *catalogHandlers) executorModels(c *gin.Context) { hasCredential := engine.ExecutorCredentials(h.repo, user.ID, projectID) if h.engine != nil { hasCredential = h.engine.ExecutorCredentials(user.ID, projectID) + for _, provider := range []string{domain.WMAExecutorID, domain.A2AExecutorID} { + if h.engine.ManagedAgentAvailable(projectID, user.ID, provider) { + catalogs[provider] = executorModelCatalog{Configured: true} + } + } } for _, engine := range append([]string{assistantEngineCodeBuddy}, assistantCLIEngines()...) { id := engine diff --git a/internal/httpapi/gin_helpers.go b/internal/httpapi/gin_helpers.go index 29b7e23e3..edc533814 100644 --- a/internal/httpapi/gin_helpers.go +++ b/internal/httpapi/gin_helpers.go @@ -27,7 +27,8 @@ func (e HTTPError) Error() string { return e.Message } // respond 渲染操作结果,是唯一的统一响应入口: // - err == nil → 200 {"ok": true}; // - 否则渲染统一 JSON 错误形态,状态码取 HTTPError 自带值, -// apperr.Error 按 Kind 映射,ErrExecutionDisabled → 403,其余 → 400。 +// apperr.Error 按 Kind 映射,ErrExecutionDisabled → 403, +// ErrExecutionResourceRelease → 503(可重试),其余 → 400。 func respond(c *gin.Context, err error) { if err == nil { c.JSON(http.StatusOK, map[string]bool{"ok": true}) @@ -50,6 +51,13 @@ func respond(c *gin.Context, err error) { c.JSON(http.StatusForbidden, map[string]string{"error": err.Error()}) return } + if errors.Is(err, engine.ErrExecutionResourceRelease) { + // The provider did not release the sandbox and the run was kept so + // the delete can be repeated; tell the client this is transient. + c.Header("Retry-After", "30") + c.JSON(http.StatusServiceUnavailable, map[string]any{"error": err.Error(), "retryable": true}) + return + } c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) } diff --git a/internal/httpapi/respond_release_test.go b/internal/httpapi/respond_release_test.go new file mode 100644 index 000000000..d97cc051e --- /dev/null +++ b/internal/httpapi/respond_release_test.go @@ -0,0 +1,38 @@ +package httpapi + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "agentflow/internal/engine" + + "github.com/gin-gonic/gin" +) + +// A failed OpenSandbox release keeps the run so the delete can be repeated; +// the response must say so (503 + Retry-After) instead of a 400 that reads as +// a permanent request error. +func TestRespondMapsExecutionResourceReleaseToRetryable503(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + err := fmt.Errorf("%w;运行记录已保留,请稍后重试删除", fmt.Errorf("%w:OpenSandbox DELETE: HTTP 500", engine.ErrExecutionResourceRelease)) + respond(c, err) + if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") == "" { + t.Fatalf("release failure = %d Retry-After=%q, want 503 with Retry-After", rec.Code, rec.Header().Get("Retry-After")) + } + var body map[string]any + if json.Unmarshal(rec.Body.Bytes(), &body) != nil || body["retryable"] != true || body["error"] != err.Error() { + t.Fatalf("body = %s", rec.Body.String()) + } + + rec = httptest.NewRecorder() + c, _ = gin.CreateTestContext(rec) + respond(c, errors.New("run x is running: cancel it before deleting")) + if rec.Code != http.StatusBadRequest { + t.Fatalf("ordinary delete refusal = %d, want 400", rec.Code) + } +} diff --git a/internal/httpapi/runners.go b/internal/httpapi/runners.go index 490bf36eb..895733d44 100644 --- a/internal/httpapi/runners.go +++ b/internal/httpapi/runners.go @@ -19,6 +19,7 @@ import ( "agentflow/internal/domain" "agentflow/internal/gitwork" + "agentflow/internal/opensandbox" "agentflow/internal/repo" "github.com/gin-gonic/gin" @@ -794,7 +795,14 @@ func (h *runnersHandlers) runnerRegister(c *gin.Context) { provided = raw } } - owner, authorized := h.resolveRunnerRegistrant(c.Request) + var owner int64 + var managedID string + var authorized bool + if strings.HasPrefix(provided, opensandbox.BootstrapPrefix) { + managedID, authorized = h.engine.OpenSandboxRegistrant(provided) + } else { + owner, authorized = h.resolveRunnerRegistrant(c.Request) + } if !authorized { // No credential at all and no shared bootstrap token configured: // registration is closed. A presented-but-invalid credential (for @@ -826,7 +834,17 @@ func (h *runnersHandlers) runnerRegister(c *gin.Context) { if !decode(c, &input) { return } - if input.MaxConcurrency < 1 { + requestedID := strings.TrimSpace(input.RunnerID) + if (managedID != "" && requestedID != "" && requestedID != managedID) || + (managedID == "" && domain.IsOpenSandboxRunner(requestedID)) { + c.JSON(http.StatusForbidden, map[string]string{"error": "runner identity is reserved for its OpenSandbox workspace"}) + return + } + if managedID != "" { + requestedID = managedID + input.MaxConcurrency = 1 + input.Labels = nil + } else if input.MaxConcurrency < 1 { input.MaxConcurrency = 1 } if input.MaxConcurrency > 32 { @@ -848,12 +866,14 @@ func (h *runnersHandlers) runnerRegister(c *gin.Context) { OwnerUserID: owner, LastSeenAt: &now, } - existing, found := h.repo.Runner(strings.TrimSpace(input.RunnerID)) + existing, found := h.repo.Runner(requestedID) renew := found && existing.OwnerUserID == owner if renew { runner.ID = existing.ID runner.CreatedAt = existing.CreatedAt runner.Runtimes = normalizeRunnerRuntimes(input.Runtimes, existing.Runtimes) + } else if managedID != "" { + runner.ID = managedID } else { runner.ID = "runner-" + randomID() } @@ -966,6 +986,10 @@ func (h *runnersHandlers) runnerTasksCollection(c *gin.Context) { if !decode(c, &input) { return } + if domain.IsOpenSandboxRunner(strings.TrimSpace(input.RunnerID)) { + c.JSON(http.StatusForbidden, gin.H{"error": "OpenSandbox Runner is reserved for its workspace"}) + return + } input.Provider = strings.TrimSpace(input.Provider) if input.Provider == "" { c.JSON(http.StatusBadRequest, map[string]string{"error": "provider 不能为空"}) @@ -1069,14 +1093,16 @@ func (h *runnersHandlers) runnerTaskClaim(c *gin.Context) { case profile.HasResourceLimits() && !input.SupportsDockerSandboxLimits: err = errors.New(domain.RunnerDockerSandboxLimitsUpgradeMessage) case task.RunID != "" && task.Action == "": - err = domain.ValidateFrozenSandbox(profile) + if profile.Driver != domain.SandboxDriverLocal || !domain.IsOpenSandboxRunner(runner.ID) || task.RunnerID != runner.ID { + err = domain.ValidateFrozenSandbox(profile) + } if err == nil { task.ProjectCredentialEnv, err = h.runnerTaskProjectCredentialEnv(c.Request.Context(), task, runner) } } if err != nil { // Finish the task before sending an unusable sandbox to the runner. - if finishErr := h.repo.CompleteRunnerTask(task.ID, runner.ID, domain.RunnerTaskFailed, nil, "", err.Error(), nil, nil, time.Now().UTC()); finishErr != nil { + if finishErr := h.repo.CompleteRunnerTask(task.ID, runner.ID, domain.RunnerTaskFailed, nil, "", err.Error(), "", nil, nil, time.Now().UTC()); finishErr != nil { return domain.RunnerTask{}, false, finishErr } if ctxErr := c.Request.Context().Err(); ctxErr != nil { @@ -1214,6 +1240,9 @@ func resolveRunnerTaskSandbox(task domain.RunnerTask, runnerOS string) domain.Ru // leased by. An untargeted, unleased task is visible to every runner because // any of them may claim it. func runnerMaySeeTask(runner domain.Runner, task domain.RunnerTask) bool { + if domain.IsOpenSandboxRunner(runner.ID) && task.RunnerID != runner.ID { + return false + } if task.LeaseOwner != "" { return task.LeaseOwner == runner.ID } @@ -1369,6 +1398,7 @@ func (h *runnersHandlers) runnerTaskComplete(c *gin.Context) { ExitCode *int `json:"exitCode"` Result string `json:"result"` Error string `json:"error"` + Code string `json:"code"` Artifacts map[string]string `json:"artifacts"` Outputs *domain.RunnerTaskOutputs `json:"outputs"` } @@ -1396,7 +1426,7 @@ func (h *runnersHandlers) runnerTaskComplete(c *gin.Context) { if input.Outputs != nil && (len(input.Outputs.FileBlobs) != 0 || len(input.Outputs.FileErrors) != 0) && !h.validateRunnerOutputTransfer(c, runner.ID, input.Outputs) { return } - if err := h.repo.CompleteRunnerTask(c.Param("id"), runner.ID, input.Status, input.ExitCode, input.Result, input.Error, input.Artifacts, input.Outputs, time.Now().UTC()); err != nil { + if err := h.repo.CompleteRunnerTask(c.Param("id"), runner.ID, input.Status, input.ExitCode, input.Result, input.Error, input.Code, input.Artifacts, input.Outputs, time.Now().UTC()); err != nil { if err == repo.ErrRunnerTaskLeaseLost { c.JSON(http.StatusConflict, map[string]string{"error": "task lease lost"}) return diff --git a/internal/httpapi/runs.go b/internal/httpapi/runs.go index 998e2020c..66311b065 100644 --- a/internal/httpapi/runs.go +++ b/internal/httpapi/runs.go @@ -154,6 +154,12 @@ func (h *runsHandlers) runs(c *gin.Context) { copied := make([]domain.KnowledgeRef, len(*req.KnowledgeRefs)) copy(copied, *req.KnowledgeRefs) runKnowledgeRefs = &copied + if workflow, ok := h.repo.Workflow(strings.TrimSpace(req.WorkflowID)); ok { + if convErr := validateRunManagedKnowledge(h.repo, workflow, copied); convErr != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": convErr.Error()}) + return + } + } } var repositories []domain.RepositoryContext if wf, ok := h.repo.Workflow(req.WorkflowID); ok && wf.Generic && strings.TrimSpace(project.DefaultRepositoryID) != "" { diff --git a/internal/httpapi/workflow_managed_knowledge.go b/internal/httpapi/workflow_managed_knowledge.go new file mode 100644 index 000000000..968f12568 --- /dev/null +++ b/internal/httpapi/workflow_managed_knowledge.go @@ -0,0 +1,109 @@ +package httpapi + +import ( + "fmt" + "strings" + + "agentflow/internal/domain" + "agentflow/internal/repo" +) + +// managedKnowledgeRefsUnsupported returns why a managed Agent (WMA/A2A) role +// cannot consume knowledge bindings. Management-side knowledge lives on the +// remote agent, so the engine only mounts knowledge MCP servers on the CLI +// path; a binding accepted here would be saved, run green, and silently +// ignored. Rejecting it mirrors the role-level KnowledgeBase rule in +// AgentDefinition.ValidateManagedExecutor. +func managedKnowledgeRefsUnsupported(agent domain.AgentDefinition, provider, nodeName string, refs []domain.KnowledgeRef) error { + if !domain.IsManagedAgentExecutor(provider) || len(refs) == 0 { + return nil + } + ids := make([]string, 0, len(refs)) + for _, ref := range refs { + ids = append(ids, ref.ConnectorID) + } + name := strings.TrimSpace(nodeName) + if name == "" { + name = agent.Name + } + return fmt.Errorf("节点 %q 使用了托管 Agent %q,不支持关联知识库(%s);请在托管 Agent 的服务端配置检索,或把该节点改用 CLI 执行器", + name, provider, strings.Join(ids, "、")) +} + +// workflowManagedKnowledgeRole resolves the role a node runs as, preferring the +// role's executor over the node override exactly like the engine does when it +// routes a node to the managed path. Generic templates keep their packaged +// roles outside the catalog, so those are resolved from the stored template. +// The lookup keys on the workflow id rather than the payload's generic flag: +// the template save branch of PUT /api/workflows stamps Generic itself, so an +// editor payload without "generic": true must still see the packaged roles. +func workflowManagedKnowledgeRole(store *repo.Store, w domain.WorkflowDefinition, node domain.WorkflowNode) (domain.AgentDefinition, string, bool) { + agentID := strings.TrimSpace(node.AgentID) + if agentID == "" || domain.IsPreviewBuildAgent(agentID) { + return domain.AgentDefinition{}, "", false + } + var agent domain.AgentDefinition + ok := false + if template, found := store.GenericTemplateByWorkflow(w.ID); found { + for _, role := range template.Agents { + if role.ID == agentID { + agent, ok = role, true + break + } + } + } + if !ok { + agent, ok = store.Agent(agentID) + if ok && store.AgentShadowsTemplateOutside(agent, w.ProjectID) { + agent, ok = store.GenericAgentByID(agentID) + } + } + if !ok { + return domain.AgentDefinition{}, "", false + } + provider := agent.ExecutorID + if provider == "" { + provider = node.ExecutorID + } + return agent, provider, true +} + +// validateWorkflowManagedKnowledge rejects knowledge bindings attached to +// nodes whose role runs as a managed Agent. +func validateWorkflowManagedKnowledge(store *repo.Store, w domain.WorkflowDefinition) error { + for _, node := range w.Nodes { + if node.Type != "agent" || len(node.KnowledgeRefs) == 0 { + continue + } + agent, provider, ok := workflowManagedKnowledgeRole(store, w, node) + if !ok { + continue + } + if err := managedKnowledgeRefsUnsupported(agent, provider, node.Name, node.KnowledgeRefs); err != nil { + return err + } + } + return nil +} + +// validateRunManagedKnowledge rejects a run-level knowledgeRefs pin when the +// workflow contains a managed Agent node: that node can never honour the pin, +// so the run would otherwise finish with the knowledge silently missing. +func validateRunManagedKnowledge(store *repo.Store, w domain.WorkflowDefinition, refs []domain.KnowledgeRef) error { + if len(refs) == 0 { + return nil + } + for _, node := range w.Nodes { + if node.Type != "agent" { + continue + } + agent, provider, ok := workflowManagedKnowledgeRole(store, w, node) + if !ok { + continue + } + if err := managedKnowledgeRefsUnsupported(agent, provider, node.Name, refs); err != nil { + return fmt.Errorf("本次运行指定了知识库,但它对整条流程生效:%w", err) + } + } + return nil +} diff --git a/internal/httpapi/workflow_managed_knowledge_test.go b/internal/httpapi/workflow_managed_knowledge_test.go new file mode 100644 index 000000000..026dbd3fe --- /dev/null +++ b/internal/httpapi/workflow_managed_knowledge_test.go @@ -0,0 +1,293 @@ +package httpapi + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/repo" +) + +func TestWorkflowManagedKnowledgeValidation(t *testing.T) { + f := cvBNewHTTPFixture(t) + project, _ := f.s.Project("default") + projectID := project.ID + + for _, role := range []domain.AgentDefinition{ + {ID: "mk-cli", Name: "CLI role", ProjectID: projectID}, + {ID: "mk-a2a", Name: "A2A role", ProjectID: projectID, ExecutorID: domain.A2AExecutorID}, + {ID: "mk-wma", Name: "WMA role", ProjectID: projectID, ExecutorID: domain.WMAExecutorID}, + } { + if err := f.s.PutAgent(role); err != nil { + t.Fatal(err) + } + } + refs := []domain.KnowledgeRef{{ConnectorID: "kc-mk", Mode: "all"}} + + cases := []struct { + name string + workflow domain.WorkflowDefinition + wantErr []string + }{ + { + name: "managed role with a node knowledge binding is rejected at save", + workflow: domain.WorkflowDefinition{ID: "mk-a2a-wf", ProjectID: projectID, Nodes: []domain.WorkflowNode{ + {ID: "n1", Name: "A2A step", Type: "agent", AgentID: "mk-a2a", KnowledgeRefs: refs}, + }}, + wantErr: []string{"A2A step", "托管 Agent", "kc-mk"}, + }, + { + name: "WMA role with a node knowledge binding is rejected at save", + workflow: domain.WorkflowDefinition{ID: "mk-wma-wf", ProjectID: projectID, Nodes: []domain.WorkflowNode{ + {ID: "n1", Name: "WMA step", Type: "agent", AgentID: "mk-wma", KnowledgeRefs: refs}, + }}, + wantErr: []string{"WMA step", "托管 Agent"}, + }, + { + name: "CLI role keeps node knowledge bindings", + workflow: domain.WorkflowDefinition{ID: "mk-cli-wf", ProjectID: projectID, Nodes: []domain.WorkflowNode{ + {ID: "n1", Name: "CLI step", Type: "agent", AgentID: "mk-cli", KnowledgeRefs: refs}, + }}, + }, + { + name: "managed role without knowledge bindings is unaffected", + workflow: domain.WorkflowDefinition{ID: "mk-plain-wf", ProjectID: projectID, Nodes: []domain.WorkflowNode{ + {ID: "n1", Name: "Plain A2A", Type: "agent", AgentID: "mk-a2a"}, + }}, + }, + { + name: "non-agent nodes never carry knowledge refs", + workflow: domain.WorkflowDefinition{ID: "mk-script-wf", ProjectID: projectID, Nodes: []domain.WorkflowNode{ + {ID: "n1", Name: "Script", Type: "script"}, + }}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := validateWorkflowManagedKnowledge(f.s, tc.workflow) + if len(tc.wantErr) == 0 { + if err != nil { + t.Fatalf("validateWorkflowManagedKnowledge() = %v, want nil", err) + } + return + } + if err == nil { + t.Fatal("validateWorkflowManagedKnowledge() = nil, want a rejection") + } + for _, want := range tc.wantErr { + if !strings.Contains(err.Error(), want) { + t.Fatalf("error %q missing %q", err.Error(), want) + } + } + }) + } + + // Run-level pins reach every node, so one managed node makes the whole pin + // unusable; workflows made only of CLI nodes keep accepting the pin. + pin := []domain.KnowledgeRef{{ConnectorID: "kc-pin", Mode: "all"}} + mixed := domain.WorkflowDefinition{ID: "mk-mixed-wf", ProjectID: projectID, Nodes: []domain.WorkflowNode{ + {ID: "n1", Name: "CLI step", Type: "agent", AgentID: "mk-cli"}, + {ID: "n2", Name: "A2A step", Type: "agent", AgentID: "mk-a2a"}, + }} + if err := validateRunManagedKnowledge(f.s, mixed, pin); err == nil || !strings.Contains(err.Error(), "kc-pin") { + t.Fatalf("run-level pin on a workflow with a managed node = %v, want rejection naming kc-pin", err) + } + cliOnly := domain.WorkflowDefinition{ID: "mk-cli-only-wf", ProjectID: projectID, Nodes: []domain.WorkflowNode{ + {ID: "n1", Name: "CLI step", Type: "agent", AgentID: "mk-cli"}, + }} + if err := validateRunManagedKnowledge(f.s, cliOnly, pin); err != nil { + t.Fatalf("run-level pin on CLI-only workflow = %v, want nil", err) + } + if err := validateRunManagedKnowledge(f.s, mixed, nil); err != nil { + t.Fatalf("run without a pin must not be rejected: %v", err) + } + if err := validateRunManagedKnowledge(f.s, mixed, []domain.KnowledgeRef{}); err != nil { + t.Fatalf("explicit empty pin must not be rejected: %v", err) + } +} + +func TestSaveWorkflowRejectsManagedNodeKnowledgeBinding(t *testing.T) { + f := cvBNewHTTPFixture(t) + project, _ := f.s.Project("default") + projectID := project.ID + if err := f.s.PutAgent(domain.AgentDefinition{ID: "sk-a2a", Name: "A2A", ProjectID: projectID, ExecutorID: domain.A2AExecutorID}); err != nil { + t.Fatal(err) + } + if err := f.s.PutAgent(domain.AgentDefinition{ID: "sk-cli", Name: "CLI", ProjectID: projectID}); err != nil { + t.Fatal(err) + } + workflow := func(id, agentID string) map[string]any { + return map[string]any{ + "id": id, "name": id, "projectId": projectID, "status": "draft", "sandboxProfileId": "test-native", + "nodes": []map[string]any{{ + "id": "n1", "name": "绑定知识库的步骤", "type": "agent", "agentId": agentID, + "knowledgeRefs": []map[string]any{{"connectorId": "kc-save", "mode": "all"}}, + }}, + "edges": []map[string]any{}, + } + } + + rec := cvBRequest(t, f, http.MethodPut, "/api/workflows", workflow("sk-a2a-wf", "sk-a2a"), true) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "托管 Agent") { + t.Fatalf("managed-agent workflow save = %d %s, want 400 naming the managed Agent", rec.Code, rec.Body.String()) + } + if _, stored := f.s.Workflow("sk-a2a-wf"); stored { + t.Fatal("rejected workflow was persisted") + } + + rec = cvBRequest(t, f, http.MethodPut, "/api/workflows", workflow("sk-cli-wf", "sk-cli"), true) + if rec.Code != http.StatusOK { + t.Fatalf("CLI workflow save = %d %s, want 200", rec.Code, rec.Body.String()) + } + stored, ok := f.s.Workflow("sk-cli-wf") + if !ok || len(stored.Nodes) != 1 || len(stored.Nodes[0].KnowledgeRefs) != 1 { + t.Fatalf("CLI workflow knowledge binding not persisted: %+v", stored.Nodes) + } +} + +// The review of 3819f1c9 found three writers that bypassed the save check: +// clone, revision restore and the generic-template branch of PUT. Each one +// must refuse to persist a managed node that still carries knowledge refs. +func TestManagedKnowledgeRejectedOnCloneAndRestore(t *testing.T) { + f := cvBNewHTTPFixture(t) + project, _ := f.s.Project("default") + projectID := project.ID + role := domain.AgentDefinition{ID: "cr-role", Name: "Role", ProjectID: projectID} + if err := f.s.PutAgent(role); err != nil { + t.Fatal(err) + } + refs := []map[string]any{{"connectorId": "kc-cr", "mode": "all"}} + body := func(revision int, knowledge []map[string]any) map[string]any { + return map[string]any{ + "id": "cr-wf", "name": "cr-wf", "projectId": projectID, "status": "draft", "sandboxProfileId": "test-native", + "revision": revision, + "nodes": []map[string]any{{"id": "n1", "name": "知识库步骤", "type": "agent", "agentId": role.ID, "knowledgeRefs": knowledge}}, + "edges": []map[string]any{}, + } + } + // Saved while the role is still a CLI role: the binding is legitimate. + rec := cvBRequest(t, f, http.MethodPut, "/api/workflows", body(0, refs), true) + if rec.Code != http.StatusOK { + t.Fatalf("CLI save = %d %s", rec.Code, rec.Body.String()) + } + withKB, _ := f.s.Workflow("cr-wf") + rec = cvBRequest(t, f, http.MethodPut, "/api/workflows", body(withKB.Revision, nil), true) + if rec.Code != http.StatusOK { + t.Fatalf("second save = %d %s", rec.Code, rec.Body.String()) + } + var kbRevision string + for _, rev := range f.s.Revisions("workflow", "cr-wf") { + var payload domain.WorkflowDefinition + if json.Unmarshal(rev.Payload, &payload) == nil && len(payload.Nodes) == 1 && len(payload.Nodes[0].KnowledgeRefs) == 1 { + kbRevision = rev.ID + } + } + if kbRevision == "" { + t.Fatal("no revision with the knowledge binding was recorded") + } + + // The role then becomes a managed Agent. + role.ExecutorID = domain.A2AExecutorID + if err := f.s.PutAgent(role); err != nil { + t.Fatal(err) + } + + rec = cvBRequest(t, f, http.MethodPost, "/api/workflows/cr-wf/revisions/"+kbRevision+"/restore", map[string]any{}, true) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "托管 Agent") { + t.Fatalf("restore of a knowledge revision onto a managed role = %d %s, want 400", rec.Code, rec.Body.String()) + } + if current, _ := f.s.Workflow("cr-wf"); len(current.Nodes[0].KnowledgeRefs) != 0 { + t.Fatalf("rejected restore still wrote the binding back: %+v", current.Nodes[0]) + } + + // A legacy row (saved before the save check existed) must not be cloned + // into a fresh LOOP either. + legacy := withKB + legacy.ID, legacy.Name, legacy.Revision = "cr-legacy", "cr-legacy", 0 + if err := f.s.PutWorkflow(legacy); err != nil { + t.Fatal(err) + } + rec = cvBRequest(t, f, http.MethodPost, "/api/workflows/cr-legacy/clone", map[string]any{"id": "cr-copy", "name": "copy", "projectId": projectID}, true) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "kc-cr") { + t.Fatalf("clone of a managed node with knowledge = %d %s, want 400", rec.Code, rec.Body.String()) + } + if _, exists := f.s.Workflow("cr-copy"); exists { + t.Fatal("rejected clone was persisted") + } + // Without the binding the same LOOP still clones. + rec = cvBRequest(t, f, http.MethodPost, "/api/workflows/cr-wf/clone", map[string]any{"id": "cr-copy-ok", "name": "copy", "projectId": projectID}, true) + if rec.Code != http.StatusCreated { + t.Fatalf("clone without knowledge = %d %s, want 201", rec.Code, rec.Body.String()) + } +} + +func TestGenericTemplateSaveAndCloneRejectManagedKnowledge(t *testing.T) { + t.Setenv("AGENTFLOW_PLATFORM_ADMINS", "example-admin") + t.Setenv("AGENTFLOW_SESSION_SECRET", "generic-admin-session-secret") + h, s := newGenericTemplateServer(t) + if err := s.PutUser(domain.User{LoginName: "example-admin", ChineseName: "Admin"}); err != nil { + t.Fatal(err) + } + admin, _ := s.UserByLoginName("example-admin") + + // Adopting once leaves a CLI copy of the MR role in the catalog under the + // template's role id — the lookup the old validator preferred. + requestJSON[domain.WorkflowDefinition](t, h, http.MethodPost, "/api/workflows/"+repo.GenericBackendDeliveryWorkflowID+"/clone", + map[string]any{"id": "alpha-backend", "name": "后端", "projectId": "alpha"}, http.StatusCreated) + if catalog, ok := s.Agent(repo.GenericAgentMR); !ok || domain.IsManagedAgentExecutor(catalog.ExecutorID) { + t.Fatalf("adopted MR role should be a CLI catalog role: %+v", catalog) + } + + template, _ := s.GenericTemplateByWorkflow(repo.GenericBackendDeliveryWorkflowID) + for i := range template.Agents { + if template.Agents[i].ID == repo.GenericAgentMR { + template.Agents[i].ExecutorID = domain.WMAExecutorID + } + } + if err := s.PutGenericTemplate(template); err != nil { + t.Fatal(err) + } + detail := requestJSONAuthed[domain.WorkflowDefinition](t, h, admin, http.MethodGet, + "/api/workflows/"+repo.GenericBackendDeliveryWorkflowID, nil, http.StatusOK) + bound := false + for i := range detail.Nodes { + if detail.Nodes[i].AgentID == repo.GenericAgentMR { + detail.Nodes[i].KnowledgeRefs = []domain.KnowledgeRef{{ConnectorID: "kc-generic", Mode: "all"}} + bound = true + } + } + if !bound { + t.Fatal("template has no MR node") + } + for _, generic := range []bool{true, false} { + payload := detail + payload.Generic = generic + rec := requestJSONAuthed[map[string]any](t, h, admin, http.MethodPut, "/api/workflows", payload, http.StatusBadRequest) + if msg, _ := rec["error"].(string); !strings.Contains(msg, "kc-generic") { + t.Fatalf("generic=%v template save error = %v, want the managed knowledge rejection", generic, rec) + } + } + stored, _ := s.GenericTemplateByWorkflow(repo.GenericBackendDeliveryWorkflowID) + for _, node := range stored.Workflow.Nodes { + if len(node.KnowledgeRefs) != 0 { + t.Fatalf("rejected template save persisted a binding: %+v", node) + } + } + + // A template whose packaged managed role already carries a binding must + // not be adopted into a project either, and must not pre-create roles. + stored.Workflow.Nodes = detail.Nodes + if err := s.PutGenericTemplate(stored); err != nil { + t.Fatal(err) + } + rec := requestJSON[map[string]any](t, h, http.MethodPost, "/api/workflows/"+repo.GenericBackendDeliveryWorkflowID+"/clone", + map[string]any{"id": "beta-backend", "name": "后端", "projectId": "beta"}, http.StatusBadRequest) + if msg, _ := rec["error"].(string); !strings.Contains(msg, "kc-generic") { + t.Fatalf("generic clone error = %v", rec) + } + if _, exists := s.Workflow("beta-backend"); exists { + t.Fatal("rejected adoption was persisted") + } +} diff --git a/internal/managedagent/a2a.go b/internal/managedagent/a2a.go new file mode 100644 index 000000000..afbcc5013 --- /dev/null +++ b/internal/managedagent/a2a.go @@ -0,0 +1,255 @@ +package managedagent + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "time" +) + +// TextAgent is a remotely managed text turn. Callers own scheduling and +// publish the completed text through the normal workflow artifact path. +type TextAgent interface { + Run(context.Context, string, func(string)) (string, error) +} + +type A2AConfig struct { + Endpoint string + Token string + // Loopback permits a personal Runner to use an Agent on the same host. + Loopback bool +} + +type A2A struct { + endpoint string + token string + client http.Client +} + +func NewA2A(config A2AConfig, client *http.Client) (*A2A, error) { + endpoint, err := url.Parse(config.Endpoint) + if err != nil || endpoint.Hostname() == "" || endpoint.User != nil || endpoint.Fragment != "" || endpoint.RawQuery != "" || endpoint.ForceQuery { + return nil, errors.New("invalid A2A endpoint") + } + if config.Loopback { + ip := net.ParseIP(endpoint.Hostname()) + if ip == nil || !ip.IsLoopback() || (endpoint.Scheme != "http" && endpoint.Scheme != "https") { + return nil, errors.New("personal Runner A2A endpoint must use a literal loopback address") + } + } else if endpoint.Scheme != "https" { + return nil, errors.New("remotely configured A2A endpoint requires HTTPS") + } + if client == nil { + client = http.DefaultClient + } + transport := *client + transport.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + return &A2A{endpoint: endpoint.String(), token: config.Token, client: transport}, nil +} + +type a2aPart struct { + Kind string `json:"kind"` + Text string `json:"text,omitempty"` +} + +type a2aMessage struct { + Kind string `json:"kind"` + MessageID string `json:"messageId,omitempty"` + Role string `json:"role"` + Parts []a2aPart `json:"parts"` +} + +type a2aResult struct { + Kind string `json:"kind"` + ID string `json:"id"` + a2aMessage + Status struct { + State string `json:"state"` + Message *a2aMessage `json:"message"` + } `json:"status"` + Artifacts []struct { + Parts []a2aPart `json:"parts"` + } `json:"artifacts"` + History []a2aMessage `json:"history"` +} + +// Run sends one text turn. A task still running after turnTimeout is +// cancelled on the Agent and reported as a turn timeout. +func (a *A2A) Run(parent context.Context, prompt string, onText func(string)) (string, error) { + ctx, stop := context.WithTimeout(parent, turnTimeout) + defer stop() + output, err := a.run(ctx, prompt, onText) + return output, turnTimeoutError("A2A", ctx, parent, err) +} + +func (a *A2A) run(ctx context.Context, prompt string, onText func(string)) (string, error) { + if len(prompt) > maxACPText { + return "", errors.New("A2A prompt exceeds 1 MiB") + } + var result a2aResult + err := a.rpc(ctx, "message/send", map[string]any{ + "message": a2aMessage{ + Kind: "message", MessageID: rand.Text(), Role: "user", + Parts: []a2aPart{{Kind: "text", Text: prompt}}, + }, + "configuration": map[string]any{ + "acceptedOutputModes": []string{"text/plain"}, + "blocking": false, + "historyLength": 1, + }, + }, &result) + if err != nil { + return "", err + } + + switch result.Kind { + case "message": + if result.Role != "agent" { + return "", errors.New("A2A response is not an Agent message") + } + case "task": + var err error + result, err = a.waitTask(ctx, result) + if err != nil { + return "", err + } + default: + return "", errors.New("A2A response must be a Message or Task") + } + output := a2aText(result) + if strings.TrimSpace(output) == "" { + return "", errors.New("A2A Agent returned no text") + } + if len(output) > maxACPText { + return "", errors.New("A2A text result exceeds 1 MiB") + } + if onText != nil { + onText(output) + } + return output, nil +} + +func (a *A2A) waitTask(ctx context.Context, result a2aResult) (a2aResult, error) { + id := result.ID + if id == "" || len(id) > 256 { + return a2aResult{}, errors.New("A2A response lacks a valid task ID") + } + defer func() { + if ctx.Err() != nil && (result.Status.State == "submitted" || result.Status.State == "working") { + cleanup, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + _ = a.rpc(cleanup, "tasks/cancel", map[string]string{"id": id}, nil) + } + }() + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + for { + switch result.Status.State { + case "completed": + return result, nil + case "submitted", "working": + select { + case <-ctx.Done(): + return a2aResult{}, ctx.Err() + case <-ticker.C: + } + case "failed", "rejected", "canceled", "input-required", "auth-required": + return a2aResult{}, fmt.Errorf("A2A task ended in state %s", result.Status.State) + default: + return a2aResult{}, errors.New("A2A task returned an unsupported state") + } + var next a2aResult + if err := a.rpc(ctx, "tasks/get", map[string]any{"id": id, "historyLength": 1}, &next); err != nil { + return a2aResult{}, err + } + if next.Kind != "task" || next.ID != id { + return a2aResult{}, errors.New("A2A returned a different task during polling") + } + result = next + } +} + +func a2aText(result a2aResult) string { + var output strings.Builder + writeParts := func(parts []a2aPart) { + for _, part := range parts { + if part.Kind == "text" { + output.WriteString(part.Text) + } + } + } + if result.Kind == "message" { + writeParts(result.Parts) + return output.String() + } + for _, artifact := range result.Artifacts { + writeParts(artifact.Parts) + } + if output.Len() > 0 { + return output.String() + } + if result.Status.Message != nil && result.Status.Message.Role == "agent" { + writeParts(result.Status.Message.Parts) + } + for i := len(result.History) - 1; output.Len() == 0 && i >= 0; i-- { + if result.History[i].Role == "agent" { + writeParts(result.History[i].Parts) + } + } + return output.String() +} + +func (a *A2A) rpc(ctx context.Context, method string, params any, output any) error { + ctx, cancel := context.WithTimeout(ctx, 45*time.Second) + defer cancel() + body, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params}) + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.endpoint, bytes.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json") + if a.token != "" { + req.Header.Set("Authorization", "Bearer "+a.token) + } + res, err := a.client.Do(req) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return fmt.Errorf("A2A %s: connection failed", method) + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return fmt.Errorf("A2A %s: HTTP %d", method, res.StatusCode) + } + var envelope struct { + JSONRPC string `json:"jsonrpc"` + ID int `json:"id"` + Result json.RawMessage `json:"result"` + Error *struct { + Code int `json:"code"` + } `json:"error"` + } + if err := json.NewDecoder(io.LimitReader(res.Body, 2<<20)).Decode(&envelope); err != nil || envelope.JSONRPC != "2.0" || envelope.ID != 1 { + return fmt.Errorf("A2A %s: invalid JSON-RPC response", method) + } + if envelope.Error != nil { + return fmt.Errorf("A2A %s: JSON-RPC error %d", method, envelope.Error.Code) + } + if output != nil && json.Unmarshal(envelope.Result, output) != nil { + return fmt.Errorf("A2A %s: invalid result", method) + } + return nil +} diff --git a/internal/managedagent/a2a_test.go b/internal/managedagent/a2a_test.go new file mode 100644 index 000000000..c7c0d0fa2 --- /dev/null +++ b/internal/managedagent/a2a_test.go @@ -0,0 +1,125 @@ +package managedagent + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestA2AEndpointPolicy(t *testing.T) { + for _, item := range []A2AConfig{ + {Endpoint: "http://example.test/a2a"}, + {Endpoint: "https://example.test/a2a", Loopback: true}, + {Endpoint: "http://user@127.0.0.1/a2a", Loopback: true}, + } { + if _, err := NewA2A(item, nil); err == nil { + t.Errorf("accepted endpoint outside the configured transport policy") + } + } +} + +func TestA2ATaskCancellation(t *testing.T) { + polling, cancelled := make(chan struct{}, 1), make(chan struct{}, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var request struct { + Method string `json:"method"` + Params struct { + ID string `json:"id"` + } `json:"params"` + } + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + state := "working" + switch request.Method { + case "message/send": + case "tasks/get": + if request.Params.ID != "task-test" { + t.Error("polled another task") + } + select { + case polling <- struct{}{}: + default: + } + case "tasks/cancel": + if request.Params.ID != "task-test" { + t.Error("cancelled another task") + } + cancelled <- struct{}{} + state = "canceled" + default: + t.Errorf("unexpected method %s", request.Method) + } + result := map[string]any{"id": "task-test", "kind": "task", "status": map[string]string{"state": state}} + json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": 1, "result": result}) + })) + defer server.Close() + client, err := NewA2A(A2AConfig{Endpoint: server.URL, Loopback: true}, nil) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + go func() { + select { + case <-polling: + cancel() + case <-ctx.Done(): + } + }() + if _, err := client.Run(ctx, "test cancellation", nil); !errors.Is(err, context.Canceled) { + t.Fatalf("got %v, want cancellation", err) + } + select { + case <-cancelled: + default: + t.Fatal("the remote task was not cancelled") + } +} + +func TestA2ATurnTimeoutIsNamedAndCancelsTheTask(t *testing.T) { + previous := turnTimeout + turnTimeout = 1500 * time.Millisecond + t.Cleanup(func() { turnTimeout = previous }) + cancelled := make(chan struct{}, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var request struct { + Method string `json:"method"` + } + _ = json.NewDecoder(r.Body).Decode(&request) + if request.Method == "tasks/cancel" { + cancelled <- struct{}{} + } + _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": 1, "result": map[string]any{ + "kind": "task", "id": "slow-task", "status": map[string]string{"state": "working"}, + }}) + })) + defer server.Close() + agent, err := NewA2A(A2AConfig{Endpoint: server.URL, Loopback: true}, server.Client()) + if err != nil { + t.Fatal(err) + } + _, err = agent.Run(context.Background(), "slow", nil) + if !errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, ErrTurnTimedOut) || !strings.Contains(err.Error(), "A2A Agent 未在 1.5s 内完成本轮") { + t.Fatalf("Run() error = %v", err) + } + select { + case <-cancelled: + case <-time.After(5 * time.Second): + t.Fatal("timed-out task was not cancelled") + } + + // A caller cancellation (run cancelled) keeps the plain context error. + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(200*time.Millisecond, cancel) + if _, err := agent.Run(ctx, "slow", nil); !errors.Is(err, context.Canceled) || strings.Contains(err.Error(), "未在") { + t.Fatalf("cancelled Run() error = %v", err) + } +} diff --git a/internal/managedagent/acp.go b/internal/managedagent/acp.go new file mode 100644 index 000000000..1423e70ab --- /dev/null +++ b/internal/managedagent/acp.go @@ -0,0 +1,294 @@ +package managedagent + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "mime" + "net/http" + "strconv" + "strings" + "time" +) + +const maxACPText = 1 << 20 + +type acpMessage struct { + ID json.RawMessage `json:"id,omitempty"` + Method string `json:"method,omitempty"` + Params json.RawMessage `json:"params,omitempty"` + Result json.RawMessage `json:"result,omitempty"` + Error *struct { + Code int `json:"code"` + } `json:"error,omitempty"` +} + +type acpEvent struct { + message acpMessage + err error +} + +type acpConnection struct { + ctx context.Context + stop context.CancelFunc + client *http.Client + url string + token string + session string + id string + nextID int + messages <-chan acpEvent +} + +func (w *WMA) connect(ctx context.Context, endpoint, token string) (*acpConnection, error) { + ctx, stop := context.WithCancel(ctx) + acp := &acpConnection{ctx: ctx, stop: stop, client: &w.client, url: endpoint, token: token, session: w.config.SessionID} + res, err := acp.request(ctx, http.MethodGet, nil) + if err != nil { + stop() + return nil, err + } + acp.id = res.Header.Get("Acp-Connection-Id") + if acp.id == "" || !isEventStream(res) { + res.Body.Close() + stop() + return nil, errors.New("WMA ACP did not return an SSE connection ID") + } + acp.messages = readEvents(ctx, res.Body) + return acp, nil +} + +func (a *acpConnection) request(ctx context.Context, method string, input any) (*http.Response, error) { + var body io.Reader + if input != nil { + raw, err := json.Marshal(input) + if err != nil { + return nil, err + } + body = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(ctx, method, a.url, body) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+a.token) + req.Header.Set("X-Agent-Session-Id", a.session) + req.Header.Set("Accept", "text/event-stream") + if a.id != "" { + req.Header.Set("Acp-Connection-Id", a.id) + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + res, err := a.client.Do(req) + if err != nil { + return nil, fmt.Errorf("WMA ACP %s: %w", method, err) + } + if res.StatusCode < 200 || res.StatusCode >= 300 { + res.Body.Close() + return nil, fmt.Errorf("WMA ACP %s: HTTP %d", method, res.StatusCode) + } + return res, nil +} + +func isEventStream(res *http.Response) bool { + contentType, _, _ := mime.ParseMediaType(res.Header.Get("Content-Type")) + return contentType == "text/event-stream" +} + +func (a *acpConnection) call(method string, params any, update func(acpMessage) error) (json.RawMessage, error) { + a.nextID++ + id := strconv.Itoa(a.nextID) + ctx, stop := context.WithCancel(a.ctx) + defer stop() + res, err := a.request(ctx, http.MethodPost, map[string]any{ + "jsonrpc": "2.0", "id": a.nextID, "method": method, "params": params, + }) + if err != nil { + return nil, err + } + var posted <-chan acpEvent + if isEventStream(res) { + posted = readEvents(ctx, res.Body) + } else { + res.Body.Close() + } + for a.messages != nil || posted != nil { + var event acpEvent + var open bool + select { + case <-ctx.Done(): + return nil, ctx.Err() + case event, open = <-a.messages: + if !open { + a.messages = nil + continue + } + case event, open = <-posted: + if !open { + posted = nil + continue + } + } + if event.err != nil { + return nil, event.err + } + msg := event.message + if msg.Method != "" { + if len(msg.ID) > 0 { + if err := a.answerRequest(ctx, msg); err != nil { + return nil, err + } + } else if update != nil { + if err := update(msg); err != nil { + return nil, err + } + } + continue + } + if string(msg.ID) != id { + continue + } + if msg.Error != nil { + return nil, fmt.Errorf("WMA ACP %s: JSON-RPC error %d", method, msg.Error.Code) + } + return msg.Result, nil + } + if err := ctx.Err(); err != nil { + return nil, err + } + return nil, fmt.Errorf("WMA ACP stream ended before %s completed", method) +} + +func (a *acpConnection) answerRequest(ctx context.Context, msg acpMessage) error { + reply := map[string]any{"jsonrpc": "2.0", "id": msg.ID} + if msg.Method == "session/request_permission" { + reply["result"] = map[string]any{"outcome": map[string]string{"outcome": "cancelled"}} + } else { + reply["error"] = map[string]any{"code": -32601, "message": "Method not supported"} + } + res, err := a.request(ctx, http.MethodPost, reply) + if err == nil { + res.Body.Close() + } + return err +} + +func (a *acpConnection) prompt(text string, onText func(string)) (string, error) { + var output strings.Builder + result, err := a.call("session/prompt", map[string]any{ + "sessionId": a.session, + "prompt": []map[string]string{{"type": "text", "text": text}}, + }, func(msg acpMessage) error { + if msg.Method != "session/update" { + return nil + } + var event struct { + SessionID string `json:"sessionId"` + Update struct { + Kind string `json:"sessionUpdate"` + Content struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"content"` + } `json:"update"` + } + if json.Unmarshal(msg.Params, &event) != nil || event.SessionID != a.session || event.Update.Kind != "agent_message_chunk" || event.Update.Content.Type != "text" { + return nil + } + delta := event.Update.Content.Text + if output.Len()+len(delta) > maxACPText { + return errors.New("WMA ACP reply exceeds 1 MiB") + } + output.WriteString(delta) + if onText != nil && delta != "" { + onText(delta) + } + return nil + }) + if err != nil { + a.cleanupRequest(http.MethodPost, map[string]any{ + "jsonrpc": "2.0", "method": "session/cancel", + "params": map[string]string{"sessionId": a.session}, + }) + return output.String(), err + } + var terminal struct { + StopReason string `json:"stopReason"` + } + if json.Unmarshal(result, &terminal) != nil || terminal.StopReason == "" { + return output.String(), errors.New("WMA ACP returned no stop reason") + } + if terminal.StopReason != "end_turn" { + switch terminal.StopReason { + case "max_tokens", "max_turn_requests", "refusal", "cancelled": + return output.String(), fmt.Errorf("WMA ACP stopped: %s", terminal.StopReason) + default: + return output.String(), errors.New("WMA ACP returned an unsupported stop reason") + } + } + return output.String(), nil +} + +func (a *acpConnection) disconnect() { + defer a.stop() + a.cleanupRequest(http.MethodDelete, nil) +} + +func (a *acpConnection) cleanupRequest(method string, body any) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if res, err := a.request(ctx, method, body); err == nil { + res.Body.Close() + } +} + +// readEvents emits one message for each complete SSE event. Empty heartbeat +// lines and comments do not produce messages. +func readEvents(ctx context.Context, body io.ReadCloser) <-chan acpEvent { + events := make(chan acpEvent, 16) + go func() { + defer close(events) + defer body.Close() + send := func(event acpEvent) bool { + select { + case events <- event: + return true + case <-ctx.Done(): + return false + } + } + scanner := bufio.NewScanner(body) + scanner.Buffer(make([]byte, 4096), maxACPText) + var data strings.Builder + for scanner.Scan() { + line := scanner.Text() + if line == "" && data.Len() > 0 { + var msg acpMessage + if json.Unmarshal([]byte(data.String()), &msg) != nil { + send(acpEvent{err: errors.New("invalid WMA ACP event")}) + return + } + data.Reset() + if !send(acpEvent{message: msg}) { + return + } + } else if value, ok := strings.CutPrefix(line, "data:"); ok { + if data.Len()+len(value)+1 > maxACPText { + send(acpEvent{err: errors.New("WMA ACP event exceeds 1 MiB")}) + return + } + data.WriteString(strings.TrimPrefix(value, " ")) + data.WriteByte('\n') + } + } + if err := scanner.Err(); err != nil && ctx.Err() == nil { + send(acpEvent{err: fmt.Errorf("read WMA ACP stream: %w", err)}) + } + }() + return events +} diff --git a/internal/managedagent/tencent.go b/internal/managedagent/tencent.go new file mode 100644 index 000000000..b24d531b1 --- /dev/null +++ b/internal/managedagent/tencent.go @@ -0,0 +1,121 @@ +package managedagent + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "regexp" + "strconv" + "time" +) + +const tencentService = "workbuddyenterprise" +const tencentVersion = "2026-07-09" + +var tencentRegion = regexp.MustCompile("^[a-z]{2}-[a-z0-9]+$") + +type TencentCloudConfig struct { + SecretID string + SecretKey string + Token string + Region string +} + +type tencentCloud struct { + config TencentCloudConfig + host string + client *http.Client +} + +func newTencentCloud(config TencentCloudConfig, client *http.Client) (*tencentCloud, error) { + if config.Region == "" { + config.Region = "ap-beijing" + } + if config.SecretID == "" || config.SecretKey == "" || !tencentRegion.MatchString(config.Region) { + return nil, errors.New("WMA Tencent Cloud mode requires a SecretId, SecretKey and valid region") + } + return &tencentCloud{config: config, host: tencentService + "." + config.Region + ".tencentcloudapi.com", client: client}, nil +} + +func (c *tencentCloud) call(ctx context.Context, action string, input any, output any) error { + ctx, stop := context.WithTimeout(ctx, 20*time.Second) + defer stop() + body, err := json.Marshal(input) + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://"+c.host+"/", bytes.NewReader(body)) + if err != nil { + return err + } + const contentType = "application/json; charset=utf-8" + now := time.Now().UTC() + req.Header.Set("Content-Type", contentType) + req.Header.Set("X-TC-Action", action) + req.Header.Set("X-TC-Region", c.config.Region) + req.Header.Set("X-TC-Version", tencentVersion) + req.Header.Set("X-TC-Timestamp", strconv.FormatInt(now.Unix(), 10)) + req.Header.Set("Authorization", c.sign(now, contentType, body)) + if c.config.Token != "" { + req.Header.Set("X-TC-Token", c.config.Token) + } + + res, err := c.client.Do(req) + if err != nil { + return fmt.Errorf("WMA Tencent Cloud %s: %w", action, err) + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return fmt.Errorf("WMA Tencent Cloud %s: HTTP %d", action, res.StatusCode) + } + var envelope struct { + Response json.RawMessage + } + if err := json.NewDecoder(io.LimitReader(res.Body, 2<<20)).Decode(&envelope); err != nil || len(envelope.Response) == 0 { + return fmt.Errorf("WMA Tencent Cloud %s: invalid response", action) + } + var failure struct { + Error *struct{ Code string } + } + if err := json.Unmarshal(envelope.Response, &failure); err != nil { + return fmt.Errorf("WMA Tencent Cloud %s: invalid response data", action) + } + if failure.Error != nil { + if errorCode.MatchString(failure.Error.Code) { + return fmt.Errorf("WMA Tencent Cloud %s: %s", action, failure.Error.Code) + } + return fmt.Errorf("WMA Tencent Cloud %s rejected the request", action) + } + if err := json.Unmarshal(envelope.Response, output); err != nil { + return fmt.Errorf("WMA Tencent Cloud %s: invalid response data", action) + } + return nil +} + +// sign implements the Tencent Cloud TC3-HMAC-SHA256 signature for a JSON POST. +func (c *tencentCloud) sign(now time.Time, contentType string, body []byte) string { + const signed = "content-type;host" + digest := func(payload []byte) string { + sum := sha256.Sum256(payload) + return hex.EncodeToString(sum[:]) + } + mac := func(key []byte, value string) []byte { + h := hmac.New(sha256.New, key) + h.Write([]byte(value)) + return h.Sum(nil) + } + day := now.Format(time.DateOnly) + scope := day + "/" + tencentService + "/tc3_request" + canonical := "POST\n/\n\ncontent-type:" + contentType + "\nhost:" + c.host + "\n\n" + signed + "\n" + digest(body) + message := fmt.Sprintf("TC3-HMAC-SHA256\n%d\n%s\n%s", now.Unix(), scope, digest([]byte(canonical))) + key := mac([]byte("TC3"+c.config.SecretKey), day) + key = mac(mac(key, tencentService), "tc3_request") + return fmt.Sprintf("TC3-HMAC-SHA256 Credential=%s/%s, SignedHeaders=%s, Signature=%x", c.config.SecretID, scope, signed, mac(key, message)) +} diff --git a/internal/managedagent/tencent_test.go b/internal/managedagent/tencent_test.go new file mode 100644 index 000000000..0c88c3fac --- /dev/null +++ b/internal/managedagent/tencent_test.go @@ -0,0 +1,50 @@ +package managedagent + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + "testing" +) + +type cloudTestTransport func(*http.Request) (*http.Response, error) + +func (f cloudTestTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestWMATencentControl(t *testing.T) { + client := &http.Client{Transport: cloudTestTransport(func(r *http.Request) (*http.Response, error) { + if r.Method != http.MethodPost || r.URL.Host != "workbuddyenterprise.ap-beijing.tencentcloudapi.com" || + r.Header.Get("X-TC-Version") != tencentVersion || r.Header.Get("X-TC-Token") != "temporary-test-token" || + !strings.HasPrefix(r.Header.Get("Authorization"), "TC3-HMAC-SHA256 Credential=example-id/") { + t.Fatal("missing signed Tencent Cloud headers") + } + body := "" + switch r.Header.Get("X-TC-Action") { + case "DescribeAgentSession": + var request struct{ SessionId string } + if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.SessionId != "session-test" { + t.Fatal("wrong session request") + } + body = `{"Response":{"AgentId":"agent-test","SessionId":"session-test","EndpointSet":[{"EndpointType":"PUBLIC","Url":"https://agent-test.ma.workbuddy.cn"}]}}` + case "DescribeUserAccessToken": + body = `{"Response":{"Error":{"Code":"UnauthorizedOperation.Test"}}}` + default: + t.Fatalf("unexpected action %q", r.Header.Get("X-TC-Action")) + } + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil + })} + wma, err := NewWMA(Config{AgentID: "agent-test", SessionID: "session-test", TencentCloud: &TencentCloudConfig{ + SecretID: "example-id", SecretKey: "example-test-secret", Token: "temporary-test-token", + }}, client) + if err != nil { + t.Fatal(err) + } + if endpoint, err := wma.sessionEndpoint(context.Background()); err != nil || endpoint != "https://agent-test.ma.workbuddy.cn"+acpPath { + t.Fatalf("unexpected ACP endpoint %q: %v", endpoint, err) + } + if err := wma.accessToken(context.Background(), new(map[string]any)); err == nil || !strings.Contains(err.Error(), "UnauthorizedOperation.Test") { + t.Fatalf("unexpected Tencent Cloud error: %v", err) + } +} diff --git a/internal/managedagent/timeout.go b/internal/managedagent/timeout.go new file mode 100644 index 000000000..971f84cf3 --- /dev/null +++ b/internal/managedagent/timeout.go @@ -0,0 +1,68 @@ +package managedagent + +import ( + "context" + "errors" + "fmt" + "time" +) + +// turnTimeout bounds one managed Agent turn. A variable so tests can shorten it. +var turnTimeout = 5 * time.Minute + +// ErrTurnTimedOut marks a turn that ran past the budget. The prompt was already +// sent and the cancellation is advisory, so the remote outcome is unknown and +// the same turn must not be resent automatically. +var ErrTurnTimedOut = errors.New("托管 Agent 轮次超时") + +type turnTimeoutFailure struct { + provider string + err error +} + +func (f *turnTimeoutFailure) Error() string { + return fmt.Sprintf("%s Agent 未在 %s 内完成本轮,已请求取消:%v", f.provider, turnTimeout, f.err) +} + +// Unwrap exposes both the sentinel and the transport error so callers can +// match either one without parsing the message. +func (f *turnTimeoutFailure) Unwrap() []error { + return []error{ErrTurnTimedOut, f.err} +} + +// turnTimeoutError names the turn budget when it, rather than the caller's +// context (run cancellation) or a single request, ended the turn. +func turnTimeoutError(provider string, turn, parent context.Context, err error) error { + if err == nil || !errors.Is(turn.Err(), context.DeadlineExceeded) || parent.Err() != nil { + return err + } + return &turnTimeoutFailure{provider: provider, err: err} +} + +// UnknownTurnError reports a managed turn whose remote outcome is unknown, +// rebuilt from a message that crossed a process boundary (a personal Runner +// completing its task). The wrapped sentinel cannot cross that boundary as a +// value, so this type matches ErrTurnTimedOut for retry classification while +// keeping the reporter's explanation intact. +type UnknownTurnError struct { + Message string +} + +func (e *UnknownTurnError) Error() string { + if e.Message == "" { + return ErrTurnTimedOut.Error() + } + return e.Message +} + +func (e *UnknownTurnError) Is(target error) bool { + return target == ErrTurnTimedOut +} + +// TurnTimeout reports the per-turn budget. Runners and the control plane read +// the same value; tests shorten it. +func TurnTimeout() time.Duration { return turnTimeout } + +// SetTurnTimeout replaces the per-turn budget and returns nothing; callers in +// tests restore the previous value. +func SetTurnTimeout(d time.Duration) { turnTimeout = d } diff --git a/internal/managedagent/wma.go b/internal/managedagent/wma.go new file mode 100644 index 000000000..cabb54acf --- /dev/null +++ b/internal/managedagent/wma.go @@ -0,0 +1,230 @@ +package managedagent + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "strings" + "time" +) + +const acpPath = "/v1/agents/acp" + +type Config struct { + Endpoint string + EnterpriseID string + AgentID string + SessionID string + APIKey string + TencentCloud *TencentCloudConfig + ACPOrigin string // optional exact origin for a tenant's private ACP gateway +} + +type WMA struct { + config Config + client http.Client + base string + cloud *tencentCloud + gate chan struct{} +} + +var identifier = regexp.MustCompile("^[a-zA-Z0-9_-]{1,128}$") +var errorCode = regexp.MustCompile("^[a-zA-Z0-9_.-]{1,64}$") + +func NewWMA(config Config, client *http.Client) (*WMA, error) { + if config.ACPOrigin != "" { + u, err := secureURL(config.ACPOrigin) + if err != nil || (u.Path != "" && u.Path != "/") { + return nil, errors.New("WMA ACP endpoint override must be an HTTPS origin") + } + config.ACPOrigin = "https://" + u.Host + } + if !identifier.MatchString(config.AgentID) || !identifier.MatchString(config.SessionID) { + return nil, errors.New("WMA requires an agent and existing session ID") + } + if client == nil { + client = http.DefaultClient + } + transport := *client + transport.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + wma := &WMA{config: config, client: transport, gate: make(chan struct{}, 1)} + if config.TencentCloud != nil { + if config.APIKey != "" || config.Endpoint != "" { + return nil, errors.New("choose one WMA control-plane authentication mode") + } + cloud, err := newTencentCloud(*config.TencentCloud, &wma.client) + if err != nil { + return nil, err + } + wma.cloud = cloud + return wma, nil + } + if !identifier.MatchString(config.EnterpriseID) || (!strings.HasPrefix(config.APIKey, "ck_") && !strings.HasPrefix(config.APIKey, "pt_")) { + return nil, errors.New("WMA OpenAPI requires an enterprise ID and a ck_ or pt_ credential") + } + if config.Endpoint == "" { + config.Endpoint = "https://www.workbuddy.cn" + } + origin, err := secureURL(config.Endpoint) + if err != nil || (origin.Path != "" && origin.Path != "/") { + return nil, errors.New("WMA control endpoint must be an HTTPS origin") + } + wma.base = "https://" + origin.Host + "/v2/enterprises/" + config.EnterpriseID + "/managedagent" + return wma, nil +} + +// Run prompts a dedicated pre-provisioned WMA session. The same session accepts +// only one active prompt. A turn with an unknown outcome is never replayed here. +func (w *WMA) Run(parent context.Context, prompt string, onText func(string)) (string, error) { + ctx, cancel := context.WithTimeout(parent, turnTimeout) + defer cancel() + output, err := w.run(ctx, prompt, onText) + return output, turnTimeoutError("WMA", ctx, parent, err) +} + +func (w *WMA) run(ctx context.Context, prompt string, onText func(string)) (string, error) { + select { + case w.gate <- struct{}{}: + defer func() { <-w.gate }() + case <-ctx.Done(): + return "", ctx.Err() + } + endpoint, err := w.sessionEndpoint(ctx) + if err != nil { + return "", err + } + var token struct { + AccessToken string `json:"accessToken"` + } + if err := w.accessToken(ctx, &token); err != nil { + return "", err + } + if token.AccessToken == "" { + return "", errors.New("WMA did not return a data-plane access token") + } + connection, err := w.connect(ctx, endpoint, token.AccessToken) + if err != nil { + return "", err + } + defer connection.disconnect() + + if _, err := connection.call("initialize", map[string]any{ + "protocolVersion": 1, + "clientCapabilities": map[string]any{ + "fs": map[string]bool{"readTextFile": false, "writeTextFile": false}, + }, + }, nil); err != nil { + return "", err + } + if _, err := connection.call("session/load", map[string]any{ + "sessionId": w.config.SessionID, "cwd": "/workspace", "mcpServers": []any{}, + }, nil); err != nil { + return "", err + } + return connection.prompt(prompt, onText) +} + +func (w *WMA) sessionEndpoint(ctx context.Context) (string, error) { + var session struct { + SessionID string `json:"sessionId"` + AgentID string `json:"agentId"` + Endpoints []struct { + Type string `json:"endpointType"` + URL string `json:"url"` + } `json:"endpointSet"` + } + path := "/agents/" + w.config.AgentID + "/sessions/" + w.config.SessionID + var err error + if w.cloud != nil { + err = w.cloud.call(ctx, "DescribeAgentSession", map[string]string{"SessionId": w.config.SessionID}, &session) + } else { + err = w.control(ctx, http.MethodGet, path, &session) + } + if err != nil { + return "", err + } + if session.SessionID != w.config.SessionID || session.AgentID != w.config.AgentID { + return "", errors.New("WMA session does not match the configured agent and session") + } + for _, endpoint := range session.Endpoints { + u, err := secureURL(endpoint.URL) + if err != nil || (u.Path != "" && u.Path != "/" && u.Path != acpPath) { + continue + } + origin := "https://" + u.Host + defaultOrigin := "https://" + strings.ToLower(w.config.AgentID) + ".ma.workbuddy.cn" + if w.config.ACPOrigin == origin || (w.config.ACPOrigin == "" && endpoint.Type == "PUBLIC" && strings.EqualFold(defaultOrigin, origin)) { + return origin + acpPath, nil + } + } + return "", errors.New("WMA session has no trusted ACP endpoint") +} + +func (w *WMA) accessToken(ctx context.Context, output any) error { + if w.cloud != nil { + return w.cloud.call(ctx, "DescribeUserAccessToken", struct{}{}, output) + } + return w.control(ctx, http.MethodPost, "/user-access-token", output) +} + +func secureURL(raw string) (*url.URL, error) { + u, err := url.Parse(raw) + if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.ForceQuery { + return nil, errors.New("invalid HTTPS endpoint") + } + return u, nil +} + +func (w *WMA) control(ctx context.Context, method, path string, output any) error { + ctx, stop := context.WithTimeout(ctx, 20*time.Second) + defer stop() + var body io.Reader + if method == http.MethodPost { + body = bytes.NewBufferString("{}") + } + req, err := http.NewRequestWithContext(ctx, method, w.base+path, body) + if err != nil { + return err + } + req.Header.Set("Accept", "application/json") + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + if strings.HasPrefix(w.config.APIKey, "ck_") { + req.Header.Set("X-Api-Key", w.config.APIKey) + } else { + req.Header.Set("Authorization", "Bearer "+w.config.APIKey) + } + res, err := w.client.Do(req) + if err != nil { + return fmt.Errorf("WMA control request: %w", err) + } + defer res.Body.Close() + if res.StatusCode < 200 || res.StatusCode >= 300 { + return fmt.Errorf("WMA control request: HTTP %d", res.StatusCode) + } + var envelope struct { + Code json.RawMessage `json:"code"` + Data json.RawMessage `json:"data"` + } + if err := json.NewDecoder(io.LimitReader(res.Body, 2<<20)).Decode(&envelope); err != nil || envelope.Code == nil { + return errors.New("invalid WMA control response") + } + code := strings.Trim(string(envelope.Code), `"`) + if code != "0" { + if errorCode.MatchString(code) { + return fmt.Errorf("WMA control request: API code %s", code) + } + return errors.New("WMA control request rejected") + } + if err := json.Unmarshal(envelope.Data, output); err != nil { + return errors.New("invalid WMA control response data") + } + return nil +} diff --git a/internal/managedagent/wma_live_test.go b/internal/managedagent/wma_live_test.go new file mode 100644 index 000000000..f6ec6ad81 --- /dev/null +++ b/internal/managedagent/wma_live_test.go @@ -0,0 +1,36 @@ +package managedagent + +import ( + "context" + "os" + "strings" + "testing" +) + +// Run with an existing dedicated Flash session and Tencent Cloud test credentials. +func TestWMATencentCloudLive(t *testing.T) { + session := os.Getenv("LF_WMA_E2E_SESSION_ID") + if session == "" { + t.Skip("set LF_WMA_E2E_SESSION_ID to run the live WMA test") + } + client, err := NewWMA(Config{ + AgentID: os.Getenv("LF_WMA_E2E_AGENT_ID"), SessionID: session, + TencentCloud: &TencentCloudConfig{ + SecretID: os.Getenv("AGENTFLOW_WMA_SECRET_ID"), SecretKey: os.Getenv("AGENTFLOW_WMA_SECRET_KEY"), + Token: os.Getenv("AGENTFLOW_WMA_SECURITY_TOKEN"), Region: os.Getenv("AGENTFLOW_WMA_REGION"), + }, + }, nil) + if err != nil { + t.Fatal(err) + } + const expected = "WMA_E2E_OK" + var streamed strings.Builder + result, err := client.Run(context.Background(), + "Only output WMA_E2E_OK. Do not call tools.", func(text string) { streamed.WriteString(text) }) + if err != nil { + t.Fatal(err) + } + if strings.TrimSpace(result) != expected || result != streamed.String() { + t.Fatalf("live WMA returned an unexpected result (%d bytes, %d streamed bytes)", len(result), streamed.Len()) + } +} diff --git a/internal/managedagent/wma_test.go b/internal/managedagent/wma_test.go new file mode 100644 index 000000000..18ae07a0f --- /dev/null +++ b/internal/managedagent/wma_test.go @@ -0,0 +1,156 @@ +package managedagent + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestWMATextAndCancellation(t *testing.T) { + for _, cancelPrompt := range []bool{false, true} { + t.Run(fmt.Sprintf("cancel=%t", cancelPrompt), func(t *testing.T) { + events := make(chan string, 8) + prompted, cancelled, closed := make(chan struct{}, 1), make(chan struct{}, 1), make(chan struct{}, 1) + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v2/") { + if r.Header.Get("X-Api-Key") != "ck_test" { + w.WriteHeader(http.StatusUnauthorized) + return + } + switch r.URL.Path { + case "/v2/enterprises/ent/managedagent/agents/agt/sessions/sess": + fmt.Fprintf(w, `{"code":0,"data":{"agentId":"agt","sessionId":"sess","endpointSet":[{"url":"https://%s","endpointType":"PUBLIC"}]}}`, r.Host) + case "/v2/enterprises/ent/managedagent/user-access-token": + fmt.Fprint(w, `{"code":0,"data":{"accessToken":"user-token"}}`) + default: + t.Errorf("unexpected control request %s", r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + return + } + if r.URL.Path != acpPath || r.Header.Get("Authorization") != "Bearer user-token" || r.Header.Get("X-Agent-Session-Id") != "sess" { + w.WriteHeader(http.StatusUnauthorized) + return + } + if r.Method == http.MethodGet { + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Acp-Connection-Id", "conn") + w.(http.Flusher).Flush() + for { + select { + case event := <-events: + fmt.Fprintf(w, "data: %s\n\n", event) + w.(http.Flusher).Flush() + case <-r.Context().Done(): + return + } + } + } + if r.Header.Get("Acp-Connection-Id") != "conn" { + w.WriteHeader(http.StatusBadRequest) + return + } + if r.Method == http.MethodDelete { + closed <- struct{}{} + w.WriteHeader(http.StatusNoContent) + return + } + var msg acpMessage + if err := json.NewDecoder(r.Body).Decode(&msg); err != nil { + t.Errorf("decode ACP request: %v", err) + w.WriteHeader(http.StatusBadRequest) + return + } + switch msg.Method { + case "initialize", "session/load": + if msg.Method == "session/load" { + events <- chunk("history should not be replayed") + } + events <- fmt.Sprintf(`{"jsonrpc":"2.0","id":%s,"result":{}}`, msg.ID) + w.WriteHeader(http.StatusAccepted) + case "session/prompt": + if !strings.Contains(string(msg.Params), "say hello") { + t.Error("prompt was not forwarded") + } + prompted <- struct{}{} + if cancelPrompt { + w.WriteHeader(http.StatusAccepted) + return + } + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprintf(w, ": heartbeat\n\ndata: %s\n\ndata: %s\n\n", chunk("hel"), chunk("lo")) + fmt.Fprintf(w, "data: {\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"stopReason\":\"end_turn\"}}\n\n", msg.ID) + case "session/cancel": + cancelled <- struct{}{} + w.WriteHeader(http.StatusAccepted) + default: + t.Errorf("unexpected RPC %s", msg.Method) + w.WriteHeader(http.StatusBadRequest) + } + })) + defer server.Close() + client, err := NewWMA(Config{ + Endpoint: server.URL, ACPOrigin: server.URL, EnterpriseID: "ent", AgentID: "agt", SessionID: "sess", APIKey: "ck_test", + }, server.Client()) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if cancelPrompt { + go func() { + select { + case <-prompted: + cancel() + case <-ctx.Done(): + } + }() + } + var output strings.Builder + text, err := client.Run(ctx, "say hello", func(delta string) { output.WriteString(delta) }) + if cancelPrompt { + if err == nil { + t.Fatal("expected interruption") + } + select { + case <-cancelled: + default: + t.Fatal("ACP cancellation was not sent") + } + } else if err != nil || text != "hello" || output.String() != text { + t.Fatalf("text = %q, observed = %q, err = %v", text, output.String(), err) + } + select { + case <-closed: + default: + t.Fatal("ACP connection was not closed") + } + }) + } +} + +func chunk(text string) string { + return fmt.Sprintf(`{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"sess","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":%q}}}}`, text) +} + +func TestWMARefusesUntrustedACPOrigin(t *testing.T) { + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasSuffix(r.URL.Path, "/agents/agt/sessions/sess") { + t.Errorf("made an unexpected credential request: %s", r.URL.Path) + } + fmt.Fprint(w, `{"code":0,"data":{"agentId":"agt","sessionId":"sess","endpointSet":[{"url":"https://agt.ma.workbuddy.cn.evil.test","endpointType":"PUBLIC"}]}}`) + })) + defer server.Close() + client, err := NewWMA(Config{Endpoint: server.URL, EnterpriseID: "ent", AgentID: "agt", SessionID: "sess", APIKey: "ck_test"}, server.Client()) + if err != nil { + t.Fatal(err) + } + if _, err := client.Run(context.Background(), "test", nil); err == nil || !strings.Contains(err.Error(), "no trusted ACP endpoint") { + t.Fatalf("unexpected error: %v", err) + } +} diff --git a/internal/opensandbox/client.go b/internal/opensandbox/client.go new file mode 100644 index 000000000..10d6492e2 --- /dev/null +++ b/internal/opensandbox/client.go @@ -0,0 +1,257 @@ +package opensandbox + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "strings" + "time" +) + +const ( + bindingMetadata = "loopforge-binding" + BootstrapPrefix = "lfos_" +) + +var ( + ErrNotFound = errors.New("OpenSandbox sandbox not found") + safeID = regexp.MustCompile("^[a-zA-Z0-9_-]{1,128}$") +) + +// RejectedError is a 4xx the provider answered definitively: the request was +// refused, so nothing was created. 408 and 429 are excluded by the client +// because there the outcome is unknown or the caller may simply retry. +type RejectedError struct { + Method string + Status int +} + +func (e *RejectedError) Error() string { + return fmt.Sprintf("OpenSandbox %s: HTTP %d", e.Method, e.Status) +} + +type Config struct { + Endpoint string `json:"endpoint"` + APIKey string `json:"apiKey"` + RunnerURL string `json:"runnerUrl"` + RunnerImage string `json:"runnerImage"` + Scope string `json:"scope"` + RunnerSigningKey string `json:"runnerSigningKey"` +} + +type Client struct { + config Config + base string + http http.Client +} + +type Sandbox struct { + ID string `json:"id"` + Metadata map[string]string `json:"metadata"` + Status struct { + State string `json:"state"` + } `json:"status"` +} + +func New(config Config, client *http.Client) (*Client, error) { + endpoint, err := cleanURL(config.Endpoint) + if err != nil || (endpoint.Path != "" && endpoint.Path != "/" && endpoint.Path != "/v1") { + return nil, errors.New("OpenSandbox endpoint must be a service origin or its /v1 base") + } + if _, err := cleanURL(config.RunnerURL); err != nil { + return nil, errors.New("OpenSandbox Runner callback URL is required") + } + if config.APIKey == "" || config.RunnerImage == "" || !safeID.MatchString(config.Scope) || len(config.RunnerSigningKey) < 32 { + return nil, errors.New("OpenSandbox requires an API key, Runner image, scope and Runner signing key of at least 32 bytes") + } + if client == nil { + client = http.DefaultClient + } + transport := *client + transport.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + return &Client{config: config, base: endpoint.Scheme + "://" + endpoint.Host + "/v1", http: transport}, nil +} + +func cleanURL(raw string) (*url.URL, error) { + u, err := url.Parse(raw) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" { + return nil, errors.New("invalid service URL") + } + return u, nil +} + +// WorkspaceFromBootstrap decodes the workspace locator. Verify the signature +// with its pinned backend before authorizing registration. +func WorkspaceFromBootstrap(token string) (string, bool) { + encoded, ok := strings.CutPrefix(token, BootstrapPrefix) + if !ok || len(encoded) > 220 { + return "", false + } + id, signature, ok := strings.Cut(encoded, ".") + if !ok || len(signature) != base64.RawURLEncoding.EncodedLen(sha256.Size) { + return "", false + } + workspace, err := base64.RawURLEncoding.DecodeString(id) + if err != nil || !safeID.Match(workspace) { + return "", false + } + return string(workspace), true +} + +func (c *Client) ValidBootstrap(token, workspace string) bool { + return hmac.Equal([]byte(token), []byte(c.bootstrap(workspace))) +} + +func (c *Client) bootstrap(workspace string) string { + mac := hmac.New(sha256.New, []byte(c.config.RunnerSigningKey)) + mac.Write([]byte(c.config.Scope + "/" + workspace)) + return BootstrapPrefix + base64.RawURLEncoding.EncodeToString([]byte(workspace)) + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) +} + +func (c *Client) binding(workspace string) string { + hash := sha256.Sum256([]byte(c.config.Scope + "/" + workspace)) + // OpenSandbox stores metadata as Kubernetes labels, limited to 63 characters. + return hex.EncodeToString(hash[:24]) +} + +// Find recovers a create whose response was lost. The provider may return +// multiple matches if an operator duplicated a resource; never select one. +func (c *Client) Find(ctx context.Context, workspace string) (Sandbox, error) { + binding := c.binding(workspace) + filter := url.Values{"metadata": {bindingMetadata + "=" + binding}, "pageSize": {"2"}} + var page struct { + Items []Sandbox `json:"items"` + Pagination struct { + HasNextPage bool `json:"hasNextPage"` + TotalItems int `json:"totalItems"` + } `json:"pagination"` + } + if err := c.do(ctx, http.MethodGet, "/sandboxes?"+filter.Encode(), nil, &page); err != nil { + return Sandbox{}, err + } + if len(page.Items) > 1 || page.Pagination.HasNextPage || page.Pagination.TotalItems > 1 { + return Sandbox{}, errors.New("multiple OpenSandbox sandboxes found for the workspace") + } + if len(page.Items) == 0 { + return Sandbox{}, ErrNotFound + } + sandbox := page.Items[0] + if !safeID.MatchString(sandbox.ID) || sandbox.Metadata[bindingMetadata] != binding { + return Sandbox{}, errors.New("OpenSandbox list returned an unexpected sandbox") + } + return sandbox, nil +} + +func (c *Client) Create(ctx context.Context, workspace string) (Sandbox, error) { + input := map[string]any{ + "image": map[string]string{"uri": c.config.RunnerImage}, + "entrypoint": []string{"/usr/local/bin/agentflow-runner", "-auto-update=false", "-concurrency=1"}, + "timeout": int((2 * time.Hour) / time.Second), + "resourceLimits": map[string]string{"cpu": "1", "memory": "2Gi"}, + "metadata": map[string]string{bindingMetadata: c.binding(workspace)}, + "env": map[string]string{ + "AGENTFLOW_SERVER_URL": c.config.RunnerURL, + "AGENTFLOW_RUNNER_BOOTSTRAP_TOKEN": c.bootstrap(workspace), + "AGENTFLOW_RUNNER_NAME": "OpenSandbox " + workspace, + "AGENTFLOW_RUNNER_STATE_PATH": "/home/runner/.agentflow-runner/state.json", + "AGENTFLOW_RUNNER_WORKSPACE": "/home/runner/workspace", + }, + } + var sandbox Sandbox + if err := c.do(ctx, http.MethodPost, "/sandboxes", input, &sandbox); err != nil { + return Sandbox{}, err + } + if !safeID.MatchString(sandbox.ID) { + return Sandbox{}, errors.New("OpenSandbox create did not return a valid sandbox ID") + } + return sandbox, nil +} + +func (c *Client) Inspect(ctx context.Context, workspace, id string) (Sandbox, error) { + if !safeID.MatchString(id) { + return Sandbox{}, errors.New("invalid OpenSandbox sandbox ID") + } + var sandbox Sandbox + if err := c.do(ctx, http.MethodGet, "/sandboxes/"+id, nil, &sandbox); err != nil { + return Sandbox{}, err + } + if sandbox.ID != id || sandbox.Metadata[bindingMetadata] != c.binding(workspace) { + return Sandbox{}, errors.New("OpenSandbox sandbox does not belong to the workspace") + } + return sandbox, nil +} + +func (c *Client) Release(ctx context.Context, workspace, id string) error { + if _, err := c.Inspect(ctx, workspace, id); err != nil { + if errors.Is(err, ErrNotFound) { + return nil + } + return err + } + err := c.do(ctx, http.MethodDelete, "/sandboxes/"+id, nil, nil) + if errors.Is(err, ErrNotFound) { + return nil + } + return err +} + +func (c *Client) do(ctx context.Context, method, path string, input, output any) error { + requestTimeout := 20 * time.Second + if method == http.MethodPost { + // Docker can pull an image and prepare the container before responding. + requestTimeout = 2 * time.Minute + } + ctx, cancel := context.WithTimeout(ctx, requestTimeout) + defer cancel() + var body io.Reader + if input != nil { + payload, err := json.Marshal(input) + if err != nil { + return err + } + body = bytes.NewReader(payload) + } + req, err := http.NewRequestWithContext(ctx, method, c.base+path, body) + if err != nil { + return err + } + req.Header.Set("OPEN-SANDBOX-API-KEY", c.config.APIKey) + req.Header.Set("Accept", "application/json") + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + res, err := c.http.Do(req) + if err != nil { + return fmt.Errorf("OpenSandbox %s: %w", method, err) + } + defer res.Body.Close() + if res.StatusCode == http.StatusNotFound && strings.HasPrefix(path, "/sandboxes/") { + return ErrNotFound + } + if res.StatusCode == http.StatusRequestTimeout || res.StatusCode == http.StatusTooManyRequests { + return fmt.Errorf("OpenSandbox %s: HTTP %d", method, res.StatusCode) + } + if res.StatusCode >= 400 && res.StatusCode < 500 { + return &RejectedError{Method: method, Status: res.StatusCode} + } + if res.StatusCode < 200 || res.StatusCode >= 300 { + return fmt.Errorf("OpenSandbox %s: HTTP %d", method, res.StatusCode) + } + if output == nil { + return nil + } + if err := json.NewDecoder(io.LimitReader(res.Body, 2<<20)).Decode(output); err != nil { + return fmt.Errorf("OpenSandbox %s: invalid response", method) + } + return nil +} diff --git a/internal/opensandbox/client_test.go b/internal/opensandbox/client_test.go new file mode 100644 index 000000000..868a8ffca --- /dev/null +++ b/internal/opensandbox/client_test.go @@ -0,0 +1,99 @@ +package opensandbox + +import ( + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + "time" +) + +func TestCreateAllowsColdImageStartup(t *testing.T) { + transport := &sandboxCreateTransport{} + client, err := New(Config{ + Endpoint: "https://sandbox.example", RunnerURL: "https://loopforge.example", + APIKey: "fixture", RunnerImage: "runner:test", Scope: "test", + RunnerSigningKey: strings.Repeat("x", 32), + }, &http.Client{Transport: transport}) + if err != nil { + t.Fatal(err) + } + if _, err := client.Create(context.Background(), "run-test"); err != nil { + t.Fatal(err) + } + if transport.budget < time.Minute || transport.budget > 2*time.Minute { + t.Fatalf("sandbox creation budget = %s, want between one and two minutes", transport.budget) + } +} + +type sandboxCreateTransport struct{ budget time.Duration } + +func (t *sandboxCreateTransport) RoundTrip(request *http.Request) (*http.Response, error) { + deadline, _ := request.Context().Deadline() + t.budget = time.Until(deadline) + return &http.Response{StatusCode: http.StatusAccepted, Body: io.NopCloser(strings.NewReader(`{"id":"sandbox-test"}`))}, nil +} + +// A definitive refusal must be distinguishable from an unknown outcome: only +// 408 and 429 (retryable, outcome unknown) stay plain errors. +func TestRequestStatusClassification(t *testing.T) { + cases := []struct { + name, method, path string + status int + rejected bool + notFound bool + plain bool + }{ + {"bad request", http.MethodPost, "/sandboxes", http.StatusBadRequest, true, false, false}, + {"forbidden", http.MethodPost, "/sandboxes", http.StatusForbidden, true, false, false}, + {"conflict", http.MethodPost, "/sandboxes", http.StatusConflict, true, false, false}, + {"unprocessable", http.MethodPost, "/sandboxes", http.StatusUnprocessableEntity, true, false, false}, + {"client timeout", http.MethodPost, "/sandboxes", http.StatusRequestTimeout, false, false, true}, + {"rate limited", http.MethodPost, "/sandboxes", http.StatusTooManyRequests, false, false, true}, + {"server error", http.MethodPost, "/sandboxes", http.StatusBadGateway, false, false, true}, + {"sandbox gone", http.MethodDelete, "/sandboxes/sbx-1", http.StatusNotFound, false, true, false}, + {"collection gone", http.MethodGet, "/sandboxes", http.StatusNotFound, true, false, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + transport := &statusTransport{method: tc.method, path: "/v1" + tc.path} + client, err := New(Config{ + Endpoint: "https://sandbox.example", RunnerURL: "https://loopforge.example", + APIKey: "fixture", RunnerImage: "runner:test", Scope: "test", + RunnerSigningKey: strings.Repeat("x", 32), + }, &http.Client{Transport: transport}) + if err != nil { + t.Fatal(err) + } + transport.response = &http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(""))} + err = client.do(context.Background(), tc.method, tc.path, nil, nil) + var rejected *RejectedError + if got := errors.As(err, &rejected); got != tc.rejected { + t.Fatalf("error %v classified as rejected=%v, want %v", err, got, tc.rejected) + } + if got := errors.Is(err, ErrNotFound); got != tc.notFound { + t.Fatalf("error %v classified as not-found=%v, want %v", err, got, tc.notFound) + } + if tc.plain && (err == nil || rejected != nil || errors.Is(err, ErrNotFound)) { + t.Fatalf("error %v should stay a plain retryable error", err) + } + if tc.rejected && (!strings.Contains(err.Error(), "HTTP") || !strings.Contains(err.Error(), tc.method)) { + t.Fatalf("rejected error %q lost the method/status text", err) + } + }) + } +} + +type statusTransport struct { + method, path string + response *http.Response +} + +func (t *statusTransport) RoundTrip(request *http.Request) (*http.Response, error) { + if request.Method != t.method || request.URL.Path != t.path { + return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(""))}, nil + } + return t.response, nil +} diff --git a/internal/repo/catalog.go b/internal/repo/catalog.go index e9ab1c4bb..9992ed270 100644 --- a/internal/repo/catalog.go +++ b/internal/repo/catalog.go @@ -392,6 +392,13 @@ func BuiltInExecutors() []domain.ExecutorDefinition { } func BuiltInExecutor(id string) (domain.ExecutorDefinition, bool) { + // Managed Agents use the role API and have no local CLI binary. + switch strings.TrimSpace(id) { + case domain.WMAExecutorID: + return domain.ExecutorDefinition{ID: domain.WMAExecutorID, Name: "WorkBuddy Managed Agent", Kind: domain.WMAExecutorID, Protocol: "acp"}, true + case domain.A2AExecutorID: + return domain.ExecutorDefinition{ID: domain.A2AExecutorID, Name: "External A2A Agent", Kind: domain.A2AExecutorID, Protocol: "json-rpc"}, true + } for _, executor := range BuiltInExecutors() { if executor.ID == strings.TrimSpace(id) { return executor, true diff --git a/internal/repo/mysql_live_test.go b/internal/repo/mysql_live_test.go index d6677be60..3d2b4cd0c 100644 --- a/internal/repo/mysql_live_test.go +++ b/internal/repo/mysql_live_test.go @@ -190,7 +190,7 @@ func TestMySQLRunnerTaskCompletionScrubsCredentials(t *testing.T) { if claimed.Invocation == nil || len(claimed.Invocation.GitSSHKeys) != 0 || claimed.Invocation.GitSSHUserID != 42 { t.Fatal("queue must retain the SSH credential reference only") } - if err := s.CompleteRunnerTask(claimed.ID, runnerID, domain.RunnerTaskSuccess, nil, "done", "", nil, nil, time.Now().UTC()); err != nil { + if err := s.CompleteRunnerTask(claimed.ID, runnerID, domain.RunnerTaskSuccess, nil, "done", "", "", nil, nil, time.Now().UTC()); err != nil { t.Fatal(err) } var payload string diff --git a/internal/repo/runner_scrub_test.go b/internal/repo/runner_scrub_test.go index 49b0dd5be..3ad986876 100644 --- a/internal/repo/runner_scrub_test.go +++ b/internal/repo/runner_scrub_test.go @@ -108,7 +108,7 @@ func TestRunnerTaskPayloadScrubbedOnTerminalTransitions(t *testing.T) { if err := st.PutRunnerTask(completed); err != nil { t.Fatalf("put completed task: %v", err) } - if err := st.CompleteRunnerTask("task-completed", "runner-1", domain.RunnerTaskSuccess, nil, "ok", "", nil, nil, now); err != nil { + if err := st.CompleteRunnerTask("task-completed", "runner-1", domain.RunnerTaskSuccess, nil, "ok", "", "", nil, nil, now); err != nil { t.Fatalf("complete task: %v", err) } assertPayloadScrubbed(t, st, "task-completed") diff --git a/internal/repo/runner_store_test.go b/internal/repo/runner_store_test.go index 1593e4267..6b3912745 100644 --- a/internal/repo/runner_store_test.go +++ b/internal/repo/runner_store_test.go @@ -249,7 +249,7 @@ func TestRunnerTaskLeaseLifecycle(t *testing.T) { } exit := 0 - if err := s.CompleteRunnerTask(task.ID, "runner-a", domain.RunnerTaskSuccess, &exit, "done", "", map[string]string{"plan": "# plan"}, nil, now); err != nil { + if err := s.CompleteRunnerTask(task.ID, "runner-a", domain.RunnerTaskSuccess, &exit, "done", "", "", map[string]string{"plan": "# plan"}, nil, now); err != nil { t.Fatal(err) } final, ok := s.RunnerTask(task.ID) @@ -263,7 +263,7 @@ func TestRunnerTaskLeaseLifecycle(t *testing.T) { t.Fatalf("task credentials survived completion: %+v", final.Invocation) } // Completing twice is rejected. - if err := s.CompleteRunnerTask(task.ID, "runner-a", domain.RunnerTaskFailed, nil, "", "", nil, nil, now); err != ErrRunnerTaskLeaseLost { + if err := s.CompleteRunnerTask(task.ID, "runner-a", domain.RunnerTaskFailed, nil, "", "", "", nil, nil, now); err != ErrRunnerTaskLeaseLost { t.Fatalf("double complete err = %v", err) } } @@ -408,3 +408,56 @@ func TestRunnerSessionLookup(t *testing.T) { t.Fatal("expired session resolved") } } + +// An external Agent turn that already started must not be requeued when its +// Runner goes away: the Agent holds the prompt, so a re-claim would run the +// same work twice. The row reports an unknown outcome, which the engine maps to +// a failure that never consumes another attempt. +func TestExpireRunnerTaskKeepsStartedExternalAgentUncertain(t *testing.T) { + s := newTestRunner(t) + now := time.Now().UTC() + started := domain.RunnerTask{ + ID: "rt-a2a-started", RunnerID: "runner-a", Provider: domain.A2AExecutorID, + Action: domain.RunnerTaskActionExternalAgent, Prompt: "do the work", MaxAttempts: 4, Status: domain.RunnerTaskQueued, + } + unstarted := domain.RunnerTask{ + ID: "rt-a2a-unstarted", RunnerID: "runner-a", Provider: domain.A2AExecutorID, + Action: domain.RunnerTaskActionExternalAgent, Prompt: "do the work", MaxAttempts: 4, Status: domain.RunnerTaskQueued, + } + for _, task := range []domain.RunnerTask{started, unstarted} { + if err := s.PutRunnerTask(task); err != nil { + t.Fatal(err) + } + } + if _, claimed, err := s.ClaimRunnerTask("runner-a", []string{domain.A2AExecutorID}, now, time.Second); err != nil || !claimed { + t.Fatalf("claim started task claimed=%v err=%v", claimed, err) + } + if err := s.StartRunnerTask("rt-a2a-started", "runner-a", now); err != nil { + t.Fatal(err) + } + if _, claimed, err := s.ClaimRunnerTask("runner-a", []string{domain.A2AExecutorID}, now, time.Second); err != nil || !claimed { + t.Fatalf("claim unstarted task claimed=%v err=%v", claimed, err) + } + + recovered, err := s.ExpireRunnerTasks(now.Add(2 * time.Second)) + if err != nil { + t.Fatal(err) + } + if len(recovered) != 2 { + t.Fatalf("recovered %d tasks, want 2", len(recovered)) + } + got, _ := s.RunnerTask("rt-a2a-started") + if got.Status != domain.RunnerTaskFailed || got.Code != domain.RunnerTaskUncertainOutcome { + t.Fatalf("started task = %s/%q, want failed/%s", got.Status, got.Code, domain.RunnerTaskUncertainOutcome) + } + if got.Attempt != 1 { + t.Fatalf("started task attempt = %d, want 1", got.Attempt) + } + // The same rule must not block a Runner that never started the task: the + // Agent never saw the prompt, so a re-claim is safe and cheaper than a + // failed node. + other, _ := s.RunnerTask("rt-a2a-unstarted") + if other.Status != domain.RunnerTaskQueued { + t.Fatalf("unstarted task status = %s, want queued", other.Status) + } +} diff --git a/internal/repo/runners.go b/internal/repo/runners.go index c6e458e2b..75883b12c 100644 --- a/internal/repo/runners.go +++ b/internal/repo/runners.go @@ -30,6 +30,7 @@ type runnerTaskPayload struct { ExitCode *int `json:"exitCode,omitempty"` Result string `json:"result,omitempty"` Error string `json:"error,omitempty"` + Code string `json:"code,omitempty"` StartedAt *runnerTaskTime `json:"startedAt,omitempty"` CompletedAt *runnerTaskTime `json:"completedAt,omitempty"` RunID string `json:"runId,omitempty"` @@ -116,6 +117,7 @@ func runnerTaskFromRow(row runnerTaskRow) domain.RunnerTask { t.ExitCode = p.ExitCode t.Result = p.Result t.Error = p.Error + t.Code = p.Code t.StartedAt = p.StartedAt.toTime() t.CompletedAt = p.CompletedAt.toTime() t.RunID = p.RunID @@ -143,7 +145,7 @@ func runnerTaskPayloadBytes(v domain.RunnerTask) []byte { } return mustJSON(runnerTaskPayload{ Prompt: v.Prompt, Workspace: v.Workspace, Args: v.Args, ExitCode: v.ExitCode, - Result: v.Result, Error: v.Error, StartedAt: newRunnerTaskTime(v.StartedAt), + Result: v.Result, Error: v.Error, Code: v.Code, StartedAt: newRunnerTaskTime(v.StartedAt), CompletedAt: newRunnerTaskTime(v.CompletedAt), RunID: v.RunID, NodeID: v.NodeID, Invocation: v.Invocation, Sandbox: v.Sandbox, Command: v.Command, Action: v.Action, PreviewArchive: v.PreviewArchive, WorkBranchMessage: v.WorkBranchMessage, Artifacts: v.Artifacts, @@ -622,10 +624,18 @@ func (r *RunnersRepo) RunnerTaskAvailable(runnerID string, providers []string) ( return false, nil } var rows []runnerTaskRow - err := r.DB.Select("id").Where("status = ? AND (runner_id = '' OR runner_id = ?) AND provider IN ?", domain.RunnerTaskQueued, runnerID, allowed).Limit(1).Find(&rows).Error + err := queuedTasksForRunner(r.DB.Select("id"), runnerID, allowed).Limit(1).Find(&rows).Error return len(rows) > 0, err } +func queuedTasksForRunner(db *gorm.DB, runnerID string, providers []string) *gorm.DB { + query := db.Where("status = ? AND provider IN ?", domain.RunnerTaskQueued, providers) + if domain.IsOpenSandboxRunner(runnerID) { + return query.Where("runner_id = ?", runnerID) + } + return query.Where("(runner_id = '' OR runner_id = ?)", runnerID) +} + // ClaimRunnerTask atomically leases the oldest queued task whose provider is // in the runner's available list and whose runner targeting (if any) matches. // The transactional claim guarantees exactly one winner even when several @@ -651,8 +661,7 @@ func (r *RunnersRepo) ClaimRunnerTask(runnerID string, providers []string, now t err := r.DB.Transaction(func(tx *gorm.DB) error { var rows []runnerTaskRow // Select only what the lease update needs; see RunnerTasks. - if err := r.locking(tx).Select("id", "attempt"). - Where("status = ? AND (runner_id = '' OR runner_id = ?) AND provider IN ?", domain.RunnerTaskQueued, runnerID, allowed). + if err := queuedTasksForRunner(r.locking(tx).Select("id", "attempt"), runnerID, allowed). Order("created_at").Limit(1). Find(&rows).Error; err != nil { return err @@ -742,7 +751,7 @@ func (r *RunnersRepo) RenewRunnerTaskLease(id, runnerID string, ttl time.Duratio // CompleteRunnerTask finalizes a task. Only the lease owner may complete it. // artifacts (legacy, by contract name) and outputs carry what the runner // reported about its workspace; either may be nil. -func (r *RunnersRepo) CompleteRunnerTask(id, runnerID, status string, exitCode *int, result, errMsg string, artifacts map[string]string, outputs *domain.RunnerTaskOutputs, now time.Time) error { +func (r *RunnersRepo) CompleteRunnerTask(id, runnerID, status string, exitCode *int, result, errMsg, code string, artifacts map[string]string, outputs *domain.RunnerTaskOutputs, now time.Time) error { if status != domain.RunnerTaskSuccess && status != domain.RunnerTaskFailed && status != domain.RunnerTaskCanceled { return fmt.Errorf("invalid final task status %q", status) } @@ -756,6 +765,7 @@ func (r *RunnersRepo) CompleteRunnerTask(id, runnerID, status string, exitCode * task.ExitCode = exitCode task.Result = result task.Error = errMsg + task.Code = code if artifacts != nil { task.Artifacts = artifacts } @@ -843,11 +853,20 @@ func (r *RunnersRepo) ExpireRunnerTasks(now time.Time) ([]domain.RunnerTask, err } for _, row := range rows { task := runnerTaskFromRow(row) - if task.Attempt < task.MaxAttempts { + // An external Agent turn that already started has reached the + // Agent; a lost lease only says this Runner stopped hearing from + // it. Neither requeueing the task nor letting the node retry can + // undo the work the Agent may still be doing, so the row reports + // an unknown outcome instead. + uncertain := task.Action == domain.RunnerTaskActionExternalAgent && task.StartedAt != nil + if task.Attempt < task.MaxAttempts && !uncertain { task.Status = domain.RunnerTaskQueued } else { task.Status = domain.RunnerTaskFailed task.Error = "lease expired" + if uncertain { + task.Code = domain.RunnerTaskUncertainOutcome + } completed := now task.CompletedAt = &completed scrubRunnerTaskCredentials(&task) diff --git a/internal/repo/runners_cases_test.go b/internal/repo/runners_cases_test.go index 9dc518db9..3d9e0eb9f 100644 --- a/internal/repo/runners_cases_test.go +++ b/internal/repo/runners_cases_test.go @@ -169,19 +169,19 @@ func TestRunnerTaskLeaseEventsExpiryCancellationAndDeregister(t *testing.T) { if control, ok := s.RunnerTaskControl(task.ID); !ok || control.DesiredState != domain.RunnerTaskDesiredCancel { t.Fatalf("control=%+v ok=%v", control, ok) } - if err := s.CompleteRunnerTask(task.ID, runner.ID, "invalid", nil, "", "", nil, nil, now); err == nil { + if err := s.CompleteRunnerTask(task.ID, runner.ID, "invalid", nil, "", "", "", nil, nil, now); err == nil { t.Fatal("invalid completion accepted") } exit := 0 outputs := &domain.RunnerTaskOutputs{Files: map[string]string{"result.md": "ok"}} - if err := s.CompleteRunnerTask(task.ID, runner.ID, domain.RunnerTaskSuccess, &exit, "done", "", map[string]string{"result": "body"}, outputs, now); err != nil { + if err := s.CompleteRunnerTask(task.ID, runner.ID, domain.RunnerTaskSuccess, &exit, "done", "", "", map[string]string{"result": "body"}, outputs, now); err != nil { t.Fatal(err) } completed, ok := s.RunnerTask(task.ID) if !ok || completed.Status != domain.RunnerTaskSuccess || completed.Invocation.CodexAPIKey != "" || completed.Invocation.Repository.GitToken != "" || completed.Invocation.Repositories[0].GitToken != "" { t.Fatalf("completed=%+v ok=%v", completed, ok) } - if err := s.CompleteRunnerTask(task.ID, runner.ID, domain.RunnerTaskSuccess, nil, "", "", nil, nil, now); !errors.Is(err, ErrRunnerTaskLeaseLost) { + if err := s.CompleteRunnerTask(task.ID, runner.ID, domain.RunnerTaskSuccess, nil, "", "", "", nil, nil, now); !errors.Is(err, ErrRunnerTaskLeaseLost) { t.Fatalf("double completion err=%v", err) } diff --git a/internal/runner/client.go b/internal/runner/client.go index 59701a062..9bc54d46b 100644 --- a/internal/runner/client.go +++ b/internal/runner/client.go @@ -329,10 +329,13 @@ func (c *Client) SendEvents(ctx context.Context, taskID string, events []domain. } type CompleteRequest struct { - Status string `json:"status"` - ExitCode *int `json:"exitCode"` - Result string `json:"result"` - Error string `json:"error"` + Status string `json:"status"` + ExitCode *int `json:"exitCode"` + Result string `json:"result"` + Error string `json:"error"` + // Code is a structured failure code the control plane acts on without + // parsing Error (e.g. domain.RunnerTaskUncertainOutcome). + Code string `json:"code,omitempty"` Artifacts map[string]string `json:"artifacts,omitempty"` Outputs *domain.RunnerTaskOutputs `json:"outputs,omitempty"` } diff --git a/internal/runner/daemon.go b/internal/runner/daemon.go index 9e7dff873..7e189228e 100644 --- a/internal/runner/daemon.go +++ b/internal/runner/daemon.go @@ -20,6 +20,7 @@ import ( "agentflow/internal/domain" "agentflow/internal/gitwork" + "agentflow/internal/managedagent" "agentflow/internal/procwatch" "agentflow/internal/runtime" ) @@ -84,6 +85,7 @@ type Config struct { // ManagedCLIRoot explicitly opts platform runners into managed CLI coordination. // Empty leaves ordinary user runners unchanged; it is never inferred from PATH. ManagedCLIRoot string + ExternalAgent managedagent.TextAgent } type daemonState struct { @@ -362,6 +364,9 @@ func (d *Daemon) refreshRuntimes(ctx context.Context) { return } } + if d.cfg.ExternalAgent != nil { + runtimes = append(runtimes, domain.RunnerRuntime{Provider: domain.A2AExecutorID, Status: domain.RuntimeStatusOnline}) + } d.mu.Lock() d.runtimes = runtimes d.mu.Unlock() @@ -577,6 +582,8 @@ func (d *Daemon) executeTask(ctx context.Context, task domain.RunnerTask) { result = execResult{status: domain.RunnerTaskFailed, errMsg: "未收到任务绑定的项目凭据"} case managed != nil && managed.err != nil: result = execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("pin managed CLI inventory: %v", managed.err)} + case task.Action == domain.RunnerTaskActionExternalAgent: + result = d.executeExternalAgent(ctx, task) case task.Action == domain.RunnerTaskActionCleanupRun: result = d.executeRunCleanup(ctx, task) case task.Action == domain.RunnerTaskActionArchivePreview: @@ -623,6 +630,9 @@ func (d *Daemon) executeTask(ctx context.Context, task domain.RunnerTask) { completeCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() req := CompleteRequest{Status: result.status, Result: result.result, Error: result.errMsg, Artifacts: artifacts, Outputs: result.outputs} + if result.uncertain { + req.Code = domain.RunnerTaskUncertainOutcome + } if result.status == domain.RunnerTaskFailed || result.status == domain.RunnerTaskSuccess { exit := result.exitCode req.ExitCode = &exit diff --git a/internal/runner/daemon_test.go b/internal/runner/daemon_test.go index e20f8d696..74d4e6f4a 100644 --- a/internal/runner/daemon_test.go +++ b/internal/runner/daemon_test.go @@ -686,7 +686,7 @@ func TestDaemonExecuteProcessRunsRealCommand(t *testing.T) { if strings.Contains(result.result, "file already closed") { t.Fatalf("stream error leaked into result %q", result.result) } - if err := s.CompleteRunnerTask("rt-echo", daemon.runnerID(), domain.RunnerTaskSuccess, &result.exitCode, result.result, result.errMsg, nil, nil, time.Now().UTC()); err != nil { + if err := s.CompleteRunnerTask("rt-echo", daemon.runnerID(), domain.RunnerTaskSuccess, &result.exitCode, result.result, result.errMsg, "", nil, nil, time.Now().UTC()); err != nil { t.Fatal(err) } final, _ := s.RunnerTask("rt-echo") @@ -737,7 +737,7 @@ func TestExecuteProcessCapturesFastCommandStdout(t *testing.T) { if strings.Contains(result.result, "file already closed") { t.Fatalf("iter %d leaked stream error into result: %q", i, result.result) } - if err := s.CompleteRunnerTask(id, daemon.runnerID(), domain.RunnerTaskSuccess, &result.exitCode, result.result, result.errMsg, nil, nil, time.Now().UTC()); err != nil { + if err := s.CompleteRunnerTask(id, daemon.runnerID(), domain.RunnerTaskSuccess, &result.exitCode, result.result, result.errMsg, "", nil, nil, time.Now().UTC()); err != nil { t.Fatal(err) } } diff --git a/internal/runner/exec.go b/internal/runner/exec.go index 95bc97c77..b088ce2e7 100644 --- a/internal/runner/exec.go +++ b/internal/runner/exec.go @@ -280,6 +280,10 @@ type execResult struct { result string errMsg string outputs *domain.RunnerTaskOutputs + // uncertain marks a failure whose remote outcome is unknown: the work was + // handed to an external Agent that may still be running. The control plane + // must not retry it automatically. + uncertain bool } // executeProcess spawns the Agent CLI in its own process group so a cancel diff --git a/internal/runner/external_agent.go b/internal/runner/external_agent.go new file mode 100644 index 000000000..f60ae10af --- /dev/null +++ b/internal/runner/external_agent.go @@ -0,0 +1,50 @@ +package runner + +import ( + "context" + "errors" + + "agentflow/internal/domain" + "agentflow/internal/managedagent" +) + +func (d *Daemon) executeExternalAgent(ctx context.Context, task domain.RunnerTask) execResult { + if task.Provider != domain.A2AExecutorID || d.cfg.ExternalAgent == nil { + return execResult{status: domain.RunnerTaskFailed, errMsg: "local A2A Agent is not configured"} + } + if err := d.client.StartTask(ctx, task.ID); err != nil { + return execResult{status: domain.RunnerTaskFailed, errMsg: "could not start leased A2A task"} + } + ctx, cancel := context.WithCancel(ctx) + defer cancel() + go func() { + select { + case desired := <-d.taskControl(task.ID): + if desired == domain.RunnerTaskDesiredCancel { + cancel() + } + case <-ctx.Done(): + } + }() + batch := newEventBatcher(task, d.client) + output, err := d.cfg.ExternalAgent.Run(ctx, task.Prompt, func(text string) { + batch.addObservation(domain.TelemetryEvent{Category: "output", Name: "agent.output", Phase: "progress", Message: text, Provider: domain.A2AExecutorID}) + batch.flush(ctx) + }) + if ctx.Err() != nil { + return execResult{status: domain.RunnerTaskCanceled} + } + if err != nil { + // A completed turn or a provider error is a final answer; a turn that + // ran past its budget is not. The prompt already reached the Agent and + // the cancel was advisory, so the control plane must not resend it. + // The sentinel cannot survive the completion report as an error value, + // so it travels as a structured code instead of the message text. + result := execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()} + if errors.Is(err, managedagent.ErrTurnTimedOut) { + result.uncertain = true + } + return result + } + return execResult{status: domain.RunnerTaskSuccess, result: output} +} diff --git a/internal/runner/external_agent_test.go b/internal/runner/external_agent_test.go new file mode 100644 index 000000000..0d7b72069 --- /dev/null +++ b/internal/runner/external_agent_test.go @@ -0,0 +1,297 @@ +package runner + +import ( + "crypto/tls" + "crypto/x509" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "agentflow/internal/domain" + "agentflow/internal/managedagent" + "agentflow/internal/repo" +) + +func TestExternalA2ASOP(t *testing.T) { + for _, target := range []string{domain.ExternalAgentRunner, domain.ExternalAgentRemote} { + t.Run(target, func(t *testing.T) { + api, store, eng := newDaemonTestServer(t) + if err := store.PutProject(domain.Project{ID: "external-test", Key: "external-test", Name: "External Agent", OwnerID: 42}); err != nil { + t.Fatal(err) + } + local := target == domain.ExternalAgentRunner + expected := "A2A_" + strings.ToUpper(target) + "_OK" + connector := externalAgentTestConnector(t, local, expected) + if local { + runner, _ := startPoolRunnerWithConfig(t, store, Config{ + ServerURL: api.URL, BootstrapToken: "boot-secret", Name: "personal-external-agent", + StatePath: filepath.Join(t.TempDir(), "state.json"), DefaultWorkspaceRoot: t.TempDir(), + HeartbeatInterval: time.Second, LongPollTimeout: 2 * time.Second, + DisableAutoUpdate: true, ExternalAgent: connector, + }) + runner.OwnerUserID = 42 + if err := store.PutRunner(runner); err != nil { + t.Fatal(err) + } + if err := store.SetRunnerSharedProjects(runner.ID, 42, []string{"external-test"}); err != nil { + t.Fatal(err) + } + if err := store.SetDefaultRunner(42, runner.ID, time.Now().UTC()); err != nil { + t.Fatal(err) + } + } else if err := eng.ConfigureManagedAgent(domain.A2AExecutorID, "external-test", 42, connector); err != nil { + t.Fatal(err) + } + if !eng.ManagedAgentAvailable("external-test", 42, domain.A2AExecutorID) { + t.Fatal("A2A Agent is missing from the role editor's availability check") + } + + role := domain.AgentDefinition{ID: "custom-agent", Name: "Custom Agent", ExecutorID: domain.A2AExecutorID, ExternalAgentTarget: target, Prompt: "{{input}}"} + if err := store.PutAgent(role); err != nil { + t.Fatal(err) + } + wf := domain.WorkflowDefinition{ + ID: "external-agent-sop", Name: "External Agent LOOP", SandboxProfileID: repo.TestNativeSandboxID, + Nodes: []domain.WorkflowNode{ + {ID: "agent", Name: "Agent", Type: "agent", AgentID: role.ID, MaxAttempts: 1}, + }, + } + if err := store.PutWorkflow(wf); err != nil { + t.Fatal(err) + } + requirements, err := eng.SOPExecutorRequirements(wf, 42, "external-test") + if err != nil || len(requirements) != 1 || requirements[0].Kind != domain.A2AExecutorID || !requirements[0].Configured { + t.Fatalf("unexpected LOOP prerequisites: %v, %v", requirements, err) + } + run, err := eng.StartWithExecutionContext(wf.ID, "Reply with exactly "+expected+" and nothing else.", domain.RepositoryContext{}, + domain.TelemetryContext{ProjectID: "external-test", ResponsibleUserID: 42}) + if err != nil { + t.Fatal(err) + } + waitFor(t, time.Minute, "external Agent LOOP", func() bool { + current, _ := store.Run(run.ID) + return current.Status == "succeeded" || current.Status == "failed" + }) + final, _ := store.Run(run.ID) + if final.Status != "succeeded" || strings.TrimSpace(final.Nodes["agent"].Output) != expected { + t.Fatalf("LOOP status %s: Agent error %q", final.Status, final.Nodes["agent"].Error) + } + if len(final.Artifacts) != 1 || final.Artifacts[0].NodeID != "agent" || final.Artifacts[0].Path != "result.md" || strings.TrimSpace(final.Artifacts[0].Content) != expected { + t.Fatalf("unexpected A2A result artifact: %+v", final.Artifacts) + } + for _, task := range store.RunnerTasks() { + if task.Action != domain.RunnerTaskActionExternalAgent { + continue + } + if !local || task.RunnerID != run.ExecutionContext.ExecutionRunnerID || task.Status != domain.RunnerTaskSuccess { + t.Fatalf("unexpected external Agent task %s on %s", task.Status, task.RunnerID) + } + return + } + if local { + t.Fatal("personal Agent did not receive a Runner task") + } + }) + } +} + +func externalAgentTestConnector(t *testing.T, local bool, expected string) *managedagent.A2A { + t.Helper() + key := "a2a-test-only" + var client *http.Client + env := "LF_A2A_E2E_REMOTE" + if local { + env = "LF_A2A_E2E_RUNNER" + } + endpoint := os.Getenv(env + "_URL") + if endpoint == "" { + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer "+key || r.Method != http.MethodPost { + w.WriteHeader(http.StatusUnauthorized) + return + } + var request struct { + Method string `json:"method"` + Params json.RawMessage `json:"params"` + } + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + text := []map[string]string{{"kind": "text", "text": expected}} + var result any + switch request.Method { + case "message/send": + if !strings.Contains(string(request.Params), expected) { + t.Error("the task prompt is missing the test request") + } + if local { + result = map[string]any{"kind": "task", "id": "async-task", "status": map[string]string{"state": "working"}} + } else { + result = map[string]any{"kind": "message", "role": "agent", "parts": text} + } + case "tasks/get": + result = map[string]any{ + "kind": "task", "id": "async-task", "status": map[string]string{"state": "completed"}, + "artifacts": []any{map[string]any{"parts": text}}, + } + default: + t.Errorf("unexpected Agent method %s", request.Method) + w.WriteHeader(http.StatusBadRequest) + return + } + json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": 1, "result": result}) + }) + var server *httptest.Server + if local { + server = httptest.NewServer(handler) + } else { + server = httptest.NewTLSServer(handler) + } + t.Cleanup(server.Close) + endpoint, client = server.URL, server.Client() + } else { + key = os.Getenv(env + "_TOKEN") + if ca := os.Getenv(env + "_CA"); ca != "" { + pem, err := os.ReadFile(ca) + if err != nil { + t.Fatal(err) + } + roots := x509.NewCertPool() + if !roots.AppendCertsFromPEM(pem) { + t.Fatal("invalid test CA") + } + client = &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}}} + } + } + connector, err := managedagent.NewA2A(managedagent.A2AConfig{Endpoint: endpoint, Token: key, Loopback: local}, client) + if err != nil { + t.Fatal(err) + } + return connector +} + +// TestExternalA2ATurnTimeoutIsNotResent covers a turn that runs past its +// budget on either target. The prompt already reached the Agent and the cancel +// is advisory, so the node must stop on the current attempt instead of sending +// the same work again: for a personal Runner the "unknown outcome" code has to +// survive the completion API, where the error value does not. +func TestExternalA2ATurnTimeoutIsNotResent(t *testing.T) { + for _, target := range []string{domain.ExternalAgentRunner, domain.ExternalAgentRemote} { + t.Run(target, func(t *testing.T) { + var sends, cancels atomic.Int32 + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var request struct { + Method string `json:"method"` + Params json.RawMessage `json:"params"` + } + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + var result any + switch request.Method { + case "message/send": + sends.Add(1) + result = map[string]any{"kind": "task", "id": "stuck-task", "status": map[string]string{"state": "working"}} + case "tasks/get": + result = map[string]any{"kind": "task", "id": "stuck-task", "status": map[string]string{"state": "working"}} + case "tasks/cancel": + cancels.Add(1) + result = map[string]any{"kind": "task", "id": "stuck-task", "status": map[string]string{"state": "canceled"}} + default: + t.Errorf("unexpected Agent method %s", request.Method) + w.WriteHeader(http.StatusBadRequest) + return + } + json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": 1, "result": result}) + }) + var server *httptest.Server + if target == domain.ExternalAgentRunner { + server = httptest.NewServer(handler) + } else { + server = httptest.NewTLSServer(handler) + } + t.Cleanup(server.Close) + connector, err := managedagent.NewA2A(managedagent.A2AConfig{ + Endpoint: server.URL, Token: "a2a-test-only", Loopback: target == domain.ExternalAgentRunner, + }, server.Client()) + if err != nil { + t.Fatal(err) + } + previous := managedagent.TurnTimeout() + managedagent.SetTurnTimeout(1500 * time.Millisecond) + t.Cleanup(func() { managedagent.SetTurnTimeout(previous) }) + + api, store, eng := newDaemonTestServer(t) + if err := store.PutProject(domain.Project{ID: "turn-timeout", Key: "turn-timeout", Name: "Turn Timeout", OwnerID: 42}); err != nil { + t.Fatal(err) + } + if target == domain.ExternalAgentRunner { + runner, _ := startPoolRunnerWithConfig(t, store, Config{ + ServerURL: api.URL, BootstrapToken: "boot-secret", Name: "personal-turn-timeout", + StatePath: filepath.Join(t.TempDir(), "state.json"), DefaultWorkspaceRoot: t.TempDir(), + HeartbeatInterval: time.Second, LongPollTimeout: 2 * time.Second, + DisableAutoUpdate: true, ExternalAgent: connector, + }) + runner.OwnerUserID = 42 + if err := store.PutRunner(runner); err != nil { + t.Fatal(err) + } + if err := store.SetRunnerSharedProjects(runner.ID, 42, []string{"turn-timeout"}); err != nil { + t.Fatal(err) + } + if err := store.SetDefaultRunner(42, runner.ID, time.Now().UTC()); err != nil { + t.Fatal(err) + } + } else if err := eng.ConfigureManagedAgent(domain.A2AExecutorID, "turn-timeout", 42, connector); err != nil { + t.Fatal(err) + } + role := domain.AgentDefinition{ID: "stuck-agent", Name: "Stuck Agent", ExecutorID: domain.A2AExecutorID, ExternalAgentTarget: target, Prompt: "{{input}}"} + if err := store.PutAgent(role); err != nil { + t.Fatal(err) + } + wf := domain.WorkflowDefinition{ + ID: "turn-timeout-sop", Name: "Turn Timeout LOOP", SandboxProfileID: repo.TestNativeSandboxID, + Nodes: []domain.WorkflowNode{{ID: "agent", Name: "Agent", Type: "agent", AgentID: role.ID, MaxAttempts: 3}}, + } + if err := store.PutWorkflow(wf); err != nil { + t.Fatal(err) + } + run, err := eng.StartWithExecutionContext(wf.ID, "do the work", domain.RepositoryContext{}, + domain.TelemetryContext{ProjectID: "turn-timeout", ResponsibleUserID: 42}) + if err != nil { + t.Fatal(err) + } + waitFor(t, 90*time.Second, "turn timeout LOOP", func() bool { + current, _ := store.Run(run.ID) + return current.Status == "succeeded" || current.Status == "failed" + }) + final, _ := store.Run(run.ID) + node := final.Nodes["agent"] + if final.Status != "failed" { + t.Fatalf("LOOP status %q, want failed (node error %q)", final.Status, node.Error) + } + if got := sends.Load(); got != 1 { + t.Fatalf("message/send count = %d, want 1: an unknown turn must not be resent", got) + } + if got := node.Attempt; got != 1 { + t.Fatalf("final attempt = %d, want 1: a timed-out turn must not consume the remaining attempts", got) + } + if got := cancels.Load(); got != 1 { + t.Fatalf("tasks/cancel count = %d, want 1", got) + } + if !strings.Contains(node.Error, "未在") || !strings.Contains(node.Error, "请求取消") { + t.Fatalf("node error %q does not explain the timeout", node.Error) + } + }) + } +} diff --git a/internal/runner/opensandbox_test.go b/internal/runner/opensandbox_test.go new file mode 100644 index 000000000..d1805a920 --- /dev/null +++ b/internal/runner/opensandbox_test.go @@ -0,0 +1,263 @@ +package runner + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "net/http/httptest" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "agentflow/internal/domain" + "agentflow/internal/managedagent" + "agentflow/internal/opensandbox" + "agentflow/internal/repo" +) + +type testManagedAgent struct{} + +func (testManagedAgent) Run(_ context.Context, prompt string, onText func(string)) (string, error) { + if !strings.Contains(prompt, "describe the change") { + return "", errors.New("the WMA task book is missing the run input") + } + onText("wma-plan") + return "wma-plan", nil +} + +func TestOpenSandboxMixedSOP(t *testing.T) { + api, store, eng := newDaemonTestServer(t) + var wma managedagent.TextAgent = testManagedAgent{} + input := "describe the change" + if session := os.Getenv("LF_WMA_E2E_SESSION_ID"); session != "" { + client, err := managedagent.NewWMA(managedagent.Config{ + AgentID: os.Getenv("LF_WMA_E2E_AGENT_ID"), SessionID: session, + TencentCloud: &managedagent.TencentCloudConfig{ + SecretID: os.Getenv("AGENTFLOW_WMA_SECRET_ID"), SecretKey: os.Getenv("AGENTFLOW_WMA_SECRET_KEY"), + Token: os.Getenv("AGENTFLOW_WMA_SECURITY_TOKEN"), Region: os.Getenv("AGENTFLOW_WMA_REGION"), + }, + }, nil) + if err != nil { + t.Fatal(err) + } + wma = client + input = "Only output wma-plan. Do not add quotes, decoration, or explanations. Do not call tools." + } + if err := eng.ConfigureManagedAgent(domain.WMAExecutorID, "sandbox-pilot", 42, wma); err != nil { + t.Fatal(err) + } + + endpoint := os.Getenv("LF_OPENSANDBOX_E2E_URL") + runnerURL, key, image := api.URL, "mock-api-key", "runner:test" + var repoContext domain.RepositoryContext + if endpoint == "" { + endpoint = startOpenSandboxFixture(t, api.URL) + private := os.Getenv("LF_OPENSANDBOX_PRIVATE_SNAPSHOT") + if private == "" { + private = bareRemoteWithBaseline(t) + } + branch := runGitT(t, private, "symbolic-ref", "--short", "HEAD") + repoContext = domain.RepositoryContext{RepositoryID: "fixture", Name: "sandbox fixture", CloneURL: private, BaseBranch: branch, WorkBranch: "pilot/verify"} + } else { + runnerURL = exposeRunnerTestAPI(t, api.URL, os.Getenv("LF_OPENSANDBOX_E2E_BIND_HOST")) + key, image = os.Getenv("LF_OPENSANDBOX_E2E_API_KEY"), os.Getenv("LF_OPENSANDBOX_E2E_IMAGE") + } + provider, err := opensandbox.New(opensandbox.Config{ + Endpoint: endpoint, APIKey: key, RunnerURL: runnerURL, RunnerImage: image, + Scope: "runner-integration-test", RunnerSigningKey: strings.Repeat("test", 10), + }, nil) + if err != nil { + t.Fatal(err) + } + if err := eng.ConfigureOpenSandbox("sandbox-test", provider, []string{"sandbox-pilot"}); err != nil { + t.Fatal(err) + } + if err := store.PutRunnerTask(domain.RunnerTask{ID: "unrelated", Provider: "terminal", Status: domain.RunnerTaskQueued, MaxAttempts: 1}); err != nil { + t.Fatal(err) + } + role := domain.AgentDefinition{ID: "wma-planner", Name: "WMA planner", ExecutorID: domain.WMAExecutorID, Prompt: "{{input}}", ProjectID: "sandbox-pilot"} + if err := store.PutAgent(role); err != nil { + t.Fatal(err) + } + wf := domain.WorkflowDefinition{ + ID: "mixed-execution", Name: "Mixed execution", SandboxProfileID: repo.TestNativeSandboxID, + Nodes: []domain.WorkflowNode{ + {ID: "plan", Name: "WMA plan", Type: "agent", AgentID: role.ID, MaxAttempts: 1}, + {ID: "prepare", Name: "Prepare", Type: "script", Script: `set -eu; test "$(cat .agentflow/inputs/plan/result.md)" = wma-plan; printf 'proof\n' > lf-sandbox-proof.txt`, MaxAttempts: 1}, + {ID: "verify", Name: "Verify", Type: "script", Script: `set -eu; test "$(cat lf-sandbox-proof.txt)" = proof; printf 'shared workspace verified\n'`, MaxAttempts: 1}, + }, + Edges: []domain.WorkflowEdge{ + {ID: "plan-prepare", Source: "plan", Target: "prepare", When: "success"}, + {ID: "prepare-verify", Source: "prepare", Target: "verify", When: "success"}, + }, + } + if err := store.PutWorkflow(wf); err != nil { + t.Fatal(err) + } + run, err := eng.StartWithExecutionContext(wf.ID, input, repoContext, domain.TelemetryContext{ProjectID: "sandbox-pilot", ResponsibleUserID: 42}) + if err != nil { + t.Fatal(err) + } + if run.ExecutionContext.ExecutionProviderID != "sandbox-test" || run.ExecutionContext.ExecutionRunnerID != domain.OpenSandboxRunnerID(run.ID) { + t.Fatalf("unexpected Runner binding: %q", run.ExecutionContext.ExecutionRunnerID) + } + waitFor(t, 150*time.Second, "mixed SOP to finish", func() bool { + final, _ := store.Run(run.ID) + return final.Status == "succeeded" || final.Status == "failed" + }) + final, _ := store.Run(run.ID) + if final.Status != "succeeded" { + t.Fatalf("run %s: plan=%s prepare=%s verify=%s", final.Status, final.Nodes["plan"].Error, final.Nodes["prepare"].Error, final.Nodes["verify"].Error) + } + if !strings.Contains(final.Nodes["verify"].Output, "shared workspace verified") || strings.TrimSpace(final.Nodes["plan"].Output) != "wma-plan" { + t.Fatalf("plan and verify outputs: %q, %q", final.Nodes["plan"].Output, final.Nodes["verify"].Output) + } + unrelated, _ := store.RunnerTask("unrelated") + if unrelated.Status != domain.RunnerTaskQueued || unrelated.LeaseOwner != "" { + t.Fatalf("workspace Runner claimed unrelated task: %+v", unrelated) + } + registeredID := final.ExecutionContext.ExecutionRunnerID + externalID := final.ExecutionContext.ExecutionResourceID + if externalID == "" { + t.Fatal("sandbox binding was not persisted") + } + waitFor(t, 25*time.Second, "sandbox and Runner release", func() bool { + _, present := store.Runner(registeredID) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _, err := provider.Inspect(ctx, run.ID, externalID) + return !present && errors.Is(err, opensandbox.ErrNotFound) + }) + t.Logf("workspace %s used OpenSandbox %s with Runner %s", run.ID, externalID, registeredID) +} + +// startOpenSandboxFixture speaks the lifecycle HTTP contract and boots the +// actual Runner daemon on the host. The optional real test uses the same SOP. +func startOpenSandboxFixture(t *testing.T, runnerURL string) string { + t.Helper() + ctx, stop := context.WithCancel(context.Background()) + root := t.TempDir() + var mu sync.Mutex + var metadata map[string]string + var daemonDone chan struct{} + created := false + fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + if r.Header.Get("OPEN-SANDBOX-API-KEY") != "mock-api-key" { + w.WriteHeader(http.StatusUnauthorized) + return + } + w.Header().Set("Content-Type", "application/json") + record := func() any { + return map[string]any{"id": "sandbox-1", "metadata": metadata, "status": map[string]string{"state": "Running"}} + } + switch r.Method + " " + r.URL.Path { + case "GET /v1/sandboxes": + items := []any{} + if created { + items = append(items, record()) + } + json.NewEncoder(w).Encode(map[string]any{"items": items, "pagination": map[string]int{"totalItems": len(items)}}) + case "POST /v1/sandboxes": + if created { + t.Error("test SOP allocated a second sandbox") + w.WriteHeader(http.StatusConflict) + return + } + var request struct { + Env map[string]string `json:"env"` + Metadata map[string]string `json:"metadata"` + } + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + t.Errorf("decode OpenSandbox create: %v", err) + w.WriteHeader(http.StatusBadRequest) + return + } + if value := request.Metadata["loopforge-binding"]; len(value) == 0 || len(value) > 63 { + t.Errorf("OpenSandbox binding is not a Kubernetes label value: %q", value) + w.WriteHeader(http.StatusBadRequest) + return + } + cfg := Config{ + ServerURL: runnerURL, BootstrapToken: request.Env["AGENTFLOW_RUNNER_BOOTSTRAP_TOKEN"], + Name: request.Env["AGENTFLOW_RUNNER_NAME"], MaxConcurrency: 1, DisableAutoUpdate: true, + StatePath: filepath.Join(root, "state.json"), DefaultWorkspaceRoot: filepath.Join(root, "workspace"), + HeartbeatInterval: time.Second, LongPollTimeout: 2 * time.Second, + } + daemon, err := New(cfg) + if err != nil { + t.Errorf("start fixture Runner: %v", err) + w.WriteHeader(http.StatusBadRequest) + return + } + metadata, created = request.Metadata, true + done := make(chan struct{}) + daemonDone = done + go func() { + defer close(done) + if err := daemon.Run(ctx); err != nil && ctx.Err() == nil { + t.Errorf("fixture Runner: %v", err) + } + }() + w.WriteHeader(http.StatusAccepted) + json.NewEncoder(w).Encode(record()) + case "GET /v1/sandboxes/sandbox-1": + if !created { + w.WriteHeader(http.StatusNotFound) + return + } + json.NewEncoder(w).Encode(record()) + case "DELETE /v1/sandboxes/sandbox-1": + created = false + stop() + w.WriteHeader(http.StatusNoContent) + default: + t.Errorf("unexpected lifecycle request %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(func() { + fixture.Close() + stop() + if daemonDone != nil { + select { + case <-daemonDone: + case <-time.After(5 * time.Second): + t.Error("fixture Runner did not stop") + } + } + }) + return fixture.URL +} + +func exposeRunnerTestAPI(t *testing.T, target, bindHost string) string { + t.Helper() + if net.ParseIP(bindHost) == nil { + t.Fatal("LF_OPENSANDBOX_E2E_BIND_HOST must be the test cluster's host bridge IP") + } + upstream, err := url.Parse(target) + if err != nil { + t.Fatal(err) + } + listener, err := net.Listen("tcp", net.JoinHostPort(bindHost, "0")) + if err != nil { + t.Fatal(err) + } + server := &http.Server{Handler: httputil.NewSingleHostReverseProxy(upstream), ReadHeaderTimeout: 5 * time.Second} + go func() { + if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) { + t.Error(err) + } + }() + t.Cleanup(func() { server.Close() }) + return fmt.Sprintf("http://%s", listener.Addr()) +} diff --git a/internal/runtime/sandbox_process.go b/internal/runtime/sandbox_process.go index c551bee45..f173f2995 100644 --- a/internal/runtime/sandbox_process.go +++ b/internal/runtime/sandbox_process.go @@ -61,6 +61,7 @@ func controlledBaseEnvironment(base []string) []string { "CLAUDE_CODE_OAUTH_TOKEN=", "CODEX_HOME=", "CLAUDE_CONFIG_DIR=", "CLAUDE_CODE_USE_BEDROCK=", "CLAUDE_CODE_USE_VERTEX=", "CLAUDE_CODE_USE_FOUNDRY=", "CODEBUDDY_INTERNET_ENVIRONMENT=", + "AGENTFLOW_WMA_", "AGENTFLOW_OPENSANDBOX_", "AGENTFLOW_A2A_", "AGENTFLOW_RUNNER_A2A_", "AGENTFLOW_RUNNER_BOOTSTRAP_TOKEN=", "AGENTFLOW_GIT_TOKEN=", "AGENTFLOW_PROJECT_CREDENTIAL_KEY=", "GH_TOKEN=", diff --git a/web/app/agents.js b/web/app/agents.js index 2a78c75eb..b39c6b615 100644 --- a/web/app/agents.js +++ b/web/app/agents.js @@ -11,7 +11,7 @@ function renderAgents(){ const empty=state.agentScope==='shared'?'还没有共享给当前项目的角色。':'当前项目还没有角色。可以新建,或从共享角色复制后改。'; closeAgentRowMenu(); state.agentUsage=used; - const rows=agents.map(a=>{const exec=(state.data.executors||[]).find(x=>x.id===a.executorId);const model=a.model||exec?.model||exec?.name||'';const uses=used.get(a.id)||0;return`
${escapeHTML(a.name)}${agentRowTag(a)}${escapeHTML(a.description||'未填写职责')}
${escapeHTML(model||'未选模型')}
${agentConfigSummary(a)}
${uses?`${uses} 个节点`:'未使用'}
`}).join(''); + const rows=agents.map(a=>{const exec=(state.data.executors||[]).find(x=>x.id===a.executorId);const model=a.model||exec?.model||exec?.name||managedAgentExecutors.find(item=>item.id===a.executorId)?.name||'';const uses=used.get(a.id)||0;return`
${escapeHTML(a.name)}${agentRowTag(a)}${escapeHTML(a.description||'未填写职责')}
${escapeHTML(model||'未选模型')}
${agentConfigSummary(a)}
${uses?`${uses} 个节点`:'未使用'}
`}).join(''); const head=''; list.innerHTML=rows?head+rows:(query&&scopedAgents().length?'
AI没有匹配的角色。

调整搜索,或新建一个角色。

':`
AI${empty}

调整搜索,或新建一个角色。

`); list.querySelectorAll('[data-agent-more]').forEach(btn=>btn.onclick=e=>{e.stopPropagation();openAgentRowMenu(btn,state.data.agents.find(a=>a.id===btn.dataset.agentMore))}); @@ -117,8 +117,10 @@ function syncAgentTabIndicators(){$$('#agentsView .agent-tabs, #agentModal .agen if(typeof document!=='undefined'&&document.fonts?.ready)document.fonts.ready.then(()=>syncAgentTabIndicators()).catch(()=>{}); function pickerHTML(items,selected,prefix){return `${(items||[]).map(x=>``).join('')||'暂无可用资产,请先到对应的资产管理页面添加'}`} function bindPickerFilters(root){(root||document).querySelectorAll('[data-picker-filter]').forEach(input=>input.oninput=()=>{const q=input.value.trim().toLowerCase();input.parentElement.querySelectorAll('.asset-check').forEach(row=>row.hidden=!!q&&!row.textContent.toLowerCase().includes(q))})} +const managedAgentExecutors=[{id:'wma',name:'WorkBuddy Managed Agent'},{id:'a2a',name:'自带 Agent(A2A)'}]; +function isManagedAgentExecutor(id){return managedAgentExecutors.some(executor=>executor.id===id)} function executorOptions(selected){ - const executors=state.data.executors||[]; + const executors=[...(state.data.executors||[]),...managedAgentExecutors]; const items=executors.filter(executor=>executorConfigured(executor.id)); const inheritedLabel=selected||items.length?'跟随责任人默认执行器': executorModelCatalogRequest?'检查配置中…':'无可用执行器'; @@ -231,8 +233,14 @@ function renderAgentEffortPicker(modelChanged=false){ paintAgentPicker('#agentEffortPicker',items.find(x=>x.id===current)||{id:current,name:current,icon:false}); } function applyAgentModelUI(executorId,model,effort,pickFirst=false){ + const managed=isManagedAgentExecutor(executorId); + const target=$('#agentExternalTargetField');if(target)target.hidden=executorId!=='a2a'; + for(const id of ['#agentExecutionModelField','#agentExecutionEffortField']){ + const field=$(id);if(field)field.hidden=managed; + } + const hint=$('#agentManagedExecutionHint');if(hint)hint.hidden=!managed; const picker=$('#agentModelPicker'),effortPicker=$('#agentEffortPicker');if(!picker||!effortPicker)return; - const editable=executorConfigured(executorId); + const editable=!managed&&executorConfigured(executorId); for(const control of [picker,effortPicker]){ const toggle=control.querySelector('[data-model-toggle]'); if(!toggle)continue; @@ -243,6 +251,7 @@ function applyAgentModelUI(executorId,model,effort,pickFirst=false){ } } const cat=executorModelCatalogs()[executorId]||{}; + if(managed){model='';effort='';pickFirst=false} let choice=executorId?(model||(pickFirst&&editable?(cat.models||[]).find(item=>item.id!=='default')?.id:'')||''):''; if(editable&&choice&&choice!=='default'&&!(cat.models||[]).some(m=>m.id===choice)&&cat.customModel)choice=AGENT_CUSTOM_MODEL; picker.querySelector('[name="modelChoice"]').value=choice; @@ -285,6 +294,7 @@ function selectAgent(a,rerender=true){ const f=$('#agentForm'); ['id','name','description'].forEach(k=>{if(f.elements[k])f.elements[k].value=a[k]||''}); if(f.elements.shared)f.elements.shared.checked=!!a.shared; + if(f.elements.externalAgentTarget)f.elements.externalAgentTarget.value=a.externalAgentTarget||'runner'; const prefs=state.data.assistantDefaults; const preferredId=prefs?.executor==='claude-code'?'claude':prefs?.executor; const selectedId=storedAgentExecutorId(a)||(!a.id?preferredId:'')||''; @@ -488,7 +498,7 @@ async function persistAgent(f){ return null; } const model=agentEffectiveModel(f); - if(executorId&&(creating||changedExecutor||f.elements.modelChoice?.value===AGENT_CUSTOM_MODEL)&&(!model||model==='default')){ + if(executorId&&!isManagedAgentExecutor(executorId)&&(creating||changedExecutor||f.elements.modelChoice?.value===AGENT_CUSTOM_MODEL)&&(!model||model==='default')){ toast('请选择模型或填写模型 ID','err'); if(creating)setAgentCreateStep(2); else setAgentTab('identity'); @@ -501,7 +511,7 @@ async function persistAgent(f){ // MR gates are checked by the platform and carry no commands; every other // gate is saved as a command gate and dropped while it has no command. function agentGatesForSave(gates){return (gates||[]).map((gate,i)=>{const base={id:gate.id||`gate-${i+1}`,name:gate.name||`门禁 ${i+1}`,stage:'after_execution',required:true,onFailure:['loop','reject','fail','human'].includes(gate.onFailure)?gate.onFailure:'loop'};return gate.mode==='mr'?{...base,mode:'mr'}:{...base,mode:'command',commands:(gate.commands||[]).map(c=>String(c||'').trim()).filter(Boolean),executionScope:gate.executionScope==='repositories'?'repositories':'run'}}).filter(g=>g.mode==='mr'||g.commands.length)} -async function persistAgentRequest(f,creating){const existing=state.data.agents.find(a=>a.id===f.elements.id.value);if(!catalogGeneric(state.workflow)&&existing&&catalogForeign(existing.projectId))return toast('这是其他项目的共享角色,请先复制到本项目再改');if(!catalogGeneric(state.workflow)&&agentPlatformLocked(existing))return toast('这是平台角色,只有平台管理员可以修改,请先复制到本项目再改');const checked=name=>[...f.querySelectorAll(`input[name="${name}"]:checked`)].map(x=>x.value);const draft=readAgentDraft(f);const artifacts=draft.artifactOutputs.map((x,i)=>({name:x.name||`artifact-${i+1}`,path:x.path||'result.md',mediaType:x.path?.endsWith('.json')?'application/json':(x.mediaType||'text/markdown'),required:!!x.required})),verification=agentGatesForSave(draft.verification),hooks=(draft.hooks||[]).map((h,i)=>({id:String(h.id||`hook-${i+1}`).trim(),name:String(h.name||`Hook ${i+1}`).trim(),event:h.event||'PreToolUse',matcher:String(h.matcher||'').trim(),language:h.language==='python'?'python':'shell',script:String(h.script||'').trim(),timeoutSec:Number(h.timeoutSec)||10,executionScope:h.executionScope==='repositories'?'repositories':'run'})).filter(h=>h.script),interventions=[];if(f.elements.interventionAfter?.checked)interventions.push({id:'human-review',name:'人工结果复核',stage:'after_execution',required:true});if(f.elements.interventionPublish?.checked)interventions.push({id:'publish-approval',name:'产物发布确认',stage:'before_publish',required:true});const a={id:f.elements.id.value.trim(),name:f.elements.name.value.trim(),version:(existing?.version||0)+1,projectId:existing?(existing.projectId||state.projectFilter||''):(state.projectFilter||''),shared:!!f.elements.shared?.checked,description:f.elements.description.value,prompt:draft.prompt,executorId:f.elements.executorId?.value||'',model:agentEffectiveModel(f),effort:f.elements.effort?.value||'',rules:checked('rules'),skills:checked('skills'),mcpServers:checked('mcpServers'),platformMcp:!!f.elements.platformMcp?.checked,knowledgeBase:!!f.elements.knowledgeBase?.checked,hooks,loop:{enabled:!!f.elements.loopEnabled?.checked,maxIterations:Number(f.elements.loopMaxIterations?.value)||1,exitCondition:'all_gates_pass',onExhausted:f.elements.loopOnExhausted?.value||'fail',feedbackPrompt:f.elements.loopFeedbackPrompt?.value||''},interventions,artifactOutputs:artifacts,verification};if(!a.id||!a.name)return toast('标识和名称不能为空');if(catalogGeneric(state.workflow)){if(!isPlatformAdmin())return toast('只有平台管理员可以编辑通用模板角色');const bundled=workflowAgent(a.id);if(!bundled)return toast('该角色不属于当前通用模板');a.projectId='';a.shared=false;a.rules=bundled.rules||[];a.skills=bundled.skills||[];a.mcpServers=f.querySelectorAll('input[name="mcpServers"]').length?checked('mcpServers'):(bundled.mcpServers||[]);a.hooks=Array.isArray(bundled.hooks)?bundled.hooks:a.hooks;a.version=bundled.version||0;try{const saved=await api(`/api/workflows/${encodeURIComponent(state.workflow.id)}/agents`,{method:'PUT',body:JSON.stringify(a)});const list=state.genericTemplateAgents||[];const gi=list.findIndex(x=>x.id===saved.id);if(gi>=0)list[gi]=saved;else list.push(saved);state.genericTemplateAgents=list;state.selectedAgent=saved.id;state.agentDraft=null;$('#agentModal').classList.remove('open');renderCanvas();renderProperties();toast('通用模板角色已保存,所有项目下次运行生效');}catch(err){toast(err.message)}return;}try{await api('/api/agents',{method:'PUT',body:JSON.stringify(a)});const i=state.data.agents.findIndex(x=>x.id===a.id);if(i>=0)state.data.agents[i]=a;else state.data.agents.push(a);if(a.shared){(state.data.rules||[]).forEach(item=>{if(a.rules.includes(item.id)&&item.projectId===a.projectId)item.shared=true});(state.data.skills||[]).forEach(item=>{if(a.skills.includes(item.id)&&item.projectId===a.projectId)item.shared=true})}state.selectedAgent=a.id;state.agentDraft=null;if(creating){state.agentScope='project';renderAgents();renderWorkflowMeta();renderCanvas();toast('Agent 新版本已保存');showCreatedAgent(a);return a}closeAgentWizard();renderAgents();renderCanvas();toast('Agent 新版本已保存');return a}catch(err){toast(err.message)}return null} +async function persistAgentRequest(f,creating){const existing=state.data.agents.find(a=>a.id===f.elements.id.value);if(!catalogGeneric(state.workflow)&&existing&&catalogForeign(existing.projectId))return toast('这是其他项目的共享角色,请先复制到本项目再改');if(!catalogGeneric(state.workflow)&&agentPlatformLocked(existing))return toast('这是平台角色,只有平台管理员可以修改,请先复制到本项目再改');const checked=name=>[...f.querySelectorAll(`input[name="${name}"]:checked`)].map(x=>x.value);const draft=readAgentDraft(f);const artifacts=draft.artifactOutputs.map((x,i)=>({name:x.name||`artifact-${i+1}`,path:x.path||'result.md',mediaType:x.path?.endsWith('.json')?'application/json':(x.mediaType||'text/markdown'),required:!!x.required})),verification=agentGatesForSave(draft.verification),hooks=(draft.hooks||[]).map((h,i)=>({id:String(h.id||`hook-${i+1}`).trim(),name:String(h.name||`Hook ${i+1}`).trim(),event:h.event||'PreToolUse',matcher:String(h.matcher||'').trim(),language:h.language==='python'?'python':'shell',script:String(h.script||'').trim(),timeoutSec:Number(h.timeoutSec)||10,executionScope:h.executionScope==='repositories'?'repositories':'run'})).filter(h=>h.script),interventions=[];if(f.elements.interventionAfter?.checked)interventions.push({id:'human-review',name:'人工结果复核',stage:'after_execution',required:true});if(f.elements.interventionPublish?.checked)interventions.push({id:'publish-approval',name:'产物发布确认',stage:'before_publish',required:true});const a={id:f.elements.id.value.trim(),name:f.elements.name.value.trim(),version:(existing?.version||0)+1,projectId:existing?(existing.projectId||state.projectFilter||''):(state.projectFilter||''),shared:!!f.elements.shared?.checked,description:f.elements.description.value,prompt:draft.prompt,executorId:f.elements.executorId?.value||'',externalAgentTarget:f.elements.executorId?.value==='a2a'?(f.elements.externalAgentTarget?.value||'runner'):undefined,model:agentEffectiveModel(f),effort:f.elements.effort?.value||'',rules:checked('rules'),skills:checked('skills'),mcpServers:checked('mcpServers'),platformMcp:!!f.elements.platformMcp?.checked,knowledgeBase:!!f.elements.knowledgeBase?.checked,hooks,loop:{enabled:!!f.elements.loopEnabled?.checked,maxIterations:Number(f.elements.loopMaxIterations?.value)||1,exitCondition:'all_gates_pass',onExhausted:f.elements.loopOnExhausted?.value||'fail',feedbackPrompt:f.elements.loopFeedbackPrompt?.value||''},interventions,artifactOutputs:artifacts,verification};if(!a.id||!a.name)return toast('标识和名称不能为空');if(catalogGeneric(state.workflow)){if(!isPlatformAdmin())return toast('只有平台管理员可以编辑通用模板角色');const bundled=workflowAgent(a.id);if(!bundled)return toast('该角色不属于当前通用模板');a.projectId='';a.shared=false;a.rules=bundled.rules||[];a.skills=bundled.skills||[];a.mcpServers=f.querySelectorAll('input[name="mcpServers"]').length?checked('mcpServers'):(bundled.mcpServers||[]);a.hooks=Array.isArray(bundled.hooks)?bundled.hooks:a.hooks;a.version=bundled.version||0;try{const saved=await api(`/api/workflows/${encodeURIComponent(state.workflow.id)}/agents`,{method:'PUT',body:JSON.stringify(a)});const list=state.genericTemplateAgents||[];const gi=list.findIndex(x=>x.id===saved.id);if(gi>=0)list[gi]=saved;else list.push(saved);state.genericTemplateAgents=list;state.selectedAgent=saved.id;state.agentDraft=null;$('#agentModal').classList.remove('open');renderCanvas();renderProperties();toast('通用模板角色已保存,所有项目下次运行生效');}catch(err){toast(err.message)}return;}try{await api('/api/agents',{method:'PUT',body:JSON.stringify(a)});const i=state.data.agents.findIndex(x=>x.id===a.id);if(i>=0)state.data.agents[i]=a;else state.data.agents.push(a);if(a.shared){(state.data.rules||[]).forEach(item=>{if(a.rules.includes(item.id)&&item.projectId===a.projectId)item.shared=true});(state.data.skills||[]).forEach(item=>{if(a.skills.includes(item.id)&&item.projectId===a.projectId)item.shared=true})}state.selectedAgent=a.id;state.agentDraft=null;if(creating){state.agentScope='project';renderAgents();renderWorkflowMeta();renderCanvas();toast('Agent 新版本已保存');showCreatedAgent(a);return a}closeAgentWizard();renderAgents();renderCanvas();toast('Agent 新版本已保存');return a}catch(err){toast(err.message)}return null} async function deleteAgent(id){ const a=(state.data.agents||[]).find(x=>x.id===id); if(!a)return toast('角色不存在或已删除'); diff --git a/web/app/flows.js b/web/app/flows.js index 1c6465809..115070558 100644 --- a/web/app/flows.js +++ b/web/app/flows.js @@ -1002,6 +1002,10 @@ function sectionHead(title,hint,count,unit){ const label=count==null?'':`${count} ${unit||'条'}`; return `
${title}${hint?`${hint}`:''}
${count!=null?`${label}`:''}
`; } +function nodeUsesManagedAgent(n){ + const agent=workflowAgent(n?.agentId); + return isManagedAgentExecutor(agent?.executorId||n?.executorId||''); +} function agentBindCard(n){ const agent=workflowAgent(n.agentId); const exec=(state.data.executors||[]).find(x=>x.id===(agent?.executorId||n.executorId)); @@ -1102,8 +1106,10 @@ function renderProperties(){ const scriptPreview=scriptLines?`
${escapeHTML(n.script.slice(0, 120))}${n.script.length>120?'…':''}
`:''; const scriptPane=n.type==='script'?`
${scriptPreview}

逐仓库执行时会自动进入每个仓库根目录,无需手写 cd。

`:''; const approvalPane=n.type==='approval'?`

确认步骤会停在「待我确认」,批准后才继续;这段说明会和上下游一起展示给确认人。

`:''; - const knowledgeBtn=n.type==='agent'?`

为当前节点指定要检索的个人知识库连接器(若角色开启了「接入我的知识库」则自动取并集,同一连接器以节点指定的子知识库范围为准),引用会标记在产物里。

`:''; - const main=`
主配置
${n.type==='agent'?agentBindCard(n)+knowledgeBtn:''}${sopSelect}${scriptPane}${approvalPane}
`; + const knowledgeBtn=n.type==='agent'&&!nodeUsesManagedAgent(n)?`

为当前节点指定要检索的个人知识库连接器(若角色开启了「接入我的知识库」则自动取并集,同一连接器以节点指定的子知识库范围为准),引用会标记在产物里。

`:''; + const staleKnowledge=(n.knowledgeRefs||[]).length; + const managedKnowledgeHint=n.type==='agent'&&nodeUsesManagedAgent(n)?`

${staleKnowledge?`该步骤的托管 Agent 不会使用节点知识库,本次运行会明确失败;请清空已关联的 ${staleKnowledge} 个知识库,或换用 CLI 执行器。`:'托管 Agent(WMA / A2A)在服务端检索,不支持节点关联知识库;需要知识库请换用 CLI 执行器。'}

${staleKnowledge?``:''}
`:''; + const main=`
主配置
${n.type==='agent'?agentBindCard(n)+knowledgeBtn+managedKnowledgeHint:''}${sopSelect}${scriptPane}${approvalPane}
`; const gates=n.type==='agent'?flowFold('gates','校验顺序',`${effectiveNodeArtifacts(n,workflowAgent(n.agentId)).length} 产物 · ${roleGates(workflowAgent(n.agentId)).length} 门禁`,nodeGatePane(n),false):''; const wantReject=state.flowWantReject??(n.onFailure==='reject'); const targets=state.workflow.nodes.filter(x=>x.id!==n.id).map(x=>``).join(''); @@ -1116,6 +1122,12 @@ function renderProperties(){ if(flowReadOnly() || !state.workflow?.nodes.includes(n))throw new Error('流程版本已切换,请重新选择知识库'); flowHistory.record();n.knowledgeRefs=refs;dirty();renderProperties(); })); + // Managed roles hide 关联知识库, so a binding left over from a CLI role + // (or an older save) needs its own way out instead of a role round-trip. + host.querySelector('#clearNodeKnowledgeRefs')?.addEventListener('click',()=>{ + if(flowReadOnly() || !state.workflow?.nodes.includes(n))return; + flowHistory.record();n.knowledgeRefs=[];dirty();renderProperties(); + }); } host.querySelector('#closeNodeDrawer')?.addEventListener('click',closeNodeDrawer); const del=host.querySelector('#deletePropertyNode');if(del)del.onclick=()=>removeNode(n.id); diff --git a/web/app/runners.js b/web/app/runners.js index 29b73a548..e4b47db3d 100644 --- a/web/app/runners.js +++ b/web/app/runners.js @@ -347,7 +347,9 @@ function renderRunnersView(){ const isProjectDefault=r.id===projectDefaultId; const canSetProjectDefault=projectLoaded&&projectId&&r.canUseInProject&&!isProjectDefault; const cliRows=discoveredCLIs.map(rt=>runnerRuntimeHTML(r,rt,shared)).join(''); - const cliSection=cliRows||'
未发现支持的 Agent CLI
'; + const localAgent=!shared&&(r.runtimes||[]).some(rt=>rt.provider==='a2a'&&rt.status!=='disabled'); + const agentRow=localAgent?'
本机 A2A Agent本机服务
':''; + const cliSection=(cliRows+agentRow)||'
未发现支持的 Agent CLI
'; const osLabel=runnerOSLabels[r.os]||r.os||'?'; const defaultBlocker=runnerDefaultBlocker(r); const checking=runnerMaintenancePending.has(r.id); diff --git a/web/index.html b/web/index.html index 1608a1709..e02a995f3 100644 --- a/web/index.html +++ b/web/index.html @@ -921,11 +921,12 @@

新建角色

运行方式
-