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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,25 @@ services:
interval: 2s
timeout: 3s
retries: 60
artifact-migration:
profiles: [platform]
# Upgrade existing volumes before the platform starts. Fresh schemas are created by the platform.
image: mysql:8.4
entrypoint: ["sh", "-ec"]
command:
- exec mysql -h mysql -u loopforge loopforge < /migrations/042_run_artifacts_content_mediumtext.sql
environment:
MYSQL_PWD: ${LOOPFORGE_DB_PASSWORD:?Run scripts/configure.sh first}
volumes:
- type: bind
source: ./migrations/042_run_artifacts_content_mediumtext.sql
target: /migrations/042_run_artifacts_content_mediumtext.sql
read_only: true
bind:
create_host_path: false
depends_on:
mysql:
condition: service_healthy
platform:
profiles: [platform]
# Published release stack: never builds. Bump the pinned tag (here and in
Expand Down Expand Up @@ -72,6 +91,8 @@ services:
depends_on:
mysql:
condition: service_healthy
artifact-migration:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/api/health', timeout=2).close()"]
interval: 3s
Expand Down
17 changes: 17 additions & 0 deletions docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,12 @@ The upstream process roles remain `-role api`, `-role worker` and `-role all`. A

Personal runners are connected from the execution-machine page with a short-lived binding code. The installer is served at `/runners/install.sh`. `AGENTFLOW_RUNNER_BINARY` can point to binaries with `{os}` and `{arch}` substitutions. Container images bundle Linux/macOS amd64/arm64 runner and gate binaries. Native source installations can build on demand with Go.

SOP deliverables support up to 20 MiB per file. Runner 0.13.0 and later transfer
declared files separately from the task completion report, so several files
can be handed off together. Installations with automatic Runner updates
enabled receive the bundled version after the platform release. Older Runners
keep their 1 MiB inline upload limit until they update.

The machine owner can use **Settings → Execution machines → Shared projects** to grant access to one or more projects where they are the owner or a member with write access. Members with write access can select a compatible shared machine for a new conversation. **Use in this project** sets a default for that user and project. Each new turn on a shared machine requires a current grant and project write access for both the machine owner and the sender. Removing a grant clears the saved project defaults that pointed to the machine.

Docker workspaces on macOS use a Linux Runner executable for Git credentials and MCP calls. The installer chooses the architecture of the installed macOS Runner, including Intel binaries running under Rosetta. For a universal Runner on Apple Silicon it installs the arm64 helpers and adds the amd64 helpers when available. Foreground starts and the command printed by `--no-start` select the native arm64 slice, including from a Rosetta shell. On Intel Macs the installer installs the amd64 helpers. By default, it places the helpers next to the host binary. A Runner-side `AGENTFLOW_RUNNER_BINARY` template with `{os}` selects the installation and runtime path. To install both helpers, use `{arch}` and give each architecture a distinct destination. The installer saves the template for upgrades and includes it in launchd and in the startup command printed by `--no-start`. Helper paths must resolve to files separate from the macOS Runner.
Expand Down Expand Up @@ -240,6 +246,17 @@ For an external MySQL deployment, review that migration and check column existen
| Required manual upgrade migrations | `009_bot_interactions_utf8mb4.sql`, `036_git_http_credentials.sql` | Follow each migration's timing and prerequisites. [Migrating existing GitHub credentials](#migrating-existing-github-credentials) |
| Optional backfills and rewrites of existing rows | `016_public_optional_repositories.sql`, `021_assistant_session_sources.sql` | Run them if the installation needs the converted rows |

Compose runs `migrations/042_run_artifacts_content_mediumtext.sql` before the
platform starts, including during `./start.sh pull`. The native development
script runs the same migration against its Compose database. It widens an existing
`run_artifacts.content` column from `TEXT` to `MEDIUMTEXT` for inline artifacts
and preserves existing data, character set, collation and nullability. Larger
files use separate chunk tables added at platform startup.
For a deployment using an external MySQL server and no Compose startup, run this
SQL file in the deployment's database upgrade step before starting the new binary.
If the Compose migration fails, review `docker compose --profile platform logs
artifact-migration`, resolve the database error and rerun the upgrade.

### Migrating existing sandboxes to inline assets

