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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions cmd/agentflow-runner/a2a_config.go
Original file line number Diff line number Diff line change
@@ -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)
}
6 changes: 6 additions & 0 deletions cmd/agentflow-runner/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions cmd/agentflow/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
131 changes: 131 additions & 0 deletions cmd/agentflow/optional_execution.go
Original file line number Diff line number Diff line change
@@ -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
}
14 changes: 14 additions & 0 deletions deploy/opensandbox-runner.Dockerfile
Original file line number Diff line number Diff line change
@@ -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"]
84 changes: 84 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,87 @@ The platform keeps the upstream Go module name `agentflow`, package boundaries a
The public edition adds account/password login and GitHub adapters. These feed the existing user, token, repository and delivery contracts; there is no separate public engine or in-memory production store. A remote repository identity beginning `github:` distinguishes GitHub owner/repository names from legacy tracker identities. The upstream `gongfengProjectId` JSON field carries this identity for compatibility.

The CLI's Classic and Portable workflow assets remain separate from each other and from platform role definitions. Sharing behavior contracts is preferable to copying runtime assets. No classic host bundle is required by a platform worker.

## Managed Agents and execution environments

An LOOP role chooses an executor. A CLI role runs in the workspace selected for the run. A WorkBuddy Managed Agent or A2A role sends a text turn to a configured Agent and publishes the reply as `result.md`. Downstream nodes get that artifact through the existing artifact handoff. A remote Agent keeps its own workspace and tool configuration.

| Role executor | Target | How the target is selected |
| --- | --- | --- |
| Existing CLI | Personal Runner | The project or personal default machine, frozen when the run starts |
| Existing CLI | OpenSandbox | The project's configured Docker or Kubernetes lifecycle server, when the run has no default machine and uses an explicit `native` sandbox profile |
| Existing CLI | Existing local runtime or cloud Runner pool | The existing scheduling rules for runs outside OpenSandbox |
| WorkBuddy Managed Agent | Existing WMA session | A server binding for the project and responsible user |
| External A2A Agent | User machine or CVM | The responsible user's personal Runner, which calls its configured loopback service |
| External A2A Agent | Cloud HTTPS service | A server binding for the project and responsible user, explicitly selected on the role |

Managed Agent dispatch records its attempt before sending the turn. An attempt with an unknown remote outcome — an interrupted turn or one that ran past its budget — requires an explicit retry. The node fails instead of consuming its remaining attempts. One WMA or A2A turn may run for up to five minutes; the connector then cancels the remote task, fails the node with a timeout and, because cancellation is only advisory, does not resend the turn on its own. The CLI and sandbox paths retain their normal task leases, workspace handoff, and result handling.

### WorkBuddy Managed Agents

Choose **WorkBuddy Managed Agent** in an LOOP role or set `"executorId":"wma"` through `PUT /api/agents`. Configure the model, tools, and access on the Agent version in WMA. Use a dedicated existing session. [WorkBuddy Agent access guide](https://cloud.tencent.com/document/product/1831/140759)

| Server environment variable | Value |
| --- | --- |
| AGENTFLOW_WMA_PROJECT | LoopForge project ID |
| AGENTFLOW_WMA_USER_ID | LoopForge responsible user ID |
| AGENTFLOW_WMA_AGENT_ID | Published Agent ID |
| AGENTFLOW_WMA_SESSION_ID | Existing dedicated session ID |
| AGENTFLOW_WMA_ACP_ORIGIN | Optional exact HTTPS origin for an approved private ACP gateway |
| AGENTFLOW_WMA_SECRET_ID, AGENTFLOW_WMA_SECRET_KEY | Tencent Cloud credentials for the enterprise identity |
| AGENTFLOW_WMA_REGION | Tencent Cloud region, default `ap-beijing` |
| AGENTFLOW_WMA_SECURITY_TOKEN | Optional token for temporary Tencent Cloud credentials |
| AGENTFLOW_WMA_ENTERPRISE_ID, AGENTFLOW_WMA_API_KEY | WorkBuddy enterprise ID and `ck_` or `pt_` key, for WorkBuddy OpenAPI authentication |
| AGENTFLOW_WMA_ENDPOINT | OpenAPI control-plane origin for a dedicated tenant. SaaS defaults to `https://www.workbuddy.cn`. |

Choose one control-plane authentication method. Both methods use the returned ACP endpoint and an access token for the data plane. The configured session is reused. A worker serializes prompts to the session until each request settles.

### External A2A Agents

Choose **自带 Agent(A2A)** in the LOOP role and select the personal Runner or cloud HTTPS target. Through the role API, use `"executorId":"a2a"` and `"externalAgentTarget":"runner"` or `"remote"`. The default A2A target is the personal Runner. The service uses the A2A v0.3 JSON-RPC binding. The connector sends a text message, follows asynchronous tasks with `tasks/get`, and requests cancellation when it knows the task ID. [A2A v0.3 specification](https://a2a-protocol.org/v0.3.0/specification/)

For a user's machine or cloud VM, bind the LoopForge Runner, share it with the project and make it the responsible user's execution machine. Place the following configuration at `~/.agentflow-runner/a2a.json` and restart the Runner. The endpoint uses a literal loopback address, so the Agent can stay on a local port. An optional `token` is sent only to this endpoint. `AGENTFLOW_RUNNER_A2A_ENDPOINT` and `AGENTFLOW_RUNNER_A2A_TOKEN` can set the same values in a service environment.

```json
{"endpoint":"http://127.0.0.1:9000/a2a"}
```

For a cloud HTTPS Agent, set `AGENTFLOW_A2A_BINDINGS_FILE` to a deployment-managed JSON file. A binding applies to one project and responsible user. The file can contain multiple entries. Include an optional `token` when the service requires bearer authentication.

```json
[
{
"projectId": "pilot-project",
"responsibleUserId": 42,
"endpoint": "https://agent.example.com/a2a"
}
]
```

Managed text roles can reference earlier node replies with `{{upstream}}` or `{{node.<id>.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'
```
55 changes: 45 additions & 10 deletions internal/domain/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"`
Expand Down
Loading
Loading