From 34f1c3418ba1fb0b31bb77a7485d26d44bc771ea Mon Sep 17 00:00:00 2001 From: Robert0622 <53806540+Robert0622@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:14:48 +0800 Subject: [PATCH 01/14] feat: add WMA, A2A and OpenSandbox execution providers --- cmd/agentflow-runner/a2a_config.go | 51 +++++ cmd/agentflow-runner/main.go | 6 + cmd/agentflow/main.go | 3 + cmd/agentflow/optional_execution.go | 131 +++++++++++ deploy/opensandbox-runner.Dockerfile | 14 ++ docs/architecture.md | 84 +++++++ internal/domain/agent.go | 55 ++++- internal/domain/observability.go | 7 +- internal/domain/run.go | 3 + internal/domain/runner.go | 14 ++ internal/engine/cloud_pool.go | 5 +- internal/engine/engine.go | 6 + internal/engine/evolution_replay.go | 3 + internal/engine/managed_agent.go | 173 +++++++++++++++ internal/engine/node_execute.go | 9 + internal/engine/opensandbox.go | 217 ++++++++++++++++++ internal/engine/opensandbox_test.go | 45 ++++ internal/engine/run_start.go | 34 ++- internal/engine/runner_dispatch.go | 23 +- internal/engine/sop_executors.go | 20 +- internal/httpapi/catalog.go | 3 + internal/httpapi/executor_models.go | 5 + internal/httpapi/runners.go | 37 +++- internal/managedagent/a2a.go | 248 +++++++++++++++++++++ internal/managedagent/a2a_test.go | 84 +++++++ internal/managedagent/acp.go | 294 +++++++++++++++++++++++++ internal/managedagent/tencent.go | 121 ++++++++++ internal/managedagent/tencent_test.go | 50 +++++ internal/managedagent/wma.go | 225 +++++++++++++++++++ internal/managedagent/wma_live_test.go | 36 +++ internal/managedagent/wma_test.go | 156 +++++++++++++ internal/opensandbox/client.go | 234 ++++++++++++++++++++ internal/repo/catalog.go | 7 + internal/repo/runners.go | 13 +- internal/runner/daemon.go | 7 + internal/runner/external_agent.go | 39 ++++ internal/runner/external_agent_test.go | 177 +++++++++++++++ internal/runner/opensandbox_test.go | 263 ++++++++++++++++++++++ internal/runtime/sandbox_process.go | 1 + web/app/agents.js | 20 +- web/app/runners.js | 4 +- web/index.html | 8 +- web/syntax_test.go | 2 +- webtest/tests/assets-agents.test.mjs | 37 ++++ 44 files changed, 2937 insertions(+), 37 deletions(-) create mode 100644 cmd/agentflow-runner/a2a_config.go create mode 100644 cmd/agentflow/optional_execution.go create mode 100644 deploy/opensandbox-runner.Dockerfile create mode 100644 internal/engine/managed_agent.go create mode 100644 internal/engine/opensandbox.go create mode 100644 internal/engine/opensandbox_test.go create mode 100644 internal/managedagent/a2a.go create mode 100644 internal/managedagent/a2a_test.go create mode 100644 internal/managedagent/acp.go create mode 100644 internal/managedagent/tencent.go create mode 100644 internal/managedagent/tencent_test.go create mode 100644 internal/managedagent/wma.go create mode 100644 internal/managedagent/wma_live_test.go create mode 100644 internal/managedagent/wma_test.go create mode 100644 internal/opensandbox/client.go create mode 100644 internal/runner/external_agent.go create mode 100644 internal/runner/external_agent_test.go create mode 100644 internal/runner/opensandbox_test.go 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..4ce25cecf 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 interrupted attempt with an unknown remote outcome requires an explicit retry. 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 f6193006f..cb4366394 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"` @@ -38,7 +40,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 4d3fd12c3..95b31ec0e 100644 --- a/internal/domain/run.go +++ b/internal/domain/run.go @@ -177,6 +177,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..740a4c77d 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" @@ -291,6 +294,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"` 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 f6b23951e..74b80c80d 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -11,6 +11,8 @@ import ( "time" "agentflow/internal/domain" + "agentflow/internal/managedagent" + "agentflow/internal/opensandbox" "agentflow/internal/preview" "agentflow/internal/repo" "agentflow/internal/runtime" @@ -47,6 +49,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..db43cebb0 --- /dev/null +++ b/internal/engine/managed_agent.go @@ -0,0 +1,173 @@ +package engine + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "strings" + "time" + + "agentflow/internal/domain" + "agentflow/internal/managedagent" + "agentflow/internal/runtime" +) + +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) +} + +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 err + } + if run.ExecutionContext.IsEvolutionReplay() { + return errors.New("进化回放暂不支持托管 Agent") + } + if len(node.ArtifactOutputs) > 0 || normalizeExecutionScope(node.ExecutionScope) == domain.ExecutionScopeRepositories || + len(node.CredentialEnv) > 0 { + return 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) && nr.ManagedPromptAttempt != attempt { + nr.ManagedPromptAttempt = attempt + nr.Provider = provider + dispatch = true + } + }); err != nil { + return err + } + if !dispatch { + return fmt.Errorf("%s 节点本次执行已发起或终止,请确认原执行结果后重试", 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 + } + if completed.Error != "" { + return "", errors.New(completed.Error) + } + return "", fmt.Errorf("个人执行器 A2A 任务结束于 %s", completed.Status) +} diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.go index 5aafaba49..9384ed2b8 100644 --- a/internal/engine/node_execute.go +++ b/internal/engine/node_execute.go @@ -441,6 +441,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/opensandbox.go b/internal/engine/opensandbox.go new file mode 100644 index 000000000..220ae9afe --- /dev/null +++ b/internal/engine/opensandbox.go @@ -0,0 +1,217 @@ +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" + +// 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) + ec := run.ExecutionContext + client := e.openSandboxForRun(run) + if !ok || !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) + } + 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 + } + if err := e.repo.DeregisterRunner(ec.ExecutionRunnerID, time.Now().UTC()); err != nil && !errors.Is(err, repo.ErrRunnerNotFound) { + return err + } + return nil +} 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..54145233b 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,9 @@ 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) { + return e.releaseOpenSandbox(run) + } 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/httpapi/catalog.go b/internal/httpapi/catalog.go index fa2ceb670..1bee2f247 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 = "" 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/runners.go b/internal/httpapi/runners.go index 490bf36eb..272131002 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,7 +1093,9 @@ 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) } @@ -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 } diff --git a/internal/managedagent/a2a.go b/internal/managedagent/a2a.go new file mode 100644 index 000000000..a4edebf71 --- /dev/null +++ b/internal/managedagent/a2a.go @@ -0,0 +1,248 @@ +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"` +} + +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") + } + ctx, stop := context.WithTimeout(ctx, 5*time.Minute) + defer stop() + 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..8d909cec4 --- /dev/null +++ b/internal/managedagent/a2a_test.go @@ -0,0 +1,84 @@ +package managedagent + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "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") + } +} 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/wma.go b/internal/managedagent/wma.go new file mode 100644 index 000000000..b64797eb8 --- /dev/null +++ b/internal/managedagent/wma.go @@ -0,0 +1,225 @@ +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(ctx context.Context, prompt string, onText func(string)) (string, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Minute) + defer cancel() + 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..af4dee3c9 --- /dev/null +++ b/internal/opensandbox/client.go @@ -0,0 +1,234 @@ +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}$") +) + +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 { + ctx, cancel := context.WithTimeout(ctx, 20*time.Second) + 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 < 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/repo/catalog.go b/internal/repo/catalog.go index d4d4b8f9d..cc147a905 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/runners.go b/internal/repo/runners.go index c6e458e2b..65daba2e5 100644 --- a/internal/repo/runners.go +++ b/internal/repo/runners.go @@ -622,10 +622,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 +659,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 diff --git a/internal/runner/daemon.go b/internal/runner/daemon.go index 9e7dff873..cfb1fadd2 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: diff --git a/internal/runner/external_agent.go b/internal/runner/external_agent.go new file mode 100644 index 000000000..6194223b4 --- /dev/null +++ b/internal/runner/external_agent.go @@ -0,0 +1,39 @@ +package runner + +import ( + "context" + + "agentflow/internal/domain" +) + +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 { + return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()} + } + 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..9e914d256 --- /dev/null +++ b/internal/runner/external_agent_test.go @@ -0,0 +1,177 @@ +package runner + +import ( + "crypto/tls" + "crypto/x509" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "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}, + {ID: "verify", Name: "Read passed artifact", Type: "script", Script: `test "$(cat .agentflow/inputs/agent/result.md)" = '` + expected + "'", MaxAttempts: 1}, + }, + Edges: []domain.WorkflowEdge{{ID: "handoff", Source: "agent", Target: "verify", When: "success"}}, + } + 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 SOP", 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("SOP status %s: Agent error %q, verify error %q", final.Status, final.Nodes["agent"].Error, final.Nodes["verify"].Error) + } + 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 +} 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/runners.js b/web/app/runners.js index 7a6ed0d38..6a0f30220 100644 --- a/web/app/runners.js +++ b/web/app/runners.js @@ -319,7 +319,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 1a1b19142..653e8b166 100644 --- a/web/index.html +++ b/web/index.html @@ -902,11 +902,12 @@

新建角色

运行方式
-