For a published Compose release, check out the target release and run `./start.sh pull`. If other API or worker processes share the Compose database, stop them first. After pulling the images, the command checks that the target image supports inline Dockerfiles and that the database still has a legacy asset table. When both conditions hold, it stops the platform, saves a database dump in `.local/loopforge-before-041.*/loopforge.sql`, and runs 041 before starting the new platform. An empty database or one whose legacy tables are already gone skips 041.
Expand Down
2 changes: 2 additions & 0 deletions e2e/api/90-route-sweep.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ test('runner task plane requires a runner session', async () => {
['POST', `/api/runners/tasks/${MISSING}/start`], ['POST', `/api/runners/tasks/${MISSING}/lease/renew`],
['GET', `/api/runners/tasks/${MISSING}/events`], ['POST', `/api/runners/tasks/${MISSING}/events`],
['POST', `/api/runners/tasks/${MISSING}/complete`], ['GET', `/api/runners/tasks/${MISSING}/control`],
['GET', `/api/runners/tasks/${MISSING}/input-file?path=plan.md`], ['PUT', `/api/runners/tasks/${MISSING}/output-file?path=plan.md`],
['POST', '/runners/tasks/claim'], ['GET', `/runners/tasks/${MISSING}/control`],
['POST', `/runners/previews/${MISSING}/complete`], ['PUT', `/runners/previews/${MISSING}/content`],
];
Expand Down Expand Up @@ -178,6 +179,7 @@ test('runner management: register, heartbeat, runtime status, run limit, unknown
for (const [method, path] of [
['GET', `/api/runners/tasks/${MISSING}`], ['POST', `/api/runners/tasks/${MISSING}/start`],
['POST', `/api/runners/tasks/${MISSING}/lease/renew`], ['GET', `/api/runners/tasks/${MISSING}/control`],
['GET', `/api/runners/tasks/${MISSING}/input-file?path=plan.md`], ['PUT', `/api/runners/tasks/${MISSING}/output-file?path=plan.md`],
]) {
await status(method, path, method === 'GET' ? undefined : {}, [400, 403, 404, 409], session);
}
Expand Down
23 changes: 23 additions & 0 deletions internal/domain/artifact_blob.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package domain

import (
"crypto/sha256"
"encoding/hex"
"errors"
)

const MaxSOPArtifactBytes = 20 << 20
const MaxInlineRunnerArtifactBytes = 1 << 20

var ErrArtifactTooLarge = errors.New("artifact exceeds the file size limit")

type ArtifactBlob struct {
ID string `json:"id"`
Size int64 `json:"size"`
SHA256 string `json:"sha256"`
}

func RunnerOutputBlobID(taskID, path string) string {
sum := sha256.Sum256([]byte(taskID + "\x00" + path))
return hex.EncodeToString(sum[:])
}
1 change: 1 addition & 0 deletions internal/domain/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,7 @@ type Artifact struct {
Size int64 `json:"size"`
SHA256 string `json:"sha256"`
Content string `json:"content"`
BlobID string `json:"-"`
// RepositoryDir records which run repository workspace the artifact was
// collected from (empty = run workspace root, where SOP deliverables live).
RepositoryDir string `json:"repositoryDir,omitempty"`
Expand Down
23 changes: 19 additions & 4 deletions internal/domain/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,15 @@ func (r Runner) SupportsProjectCredentials() bool {
return versionAtLeast(r.RunnerVersion, RunnerVersionProjectCredentials)
}

// RunnerVersionArtifactTransfer introduced task-scoped streaming for SOP files.
const RunnerVersionArtifactTransfer = "0.13.0"

const RunnerResultReportError = "执行结果回传失败"

func (r Runner) SupportsArtifactTransfer() bool {
return versionAtLeast(r.RunnerVersion, RunnerVersionArtifactTransfer)
}

// RunnerVersionConversationSOPWorkspace discovers nested conversation checkouts
// and prepares them inside the SOP sandbox while preserving local work.
const RunnerVersionConversationSOPWorkspace = "0.12.3"
Expand Down Expand Up @@ -631,6 +640,7 @@ type RunnerInvocation struct {
// move a missing output file found elsewhere in the workspace into
// place, as the control plane does for its own sandboxes.
ReportOutputs bool `json:"reportOutputs,omitempty"`
ArtifactTransfer bool `json:"artifactTransfer,omitempty"`
OutputFiles []string `json:"outputFiles,omitempty"`
RecoverOutputs bool `json:"recoverOutputs,omitempty"`
HumanContext string `json:"humanContext,omitempty"`
Expand Down Expand Up @@ -735,17 +745,22 @@ func (inv *RunnerInvocation) GitSSHRemotes() []string {

// RunnerInputFile is one file written into the task workspace before a run.
type RunnerInputFile struct {
Path string `json:"path"`
Content string `json:"content"`
Path string `json:"path"`
Content string `json:"content,omitempty"`
ArtifactID string `json:"artifactId,omitempty"`
SHA256 string `json:"sha256,omitempty"`
Restore bool `json:"restore,omitempty"`
}

// RunnerTaskOutputs is what a runner reports about the task workspace after
// an invocation or script.
type RunnerTaskOutputs struct {
// Files maps a workspace-relative OutputFiles path to its content. Missing
// files and non-regular files are absent; oversized ones are in TooLarge.
Files map[string]string `json:"files,omitempty"`
TooLarge []string `json:"tooLarge,omitempty"`
Files map[string]string `json:"files,omitempty"`
TooLarge []string `json:"tooLarge,omitempty"`
FileBlobs map[string]ArtifactBlob `json:"fileBlobs,omitempty"`
FileErrors map[string]string `json:"fileErrors,omitempty"`
// Patches maps a repository checkout dir ("" is the workspace root) to
// its repository-patch inventory. Unchanged checkouts are absent.
Patches map[string]string `json:"patches,omitempty"`
Expand Down
106 changes: 106 additions & 0 deletions internal/engine/artifact_prompt_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package engine

import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"

"agentflow/internal/domain"
"agentflow/internal/repo"
"agentflow/internal/runtime"
)

func TestDownstreamPromptRendersArtifactBody(t *testing.T) {
for _, tc := range []struct {
name string
content string
}{
{name: "inline", content: "PLAN-BODY-123"},
{name: "chunked", content: "PLAN-BODY-123" + strings.Repeat("x", domain.MaxInlineRunnerArtifactBytes)},
} {
t.Run(tc.name, func(t *testing.T) {
store, err := repo.OpenTest()
if err != nil {
t.Fatal(err)
}
t.Cleanup(store.Close)
run := runArtifactPromptSOP(t, store, tc.content)
output := run.Nodes["reader"].Output
if !strings.Contains(output, "READ<<"+tc.content+">>END") {
start := strings.Index(output, "READ<<")
t.Fatalf("reader prompt did not receive the upstream artifact body: %.80q", output[max(start, 0):])
}
})
}
}

func runArtifactPromptSOP(t *testing.T, store *repo.Store, content string) domain.Run {
t.Helper()
const sandboxID = "artifact-prompt-sandbox"
if err := store.PutSandbox(domain.SandboxProfile{ID: sandboxID, Name: "Artifact prompt sandbox", Driver: domain.SandboxDriverNative}); err != nil {
t.Fatal(err)
}
if err := store.PutExecutor(domain.ExecutorDefinition{ID: "mock", Name: "Mock executor", Kind: "mock", Protocol: "events-v1"}); err != nil {
t.Fatal(err)
}
putGateTestAgent(t, store, "writer-agent", nil)
if err := store.PutAgent(domain.AgentDefinition{ID: "reader-agent", Name: "reader-agent", ExecutorID: "mock", Prompt: "READ<<{{artifact.writer.plan}}>>END"}); err != nil {
t.Fatal(err)
}
workflow := domain.WorkflowDefinition{
ID: fmt.Sprintf("artifact-prompt-%d", time.Now().UnixNano()), Name: "Artifact prompt", SandboxProfileID: sandboxID,
Nodes: []domain.WorkflowNode{
{ID: "writer", Name: "Writer", Type: "agent", AgentID: "writer-agent", MaxAttempts: 1,
ArtifactOutputs: []domain.ArtifactContract{{Name: "plan", Path: "plan.md", Required: true}}},
{ID: "reader", Name: "Reader", Type: "agent", AgentID: "reader-agent", MaxAttempts: 1},
},
Edges: []domain.WorkflowEdge{{ID: "writer-reader", Source: "writer", Target: "reader", When: "success"}},
}
if err := store.PutWorkflow(workflow); err != nil {
t.Fatal(err)
}
manager := runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))
eng := New(store, manager)
eng.ConfigureExecution("artifact-prompt-worker", "", 30*time.Second, false)
run, err := eng.Start(workflow.ID, "")
if err != nil {
t.Fatal(err)
}
workspace := manager.RunWorkspace(run.ID)
if err := os.MkdirAll(workspace, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(workspace, "plan.md"), []byte(content), 0o600); err != nil {
t.Fatal(err)
}
eng.ConfigureExecution("artifact-prompt-worker", "", 30*time.Second, true)
if _, err := eng.acquireLease(run); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second)
done := make(chan struct{})
go func() {
defer close(done)
eng.execute(ctx, run.ID)
}()
defer func() { cancel(); <-done }()
for ctx.Err() == nil {
current, ok := store.RunState(run.ID)
if !ok {
t.Fatal("could not read run")
}
if domain.TerminalRunStatus(current.Status) {
if current.Status != "succeeded" {
t.Fatalf("run %s: writer=%q reader=%q", current.Status, current.Nodes["writer"].Error, current.Nodes["reader"].Error)
}
return current
}
time.Sleep(20 * time.Millisecond)
}
t.Fatal("run did not finish")
return domain.Run{}
}
Loading
Loading