Skip to content

An open-source, faster Devin alternative

TypeScript

Remove the legacy Go CLI cmd/oc and its release workflow (097 step 7.1)

Mohamed Habib via Computerac082aef962e
diff --git a/.github/workflows/release-cli.yml b/.github/workflows/release-cli.yml
deleted file mode 100644
index a4a50f79..00000000
--- a/.github/workflows/release-cli.yml
+++ /dev/null
@@ -1,126 +0,0 @@
-name: Release CLI
-
-on:
- push:
- branches: [main]
- paths:
- - 'cmd/oc/**'
- - 'internal/**'
- - 'VERSION'
- - 'go.mod'
- - 'go.sum'
- - '.github/workflows/release-cli.yml'
-
-permissions:
- contents: write
-
-jobs:
- release:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
- with:
- fetch-depth: 0 # need full history for tags
-
- - uses: actions/setup-go@v5
- with:
- go-version-file: go.mod
-
- - name: Determine version
- id: version
- run: |
- BASE=$(cat VERSION | tr -d '[:space:]')
- echo "base=$BASE" >> "$GITHUB_OUTPUT"
-
- # Find the latest tag matching this base version
- LATEST=$(git tag --list "v${BASE}.*" --sort=-v:refname | head -n1)
-
- if [ -z "$LATEST" ]; then
- # No existing tag for this base version — start at .0
- PATCH=0
- else
- # Extract 4th number and bump
- CURRENT_PATCH=$(echo "$LATEST" | sed "s/v${BASE}\.//")
- PATCH=$((CURRENT_PATCH + 1))
- fi
-
- VERSION="${BASE}.${PATCH}"
- echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- echo "tag=v${VERSION}" >> "$GITHUB_OUTPUT"
- echo "Releasing v${VERSION}"
-
- - name: Check if tag already exists
- id: check_tag
- run: |
- if git rev-parse "refs/tags/${{ steps.version.outputs.tag }}" >/dev/null 2>&1; then
- echo "exists=true" >> "$GITHUB_OUTPUT"
- else
- echo "exists=false" >> "$GITHUB_OUTPUT"
- fi
-
- # The same main merge can trigger the API-edge and CLI workflows in
- # parallel. Do not publish a CLI that advertises `oc login` until the
- # additive edge contract is observably live.
- - name: Wait for CLI login edge contract
- if: steps.check_tag.outputs.exists == 'false'
- run: |
- for attempt in $(seq 1 120); do
- status=$(curl -sS \
- --output /tmp/cli-login-edge.json \
- --write-out '%{http_code}' \
- https://app.opencomputer.dev/auth/cli/device || true)
- if [ "$status" = "405" ] &&
- jq -e '.error == "method_not_allowed"' /tmp/cli-login-edge.json >/dev/null 2>&1; then
- echo "CLI login edge contract is live."
- exit 0
- fi
- echo "Waiting for API edge (attempt $attempt/120; status ${status:-unavailable})..."
- sleep 5
- done
- echo "CLI login edge contract did not become ready; refusing to publish."
- exit 1
-
- - name: Build CLI binaries
- if: steps.check_tag.outputs.exists == 'false'
- run: |
- VERSION="${{ steps.version.outputs.version }}"
- LDFLAGS="-s -w -X github.com/opensandbox/opensandbox/cmd/oc/internal/commands.Version=${VERSION}"
- mkdir -p dist
-
- platforms=(
- "linux/amd64"
- "linux/arm64"
- "darwin/amd64"
- "darwin/arm64"
- )
-
- for platform in "${platforms[@]}"; do
- GOOS="${platform%/*}"
- GOARCH="${platform#*/}"
- output="dist/oc-${GOOS}-${GOARCH}"
- echo "Building ${GOOS}/${GOARCH}..."
- CGO_ENABLED=0 GOOS="$GOOS" GOARCH="$GOARCH" go build \
- -ldflags "$LDFLAGS" \
- -o "$output" \
- ./cmd/oc
- done
-
- # Create checksums
- cd dist && sha256sum oc-* > checksums.txt
-
- - name: Create tag
- if: steps.check_tag.outputs.exists == 'false'
- run: |
- git tag "${{ steps.version.outputs.tag }}"
- git push origin "${{ steps.version.outputs.tag }}"
-
- - name: Create GitHub Release
- if: steps.check_tag.outputs.exists == 'false'
- uses: softprops/action-gh-release@v2
- with:
- tag_name: ${{ steps.version.outputs.tag }}
- name: oc ${{ steps.version.outputs.tag }}
- generate_release_notes: true
- files: |
- dist/oc-*
- dist/checksums.txt
diff --git a/AGENTS.md b/AGENTS.md
index 358f0695..0f8c4cfb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -34,7 +34,7 @@ truth they come from.
- `internal/config/config.go` — environment variables and runtime config
- `proto/` — inter-tier contracts
- `docs/docs.json` — docs navigation
-- `cmd/oc/` — CLI entrypoint
+- `cli/` — the `opencomputer` CLI (TypeScript, published as `@opencomputer/cli`)
- `sdks/typescript/` and `sdks/python/` — published SDKs
Managed-agent product behavior is mostly **not** implemented here:
@@ -152,7 +152,7 @@ Client -> Control Plane -> Data Plane -> In-VM Agent
machine-level execution.
- **In-VM agent** (`cmd/agent`, `internal/agent/`, `proto/agent/`) owns exec,
files, PTY, and process interaction inside the sandbox.
-- **CLI** (`cmd/oc/`) is the user-facing shell over platform APIs.
+- **CLI** (`cli/`) is the user-facing shell over platform APIs.
The stable mental model is:
@@ -164,7 +164,7 @@ The stable mental model is:
Use this as a routing map, not a full index:
-- `cmd/server/`, `cmd/worker/`, `cmd/agent/`, `cmd/oc/` — entrypoints
+- `cmd/server/`, `cmd/worker/`, `cmd/agent/` — entrypoints
- `internal/api/` — HTTP handlers and API composition
- `internal/auth/` — auth, API keys, WorkOS, middleware
- `internal/sandbox/` — sandbox state machine and routing
@@ -189,7 +189,7 @@ you are editing:
- `proto/` — contracts between tiers
- public HTTP API routes in `internal/api/`
- `sdks/` — published TypeScript and Python SDKs
-- `cmd/oc/` — CLI behavior users script against
+- `cli/` — CLI behavior users script against
- `docs/` — user-facing product and API documentation
If a change crosses one of these boundaries, treat it as a contract change, not
@@ -222,21 +222,16 @@ just a refactor.
## CLI boundary
-`cmd/oc/` spans two kinds of user flows:
-
-- direct OpenComputer platform commands: sandboxes, exec, files, checkpoints,
- previews, secrets
-- managed-agent commands, which delegate to `sessions-api`
-
-Do not assume all `oc` behavior is implemented in this repo just because the
-command lives here.
+The `opencomputer` CLI lives in `cli/`. Managed-agent commands delegate to
+`sessions-api`; do not assume all CLI behavior is implemented in this repo just
+because the command lives here.
## Change strategy
When making changes, prefer the narrowest layer that can correctly own the work:
- docs/content issue -> `docs/`
-- CLI UX issue -> `cmd/oc/`
+- CLI UX issue -> `cli/`
- SDK issue -> `sdks/`
- API shape/auth issue -> `internal/api/` or `internal/auth/`
- sandbox lifecycle issue -> `internal/sandbox/`, `internal/worker/`,
diff --git a/Makefile b/Makefile
index 9ec16e17..1ff6bbc7 100644
--- a/Makefile
+++ b/Makefile
@@ -5,17 +5,15 @@ BINARY_SERVER = opensandbox-server
BINARY_WORKER = opensandbox-worker
BINARY_AGENT = osb-agent
BUILD_DIR = bin
-VERSION ?= $(shell cat VERSION | tr -d '[:space:]').dev
GIT_SHA ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "dev")
-LDFLAGS_OC = -s -w -X github.com/opensandbox/opensandbox/cmd/oc/internal/commands.Version=$(VERSION)
LDFLAGS_WORKER = -X main.WorkerVersion=$(GIT_SHA) -X main.AgentVersion=$(GIT_SHA)
## help: Show this help message
help:
@grep -E '^##' $(MAKEFILE_LIST) | sed 's/## //' | column -t -s ':'
-## build: Build server, worker, agent, and CLI binaries
-build: build-server build-worker build-agent build-oc
+## build: Build server, worker, and agent binaries
+build: build-server build-worker build-agent
## build-server: Build the control plane server
build-server:
@@ -41,14 +39,6 @@ build-agent-amd64:
build-server-arm64:
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o $(BUILD_DIR)/$(BINARY_SERVER)-arm64 ./cmd/server
-## build-oc: Build the oc CLI tool
-build-oc:
- CGO_ENABLED=0 go build -ldflags "$(LDFLAGS_OC)" -o $(BUILD_DIR)/oc ./cmd/oc
-
-## install-oc: Build and install oc to $GOPATH/bin
-install-oc:
- CGO_ENABLED=0 go install -ldflags "$(LDFLAGS_OC)" ./cmd/oc
-
## --- Local Testing (3 tiers) ---
## run-dev: Tier 1 - Combined mode, no auth, no PG/NATS (simplest)
diff --git a/ci/tests/api/cli_test.go b/ci/tests/api/cli_test.go
deleted file mode 100644
index 8c1e0bfe..00000000
--- a/ci/tests/api/cli_test.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package api_test
-
-import (
- "os"
- "os/exec"
- "path/filepath"
- "strings"
- "testing"
-)
-
-// TestCLI_Smoke builds the oc CLI binary and exercises a few subcommands.
-// Catches argparse / output regressions invisible to direct-API tests.
-//
-// Builds via `go build` so the binary is consistent with the rest of the PR.
-// Skips if go isn't on PATH (shouldn't happen in CI).
-func TestCLI_Smoke(t *testing.T) {
- if _, err := exec.LookPath("go"); err != nil {
- t.Skip("go not on PATH")
- }
- root := repoRoot(t)
- cliBin := filepath.Join(t.TempDir(), "oc")
- build := exec.Command("go", "build", "-o", cliBin, "./cmd/oc")
- build.Dir = root
- if out, err := build.CombinedOutput(); err != nil {
- t.Fatalf("build oc: %v\n%s", err, out)
- }
-
- // --help: every CLI must expose usage. Catches malformed cobra trees.
- out, err := exec.Command(cliBin, "--help").CombinedOutput()
- if err != nil {
- t.Fatalf("oc --help: %v\n%s", err, out)
- }
- if !strings.Contains(string(out), "Usage:") {
- t.Errorf("oc --help: missing 'Usage:' in output: %q", out)
- }
-
- // version: smoke check that the version subcommand exists and exits 0
- out, err = exec.Command(cliBin, "version").CombinedOutput()
- if err != nil {
- // version is optional in some CLIs — log but don't fail
- t.Logf("oc version: %v (output=%q) — skipping version assertion", err, out)
- } else if len(strings.TrimSpace(string(out))) == 0 {
- t.Errorf("oc version: empty output")
- }
-
- // If we have a running stack, exercise an API-authenticated command.
- server := os.Getenv(envServerURL)
- apiKey := os.Getenv(envAPIKey)
- if server == "" || apiKey == "" {
- t.Logf("no live stack — skipping live CLI command test")
- return
- }
- cmd := exec.Command(cliBin, "agent", "list")
- cmd.Env = append(os.Environ(),
- "OPENCOMPUTER_API_URL="+server,
- "OPENCOMPUTER_API_KEY="+apiKey,
- )
- out, err = cmd.CombinedOutput()
- if err != nil {
- t.Fatalf("oc agent list: %v\n%s", err, out)
- }
- // Just confirm it returned without error — the org may have zero agents.
- t.Logf("oc agent list returned %d bytes", len(out))
-}
-
diff --git a/cmd/oc/internal/bundle/bundle.go b/cmd/oc/internal/bundle/bundle.go
deleted file mode 100644
index 1c07fc1e..00000000
--- a/cmd/oc/internal/bundle/bundle.go
+++ /dev/null
@@ -1,88 +0,0 @@
-// Package bundle packs a fileset into a .tar.gz and content-addresses it.
-//
-// The content address is the STANDARD blob digest — sha256 of the packed bytes
-// (as OCI addresses blobs), NOT a digest of a canonical serialization of the
-// fileset. That distinction is the whole point: the CLI, the host, and the box
-// all hash the SAME uploaded object (the CLI hashes what it uploads; the server
-// hashes the object it received; the box hashes the object it fetched), so no
-// party ever recomputes an address from scratch. There is therefore no canonical
-// form to reproduce across languages — sha256 is sha256 everywhere — and no
-// hand-rolled tar codec or JSON escaper. The tar is plain transport (stdlib
-// archive/tar); it need not be canonical because its bytes are not the address.
-package bundle
-
-import (
- "archive/tar"
- "bytes"
- "compress/gzip"
- "crypto/sha256"
- "encoding/hex"
- "time"
-)
-
-// File is one entry in a bundle. Mode is normalized to 0o644 or 0o755.
-type File struct {
- Path string // bundle-root-relative, forward-slash separated
- Mode int // 0o644 | 0o755
- Content []byte
-}
-
-// NormalizeMode collapses an on-disk mode to the two the bundle allows: 0o755 if
-// any execute bit is set, else 0o644.
-func NormalizeMode(mode int) int {
- if mode&0o111 != 0 {
- return 0o755
- }
- return 0o644
-}
-
-// Digest is the content address of the packed bundle: "sha256:" + sha256(blob).
-// The caller hashes exactly the bytes it uploads; the server and box verify by
-// hashing exactly the bytes they hold — no reproduction, no lockstep.
-func Digest(blob []byte) string {
- sum := sha256.Sum256(blob)
- return "sha256:" + hex.EncodeToString(sum[:])
-}
-
-// Pack writes the fileset to a gzip-compressed tar with the standard library.
-// Entries are sorted and mtime is pinned to the epoch so the output is stable
-// for identical input (dedup-friendly), but nothing depends on the exact bytes —
-// the digest is over whatever Pack produces, and the box unpacks with system tar.
-func Pack(files []File) ([]byte, error) {
- sorted := append([]File(nil), files...)
- sortByPath(sorted)
-
- var buf bytes.Buffer
- zw := gzip.NewWriter(&buf)
- tw := tar.NewWriter(zw)
- for _, f := range sorted {
- if err := tw.WriteHeader(&tar.Header{
- Name: f.Path,
- Mode: int64(f.Mode),
- Size: int64(len(f.Content)),
- Typeflag: tar.TypeReg,
- ModTime: time.Unix(0, 0),
- }); err != nil {
- return nil, err
- }
- if _, err := tw.Write(f.Content); err != nil {
- return nil, err
- }
- }
- if err := tw.Close(); err != nil {
- return nil, err
- }
- if err := zw.Close(); err != nil {
- return nil, err
- }
- return buf.Bytes(), nil
-}
-
-// sortByPath orders entries by path bytes (insertion sort; a bundle is small).
-func sortByPath(files []File) {
- for i := 1; i < len(files); i++ {
- for j := i; j > 0 && files[j-1].Path > files[j].Path; j-- {
- files[j-1], files[j] = files[j], files[j-1]
- }
- }
-}
diff --git a/cmd/oc/internal/bundle/bundle_test.go b/cmd/oc/internal/bundle/bundle_test.go
deleted file mode 100644
index 506ef426..00000000
--- a/cmd/oc/internal/bundle/bundle_test.go
+++ /dev/null
@@ -1,125 +0,0 @@
-package bundle
-
-import (
- "archive/tar"
- "bytes"
- "compress/gzip"
- "io"
- "strings"
- "testing"
-)
-
-var files = []File{
- {Path: "artifact.json", Mode: 0o644, Content: []byte(`{"entry":"oc.js"}`)},
- {Path: "oc.js", Mode: 0o644, Content: []byte("export const x = 1;\n")},
- {Path: "skills/triage/SKILL.md", Mode: 0o644, Content: []byte("---\nname: triage\n---\n")},
- {Path: "bin/run.sh", Mode: 0o755, Content: []byte("#!/bin/sh\necho hi\n")},
-}
-
-// TestDigestIsBlobSha256 pins the contract: the address is sha256 of the packed
-// bytes, so it is exactly what any party recomputes by hashing the same object.
-func TestDigestIsBlobSha256(t *testing.T) {
- blob, err := Pack(files)
- if err != nil {
- t.Fatal(err)
- }
- if got := Digest(blob); got != Digest(blob) || !strings.HasPrefix(got, "sha256:") || len(got) != len("sha256:")+64 {
- t.Fatalf("unexpected digest shape: %s", got)
- }
- // Re-hashing the identical bytes (as the server/box do) yields the same value.
- same := Digest(append([]byte(nil), blob...))
- if same != Digest(blob) {
- t.Fatalf("digest not a pure function of the bytes: %s vs %s", same, Digest(blob))
- }
-}
-
-// TestPackDeterministic keeps identical input -> identical bytes (skill dedup).
-func TestPackDeterministic(t *testing.T) {
- a, err := Pack(files)
- if err != nil {
- t.Fatal(err)
- }
- // Input order must not matter (Pack sorts).
- rev := make([]File, len(files))
- for i, f := range files {
- rev[len(files)-1-i] = f
- }
- b, err := Pack(rev)
- if err != nil {
- t.Fatal(err)
- }
- if !bytes.Equal(a, b) {
- t.Fatal("Pack is not deterministic across input order")
- }
- if Digest(a) != Digest(b) {
- t.Fatal("digest depends on input order")
- }
-}
-
-// TestPackRoundTrip unpacks with a standard tar reader (what system tar / a real
-// TS reader does) and checks the fileset survives, including a long path the old
-// hand-rolled ustar codec had to special-case.
-func TestPackRoundTrip(t *testing.T) {
- long := "skills/" + strings.Repeat("a/", 60) + "SKILL.md" // ~130 bytes
- in := append(append([]File(nil), files...), File{Path: long, Mode: 0o644, Content: []byte("x")})
- blob, err := Pack(in)
- if err != nil {
- t.Fatal(err)
- }
- out, err := readTarGz(blob)
- if err != nil {
- t.Fatal(err)
- }
- if len(out) != len(in) {
- t.Fatalf("unpacked %d, want %d", len(out), len(in))
- }
- byPath := map[string]File{}
- for _, f := range out {
- byPath[f.Path] = f
- }
- for _, want := range in {
- got, ok := byPath[want.Path]
- if !ok {
- t.Fatalf("missing %q after round trip", want.Path)
- }
- if got.Mode != want.Mode || !bytes.Equal(got.Content, want.Content) {
- t.Errorf("%q changed: mode %o/%o", want.Path, got.Mode, want.Mode)
- }
- }
-}
-
-func TestNormalizeMode(t *testing.T) {
- cases := map[int]int{0o644: 0o644, 0o600: 0o644, 0o755: 0o755, 0o700: 0o755, 0o777: 0o755}
- for in, want := range cases {
- if got := NormalizeMode(in); got != want {
- t.Errorf("NormalizeMode(%o) = %o, want %o", in, got, want)
- }
- }
-}
-
-func readTarGz(tarGz []byte) ([]File, error) {
- zr, err := gzip.NewReader(bytes.NewReader(tarGz))
- if err != nil {
- return nil, err
- }
- tr := tar.NewReader(zr)
- var out []File
- for {
- hdr, err := tr.Next()
- if err == io.EOF {
- break
- }
- if err != nil {
- return nil, err
- }
- if hdr.Typeflag != tar.TypeReg {
- continue
- }
- content, err := io.ReadAll(tr)
- if err != nil {
- return nil, err
- }
- out = append(out, File{Path: hdr.Name, Mode: int(hdr.Mode) & 0o7777, Content: content})
- }
- return out, nil
-}
diff --git a/cmd/oc/internal/client/client.go b/cmd/oc/internal/client/client.go
deleted file mode 100644
index 461cd529..00000000
--- a/cmd/oc/internal/client/client.go
+++ /dev/null
@@ -1,335 +0,0 @@
-package client
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "strings"
-
- "github.com/gorilla/websocket"
-)
-
-type contextKey struct{}
-type sessionsContextKey struct{}
-
-// Client is an HTTP client for the OpenComputer API.
-type Client struct {
- baseURL string
- apiKey string
- token string // Bearer token for direct worker access
- httpClient *http.Client
-}
-
-// APIError represents an error response from the API.
-type APIError struct {
- StatusCode int
- Message string
-}
-
-func (e *APIError) Error() string {
- return fmt.Sprintf("API error %d: %s", e.StatusCode, e.Message)
-}
-
-// New creates a new API client.
-func New(baseURL, apiKey string) *Client {
- baseURL = strings.TrimRight(baseURL, "/")
- if !strings.HasSuffix(baseURL, "/api") {
- baseURL += "/api"
- }
- return &Client{
- baseURL: baseURL,
- apiKey: apiKey,
- httpClient: &http.Client{},
- }
-}
-
-// WithClient stores the client in the context.
-func WithClient(ctx context.Context, c *Client) context.Context {
- return context.WithValue(ctx, contextKey{}, c)
-}
-
-// FromContext retrieves the client from the context.
-func FromContext(ctx context.Context) *Client {
- return ctx.Value(contextKey{}).(*Client)
-}
-
-// WithSessionsClient stores the sessions-api client in the context.
-func WithSessionsClient(ctx context.Context, c *Client) context.Context {
- return context.WithValue(ctx, sessionsContextKey{}, c)
-}
-
-// SessionsFromContext retrieves the sessions-api client from the context.
-func SessionsFromContext(ctx context.Context) *Client {
- v := ctx.Value(sessionsContextKey{})
- if v == nil {
- return nil
- }
- return v.(*Client)
-}
-
-// NewSessionsAPI creates a client for the sessions-api service.
-// Uses X-API-Key auth but no /api prefix (sessions-api routes are /v1/...).
-func NewSessionsAPI(baseURL, apiKey string) *Client {
- baseURL = strings.TrimRight(baseURL, "/")
- return &Client{
- baseURL: baseURL,
- apiKey: apiKey,
- httpClient: &http.Client{},
- }
-}
-
-// NewWorker creates a client that authenticates with a Bearer token directly to a worker.
-// Worker routes have no /api prefix (unlike the control plane).
-func NewWorker(connectURL, token string) *Client {
- connectURL = strings.TrimRight(connectURL, "/")
- return &Client{
- baseURL: connectURL,
- token: token,
- httpClient: &http.Client{},
- }
-}
-
-func (c *Client) headers() http.Header {
- h := http.Header{}
- if c.token != "" {
- h.Set("Authorization", "Bearer "+c.token)
- } else if c.apiKey != "" {
- h.Set("X-API-Key", c.apiKey)
- }
- return h
-}
-
-func (c *Client) do(req *http.Request) (*http.Response, error) {
- for k, v := range c.headers() {
- req.Header[k] = v
- }
- resp, err := c.httpClient.Do(req)
- if err != nil {
- return nil, err
- }
- if resp.StatusCode >= 400 {
- defer resp.Body.Close()
- body, _ := io.ReadAll(resp.Body)
- // Two error shapes: the control plane returns {"error":"string"}; the
- // sessions-api (/v3) returns {"error":{"type","message"}}. Extract a clean
- // message from whichever applies (fall back to the raw body).
- var errResp struct {
- Error json.RawMessage `json:"error"`
- }
- msg := string(body)
- if json.Unmarshal(body, &errResp) == nil && len(errResp.Error) > 0 {
- var s string
- var obj struct {
- Message string `json:"message"`
- }
- if json.Unmarshal(errResp.Error, &s) == nil && s != "" {
- msg = s
- } else if json.Unmarshal(errResp.Error, &obj) == nil && obj.Message != "" {
- msg = obj.Message
- }
- }
- return nil, &APIError{StatusCode: resp.StatusCode, Message: msg}
- }
- return resp, nil
-}
-
-// Get performs a GET request and decodes the JSON response.
-func (c *Client) Get(ctx context.Context, path string, result interface{}) error {
- req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+path, nil)
- if err != nil {
- return err
- }
- resp, err := c.do(req)
- if err != nil {
- return err
- }
- defer resp.Body.Close()
- if result != nil {
- return json.NewDecoder(resp.Body).Decode(result)
- }
- return nil
-}
-
-// Post performs a POST request with a JSON body and decodes the response.
-func (c *Client) Post(ctx context.Context, path string, body, result interface{}) error {
- var bodyReader io.Reader
- if body != nil {
- data, err := json.Marshal(body)
- if err != nil {
- return err
- }
- bodyReader = bytes.NewReader(data)
- }
- req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+path, bodyReader)
- if err != nil {
- return err
- }
- if body != nil {
- req.Header.Set("Content-Type", "application/json")
- }
- resp, err := c.do(req)
- if err != nil {
- return err
- }
- defer resp.Body.Close()
- if result != nil {
- return json.NewDecoder(resp.Body).Decode(result)
- }
- return nil
-}
-
-// Patch performs a PATCH request with a JSON body and decodes the response.
-func (c *Client) Patch(ctx context.Context, path string, body, result interface{}) error {
- var bodyReader io.Reader
- if body != nil {
- data, err := json.Marshal(body)
- if err != nil {
- return err
- }
- bodyReader = bytes.NewReader(data)
- }
- req, err := http.NewRequestWithContext(ctx, "PATCH", c.baseURL+path, bodyReader)
- if err != nil {
- return err
- }
- if body != nil {
- req.Header.Set("Content-Type", "application/json")
- }
- resp, err := c.do(req)
- if err != nil {
- return err
- }
- defer resp.Body.Close()
- if result != nil {
- return json.NewDecoder(resp.Body).Decode(result)
- }
- return nil
-}
-
-// GetStream performs a GET request and returns the raw response so the
-// caller can stream chunks (e.g. SSE log feeds). Caller closes resp.Body.
-func (c *Client) GetStream(ctx context.Context, path string) (*http.Response, error) {
- req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+path, nil)
- if err != nil {
- return nil, err
- }
- req.Header.Set("Accept", "text/event-stream")
- return c.do(req)
-}
-
-// PostStream performs a POST request and returns the raw response so the
-// caller can stream chunks (e.g. SSE / chat-completions). Caller is
-// responsible for closing resp.Body.
-func (c *Client) PostStream(ctx context.Context, path string, body interface{}) (*http.Response, error) {
- var bodyReader io.Reader
- if body != nil {
- data, err := json.Marshal(body)
- if err != nil {
- return nil, err
- }
- bodyReader = bytes.NewReader(data)
- }
- req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+path, bodyReader)
- if err != nil {
- return nil, err
- }
- if body != nil {
- req.Header.Set("Content-Type", "application/json")
- }
- req.Header.Set("Accept", "text/event-stream")
- return c.do(req)
-}
-
-// Put performs a PUT request with a raw body.
-func (c *Client) Put(ctx context.Context, path string, body io.Reader) error {
- req, err := http.NewRequestWithContext(ctx, "PUT", c.baseURL+path, body)
- if err != nil {
- return err
- }
- resp, err := c.do(req)
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
-
-// PutJSON performs a PUT request with a JSON body and decodes the response.
-func (c *Client) PutJSON(ctx context.Context, path string, body, result interface{}) error {
- var bodyReader io.Reader
- if body != nil {
- data, err := json.Marshal(body)
- if err != nil {
- return err
- }
- bodyReader = bytes.NewReader(data)
- }
- req, err := http.NewRequestWithContext(ctx, "PUT", c.baseURL+path, bodyReader)
- if err != nil {
- return err
- }
- if body != nil {
- req.Header.Set("Content-Type", "application/json")
- }
- resp, err := c.do(req)
- if err != nil {
- return err
- }
- defer resp.Body.Close()
- if result != nil {
- return json.NewDecoder(resp.Body).Decode(result)
- }
- return nil
-}
-
-// Delete performs a DELETE request.
-func (c *Client) Delete(ctx context.Context, path string) error {
- req, err := http.NewRequestWithContext(ctx, "DELETE", c.baseURL+path, nil)
- if err != nil {
- return err
- }
- resp, err := c.do(req)
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
-
-// DeleteIgnoreNotFound performs a DELETE request, ignoring 404 errors.
-func (c *Client) DeleteIgnoreNotFound(ctx context.Context, path string) error {
- err := c.Delete(ctx, path)
- if err != nil {
- if apiErr, ok := err.(*APIError); ok && apiErr.StatusCode == 404 {
- return nil
- }
- }
- return err
-}
-
-// DialWebSocket opens a WebSocket connection.
-func (c *Client) DialWebSocket(ctx context.Context, path string) (*websocket.Conn, error) {
- wsURL := c.baseURL + path
- wsURL = strings.Replace(wsURL, "http://", "ws://", 1)
- wsURL = strings.Replace(wsURL, "https://", "wss://", 1)
-
- dialer := websocket.Dialer{}
- conn, _, err := dialer.DialContext(ctx, wsURL, c.headers())
- if err != nil {
- return nil, fmt.Errorf("websocket dial: %w", err)
- }
- return conn, nil
-}
-
-// PostRaw performs a POST with no body and returns no result (for simple actions).
-func (c *Client) PostRaw(ctx context.Context, path string) error {
- return c.Post(ctx, path, nil, nil)
-}
-
-// BaseURL returns the client's base URL.
-func (c *Client) BaseURL() string {
- return c.baseURL
-}
diff --git a/cmd/oc/internal/commands/agent.go b/cmd/oc/internal/commands/agent.go
deleted file mode 100644
index 5a04952e..00000000
--- a/cmd/oc/internal/commands/agent.go
+++ /dev/null
@@ -1,184 +0,0 @@
-package commands
-
-// The `oc agent` command family, rebuilt on the v3 Durable Agent Sessions API
-// (/v3/agents/*). The legacy v1 managed-agents verbs (channels/packages/chat)
-// were removed wholesale — agents are reusable behaviors deployed as numbered
-// revisions, a different model entirely. Built-in runtimes use prompt + model
-// + skills; framework runtimes such as Flue carry behavior in their app.
-//
-// Verbs (each in its own file):
-// agent.go — parent command, shared response types, helpers, registration
-// agent_crud.go — create / list / get
-// agent_deploy.go — deploy / revisions / rollback / status / link / unlink / deployments
-// Sessions live under `oc session` (session.go).
-
-import (
- "bufio"
- "fmt"
- "os"
- "strings"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-// ── Shared response types (mirror the sessions-api JSON, snake_case) ──
-
-type RevisionRef struct {
- ID string `json:"id"`
- Number int `json:"number"`
- Digest string `json:"digest"`
-}
-
-type Agent struct {
- ID string `json:"id"`
- Name string `json:"name"`
- InvokeURL string `json:"invoke_url"`
- Prompt string `json:"prompt,omitempty"`
- Model string `json:"model"`
- Runtime string `json:"runtime"`
- CredentialID *string `json:"credential_id,omitempty"`
- ActiveRevisionID string `json:"active_revision_id,omitempty"`
- ActiveRevision *RevisionRef `json:"active_revision,omitempty"`
- CreatedAt string `json:"created_at"`
-}
-
-type AgentList struct {
- Data []Agent `json:"data"`
- NextCursor *string `json:"next_cursor,omitempty"`
-}
-
-type Revision struct {
- ID string `json:"id"`
- Number int `json:"number"`
- Digest string `json:"digest"`
- CreatedAt string `json:"created_at"`
- Active bool `json:"active"`
-}
-
-type RevisionList struct {
- Data []Revision `json:"data"`
-}
-
-type Deployment struct {
- ID string `json:"id"`
- State string `json:"state"`
- Result string `json:"result,omitempty"`
- RevisionID string `json:"revision_id,omitempty"`
- InputType string `json:"input_type,omitempty"`
- Ref string `json:"ref,omitempty"`
- Sha string `json:"sha,omitempty"`
- Active bool `json:"active,omitempty"`
- ErrorClass string `json:"error_class,omitempty"`
- Error map[string]interface{} `json:"error,omitempty"`
- Source map[string]interface{} `json:"source,omitempty"`
- CreatedAt string `json:"created_at,omitempty"`
-}
-
-type DeploymentEnvelope struct {
- Deployment Deployment `json:"deployment"`
-}
-
-type DeploymentList struct {
- Data []Deployment `json:"data"`
-}
-
-type DeploymentSource struct {
- AgentID string `json:"agent_id"`
- RepoID string `json:"repo_id"`
- Path string `json:"path"`
- ProductionRef string `json:"production_ref"`
- Status string `json:"status"`
- LatestSeenSha string `json:"latest_seen_sha,omitempty"`
- ActiveDeployedSha string `json:"active_deployed_sha,omitempty"`
-}
-
-type SourceEnvelope struct {
- Source DeploymentSource `json:"source"`
- DeploymentID string `json:"deployment_id,omitempty"`
- DeployError *struct {
- Type string `json:"type"`
- Message string `json:"message"`
- } `json:"deploy_error,omitempty"`
-}
-
-// ── Helpers ──
-
-// sessionsClient returns the sessions-api (/v3) client from context, or errors.
-func sessionsClient(cmd *cobra.Command) (*client.Client, error) {
- c := client.SessionsFromContext(cmd.Context())
- if c == nil {
- return nil, fmt.Errorf("sessions-api URL not configured. Set SESSIONS_API_URL or use --sessions-api-url")
- }
- return c, nil
-}
-
-func formatAge(isoTime string) string {
- if isoTime == "" {
- return "-"
- }
- t, err := time.Parse(time.RFC3339Nano, isoTime)
- if err != nil {
- return isoTime
- }
- return time.Since(t).Truncate(time.Second).String()
-}
-
-func shortSha(sha string) string {
- if len(sha) > 7 {
- return sha[:7]
- }
- return sha
-}
-
-// stdinIsTTY reports whether stdin is attached to a terminal.
-func stdinIsTTY() bool {
- fi, err := os.Stdin.Stat()
- if err != nil {
- return false
- }
- return (fi.Mode() & os.ModeCharDevice) != 0
-}
-
-// confirmDestructive gates destructive verbs on explicit consent: --yes proceeds;
-// a TTY prompts; a non-TTY without --yes refuses (scripts must pass --yes).
-func confirmDestructive(cmd *cobra.Command, action string) error {
- if yes, _ := cmd.Flags().GetBool("yes"); yes {
- return nil
- }
- if !stdinIsTTY() {
- return fmt.Errorf("refusing to %s without --yes (stdin is not a terminal)", action)
- }
- fmt.Fprintf(os.Stderr, "%s? [y/N] ", action)
- line, _ := bufio.NewReader(os.Stdin).ReadString('\n')
- switch strings.ToLower(strings.TrimSpace(line)) {
- case "y", "yes":
- return nil
- default:
- return fmt.Errorf("aborted")
- }
-}
-
-// ── Parent command ──
-
-var agentCmd = &cobra.Command{
- Use: "agent",
- Short: "Create, deploy, and manage agents",
- Long: "Manage Durable Agent Sessions agents on OpenComputer.\n\n" +
- "An agent is reusable behavior for durable sessions. Built-in agents combine\n" +
- "a prompt, model, and skills; Flue agents deploy a compiled app. Deploying\n" +
- "produces a numbered revision; the active revision is what new sessions run.\n" +
- "Deploy from a local directory (`oc agent deploy`) or link a GitHub repo for\n" +
- "push-to-deploy (`oc agent link`).",
-}
-
-func init() {
- registerAgentCrud()
- registerAgentDeploy()
- registerAgentConfig()
- registerAgentSchedules()
- registerAgentInvoke()
- registerAgentHooks()
- rootCmd.AddCommand(sessionCmd)
-}
diff --git a/cmd/oc/internal/commands/agent_build.go b/cmd/oc/internal/commands/agent_build.go
deleted file mode 100644
index 936821a7..00000000
--- a/cmd/oc/internal/commands/agent_build.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package commands
-
-import (
- "encoding/json"
- "fmt"
- "os"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/fluebuild"
- "github.com/spf13/cobra"
-)
-
-const offlineCommandAnnotation = "opencomputer.dev/offline"
-
-var agentBuildCmd = &cobra.Command{
- Use: "build",
- Short: "Build a Flue deployment artifact without deploying it",
- Long: "Validate and build a Flue repository into bundle.tgz and deployment.json.\n\n" +
- "This command does not fetch source, install dependencies, authenticate, upload,\n" +
- "or deploy. Run npm ci before a full build. --check-only validates source and\n" +
- "configuration without executing repository code or requiring node_modules.",
- Example: " oc agent build --dir . --target cloudflare --output /tmp/flue-build --json\n" +
- " oc agent build --dir . --check-only --json",
- Args: cobra.NoArgs,
- Annotations: map[string]string{offlineCommandAnnotation: "true"},
- RunE: func(cmd *cobra.Command, _ []string) error {
- dir, _ := cmd.Flags().GetString("dir")
- target, _ := cmd.Flags().GetString("target")
- output, _ := cmd.Flags().GetString("output")
- checkOnly, _ := cmd.Flags().GetBool("check-only")
- if !checkOnly && output == "" {
- return fmt.Errorf("--output is required unless --check-only is set")
- }
-
- result, err := fluebuild.Build(cmd.Context(), fluebuild.Options{
- Dir: dir,
- Target: target,
- OutputDir: output,
- BuilderVersion: Version,
- SynthesisTemplateVersion: os.Getenv("OC_FLUE_SYNTH_TEMPLATE_VERSION"),
- CheckOnly: checkOnly,
- })
- if err != nil {
- return err
- }
- if jsonOutput {
- encoder := json.NewEncoder(os.Stdout)
- encoder.SetEscapeHTML(false)
- return encoder.Encode(result.Deployment)
- }
- if checkOnly {
- fmt.Printf("Valid Flue entrypoint %s (%s, %s/%s)\n",
- result.Deployment.Flue.Entrypoint,
- result.Deployment.Model,
- result.Deployment.Runtime.Family,
- result.Deployment.Runtime.Type)
- return nil
- }
- fmt.Printf("Built %s and %s in %s (%s, %d bytes)\n",
- fluebuild.BundleFilename,
- fluebuild.DeploymentFilename,
- output,
- result.Deployment.Bundle.Digest,
- result.Deployment.Bundle.SizeBytes)
- return nil
- },
-}
-
-func init() {
- agentBuildCmd.Flags().String("dir", ".", "Flue repository root")
- agentBuildCmd.Flags().String("target", fluebuild.TargetCloudflare, "Build target")
- agentBuildCmd.Flags().String("output", "", "Directory for bundle.tgz and deployment.json")
- agentBuildCmd.Flags().Bool("check-only", false, "Validate without executing repository code")
-}
diff --git a/cmd/oc/internal/commands/agent_config.go b/cmd/oc/internal/commands/agent_config.go
deleted file mode 100644
index 2260a217..00000000
--- a/cmd/oc/internal/commands/agent_config.go
+++ /dev/null
@@ -1,157 +0,0 @@
-package commands
-
-// Preview Flue configuration has one source of truth: non-secret vars come from agent.toml and
-// write-only secrets come from this command. Both are applied by the next explicit agent deploy.
-
-import (
- "fmt"
- "io"
- "net/url"
- "os"
- "strings"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-type agentConfig struct {
- Vars map[string]string `json:"vars"`
- DeploymentRequired bool `json:"deployment_required,omitempty"`
-}
-
-type agentSecret struct {
- Name string `json:"name"`
- Last4 string `json:"last4"`
- UpdatedAt string `json:"updated_at"`
- DeploymentRequired bool `json:"deployment_required,omitempty"`
-}
-
-type agentSecretList struct {
- Data []agentSecret `json:"data"`
-}
-
-func agentConfigPath(id string) string { return "/v3/agents/" + id + "/config" }
-func agentSecretsPath(id string) string { return "/v3/agents/" + id + "/secrets" }
-func agentSecretPath(id, name string) string {
- return agentSecretsPath(id) + "/" + url.PathEscape(name)
-}
-
-// syncManifestVars makes agent.toml the only non-secret config source. An absent [vars] section is
-// an empty desired map, so deleting the section and deploying removes prior bindings.
-func syncManifestVars(cmd *cobra.Command, sc *client.Client, id string, m *manifest) error {
- vars := m.Vars
- if vars == nil {
- vars = map[string]string{}
- }
- var saved agentConfig
- if err := sc.PutJSON(cmd.Context(), agentConfigPath(id), map[string]interface{}{"vars": vars}, &saved); err != nil {
- return fmt.Errorf("sync agent.toml [vars]: %w", err)
- }
- return nil
-}
-
-var agentSecretCmd = &cobra.Command{
- Use: "secret",
- Short: "Manage write-only Flue Worker secrets for the next deploy",
-}
-
-var agentSecretListCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List secret metadata (values are never returned)",
- Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, _ []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- id, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- var res agentSecretList
- if err := sc.Get(cmd.Context(), agentSecretsPath(id), &res); err != nil {
- return err
- }
- printer.Print(res.Data, func() {
- if len(res.Data) == 0 {
- fmt.Println("No secrets.")
- return
- }
- rows := make([][]string, 0, len(res.Data))
- for _, secret := range res.Data {
- rows = append(rows, []string{secret.Name, secret.Last4, formatAge(secret.UpdatedAt)})
- }
- printer.Table([]string{"NAME", "LAST4", "UPDATED"}, rows)
- })
- return nil
- },
-}
-
-var agentSecretSetCmd = &cobra.Command{
- Use: "set <name> --from-stdin",
- Short: "Save or rotate a Worker secret for the next deploy",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- fromStdin, _ := cmd.Flags().GetBool("from-stdin")
- if !fromStdin {
- return fmt.Errorf("secret values are accepted only via --from-stdin")
- }
- raw, err := io.ReadAll(os.Stdin)
- if err != nil {
- return fmt.Errorf("reading stdin: %w", err)
- }
- value := strings.TrimSuffix(strings.TrimSuffix(string(raw), "\n"), "\r")
- if value == "" {
- return fmt.Errorf("secret value cannot be empty")
- }
-
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- id, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- var saved agentSecret
- if err := sc.PutJSON(cmd.Context(), agentSecretPath(id, args[0]), map[string]string{"value": value}, &saved); err != nil {
- return err
- }
- printer.Print(saved, func() {
- fmt.Printf("Secret %s saved. Run `oc agent deploy` to apply it.\n", saved.Name)
- })
- return nil
- },
-}
-
-var agentSecretDeleteCmd = &cobra.Command{
- Use: "delete <name>",
- Aliases: []string{"rm"},
- Short: "Remove a Worker secret on the next deploy",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- id, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- if err := sc.Delete(cmd.Context(), agentSecretPath(id, args[0])); err != nil {
- return err
- }
- fmt.Printf("Secret %s removed. Run `oc agent deploy` to apply it.\n", args[0])
- return nil
- },
-}
-
-func registerAgentConfig() {
- for _, command := range []*cobra.Command{agentSecretListCmd, agentSecretSetCmd, agentSecretDeleteCmd} {
- command.Flags().String("agent", "", "Target agent id or name (else the cwd agent.toml)")
- }
- agentSecretSetCmd.Flags().Bool("from-stdin", false, "Read the secret value from stdin")
- agentSecretCmd.AddCommand(agentSecretListCmd, agentSecretSetCmd, agentSecretDeleteCmd)
- agentCmd.AddCommand(agentSecretCmd)
-}
diff --git a/cmd/oc/internal/commands/agent_config_test.go b/cmd/oc/internal/commands/agent_config_test.go
deleted file mode 100644
index 8243ad34..00000000
--- a/cmd/oc/internal/commands/agent_config_test.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package commands
-
-import (
- "strings"
- "testing"
-)
-
-func TestAgentSecretSetRejectsPositionalValue(t *testing.T) {
- if err := agentSecretSetCmd.Args(agentSecretSetCmd, []string{"TOKEN", "secret-value"}); err == nil {
- t.Fatal("expected a positional secret value to be rejected")
- }
-}
-
-func TestAgentSecretSetRequiresStdinFlag(t *testing.T) {
- if err := agentSecretSetCmd.Flags().Set("from-stdin", "false"); err != nil {
- t.Fatal(err)
- }
- err := agentSecretSetCmd.RunE(agentSecretSetCmd, []string{"TOKEN"})
- if err == nil || !strings.Contains(err.Error(), "--from-stdin") {
- t.Fatalf("error = %v, want --from-stdin requirement", err)
- }
-}
diff --git a/cmd/oc/internal/commands/agent_crud.go b/cmd/oc/internal/commands/agent_crud.go
deleted file mode 100644
index 2c9015a9..00000000
--- a/cmd/oc/internal/commands/agent_crud.go
+++ /dev/null
@@ -1,130 +0,0 @@
-package commands
-
-import (
- "fmt"
-
- "github.com/spf13/cobra"
-)
-
-var agentCreateCmd = &cobra.Command{
- Use: "create <name>",
- Short: "Create an agent",
- Example: " oc agent create issue-fixer --prompt \"You fix issues.\" --model anthropic/claude-sonnet-5\n" +
- " (tip: `oc agent init` + `oc agent deploy` is the usual flow — create is for quick one-offs)",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- prompt, _ := cmd.Flags().GetString("prompt")
- model, _ := cmd.Flags().GetString("model")
- runtime, _ := cmd.Flags().GetString("runtime")
- credential, _ := cmd.Flags().GetString("credential")
- // Flue agents carry their instructions in code, so --prompt is optional
- // for them (required for every other runtime).
- if prompt == "" && runtime != "flue" {
- return fmt.Errorf("--prompt is required")
- }
- if model == "" {
- return fmt.Errorf("--model is required")
- }
- body := map[string]interface{}{"name": args[0], "model": model}
- if prompt != "" {
- body["prompt"] = prompt
- }
- if runtime != "" {
- body["runtime"] = runtime
- }
- if credential != "" {
- body["credential"] = credential
- }
- var a Agent
- if err := sc.Post(cmd.Context(), "/v3/agents", body, &a); err != nil {
- return err
- }
- printer.Print(a, func() {
- fmt.Printf("Created agent %s (%s)\n", a.Name, a.ID)
- if a.ActiveRevision != nil {
- fmt.Printf("Active revision: %d\n", a.ActiveRevision.Number)
- }
- })
- return nil
- },
-}
-
-var agentListCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List agents",
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- var resp AgentList
- if err := sc.Get(cmd.Context(), "/v3/agents", &resp); err != nil {
- return err
- }
- printer.Print(resp.Data, func() {
- if len(resp.Data) == 0 {
- fmt.Println("No agents found.")
- return
- }
- headers := []string{"ID", "NAME", "MODEL", "RUNTIME", "ACTIVE_REV", "CREATED"}
- var rows [][]string
- for _, a := range resp.Data {
- rev := "-"
- if a.ActiveRevision != nil {
- rev = fmt.Sprintf("%d", a.ActiveRevision.Number)
- }
- rows = append(rows, []string{a.ID, a.Name, a.Model, a.Runtime, rev, formatAge(a.CreatedAt)})
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var agentGetCmd = &cobra.Command{
- Use: "get [id|name]",
- Short: "Show an agent (defaults to the agent.toml in the current directory)",
- Args: cobra.MaximumNArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- id, err := targetAgentID(cmd, sc, args)
- if err != nil {
- return err
- }
- var a Agent
- if err := sc.Get(cmd.Context(), "/v3/agents/"+id, &a); err != nil {
- return err
- }
- printer.Print(a, func() {
- fmt.Printf("ID: %s\n", a.ID)
- fmt.Printf("Name: %s\n", a.Name)
- fmt.Printf("Model: %s\n", a.Model)
- fmt.Printf("Runtime: %s\n", a.Runtime)
- if a.ActiveRevision != nil {
- fmt.Printf("Active: revision %d (%s)\n", a.ActiveRevision.Number, a.ActiveRevision.Digest)
- }
- fmt.Printf("Created: %s ago\n", formatAge(a.CreatedAt))
- })
- return nil
- },
-}
-
-func registerAgentCrud() {
- agentCreateCmd.Flags().String("prompt", "", "System prompt (required, except --runtime flue)")
- agentCreateCmd.Flags().String("model", "", "Model, e.g. anthropic/claude-sonnet-5 (required)")
- agentCreateCmd.Flags().String("runtime", "claude", "Runtime family (claude|codex|pi|flue)")
- agentCreateCmd.Flags().String("credential", "", "Credential id (optional)")
- agentGetCmd.Flags().String("agent", "", "Agent id or name (else the cwd agent.toml)")
-
- agentCmd.AddCommand(agentCreateCmd)
- agentCmd.AddCommand(agentListCmd)
- agentCmd.AddCommand(agentGetCmd)
-}
diff --git a/cmd/oc/internal/commands/agent_deploy.go b/cmd/oc/internal/commands/agent_deploy.go
deleted file mode 100644
index 12870b5f..00000000
--- a/cmd/oc/internal/commands/agent_deploy.go
+++ /dev/null
@@ -1,773 +0,0 @@
-package commands
-
-import (
- "fmt"
- "io"
- "io/fs"
- "net/url"
- "os"
- "path/filepath"
- "strings"
- "time"
-
- "github.com/BurntSushi/toml"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/config"
- "github.com/spf13/cobra"
- "golang.org/x/term"
-)
-
-// ── agent.toml manifest + deploy bundle ──
-
-type manifest struct {
- Name string `toml:"name"`
- Model string `toml:"model"`
- // Non-secret Flue Worker bindings. The manifest is authoritative: omitting
- // [vars] clears prior values on deploy. Secrets never belong in agent.toml.
- Vars map[string]string `toml:"vars"`
- Runtime struct {
- Family string `toml:"family"`
- Type string `toml:"type"`
- } `toml:"runtime"`
- Agent struct {
- ID string `toml:"id"`
- } `toml:"agent"`
- Limits map[string]interface{} `toml:"limits"`
- Schedules []scheduleDecl `toml:"schedules"` // cron for agents (015); synced on deploy-activate
-}
-
-// One agent.toml [[schedules]] entry. Rides the deployment input; the server syncs on activate.
-type scheduleDecl struct {
- Name string `toml:"name" json:"name"`
- Cron string `toml:"cron" json:"cron"`
- TZ string `toml:"tz,omitempty" json:"tz,omitempty"`
- Input string `toml:"input" json:"input"`
- Overlap string `toml:"overlap,omitempty" json:"overlap,omitempty"`
-}
-
-type skillFile struct {
- Path string `json:"path"`
- Content string `json:"content"`
- Mode int `json:"mode,omitempty"`
-}
-
-func readManifest(dir string) (*manifest, error) {
- var m manifest
- if _, err := toml.DecodeFile(filepath.Join(dir, "agent.toml"), &m); err != nil {
- return nil, err
- }
- return &m, nil
-}
-
-func readPrompt(dir string) (string, error) {
- b, err := os.ReadFile(filepath.Join(dir, "prompt.md"))
- if err != nil {
- return "", err
- }
- return string(b), nil
-}
-
-// readSkills walks <dir>/skills/** into skill-root-relative SkillFiles (e.g.
-// "hello/SKILL.md"), matching the inline-deploy + worker convention. Returns
-// nil (not an error) when there is no skills/ directory.
-func readSkills(dir string) ([]skillFile, error) {
- root := filepath.Join(dir, "skills")
- info, err := os.Stat(root)
- if err != nil || !info.IsDir() {
- return nil, nil
- }
- var out []skillFile
- err = filepath.WalkDir(root, func(p string, d fs.DirEntry, walkErr error) error {
- if walkErr != nil {
- return walkErr
- }
- if d.IsDir() {
- return nil
- }
- rel, _ := filepath.Rel(root, p)
- b, err := os.ReadFile(p)
- if err != nil {
- return err
- }
- mode := 0o644
- if st, err := d.Info(); err == nil && st.Mode()&0o111 != 0 {
- mode = 0o755
- }
- out = append(out, skillFile{Path: filepath.ToSlash(rel), Content: string(b), Mode: mode})
- return nil
- })
- return out, err
-}
-
-// ── Agent resolution (§4.2) ──
-
-// targetAgentID resolves the agent a verb acts on: explicit arg > --agent flag >
-// the cwd agent.toml ([agent].id, else name). Errors if none apply.
-func targetAgentID(cmd *cobra.Command, sc *client.Client, args []string) (string, error) {
- if len(args) > 0 && strings.TrimSpace(args[0]) != "" {
- return resolveRef(cmd, sc, args[0])
- }
- if explicit, _ := cmd.Flags().GetString("agent"); explicit != "" {
- return resolveRef(cmd, sc, explicit)
- }
- if m, err := readManifest("."); err == nil {
- if m.Agent.ID != "" {
- return m.Agent.ID, nil
- }
- if m.Name != "" {
- return resolveRef(cmd, sc, m.Name)
- }
- }
- return "", fmt.Errorf("no agent — pass <id|name>, --agent, or run inside an agent directory with agent.toml")
-}
-
-// resolveRef maps an "agt_…" id (used as-is) or a name (looked up) to an id.
-func resolveRef(cmd *cobra.Command, sc *client.Client, ref string) (string, error) {
- if strings.HasPrefix(ref, "agt_") {
- return ref, nil
- }
- var list AgentList
- if err := sc.Get(cmd.Context(), "/v3/agents", &list); err != nil {
- return "", err
- }
- for _, a := range list.Data {
- if a.Name == ref {
- return a.ID, nil
- }
- }
- return "", fmt.Errorf("no agent named %q", ref)
-}
-
-func revisionNumber(cmd *cobra.Command, sc *client.Client, id, revisionID string) int {
- if revisionID == "" {
- return 0
- }
- var revs RevisionList
- if err := sc.Get(cmd.Context(), "/v3/agents/"+id+"/revisions", &revs); err != nil {
- return 0
- }
- for _, r := range revs.Data {
- if r.ID == revisionID {
- return r.Number
- }
- }
- return 0
-}
-
-// loadDeployHandoff fetches the public URL only for human-readable output. A
-// successful deployment stays successful if this convenience read fails; the
-// user can still retrieve the URL with `oc agent get`.
-func loadDeployHandoff(cmd *cobra.Command, sc *client.Client, id string) Agent {
- agent := Agent{ID: id}
- if err := sc.Get(cmd.Context(), "/v3/agents/"+id, &agent); err != nil {
- return Agent{ID: id}
- }
- if agent.ID == "" {
- agent.ID = id
- }
- return agent
-}
-
-type deploySuccess struct {
- Agent Agent
- Revision int
- Status string
- Digest string
-}
-
-type deployOutputStyle struct {
- color bool
- hyperlinks bool
-}
-
-func deployStyleFor(w io.Writer) deployOutputStyle {
- file, ok := w.(*os.File)
- if !ok || !term.IsTerminal(int(file.Fd())) || os.Getenv("TERM") == "dumb" {
- return deployOutputStyle{}
- }
- return deployOutputStyle{
- color: !noColor && os.Getenv("NO_COLOR") == "",
- hyperlinks: true,
- }
-}
-
-func ansiText(value, code string, enabled bool) string {
- if !enabled {
- return value
- }
- return "\x1b[" + code + "m" + value + "\x1b[0m"
-}
-
-func oneLine(value string) string {
- return strings.Map(func(r rune) rune {
- if r == '\n' || r == '\r' || r == '\x1b' || r == '\a' || r < 0x20 || r == 0x7f {
- return ' '
- }
- return r
- }, value)
-}
-
-func terminalLink(rawURL string, style deployOutputStyle) string {
- visible := oneLine(rawURL)
- if visible != rawURL {
- return visible
- }
- parsed, err := url.ParseRequestURI(rawURL)
- if err != nil || parsed.Scheme != "https" || parsed.Host == "" {
- return visible
- }
- visible = ansiText(visible, "4;36", style.color)
- if !style.hyperlinks {
- return visible
- }
- return "\x1b]8;;" + rawURL + "\x1b\\" + visible + "\x1b]8;;\x1b\\"
-}
-
-func renderDeploySuccess(w io.Writer, success deploySuccess, style deployOutputStyle) {
- agentID := oneLine(success.Agent.ID)
- name := oneLine(success.Agent.Name)
- if name == "" {
- name = agentID
- }
- if name == "" {
- name = "agent"
- }
-
- mark := ansiText("✓", "32", style.color)
- title := "Deployed " + ansiText(name, "1", style.color)
- fmt.Fprintf(w, "%s %s\n", mark, title)
-
- status := oneLine(success.Status)
- statusCode := "32"
- if status == "staged" {
- statusCode = "33"
- }
- status = ansiText(status, statusCode, style.color)
- var revisionParts []string
- if success.Revision > 0 {
- revisionParts = append(revisionParts, fmt.Sprintf("%d", success.Revision))
- }
- if status != "" {
- revisionParts = append(revisionParts, status)
- }
- if digest := oneLine(success.Digest); digest != "" {
- revisionParts = append(revisionParts, digest)
- }
- if success.Agent.InvokeURL != "" {
- fmt.Fprintf(w, "\n %s\n", ansiText("Agent URL", "1", style.color))
- fmt.Fprintf(w, " %s\n", terminalLink(success.Agent.InvokeURL, style))
- }
- if len(revisionParts) > 0 {
- fmt.Fprintf(w, "\n %-11s %s\n", "Revision", strings.Join(revisionParts, " · "))
- }
- if agentID != "" {
- manageURL := strings.TrimRight(config.DefaultAPIURL, "/") + "/agents/" + url.PathEscape(agentID)
- fmt.Fprintf(w, " %-11s %s\n", "Dashboard", terminalLink(manageURL, style))
- fmt.Fprintf(w, "\n %s\n", ansiText("Try it", "1", style.color))
- fmt.Fprintf(w, " %s oc agent invoke %s --data '{\"message\":\"Hello\"}'\n", ansiText("$", "2", style.color), agentID)
- }
-}
-
-func printDeploySuccess(w io.Writer, success deploySuccess) {
- renderDeploySuccess(w, success, deployStyleFor(w))
-}
-
-// ── async deployment polling ──
-
-func terminalState(s string) bool {
- switch s {
- case "ready", "failed", "skipped", "superseded":
- return true
- }
- return false
-}
-
-func deployFailMsg(d Deployment) string {
- if m, ok := d.Error["message"].(string); ok && m != "" {
- return m
- }
- if d.ErrorClass != "" {
- return d.ErrorClass
- }
- return "unknown error"
-}
-
-// pollDeployment polls a deployment until it reaches a terminal state or the
-// timeout elapses, printing each state transition to stderr on a TTY.
-func pollDeployment(cmd *cobra.Command, sc *client.Client, agentID, depID string, timeout time.Duration) (Deployment, error) {
- deadline := time.Now().Add(timeout)
- last := ""
- for {
- var d Deployment
- if err := sc.Get(cmd.Context(), "/v3/agents/"+agentID+"/deployments/"+depID, &d); err != nil {
- return d, err
- }
- if d.State != last {
- printDeployProgress(d.State)
- }
- last = d.State
- if terminalState(d.State) {
- return d, nil
- }
- if time.Now().After(deadline) {
- return d, fmt.Errorf("timed out after %s waiting for deployment %s (last state: %s)", timeout, depID, d.State)
- }
- time.Sleep(2 * time.Second)
- }
-}
-
-func printDeployProgress(state string) {
- if stdinIsTTY() && !jsonOutput {
- fmt.Fprintf(os.Stderr, " … %s\n", state)
- }
-}
-
-// ── deploy ──
-
-var agentDeployCmd = &cobra.Command{
- Use: "deploy [dir]",
- Short: "Deploy an agent from a local directory",
- Example: " oc agent deploy # deploy the agent.toml in the current directory\n" +
- " oc agent deploy ./agents/triage # deploy a specific directory\n" +
- " oc agent deploy --no-activate # stage a revision without making it active\n" +
- " oc agent deploy --idempotency-key $GITHUB_SHA # CI-safe (retries return the same deploy)",
- Args: cobra.MaximumNArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- dir := "."
- if len(args) > 0 {
- dir = args[0]
- }
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- m, err := readManifest(dir)
- if err != nil {
- return fmt.Errorf("read agent.toml: %w", err)
- }
- if m.Name == "" && m.Agent.ID == "" {
- return fmt.Errorf("agent.toml needs a `name` (or [agent].id)")
- }
- if m.Model == "" {
- return fmt.Errorf("agent.toml needs a `model`")
- }
- // Flue agents deploy a built artifact, not prompt.md/skills/ (§11.7.8).
- if m.Runtime.Family == "flue" {
- noActivate, _ := cmd.Flags().GetBool("no-activate")
- return deployFlue(cmd, sc, dir, m, noActivate)
- }
- prompt, err := readPrompt(dir)
- if err != nil {
- return fmt.Errorf("read prompt.md: %w", err)
- }
- skills, err := readSkills(dir)
- if err != nil {
- return fmt.Errorf("read skills/: %w", err)
- }
- runtime := m.Runtime.Family
- if runtime == "" {
- runtime = "claude"
- }
-
- explicit, _ := cmd.Flags().GetString("agent")
- var id string
- created := false
- switch {
- case explicit != "":
- id, err = resolveRef(cmd, sc, explicit)
- case m.Agent.ID != "":
- id = m.Agent.ID
- default:
- id, created, err = ensureAgentByName(cmd, sc, m.Name, prompt, m.Model, runtime)
- }
- if err != nil {
- return err
- }
-
- noActivate, _ := cmd.Flags().GetBool("no-activate")
-
- // A fresh agent with no skills: `create` already produced the first
- // revision (the deploy) — don't append a redundant identical one.
- if created && len(skills) == 0 {
- a := Agent{ID: id}
- _ = sc.Get(cmd.Context(), "/v3/agents/"+id, &a)
- n := 0
- if a.ActiveRevision != nil {
- n = a.ActiveRevision.Number
- }
- printer.Print(map[string]interface{}{"agent_id": id, "revision": n, "state": "ready", "active": true}, func() {
- printDeploySuccess(printer.W, deploySuccess{Agent: a, Revision: n, Status: "active"})
- })
- return nil
- }
-
- rt := m.Runtime.Type
- if rt == "" {
- rt = "default"
- }
- input := map[string]interface{}{"type": "inline", "prompt": prompt, "model": m.Model, "runtime": map[string]string{"type": rt}}
- if len(skills) > 0 {
- input["skills"] = skills
- }
- // [[schedules]] present in agent.toml → carry them so the server syncs on activate (015 §3).
- // Absent → omit the key entirely (no sync; existing schedules untouched).
- if len(m.Schedules) > 0 {
- input["schedules"] = m.Schedules
- }
- body := map[string]interface{}{"input": input, "activate": !noActivate}
- if idem, _ := cmd.Flags().GetString("idempotency-key"); idem != "" {
- body["idempotency_key"] = idem
- }
- var env DeploymentEnvelope
- if err := sc.Post(cmd.Context(), "/v3/agents/"+id+"/deployments", body, &env); err != nil {
- return err
- }
- d := env.Deployment
- if d.State == "failed" {
- printer.Print(d, func() { fmt.Printf("Deploy failed: %s\n", deployFailMsg(d)) })
- return &ExitError{Code: 1}
- }
- handoff := Agent{}
- if !jsonOutput && d.State == "ready" {
- handoff = loadDeployHandoff(cmd, sc, id)
- }
- printer.Print(d, func() {
- if d.State == "ready" {
- n := revisionNumber(cmd, sc, id, d.RevisionID)
- status := "staged"
- if d.Active {
- status = "active"
- }
- printDeploySuccess(printer.W, deploySuccess{Agent: handoff, Revision: n, Status: status})
- } else {
- fmt.Printf("Deployment %s: %s\n", d.ID, d.State)
- }
- })
- return nil
- },
-}
-
-func ensureAgentByName(cmd *cobra.Command, sc *client.Client, name, prompt, model, runtime string) (string, bool, error) {
- var list AgentList
- if err := sc.Get(cmd.Context(), "/v3/agents", &list); err != nil {
- return "", false, err
- }
- for _, a := range list.Data {
- if a.Name == name {
- // Fail fast on a runtime-family mismatch. The server rejects the
- // deployment anyway, but only after the build + artifact upload — a
- // flue deploy onto an existing claude agent would waste both.
- if runtime != "" && a.Runtime != "" && a.Runtime != runtime {
- return "", false, fmt.Errorf(
- "agent %q already exists with runtime %q, but this deploy is %q — rename the agent in agent.toml, or deploy the matching runtime",
- name, a.Runtime, runtime)
- }
- return a.ID, false, nil
- }
- }
- body := map[string]interface{}{"name": name, "model": model, "runtime": runtime}
- if prompt != "" {
- body["prompt"] = prompt // flue agents carry instructions in code — no prompt
- }
- var a Agent
- if err := sc.Post(cmd.Context(), "/v3/agents", body, &a); err != nil {
- return "", false, err
- }
- return a.ID, true, nil
-}
-
-// ── revisions / rollback / status ──
-
-var agentRevisionsCmd = &cobra.Command{
- Use: "revisions [id|name]",
- Short: "List an agent's revisions",
- Example: " oc agent revisions issue-fixer\n oc agent revisions # uses the cwd agent.toml",
- Args: cobra.MaximumNArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- id, err := targetAgentID(cmd, sc, args)
- if err != nil {
- return err
- }
- var revs RevisionList
- if err := sc.Get(cmd.Context(), "/v3/agents/"+id+"/revisions", &revs); err != nil {
- return err
- }
- printer.Print(revs.Data, func() {
- if len(revs.Data) == 0 {
- fmt.Println("No revisions.")
- return
- }
- headers := []string{"REV", "ACTIVE", "DIGEST", "CREATED"}
- var rows [][]string
- for _, r := range revs.Data {
- active := ""
- if r.Active {
- active = "✓"
- }
- rows = append(rows, []string{fmt.Sprintf("%d", r.Number), active, shortDigest(r.Digest), formatAge(r.CreatedAt)})
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var agentRollbackCmd = &cobra.Command{
- Use: "rollback <revision>",
- Short: "Activate an earlier revision (by number or rev_ id)",
- Example: " oc agent rollback 3 --agent issue-fixer\n oc agent rollback 3 # uses the cwd agent.toml",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- id, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- var res struct {
- ActiveRevisionID string `json:"active_revision_id"`
- }
- if err := sc.Post(cmd.Context(), "/v3/agents/"+id+"/revisions/"+args[0]+"/activate", nil, &res); err != nil {
- return err
- }
- printer.Print(res, func() {
- fmt.Printf("Activated revision %s (active_revision_id=%s)\n", args[0], res.ActiveRevisionID)
- })
- return nil
- },
-}
-
-var agentStatusCmd = &cobra.Command{
- Use: "status [id|name]",
- Short: "Show an agent's active revision + deployment-source status",
- Args: cobra.MaximumNArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- id, err := targetAgentID(cmd, sc, args)
- if err != nil {
- return err
- }
- var a Agent
- if err := sc.Get(cmd.Context(), "/v3/agents/"+id, &a); err != nil {
- return err
- }
- var src SourceEnvelope
- hasLink := sc.Get(cmd.Context(), "/v3/agents/"+id+"/deployment-source", &src) == nil && src.Source.AgentID != ""
- printer.Print(map[string]interface{}{"agent": a, "linked": hasLink, "source": src.Source}, func() {
- fmt.Printf("%s (%s)\n", a.Name, a.ID)
- if a.ActiveRevision != nil {
- fmt.Printf(" active revision: %d (%s)\n", a.ActiveRevision.Number, shortDigest(a.ActiveRevision.Digest))
- } else {
- fmt.Println(" active revision: none")
- }
- if hasLink {
- fmt.Printf(" deploy source: %s @ %s [%s]\n", src.Source.Path, src.Source.ProductionRef, src.Source.Status)
- if src.Source.ActiveDeployedSha != "" {
- fmt.Printf(" deployed sha: %s\n", shortSha(src.Source.ActiveDeployedSha))
- }
- } else {
- fmt.Println(" deploy source: (not linked)")
- }
- })
- return nil
- },
-}
-
-// ── link / unlink / deployments ──
-
-var agentLinkCmd = &cobra.Command{
- Use: "link <owner/repo>",
- Short: "Link a GitHub repo directory for push-to-deploy",
- Example: " oc agent link acme/agents --path agents/issue-fixer --agent issue-fixer\n" +
- " oc agent link acme/agents --path agents/issue-fixer --branch main --wait",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- id, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- path, _ := cmd.Flags().GetString("path")
- branch, _ := cmd.Flags().GetString("branch")
- noDeploy, _ := cmd.Flags().GetBool("no-deploy")
- body := map[string]interface{}{"repo": args[0], "path": path, "production_ref": branch, "deploy_now": !noDeploy}
- var res SourceEnvelope
- if err := sc.Post(cmd.Context(), "/v3/agents/"+id+"/deployment-source", body, &res); err != nil {
- return err
- }
- printer.Print(res, func() {
- fmt.Printf("Linked %s:%s @ %s [%s]\n", args[0], res.Source.Path, res.Source.ProductionRef, res.Source.Status)
- if res.DeployError != nil {
- fmt.Printf(" (initial deploy could not start: %s)\n", res.DeployError.Message)
- } else if res.DeploymentID != "" {
- fmt.Printf(" deploying %s — poll: oc agent deployments\n", res.DeploymentID)
- }
- })
- if wait, _ := cmd.Flags().GetBool("wait"); wait && res.DeploymentID != "" {
- to, _ := cmd.Flags().GetInt("timeout")
- d, perr := pollDeployment(cmd, sc, id, res.DeploymentID, time.Duration(to)*time.Second)
- if perr != nil {
- return perr
- }
- if d.State == "failed" {
- fmt.Fprintf(os.Stderr, "Deploy failed: %s\n", deployFailMsg(d))
- return &ExitError{Code: 1}
- }
- fmt.Printf("Deploy %s: %s\n", res.DeploymentID, d.State)
- }
- return nil
- },
-}
-
-var agentDeploymentCmd = &cobra.Command{
- Use: "deployment <deployment-id>",
- Short: "Show one deployment (use --wait to poll to a terminal state)",
- Example: " oc agent deployment dep_123 --agent issue-fixer\n" +
- " oc agent deployment dep_123 --wait # block until ready|failed (exit non-zero on failure)",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- id, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- var d Deployment
- if wait, _ := cmd.Flags().GetBool("wait"); wait {
- to, _ := cmd.Flags().GetInt("timeout")
- d, err = pollDeployment(cmd, sc, id, args[0], time.Duration(to)*time.Second)
- } else {
- err = sc.Get(cmd.Context(), "/v3/agents/"+id+"/deployments/"+args[0], &d)
- }
- if err != nil {
- return err
- }
- printer.Print(d, func() {
- fmt.Printf("%s %s", d.ID, d.State)
- if d.Result != "" {
- fmt.Printf(" (%s)", d.Result)
- }
- fmt.Println()
- if d.State == "failed" {
- fmt.Printf(" error: %s\n", deployFailMsg(d))
- }
- })
- if d.State == "failed" {
- return &ExitError{Code: 1}
- }
- return nil
- },
-}
-
-var agentUnlinkCmd = &cobra.Command{
- Use: "unlink",
- Short: "Remove the agent's deployment-source link",
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- id, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- if err := confirmDestructive(cmd, "unlink the deployment source"); err != nil {
- return err
- }
- if err := sc.Delete(cmd.Context(), "/v3/agents/"+id+"/deployment-source"); err != nil {
- return err
- }
- fmt.Println("Unlinked. Existing revisions are unchanged.")
- return nil
- },
-}
-
-var agentDeploymentsCmd = &cobra.Command{
- Use: "deployments [id|name]",
- Short: "List an agent's deployments",
- Args: cobra.MaximumNArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- id, err := targetAgentID(cmd, sc, args)
- if err != nil {
- return err
- }
- var resp DeploymentList
- if err := sc.Get(cmd.Context(), "/v3/agents/"+id+"/deployments", &resp); err != nil {
- return err
- }
- printer.Print(resp.Data, func() {
- if len(resp.Data) == 0 {
- fmt.Println("No deployments.")
- return
- }
- headers := []string{"ID", "INPUT", "STATE", "RESULT", "REF", "SHA", "CREATED"}
- var rows [][]string
- for _, d := range resp.Data {
- via := d.InputType
- if v, ok := d.Source["via"].(string); ok && via == "" {
- via = v
- }
- rows = append(rows, []string{d.ID, via, d.State, d.Result, d.Ref, shortSha(d.Sha), formatAge(d.CreatedAt)})
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-func shortDigest(d string) string {
- d = strings.TrimPrefix(d, "sha256:")
- if len(d) > 12 {
- return d[:12]
- }
- return d
-}
-
-func registerAgentDeploy() {
- agentCmd.AddCommand(agentBuildCmd)
- agentDeployCmd.Flags().String("agent", "", "Target agent id or name (else the manifest's [agent].id / name)")
- agentDeployCmd.Flags().Bool("no-activate", false, "Create the revision without activating it (stage)")
- agentDeployCmd.Flags().String("idempotency-key", "", "CI-safe key: a retry with the same key returns the same deployment")
- agentDeployCmd.Flags().Int("timeout", 180, "Seconds to wait for a Flue deploy to boot-verify (poll to terminal state)")
- agentDeployCmd.Flags().Bool("verbose", false, "Show full framework build output")
-
- for _, c := range []*cobra.Command{agentRevisionsCmd, agentRollbackCmd, agentStatusCmd, agentLinkCmd, agentUnlinkCmd, agentDeploymentsCmd, agentDeploymentCmd} {
- c.Flags().String("agent", "", "Target agent id or name (else the cwd agent.toml)")
- }
- agentLinkCmd.Flags().String("path", "", "Agent directory within the repo (e.g. agents/issue-fixer)")
- agentLinkCmd.Flags().String("branch", "main", "Production branch that auto-activates on push")
- agentLinkCmd.Flags().Bool("no-deploy", false, "Link only; don't deploy the current HEAD now")
- agentLinkCmd.Flags().Bool("wait", false, "Wait for the initial deploy to reach a terminal state (exit non-zero on failure)")
- agentLinkCmd.Flags().Int("timeout", 180, "Seconds to wait with --wait")
- agentUnlinkCmd.Flags().Bool("yes", false, "Skip confirmation (required for non-interactive callers)")
- agentDeploymentCmd.Flags().Bool("wait", false, "Poll until the deployment reaches a terminal state (exit non-zero on failure)")
- agentDeploymentCmd.Flags().Int("timeout", 180, "Seconds to wait with --wait")
-
- agentCmd.AddCommand(agentInitCmd)
- agentCmd.AddCommand(agentDeployCmd)
- agentCmd.AddCommand(agentRevisionsCmd)
- agentCmd.AddCommand(agentRollbackCmd)
- agentCmd.AddCommand(agentStatusCmd)
- agentCmd.AddCommand(agentLinkCmd)
- agentCmd.AddCommand(agentUnlinkCmd)
- agentCmd.AddCommand(agentDeploymentsCmd)
- agentCmd.AddCommand(agentDeploymentCmd)
-}
diff --git a/cmd/oc/internal/commands/agent_deploy_flue.go b/cmd/oc/internal/commands/agent_deploy_flue.go
deleted file mode 100644
index 2c5d37d9..00000000
--- a/cmd/oc/internal/commands/agent_deploy_flue.go
+++ /dev/null
@@ -1,508 +0,0 @@
-package commands
-
-// Flue deploy flow (design 013 §6 — the Worker-for-Platforms Durable-Object model).
-// A prompt-defined root stages only agent.toml, prompt.md, and exact SKILL.md files;
-// the isolated managed builder owns synthesis and the framework build. A complete app
-// runs its own local `flue build --target cloudflare` and stages only the resulting
-// regular .js/.mjs modules. Both paths keep source/module bytes out of API JSON and
-// converge on the same off-host deploy runner and verifying → ready|failed poll.
-
-import (
- "bytes"
- "context"
- "crypto/rand"
- "encoding/hex"
- "errors"
- "fmt"
- "io"
- "net/http"
- "os"
- "path/filepath"
- "regexp"
- "strings"
- "time"
- "unicode/utf8"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/bundle"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/fluebuild"
- "github.com/spf13/cobra"
-)
-
-// artifactUploadResponse is the reply from POST /v3/agents/:id/artifacts. AlreadyUploaded
-// is set (and URL omitted) when the content-addressed object already exists: R2 is
-// write-once, so the server refuses to re-issue a PUT for a pinned digest (a re-issuable
-// PUT would let scan-clean bytes be swapped for key-bearing ones post-verify). The CLI
-// then skips the PUT and references the digest directly.
-type artifactUploadResponse struct {
- URL string `json:"url"`
- ExpiresAt string `json:"expires_at"`
- AlreadyUploaded bool `json:"already_uploaded"`
-}
-
-type localSourceUploadResponse struct {
- URL string `json:"url"`
- ExpiresAt string `json:"expires_at"`
- AlreadyUploaded bool `json:"already_uploaded"`
-}
-
-const (
- fluePromptMaxBytes = 256 * 1024
- fluePromptMaxSkills = 32
- fluePromptMaxSkillBytes = 256 * 1024
- fluePromptMaxSkillsBytes = 2 * 1024 * 1024
- fluePromptMaxArchive = 4 * 1024 * 1024
-)
-
-var fluePromptSkillName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`)
-
-func deployFlue(cmd *cobra.Command, sc *client.Client, dir string, m *manifest, noActivate bool) error {
- if isPromptDefinedFlueRoot(dir) {
- return deployPromptDefinedFlue(cmd, sc, dir, m, noActivate)
- }
- // 1. Run the same credential, manifest, engine, and lockfile projection as
- // the managed builder before any authenticated API call. --check-only
- // never executes repository code and never needs installed dependencies.
- if _, err := fluebuild.Build(cmd.Context(), fluebuild.Options{
- Dir: dir,
- Target: fluebuild.TargetCloudflare,
- BuilderVersion: Version,
- CheckOnly: true,
- }); err != nil {
- return presentFlueBuildError(err)
- }
-
- // 2. Resolve the target agent (create with runtime=flue + no prompt if new).
- // Done before the build so a runtime-family mismatch fails fast — ahead of the
- // build and the upload, not after.
- id, err := resolveDeployAgent(cmd, sc, m)
- if err != nil {
- return err
- }
- // [vars] is part of the deployment input even though the values live in the
- // agent config resource. Persist it before enqueueing so the off-host runner
- // cannot race ahead and compose the Worker with stale bindings. Secrets are
- // intentionally CLI/API only and are resolved by that same runner.
- if err := syncManifestVars(cmd, sc, id, m); err != nil {
- return err
- }
-
- // 3–4. Build through the shared credential-free package. It extracts only
- // strict WfP metadata + regular modules and credential-scans the final bytes.
- verbose, _ := cmd.Flags().GetBool("verbose")
- var buildLog bytes.Buffer
- buildStdout, buildStderr := io.Writer(&buildLog), io.Writer(&buildLog)
- if verbose {
- buildStdout, buildStderr = os.Stderr, os.Stderr
- } else {
- printDeployProgress("building")
- }
- artifact, err := fluebuild.Build(cmd.Context(), fluebuild.Options{
- Dir: dir,
- Target: fluebuild.TargetCloudflare,
- BuilderVersion: Version,
- BuildStdout: buildStdout,
- BuildStderr: buildStderr,
- })
- if err != nil {
- if !verbose && buildLog.Len() > 0 {
- endsWithNewline := buildLog.Bytes()[buildLog.Len()-1] == '\n'
- fmt.Fprintln(os.Stderr, "Framework build output:")
- _, _ = io.Copy(os.Stderr, &buildLog)
- if !endsWithNewline {
- fmt.Fprintln(os.Stderr)
- }
- }
- return presentFlueBuildError(err)
- }
- digest := artifact.Deployment.Bundle.Digest
- wrangler := artifact.Deployment.Flue.Wrangler
-
- // 5. Upload: presigned PUT to R2 (the API host never sees the bytes).
- if !verbose {
- printDeployProgress("uploading")
- }
- if err := uploadArtifact(cmd.Context(), sc, id, digest, artifact.Bundle); err != nil {
- return err
- }
-
- // 6. Deployment referencing the R2 bundle digest + the canonical descriptor (no
- // module bytes in the JSON). The CP keys the flue-DO path off the agent's
- // runtime="flue" + the presence of flue_bundle_digest/flue_wrangler, then hands
- // off to the off-host runner (fetch → compose → mint → WfP-upload) → verifying.
- rt := artifact.Deployment.Runtime.Type
- input := map[string]interface{}{
- "type": "inline",
- "model": artifact.Deployment.Model,
- "runtime": map[string]string{"type": rt},
- "flue_bundle_digest": digest, // sha256: of the tar.gz staged in R2
- "flue_wrangler": wrangler, // strict adapter descriptor; never raw wrangler.json
- "flue_agent_name": artifact.Deployment.Flue.Entrypoint,
- }
- body := map[string]interface{}{"input": input, "activate": !noActivate}
- if idem, _ := cmd.Flags().GetString("idempotency-key"); idem != "" {
- body["idempotency_key"] = idem
- }
- var env DeploymentEnvelope
- if err := sc.Post(cmd.Context(), "/v3/agents/"+id+"/deployments", body, &env); err != nil {
- return err
- }
- d := env.Deployment
-
- // 7. Poll to terminal while the off-host runner uploads and finalizes the deployment.
- if !terminalState(d.State) && d.State != "" {
- to, _ := cmd.Flags().GetInt("timeout")
- d, err = pollDeployment(cmd, sc, id, d.ID, time.Duration(to)*time.Second)
- if err != nil {
- return err
- }
- }
- if d.State == "failed" {
- printer.Print(d, func() { fmt.Printf("Deploy failed: %s\n", deployFailMsg(d)) })
- return &ExitError{Code: 1}
- }
- handoff := Agent{}
- if !jsonOutput && d.State == "ready" {
- handoff = loadDeployHandoff(cmd, sc, id)
- }
- printer.Print(d, func() {
- n := revisionNumber(cmd, sc, id, d.RevisionID)
- status := "staged"
- if d.Active {
- status = "active"
- }
- printDeploySuccess(printer.W, deploySuccess{
- Agent: handoff, Revision: n, Status: status, Digest: shortDigest(digest),
- })
- })
- return nil
-}
-
-func isPromptDefinedFlueRoot(dir string) bool {
- exists := func(name string) bool {
- _, err := os.Lstat(name)
- return err == nil
- }
- if !exists(filepath.Join(dir, "prompt.md")) {
- return false
- }
- for _, marker := range []string{
- "package.json",
- "flue.config.ts",
- "flue.config.js",
- "flue.config.mjs",
- "flue.config.cjs",
- } {
- if _, err := os.Lstat(filepath.Join(dir, marker)); err == nil {
- return false
- }
- }
- return true
-}
-
-// deployPromptDefinedFlue stages the bounded behavior source directly into the
-// transient source bucket, then asks the existing isolated managed-build plane
-// to synthesize and build it. The API sees only the source reference.
-func deployPromptDefinedFlue(
- cmd *cobra.Command,
- sc *client.Client,
- dir string,
- m *manifest,
- noActivate bool,
-) error {
- if m.Name == "" {
- return fmt.Errorf("prompt-defined Flue deployments require `name` in agent.toml")
- }
- if m.Runtime.Type != "" && m.Runtime.Type != "default" {
- return fmt.Errorf("prompt-defined Flue deployments require runtime.type = \"default\"")
- }
- files, err := readPromptDefinedFlueSource(dir)
- if err != nil {
- return err
- }
- sourceTarGz, err := bundle.Pack(files)
- if err != nil {
- return fmt.Errorf("pack prompt-defined Flue source: %w", err)
- }
- if len(sourceTarGz) > fluePromptMaxArchive {
- return fmt.Errorf(
- "prompt-defined Flue source archive exceeds %d bytes",
- fluePromptMaxArchive,
- )
- }
- uploadID, err := newLocalSourceUploadID()
- if err != nil {
- return fmt.Errorf("create source upload id: %w", err)
- }
- digest := bundle.Digest(sourceTarGz)
-
- id, err := resolveDeployAgent(cmd, sc, m)
- if err != nil {
- return err
- }
- if err := syncManifestVars(cmd, sc, id, m); err != nil {
- return err
- }
- if !jsonOutput {
- printDeployProgress("uploading source")
- }
- if err := uploadLocalBuildSource(
- cmd.Context(),
- sc,
- id,
- uploadID,
- digest,
- sourceTarGz,
- ); err != nil {
- return err
- }
-
- rt := m.Runtime.Type
- if rt == "" {
- rt = "default"
- }
- input := map[string]interface{}{
- "type": "source",
- "source": map[string]interface{}{"upload_id": uploadID, "digest": digest, "size_bytes": len(sourceTarGz)},
- "entrypoint": m.Name,
- "model": m.Model,
- "runtime": map[string]string{"type": rt},
- }
- body := map[string]interface{}{"input": input, "activate": !noActivate}
- if idem, _ := cmd.Flags().GetString("idempotency-key"); idem != "" {
- body["idempotency_key"] = idem
- }
- var env DeploymentEnvelope
- if err := sc.Post(cmd.Context(), "/v3/agents/"+id+"/deployments", body, &env); err != nil {
- return err
- }
- d := env.Deployment
- if !terminalState(d.State) && d.State != "" {
- to, _ := cmd.Flags().GetInt("timeout")
- d, err = pollDeployment(cmd, sc, id, d.ID, time.Duration(to)*time.Second)
- if err != nil {
- return err
- }
- }
- if d.State == "failed" {
- printer.Print(d, func() { fmt.Printf("Deploy failed: %s\n", deployFailMsg(d)) })
- return &ExitError{Code: 1}
- }
- handoff := Agent{}
- if !jsonOutput && d.State == "ready" {
- handoff = loadDeployHandoff(cmd, sc, id)
- }
- printer.Print(d, func() {
- n := revisionNumber(cmd, sc, id, d.RevisionID)
- status := "staged"
- if d.Active {
- status = "active"
- }
- printDeploySuccess(printer.W, deploySuccess{
- Agent: handoff, Revision: n, Status: status,
- })
- })
- return nil
-}
-
-func readPromptDefinedFlueSource(dir string) ([]bundle.File, error) {
- readRegular := func(rel string, maxBytes int) ([]byte, error) {
- path := filepath.Join(dir, filepath.FromSlash(rel))
- info, err := os.Lstat(path)
- if err != nil {
- if os.IsNotExist(err) {
- return nil, fmt.Errorf("%s is missing", rel)
- }
- return nil, fmt.Errorf("inspect %s: %w", rel, err)
- }
- if !info.Mode().IsRegular() {
- return nil, fmt.Errorf("%s must be a regular file", rel)
- }
- if info.Size() > int64(maxBytes) {
- return nil, fmt.Errorf("%s exceeds %d bytes", rel, maxBytes)
- }
- content, err := os.ReadFile(path)
- if err != nil {
- return nil, fmt.Errorf("read %s: %w", rel, err)
- }
- if !utf8.Valid(content) {
- return nil, fmt.Errorf("%s must be valid UTF-8", rel)
- }
- return content, nil
- }
-
- manifestBytes, err := readRegular("agent.toml", fluePromptMaxArchive)
- if err != nil {
- return nil, err
- }
- promptBytes, err := readRegular("prompt.md", fluePromptMaxBytes)
- if err != nil {
- return nil, err
- }
- if strings.TrimSpace(string(promptBytes)) == "" {
- return nil, fmt.Errorf("prompt.md must not be empty")
- }
- if _, err := os.Lstat(filepath.Join(dir, "mcp.json")); err == nil {
- return nil, fmt.Errorf("mcp.json is not supported by prompt-defined Flue agents")
- } else if !os.IsNotExist(err) {
- return nil, fmt.Errorf("inspect mcp.json: %w", err)
- }
-
- files := []bundle.File{
- {Path: "agent.toml", Mode: 0o644, Content: manifestBytes},
- {Path: "prompt.md", Mode: 0o644, Content: promptBytes},
- }
- skillsRoot := filepath.Join(dir, "skills")
- entries, err := os.ReadDir(skillsRoot)
- if err != nil {
- if os.IsNotExist(err) {
- return files, nil
- }
- return nil, fmt.Errorf("read skills/: %w", err)
- }
- rootInfo, err := os.Lstat(skillsRoot)
- if err != nil {
- return nil, fmt.Errorf("inspect skills/: %w", err)
- }
- if !rootInfo.IsDir() {
- return nil, fmt.Errorf("skills must be a directory")
- }
-
- totalSkillBytes := 0
- for _, entry := range entries {
- if !entry.IsDir() {
- continue
- }
- rel := "skills/" + entry.Name() + "/SKILL.md"
- if _, err := os.Lstat(filepath.Join(dir, filepath.FromSlash(rel))); err != nil {
- if os.IsNotExist(err) {
- continue
- }
- return nil, fmt.Errorf("inspect %s: %w", rel, err)
- }
- if !fluePromptSkillName.MatchString(entry.Name()) {
- return nil, fmt.Errorf("skill directory %q has an invalid name", entry.Name())
- }
- content, err := readRegular(rel, fluePromptMaxSkillBytes)
- if err != nil {
- return nil, err
- }
- totalSkillBytes += len(content)
- if totalSkillBytes > fluePromptMaxSkillsBytes {
- return nil, fmt.Errorf(
- "prompt-defined Flue skill files exceed %d bytes",
- fluePromptMaxSkillsBytes,
- )
- }
- files = append(files, bundle.File{Path: rel, Mode: 0o644, Content: content})
- if len(files)-2 > fluePromptMaxSkills {
- return nil, fmt.Errorf(
- "prompt-defined Flue agents support at most %d skills",
- fluePromptMaxSkills,
- )
- }
- }
- return files, nil
-}
-
-func newLocalSourceUploadID() (string, error) {
- var raw [16]byte
- if _, err := rand.Read(raw[:]); err != nil {
- return "", err
- }
- return "src_" + hex.EncodeToString(raw[:]), nil
-}
-
-func uploadLocalBuildSource(
- ctx context.Context,
- sc *client.Client,
- agentID string,
- uploadID string,
- digest string,
- tarGz []byte,
-) error {
- body := map[string]interface{}{
- "upload_id": uploadID,
- "digest": digest,
- "size_bytes": len(tarGz),
- }
- var response localSourceUploadResponse
- if err := sc.Post(
- ctx,
- "/v3/agents/"+agentID+"/source-artifacts",
- body,
- &response,
- ); err != nil {
- return fmt.Errorf("request source upload url: %w", err)
- }
- if response.AlreadyUploaded {
- return nil
- }
- if response.URL == "" {
- return fmt.Errorf("source upload url response was empty")
- }
- return putGzip(ctx, response.URL, tarGz, "source")
-}
-
-func presentFlueBuildError(err error) error {
- var credentialErr *fluebuild.CredentialError
- if !errors.As(err, &credentialErr) {
- return err
- }
- fmt.Fprintln(os.Stderr, "Refusing to deploy — possible credential(s) found (model keys come from the OpenComputer credential, never code):")
- for _, finding := range credentialErr.Findings {
- fmt.Fprintf(os.Stderr, " %s:%d %s %s\n", finding.Path, finding.Line, finding.Kind, finding.Match)
- }
- return &ExitError{Code: 1}
-}
-
-// resolveDeployAgent picks the agent a flue deploy targets: --agent > manifest
-// [agent].id > ensure-by-name (creating a flue agent with no prompt if absent).
-func resolveDeployAgent(cmd *cobra.Command, sc *client.Client, m *manifest) (string, error) {
- if explicit, _ := cmd.Flags().GetString("agent"); explicit != "" {
- return resolveRef(cmd, sc, explicit)
- }
- if m.Agent.ID != "" {
- return m.Agent.ID, nil
- }
- id, _, err := ensureAgentByName(cmd, sc, m.Name, "", m.Model, "flue")
- return id, err
-}
-
-// uploadArtifact requests a presigned PUT URL, then PUTs the bundle to it. The PUT
-// carries no OC auth (the signature is in the URL); Content-Type must match what the
-// server signed for the object (application/gzip).
-func uploadArtifact(ctx context.Context, sc *client.Client, agentID, digest string, tarGz []byte) error {
- reqBody := map[string]interface{}{"digest": digest, "size_bytes": len(tarGz)}
- var resp artifactUploadResponse
- if err := sc.Post(ctx, "/v3/agents/"+agentID+"/artifacts", reqBody, &resp); err != nil {
- return fmt.Errorf("request bundle upload url: %w", err)
- }
- if resp.AlreadyUploaded {
- // The digest's bytes are already in R2 (write-once); nothing to PUT.
- return nil
- }
- if resp.URL == "" {
- return fmt.Errorf("bundle upload url response was empty")
- }
- return putGzip(ctx, resp.URL, tarGz, "bundle")
-}
-
-func putGzip(ctx context.Context, url string, tarGz []byte, label string) error {
- req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, bytes.NewReader(tarGz))
- if err != nil {
- return err
- }
- req.Header.Set("Content-Type", "application/gzip")
- req.ContentLength = int64(len(tarGz))
- put, err := http.DefaultClient.Do(req)
- if err != nil {
- return fmt.Errorf("upload %s: %w", label, err)
- }
- defer put.Body.Close()
- if put.StatusCode >= 300 {
- snippet, _ := io.ReadAll(io.LimitReader(put.Body, 512))
- return fmt.Errorf("%s upload failed (HTTP %d): %s", label, put.StatusCode, string(snippet))
- }
- return nil
-}
diff --git a/cmd/oc/internal/commands/agent_deploy_flue_test.go b/cmd/oc/internal/commands/agent_deploy_flue_test.go
deleted file mode 100644
index c36aeacd..00000000
--- a/cmd/oc/internal/commands/agent_deploy_flue_test.go
+++ /dev/null
@@ -1,617 +0,0 @@
-package commands
-
-// Contract-mock end-to-end for the Flue DO deploy flow (design 013 §6). A fake control
-// plane implements the presigned-PUT bundle upload (POST /v3/agents/:id/artifacts + the
-// signed PUT) and the deployment create + a verifying→ready poll. A throwaway
-// `node_modules/.bin/flue` script stands in for the app's flue CLI, so the real
-// runFlueBuild exec path runs and produces a deliberately noisy dist/<app>/. deployFlue
-// is driven end to end; we assert the uploaded bytes are byte-exactly the canonical
-// module-only tar.gz for the digest the CLI
-// advertised (the content-address chain), and that the POSTed deployment body is the
-// byte-free DO request: flue_bundle_digest + the canonical flue_wrangler descriptor +
-// flue_agent_name, with no raw Wrangler dump, module bytes, or framework_artifact_digest.
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "regexp"
- "runtime"
- "strings"
- "sync"
- "testing"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/bundle"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/fluebuild"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/output"
- "github.com/spf13/cobra"
-)
-
-// The exact bytes the fake `flue build` emits into dist/e2e_flue/ (heredoc appends a
-// trailing newline). The build is nested a directory deep, with an assets/ file, to
-// exercise the dist/<app>/ discovery and prove the WHOLE tree is staged.
-const (
- fakeAgentID = "agt_0123456789abcdef01234567"
- e2eModuleBody = `export default { fetch() { return new Response("ok"); } };`
- e2eAssetBody = `export const chunk = 1;`
- e2eRuntimeBody = `export const runtime = "flue";`
- e2eWranglerBody = `{"$schema":"../../node_modules/wrangler/config-schema.json","name":"e2e-flue","main":"index.js","compatibility_date":"2026-04-01","compatibility_flags":["nodejs_compat"],"no_bundle":true,"configPath":"/Users/developer/project/flue.config.ts","userConfigPath":"/Users/developer/project/wrangler.json","durable_objects":{"bindings":[{"name":"AGENT","class_name":"FlueE2EAgent"},{"name":"FLUE_REGISTRY","class_name":"FlueRegistry"}]},"vars":{"MUST_NOT_LEAVE":"raw-wrangler"},"migrations":[{"tag":"attacker-owned","new_sqlite_classes":["Wrong"]}],"routes":["example.com/*"],"services":[{"binding":"OTHER","service":"victim"}]}`
-)
-
-type fakeCP struct {
- mu sync.Mutex
- self string
- createBody map[string]any
- configPutBody map[string]any
- artifactDigest string
- artifactSize float64
- uploaded []byte
- sourceBody map[string]any
- sourceUploaded []byte
- deployBody map[string]any
- getCount int
-}
-
-func (f *fakeCP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- f.mu.Lock()
- defer f.mu.Unlock()
- writeJSON := func(v any) {
- w.Header().Set("Content-Type", "application/json")
- _ = json.NewEncoder(w).Encode(v)
- }
- switch {
- case r.Method == "GET" && r.URL.Path == "/v3/agents":
- writeJSON(map[string]any{"data": []any{}})
- case r.Method == "POST" && r.URL.Path == "/v3/agents":
- _ = json.NewDecoder(r.Body).Decode(&f.createBody)
- writeJSON(map[string]any{"id": fakeAgentID, "name": "e2e-flue", "model": "anthropic/claude-sonnet-5", "runtime": "flue"})
- case r.Method == "GET" && r.URL.Path == "/v3/agents/"+fakeAgentID:
- writeJSON(map[string]any{
- "id": fakeAgentID, "name": "e2e-flue", "model": "anthropic/claude-sonnet-5", "runtime": "flue",
- "invoke_url": "https://agt-0123456789abcdef01234567.agents.opencomputer.dev",
- })
- case r.Method == "PUT" && r.URL.Path == "/v3/agents/"+fakeAgentID+"/config":
- _ = json.NewDecoder(r.Body).Decode(&f.configPutBody)
- writeJSON(map[string]any{
- "vars": f.configPutBody["vars"], "deployment_required": true,
- })
- case r.Method == "POST" && r.URL.Path == "/v3/agents/"+fakeAgentID+"/artifacts":
- var body map[string]any
- _ = json.NewDecoder(r.Body).Decode(&body)
- f.artifactDigest, _ = body["digest"].(string)
- f.artifactSize, _ = body["size_bytes"].(float64)
- writeJSON(map[string]any{"url": f.self + "/upload/" + f.artifactDigest, "expires_at": "2099-01-01T00:00:00Z"})
- case r.Method == "POST" && r.URL.Path == "/v3/agents/"+fakeAgentID+"/source-artifacts":
- _ = json.NewDecoder(r.Body).Decode(&f.sourceBody)
- uploadID, _ := f.sourceBody["upload_id"].(string)
- writeJSON(map[string]any{"url": f.self + "/source-upload/" + uploadID, "expires_at": "2099-01-01T00:00:00Z"})
- case r.Method == "PUT" && strings.HasPrefix(r.URL.Path, "/upload/"):
- if ct := r.Header.Get("Content-Type"); ct != "application/gzip" {
- http.Error(w, "bad content-type: "+ct, http.StatusBadRequest)
- return
- }
- buf := new(bytes.Buffer)
- _, _ = buf.ReadFrom(r.Body)
- f.uploaded = buf.Bytes()
- w.WriteHeader(http.StatusOK)
- case r.Method == "PUT" && strings.HasPrefix(r.URL.Path, "/source-upload/"):
- if ct := r.Header.Get("Content-Type"); ct != "application/gzip" {
- http.Error(w, "bad content-type: "+ct, http.StatusBadRequest)
- return
- }
- buf := new(bytes.Buffer)
- _, _ = buf.ReadFrom(r.Body)
- f.sourceUploaded = buf.Bytes()
- w.WriteHeader(http.StatusOK)
- case r.Method == "POST" && r.URL.Path == "/v3/agents/"+fakeAgentID+"/deployments":
- _ = json.NewDecoder(r.Body).Decode(&f.deployBody)
- writeJSON(map[string]any{"deployment": map[string]any{"id": "dep_1", "state": "verifying"}})
- case r.Method == "GET" && r.URL.Path == "/v3/agents/"+fakeAgentID+"/deployments/dep_1":
- f.getCount++
- if f.getCount < 2 {
- writeJSON(map[string]any{"id": "dep_1", "state": "verifying"}) // verifying → …
- } else {
- writeJSON(map[string]any{"id": "dep_1", "state": "ready", "active": true, "revision_id": "rev_1"}) // → terminal
- }
- case r.Method == "GET" && r.URL.Path == "/v3/agents/"+fakeAgentID+"/revisions":
- writeJSON(map[string]any{"data": []any{}})
- default:
- http.Error(w, "unexpected "+r.Method+" "+r.URL.Path, http.StatusNotFound)
- }
-}
-
-func TestDeployFlueDoEndToEnd(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("fake flue build is a POSIX shell script")
- }
- t.Setenv("WRANGLER_LOG", "")
-
- // A Flue app dir: manifest + clean source + a stand-in `flue` bin whose
- // `build --target cloudflare` writes a deterministic but noisy dist/e2e_flue/.
- dir := t.TempDir()
- writeFile(t, filepath.Join(dir, "agent.toml"),
- "name = \"e2e-flue\"\nmodel = \"anthropic/claude-sonnet-5\"\n\n[runtime]\nfamily = \"flue\"\n", 0o644)
- writeFile(t, filepath.Join(dir, "package.json"),
- `{"engines":{"node":">=18"},"devDependencies":{"@flue/cli":"1.0.0"}}`, 0o644)
- writeFile(t, filepath.Join(dir, "package-lock.json"),
- `{"lockfileVersion":3}`, 0o644)
- writeFile(t, filepath.Join(dir, "src", "opencomputer.ts"),
- "import { serveOC } from '@opencomputer/flue';\nexport default serveOC(agent);\n", 0o644)
- buildScript := "#!/bin/sh\nset -e\ntest \"${WRANGLER_LOG:-}\" = error\necho 'FLUE BUILD BANNER'\necho 'FLUE BUILD DETAIL' >&2\nmkdir -p dist/e2e_flue/assets dist/e2e_flue/.vite dist/e2e_flue/.flue-vite\n" +
- "cat > dist/e2e_flue/index.js <<'JS'\n" + e2eModuleBody + "\nJS\n" +
- "cat > dist/e2e_flue/assets/chunk.js <<'JS'\n" + e2eAssetBody + "\nJS\n" +
- "cat > dist/e2e_flue/.flue-vite/runtime.mjs <<'JS'\n" + e2eRuntimeBody + "\nJS\n" +
- "printf '%s' '{\"version\":3}' > dist/e2e_flue/.vite/manifest.json\n" +
- "printf '%s' '{\"version\":3}' > dist/e2e_flue/index.js.map\n" +
- "cat > dist/e2e_flue/wrangler.json <<'JSON'\n" + e2eWranglerBody + "\nJSON\n"
- writeFile(t, filepath.Join(dir, "node_modules", ".bin", "flue"), buildScript, 0o755)
-
- // Only regular modules leave the machine. Raw Wrangler metadata, .vite state and
- // source maps are absent; .flue-vite is a legitimate module path.
- expectedFiles := []bundle.File{
- {Path: "index.js", Mode: 0o644, Content: []byte(e2eModuleBody + "\n")},
- {Path: "assets/chunk.js", Mode: 0o644, Content: []byte(e2eAssetBody + "\n")},
- {Path: ".flue-vite/runtime.mjs", Mode: 0o644, Content: []byte(e2eRuntimeBody + "\n")},
- }
- expectedTarGz, err := bundle.Pack(expectedFiles)
- if err != nil {
- t.Fatal(err)
- }
- expectedDigest := bundle.Digest(expectedTarGz)
-
- // Fake control plane.
- f := &fakeCP{}
- srv := httptest.NewServer(f)
- defer srv.Close()
- f.self = srv.URL
-
- // Drive the real deployFlue.
- sc := client.NewSessionsAPI(srv.URL, "test-key")
- cmd := &cobra.Command{}
- cmd.Flags().String("agent", "", "")
- cmd.Flags().String("idempotency-key", "", "")
- cmd.Flags().Int("timeout", 30, "")
- cmd.SetContext(context.Background())
- m := &manifest{Name: "e2e-flue", Model: "anthropic/claude-sonnet-5"}
- m.Runtime.Family = "flue"
-
- prev := printer
- printer = output.New(false)
- var humanOutput bytes.Buffer
- printer.W = &humanOutput
- defer func() { printer = prev }()
-
- if err := deployFlue(cmd, sc, dir, m, false); err != nil {
- t.Fatalf("deployFlue: %v", err)
- }
- for _, want := range []string{
- "✓ Deployed e2e-flue\n",
- "Agent URL\n https://agt-0123456789abcdef01234567.agents.opencomputer.dev\n",
- "Revision active · " + shortDigest(expectedDigest) + "\n",
- "Dashboard https://app.opencomputer.dev/agents/" + fakeAgentID + "\n",
- "$ oc agent invoke " + fakeAgentID + " --data '{\"message\":\"Hello\"}'\n",
- } {
- if !strings.Contains(humanOutput.String(), want) {
- t.Errorf("human deploy output missing %q:\n%s", want, humanOutput.String())
- }
- }
- if strings.Contains(humanOutput.String(), "FLUE BUILD") {
- t.Fatalf("framework build chatter leaked into the deploy result:\n%s", humanOutput.String())
- }
-
- // Agent created as flue, no prompt.
- if f.createBody["runtime"] != "flue" {
- t.Errorf("create runtime = %v, want flue", f.createBody["runtime"])
- }
- if _, ok := f.createBody["prompt"]; ok {
- t.Errorf("create body carried a prompt for a flue agent: %v", f.createBody["prompt"])
- }
-
- // The content address the CLI advertised == the digest of the module-only bundle, and
- // the PUT body is byte-exactly that canonical tar.gz — the full upload integrity chain.
- if f.artifactDigest != expectedDigest {
- t.Errorf("advertised digest = %s, want %s", f.artifactDigest, expectedDigest)
- }
- if int(f.artifactSize) != len(f.uploaded) {
- t.Errorf("size_bytes %d != uploaded len %d", int(f.artifactSize), len(f.uploaded))
- }
- if !bytes.Equal(f.uploaded, expectedTarGz) {
- t.Errorf("uploaded bytes are not the canonical bundle for the digest (len got %d want %d)", len(f.uploaded), len(expectedTarGz))
- }
-
- // The deployment body is the byte-free DO request.
- input, _ := f.deployBody["input"].(map[string]any)
- if input == nil {
- t.Fatalf("deployment body had no input: %v", f.deployBody)
- }
- if input["type"] != "inline" {
- t.Errorf("input.type = %v, want inline", input["type"])
- }
- if f.deployBody["activate"] != true {
- t.Errorf("activate = %v, want true (no --no-activate)", f.deployBody["activate"])
- }
- if input["flue_bundle_digest"] != expectedDigest {
- t.Errorf("flue_bundle_digest = %v, want %s", input["flue_bundle_digest"], expectedDigest)
- }
- if input["flue_agent_name"] != "e2e-flue" {
- t.Errorf("flue_agent_name = %v, want e2e-flue", input["flue_agent_name"])
- }
- // No module bytes, no pre-013 digest field.
- if _, ok := input["flue_module"]; ok {
- t.Errorf("byte-free contract violated: input carried flue_module: %v", input["flue_module"])
- }
- if _, ok := input["prompt"]; ok {
- t.Errorf("flue DO deploy carried a prompt: %v", input["prompt"])
- }
- if _, ok := input["framework_artifact_digest"]; ok {
- t.Errorf("flue DO deploy carried a framework_artifact_digest: %v", input["framework_artifact_digest"])
- }
-
- // flue_wrangler is the exact canonical descriptor, not the generated resolution dump.
- wr, _ := input["flue_wrangler"].(map[string]any)
- if wr == nil {
- t.Fatalf("input.flue_wrangler missing: %v", input)
- }
- if wr["main"] != "index.js" {
- t.Errorf("flue_wrangler.main = %v, want index.js", wr["main"])
- }
- if wr["durable_objects"] == nil {
- t.Errorf("flue_wrangler lost durable_objects: %v", wr)
- }
- wantKeys := map[string]bool{
- "main": true, "compatibility_date": true, "compatibility_flags": true,
- "no_bundle": true, "durable_objects": true,
- }
- if len(wr) != len(wantKeys) {
- t.Errorf("flue_wrangler keys = %v, want only canonical descriptor", wr)
- }
- for key := range wr {
- if !wantKeys[key] {
- t.Errorf("raw Wrangler capability %q escaped into deployment: %v", key, wr[key])
- }
- }
- if wr["compatibility_date"] != "2026-04-01" || wr["no_bundle"] != true {
- t.Errorf("flue_wrangler profile changed: %v", wr)
- }
- encodedWrangler, _ := json.Marshal(wr)
- for _, leaked := range []string{"/Users/developer", "MUST_NOT_LEAVE", "attacker-owned", "example.com", "victim"} {
- if strings.Contains(string(encodedWrangler), leaked) {
- t.Errorf("raw Wrangler value %q escaped into deployment: %s", leaked, encodedWrangler)
- }
- }
-
- // The verifying→ready sequence was actually polled.
- if f.getCount < 2 {
- t.Errorf("expected the poll to observe verifying→ready (got %d GETs)", f.getCount)
- }
- if vars, ok := f.configPutBody["vars"].(map[string]any); !ok || len(vars) != 0 {
- t.Errorf("manifest without [vars] should clear desired vars, got %#v", f.configPutBody)
- }
-}
-
-func TestFlueBuildEnvPreservesExplicitWranglerLog(t *testing.T) {
- t.Setenv("WRANGLER_LOG", "debug")
- for _, value := range fluebuild.BuildEnv() {
- if value == "WRANGLER_LOG=debug" {
- return
- }
- }
- t.Fatal("flueBuildEnv did not preserve explicit WRANGLER_LOG=debug")
-}
-
-func TestExtractFlueWranglerDescriptorRejectsUnsafeInput(t *testing.T) {
- valid := func() map[string]any {
- var value map[string]any
- if err := json.Unmarshal([]byte(e2eWranglerBody), &value); err != nil {
- t.Fatal(err)
- }
- return value
- }
- tests := []struct {
- name string
- mutate func(map[string]any)
- }{
- {name: "unsafe main", mutate: func(value map[string]any) { value["main"] = "../index.js" }},
- {name: "invalid compatibility date", mutate: func(value map[string]any) { value["compatibility_date"] = "2026-02-30" }},
- {name: "invalid compatibility flag", mutate: func(value map[string]any) {
- value["compatibility_flags"] = []any{"nodejs_compat", "unsafe flag"}
- }},
- {name: "duplicate compatibility flag", mutate: func(value map[string]any) {
- value["compatibility_flags"] = []any{"nodejs_compat", "nodejs_compat"}
- }},
- {name: "bundling enabled", mutate: func(value map[string]any) { value["no_bundle"] = false }},
- {name: "foreign script binding", mutate: func(value map[string]any) {
- bindings := value["durable_objects"].(map[string]any)["bindings"].([]any)
- bindings[0].(map[string]any)["script_name"] = "victim-worker"
- }},
- {name: "missing durable objects", mutate: func(value map[string]any) {
- value["durable_objects"].(map[string]any)["bindings"] = []any{}
- }},
- {name: "duplicate binding name", mutate: func(value map[string]any) {
- value["durable_objects"].(map[string]any)["bindings"] = []any{
- map[string]any{"name": "FLUE_REGISTRY", "class_name": "FlueE2EAgent"},
- map[string]any{"name": "FLUE_REGISTRY", "class_name": "FlueRegistry"},
- }
- }},
- }
- for _, tc := range tests {
- t.Run(tc.name, func(t *testing.T) {
- value := valid()
- tc.mutate(value)
- raw, err := json.Marshal(value)
- if err != nil {
- t.Fatal(err)
- }
- if _, err := fluebuild.ExtractWranglerDescriptor(raw); err == nil {
- t.Fatalf("expected %s to be rejected", tc.name)
- }
- })
- }
-}
-
-func TestExtractFlueWranglerDescriptorPreservesBuildProfile(t *testing.T) {
- var value map[string]any
- if err := json.Unmarshal([]byte(e2eWranglerBody), &value); err != nil {
- t.Fatal(err)
- }
- value["compatibility_date"] = "2026-07-01"
- value["compatibility_flags"] = []any{"nodejs_compat", "nodejs_als"}
- bindings := value["durable_objects"].(map[string]any)["bindings"].([]any)
- bindings[1] = map[string]any{"name": "FLUE_STATE", "class_name": "FlueState"}
-
- raw, err := json.Marshal(value)
- if err != nil {
- t.Fatal(err)
- }
- descriptor, err := fluebuild.ExtractWranglerDescriptor(raw)
- if err != nil {
- t.Fatalf("extract descriptor: %v", err)
- }
- if descriptor.CompatibilityDate != "2026-07-01" {
- t.Fatalf("compatibility date = %q", descriptor.CompatibilityDate)
- }
- if strings.Join(descriptor.CompatibilityFlags, ",") != "nodejs_compat,nodejs_als" {
- t.Fatalf("compatibility flags = %v", descriptor.CompatibilityFlags)
- }
- if descriptor.DurableObjects.Bindings[1].Name != "FLUE_STATE" || descriptor.DurableObjects.Bindings[1].ClassName != "FlueState" {
- t.Fatalf("renamed Flue internal binding was not preserved: %v", descriptor.DurableObjects.Bindings)
- }
-}
-
-func TestReadBundleModulesRejectsSymlink(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("symlink semantics differ on Windows")
- }
- root := t.TempDir()
- outside := filepath.Join(t.TempDir(), "outside.js")
- writeFile(t, outside, "export const secret = true;", 0o644)
- writeFile(t, filepath.Join(root, "index.js"), "export {};", 0o644)
- if err := os.Symlink(outside, filepath.Join(root, "leak.js")); err != nil {
- t.Fatal(err)
- }
- if _, err := fluebuild.ReadBundleModules(root); err == nil || !strings.Contains(err.Error(), "symlink") {
- t.Fatalf("expected symlink rejection, got %v", err)
- }
-}
-
-func TestReadBundleModulesRejectsUnexpectedRegularFile(t *testing.T) {
- root := t.TempDir()
- writeFile(t, filepath.Join(root, "index.js"), "export {};", 0o644)
- writeFile(t, filepath.Join(root, "runtime.wasm"), "not really wasm", 0o644)
- if _, err := fluebuild.ReadBundleModules(root); err == nil || !strings.Contains(err.Error(), "unsupported file") {
- t.Fatalf("expected unsupported-file rejection, got %v", err)
- }
-}
-
-func TestSyncManifestVarsReplacesDesiredVars(t *testing.T) {
- f := &fakeCP{}
- srv := httptest.NewServer(f)
- defer srv.Close()
- f.self = srv.URL
-
- sc := client.NewSessionsAPI(srv.URL, "test-key")
- cmd := &cobra.Command{}
- cmd.SetContext(context.Background())
- m := &manifest{Vars: map[string]string{"PUBLIC_MODE": "careful", "MAX_ITEMS": "12"}}
- if err := syncManifestVars(cmd, sc, fakeAgentID, m); err != nil {
- t.Fatalf("syncManifestVars: %v", err)
- }
- vars, _ := f.configPutBody["vars"].(map[string]any)
- if vars["PUBLIC_MODE"] != "careful" || vars["MAX_ITEMS"] != "12" {
- t.Errorf("vars PUT = %#v", f.configPutBody["vars"])
- }
-}
-
-func TestDeployFlueBlocksOnLeakedKey(t *testing.T) {
- dir := t.TempDir()
- writeFile(t, filepath.Join(dir, "agent.toml"),
- "name = \"leaky\"\nmodel = \"anthropic/claude-sonnet-5\"\n[runtime]\nfamily = \"flue\"\n", 0o644)
- writeFile(t, filepath.Join(dir, "package.json"),
- `{"engines":{"node":">=18"},"devDependencies":{"@flue/cli":"1.0.0"}}`, 0o644)
- writeFile(t, filepath.Join(dir, "package-lock.json"),
- `{"lockfileVersion":3}`, 0o644)
- writeFile(t, filepath.Join(dir, "src", "leak.ts"),
- "const k = \"sk-ant-api03-AbCdEf0123456789AbCdEf0123456789_-xyzTUV\";\n", 0o644)
-
- sc := client.NewSessionsAPI("http://127.0.0.1:0", "k") // must never be hit
- cmd := &cobra.Command{}
- cmd.Flags().String("agent", "", "")
- cmd.Flags().String("idempotency-key", "", "")
- cmd.Flags().Int("timeout", 5, "")
- cmd.SetContext(context.Background())
- m := &manifest{Name: "leaky", Model: "anthropic/claude-sonnet-5"}
- m.Runtime.Family = "flue"
-
- prev := printer
- printer = output.New(false)
- defer func() { printer = prev }()
-
- err := deployFlue(cmd, sc, dir, m, false)
- if err == nil {
- t.Fatal("expected deploy to fail on a leaked key")
- }
-}
-
-func TestDeployPromptDefinedFlueEndToEnd(t *testing.T) {
- dir := t.TempDir()
- manifestBytes := []byte(
- "name = \"e2e-flue\"\nmodel = \"anthropic/claude-sonnet-5\"\n" +
- "[runtime]\nfamily = \"flue\"\ntype = \"default\"\n",
- )
- promptBytes := []byte("Help the user with `quotes`, ${expressions}, and care.\n")
- skillBytes := []byte("# Review\n\nInspect the diff before publishing.\n")
- writeFile(t, filepath.Join(dir, "agent.toml"), string(manifestBytes), 0o644)
- writeFile(t, filepath.Join(dir, "prompt.md"), string(promptBytes), 0o644)
- writeFile(t, filepath.Join(dir, "skills", "review", "SKILL.md"), string(skillBytes), 0o644)
- writeFile(t, filepath.Join(dir, "README.md"), "not part of the build source\n", 0o644)
- if !isPromptDefinedFlueRoot(dir) {
- t.Fatal("expected prompt-defined root")
- }
-
- expected, err := bundle.Pack([]bundle.File{
- {Path: "agent.toml", Mode: 0o644, Content: manifestBytes},
- {Path: "prompt.md", Mode: 0o644, Content: promptBytes},
- {Path: "skills/review/SKILL.md", Mode: 0o644, Content: skillBytes},
- })
- if err != nil {
- t.Fatal(err)
- }
- expectedDigest := bundle.Digest(expected)
-
- f := &fakeCP{}
- srv := httptest.NewServer(f)
- defer srv.Close()
- f.self = srv.URL
-
- cmd := &cobra.Command{}
- cmd.Flags().String("agent", "", "")
- cmd.Flags().String("idempotency-key", "local-e2e", "")
- cmd.Flags().Int("timeout", 30, "")
- cmd.SetContext(context.Background())
- m := &manifest{Name: "e2e-flue", Model: "anthropic/claude-sonnet-5"}
- m.Runtime.Family = "flue"
- m.Runtime.Type = "default"
-
- prev := printer
- printer = output.New(false)
- var humanOutput bytes.Buffer
- printer.W = &humanOutput
- defer func() { printer = prev }()
-
- err = deployFlue(
- cmd,
- client.NewSessionsAPI(srv.URL, "test-key"),
- dir,
- m,
- false,
- )
- if err != nil {
- t.Fatalf("deployFlue: %v", err)
- }
- if !bytes.Equal(f.sourceUploaded, expected) {
- t.Fatalf("uploaded source differs from bounded canonical source (got %d bytes, want %d)", len(f.sourceUploaded), len(expected))
- }
- if f.sourceBody["digest"] != expectedDigest {
- t.Errorf("source digest = %v, want %s", f.sourceBody["digest"], expectedDigest)
- }
- if f.sourceBody["size_bytes"] != float64(len(expected)) {
- t.Errorf("source size = %v, want %d", f.sourceBody["size_bytes"], len(expected))
- }
- uploadID, _ := f.sourceBody["upload_id"].(string)
- if !regexp.MustCompile(`^src_[0-9a-f]{32}$`).MatchString(uploadID) {
- t.Errorf("upload id = %q", uploadID)
- }
-
- input, _ := f.deployBody["input"].(map[string]any)
- if input["type"] != "source" || input["entrypoint"] != "e2e-flue" ||
- input["model"] != "anthropic/claude-sonnet-5" {
- t.Errorf("source deployment input = %#v", input)
- }
- source, _ := input["source"].(map[string]any)
- if source["upload_id"] != uploadID || source["digest"] != expectedDigest ||
- source["size_bytes"] != float64(len(expected)) {
- t.Errorf("deployment source ref = %#v", source)
- }
- if runtimeInput, _ := input["runtime"].(map[string]any); runtimeInput["type"] != "default" {
- t.Errorf("runtime input = %#v", input["runtime"])
- }
- if f.deployBody["activate"] != true || f.deployBody["idempotency_key"] != "local-e2e" {
- t.Errorf("deployment envelope = %#v", f.deployBody)
- }
- encoded, _ := json.Marshal(f.deployBody)
- for _, forbidden := range []string{
- string(promptBytes),
- string(skillBytes),
- "README.md",
- "source.tgz",
- } {
- if strings.Contains(string(encoded), forbidden) {
- t.Errorf("byte-free deployment request leaked %q: %s", forbidden, encoded)
- }
- }
- if !strings.Contains(humanOutput.String(), "✓ Deployed e2e-flue") ||
- !strings.Contains(humanOutput.String(), "Agent URL") {
- t.Errorf("deploy handoff missing:\n%s", humanOutput.String())
- }
-
- writeFile(t, filepath.Join(dir, "package.json"), "{}\n", 0o644)
- if isPromptDefinedFlueRoot(dir) {
- t.Fatal("a package marker must select the complete-app path")
- }
-}
-
-func TestReadPromptDefinedFlueSourceRejectsUnsafeShapes(t *testing.T) {
- base := func(t *testing.T) string {
- t.Helper()
- dir := t.TempDir()
- writeFile(t, filepath.Join(dir, "agent.toml"), "name='a'\n", 0o644)
- writeFile(t, filepath.Join(dir, "prompt.md"), "Help.\n", 0o644)
- return dir
- }
- t.Run("mcp", func(t *testing.T) {
- dir := base(t)
- writeFile(t, filepath.Join(dir, "mcp.json"), "{}\n", 0o644)
- if _, err := readPromptDefinedFlueSource(dir); err == nil || !strings.Contains(err.Error(), "mcp.json") {
- t.Fatalf("expected mcp rejection, got %v", err)
- }
- })
- t.Run("invalid skill name", func(t *testing.T) {
- dir := base(t)
- writeFile(t, filepath.Join(dir, "skills", "Review_Skill", "SKILL.md"), "# Review\n", 0o644)
- if _, err := readPromptDefinedFlueSource(dir); err == nil || !strings.Contains(err.Error(), "invalid name") {
- t.Fatalf("expected skill-name rejection, got %v", err)
- }
- })
- t.Run("prompt symlink", func(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("symlink semantics differ on Windows")
- }
- dir := base(t)
- if err := os.Remove(filepath.Join(dir, "prompt.md")); err != nil {
- t.Fatal(err)
- }
- outside := filepath.Join(t.TempDir(), "prompt.md")
- writeFile(t, outside, "secret\n", 0o644)
- if err := os.Symlink(outside, filepath.Join(dir, "prompt.md")); err != nil {
- t.Fatal(err)
- }
- if _, err := readPromptDefinedFlueSource(dir); err == nil || !strings.Contains(err.Error(), "regular file") {
- t.Fatalf("expected symlink rejection, got %v", err)
- }
- })
-}
-
-func writeFile(t *testing.T, path, content string, mode os.FileMode) {
- t.Helper()
- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(path, []byte(content), mode); err != nil {
- t.Fatal(err)
- }
-}
diff --git a/cmd/oc/internal/commands/agent_deploy_handoff_test.go b/cmd/oc/internal/commands/agent_deploy_handoff_test.go
deleted file mode 100644
index 95dc18a7..00000000
--- a/cmd/oc/internal/commands/agent_deploy_handoff_test.go
+++ /dev/null
@@ -1,153 +0,0 @@
-package commands
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/output"
- "github.com/spf13/cobra"
-)
-
-func TestAgentDeployFreshAgentPrintsPublicHandoff(t *testing.T) {
- const agentID = "agt_abcdef0123456789abcdef01"
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- switch {
- case r.Method == http.MethodGet && r.URL.Path == "/v3/agents":
- _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{}})
- case r.Method == http.MethodPost && r.URL.Path == "/v3/agents":
- _ = json.NewEncoder(w).Encode(map[string]any{
- "id": agentID, "name": "triage", "model": "anthropic/claude-sonnet-4", "runtime": "claude",
- })
- case r.Method == http.MethodGet && r.URL.Path == "/v3/agents/"+agentID:
- _ = json.NewEncoder(w).Encode(map[string]any{
- "id": agentID, "name": "triage", "model": "anthropic/claude-sonnet-4", "runtime": "claude",
- "invoke_url": "https://agt-abcdef0123456789abcdef01.agents.opencomputer.dev",
- "active_revision": map[string]any{"id": "rev_1", "number": 1, "digest": "sha256:test"},
- })
- default:
- http.Error(w, "unexpected "+r.Method+" "+r.URL.Path, http.StatusNotFound)
- }
- }))
- defer server.Close()
-
- dir := t.TempDir()
- if err := os.WriteFile(filepath.Join(dir, "agent.toml"), []byte("name = \"triage\"\nmodel = \"anthropic/claude-sonnet-4\"\n"), 0o644); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(dir, "prompt.md"), []byte("Be concise.\n"), 0o644); err != nil {
- t.Fatal(err)
- }
-
- cmd := &cobra.Command{}
- cmd.Flags().String("agent", "", "")
- cmd.Flags().Bool("no-activate", false, "")
- sc := client.NewSessionsAPI(server.URL, "test-key")
- cmd.SetContext(client.WithSessionsClient(context.Background(), sc))
-
- previousPrinter, previousJSON := printer, jsonOutput
- var humanOutput bytes.Buffer
- printer = output.New(false)
- printer.W = &humanOutput
- jsonOutput = false
- defer func() {
- printer = previousPrinter
- jsonOutput = previousJSON
- }()
-
- if err := agentDeployCmd.RunE(cmd, []string{dir}); err != nil {
- t.Fatalf("agent deploy: %v", err)
- }
-
- got := humanOutput.String()
- want := "✓ Deployed triage\n\n" +
- " Agent URL\n" +
- " https://agt-abcdef0123456789abcdef01.agents.opencomputer.dev\n\n" +
- " Revision 1 · active\n" +
- " Dashboard https://app.opencomputer.dev/agents/" + agentID + "\n\n" +
- " Try it\n" +
- " $ oc agent invoke " + agentID + " --data '{\"message\":\"Hello\"}'\n"
- if got != want {
- t.Fatalf("human deploy output mismatch:\n--- got ---\n%s--- want ---\n%s", got, want)
- }
- if strings.Contains(got, "\x1b") {
- t.Fatalf("redirected output contained a terminal control sequence: %q", got)
- }
-
- var machineOutput bytes.Buffer
- printer = output.New(true)
- printer.W = &machineOutput
- jsonOutput = true
- if err := agentDeployCmd.RunE(cmd, []string{dir}); err != nil {
- t.Fatalf("agent deploy --json: %v", err)
- }
- var machine map[string]any
- if err := json.Unmarshal(machineOutput.Bytes(), &machine); err != nil {
- t.Fatalf("machine output is not one JSON object: %v\n%s", err, machineOutput.String())
- }
- if machine["agent_id"] != agentID || machine["state"] != "ready" || machine["active"] != true || machine["revision"] != float64(1) {
- t.Fatalf("machine deploy schema changed: %#v", machine)
- }
- if strings.Contains(machineOutput.String(), "Deployed") || strings.Contains(machineOutput.String(), "\x1b") {
- t.Fatalf("machine output contained presentation text: %q", machineOutput.String())
- }
-}
-
-func TestDeploySuccessWithoutConvenienceReadStaysUseful(t *testing.T) {
- var out bytes.Buffer
- renderDeploySuccess(&out, deploySuccess{
- Agent: Agent{ID: "agt_abcdef0123456789abcdef01"}, Revision: 2, Status: "active",
- }, deployOutputStyle{})
- got := out.String()
- for _, want := range []string{
- "✓ Deployed agt_abcdef0123456789abcdef01",
- "Revision 2 · active",
- "Dashboard https://app.opencomputer.dev/agents/agt_abcdef0123456789abcdef01",
- "$ oc agent invoke agt_abcdef0123456789abcdef01",
- } {
- if !strings.Contains(got, want) {
- t.Errorf("fallback output missing %q:\n%s", want, got)
- }
- }
- if strings.Contains(got, "Agent URL") {
- t.Fatalf("fallback invented an Agent URL: %s", got)
- }
-}
-
-func TestDeploySuccessTTYStyleIsRestrainedAndLinked(t *testing.T) {
- const invokeURL = "https://agt-abcdef0123456789abcdef01.agents.opencomputer.dev"
- var out bytes.Buffer
- renderDeploySuccess(&out, deploySuccess{
- Agent: Agent{
- ID: "agt_abcdef0123456789abcdef01", Name: "triage", InvokeURL: invokeURL,
- },
- Revision: 3, Status: "staged", Digest: "f42ea75bad3e",
- }, deployOutputStyle{color: true, hyperlinks: true})
- got := out.String()
- for _, want := range []string{
- "\x1b[32m✓\x1b[0m",
- "Deployed \x1b[1mtriage\x1b[0m",
- "\x1b[1mAgent URL\x1b[0m",
- "3 · \x1b[33mstaged\x1b[0m · f42ea75bad3e",
- "\x1b]8;;" + invokeURL + "\x1b\\\x1b[4;36m" + invokeURL + "\x1b[0m\x1b]8;;\x1b\\",
- } {
- if !strings.Contains(got, want) {
- t.Errorf("styled output missing %q:\n%q", want, got)
- }
- }
-}
-
-func TestTerminalLinkRejectsControlSequenceInjection(t *testing.T) {
- got := terminalLink("https://example.com/ok\x1b]8;;https://evil.example", deployOutputStyle{color: true, hyperlinks: true})
- if strings.Contains(got, "\x1b") || !strings.Contains(got, "https://example.com/ok") {
- t.Fatalf("unsafe terminal link projection: %q", got)
- }
-}
diff --git a/cmd/oc/internal/commands/agent_hooks.go b/cmd/oc/internal/commands/agent_hooks.go
deleted file mode 100644
index d45e8e07..00000000
--- a/cmd/oc/internal/commands/agent_hooks.go
+++ /dev/null
@@ -1,277 +0,0 @@
-package commands
-
-import (
- "fmt"
- "net/url"
- "strings"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-type AgentHook struct {
- ID string `json:"id"`
- AgentID string `json:"agent_id"`
- Name string `json:"name"`
- Status string `json:"status"`
- SecretLast4 string `json:"secret_last4"`
- RevokedReason *string `json:"revoked_reason"`
- ExpiresAt *string `json:"expires_at"`
- CreatedAt string `json:"created_at"`
-}
-
-type AgentHookCreateResponse struct {
- Hook AgentHook `json:"hook"`
- HookURL string `json:"hook_url"`
-}
-
-type agentHookListResponse struct {
- Data []AgentHook `json:"data"`
- NextCursor *string `json:"next_cursor"`
-}
-
-func agentHookListPath(agentID string, includeRevoked bool, cursor string, limit int) string {
- query := url.Values{}
- if includeRevoked {
- query.Set("include_revoked", "true")
- }
- if cursor != "" {
- query.Set("cursor", cursor)
- }
- if limit > 0 {
- query.Set("limit", fmt.Sprintf("%d", limit))
- }
- path := "/v3/agents/" + agentID + "/hooks"
- if encoded := query.Encode(); encoded != "" {
- path += "?" + encoded
- }
- return path
-}
-
-func resolveHookID(cmd *cobra.Command, sc *client.Client, agentID, ref string) (string, error) {
- if strings.HasPrefix(ref, "hk_") {
- return ref, nil
- }
- var current []AgentHook
- var revoked []AgentHook
- cursor := ""
- for {
- var response agentHookListResponse
- if err := sc.Get(
- cmd.Context(),
- agentHookListPath(agentID, true, cursor, 100),
- &response,
- ); err != nil {
- return "", err
- }
- for _, hook := range response.Data {
- if hook.Name != ref {
- continue
- }
- if hook.Status == "revoked" {
- revoked = append(revoked, hook)
- } else {
- current = append(current, hook)
- }
- }
- if response.NextCursor == nil || *response.NextCursor == "" {
- break
- }
- cursor = *response.NextCursor
- }
- if len(current) == 1 {
- return current[0].ID, nil
- }
- if len(current) > 1 {
- return "", fmt.Errorf("multiple current Hooks named %q; use a Hook id", ref)
- }
- if len(revoked) == 1 {
- return revoked[0].ID, nil
- }
- if len(revoked) > 1 {
- return "", fmt.Errorf("multiple revoked Hooks named %q; use a Hook id", ref)
- }
- return "", fmt.Errorf("no Hook named %q on this agent", ref)
-}
-
-func hookReason(reason *string) string {
- if reason == nil || *reason == "" {
- return "-"
- }
- if *reason == "secret_exposure" {
- return "secret exposure"
- }
- return *reason
-}
-
-func hookExpiry(expiresAt *string) string {
- if expiresAt == nil || *expiresAt == "" {
- return "never"
- }
- return *expiresAt
-}
-
-var agentHooksCmd = &cobra.Command{
- Use: "hooks",
- Short: "List an agent's Hook URLs",
- Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, _ []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- includeRevoked, _ := cmd.Flags().GetBool("include-revoked")
- cursor, _ := cmd.Flags().GetString("cursor")
- limit, _ := cmd.Flags().GetInt("limit")
- var response agentHookListResponse
- if err := sc.Get(
- cmd.Context(),
- agentHookListPath(agentID, includeRevoked, cursor, limit),
- &response,
- ); err != nil {
- return err
- }
- printer.Print(response, func() {
- if len(response.Data) == 0 {
- fmt.Println("No Hook URLs.")
- return
- }
- rows := make([][]string, 0, len(response.Data))
- for _, hook := range response.Data {
- rows = append(rows, []string{
- hook.Name,
- hook.ID,
- hook.Status,
- hook.SecretLast4,
- hookExpiry(hook.ExpiresAt),
- hookReason(hook.RevokedReason),
- })
- }
- printer.Table([]string{"NAME", "ID", "STATUS", "LAST4", "EXPIRES", "REVOKED"}, rows)
- if response.NextCursor != nil {
- fmt.Printf("More: oc agent hooks --agent %s --cursor %s\n", agentID, *response.NextCursor)
- }
- })
- return nil
- },
-}
-
-var agentHookCmd = &cobra.Command{
- Use: "hook",
- Short: "Create, inspect, and revoke Agent Hook URLs",
-}
-
-var agentHookCreateCmd = &cobra.Command{
- Use: "create <name>",
- Short: "Create a named Hook URL",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- body := map[string]interface{}{"name": args[0]}
- if expiresAt, _ := cmd.Flags().GetString("expires-at"); expiresAt != "" {
- body["expires_at"] = expiresAt
- }
- var response AgentHookCreateResponse
- if err := sc.Post(cmd.Context(), "/v3/agents/"+agentID+"/hooks", body, &response); err != nil {
- return err
- }
- printer.Print(response, func() {
- fmt.Printf("Created Hook %s (%s)\n", response.Hook.Name, response.Hook.ID)
- fmt.Printf("URL: %s\n", response.HookURL)
- fmt.Println("Copy it now. The complete URL cannot be retrieved again.")
- })
- return nil
- },
-}
-
-var agentHookGetCmd = &cobra.Command{
- Use: "get <id|name>",
- Short: "Show a Hook without its secret URL",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- hookID, err := resolveHookID(cmd, sc, agentID, args[0])
- if err != nil {
- return err
- }
- var hook AgentHook
- if err := sc.Get(cmd.Context(), "/v3/agents/"+agentID+"/hooks/"+hookID, &hook); err != nil {
- return err
- }
- printer.Print(hook, func() {
- fmt.Printf("Name: %s\n", hook.Name)
- fmt.Printf("ID: %s\n", hook.ID)
- fmt.Printf("Status: %s\n", hook.Status)
- fmt.Printf("Last 4: %s\n", hook.SecretLast4)
- fmt.Printf("Expires: %s\n", hookExpiry(hook.ExpiresAt))
- fmt.Printf("Revoked: %s\n", hookReason(hook.RevokedReason))
- })
- return nil
- },
-}
-
-var agentHookRevokeCmd = &cobra.Command{
- Use: "revoke <id|name>",
- Short: "Permanently revoke a Hook URL",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- hookID, err := resolveHookID(cmd, sc, agentID, args[0])
- if err != nil {
- return err
- }
- if err := confirmDestructive(cmd, fmt.Sprintf("Permanently revoke Hook %s", args[0])); err != nil {
- return err
- }
- if err := sc.Delete(cmd.Context(), "/v3/agents/"+agentID+"/hooks/"+hookID); err != nil {
- return err
- }
- printer.Print(map[string]string{"id": hookID, "status": "revoked"}, func() {
- fmt.Printf("Revoked Hook %s.\n", hookID)
- })
- return nil
- },
-}
-
-func registerAgentHooks() {
- for _, command := range []*cobra.Command{
- agentHooksCmd,
- agentHookCreateCmd,
- agentHookGetCmd,
- agentHookRevokeCmd,
- } {
- command.Flags().String("agent", "", "Agent id or name (else the cwd agent.toml)")
- }
- agentHooksCmd.Flags().Bool("include-revoked", false, "Include revoked Hooks")
- agentHooksCmd.Flags().String("cursor", "", "Continue a previous list page")
- agentHooksCmd.Flags().Int("limit", 0, "Maximum Hooks to return (server caps at 100)")
- agentHookCreateCmd.Flags().String("expires-at", "", "RFC 3339 expiry (default: no expiry)")
- agentHookRevokeCmd.Flags().Bool("yes", false, "Skip the confirmation prompt")
- agentHookCmd.AddCommand(agentHookCreateCmd, agentHookGetCmd, agentHookRevokeCmd)
- agentCmd.AddCommand(agentHooksCmd, agentHookCmd)
-}
diff --git a/cmd/oc/internal/commands/agent_hooks_test.go b/cmd/oc/internal/commands/agent_hooks_test.go
deleted file mode 100644
index 5cb9eae6..00000000
--- a/cmd/oc/internal/commands/agent_hooks_test.go
+++ /dev/null
@@ -1,102 +0,0 @@
-package commands
-
-import (
- "context"
- "encoding/json"
- "io"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-func TestResolveHookIDPrefersCurrentHookAcrossPages(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Header.Get("X-API-Key") != "osb_test" {
- t.Errorf("missing sessions API key")
- }
- if r.URL.Query().Get("include_revoked") != "true" || r.URL.Query().Get("limit") != "100" {
- t.Errorf("query = %q", r.URL.RawQuery)
- }
- w.Header().Set("Content-Type", "application/json")
- if r.URL.Query().Get("cursor") == "" {
- _, _ = io.WriteString(w, `{"data":[{"id":"hk_aaaaaaaaaaaaaaaaaaaaaaaa","agent_id":"agt_0123456789abcdef01234567","name":"grafana","status":"revoked","secret_last4":"old1","revoked_reason":"manual","expires_at":null,"created_at":"2026-07-20T00:00:00Z"}],"next_cursor":"next"}`)
- return
- }
- _, _ = io.WriteString(w, `{"data":[{"id":"hk_bbbbbbbbbbbbbbbbbbbbbbbb","agent_id":"agt_0123456789abcdef01234567","name":"grafana","status":"active","secret_last4":"new1","revoked_reason":null,"expires_at":null,"created_at":"2026-07-21T00:00:00Z"}],"next_cursor":null}`)
- }))
- defer server.Close()
-
- command := &cobra.Command{}
- command.SetContext(context.Background())
- hookID, err := resolveHookID(
- command,
- client.NewSessionsAPI(server.URL, "osb_test"),
- "agt_0123456789abcdef01234567",
- "grafana",
- )
- if err != nil {
- t.Fatal(err)
- }
- if hookID != "hk_bbbbbbbbbbbbbbbbbbbbbbbb" {
- t.Fatalf("hook id = %q", hookID)
- }
-}
-
-func TestResolveHookIDRejectsAmbiguousRevokedNames(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- _, _ = io.WriteString(w, `{"data":[{"id":"hk_aaaaaaaaaaaaaaaaaaaaaaaa","name":"grafana","status":"revoked"},{"id":"hk_bbbbbbbbbbbbbbbbbbbbbbbb","name":"grafana","status":"revoked"}],"next_cursor":null}`)
- }))
- defer server.Close()
-
- command := &cobra.Command{}
- command.SetContext(context.Background())
- _, err := resolveHookID(
- command,
- client.NewSessionsAPI(server.URL, "osb_test"),
- "agt_0123456789abcdef01234567",
- "grafana",
- )
- if err == nil || !strings.Contains(err.Error(), "multiple revoked Hooks") {
- t.Fatalf("error = %v", err)
- }
-}
-
-func TestAgentHookPublicMetadataCannotCarryTheSecretURL(t *testing.T) {
- response := AgentHookCreateResponse{
- Hook: AgentHook{
- ID: "hk_aaaaaaaaaaaaaaaaaaaaaaaa",
- AgentID: "agt_0123456789abcdef01234567",
- Name: "grafana",
- Status: "active",
- SecretLast4: "last",
- },
- HookURL: "https://example.test/hooks/ochk_v1_secret",
- }
- encoded, err := json.Marshal(response.Hook)
- if err != nil {
- t.Fatal(err)
- }
- if strings.Contains(string(encoded), "ochk_v1_") || strings.Contains(string(encoded), "hook_url") {
- t.Fatalf("Hook metadata leaked credential material: %s", encoded)
- }
- if !strings.Contains(response.HookURL, "ochk_v1_") {
- t.Fatal("create response should retain its copy-once URL")
- }
-}
-
-func TestAgentHookCommandShape(t *testing.T) {
- if agentHooksCmd.Use != "hooks" {
- t.Fatalf("list command use = %q", agentHooksCmd.Use)
- }
- if agentHookCreateCmd.Flags().Lookup("expires-at") == nil {
- t.Fatal("hook create must expose --expires-at")
- }
- if agentHookRevokeCmd.Flags().Lookup("yes") == nil {
- t.Fatal("hook revoke must require or accept explicit confirmation")
- }
-}
diff --git a/cmd/oc/internal/commands/agent_init.go b/cmd/oc/internal/commands/agent_init.go
deleted file mode 100644
index d82a8173..00000000
--- a/cmd/oc/internal/commands/agent_init.go
+++ /dev/null
@@ -1,99 +0,0 @@
-package commands
-
-import (
- "fmt"
- "os"
- "path/filepath"
-
- "github.com/spf13/cobra"
-)
-
-const agentTomlTmpl = `name = %q
-model = %q
-
-[runtime]
-family = %q # claude | codex | pi | flue
-type = "default"
-
-[limits]
-turns = 24
-`
-
-const promptTmpl = `You are a helpful agent.
-
-Describe the agent's behavior here — this file is the system prompt.
-`
-
-const skillTmpl = `---
-name: example
-description: An example skill. Rename or delete this folder.
----
-
-# Example skill
-
-Describe what this skill does and when to use it. Delete the skills/ directory
-entirely if your agent doesn't need skills.
-`
-
-var agentInitCmd = &cobra.Command{
- Use: "init [dir]",
- Short: "Scaffold a deployable agent directory (agent.toml + prompt.md + skills/)",
- Example: " oc agent init\n" +
- " oc agent init ./agents/triage --name triage --model anthropic/claude-sonnet-5\n" +
- " oc agent init ./agents/edge --runtime flue\n" +
- " oc agent init && $EDITOR prompt.md && oc agent deploy",
- Args: cobra.MaximumNArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- dir := "."
- if len(args) > 0 {
- dir = args[0]
- }
- name, _ := cmd.Flags().GetString("name")
- model, _ := cmd.Flags().GetString("model")
- runtime, _ := cmd.Flags().GetString("runtime")
- if name == "" {
- if abs, err := filepath.Abs(dir); err == nil {
- name = filepath.Base(abs)
- }
- if name == "" || name == "." || name == string(filepath.Separator) {
- name = "my-agent"
- }
- }
-
- if err := os.MkdirAll(filepath.Join(dir, "skills", "example"), 0o755); err != nil {
- return err
- }
- files := []struct{ path, content string }{
- {filepath.Join(dir, "agent.toml"), fmt.Sprintf(agentTomlTmpl, name, model, runtime)},
- {filepath.Join(dir, "prompt.md"), promptTmpl},
- {filepath.Join(dir, "skills", "example", "SKILL.md"), skillTmpl},
- }
- created := 0
- for _, f := range files {
- if _, err := os.Stat(f.path); err == nil {
- fmt.Printf(" skip %s (exists)\n", f.path)
- continue
- }
- if err := os.WriteFile(f.path, []byte(f.content), 0o644); err != nil {
- return err
- }
- fmt.Printf(" create %s\n", f.path)
- created++
- }
- if runtime == "flue" {
- fmt.Printf(
- "\nScaffolded %d file(s). Edit prompt.md, then: oc agent deploy %s\n",
- created, dir,
- )
- } else {
- fmt.Printf("\nScaffolded %d file(s). Edit prompt.md, then: oc agent deploy %s\n", created, dir)
- }
- return nil
- },
-}
-
-func init() {
- agentInitCmd.Flags().String("name", "", "Agent name (default: the directory name)")
- agentInitCmd.Flags().String("model", "anthropic/claude-sonnet-5", "Model")
- agentInitCmd.Flags().String("runtime", "claude", "Runtime family (claude|codex|pi|flue)")
-}
diff --git a/cmd/oc/internal/commands/agent_invoke.go b/cmd/oc/internal/commands/agent_invoke.go
deleted file mode 100644
index 2e2d380a..00000000
--- a/cmd/oc/internal/commands/agent_invoke.go
+++ /dev/null
@@ -1,248 +0,0 @@
-package commands
-
-import (
- "bytes"
- "context"
- "crypto/rand"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "os"
- "strconv"
- "strings"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/config"
- "github.com/spf13/cobra"
-)
-
-const agentInvokeResponseMaxBytes = 1 << 20
-
-type AgentInvokeReceipt struct {
- RequestID string `json:"request_id"`
- Session struct {
- ID string `json:"id"`
- Status string `json:"status"`
- Head int `json:"head"`
- } `json:"session"`
- ClientToken string `json:"client_token,omitempty"`
- Links struct {
- Events string `json:"events"`
- Messages string `json:"messages"`
- } `json:"links"`
- Replayed bool `json:"replayed"`
-}
-
-type invokeWait func(context.Context, time.Duration) error
-
-func waitForInvokeRetry(ctx context.Context, duration time.Duration) error {
- timer := time.NewTimer(duration)
- defer timer.Stop()
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-timer.C:
- return nil
- }
-}
-
-func generatedInvokeKey() (string, error) {
- var value [16]byte
- if _, err := rand.Read(value[:]); err != nil {
- return "", fmt.Errorf("generate idempotency key: %w", err)
- }
- return "oc-cli-" + hex.EncodeToString(value[:]), nil
-}
-
-func invokeRetryDelay(response *http.Response, attempt int) time.Duration {
- if raw := response.Header.Get("Retry-After"); raw != "" {
- if seconds, err := strconv.Atoi(raw); err == nil && seconds > 0 {
- return min(time.Duration(seconds)*time.Second, 8*time.Second)
- }
- }
- return min(250*time.Millisecond*time.Duration(1<<attempt), 2*time.Second)
-}
-
-func readBoundedResponse(response *http.Response) ([]byte, error) {
- defer response.Body.Close()
- body, err := io.ReadAll(io.LimitReader(response.Body, agentInvokeResponseMaxBytes+1))
- if err != nil {
- return nil, err
- }
- if len(body) > agentInvokeResponseMaxBytes {
- return nil, fmt.Errorf("Agent URL response exceeds %d bytes", agentInvokeResponseMaxBytes)
- }
- return body, nil
-}
-
-func invokeAgentURL(
- ctx context.Context,
- httpClient *http.Client,
- apiKey string,
- invokeURL string,
- body []byte,
- idempotencyKey string,
- maxRetries int,
- wait invokeWait,
-) (AgentInvokeReceipt, error) {
- var receipt AgentInvokeReceipt
- target := strings.TrimRight(invokeURL, "/") + "/"
-
- for attempt := 0; ; attempt++ {
- request, err := http.NewRequestWithContext(ctx, http.MethodPost, target, bytes.NewReader(body))
- if err != nil {
- return receipt, err
- }
- request.Header.Set("Authorization", "Bearer "+apiKey)
- request.Header.Set("Content-Type", "application/json")
- request.Header.Set("Idempotency-Key", idempotencyKey)
-
- response, err := httpClient.Do(request)
- if err != nil {
- if attempt < maxRetries && ctx.Err() == nil {
- if waitErr := wait(ctx, min(250*time.Millisecond*time.Duration(1<<attempt), 2*time.Second)); waitErr != nil {
- return receipt, waitErr
- }
- continue
- }
- return receipt, err
- }
-
- retryable := response.StatusCode == http.StatusTooManyRequests || response.StatusCode >= 500
- if retryable && attempt < maxRetries {
- delay := invokeRetryDelay(response, attempt)
- _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, agentInvokeResponseMaxBytes))
- response.Body.Close()
- if err := wait(ctx, delay); err != nil {
- return receipt, err
- }
- continue
- }
-
- responseBody, err := readBoundedResponse(response)
- if err != nil {
- return receipt, err
- }
- if response.StatusCode < 200 || response.StatusCode >= 300 {
- var envelope struct {
- Error struct {
- Message string `json:"message"`
- } `json:"error"`
- }
- message := strings.TrimSpace(string(responseBody))
- if json.Unmarshal(responseBody, &envelope) == nil && envelope.Error.Message != "" {
- message = envelope.Error.Message
- }
- return receipt, &client.APIError{StatusCode: response.StatusCode, Message: message}
- }
- if err := json.Unmarshal(responseBody, &receipt); err != nil {
- return receipt, fmt.Errorf("decode Agent URL response: %w", err)
- }
- return receipt, nil
- }
-}
-
-func agentInvokeInput(cmd *cobra.Command) ([]byte, error) {
- data, _ := cmd.Flags().GetString("data")
- path, _ := cmd.Flags().GetString("file")
- fromStdin, _ := cmd.Flags().GetBool("stdin")
- selected := 0
- if cmd.Flags().Changed("data") {
- selected++
- }
- if path != "" {
- selected++
- }
- if fromStdin {
- selected++
- }
- if selected > 1 {
- return nil, fmt.Errorf("use only one of --data, --file, or --stdin")
- }
-
- var body []byte
- var err error
- switch {
- case path != "":
- body, err = os.ReadFile(path)
- case fromStdin:
- body, err = io.ReadAll(os.Stdin)
- default:
- body = []byte(data)
- }
- if err != nil {
- return nil, err
- }
- if !json.Valid(body) {
- return nil, fmt.Errorf("invocation body must be valid JSON")
- }
- return body, nil
-}
-
-var agentInvokeCmd = &cobra.Command{
- Use: "invoke <id|name>",
- Short: "Start a session through an agent's canonical URL",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID, err := resolveRef(cmd, sc, args[0])
- if err != nil {
- return err
- }
- var agent Agent
- if err := sc.Get(cmd.Context(), "/v3/agents/"+agentID, &agent); err != nil {
- return err
- }
- if agent.InvokeURL == "" {
- return fmt.Errorf("agent response did not include invoke_url")
- }
-
- body, err := agentInvokeInput(cmd)
- if err != nil {
- return err
- }
- key, _ := cmd.Flags().GetString("idempotency-key")
- if key == "" {
- key, err = generatedInvokeKey()
- if err != nil {
- return err
- }
- }
- cfg := config.Load(cmd)
- if cfg.APIKey == "" {
- return fmt.Errorf("OpenComputer API key is required")
- }
- httpClient := &http.Client{
- Timeout: 30 * time.Second,
- CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
- return fmt.Errorf("Agent URL must not redirect")
- },
- }
- receipt, err := invokeAgentURL(
- cmd.Context(), httpClient, cfg.APIKey, agent.InvokeURL, body, key, 2, waitForInvokeRetry,
- )
- if err != nil {
- return err
- }
- printer.Print(receipt, func() {
- fmt.Printf("Accepted session %s (status: %s)\n", receipt.Session.ID, receipt.Session.Status)
- fmt.Printf("Follow: oc session logs %s\n", receipt.Session.ID)
- fmt.Printf("Steer: oc session steer %s \"message\"\n", receipt.Session.ID)
- })
- return nil
- },
-}
-
-func registerAgentInvoke() {
- agentInvokeCmd.Flags().String("data", "{}", "JSON request body")
- agentInvokeCmd.Flags().String("file", "", "Read the JSON request body from a file")
- agentInvokeCmd.Flags().Bool("stdin", false, "Read the JSON request body from stdin")
- agentInvokeCmd.Flags().String("idempotency-key", "", "Reuse a logical invocation across retries")
- agentCmd.AddCommand(agentInvokeCmd)
-}
diff --git a/cmd/oc/internal/commands/agent_invoke_test.go b/cmd/oc/internal/commands/agent_invoke_test.go
deleted file mode 100644
index 359c3dfe..00000000
--- a/cmd/oc/internal/commands/agent_invoke_test.go
+++ /dev/null
@@ -1,113 +0,0 @@
-package commands
-
-import (
- "context"
- "io"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
- "time"
-
- "github.com/spf13/cobra"
-)
-
-func noInvokeWait(context.Context, time.Duration) error { return nil }
-
-func TestInvokeAgentURLUsesExactRootBearerAndStableIdempotencyKey(t *testing.T) {
- var requests int
- var firstKey string
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- requests++
- if r.URL.Path != "/" || r.URL.RawQuery != "" {
- t.Errorf("request target = %q, want exact root", r.URL.RequestURI())
- }
- if got := r.Header.Get("Authorization"); got != "Bearer osb_test" {
- t.Errorf("Authorization = %q", got)
- }
- if got := r.Header.Get("X-API-Key"); got != "" {
- t.Errorf("X-API-Key must be absent, got %q", got)
- }
- key := r.Header.Get("Idempotency-Key")
- if requests == 1 {
- firstKey = key
- } else if key != firstKey {
- t.Errorf("retry key = %q, want %q", key, firstKey)
- }
- body, _ := io.ReadAll(r.Body)
- if string(body) != `{"task":"triage"}` {
- t.Errorf("body = %q", body)
- }
- if requests == 1 {
- http.Error(w, "temporary", http.StatusServiceUnavailable)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusAccepted)
- _, _ = io.WriteString(w, `{"request_id":"req_1","session":{"id":"ses_1","status":"running","head":1},"replayed":false}`)
- }))
- defer server.Close()
-
- receipt, err := invokeAgentURL(
- context.Background(),
- server.Client(),
- "osb_test",
- server.URL,
- []byte(`{"task":"triage"}`),
- "stable-key",
- 2,
- noInvokeWait,
- )
- if err != nil {
- t.Fatal(err)
- }
- if requests != 2 {
- t.Fatalf("requests = %d, want 2", requests)
- }
- if receipt.Session.ID != "ses_1" || receipt.Session.Status != "running" {
- t.Fatalf("receipt = %#v", receipt)
- }
-}
-
-func TestAgentInvokeInputValidatesJSONAndExclusiveSources(t *testing.T) {
- command := &cobra.Command{}
- command.Flags().String("data", "{}", "")
- command.Flags().String("file", "", "")
- command.Flags().Bool("stdin", false, "")
-
- if err := command.Flags().Set("data", `{"ok":true}`); err != nil {
- t.Fatal(err)
- }
- body, err := agentInvokeInput(command)
- if err != nil || string(body) != `{"ok":true}` {
- t.Fatalf("body = %q, err = %v", body, err)
- }
-
- if err := command.Flags().Set("stdin", "true"); err != nil {
- t.Fatal(err)
- }
- if _, err := agentInvokeInput(command); err == nil || !strings.Contains(err.Error(), "only one") {
- t.Fatalf("exclusive source error = %v", err)
- }
-
- invalid := &cobra.Command{}
- invalid.Flags().String("data", "{}", "")
- invalid.Flags().String("file", "", "")
- invalid.Flags().Bool("stdin", false, "")
- if err := invalid.Flags().Set("data", "not-json"); err != nil {
- t.Fatal(err)
- }
- if _, err := agentInvokeInput(invalid); err == nil || !strings.Contains(err.Error(), "valid JSON") {
- t.Fatalf("JSON validation error = %v", err)
- }
-}
-
-func TestGeneratedInvokeKeyHasStablePublicShape(t *testing.T) {
- key, err := generatedInvokeKey()
- if err != nil {
- t.Fatal(err)
- }
- if len(key) != len("oc-cli-")+32 || !strings.HasPrefix(key, "oc-cli-") {
- t.Fatalf("generated key = %q", key)
- }
-}
diff --git a/cmd/oc/internal/commands/agent_schedules.go b/cmd/oc/internal/commands/agent_schedules.go
deleted file mode 100644
index e0ee62a5..00000000
--- a/cmd/oc/internal/commands/agent_schedules.go
+++ /dev/null
@@ -1,356 +0,0 @@
-package commands
-
-// `oc agent schedule[s]` — cron for agents (design 015). A schedule fires an agent on a cron; each
-// firing starts one session on the active revision. Agent addressing follows the house convention:
-// --agent <id|name> on every verb, else the cwd agent.toml. Schedules are referenced by NAME (or a
-// sch_… id); the name is resolved to an id against the agent.
-
-import (
- "fmt"
- "strings"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-// ── Response types (mirror the sessions-api JSON, snake_case) ──
-
-type Schedule struct {
- ID string `json:"id"`
- AgentID string `json:"agent_id"`
- Name string `json:"name"`
- Cron string `json:"cron"`
- TZ *string `json:"tz"`
- Input string `json:"input"`
- Overlap string `json:"overlap"`
- State string `json:"state"`
- NextFireAt string `json:"next_fire_at"`
- LastFiredAt *string `json:"last_fired_at"`
- ConsecutiveFailures int `json:"consecutive_failures"`
- LastError *string `json:"last_error"`
- CreatedAt string `json:"created_at"`
-}
-
-type scheduleEnvelope struct {
- Schedule Schedule `json:"schedule"`
-}
-type scheduleListResp struct {
- Schedules []Schedule `json:"schedules"`
-}
-
-type ScheduleRun struct {
- ID string `json:"id"`
- ScheduleID string `json:"schedule_id"`
- ScheduledFor *string `json:"scheduled_for"`
- FiredAt string `json:"fired_at"`
- Outcome string `json:"outcome"`
- SessionID *string `json:"session_id"`
- Error *string `json:"error"`
-}
-type runEnvelope struct {
- Run ScheduleRun `json:"run"`
-}
-type runListResp struct {
- Runs []ScheduleRun `json:"runs"`
- NextCursor *string `json:"next_cursor"`
-}
-
-// schedStr renders a nullable/empty string field as "-".
-func schedStr(p *string) string {
- if p == nil || *p == "" {
- return "-"
- }
- return *p
-}
-
-// resolveScheduleID maps a "sch_…" id (used as-is) or a schedule NAME (looked up on the agent) to id.
-// The prefix check is unambiguous: schedule names are strict slugs (^[a-z0-9][a-z0-9-]{0,63}$, no
-// underscores), so a name can never begin with "sch_".
-func resolveScheduleID(cmd *cobra.Command, sc *client.Client, agentID, ref string) (string, error) {
- if strings.HasPrefix(ref, "sch_") {
- return ref, nil
- }
- var list scheduleListResp
- if err := sc.Get(cmd.Context(), "/v3/agents/"+agentID+"/schedules", &list); err != nil {
- return "", err
- }
- for _, s := range list.Schedules {
- if s.Name == ref {
- return s.ID, nil
- }
- }
- return "", fmt.Errorf("no schedule named %q on this agent", ref)
-}
-
-var agentSchedulesCmd = &cobra.Command{
- Use: "schedules",
- Short: "List an agent's schedules (cron for agents)",
- Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- var resp scheduleListResp
- if err := sc.Get(cmd.Context(), "/v3/agents/"+agentID+"/schedules", &resp); err != nil {
- return err
- }
- printer.Print(resp.Schedules, func() {
- if len(resp.Schedules) == 0 {
- fmt.Println("No schedules.")
- return
- }
- headers := []string{"NAME", "CRON", "TZ", "STATE", "NEXT_FIRE", "FAILS"}
- var rows [][]string
- for _, s := range resp.Schedules {
- rows = append(rows, []string{s.Name, s.Cron, schedStr(s.TZ), s.State, s.NextFireAt, fmt.Sprintf("%d", s.ConsecutiveFailures)})
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var agentScheduleCmd = &cobra.Command{
- Use: "schedule",
- Short: "Manage an agent's schedules (create/get/pause/resume/delete/fire/runs)",
-}
-
-var agentScheduleCreateCmd = &cobra.Command{
- Use: "create <name>",
- Short: "Create a schedule on an agent",
- Example: " oc agent schedule create morning-sweep --cron \"0 9 * * 1-5\" --input \"Reconcile docs; open a draft PR if anything drifted.\"",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- cron, _ := cmd.Flags().GetString("cron")
- input, _ := cmd.Flags().GetString("input")
- tz, _ := cmd.Flags().GetString("tz")
- overlap, _ := cmd.Flags().GetString("overlap")
- if cron == "" {
- return fmt.Errorf("--cron is required")
- }
- if input == "" {
- return fmt.Errorf("--input is required")
- }
- body := map[string]interface{}{"name": args[0], "cron": cron, "input": input}
- if tz != "" {
- body["tz"] = tz
- }
- if overlap != "" {
- body["overlap"] = overlap
- }
- var env scheduleEnvelope
- if err := sc.Post(cmd.Context(), "/v3/agents/"+agentID+"/schedules", body, &env); err != nil {
- return err
- }
- printer.Print(env.Schedule, func() {
- fmt.Printf("Created schedule %s (%s) — next fire %s\n", env.Schedule.Name, env.Schedule.ID, env.Schedule.NextFireAt)
- })
- return nil
- },
-}
-
-var agentScheduleGetCmd = &cobra.Command{
- Use: "get <name>",
- Short: "Show a schedule",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- sid, err := resolveScheduleID(cmd, sc, agentID, args[0])
- if err != nil {
- return err
- }
- var env scheduleEnvelope
- if err := sc.Get(cmd.Context(), "/v3/agents/"+agentID+"/schedules/"+sid, &env); err != nil {
- return err
- }
- printer.Print(env.Schedule, func() {
- s := env.Schedule
- fmt.Printf("Name: %s\n", s.Name)
- fmt.Printf("ID: %s\n", s.ID)
- fmt.Printf("Cron: %s (%s)\n", s.Cron, schedStr(s.TZ))
- fmt.Printf("State: %s\n", s.State)
- fmt.Printf("Next fire: %s\n", s.NextFireAt)
- fmt.Printf("Last fired: %s\n", schedStr(s.LastFiredAt))
- fmt.Printf("Overlap: %s\n", s.Overlap)
- if s.LastError != nil && *s.LastError != "" {
- fmt.Printf("Last error: %s (failures: %d)\n", *s.LastError, s.ConsecutiveFailures)
- }
- fmt.Printf("Input: %s\n", s.Input)
- })
- return nil
- },
-}
-
-// patchPaused PATCHes {paused} and reports the resulting state (pause / resume share this).
-func patchPaused(cmd *cobra.Command, args []string, paused bool, verb string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- sid, err := resolveScheduleID(cmd, sc, agentID, args[0])
- if err != nil {
- return err
- }
- var env scheduleEnvelope
- if err := sc.Patch(cmd.Context(), "/v3/agents/"+agentID+"/schedules/"+sid, map[string]interface{}{"paused": paused}, &env); err != nil {
- return err
- }
- printer.Print(env.Schedule, func() {
- fmt.Printf("%s %s — state %s, next fire %s\n", verb, env.Schedule.Name, env.Schedule.State, env.Schedule.NextFireAt)
- })
- return nil
-}
-
-var agentSchedulePauseCmd = &cobra.Command{
- Use: "pause <name>", Short: "Pause a schedule", Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error { return patchPaused(cmd, args, true, "Paused") },
-}
-var agentScheduleResumeCmd = &cobra.Command{
- Use: "resume <name>", Short: "Resume a schedule", Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error { return patchPaused(cmd, args, false, "Resumed") },
-}
-
-var agentScheduleDeleteCmd = &cobra.Command{
- Use: "delete <name>", Aliases: []string{"rm"}, Short: "Delete a schedule (run history is kept)", Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- sid, err := resolveScheduleID(cmd, sc, agentID, args[0])
- if err != nil {
- return err
- }
- if err := sc.Delete(cmd.Context(), "/v3/agents/"+agentID+"/schedules/"+sid); err != nil {
- return err
- }
- printer.Print(map[string]interface{}{"deleted": args[0]}, func() { fmt.Printf("Deleted schedule %s\n", args[0]) })
- return nil
- },
-}
-
-var agentScheduleFireCmd = &cobra.Command{
- Use: "fire <name>", Short: "Test-fire a schedule now (prints the created session)", Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- sid, err := resolveScheduleID(cmd, sc, agentID, args[0])
- if err != nil {
- return err
- }
- var env runEnvelope
- if err := sc.Post(cmd.Context(), "/v3/agents/"+agentID+"/schedules/"+sid+"/fire", nil, &env); err != nil {
- return err
- }
- printer.Print(env.Run, func() {
- r := env.Run
- if r.Outcome == "enacted" && r.SessionID != nil {
- fmt.Printf("Fired — session %s\n", *r.SessionID)
- fmt.Printf(" tail it: oc session logs %s\n", *r.SessionID)
- } else {
- fmt.Printf("Fired — outcome %s\n", r.Outcome)
- if r.Error != nil && *r.Error != "" {
- fmt.Printf(" error: %s\n", *r.Error)
- }
- }
- })
- return nil
- },
-}
-
-var agentScheduleRunsCmd = &cobra.Command{
- Use: "runs <name>", Short: "Show a schedule's run history (newest first)", Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID, err := targetAgentID(cmd, sc, nil)
- if err != nil {
- return err
- }
- sid, err := resolveScheduleID(cmd, sc, agentID, args[0])
- if err != nil {
- return err
- }
- limit, _ := cmd.Flags().GetInt("limit")
- path := fmt.Sprintf("/v3/agents/%s/schedules/%s/runs", agentID, sid)
- if limit > 0 {
- path += fmt.Sprintf("?limit=%d", limit)
- }
- var resp runListResp
- if err := sc.Get(cmd.Context(), path, &resp); err != nil {
- return err
- }
- printer.Print(resp.Runs, func() {
- if len(resp.Runs) == 0 {
- fmt.Println("No runs yet.")
- return
- }
- headers := []string{"OUTCOME", "SCHEDULED_FOR", "FIRED", "SESSION", "ERROR"}
- var rows [][]string
- for _, r := range resp.Runs {
- rows = append(rows, []string{r.Outcome, schedStr(r.ScheduledFor), r.FiredAt, schedStr(r.SessionID), schedStr(r.Error)})
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-func registerAgentSchedules() {
- // Agent addressing: --agent on every verb, else the cwd agent.toml.
- for _, c := range []*cobra.Command{
- agentSchedulesCmd, agentScheduleCreateCmd, agentScheduleGetCmd,
- agentSchedulePauseCmd, agentScheduleResumeCmd, agentScheduleDeleteCmd,
- agentScheduleFireCmd, agentScheduleRunsCmd,
- } {
- c.Flags().String("agent", "", "Agent id or name (else the cwd agent.toml)")
- }
- agentScheduleCreateCmd.Flags().String("cron", "", "5-field cron, e.g. \"0 9 * * 1-5\" (required)")
- agentScheduleCreateCmd.Flags().String("tz", "", "IANA time zone, e.g. Europe/London (optional; UTC if omitted)")
- agentScheduleCreateCmd.Flags().String("input", "", "First user message of every run (required)")
- agentScheduleCreateCmd.Flags().String("overlap", "", "skip (default) | allow")
- agentScheduleRunsCmd.Flags().Int("limit", 0, "Max runs to show")
-
- agentScheduleCmd.AddCommand(
- agentScheduleCreateCmd, agentScheduleGetCmd, agentSchedulePauseCmd, agentScheduleResumeCmd,
- agentScheduleDeleteCmd, agentScheduleFireCmd, agentScheduleRunsCmd,
- )
- agentCmd.AddCommand(agentSchedulesCmd)
- agentCmd.AddCommand(agentScheduleCmd)
-}
diff --git a/cmd/oc/internal/commands/allowed_hosts.go b/cmd/oc/internal/commands/allowed_hosts.go
deleted file mode 100644
index 3a9d3266..00000000
--- a/cmd/oc/internal/commands/allowed_hosts.go
+++ /dev/null
@@ -1,75 +0,0 @@
-package commands
-
-import (
- "fmt"
- "sort"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-var sandboxAllowedHostsCmd = &cobra.Command{
- Use: "allowed-hosts <sandbox-id>",
- Short: "Show the egress allowlist + per-secret allowed hosts for a sandbox",
- Long: `Show the egress allowlist (and any per-secret host restrictions) the
-sandbox's secrets proxy enforces. Useful for debugging "why is my
-outbound HTTP call being blocked" without having to cross-reference the
-secret store config separately.
-
-Sandboxes created without --secret-store have no per-store egress
-restriction; this command reports an empty list for those.`,
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- var resp struct {
- SandboxID string `json:"sandboxID"`
- SecretStore string `json:"secretStore"`
- EgressAllowlist []string `json:"egressAllowlist"`
- PerSecretAllowedHosts map[string][]string `json:"perSecretAllowedHosts"`
- }
- if err := c.Get(cmd.Context(), "/sandboxes/"+args[0]+"/allowed-hosts", &resp); err != nil {
- return err
- }
-
- printer.Print(resp, func() {
- if resp.SecretStore == "" {
- fmt.Printf("Sandbox %s has no secret store attached — no per-store egress restriction.\n", resp.SandboxID)
- return
- }
- fmt.Printf("Sandbox %s (secret store: %s)\n", resp.SandboxID, resp.SecretStore)
-
- fmt.Println()
- fmt.Println("Egress allowlist:")
- if len(resp.EgressAllowlist) == 0 {
- fmt.Println(" (empty — store has no allowlist; egress is governed by platform-level policy)")
- } else {
- for _, h := range resp.EgressAllowlist {
- fmt.Printf(" • %s\n", h)
- }
- }
-
- if len(resp.PerSecretAllowedHosts) > 0 {
- fmt.Println()
- fmt.Println("Per-secret allowed hosts:")
- // Sort keys for deterministic output
- names := make([]string, 0, len(resp.PerSecretAllowedHosts))
- for k := range resp.PerSecretAllowedHosts {
- names = append(names, k)
- }
- sort.Strings(names)
- for _, name := range names {
- hosts := resp.PerSecretAllowedHosts[name]
- fmt.Printf(" %s:\n", name)
- for _, h := range hosts {
- fmt.Printf(" • %s\n", h)
- }
- }
- }
- })
- return nil
- },
-}
-
-func init() {
- sandboxCmd.AddCommand(sandboxAllowedHostsCmd)
-}
diff --git a/cmd/oc/internal/commands/auth.go b/cmd/oc/internal/commands/auth.go
deleted file mode 100644
index 34580125..00000000
--- a/cmd/oc/internal/commands/auth.go
+++ /dev/null
@@ -1,687 +0,0 @@
-package commands
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net"
- "net/http"
- "net/url"
- "os"
- "os/exec"
- "runtime"
- "strings"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/config"
- "github.com/spf13/cobra"
-)
-
-const maxAuthResponseBytes = 64 << 10
-
-type deviceAuthorization struct {
- DeviceCode string `json:"device_code"`
- UserCode string `json:"user_code"`
- VerificationURI string `json:"verification_uri"`
- VerificationURIComplete string `json:"verification_uri_complete"`
- ExpiresIn int `json:"expires_in"`
- Interval int `json:"interval"`
-}
-
-type loginCredential struct {
- ID string `json:"id"`
- Key string `json:"key"`
- KeyPrefix string `json:"key_prefix"`
- Name string `json:"name"`
-}
-
-type loginIdentity struct {
- UserID string `json:"user_id"`
- Email string `json:"email"`
- OrgID string `json:"org_id"`
- OrgName string `json:"org_name"`
- APIURL string `json:"api_url"`
-}
-
-type deviceExchange struct {
- Status string `json:"status"`
- RetryAfter int `json:"retry_after"`
- Credential loginCredential `json:"credential"`
- User struct {
- ID string `json:"id"`
- Email string `json:"email"`
- Name string `json:"name"`
- } `json:"user"`
- Org struct {
- ID string `json:"id"`
- Name string `json:"name"`
- } `json:"org"`
-}
-
-type loginResult struct {
- loginIdentity
- Credential struct {
- ID string `json:"id"`
- KeyPrefix string `json:"key_prefix"`
- Name string `json:"name"`
- } `json:"credential"`
-}
-
-type edgeErrorBody struct {
- Error string `json:"error"`
-}
-
-type cliAuthAPIError struct {
- Code string
- API *client.APIError
-}
-
-func (e *cliAuthAPIError) Error() string {
- return e.API.Error()
-}
-
-func (e *cliAuthAPIError) Unwrap() error {
- return e.API
-}
-
-type cliAuthHTTP struct {
- baseURL string
- client *http.Client
-}
-
-func newCLIAuthHTTP(apiURL string) *cliAuthHTTP {
- base := strings.TrimRight(apiURL, "/")
- base = strings.TrimSuffix(base, "/api")
- return &cliAuthHTTP{
- baseURL: base,
- client: &http.Client{
- Timeout: 30 * time.Second,
- CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
- return http.ErrUseLastResponse
- },
- },
- }
-}
-
-func (c *cliAuthHTTP) do(
- ctx context.Context,
- method string,
- path string,
- apiKey string,
- body any,
- out any,
-) (int, string, error) {
- var bodyReader io.Reader
- if body != nil {
- encoded, err := json.Marshal(body)
- if err != nil {
- return 0, "", err
- }
- bodyReader = bytes.NewReader(encoded)
- }
- req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, bodyReader)
- if err != nil {
- return 0, "", err
- }
- if body != nil || (method == http.MethodPost && path == "/auth/cli/device") {
- req.Header.Set("Content-Type", "application/json")
- }
- if apiKey != "" {
- req.Header.Set("X-API-Key", apiKey)
- }
-
- resp, err := c.client.Do(req)
- if err != nil {
- return 0, "", err
- }
- defer resp.Body.Close()
- raw, err := io.ReadAll(io.LimitReader(resp.Body, maxAuthResponseBytes+1))
- if err != nil {
- return resp.StatusCode, "", err
- }
- if len(raw) > maxAuthResponseBytes {
- return resp.StatusCode, "", errors.New("OpenComputer returned an oversized authentication response")
- }
- if resp.StatusCode >= 400 {
- var edgeErr edgeErrorBody
- if json.Unmarshal(raw, &edgeErr) != nil || edgeErr.Error == "" {
- edgeErr.Error = "unexpected_auth_response"
- }
- return resp.StatusCode, edgeErr.Error, nil
- }
- if out != nil && len(raw) > 0 {
- if err := json.Unmarshal(raw, out); err != nil {
- return resp.StatusCode, "", errors.New("OpenComputer returned an invalid authentication response")
- }
- }
- return resp.StatusCode, "", nil
-}
-
-func (c *cliAuthHTTP) start(ctx context.Context) (deviceAuthorization, error) {
- var receipt deviceAuthorization
- status, code, err := c.do(ctx, http.MethodPost, "/auth/cli/device", "", nil, &receipt)
- if err != nil {
- return receipt, err
- }
- if status != http.StatusOK {
- return receipt, authAPIError(status, code)
- }
- verification, err := url.Parse(receipt.VerificationURIComplete)
- if err != nil || verification.Scheme != "https" || verification.Host == "" {
- return receipt, errors.New("OpenComputer returned an invalid verification URL")
- }
- if receipt.DeviceCode == "" || receipt.UserCode == "" || receipt.ExpiresIn <= 0 || receipt.Interval <= 0 {
- return receipt, errors.New("OpenComputer returned an incomplete authentication response")
- }
- if strings.Contains(receipt.VerificationURI, receipt.DeviceCode) ||
- strings.Contains(receipt.VerificationURIComplete, receipt.DeviceCode) {
- return receipt, errors.New("OpenComputer returned an unsafe verification URL")
- }
- return receipt, nil
-}
-
-func (c *cliAuthHTTP) exchange(
- ctx context.Context,
- deviceCode string,
- credentialName string,
-) (deviceExchange, error) {
- var exchange deviceExchange
- status, code, err := c.do(ctx, http.MethodPost, "/auth/cli/device/exchange", "", map[string]string{
- "device_code": deviceCode,
- "credential_name": credentialName,
- }, &exchange)
- if err != nil {
- return exchange, err
- }
- if status == http.StatusAccepted {
- if exchange.Status != "authorization_pending" {
- return exchange, errors.New("OpenComputer returned an invalid pending response")
- }
- return exchange, nil
- }
- if status != http.StatusOK {
- return exchange, authAPIError(status, code)
- }
- if exchange.Status != "authorized" ||
- exchange.Credential.ID == "" ||
- !validOrgKey(exchange.Credential.Key) ||
- exchange.User.ID == "" ||
- exchange.Org.ID == "" {
- return exchange, errors.New("OpenComputer returned an incomplete login credential")
- }
- return exchange, nil
-}
-
-func validOrgKey(key string) bool {
- if len(key) != 68 || !strings.HasPrefix(key, "osb_") {
- return false
- }
- for _, r := range key[4:] {
- if (r < '0' || r > '9') && (r < 'a' || r > 'f') {
- return false
- }
- }
- return true
-}
-
-func (c *cliAuthHTTP) whoami(ctx context.Context, apiKey string) (loginIdentity, error) {
- var identity loginIdentity
- status, code, err := c.do(ctx, http.MethodGet, "/api/whoami", apiKey, nil, &identity)
- if err != nil {
- return identity, err
- }
- if status != http.StatusOK {
- return identity, authAPIError(status, code)
- }
- identity.APIURL = c.baseURL
- if identity.OrgID == "" {
- return identity, errors.New("OpenComputer returned an incomplete identity response")
- }
- return identity, nil
-}
-
-func (c *cliAuthHTTP) revoke(ctx context.Context, apiKey string) error {
- status, code, err := c.do(ctx, http.MethodDelete, "/auth/cli/credential", apiKey, nil, nil)
- if err != nil {
- return err
- }
- switch status {
- case http.StatusNoContent, http.StatusUnauthorized, http.StatusNotFound:
- return nil
- default:
- return authAPIError(status, code)
- }
-}
-
-func authAPIError(status int, code string) error {
- action := "Retry in a moment; existing configured credentials were not changed."
- switch code {
- case "authorization_expired":
- action = "The confirmation expired; run `oc login` again."
- case "authorization_denied":
- action = "Authorization was denied; run `oc login` again and approve the displayed code."
- case "cli_login_unavailable":
- action = "CLI login is not configured on this OpenComputer API."
- case "invalid_request":
- action = "The CLI and API disagree on the login request; update `oc` and retry."
- case "account_provisioning_unavailable":
- action = "Authorization completed, but the OpenComputer account could not be prepared; run `oc login` again."
- case "credential_creation_failed":
- action = "Authorization completed, but the CLI credential could not be created; run `oc login` again."
- case "rate_limited":
- action = "Too many login attempts were made from this network; wait a minute and retry."
- }
- if code == "" {
- code = "authentication_failed"
- }
- return &cliAuthAPIError{
- Code: code,
- API: &client.APIError{
- StatusCode: status,
- Message: fmt.Sprintf("%s: %s", code, action),
- },
- }
-}
-
-var (
- openAuthBrowser = openBrowser
- authSleep = sleepContext
-)
-
-func openBrowser(rawURL string) error {
- var command string
- var args []string
- switch runtime.GOOS {
- case "darwin":
- command, args = "open", []string{rawURL}
- case "windows":
- command, args = "rundll32", []string{"url.dll,FileProtocolHandler", rawURL}
- default:
- command, args = "xdg-open", []string{rawURL}
- }
- return exec.Command(command, args...).Start()
-}
-
-func sleepContext(ctx context.Context, delay time.Duration) error {
- timer := time.NewTimer(delay)
- defer timer.Stop()
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-timer.C:
- return nil
- }
-}
-
-func credentialName() string {
- hostname, err := os.Hostname()
- if err != nil {
- return "oc CLI"
- }
- hostname = strings.TrimSpace(strings.Map(func(r rune) rune {
- if r < 0x20 || r == 0x7f {
- return -1
- }
- return r
- }, hostname))
- if hostname == "" {
- return "oc CLI"
- }
- name := []rune("oc CLI on " + hostname)
- if len(name) > 100 {
- name = name[:100]
- }
- return string(name)
-}
-
-func printLoginResult(cmd *cobra.Command, result loginResult, already bool) error {
- if jsonOutput {
- return json.NewEncoder(cmd.OutOrStdout()).Encode(result)
- }
- renderLoginResult(
- cmd.OutOrStdout(),
- result,
- already,
- deployStyleFor(cmd.OutOrStdout()),
- )
- return nil
-}
-
-func renderLoginResult(w io.Writer, result loginResult, already bool, style deployOutputStyle) {
- action := "Logged in as"
- if already {
- action = "Already logged in as"
- }
- mark := ansiText("✓", "32", style.color)
- email := ansiText(oneLine(result.Email), "1", style.color)
- fmt.Fprintf(w, "%s %s %s\n", mark, action, email)
- fmt.Fprintf(w, "\n %-11s %s\n", "Workspace", oneLine(result.OrgName))
- fmt.Fprintf(w, " %-11s %s\n", "API", terminalLink(result.APIURL, style))
- if !already {
- fmt.Fprintf(w, "\n %s\n", ansiText("Next", "1", style.color))
- fmt.Fprintf(w, " %s oc agent init\n", ansiText("$", "2", style.color))
- }
-}
-
-func renderLoginInstructions(w io.Writer, receipt deviceAuthorization, style deployOutputStyle) {
- fmt.Fprintln(w, "Open this page to sign in:")
- fmt.Fprintf(w, " %s\n", terminalLink(receipt.VerificationURIComplete, style))
- fmt.Fprintf(
- w,
- "\n %-11s %s\n",
- "Code",
- ansiText(oneLine(receipt.UserCode), "1", style.color),
- )
-}
-
-type loginCanceledError struct {
- cause error
-}
-
-func (e *loginCanceledError) Error() string {
- return "login canceled; no credentials were changed"
-}
-
-func (e *loginCanceledError) Unwrap() error {
- return e.cause
-}
-
-func canceledLoginError(err error) error {
- if errors.Is(err, context.Canceled) {
- return &loginCanceledError{cause: err}
- }
- return err
-}
-
-func identityAsLoginResult(identity loginIdentity, metadata *config.LoginMetadata) loginResult {
- result := loginResult{loginIdentity: identity}
- if metadata != nil {
- result.Credential.ID = metadata.CredentialID
- result.Credential.KeyPrefix = metadata.KeyPrefix
- result.Credential.Name = metadata.Name
- }
- return result
-}
-
-func loginAPIForSavedCredential(fileCfg config.Config, fallback string) string {
- if fileCfg.Login != nil && fileCfg.Login.APIURL != "" {
- return newCLIAuthHTTP(fileCfg.Login.APIURL).baseURL
- }
- if fileCfg.APIURL != "" {
- return newCLIAuthHTTP(fileCfg.APIURL).baseURL
- }
- return newCLIAuthHTTP(fallback).baseURL
-}
-
-func insecureRemoteAPIURL(rawURL string) bool {
- parsed, err := url.Parse(rawURL)
- if err != nil || parsed.Scheme != "http" {
- return false
- }
- host := parsed.Hostname()
- if strings.EqualFold(host, "localhost") {
- return false
- }
- ip := net.ParseIP(host)
- return ip == nil || !ip.IsLoopback()
-}
-
-func runLogin(cmd *cobra.Command, force, noBrowser bool) error {
- source := config.EffectiveCredentialSource(cmd)
- if source == config.CredentialSourceEnvironment || source == config.CredentialSourceFlag {
- return fmt.Errorf("%s currently controls authentication; unset it before running `oc login`", source)
- }
-
- fileCfg := config.LoadFile()
- resolved := config.Load(cmd)
- if resolved.APIURL == "" {
- resolved.APIURL = config.DefaultAPIURL
- }
- authClient := newCLIAuthHTTP(resolved.APIURL)
- loginAPI := authClient.baseURL
- errOut := cmd.ErrOrStderr()
- if insecureRemoteAPIURL(loginAPI) {
- fmt.Fprintf(
- errOut,
- "Warning: %s is not HTTPS; login credentials will be sent over an unencrypted connection.\n",
- oneLine(loginAPI),
- )
- }
-
- var oldManagedKey string
- var oldManagedAPI string
- if fileCfg.APIKey != "" {
- if fileCfg.Login == nil {
- if !force {
- return errors.New("a manually configured API key is already saved; use `oc login --force` to replace it locally")
- }
- } else {
- oldAPI := loginAPIForSavedCredential(fileCfg, loginAPI)
- if oldAPI != loginAPI && !force {
- return fmt.Errorf(
- "saved login belongs to %s, but the current API is %s; unset the API URL override or use `oc login --force` to replace it",
- oldAPI,
- loginAPI,
- )
- }
- if force {
- // Replacement is intentionally not gated on the old host. Keep
- // the exact old credential for best-effort revoke only after
- // the new login is durably saved and verified.
- oldManagedKey = fileCfg.APIKey
- oldManagedAPI = oldAPI
- } else {
- identity, err := newCLIAuthHTTP(oldAPI).whoami(cmd.Context(), fileCfg.APIKey)
- if err == nil {
- return printLoginResult(cmd, identityAsLoginResult(identity, fileCfg.Login), true)
- } else {
- var apiErr *client.APIError
- if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized {
- // The old key is already terminal and needs no revoke.
- } else {
- return fmt.Errorf("checking existing login before replacement: %w", err)
- }
- }
- }
- }
- }
- if fileCfg.APIURL != "" && newCLIAuthHTTP(fileCfg.APIURL).baseURL != loginAPI {
- fmt.Fprintf(
- errOut,
- "Using API %s; successful login will replace the saved API URL %s.\n",
- oneLine(loginAPI),
- oneLine(newCLIAuthHTTP(fileCfg.APIURL).baseURL),
- )
- }
-
- receipt, err := authClient.start(cmd.Context())
- if err != nil {
- if errors.Is(err, context.Canceled) {
- return canceledLoginError(err)
- }
- return fmt.Errorf("starting login: %w", err)
- }
- style := deployStyleFor(errOut)
- renderLoginInstructions(errOut, receipt, style)
- if !noBrowser {
- if err := openAuthBrowser(receipt.VerificationURIComplete); err != nil {
- fmt.Fprintln(errOut, "Could not open a browser automatically. Open the URL above.")
- }
- }
- fmt.Fprintln(errOut, "\nWaiting for confirmation…")
- fmt.Fprintln(errOut)
-
- interval := time.Duration(receipt.Interval) * time.Second
- deadline := time.Now().Add(time.Duration(receipt.ExpiresIn) * time.Second)
- var exchange deviceExchange
- consecutiveTransientFailures := 0
- for {
- if time.Now().Add(interval).After(deadline) {
- return authAPIError(http.StatusGone, "authorization_expired")
- }
- if err := authSleep(cmd.Context(), interval); err != nil {
- return canceledLoginError(err)
- }
- exchange, err = authClient.exchange(cmd.Context(), receipt.DeviceCode, credentialName())
- if err != nil {
- if errors.Is(err, context.Canceled) {
- return canceledLoginError(err)
- }
- var authErr *cliAuthAPIError
- if errors.As(err, &authErr) &&
- authErr.Code == "auth_provider_unavailable" &&
- consecutiveTransientFailures < 2 {
- consecutiveTransientFailures++
- continue
- }
- return fmt.Errorf("confirming login: %w", err)
- }
- consecutiveTransientFailures = 0
- if exchange.Status == "authorized" {
- break
- }
- if exchange.RetryAfter > 0 {
- next := time.Duration(exchange.RetryAfter) * time.Second
- if next > interval {
- interval = next
- }
- }
- }
-
- nextCfg := fileCfg
- nextCfg.APIURL = loginAPI
- nextCfg.APIKey = exchange.Credential.Key
- nextCfg.Login = &config.LoginMetadata{
- CredentialID: exchange.Credential.ID,
- KeyPrefix: exchange.Credential.KeyPrefix,
- Name: exchange.Credential.Name,
- APIURL: loginAPI,
- }
- if err := config.Save(nextCfg); err != nil {
- return fmt.Errorf(
- "login was authorized but the credential could not be saved; remove %q in the dashboard if needed: %w",
- exchange.Credential.Name,
- err,
- )
- }
-
- identity, err := authClient.whoami(cmd.Context(), exchange.Credential.Key)
- if err != nil {
- return fmt.Errorf(
- "login credential was saved but verification failed; inspect it in the dashboard before retrying: %w",
- err,
- )
- }
-
- if oldManagedKey != "" {
- if err := newCLIAuthHTTP(oldManagedAPI).revoke(cmd.Context(), oldManagedKey); err != nil {
- fmt.Fprintf(
- errOut,
- "Warning: replacement login is active, but the previous CLI credential at %s could not be revoked. Remove it in the dashboard if needed.\n",
- oneLine(oldManagedAPI),
- )
- }
- }
-
- result := identityAsLoginResult(identity, nextCfg.Login)
- return printLoginResult(cmd, result, false)
-}
-
-func runWhoami(cmd *cobra.Command) error {
- cfg := config.Load(cmd)
- if cfg.APIKey == "" {
- return errors.New("not logged in; run `oc login` or set OPENCOMPUTER_API_KEY")
- }
- identity, err := newCLIAuthHTTP(cfg.APIURL).whoami(cmd.Context(), cfg.APIKey)
- if err != nil {
- return err
- }
- if jsonOutput {
- return json.NewEncoder(cmd.OutOrStdout()).Encode(identity)
- }
- fmt.Fprintf(cmd.OutOrStdout(), "User %s\n", oneLine(identity.Email))
- fmt.Fprintf(cmd.OutOrStdout(), "Workspace %s\n", oneLine(identity.OrgName))
- fmt.Fprintf(cmd.OutOrStdout(), "Org ID %s\n", oneLine(identity.OrgID))
- fmt.Fprintf(cmd.OutOrStdout(), "API %s\n", oneLine(identity.APIURL))
- return nil
-}
-
-func runLogout(cmd *cobra.Command, localOnly bool) error {
- source := config.EffectiveCredentialSource(cmd)
- if !localOnly &&
- (source == config.CredentialSourceEnvironment || source == config.CredentialSourceFlag) {
- return fmt.Errorf("%s still controls authentication; unset it before logging out", source)
- }
- fileCfg := config.LoadFile()
- if fileCfg.APIKey == "" || fileCfg.Login == nil {
- return errors.New("there is no CLI-managed login to revoke")
- }
-
- if !localOnly {
- apiURL := fileCfg.Login.APIURL
- if apiURL == "" {
- apiURL = fileCfg.APIURL
- }
- if apiURL == "" {
- apiURL = config.DefaultAPIURL
- }
- if err := newCLIAuthHTTP(apiURL).revoke(cmd.Context(), fileCfg.APIKey); err != nil {
- return fmt.Errorf("remote logout was not confirmed; local login was retained (retry or use `oc logout --local`): %w", err)
- }
- }
-
- fileCfg.APIKey = ""
- fileCfg.Login = nil
- if err := config.Save(fileCfg); err != nil {
- return fmt.Errorf("clearing local login: %w", err)
- }
- if jsonOutput {
- return json.NewEncoder(cmd.OutOrStdout()).Encode(map[string]string{"status": "logged_out"})
- }
- if localOnly {
- fmt.Fprintln(cmd.OutOrStdout(), "Local login cleared. The remote credential was not revoked.")
- return nil
- }
- fmt.Fprintln(cmd.OutOrStdout(), "Logged out.")
- return nil
-}
-
-var loginCmd = &cobra.Command{
- Use: "login",
- Short: "Sign in to OpenComputer",
- Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, _ []string) error {
- force, _ := cmd.Flags().GetBool("force")
- noBrowser, _ := cmd.Flags().GetBool("no-browser")
- return runLogin(cmd, force, noBrowser)
- },
-}
-
-var whoamiCmd = &cobra.Command{
- Use: "whoami",
- Short: "Show the current OpenComputer identity",
- Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, _ []string) error {
- return runWhoami(cmd)
- },
-}
-
-var logoutCmd = &cobra.Command{
- Use: "logout",
- Short: "Revoke the CLI login and clear it locally",
- Args: cobra.NoArgs,
- RunE: func(cmd *cobra.Command, _ []string) error {
- localOnly, _ := cmd.Flags().GetBool("local")
- return runLogout(cmd, localOnly)
- },
-}
-
-func init() {
- loginCmd.Flags().Bool("no-browser", false, "Print the confirmation URL without opening a browser")
- loginCmd.Flags().Bool("force", false, "Replace an existing saved credential")
- logoutCmd.Flags().Bool("local", false, "Clear local login state without remote revocation")
-}
diff --git a/cmd/oc/internal/commands/auth_test.go b/cmd/oc/internal/commands/auth_test.go
deleted file mode 100644
index 96ff5bec..00000000
--- a/cmd/oc/internal/commands/auth_test.go
+++ /dev/null
@@ -1,948 +0,0 @@
-package commands
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "sync"
- "testing"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/config"
- "github.com/spf13/cobra"
-)
-
-const (
- testDeviceCode = "private-device-code"
- testUserCode = "ABCD-EFGH"
- testKey = "osb_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
- oldTestKey = "osb_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
-)
-
-func authTestCommand(t *testing.T, apiURL string) (*cobra.Command, *bytes.Buffer, *bytes.Buffer) {
- t.Helper()
- home := t.TempDir()
- t.Setenv("HOME", home)
- if runtime.GOOS == "windows" {
- t.Setenv("USERPROFILE", home)
- }
- t.Setenv("OPENCOMPUTER_API_URL", apiURL)
- t.Setenv("OPENCOMPUTER_API_KEY", "")
- t.Setenv("SESSIONS_API_URL", "")
-
- cmd := &cobra.Command{}
- cmd.SetContext(context.Background())
- var stdout, stderr bytes.Buffer
- cmd.SetOut(&stdout)
- cmd.SetErr(&stderr)
-
- oldSleep, oldOpen, oldJSON := authSleep, openAuthBrowser, jsonOutput
- authSleep = func(context.Context, time.Duration) error { return nil }
- openAuthBrowser = func(string) error { return nil }
- jsonOutput = false
- t.Cleanup(func() {
- authSleep = oldSleep
- openAuthBrowser = oldOpen
- jsonOutput = oldJSON
- })
- return cmd, &stdout, &stderr
-}
-
-func writeJSONResponse(w http.ResponseWriter, status int, body any) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(status)
- _ = json.NewEncoder(w).Encode(body)
-}
-
-func deviceReceipt() map[string]any {
- return map[string]any{
- "device_code": testDeviceCode,
- "user_code": testUserCode,
- "verification_uri": "https://auth.example.test/device",
- "verification_uri_complete": "https://auth.example.test/device?user_code=" + testUserCode,
- "expires_in": 300,
- "interval": 1,
- }
-}
-
-func authorizedExchange() map[string]any {
- return map[string]any{
- "status": "authorized",
- "credential": map[string]any{
- "id": "credential-1",
- "key": testKey,
- "key_prefix": "osb_aaaa",
- "name": "oc CLI on test",
- },
- "user": map[string]any{
- "id": "user-1",
- "email": "[email protected]",
- "name": "Igor",
- },
- "org": map[string]any{
- "id": "org-1",
- "name": "Igor's workspace",
- },
- }
-}
-
-func whoamiResponse() map[string]any {
- return map[string]any{
- "user_id": "user-1",
- "email": "[email protected]",
- "org_id": "org-1",
- "org_name": "Igor's workspace",
- }
-}
-
-func TestLoginHumanOutputMatchesDeployPresentation(t *testing.T) {
- result := loginResult{
- loginIdentity: loginIdentity{
- Email: "[email protected]",
- OrgName: "Igor's workspace",
- APIURL: "https://app.opencomputer.dev",
- },
- }
- var out bytes.Buffer
- renderLoginResult(&out, result, false, deployOutputStyle{})
- want := "✓ Logged in as [email protected]\n\n" +
- " Workspace Igor's workspace\n" +
- " API https://app.opencomputer.dev\n\n" +
- " Next\n" +
- " $ oc agent init\n"
- if out.String() != want {
- t.Fatalf("login output:\n%q\nwant:\n%q", out.String(), want)
- }
-
- out.Reset()
- renderLoginResult(&out, result, true, deployOutputStyle{})
- if strings.Contains(out.String(), "Next") ||
- !strings.HasPrefix(out.String(), "✓ Already logged in as [email protected]\n") {
- t.Fatalf("existing-login output:\n%q", out.String())
- }
-
- out.Reset()
- renderLoginResult(&out, result, false, deployOutputStyle{color: true, hyperlinks: true})
- for _, want := range []string{
- "\x1b[32m✓\x1b[0m",
- "\x1b[[email protected]\x1b[0m",
- "\x1b]8;;https://app.opencomputer.dev\x1b\\",
- "\x1b[1mNext\x1b[0m",
- } {
- if !strings.Contains(out.String(), want) {
- t.Fatalf("styled login output missing %q:\n%q", want, out.String())
- }
- }
-}
-
-func TestLoginInstructionsAreCompactAndCopyable(t *testing.T) {
- receipt := deviceAuthorization{
- UserCode: testUserCode,
- VerificationURIComplete: "https://auth.example.test/device?user_code=" + testUserCode,
- }
- var out bytes.Buffer
- renderLoginInstructions(&out, receipt, deployOutputStyle{})
- want := "Open this page to sign in:\n" +
- " https://auth.example.test/device?user_code=ABCD-EFGH\n\n" +
- " Code ABCD-EFGH\n"
- if out.String() != want {
- t.Fatalf("login instructions:\n%q\nwant:\n%q", out.String(), want)
- }
-}
-
-func TestLoginPollsSavesVerifiesAndNeverPrintsCredential(t *testing.T) {
- var mu sync.Mutex
- var exchanges int
- var opened string
- var delays []time.Duration
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/auth/cli/device":
- if r.Method != http.MethodPost {
- t.Errorf("start method = %s", r.Method)
- }
- if r.Header.Get("X-API-Key") != "" {
- t.Error("start unexpectedly carried an API key")
- }
- writeJSONResponse(w, 200, deviceReceipt())
- case "/auth/cli/device/exchange":
- var body map[string]string
- if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
- t.Errorf("exchange body: %v", err)
- }
- if body["device_code"] != testDeviceCode {
- t.Errorf("device code = %q", body["device_code"])
- }
- mu.Lock()
- exchanges++
- attempt := exchanges
- mu.Unlock()
- if attempt == 1 {
- writeJSONResponse(w, 202, map[string]any{
- "status": "authorization_pending",
- "retry_after": 2,
- })
- return
- }
- writeJSONResponse(w, 200, authorizedExchange())
- case "/api/whoami":
- if r.Header.Get("X-API-Key") != testKey {
- t.Errorf("whoami key = %q", r.Header.Get("X-API-Key"))
- }
- writeJSONResponse(w, 200, whoamiResponse())
- default:
- http.NotFound(w, r)
- }
- }))
- defer server.Close()
-
- cmd, stdout, stderr := authTestCommand(t, server.URL)
- authSleep = func(_ context.Context, delay time.Duration) error {
- delays = append(delays, delay)
- return nil
- }
- openAuthBrowser = func(rawURL string) error {
- opened = rawURL
- return nil
- }
- if err := runLogin(cmd, false, false); err != nil {
- t.Fatalf("runLogin: %v", err)
- }
-
- if exchanges != 2 {
- t.Fatalf("exchange attempts = %d, want 2", exchanges)
- }
- if fmt.Sprint(delays) != "[1s 2s]" {
- t.Fatalf("poll delays = %v, want [1s 2s]", delays)
- }
- if opened != "https://auth.example.test/device?user_code="+testUserCode {
- t.Fatalf("opened URL = %q", opened)
- }
- if !strings.Contains(stderr.String(), testUserCode) ||
- !strings.Contains(stderr.String(), "https://auth.example.test/device") {
- t.Fatalf("missing confirmation instructions:\n%s", stderr.String())
- }
- combined := stdout.String() + stderr.String()
- if strings.Contains(combined, testKey) || strings.Contains(combined, testDeviceCode) {
- t.Fatalf("secret leaked to output: %q", combined)
- }
- if !strings.Contains(stdout.String(), "Logged in as [email protected]") ||
- !strings.Contains(stdout.String(), "Igor's workspace") ||
- !strings.Contains(stdout.String(), "$ oc agent init") {
- t.Fatalf("unexpected success output:\n%s", stdout.String())
- }
-
- saved := config.LoadFile()
- if saved.APIKey != testKey || saved.Login == nil || saved.Login.CredentialID != "credential-1" {
- t.Fatalf("saved config = %#v", saved)
- }
- if runtime.GOOS != "windows" {
- info, err := os.Stat(config.ConfigPath())
- if err != nil {
- t.Fatal(err)
- }
- if info.Mode().Perm() != 0o600 {
- t.Fatalf("config mode = %o", info.Mode().Perm())
- }
- }
-}
-
-func TestLoginBrowserFailurePointsBackToPrintedURLBeforeWaiting(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/auth/cli/device":
- writeJSONResponse(w, 200, deviceReceipt())
- case "/auth/cli/device/exchange":
- writeJSONResponse(w, 200, authorizedExchange())
- case "/api/whoami":
- writeJSONResponse(w, 200, whoamiResponse())
- default:
- http.NotFound(w, r)
- }
- }))
- defer server.Close()
- cmd, _, stderr := authTestCommand(t, server.URL)
- openAuthBrowser = func(string) error {
- return errors.New("no browser opener at /private/path")
- }
- if err := runLogin(cmd, false, false); err != nil {
- t.Fatalf("runLogin: %v", err)
- }
- got := stderr.String()
- failure := "Could not open a browser automatically. Open the URL above."
- if !strings.Contains(got, failure) ||
- strings.Contains(got, "/private/path") ||
- strings.Index(got, failure) > strings.Index(got, "Waiting for confirmation…") {
- t.Fatalf("browser-failure output:\n%s", got)
- }
-}
-
-func TestLoginNoBrowserAndJSONContainNoKeyOrDeviceCode(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/auth/cli/device":
- writeJSONResponse(w, 200, deviceReceipt())
- case "/auth/cli/device/exchange":
- writeJSONResponse(w, 200, authorizedExchange())
- case "/api/whoami":
- writeJSONResponse(w, 200, whoamiResponse())
- default:
- http.NotFound(w, r)
- }
- }))
- defer server.Close()
- cmd, stdout, stderr := authTestCommand(t, server.URL)
- jsonOutput = true
- openAuthBrowser = func(string) error {
- t.Fatal("browser opener called under --no-browser")
- return nil
- }
- if err := runLogin(cmd, false, true); err != nil {
- t.Fatalf("runLogin: %v", err)
- }
- var got map[string]any
- if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
- t.Fatalf("JSON output: %v\n%s", err, stdout.String())
- }
- combined := stdout.String() + stderr.String()
- if strings.Contains(combined, testKey) || strings.Contains(combined, testDeviceCode) {
- t.Fatalf("secret leaked to output: %q", combined)
- }
- if got["email"] != "[email protected]" || got["org_id"] != "org-1" {
- t.Fatalf("login JSON = %#v", got)
- }
-}
-
-func TestLoginRejectsVerificationURLContainingDeviceCodeBeforePrinting(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- receipt := deviceReceipt()
- receipt["verification_uri_complete"] = "https://auth.example.test/device?device_code=" + testDeviceCode
- writeJSONResponse(w, 200, receipt)
- }))
- defer server.Close()
- cmd, stdout, stderr := authTestCommand(t, server.URL)
- err := runLogin(cmd, false, true)
- if err == nil || !strings.Contains(err.Error(), "unsafe verification URL") {
- t.Fatalf("error = %v", err)
- }
- if strings.Contains(stdout.String()+stderr.String(), testDeviceCode) {
- t.Fatalf("device code leaked to output: %q", stdout.String()+stderr.String())
- }
-}
-
-func TestLoginRefusesEnvironmentCredentialWithoutCallingAPI(t *testing.T) {
- var calls int
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- calls++
- http.Error(w, "unexpected", 500)
- }))
- defer server.Close()
- cmd, _, _ := authTestCommand(t, server.URL)
- t.Setenv("OPENCOMPUTER_API_KEY", "environment-key")
- err := runLogin(cmd, true, true)
- if err == nil || !strings.Contains(err.Error(), "OPENCOMPUTER_API_KEY") {
- t.Fatalf("error = %v", err)
- }
- if calls != 0 {
- t.Fatalf("API called %d times", calls)
- }
-}
-
-func TestLoginRefusesFlagCredentialWithoutCallingAPI(t *testing.T) {
- var calls int
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- calls++
- http.Error(w, "unexpected", 500)
- }))
- defer server.Close()
- cmd, _, _ := authTestCommand(t, server.URL)
- cmd.Flags().String("api-key", "", "")
- if err := cmd.Flags().Set("api-key", "flag-key"); err != nil {
- t.Fatal(err)
- }
- err := runLogin(cmd, true, true)
- if err == nil || !strings.Contains(err.Error(), "--api-key") {
- t.Fatalf("error = %v", err)
- }
- if calls != 0 {
- t.Fatalf("API called %d times", calls)
- }
-}
-
-func TestLoginForceStoresAndVerifiesReplacementBeforeRevokingOld(t *testing.T) {
- var sequence []string
- var mu sync.Mutex
- record := func(s string) {
- mu.Lock()
- defer mu.Unlock()
- sequence = append(sequence, s)
- }
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/api/whoami":
- key := r.Header.Get("X-API-Key")
- if key == oldTestKey {
- record("old-whoami")
- } else if key == testKey {
- saved := config.LoadFile()
- if saved.APIKey != testKey {
- t.Errorf("new key not saved before verification")
- }
- record("new-whoami")
- }
- writeJSONResponse(w, 200, whoamiResponse())
- case "/auth/cli/device":
- record("start")
- writeJSONResponse(w, 200, deviceReceipt())
- case "/auth/cli/device/exchange":
- record("exchange")
- writeJSONResponse(w, 200, authorizedExchange())
- case "/auth/cli/credential":
- if r.Header.Get("X-API-Key") != oldTestKey {
- t.Errorf("revoked key = %q", r.Header.Get("X-API-Key"))
- }
- if config.LoadFile().APIKey != testKey {
- t.Errorf("replacement not saved before old-key revoke")
- }
- record("old-revoke")
- w.WriteHeader(http.StatusNoContent)
- default:
- http.NotFound(w, r)
- }
- }))
- defer server.Close()
- cmd, _, _ := authTestCommand(t, server.URL)
- if err := config.Save(config.Config{
- APIURL: server.URL,
- APIKey: oldTestKey,
- Login: &config.LoginMetadata{
- CredentialID: "old-id",
- KeyPrefix: "osb_bbbb",
- Name: "oc CLI on old",
- APIURL: server.URL,
- },
- }); err != nil {
- t.Fatal(err)
- }
- if err := runLogin(cmd, true, true); err != nil {
- t.Fatalf("runLogin --force: %v", err)
- }
- got := strings.Join(sequence, ",")
- want := "start,exchange,new-whoami,old-revoke"
- if got != want {
- t.Fatalf("sequence = %q, want %q", got, want)
- }
-}
-
-func TestLoginForceContinuesWhenPreviousAPIIsUnreachable(t *testing.T) {
- oldServer := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
- oldURL := oldServer.URL
- oldServer.Close()
-
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/auth/cli/device":
- writeJSONResponse(w, 200, deviceReceipt())
- case "/auth/cli/device/exchange":
- writeJSONResponse(w, 200, authorizedExchange())
- case "/api/whoami":
- if r.Header.Get("X-API-Key") != testKey {
- t.Errorf("unexpected key at replacement API")
- }
- writeJSONResponse(w, 200, whoamiResponse())
- default:
- http.NotFound(w, r)
- }
- }))
- defer server.Close()
- cmd, _, stderr := authTestCommand(t, server.URL)
- if err := config.Save(config.Config{
- APIURL: oldURL,
- APIKey: oldTestKey,
- Login: &config.LoginMetadata{
- CredentialID: "old-id",
- KeyPrefix: "osb_bbbb",
- Name: "oc CLI on old",
- APIURL: oldURL,
- },
- }); err != nil {
- t.Fatal(err)
- }
-
- if err := runLogin(cmd, true, true); err != nil {
- t.Fatalf("runLogin --force: %v", err)
- }
- if !strings.Contains(stderr.String(), "replacement login is active") ||
- !strings.Contains(stderr.String(), "could not be revoked") {
- t.Fatalf("stderr = %q", stderr.String())
- }
- got := config.LoadFile()
- if got.APIKey != testKey || got.Login == nil || got.Login.APIURL != server.URL {
- t.Fatalf("replacement config = %#v", got)
- }
-}
-
-func TestLoginRefusesSavedLoginAtDifferentEffectiveAPIWithoutForce(t *testing.T) {
- oldServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- t.Errorf("old API should not be called")
- http.Error(w, "unexpected", 500)
- }))
- defer oldServer.Close()
- newServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- t.Errorf("new API should not be called")
- http.Error(w, "unexpected", 500)
- }))
- defer newServer.Close()
- cmd, _, _ := authTestCommand(t, newServer.URL)
- if err := config.Save(config.Config{
- APIURL: oldServer.URL,
- APIKey: oldTestKey,
- Login: &config.LoginMetadata{
- CredentialID: "old-id",
- KeyPrefix: "osb_bbbb",
- Name: "oc CLI on old",
- APIURL: oldServer.URL,
- },
- }); err != nil {
- t.Fatal(err)
- }
-
- err := runLogin(cmd, false, true)
- if err == nil ||
- !strings.Contains(err.Error(), "saved login belongs to "+oldServer.URL) ||
- !strings.Contains(err.Error(), "current API is "+newServer.URL) {
- t.Fatalf("error = %v", err)
- }
-}
-
-func TestLoginMakesEffectiveAPIURLPersistenceExplicit(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/auth/cli/device":
- writeJSONResponse(w, 200, deviceReceipt())
- case "/auth/cli/device/exchange":
- writeJSONResponse(w, 200, authorizedExchange())
- case "/api/whoami":
- writeJSONResponse(w, 200, whoamiResponse())
- default:
- http.NotFound(w, r)
- }
- }))
- defer server.Close()
- cmd, _, stderr := authTestCommand(t, server.URL)
- if err := config.Save(config.Config{APIURL: "https://old.example.test"}); err != nil {
- t.Fatal(err)
- }
-
- if err := runLogin(cmd, false, true); err != nil {
- t.Fatalf("runLogin: %v", err)
- }
- if !strings.Contains(stderr.String(), "successful login will replace the saved API URL https://old.example.test") {
- t.Fatalf("stderr = %q", stderr.String())
- }
- if got := config.LoadFile(); got.APIURL != server.URL || got.Login == nil || got.Login.APIURL != server.URL {
- t.Fatalf("saved config = %#v", got)
- }
-}
-
-func TestLoginWithValidManagedCredentialExitsWithoutNewAuthorization(t *testing.T) {
- var starts int
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/api/whoami":
- writeJSONResponse(w, 200, whoamiResponse())
- case "/auth/cli/device":
- starts++
- http.Error(w, "unexpected", 500)
- default:
- http.NotFound(w, r)
- }
- }))
- defer server.Close()
- cmd, stdout, _ := authTestCommand(t, server.URL)
- if err := config.Save(config.Config{
- APIURL: server.URL,
- APIKey: testKey,
- Login: &config.LoginMetadata{
- CredentialID: "credential-1",
- KeyPrefix: "osb_aaaa",
- Name: "oc CLI on test",
- APIURL: server.URL,
- },
- }); err != nil {
- t.Fatal(err)
- }
- if err := runLogin(cmd, false, false); err != nil {
- t.Fatalf("runLogin: %v", err)
- }
- if starts != 0 {
- t.Fatalf("started %d new authorizations", starts)
- }
- if !strings.Contains(stdout.String(), "Already logged in as [email protected]") {
- t.Fatalf("stdout = %q", stdout.String())
- }
-}
-
-func TestLoginForceNeverRevokesManualFileKey(t *testing.T) {
- var revokes int
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/auth/cli/device":
- writeJSONResponse(w, 200, deviceReceipt())
- case "/auth/cli/device/exchange":
- writeJSONResponse(w, 200, authorizedExchange())
- case "/api/whoami":
- writeJSONResponse(w, 200, whoamiResponse())
- case "/auth/cli/credential":
- revokes++
- w.WriteHeader(http.StatusNoContent)
- default:
- http.NotFound(w, r)
- }
- }))
- defer server.Close()
- cmd, _, _ := authTestCommand(t, server.URL)
- if err := config.Save(config.Config{APIURL: server.URL, APIKey: oldTestKey}); err != nil {
- t.Fatal(err)
- }
- if err := runLogin(cmd, true, true); err != nil {
- t.Fatalf("runLogin --force: %v", err)
- }
- if revokes != 0 {
- t.Fatalf("manual key was remotely revoked %d time(s)", revokes)
- }
-}
-
-func TestLogoutAmbiguousFailureRetainsLocalCredential(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- writeJSONResponse(w, 503, map[string]string{"error": "credential_revocation_unavailable"})
- }))
- defer server.Close()
- cmd, _, _ := authTestCommand(t, server.URL)
- if err := config.Save(config.Config{
- APIURL: server.URL,
- APIKey: testKey,
- Login: &config.LoginMetadata{
- CredentialID: "credential-1",
- KeyPrefix: "osb_aaaa",
- Name: "oc CLI on test",
- APIURL: server.URL,
- },
- }); err != nil {
- t.Fatal(err)
- }
- err := runLogout(cmd, false)
- if err == nil || !strings.Contains(err.Error(), "local login was retained") {
- t.Fatalf("error = %v", err)
- }
- if got := config.LoadFile(); got.APIKey != testKey || got.Login == nil {
- t.Fatalf("credential was cleared after ambiguous revoke: %#v", got)
- }
-}
-
-func TestLogoutRevokesAndClearsManagedCredential(t *testing.T) {
- var revoked string
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- revoked = r.Header.Get("X-API-Key")
- w.WriteHeader(http.StatusNoContent)
- }))
- defer server.Close()
- cmd, stdout, _ := authTestCommand(t, server.URL)
- if err := config.Save(config.Config{
- APIURL: server.URL,
- APIKey: testKey,
- Login: &config.LoginMetadata{
- CredentialID: "credential-1",
- KeyPrefix: "osb_aaaa",
- Name: "oc CLI on test",
- APIURL: server.URL,
- },
- }); err != nil {
- t.Fatal(err)
- }
- if err := runLogout(cmd, false); err != nil {
- t.Fatalf("runLogout: %v", err)
- }
- if revoked != testKey {
- t.Fatalf("revoked key = %q", revoked)
- }
- if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {
- t.Fatalf("credential remains after logout: %#v", got)
- }
- if strings.TrimSpace(stdout.String()) != "Logged out." {
- t.Fatalf("stdout = %q", stdout.String())
- }
-}
-
-func TestLogoutLocalDoesNotCallRemote(t *testing.T) {
- var calls int
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- calls++
- http.Error(w, "unexpected", 500)
- }))
- defer server.Close()
- cmd, stdout, _ := authTestCommand(t, server.URL)
- if err := config.Save(config.Config{
- APIURL: server.URL,
- APIKey: testKey,
- Login: &config.LoginMetadata{
- CredentialID: "credential-1",
- KeyPrefix: "osb_aaaa",
- Name: "oc CLI on test",
- APIURL: server.URL,
- },
- }); err != nil {
- t.Fatal(err)
- }
- if err := runLogout(cmd, true); err != nil {
- t.Fatalf("runLogout --local: %v", err)
- }
- if calls != 0 {
- t.Fatalf("remote called %d times", calls)
- }
- if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {
- t.Fatalf("local login remains: %#v", got)
- }
- if strings.TrimSpace(stdout.String()) != "Local login cleared. The remote credential was not revoked." {
- t.Fatalf("stdout = %q", stdout.String())
- }
-}
-
-func TestLogoutLocalIgnoresEffectiveCredentialOverride(t *testing.T) {
- cmd, _, _ := authTestCommand(t, "https://unused.example.test")
- if err := config.Save(config.Config{
- APIURL: "https://saved.example.test",
- APIKey: testKey,
- Login: &config.LoginMetadata{
- CredentialID: "credential-1",
- KeyPrefix: "osb_aaaa",
- Name: "oc CLI on test",
- APIURL: "https://saved.example.test",
- },
- }); err != nil {
- t.Fatal(err)
- }
- t.Setenv("OPENCOMPUTER_API_KEY", "environment-key")
-
- if err := runLogout(cmd, true); err != nil {
- t.Fatalf("runLogout --local: %v", err)
- }
- if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {
- t.Fatalf("local login remains: %#v", got)
- }
-}
-
-func TestLoginCancellationDoesNotSaveCredential(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/auth/cli/device" {
- t.Fatalf("unexpected path after cancellation: %s", r.URL.Path)
- }
- writeJSONResponse(w, 200, deviceReceipt())
- }))
- defer server.Close()
- cmd, _, _ := authTestCommand(t, server.URL)
- authSleep = func(context.Context, time.Duration) error { return context.Canceled }
- err := runLogin(cmd, false, true)
- if !errors.Is(err, context.Canceled) {
- t.Fatalf("error = %v, want context.Canceled", err)
- }
- if err.Error() != "login canceled; no credentials were changed" {
- t.Fatalf("cancellation error = %v", err)
- }
- if _, err := os.Stat(filepath.Join(os.Getenv("HOME"), ".oc", "config.json")); !os.IsNotExist(err) {
- t.Fatalf("config unexpectedly created: %v", err)
- }
-}
-
-func TestLoginReportsDeniedAndExpiredWithoutSaving(t *testing.T) {
- for _, tc := range []struct {
- name string
- status int
- code string
- wantAction string
- }{
- {name: "denied", status: http.StatusForbidden, code: "authorization_denied", wantAction: "approve the displayed code"},
- {name: "expired", status: http.StatusGone, code: "authorization_expired", wantAction: "run `oc login` again"},
- } {
- t.Run(tc.name, func(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/auth/cli/device":
- writeJSONResponse(w, 200, deviceReceipt())
- case "/auth/cli/device/exchange":
- writeJSONResponse(w, tc.status, map[string]string{"error": tc.code})
- default:
- http.NotFound(w, r)
- }
- }))
- defer server.Close()
- cmd, _, _ := authTestCommand(t, server.URL)
- err := runLogin(cmd, false, true)
- if err == nil ||
- !strings.Contains(err.Error(), tc.code) ||
- !strings.Contains(err.Error(), tc.wantAction) {
- t.Fatalf("error = %v", err)
- }
- if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {
- t.Fatalf("terminal authorization mutated config: %#v", got)
- }
- })
- }
-}
-
-func TestLoginRetriesTransientExchangeTwiceThenLeavesConfigUntouched(t *testing.T) {
- var exchanges int
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/auth/cli/device":
- writeJSONResponse(w, 200, deviceReceipt())
- case "/auth/cli/device/exchange":
- exchanges++
- writeJSONResponse(w, 503, map[string]string{"error": "auth_provider_unavailable"})
- default:
- http.NotFound(w, r)
- }
- }))
- defer server.Close()
- cmd, _, _ := authTestCommand(t, server.URL)
- err := runLogin(cmd, false, true)
- if err == nil || !strings.Contains(err.Error(), "auth_provider_unavailable") {
- t.Fatalf("error = %v", err)
- }
- if exchanges != 3 {
- t.Fatalf("exchange attempts = %d, want 3", exchanges)
- }
- if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {
- t.Fatalf("transient failure mutated config: %#v", got)
- }
-}
-
-func TestLoginDoesNotRetryPostAuthorizationCredentialFailure(t *testing.T) {
- var exchanges int
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/auth/cli/device":
- writeJSONResponse(w, 200, deviceReceipt())
- case "/auth/cli/device/exchange":
- exchanges++
- writeJSONResponse(w, 503, map[string]string{"error": "credential_creation_failed"})
- default:
- http.NotFound(w, r)
- }
- }))
- defer server.Close()
- cmd, _, _ := authTestCommand(t, server.URL)
- err := runLogin(cmd, false, true)
- if err == nil || !strings.Contains(err.Error(), "run `oc login` again") {
- t.Fatalf("error = %v", err)
- }
- if exchanges != 1 {
- t.Fatalf("exchange attempts = %d, want 1 for a consumed device grant", exchanges)
- }
- if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {
- t.Fatalf("credential failure mutated config: %#v", got)
- }
-}
-
-func TestWhoamiJSONIsStable(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Header.Get("X-API-Key") != testKey {
- t.Errorf("key = %q", r.Header.Get("X-API-Key"))
- }
- writeJSONResponse(w, 200, whoamiResponse())
- }))
- defer server.Close()
- cmd, stdout, _ := authTestCommand(t, server.URL)
- t.Setenv("OPENCOMPUTER_API_KEY", testKey)
- jsonOutput = true
- if err := runWhoami(cmd); err != nil {
- t.Fatalf("runWhoami: %v", err)
- }
- var got map[string]any
- if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
- t.Fatal(err)
- }
- want := fmt.Sprintf(
- `{"api_url":%q,"email":"[email protected]","org_id":"org-1","org_name":"Igor's workspace","user_id":"user-1"}`,
- server.URL,
- )
- encoded, _ := json.Marshal(got)
- var wantMap map[string]any
- _ = json.Unmarshal([]byte(want), &wantMap)
- wantEncoded, _ := json.Marshal(wantMap)
- if string(encoded) != string(wantEncoded) {
- t.Fatalf("whoami JSON = %s, want %s", encoded, wantEncoded)
- }
-}
-
-func TestAuthClientNeverFollowsRedirectsWithCredentials(t *testing.T) {
- var destinationCalls int
- destination := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- destinationCalls++
- if r.Header.Get("X-API-Key") != "" {
- t.Errorf("redirect leaked key %q", r.Header.Get("X-API-Key"))
- }
- writeJSONResponse(w, 200, whoamiResponse())
- }))
- defer destination.Close()
- redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- http.Redirect(w, r, destination.URL+r.URL.Path, http.StatusFound)
- }))
- defer redirector.Close()
-
- _, err := newCLIAuthHTTP(redirector.URL).whoami(context.Background(), testKey)
- if err == nil {
- t.Fatal("redirecting auth endpoint unexpectedly succeeded")
- }
- if destinationCalls != 0 {
- t.Fatalf("redirect destination called %d times", destinationCalls)
- }
-}
-
-func TestInsecureRemoteAPIURLWarningPolicy(t *testing.T) {
- for _, tc := range []struct {
- url string
- want bool
- }{
- {url: "https://api.example.test", want: false},
- {url: "http://localhost:8787", want: false},
- {url: "http://127.0.0.1:8787", want: false},
- {url: "http://[::1]:8787", want: false},
- {url: "http://api.example.test", want: true},
- } {
- if got := insecureRemoteAPIURL(tc.url); got != tc.want {
- t.Errorf("insecureRemoteAPIURL(%q) = %v, want %v", tc.url, got, tc.want)
- }
- }
-}
-
-func TestConfigSetAPIKeyClearsLoginManagementMetadata(t *testing.T) {
- cmd, _, _ := authTestCommand(t, "https://example.test")
- if err := config.Save(config.Config{
- APIURL: "https://example.test",
- APIKey: oldTestKey,
- Login: &config.LoginMetadata{
- CredentialID: "old-id",
- KeyPrefix: "osb_bbbb",
- Name: "oc CLI on old",
- APIURL: "https://example.test",
- },
- }); err != nil {
- t.Fatal(err)
- }
- if err := configSetCmd.RunE(cmd, []string{"api-key", testKey}); err != nil {
- t.Fatalf("config set api-key: %v", err)
- }
- got := config.LoadFile()
- if got.APIKey != testKey || got.Login != nil {
- t.Fatalf("config set left login-managed state: %#v", got)
- }
-}
diff --git a/cmd/oc/internal/commands/checkpoint.go b/cmd/oc/internal/commands/checkpoint.go
deleted file mode 100644
index 9119afc7..00000000
--- a/cmd/oc/internal/commands/checkpoint.go
+++ /dev/null
@@ -1,230 +0,0 @@
-package commands
-
-import (
- "fmt"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/pkg/types"
- "github.com/spf13/cobra"
-)
-
-// CheckpointInfo matches the API response for checkpoints.
-type CheckpointInfo struct {
- ID string `json:"id"`
- SandboxID string `json:"sandboxId"`
- OrgID string `json:"orgId"`
- Name string `json:"name"`
- Status string `json:"status"`
- RootfsS3Key string `json:"rootfsS3Key,omitempty"`
- WorkspaceS3Key string `json:"workspaceS3Key,omitempty"`
- SizeBytes int64 `json:"sizeBytes"`
- IsPublic bool `json:"isPublic"`
- CreatedAt time.Time `json:"createdAt"`
-}
-
-var checkpointCmd = &cobra.Command{
- Use: "checkpoint",
- Aliases: []string{"cp"},
- Short: "Manage sandbox checkpoints",
-}
-
-var checkpointCreateCmd = &cobra.Command{
- Use: "create <sandbox-id>",
- Short: "Create a checkpoint of a running sandbox",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- name, _ := cmd.Flags().GetString("name")
- kind, _ := cmd.Flags().GetString("kind")
- promoteToFull, _ := cmd.Flags().GetBool("promote-to-full")
- retentionPolicy, _ := cmd.Flags().GetString("retention-policy")
- retentionMaxCount, _ := cmd.Flags().GetInt("retention-max-count")
-
- req := map[string]any{"name": name}
- if kind != "" && kind != "full" {
- if kind != "disk_only" {
- return fmt.Errorf("unsupported checkpoint kind %q; expected full or disk_only", kind)
- }
- req["kind"] = kind
- }
- if promoteToFull {
- if kind != "disk_only" {
- return fmt.Errorf("--promote-to-full requires --kind disk_only")
- }
- req["promoteToFull"] = true
- }
- if retentionPolicy != "" && retentionPolicy != "none" {
- if retentionPolicy != "delete_oldest" {
- return fmt.Errorf("unsupported retention policy %q; expected none or delete_oldest", retentionPolicy)
- }
- policy := map[string]any{"mode": retentionPolicy}
- if retentionMaxCount > 0 {
- policy["maxCount"] = retentionMaxCount
- }
- req["retentionPolicy"] = policy
- }
- var cp CheckpointInfo
- if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/checkpoints", args[0]), req, &cp); err != nil {
- return err
- }
-
- printer.Print(cp, func() {
- fmt.Printf("Checkpoint created: %s (status: %s)\n", cp.ID, cp.Status)
- fmt.Printf("Name: %s\n", cp.Name)
- })
- return nil
- },
-}
-
-var checkpointListCmd = &cobra.Command{
- Use: "list <sandbox-id>",
- Short: "List checkpoints for a sandbox",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var checkpoints []CheckpointInfo
- if err := c.Get(cmd.Context(), fmt.Sprintf("/sandboxes/%s/checkpoints", args[0]), &checkpoints); err != nil {
- return err
- }
-
- printer.Print(checkpoints, func() {
- if len(checkpoints) == 0 {
- fmt.Println("No checkpoints found.")
- return
- }
- headers := []string{"ID", "NAME", "STATUS", "SIZE", "CREATED"}
- var rows [][]string
- for _, cp := range checkpoints {
- size := fmt.Sprintf("%.1f MB", float64(cp.SizeBytes)/1024/1024)
- if cp.SizeBytes == 0 {
- size = "-"
- }
- rows = append(rows, []string{
- cp.ID,
- cp.Name,
- cp.Status,
- size,
- cp.CreatedAt.Format(time.RFC3339),
- })
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var checkpointRestoreCmd = &cobra.Command{
- Use: "restore <sandbox-id> <checkpoint-id>",
- Short: "Restore a sandbox to a checkpoint (in-place revert)",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var result map[string]string
- if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/checkpoints/%s/restore", args[0], args[1]), nil, &result); err != nil {
- return err
- }
-
- printer.Print(result, func() {
- fmt.Printf("Sandbox %s restored to checkpoint %s\n", args[0], args[1])
- })
- return nil
- },
-}
-
-var checkpointSpawnCmd = &cobra.Command{
- Use: "spawn <checkpoint-id>",
- Short: "Create a new sandbox from a checkpoint",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- timeout, _ := cmd.Flags().GetInt("timeout")
-
- req := map[string]int{"timeout": timeout}
- var sandbox types.Sandbox
- if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/from-checkpoint/%s", args[0]), req, &sandbox); err != nil {
- return err
- }
-
- printer.Print(sandbox, func() {
- fmt.Printf("Created sandbox %s from checkpoint (status: %s)\n", sandbox.ID, sandbox.Status)
- if sandbox.ConnectURL != "" {
- fmt.Printf("Connect URL: %s\n", sandbox.ConnectURL)
- }
- })
- return nil
- },
-}
-
-var checkpointDeleteCmd = &cobra.Command{
- Use: "delete <sandbox-id> <checkpoint-id>",
- Short: "Delete a checkpoint",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- if err := c.DeleteIgnoreNotFound(cmd.Context(), fmt.Sprintf("/sandboxes/%s/checkpoints/%s", args[0], args[1])); err != nil {
- return err
- }
- fmt.Printf("Checkpoint %s deleted.\n", args[1])
- return nil
- },
-}
-
-// checkpointPublishCmd marks a checkpoint as publicly forkable across orgs
-// (design 009). The owner org still keeps exclusive control of patches and
-// deletion; publish only affects the fork auth gate.
-var checkpointPublishCmd = &cobra.Command{
- Use: "publish <checkpoint-id>",
- Short: "Mark a checkpoint as publicly forkable by any org",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- return setCheckpointPublic(cmd, args[0], true)
- },
-}
-
-var checkpointUnpublishCmd = &cobra.Command{
- Use: "unpublish <checkpoint-id>",
- Short: "Revoke public forkability of a checkpoint",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- return setCheckpointPublic(cmd, args[0], false)
- },
-}
-
-func setCheckpointPublic(cmd *cobra.Command, id string, isPublic bool) error {
- c := client.FromContext(cmd.Context())
- verb := "publish"
- if !isPublic {
- verb = "unpublish"
- }
- var cp CheckpointInfo
- if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/checkpoints/%s/%s", id, verb), nil, &cp); err != nil {
- return err
- }
- printer.Print(cp, func() {
- fmt.Printf("Checkpoint %s is_public=%t\n", cp.ID, cp.IsPublic)
- })
- return nil
-}
-
-func init() {
- checkpointCreateCmd.Flags().String("name", "", "Checkpoint name (required)")
- checkpointCreateCmd.Flags().String("kind", "full", "Checkpoint kind (full, disk_only)")
- checkpointCreateCmd.Flags().Bool("promote-to-full", false, "For disk_only checkpoints, asynchronously create a derived full checkpoint for faster forks")
- checkpointCreateCmd.Flags().MarkHidden("promote-to-full")
- checkpointCreateCmd.Flags().String("retention-policy", "none", "Retention policy for automatic checkpoint cleanup (none, delete_oldest)")
- checkpointCreateCmd.Flags().Int("retention-max-count", 0, "Maximum checkpoints of this kind to keep when --retention-policy=delete_oldest (full: 1-10, disk_only: 1-100, default server limit)")
- checkpointCreateCmd.MarkFlagRequired("name")
-
- checkpointSpawnCmd.Flags().Int("timeout", 0, "Idle timeout in seconds before auto-hibernate (0 = never hibernate)")
-
- checkpointCmd.AddCommand(checkpointCreateCmd)
- checkpointCmd.AddCommand(checkpointListCmd)
- checkpointCmd.AddCommand(checkpointRestoreCmd)
- checkpointCmd.AddCommand(checkpointSpawnCmd)
- checkpointCmd.AddCommand(checkpointDeleteCmd)
- checkpointCmd.AddCommand(checkpointPublishCmd)
- checkpointCmd.AddCommand(checkpointUnpublishCmd)
-}
diff --git a/cmd/oc/internal/commands/config_cmd.go b/cmd/oc/internal/commands/config_cmd.go
deleted file mode 100644
index 98401845..00000000
--- a/cmd/oc/internal/commands/config_cmd.go
+++ /dev/null
@@ -1,66 +0,0 @@
-package commands
-
-import (
- "fmt"
- "strings"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/config"
- "github.com/spf13/cobra"
-)
-
-var configCmd = &cobra.Command{
- Use: "config",
- Short: "Manage CLI configuration",
-}
-
-var configSetCmd = &cobra.Command{
- Use: "set <key> <value>",
- Short: "Set a configuration value",
- Long: `Set a configuration value. Supported keys:
- api-key Your OpenComputer API key
- api-url API base URL`,
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- cfg := config.LoadFile()
-
- switch args[0] {
- case "api-key":
- cfg.APIKey = args[1]
- cfg.Login = nil
- case "api-url":
- cfg.APIURL = args[1]
- default:
- return fmt.Errorf("unknown config key: %s (valid: api-key, api-url)", args[0])
- }
-
- if err := config.Save(cfg); err != nil {
- return fmt.Errorf("saving config: %w", err)
- }
-
- fmt.Printf("Config %s updated.\n", args[0])
- return nil
- },
-}
-
-var configShowCmd = &cobra.Command{
- Use: "show",
- Short: "Show current configuration",
- RunE: func(cmd *cobra.Command, args []string) error {
- cfg := config.Load(cmd)
-
- maskedKey := cfg.APIKey
- if len(maskedKey) > 8 {
- maskedKey = maskedKey[:4] + strings.Repeat("*", len(maskedKey)-8) + maskedKey[len(maskedKey)-4:]
- }
-
- fmt.Printf("API URL: %s\n", cfg.APIURL)
- fmt.Printf("API Key: %s\n", maskedKey)
- fmt.Printf("Config file: %s\n", config.ConfigPath())
- return nil
- },
-}
-
-func init() {
- configCmd.AddCommand(configSetCmd)
- configCmd.AddCommand(configShowCmd)
-}
diff --git a/cmd/oc/internal/commands/exec.go b/cmd/oc/internal/commands/exec.go
deleted file mode 100644
index 2d6a661e..00000000
--- a/cmd/oc/internal/commands/exec.go
+++ /dev/null
@@ -1,331 +0,0 @@
-package commands
-
-import (
- "context"
- "encoding/binary"
- "fmt"
- "os"
- "os/signal"
- "strings"
- "syscall"
-
- "github.com/gorilla/websocket"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/pkg/types"
- "github.com/spf13/cobra"
-)
-
-// Exec WebSocket binary protocol stream IDs.
-const (
- execStreamStdin = 0x00
- execStreamStdout = 0x01
- execStreamStderr = 0x02
- execStreamExit = 0x03
- execStreamScrollbackEnd = 0x04
-)
-
-var execCmd = &cobra.Command{
- Use: "exec <sandbox-id> -- <command> [args...]",
- Short: "Execute a command in a sandbox",
- Long: `Execute a command in a running sandbox using session-based exec.
-
-By default, creates a session, attaches to it over WebSocket, and streams
-stdout/stderr live to your terminal. The CLI exits with the command's
-exit code. Stdin is forwarded to the process (Ctrl-C sends SIGINT; press
-Ctrl-C twice to force-detach).
-
-Modes:
- (default) create, stream live, exit with the command's exit code
- --detach create and print the session id, don't wait
- --wait run synchronously via /exec/run (buffered, no streaming)
-
-Examples:
- oc exec abc123 -- echo hello
- oc exec abc123 -- npm install # streams output live
- oc exec abc123 --detach -- long-job # fire and forget
- oc exec abc123 --cwd /app -- ls -la
-
-Subcommands:
- oc exec list <sandbox-id> List active exec sessions
- oc exec attach <sandbox-id> <session-id> Reconnect + stream
- oc exec kill <sandbox-id> <session-id> Kill a session`,
- Args: cobra.MinimumNArgs(1),
- DisableFlagParsing: false,
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- sandboxID := args[0]
-
- if len(args) < 2 {
- return fmt.Errorf("no command specified. Usage: oc exec <sandbox-id> -- <command>")
- }
- command := args[1]
- cmdArgs := args[2:]
-
- cwd, _ := cmd.Flags().GetString("cwd")
- timeout, _ := cmd.Flags().GetInt("timeout")
- envSlice, _ := cmd.Flags().GetStringSlice("env")
- wait, _ := cmd.Flags().GetBool("wait")
- detach, _ := cmd.Flags().GetBool("detach")
-
- if wait && detach {
- return fmt.Errorf("--wait and --detach are mutually exclusive")
- }
-
- if wait {
- // Buffered mode: POST /exec/run, print everything at the end.
- req := types.ProcessConfig{
- Command: command,
- Args: cmdArgs,
- Cwd: cwd,
- Timeout: timeout,
- Env: parseKVSlice(envSlice),
- }
-
- var result types.ProcessResult
- if err := c.Post(cmd.Context(), "/sandboxes/"+sandboxID+"/exec/run", req, &result); err != nil {
- return err
- }
-
- if jsonOutput {
- printer.PrintJSON(result)
- } else {
- if result.Stdout != "" {
- fmt.Print(result.Stdout)
- }
- if result.Stderr != "" {
- fmt.Fprint(os.Stderr, result.Stderr)
- }
- if result.ExitCode != 0 {
- os.Exit(result.ExitCode)
- }
- }
- return nil
- }
-
- // Create an exec session.
- req := types.ExecSessionCreateRequest{
- Command: command,
- Args: cmdArgs,
- Cwd: cwd,
- Timeout: timeout,
- Env: parseKVSlice(envSlice),
- }
-
- var sessionInfo types.ExecSessionInfo
- if err := c.Post(cmd.Context(), "/sandboxes/"+sandboxID+"/exec", req, &sessionInfo); err != nil {
- return err
- }
-
- if detach {
- if jsonOutput {
- printer.PrintJSON(sessionInfo)
- } else {
- fmt.Printf("Session %s created (command: %s)\n", sessionInfo.SessionID, sessionInfo.Command)
- fmt.Printf("Attach with: oc exec attach %s %s\n", sandboxID, sessionInfo.SessionID)
- }
- return nil
- }
-
- // Default: attach + stream.
- code, err := streamExecSession(cmd.Context(), c, sandboxID, sessionInfo.SessionID, true)
- if err != nil {
- return err
- }
- if code != 0 {
- os.Exit(code)
- }
- return nil
- },
-}
-
-var execListCmd = &cobra.Command{
- Use: "list <sandbox-id>",
- Short: "List active exec sessions",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- sandboxID := args[0]
-
- var sessions []types.ExecSessionInfo
- if err := c.Get(cmd.Context(), "/sandboxes/"+sandboxID+"/exec", &sessions); err != nil {
- return err
- }
-
- if jsonOutput {
- printer.PrintJSON(sessions)
- } else {
- if len(sessions) == 0 {
- fmt.Println("No active exec sessions.")
- return nil
- }
- for _, s := range sessions {
- status := "running"
- if !s.Running {
- exitCode := 0
- if s.ExitCode != nil {
- exitCode = *s.ExitCode
- }
- status = fmt.Sprintf("exited (%d)", exitCode)
- }
- cmdStr := s.Command
- if len(s.Args) > 0 {
- cmdStr += " " + strings.Join(s.Args, " ")
- }
- fmt.Printf(" %s %s %s clients=%d\n", s.SessionID, status, cmdStr, s.AttachedClients)
- }
- }
- return nil
- },
-}
-
-var execAttachCmd = &cobra.Command{
- Use: "attach <sandbox-id> <session-id>",
- Short: "Reconnect to an exec session and stream its output",
- Long: `Open a WebSocket to an existing exec session. The server replays the
-scrollback buffer (historical output), then switches to live streaming.
-Stdin is forwarded to the process; Ctrl-C sends SIGINT.`,
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- sandboxID := args[0]
- sessionID := args[1]
-
- code, err := streamExecSession(cmd.Context(), c, sandboxID, sessionID, true)
- if err != nil {
- return err
- }
- if code != 0 {
- os.Exit(code)
- }
- return nil
- },
-}
-
-var execKillCmd = &cobra.Command{
- Use: "kill <sandbox-id> <session-id>",
- Short: "Kill an exec session",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- sandboxID := args[0]
- sessionID := args[1]
-
- signal, _ := cmd.Flags().GetInt("signal")
- body := map[string]int{"signal": signal}
-
- var resp map[string]interface{}
- if err := c.Post(cmd.Context(), "/sandboxes/"+sandboxID+"/exec/"+sessionID+"/kill", body, &resp); err != nil {
- return err
- }
-
- fmt.Printf("Session %s killed\n", sessionID)
- return nil
- },
-}
-
-// streamExecSession attaches to an exec session's WebSocket, pipes
-// stdout/stderr to the terminal, forwards stdin when requested, and
-// returns when the session ends. Returns the process exit code, or -1
-// if the WS closed without an exit frame.
-//
-// First SIGINT sends SIGINT to the process via the HTTP kill endpoint;
-// a second SIGINT aborts the CLI without waiting.
-func streamExecSession(ctx context.Context, c *client.Client, sandboxID, sessionID string, forwardStdin bool) (int, error) {
- wsPath := fmt.Sprintf("/sandboxes/%s/exec/%s", sandboxID, sessionID)
- conn, err := c.DialWebSocket(ctx, wsPath)
- if err != nil {
- return -1, fmt.Errorf("attach failed: %w", err)
- }
- defer conn.Close()
-
- // Graceful Ctrl-C: forward SIGINT to the process. Second Ctrl-C bails.
- sigCh := make(chan os.Signal, 1)
- signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
- defer signal.Stop(sigCh)
- interrupts := 0
- go func() {
- for range sigCh {
- interrupts++
- if interrupts >= 2 {
- conn.Close()
- return
- }
- body := map[string]int{"signal": int(syscall.SIGINT)}
- _ = c.Post(ctx, fmt.Sprintf("/sandboxes/%s/exec/%s/kill", sandboxID, sessionID), body, nil)
- fmt.Fprintln(os.Stderr, "\n^C sent SIGINT (press again to force-detach)")
- }
- }()
-
- // Stdin → WS (stream 0x00). Runs until EOF/error.
- if forwardStdin {
- go func() {
- buf := make([]byte, 4096)
- for {
- n, err := os.Stdin.Read(buf)
- if n > 0 {
- msg := make([]byte, 1+n)
- msg[0] = execStreamStdin
- copy(msg[1:], buf[:n])
- if werr := conn.WriteMessage(websocket.BinaryMessage, msg); werr != nil {
- return
- }
- }
- if err != nil {
- return
- }
- }
- }()
- }
-
- // WS → stdout/stderr. Exit frame terminates.
- exitCode := -1
- gotExit := false
- for {
- _, msg, err := conn.ReadMessage()
- if err != nil {
- break
- }
- if len(msg) < 1 {
- continue
- }
- switch msg[0] {
- case execStreamStdout:
- _, _ = os.Stdout.Write(msg[1:])
- case execStreamStderr:
- _, _ = os.Stderr.Write(msg[1:])
- case execStreamExit:
- gotExit = true
- if len(msg) >= 5 {
- exitCode = int(int32(binary.BigEndian.Uint32(msg[1:5])))
- } else {
- exitCode = 0
- }
- case execStreamScrollbackEnd:
- // Marks the boundary between replayed history and live output.
- // Nothing to do for the CLI — we stream both the same way.
- }
- }
-
- if !gotExit {
- // WS closed without an exit frame — either the user force-detached
- // (second Ctrl-C) or the network dropped. Return -1 so the caller
- // can decide what to do.
- return -1, nil
- }
- return exitCode, nil
-}
-
-func init() {
- execCmd.Flags().String("cwd", "", "Working directory")
- execCmd.Flags().Int("timeout", 0, "Timeout in seconds (0 = no timeout)")
- execCmd.Flags().StringSlice("env", nil, "Environment variables (KEY=VALUE)")
- execCmd.Flags().Bool("wait", false, "Run synchronously via /exec/run (buffered, no streaming)")
- execCmd.Flags().Bool("detach", false, "Create the session and print its id; don't stream")
-
- execKillCmd.Flags().Int("signal", 9, "Signal to send (default SIGKILL=9)")
-
- execCmd.AddCommand(execListCmd)
- execCmd.AddCommand(execAttachCmd)
- execCmd.AddCommand(execKillCmd)
-}
diff --git a/cmd/oc/internal/commands/exit.go b/cmd/oc/internal/commands/exit.go
deleted file mode 100644
index 37ce9637..00000000
--- a/cmd/oc/internal/commands/exit.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package commands
-
-import (
- "encoding/json"
- "errors"
- "fmt"
- "os"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
-)
-
-// ExitError signals a specific process exit code to main.go. The error is
-// assumed already-rendered (RenderError won't reprint it). Codes mirror the
-// classes below.
-type ExitError struct{ Code int }
-
-func (e *ExitError) Error() string { return "" }
-
-// exitCodeForStatus maps an HTTP status to the CLI's exit-code classes so agents
-// and CI can branch on the outcome:
-//
-// 0 success
-// 1 general error (bad args/flags, local failure)
-// 3 upstream 4xx (not found, unauthorized, invalid)
-// 4 conflict (409 — already exists / invalid state)
-// 5 transient (5xx — retry-safe)
-func exitCodeForStatus(status int) int {
- switch {
- case status == 409:
- return 4
- case status >= 400 && status < 500:
- return 3
- case status >= 500:
- return 5
- default:
- return 1
- }
-}
-
-// RenderError prints err to stderr (a JSON envelope under --json, else plain)
-// and returns the process exit code. An ExitError is treated as already-rendered
-// (its code is returned with no reprint). main.go calls os.Exit(RenderError(...)).
-func RenderError(err error) int {
- if err == nil {
- return 0
- }
- var exit *ExitError
- if errors.As(err, &exit) {
- return exit.Code
- }
- code := 1
- msg := err.Error()
- var apiErr *client.APIError
- if errors.As(err, &apiErr) {
- code = exitCodeForStatus(apiErr.StatusCode)
- msg = apiErr.Message
- }
- if jsonOutput {
- b, _ := json.Marshal(map[string]any{"error": msg, "code": code})
- fmt.Fprintln(os.Stderr, string(b))
- } else {
- fmt.Fprintln(os.Stderr, "Error: "+msg)
- }
- return code
-}
diff --git a/cmd/oc/internal/commands/feedback.go b/cmd/oc/internal/commands/feedback.go
deleted file mode 100644
index e8834eac..00000000
--- a/cmd/oc/internal/commands/feedback.go
+++ /dev/null
@@ -1,562 +0,0 @@
-package commands
-
-import (
- "bytes"
- "context"
- "crypto/ed25519"
- "crypto/rand"
- "crypto/sha256"
- "crypto/x509"
- "encoding/base64"
- "encoding/hex"
- "encoding/json"
- "encoding/pem"
- "fmt"
- "io"
- "net/http"
- "net/url"
- "os"
- "strings"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/config"
- "github.com/spf13/cobra"
-)
-
-// feedback.now emitter (https://feedback.now). Any host that publishes
-// /.well-known/agent-feedback.json is a valid target; OpenComputer's own API
-// host is the default. Submission is anonymous unless --signing-key is given.
-// These commands never touch the OpenComputer API key — the protocol is
-// deliberately unauthenticated so third-party agents can report friction.
-
-const (
- feedbackDiscoveryPath = "/.well-known/agent-feedback.json"
- feedbackTimeout = 15 * time.Second
- feedbackEnvTarget = "OC_FEEDBACK_TARGET"
- feedbackEnvSigningKey = "OC_FEEDBACK_SIGNING_KEY"
-)
-
-var feedbackCmd = &cobra.Command{
- Use: "feedback",
- Short: "Report bugs and friction to a feedback.now-compatible API (OpenComputer by default)",
- Long: "Emit structured feedback using the feedback.now protocol.\n\n" +
- "Agents (or humans) hit a bug, docs mismatch, or friction in an API/CLI/SDK\n" +
- "and file it here without an account. The target host is discovered from\n" +
- "/.well-known/agent-feedback.json, so this works against any feedback.now\n" +
- "receiver, not just OpenComputer. Every submission returns a receipt ID you\n" +
- "can poll with `oc feedback receipt`.\n\n" +
- "Target selection: --target, else $" + feedbackEnvTarget + ", else the configured\n" +
- "OpenComputer API URL. Optional Ed25519 signing: --signing-key or\n" +
- "$" + feedbackEnvSigningKey + " (PEM file from `oc feedback keygen`).",
- Annotations: map[string]string{offlineCommandAnnotation: "true"},
-}
-
-var feedbackPolicyCmd = &cobra.Command{
- Use: "policy",
- Short: "Show the target's feedback.now discovery document and policy",
- Args: cobra.NoArgs,
- Annotations: map[string]string{offlineCommandAnnotation: "true"},
- RunE: func(cmd *cobra.Command, _ []string) error {
- fc, err := newFeedbackClient(cmd)
- if err != nil {
- return err
- }
- disc, err := fc.discover(cmd.Context())
- if err != nil {
- return err
- }
- policyURL := fc.resolve(disc.PolicyURL, "/api/v1/policy")
- var policy map[string]any
- if err := fc.getJSON(cmd.Context(), policyURL, &policy); err != nil {
- return err
- }
- out := map[string]any{"target": fc.base.String(), "discovery": disc.raw, "policy": policy}
- if jsonOutput {
- return printer.PrintJSON(out)
- }
- fmt.Printf("Target: %s\n", fc.base)
- fmt.Printf("Name: %s\n", disc.Name)
- fmt.Printf("Policy: %s\n", policyURL)
- fmt.Printf("Categories: %s\n", strings.Join(stringList(policy["categories"]), ", "))
- fmt.Printf("Severities: %s\n", strings.Join(stringList(policy["severity_levels"]), ", "))
- fmt.Printf("Evidence: %s\n", strings.Join(stringList(policy["evidence_types"]), ", "))
- if auth, ok := disc.raw["auth"].(map[string]any); ok {
- fmt.Printf("Signing: %v (optional)\n", auth["type"])
- }
- return nil
- },
-}
-
-var feedbackSubmitCmd = &cobra.Command{
- Use: "submit",
- Short: "Submit a structured feedback report (bug, docs mismatch, friction, feature gap)",
- Example: " oc feedback submit --surface 'POST /api/sandboxes' --category bug --severity high \\\n" +
- " --title 'create returns 500 when template is missing' \\\n" +
- " --summary 'Expected a 404 with a clear error' \\\n" +
- " --evidence http_summary='{\"status\":500}' --evidence [email protected]\n" +
- " oc feedback submit --target https://api.example.com --surface 'GET /v1/items' \\\n" +
- " --category docs_mismatch --severity low --title 'docs say limit max is 500, API caps at 100'",
- Args: cobra.NoArgs,
- Annotations: map[string]string{offlineCommandAnnotation: "true"},
- RunE: func(cmd *cobra.Command, _ []string) error {
- fc, err := newFeedbackClient(cmd)
- if err != nil {
- return err
- }
- f := cmd.Flags()
- title, _ := f.GetString("title")
- surface, _ := f.GetString("surface")
- category, _ := f.GetString("category")
- severity, _ := f.GetString("severity")
- if title == "" || surface == "" || category == "" || severity == "" {
- return fmt.Errorf("--title, --surface, --category and --severity are required")
- }
- summary, _ := f.GetString("summary")
- hypothesis, _ := f.GetString("hypothesis")
- repro, _ := f.GetString("reproducibility")
- confidence, _ := f.GetFloat64("confidence")
- kind, _ := f.GetString("kind")
- product, _ := f.GetString("product")
- evidenceFlags, _ := f.GetStringArray("evidence")
- evidence, err := parseEvidenceFlags(evidenceFlags)
- if err != nil {
- return err
- }
-
- signal := map[string]any{"category": category, "severity": severity, "confidence": confidence}
- if repro != "" {
- signal["reproducibility"] = repro
- }
- subject := map[string]any{"surface": surface, "domain": fc.domain(cmd)}
- if kind != "" {
- subject["kind"] = kind
- }
- if product != "" {
- subject["product"] = product
- }
- content := map[string]any{"title": title}
- if summary != "" {
- content["summary"] = summary
- }
- if hypothesis != "" {
- content["hypothesis"] = hypothesis
- }
- body := map[string]any{
- "reporter": fc.reporter(cmd),
- "subject": subject,
- "signal": signal,
- "content": content,
- }
- if len(evidence) > 0 {
- body["evidence"] = evidence
- }
-
- disc, err := fc.discover(cmd.Context())
- if err != nil {
- return err
- }
- endpoint := fc.resolve(disc.endpoint("feedback", "submit"), "/api/v1/feedback")
- var resp map[string]any
- if err := fc.postJSON(cmd.Context(), endpoint, body, &resp); err != nil {
- return err
- }
- return fc.printReceipt(resp)
- },
-}
-
-var feedbackObserveCmd = &cobra.Command{
- Use: "observe",
- Short: "Submit a lightweight observation (no title/evidence required)",
- Example: " oc feedback observe --surface 'oc sandbox create' --category friction \\\n" +
- " --summary '--template flag name differs from docs'",
- Args: cobra.NoArgs,
- Annotations: map[string]string{offlineCommandAnnotation: "true"},
- RunE: func(cmd *cobra.Command, _ []string) error {
- fc, err := newFeedbackClient(cmd)
- if err != nil {
- return err
- }
- f := cmd.Flags()
- surface, _ := f.GetString("surface")
- if surface == "" {
- return fmt.Errorf("--surface is required")
- }
- rep := fc.reporter(cmd)
- body := map[string]any{
- "surface": surface,
- "domain": fc.domain(cmd),
- "agent_vendor": rep["agent_vendor"],
- "agent_product": rep["agent_product"],
- }
- if v := rep["agent_version"]; v != "" {
- body["agent_version"] = v
- }
- for _, k := range []string{"category", "severity", "summary", "kind"} {
- if v, _ := f.GetString(k); v != "" {
- body[k] = v
- }
- }
- if f.Changed("confidence") {
- body["confidence"], _ = f.GetFloat64("confidence")
- }
-
- disc, err := fc.discover(cmd.Context())
- if err != nil {
- return err
- }
- endpoint := fc.resolve(disc.endpoint("observations", "submit"), "/api/v1/observations")
- var resp map[string]any
- if err := fc.postJSON(cmd.Context(), endpoint, body, &resp); err != nil {
- return err
- }
- return fc.printReceipt(resp)
- },
-}
-
-var feedbackReceiptCmd = &cobra.Command{
- Use: "receipt <receipt-id>",
- Short: "Poll a receipt to see whether the report was accepted, folded as a duplicate, or triaged",
- Args: cobra.ExactArgs(1),
- Annotations: map[string]string{offlineCommandAnnotation: "true"},
- RunE: func(cmd *cobra.Command, args []string) error {
- fc, err := newFeedbackClient(cmd)
- if err != nil {
- return err
- }
- disc, err := fc.discover(cmd.Context())
- if err != nil {
- return err
- }
- tmpl := disc.endpoint("receipts", "get")
- if tmpl == "" {
- tmpl = "/api/v1/receipts/{id}"
- }
- u := fc.resolve(strings.Replace(tmpl, "{id}", url.PathEscape(args[0]), 1), "/api/v1/receipts/"+url.PathEscape(args[0]))
- var resp struct {
- Data map[string]any `json:"data"`
- }
- if err := fc.getJSON(cmd.Context(), u, &resp); err != nil {
- return err
- }
- if jsonOutput {
- return printer.PrintJSON(resp.Data)
- }
- rows := [][]string{}
- for _, k := range []string{"id", "status", "feedback_id", "observation_id", "feedback_status", "duplicate_of", "quality_score", "created_at", "updated_at"} {
- if v, ok := resp.Data[k]; ok && v != nil {
- rows = append(rows, []string{k, fmt.Sprint(v)})
- }
- }
- printer.Table([]string{"FIELD", "VALUE"}, rows)
- return nil
- },
-}
-
-var feedbackKeygenCmd = &cobra.Command{
- Use: "keygen",
- Short: "Generate an Ed25519 signing key for agent identity (optional)",
- Long: "Writes a PKCS#8 PEM private key. Pass it via --signing-key or $" + feedbackEnvSigningKey +
- " so receivers can build a reputation for this agent across submissions.",
- Args: cobra.NoArgs,
- Annotations: map[string]string{offlineCommandAnnotation: "true"},
- RunE: func(cmd *cobra.Command, _ []string) error {
- out, _ := cmd.Flags().GetString("out")
- if out == "" {
- return fmt.Errorf("--out is required")
- }
- pub, priv, err := ed25519.GenerateKey(rand.Reader)
- if err != nil {
- return err
- }
- der, err := x509.MarshalPKCS8PrivateKey(priv)
- if err != nil {
- return err
- }
- if err := os.WriteFile(out, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), 0o600); err != nil {
- return err
- }
- spki, err := x509.MarshalPKIXPublicKey(pub)
- if err != nil {
- return err
- }
- res := map[string]any{"path": out, "public_key": base64.StdEncoding.EncodeToString(spki)}
- if jsonOutput {
- return printer.PrintJSON(res)
- }
- fmt.Printf("Wrote %s\nPublic key (X-Agent-Key): %s\n", out, res["public_key"])
- return nil
- },
-}
-
-func init() {
- pf := feedbackCmd.PersistentFlags()
- pf.String("target", "", "Base URL of a feedback.now receiver (default: $"+feedbackEnvTarget+" or the OpenComputer API URL)")
- pf.String("signing-key", "", "PEM Ed25519 private key to sign requests (default: $"+feedbackEnvSigningKey+")")
- pf.String("agent-vendor", "opencomputer", "reporter.agent_vendor")
- pf.String("agent-product", "oc-cli", "reporter.agent_product")
- pf.String("agent-version", "", "reporter.agent_version (default: oc version)")
- pf.String("domain", "", "subject.domain (default: target host)")
-
- for _, c := range []*cobra.Command{feedbackSubmitCmd, feedbackObserveCmd} {
- c.Flags().String("surface", "", "What was being used, e.g. 'POST /api/sandboxes' or 'oc sandbox create'")
- c.Flags().String("category", "", "bug | docs_mismatch | friction | feature_gap | quality_degradation | other")
- c.Flags().String("severity", "", "critical | high | medium | low")
- c.Flags().Float64("confidence", 0.7, "0..1 confidence that this is a real issue")
- c.Flags().String("summary", "", "What happened vs. what was expected")
- c.Flags().String("kind", "", "api_endpoint | docs_page | cli_command | sdk_method | other")
- }
- feedbackSubmitCmd.Flags().String("title", "", "Short title (required)")
- feedbackSubmitCmd.Flags().String("hypothesis", "", "Suspected root cause")
- feedbackSubmitCmd.Flags().String("reproducibility", "", "always | sometimes | intermittent | once")
- feedbackSubmitCmd.Flags().String("product", "", "subject.product, e.g. 'typescript-sdk'")
- feedbackSubmitCmd.Flags().StringArray("evidence", nil, "type=content or type=@file (repeatable; types: http_summary, stderr_excerpt, repro_steps, log_excerpt, other)")
-
- feedbackKeygenCmd.Flags().String("out", "", "Where to write the PEM private key")
-
- feedbackCmd.AddCommand(feedbackPolicyCmd, feedbackSubmitCmd, feedbackObserveCmd, feedbackReceiptCmd, feedbackKeygenCmd)
-}
-
-// ── client ────────────────────────────────────────────────────────────────
-
-type feedbackClient struct {
- base *url.URL
- http *http.Client
- key ed25519.PrivateKey // nil → anonymous
-}
-
-type feedbackDiscovery struct {
- Name string
- PolicyURL string
- raw map[string]any
-}
-
-// endpoint returns endpoints.<group>.<op>.url from the discovery document, or "".
-func (d *feedbackDiscovery) endpoint(group, op string) string {
- eps, _ := d.raw["endpoints"].(map[string]any)
- g, _ := eps[group].(map[string]any)
- o, _ := g[op].(map[string]any)
- u, _ := o["url"].(string)
- return u
-}
-
-func newFeedbackClient(cmd *cobra.Command) (*feedbackClient, error) {
- target, _ := cmd.Flags().GetString("target")
- if target == "" {
- target = os.Getenv(feedbackEnvTarget)
- }
- if target == "" {
- target = config.Load(cmd).APIURL
- }
- if !strings.Contains(target, "://") {
- target = "https://" + target
- }
- base, err := url.Parse(target)
- if err != nil || base.Host == "" {
- return nil, fmt.Errorf("invalid feedback target %q", target)
- }
- base.Path, base.RawQuery, base.Fragment = "", "", ""
-
- fc := &feedbackClient{base: base, http: &http.Client{Timeout: feedbackTimeout}}
- keyPath, _ := cmd.Flags().GetString("signing-key")
- if keyPath == "" {
- keyPath = os.Getenv(feedbackEnvSigningKey)
- }
- if keyPath != "" {
- fc.key, err = loadEd25519Key(keyPath)
- if err != nil {
- return nil, err
- }
- }
- return fc, nil
-}
-
-func loadEd25519Key(path string) (ed25519.PrivateKey, error) {
- raw, err := os.ReadFile(path)
- if err != nil {
- return nil, fmt.Errorf("read signing key: %w", err)
- }
- block, _ := pem.Decode(raw)
- if block == nil {
- return nil, fmt.Errorf("signing key %s: not PEM", path)
- }
- k, err := x509.ParsePKCS8PrivateKey(block.Bytes)
- if err != nil {
- return nil, fmt.Errorf("signing key %s: %w", path, err)
- }
- priv, ok := k.(ed25519.PrivateKey)
- if !ok {
- return nil, fmt.Errorf("signing key %s: not an Ed25519 key", path)
- }
- return priv, nil
-}
-
-func (fc *feedbackClient) resolve(u, fallback string) string {
- if u == "" {
- u = fallback
- }
- ref, err := url.Parse(u)
- if err != nil {
- return fc.base.String() + fallback
- }
- return fc.base.ResolveReference(ref).String()
-}
-
-func (fc *feedbackClient) domain(cmd *cobra.Command) string {
- if d, _ := cmd.Flags().GetString("domain"); d != "" {
- return d
- }
- return fc.base.Hostname()
-}
-
-func (fc *feedbackClient) reporter(cmd *cobra.Command) map[string]string {
- vendor, _ := cmd.Flags().GetString("agent-vendor")
- product, _ := cmd.Flags().GetString("agent-product")
- version, _ := cmd.Flags().GetString("agent-version")
- if version == "" {
- version = Version
- }
- return map[string]string{"agent_vendor": vendor, "agent_product": product, "agent_version": version}
-}
-
-func (fc *feedbackClient) discover(ctx context.Context) (*feedbackDiscovery, error) {
- var raw map[string]any
- if err := fc.getJSON(ctx, fc.base.String()+feedbackDiscoveryPath, &raw); err != nil {
- return nil, fmt.Errorf("%s does not advertise feedback.now (%s): %w", fc.base.Host, feedbackDiscoveryPath, err)
- }
- d := &feedbackDiscovery{raw: raw}
- d.Name, _ = raw["name"].(string)
- d.PolicyURL, _ = raw["policy_url"].(string)
- return d, nil
-}
-
-func (fc *feedbackClient) getJSON(ctx context.Context, u string, out any) error {
- return fc.do(ctx, http.MethodGet, u, nil, out)
-}
-
-func (fc *feedbackClient) postJSON(ctx context.Context, u string, body any, out any) error {
- b, err := json.Marshal(body)
- if err != nil {
- return err
- }
- return fc.do(ctx, http.MethodPost, u, b, out)
-}
-
-// feedbackErrorMessage flattens the receiver's error envelope, including
-// feedback.now's per-field validation errors, into one line.
-func feedbackErrorMessage(status int, data []byte) string {
- var body map[string]any
- _ = json.Unmarshal(data, &body)
- msg, _ := body["error"].(string)
- if msg == "" {
- msg = http.StatusText(status)
- }
- if errs, ok := body["errors"].([]any); ok && len(errs) > 0 {
- parts := make([]string, 0, len(errs))
- for _, fe := range errs {
- m, _ := fe.(map[string]any)
- parts = append(parts, fmt.Sprintf("%v: %v", m["field"], m["message"]))
- }
- msg += " (" + strings.Join(parts, "; ") + ")"
- }
- return msg
-}
-
-func (fc *feedbackClient) do(ctx context.Context, method, u string, body []byte, out any) error {
- req, err := http.NewRequestWithContext(ctx, method, u, bytes.NewReader(body))
- if err != nil {
- return err
- }
- req.Header.Set("Accept", "application/json")
- req.Header.Set("User-Agent", "oc-cli/"+Version)
- if body != nil {
- req.Header.Set("Content-Type", "application/json")
- }
- if fc.key != nil {
- fc.sign(req, body)
- }
- resp, err := fc.http.Do(req)
- if err != nil {
- return err
- }
- defer resp.Body.Close()
- data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
- if err != nil {
- return err
- }
- if resp.StatusCode >= 400 {
- return &client.APIError{StatusCode: resp.StatusCode, Message: feedbackErrorMessage(resp.StatusCode, data)}
- }
- if out == nil {
- return nil
- }
- if err := json.Unmarshal(data, out); err != nil {
- return fmt.Errorf("decode response from %s: %w", u, err)
- }
- return nil
-}
-
-// sign adds the feedback.now Ed25519 headers. Payload per spec:
-// timestamp\nMETHOD\npath\nsha256hex(body).
-func (fc *feedbackClient) sign(req *http.Request, body []byte) {
- ts := time.Now().UTC().Format(time.RFC3339)
- sum := sha256.Sum256(body)
- payload := strings.Join([]string{ts, req.Method, req.URL.Path, hex.EncodeToString(sum[:])}, "\n")
- sig := ed25519.Sign(fc.key, []byte(payload))
- spki, err := x509.MarshalPKIXPublicKey(fc.key.Public())
- if err != nil {
- return
- }
- req.Header.Set("X-Agent-Key", base64.StdEncoding.EncodeToString(spki))
- req.Header.Set("X-Agent-Signature", base64.StdEncoding.EncodeToString(sig))
- req.Header.Set("X-Agent-Timestamp", ts)
-}
-
-func (fc *feedbackClient) printReceipt(resp map[string]any) error {
- receipt, _ := resp["receipt"].(map[string]any)
- if jsonOutput {
- return printer.PrintJSON(resp)
- }
- status, _ := receipt["status"].(string)
- fmt.Printf("Receipt: %v\nStatus: %s\n", receipt["id"], status)
- if v, ok := receipt["feedback_id"]; ok && v != nil {
- fmt.Printf("Feedback: %v\n", v)
- }
- if v, ok := receipt["observation_id"]; ok && v != nil {
- fmt.Printf("Observation: %v\n", v)
- }
- if v, ok := receipt["duplicate_of"]; ok && v != nil {
- fmt.Printf("Folded into existing report %v\n", v)
- }
- fmt.Printf("Poll with: oc feedback receipt %v --target %s\n", receipt["id"], fc.base)
- return nil
-}
-
-// parseEvidenceFlags turns type=content / type=@file into evidence objects.
-func parseEvidenceFlags(flags []string) ([]map[string]any, error) {
- out := make([]map[string]any, 0, len(flags))
- for _, f := range flags {
- typ, val, ok := strings.Cut(f, "=")
- if !ok || typ == "" {
- return nil, fmt.Errorf("--evidence %q: expected type=content or type=@file", f)
- }
- if strings.HasPrefix(val, "@") {
- b, err := os.ReadFile(val[1:])
- if err != nil {
- return nil, fmt.Errorf("--evidence %s: %w", typ, err)
- }
- val = string(b)
- }
- out = append(out, map[string]any{"type": typ, "content": val})
- }
- return out, nil
-}
-
-func stringList(v any) []string {
- arr, _ := v.([]any)
- out := make([]string, 0, len(arr))
- for _, x := range arr {
- out = append(out, fmt.Sprint(x))
- }
- return out
-}
diff --git a/cmd/oc/internal/commands/feedback_test.go b/cmd/oc/internal/commands/feedback_test.go
deleted file mode 100644
index 372dc6ee..00000000
--- a/cmd/oc/internal/commands/feedback_test.go
+++ /dev/null
@@ -1,242 +0,0 @@
-package commands
-
-import (
- "crypto/ed25519"
- "crypto/sha256"
- "crypto/x509"
- "encoding/base64"
- "encoding/hex"
- "encoding/json"
- "io"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/output"
- "github.com/spf13/cobra"
- "github.com/spf13/pflag"
-)
-
-// stub feedback.now receiver: serves discovery pointing at itself and records
-// the last submission body + headers.
-type feedbackStub struct {
- srv *httptest.Server
- lastPath string
- lastBody map[string]any
- lastHdr http.Header
-}
-
-func newFeedbackStub(t *testing.T) *feedbackStub {
- t.Helper()
- s := &feedbackStub{}
- mux := http.NewServeMux()
- mux.HandleFunc("/.well-known/agent-feedback.json", func(w http.ResponseWriter, _ *http.Request) {
- // Relative + absolute URLs mixed on purpose: the emitter must resolve both.
- json.NewEncoder(w).Encode(map[string]any{
- "schema_version": "1.1",
- "name": "Stub",
- "policy_url": "/api/v1/policy",
- "endpoints": map[string]any{
- "feedback": map[string]any{"submit": map[string]any{"method": "POST", "url": "/custom/feedback"}},
- "observations": map[string]any{"submit": map[string]any{"method": "POST", "url": s.srv.URL + "/custom/obs"}},
- "receipts": map[string]any{"get": map[string]any{"method": "GET", "url": "/custom/receipts/{id}"}},
- },
- })
- })
- mux.HandleFunc("/api/v1/policy", func(w http.ResponseWriter, _ *http.Request) {
- json.NewEncoder(w).Encode(map[string]any{"categories": []string{"bug"}, "severity_levels": []string{"low"}, "evidence_types": []string{"other"}})
- })
- record := func(w http.ResponseWriter, r *http.Request) {
- s.lastPath = r.URL.Path
- s.lastHdr = r.Header.Clone()
- raw, _ := io.ReadAll(r.Body)
- s.lastBody = nil
- _ = json.Unmarshal(raw, &s.lastBody)
- if sig := r.Header.Get("X-Agent-Signature"); sig != "" {
- if !verifySig(r, raw) {
- w.WriteHeader(401)
- return
- }
- }
- if r.URL.Path == "/custom/feedback" {
- if _, ok := s.lastBody["content"].(map[string]any)["title"]; !ok {
- w.WriteHeader(400)
- json.NewEncoder(w).Encode(map[string]any{"error": "validation_failed", "errors": []map[string]any{{"field": "content.title", "error": "required", "message": "title is required"}}})
- return
- }
- }
- w.WriteHeader(201)
- json.NewEncoder(w).Encode(map[string]any{"receipt": map[string]any{"id": "rcpt_1", "status": "accepted", "feedback_id": "fb_1"}})
- }
- mux.HandleFunc("/custom/feedback", record)
- mux.HandleFunc("/custom/obs", record)
- mux.HandleFunc("/custom/receipts/", func(w http.ResponseWriter, r *http.Request) {
- s.lastPath = r.URL.Path
- json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"id": strings.TrimPrefix(r.URL.Path, "/custom/receipts/"), "status": "duplicate", "duplicate_of": "fb_0"}})
- })
- s.srv = httptest.NewServer(mux)
- t.Cleanup(s.srv.Close)
- return s
-}
-
-func verifySig(r *http.Request, body []byte) bool {
- spki, err := base64.StdEncoding.DecodeString(r.Header.Get("X-Agent-Key"))
- if err != nil {
- return false
- }
- pubAny, err := x509.ParsePKIXPublicKey(spki)
- if err != nil {
- return false
- }
- pub, ok := pubAny.(ed25519.PublicKey)
- if !ok {
- return false
- }
- sig, err := base64.StdEncoding.DecodeString(r.Header.Get("X-Agent-Signature"))
- if err != nil {
- return false
- }
- sum := sha256.Sum256(body)
- payload := strings.Join([]string{r.Header.Get("X-Agent-Timestamp"), r.Method, r.URL.Path, hex.EncodeToString(sum[:])}, "\n")
- return ed25519.Verify(pub, []byte(payload), sig)
-}
-
-func runFeedback(t *testing.T, args ...string) (string, error) {
- t.Helper()
- t.Setenv("HOME", t.TempDir())
- t.Setenv("OPENCOMPUTER_API_KEY", "")
- t.Setenv("OC_NO_UPDATE_CHECK", "1")
- r, w, err := os.Pipe()
- if err != nil {
- t.Fatal(err)
- }
- oldStdout := os.Stdout
- os.Stdout = w
- printer = output.New(false)
- printer.W = w
- rootCmd.SetArgs(append([]string{"feedback"}, args...))
- runErr := rootCmd.Execute()
- os.Stdout = oldStdout
- w.Close()
- out, _ := io.ReadAll(r)
- // cobra keeps parsed flag values across Execute calls in one process;
- // restore defaults so tests don't leak --target/--title into each other.
- for _, c := range append([]*cobra.Command{feedbackCmd}, feedbackCmd.Commands()...) {
- for _, fs := range []*pflag.FlagSet{c.PersistentFlags(), c.Flags()} {
- fs.VisitAll(func(f *pflag.Flag) {
- if f.Changed && f.Value.Type() != "stringArray" {
- _ = f.Value.Set(f.DefValue)
- f.Changed = false
- }
- })
- }
- }
- return string(out), runErr
-}
-
-func TestFeedbackSubmitDiscoversEndpointAndSendsSpecShape(t *testing.T) {
- stub := newFeedbackStub(t)
- out, err := runFeedback(t, "submit", "--target", stub.srv.URL,
- "--surface", "POST /api/sandboxes", "--category", "bug", "--severity", "high",
- "--title", "boom", "--summary", "expected 404", "--reproducibility", "always",
- "--evidence", "http_summary={\"status\":500}")
- if err != nil {
- t.Fatalf("submit: %v", err)
- }
- if stub.lastPath != "/custom/feedback" {
- t.Fatalf("did not follow discovery url, got %s", stub.lastPath)
- }
- if stub.lastHdr.Get("X-Agent-Signature") != "" {
- t.Fatal("unsigned submission should carry no signature")
- }
- rep := stub.lastBody["reporter"].(map[string]any)
- if rep["agent_vendor"] != "opencomputer" || rep["agent_product"] != "oc-cli" {
- t.Fatalf("reporter = %v", rep)
- }
- subj := stub.lastBody["subject"].(map[string]any)
- if subj["surface"] != "POST /api/sandboxes" || subj["domain"] != "127.0.0.1" {
- t.Fatalf("subject = %v", subj)
- }
- sig := stub.lastBody["signal"].(map[string]any)
- if sig["category"] != "bug" || sig["severity"] != "high" || sig["reproducibility"] != "always" || sig["confidence"] != 0.7 {
- t.Fatalf("signal = %v", sig)
- }
- ev := stub.lastBody["evidence"].([]any)
- if len(ev) != 1 || ev[0].(map[string]any)["type"] != "http_summary" {
- t.Fatalf("evidence = %v", ev)
- }
- if !strings.Contains(out, "Receipt: rcpt_1") || !strings.Contains(out, "Feedback: fb_1") {
- t.Fatalf("output = %q", out)
- }
-}
-
-func TestFeedbackSubmitSignsWithEd25519(t *testing.T) {
- stub := newFeedbackStub(t)
- keyPath := filepath.Join(t.TempDir(), "agent.pem")
- if _, err := runFeedback(t, "keygen", "--out", keyPath); err != nil {
- t.Fatalf("keygen: %v", err)
- }
- if _, err := runFeedback(t, "submit", "--target", stub.srv.URL, "--signing-key", keyPath,
- "--surface", "s", "--category", "bug", "--severity", "low", "--title", "t"); err != nil {
- t.Fatalf("signed submit rejected by stub verifier: %v", err)
- }
- if stub.lastHdr.Get("X-Agent-Key") == "" || stub.lastHdr.Get("X-Agent-Timestamp") == "" {
- t.Fatal("missing signing headers")
- }
-}
-
-func TestFeedbackObserveUsesAbsoluteDiscoveryURL(t *testing.T) {
- stub := newFeedbackStub(t)
- if _, err := runFeedback(t, "observe", "--target", stub.srv.URL, "--surface", "oc sandbox create", "--category", "friction", "--domain", "example.test"); err != nil {
- t.Fatalf("observe: %v", err)
- }
- if stub.lastPath != "/custom/obs" {
- t.Fatalf("path = %s", stub.lastPath)
- }
- if stub.lastBody["domain"] != "example.test" || stub.lastBody["agent_product"] != "oc-cli" || stub.lastBody["category"] != "friction" {
- t.Fatalf("body = %v", stub.lastBody)
- }
- if _, has := stub.lastBody["confidence"]; has {
- t.Fatal("confidence should be omitted when not passed")
- }
-}
-
-func TestFeedbackReceiptAndValidationErrors(t *testing.T) {
- stub := newFeedbackStub(t)
- out, err := runFeedback(t, "receipt", "rcpt_9", "--target", stub.srv.URL)
- if err != nil {
- t.Fatalf("receipt: %v", err)
- }
- if stub.lastPath != "/custom/receipts/rcpt_9" || !strings.Contains(out, "duplicate") || !strings.Contains(out, "fb_0") {
- t.Fatalf("path=%s out=%q", stub.lastPath, out)
- }
-
- _, err = runFeedback(t, "submit", "--target", stub.srv.URL, "--surface", "s", "--category", "bug", "--severity", "low")
- if err == nil || !strings.Contains(err.Error(), "--title") {
- t.Fatalf("expected local required-flag error, got %v", err)
- }
-
- _, err = runFeedback(t, "submit", "--target", "http://127.0.0.1:9", "--surface", "s", "--category", "bug", "--severity", "low", "--title", "t")
- if err == nil || !strings.Contains(err.Error(), "does not advertise feedback.now") {
- t.Fatalf("expected discovery failure, got %v", err)
- }
-}
-
-func TestParseEvidenceFlags(t *testing.T) {
- dir := t.TempDir()
- p := filepath.Join(dir, "err.log")
- os.WriteFile(p, []byte("stack trace"), 0o600)
- ev, err := parseEvidenceFlags([]string{"stderr_excerpt=@" + p, "other=a=b"})
- if err != nil {
- t.Fatal(err)
- }
- if ev[0]["content"] != "stack trace" || ev[1]["type"] != "other" || ev[1]["content"] != "a=b" {
- t.Fatalf("ev = %v", ev)
- }
- if _, err := parseEvidenceFlags([]string{"nope"}); err == nil {
- t.Fatal("expected error for missing =")
- }
-}
diff --git a/cmd/oc/internal/commands/logs.go b/cmd/oc/internal/commands/logs.go
deleted file mode 100644
index 97360aca..00000000
--- a/cmd/oc/internal/commands/logs.go
+++ /dev/null
@@ -1,183 +0,0 @@
-package commands
-
-import (
- "bufio"
- "encoding/json"
- "fmt"
- "io"
- "net/url"
- "os"
- "strconv"
- "strings"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-var logsCmd = &cobra.Command{
- Use: "logs <sandbox-id>",
- Short: "Stream a sandbox's session logs (live tail by default)",
- Long: `Stream logs from a sandbox session — /var/log/* and every exec'd
-command's stdout/stderr — shipped from inside the sandbox to Axiom and
-served back through the control plane.
-
-Default behaviour: tail. Prints the historical batch starting at
-the sandbox's createdAt, then polls forever for new lines until you
-hit Ctrl-C. Stopped/hibernated sandboxes flip to historical-only
-automatically (no new lines will arrive after stop) so --no-tail is
-not strictly needed for those.
-
-Examples:
- oc logs sb-abc # live tail
- oc logs sb-abc --no-tail # one historical batch, then exit
- oc logs sb-abc --since 30m # last 30 minutes
- oc logs sb-abc --grep error # server-side substring filter
- oc logs sb-abc --source exec_stdout,exec_stderr
- oc logs sb-abc --json # raw event JSON, one per line`,
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- ctx := cmd.Context()
- c := client.FromContext(ctx)
- sandboxID := args[0]
-
- noTail, _ := cmd.Flags().GetBool("no-tail")
- since, _ := cmd.Flags().GetString("since")
- until, _ := cmd.Flags().GetString("until")
- grep, _ := cmd.Flags().GetString("grep")
- sources, _ := cmd.Flags().GetStringSlice("source")
- limit, _ := cmd.Flags().GetInt("limit")
- jsonOut, _ := cmd.Flags().GetBool("json")
-
- qs := url.Values{}
- if noTail {
- qs.Set("tail", "false")
- }
- if since != "" {
- // Accept both Go duration (e.g. "30m", "2h") and RFC3339.
- if d, err := time.ParseDuration(since); err == nil {
- qs.Set("since", time.Now().UTC().Add(-d).Format(time.RFC3339))
- } else if _, err := time.Parse(time.RFC3339, since); err == nil {
- qs.Set("since", since)
- } else {
- return fmt.Errorf("--since must be a Go duration (e.g. 30m) or RFC3339 timestamp")
- }
- }
- if until != "" {
- if _, err := time.Parse(time.RFC3339, until); err != nil {
- return fmt.Errorf("--until must be an RFC3339 timestamp")
- }
- qs.Set("until", until)
- }
- if grep != "" {
- qs.Set("q", grep)
- }
- if len(sources) > 0 {
- qs.Set("source", strings.Join(sources, ","))
- }
- if limit > 0 {
- qs.Set("limit", strconv.Itoa(limit))
- }
-
- // client.New() already appends /api to baseURL — use the bare
- // path here, matching the convention in exec/sandbox commands.
- path := "/sandboxes/" + url.PathEscape(sandboxID) + "/logs"
- if encoded := qs.Encode(); encoded != "" {
- path += "?" + encoded
- }
-
- resp, err := c.GetStream(ctx, path)
- if err != nil {
- return err
- }
- defer resp.Body.Close()
- if resp.StatusCode != 200 {
- buf, _ := io.ReadAll(resp.Body)
- return fmt.Errorf("logs request failed (HTTP %d): %s", resp.StatusCode, strings.TrimSpace(string(buf)))
- }
-
- return streamSandboxLogs(resp.Body, os.Stdout, jsonOut)
- },
-}
-
-// logEvent mirrors the on-the-wire shape from internal/api/sandbox_logs.go.
-// Unknown extra fields from server are tolerated by json.Unmarshal.
-type logEvent struct {
- Time time.Time `json:"_time"`
- Source string `json:"source"`
- Line string `json:"line"`
- Path string `json:"path,omitempty"`
- ExecID string `json:"exec_id,omitempty"`
- Command string `json:"command,omitempty"`
- Argv []string `json:"argv,omitempty"`
- ExitCode *int `json:"exit_code,omitempty"`
-}
-
-// streamSandboxLogs parses an SSE stream and writes each event to w.
-// Splits out from the cobra RunE so it's unit-testable.
-func streamSandboxLogs(r io.Reader, w io.Writer, jsonOut bool) error {
- reader := bufio.NewReader(r)
- for {
- line, err := reader.ReadString('\n')
- if line != "" {
- line = strings.TrimRight(line, "\r\n")
- // SSE comments start with ":" — keepalives, errors. Ignore.
- if strings.HasPrefix(line, ":") {
- if err == io.EOF {
- return nil
- }
- continue
- }
- if strings.HasPrefix(line, "data:") {
- payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
- if payload != "" {
- if jsonOut {
- fmt.Fprintln(w, payload)
- } else {
- var ev logEvent
- if jerr := json.Unmarshal([]byte(payload), &ev); jerr == nil {
- renderEvent(w, ev)
- }
- }
- }
- }
- }
- if err != nil {
- if err == io.EOF {
- return nil
- }
- return err
- }
- }
-}
-
-func renderEvent(w io.Writer, ev logEvent) {
- ts := ev.Time.Local().Format("15:04:05.000")
- color := sourceColor(ev.Source)
- fmt.Fprintf(w, "%s %s%-12s\033[0m %s\n", ts, color, ev.Source, ev.Line)
-}
-
-func sourceColor(s string) string {
- switch s {
- case "var_log":
- return "\033[36m" // cyan
- case "exec_stdout":
- return "\033[37m" // light gray
- case "exec_stderr":
- return "\033[31m" // red
- case "agent":
- return "\033[33m" // yellow
- default:
- return "\033[37m"
- }
-}
-
-func init() {
- logsCmd.Flags().Bool("no-tail", false, "exit after the historical batch instead of tailing")
- logsCmd.Flags().String("since", "", "Go duration (e.g. 30m, 2h) or RFC3339 timestamp")
- logsCmd.Flags().String("until", "", "RFC3339 timestamp; ignored when tailing")
- logsCmd.Flags().String("grep", "", "server-side substring filter on the log line")
- logsCmd.Flags().StringSlice("source", nil, "comma-separated filter: var_log, exec_stdout, exec_stderr, agent")
- logsCmd.Flags().Int("limit", 0, "max historical rows (0 = server default of 1000)")
- logsCmd.Flags().Bool("json", false, "emit raw event JSON instead of formatted lines")
-}
diff --git a/cmd/oc/internal/commands/logs_test.go b/cmd/oc/internal/commands/logs_test.go
deleted file mode 100644
index 75228529..00000000
--- a/cmd/oc/internal/commands/logs_test.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package commands
-
-import (
- "bytes"
- "encoding/json"
- "strings"
- "testing"
-)
-
-func TestStreamSandboxLogs_FormattedMode(t *testing.T) {
- sse := "" +
- ": keepalive\n\n" +
- "data: {\"_time\":\"2026-05-13T12:00:00Z\",\"source\":\"var_log\",\"line\":\"hello\"}\n\n" +
- ": ping\n\n" +
- "data: {\"_time\":\"2026-05-13T12:00:01Z\",\"source\":\"exec_stdout\",\"line\":\"world\"}\n\n"
-
- var out bytes.Buffer
- if err := streamSandboxLogs(strings.NewReader(sse), &out, false); err != nil {
- t.Fatalf("stream: %v", err)
- }
- s := out.String()
- for _, want := range []string{"hello", "world", "var_log", "exec_stdout"} {
- if !strings.Contains(s, want) {
- t.Errorf("formatted output missing %q:\n%s", want, s)
- }
- }
-}
-
-func TestStreamSandboxLogs_JSONMode(t *testing.T) {
- payload := `{"_time":"2026-05-13T12:00:00Z","source":"var_log","line":"hello"}`
- sse := "data: " + payload + "\n\n"
-
- var out bytes.Buffer
- if err := streamSandboxLogs(strings.NewReader(sse), &out, true); err != nil {
- t.Fatalf("stream: %v", err)
- }
- // In JSON mode, the payload is printed verbatim. Verify it parses back
- // to the same shape — protects against accidental wrapping/quoting.
- got := strings.TrimSpace(out.String())
- var rt map[string]any
- if err := json.Unmarshal([]byte(got), &rt); err != nil {
- t.Fatalf("output is not valid JSON: %v\n%s", err, got)
- }
- if rt["line"] != "hello" {
- t.Errorf("round-tripped line = %v, want hello", rt["line"])
- }
-}
-
-func TestStreamSandboxLogs_SkipsCommentsAndBlanks(t *testing.T) {
- sse := ": just a keepalive\n\n: another\n\n\n\n"
- var out bytes.Buffer
- if err := streamSandboxLogs(strings.NewReader(sse), &out, false); err != nil {
- t.Fatalf("stream: %v", err)
- }
- if out.Len() != 0 {
- t.Errorf("expected no output for comment-only stream, got: %q", out.String())
- }
-}
-
-func TestStreamSandboxLogs_TolerantOfMalformedPayload(t *testing.T) {
- // A bad payload shouldn't kill the whole stream — subsequent good
- // events should still render.
- sse := "" +
- "data: not-json\n\n" +
- "data: {\"_time\":\"2026-05-13T12:00:00Z\",\"source\":\"var_log\",\"line\":\"after-bad\"}\n\n"
- var out bytes.Buffer
- if err := streamSandboxLogs(strings.NewReader(sse), &out, false); err != nil {
- t.Fatalf("stream: %v", err)
- }
- if !strings.Contains(out.String(), "after-bad") {
- t.Errorf("good event after malformed payload was dropped:\n%s", out.String())
- }
-}
diff --git a/cmd/oc/internal/commands/mounts.go b/cmd/oc/internal/commands/mounts.go
deleted file mode 100644
index b4458628..00000000
--- a/cmd/oc/internal/commands/mounts.go
+++ /dev/null
@@ -1,213 +0,0 @@
-package commands
-
-import (
- "fmt"
- "net/url"
- "os"
- "strings"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-// MountInfo mirrors internal/mounts.MountRecord — copied here to avoid an
-// internal-package import from the CLI binary.
-type MountInfo struct {
- Path string `json:"path"`
- Driver string `json:"driver"`
- ReadOnly bool `json:"readOnly"`
- Remote string `json:"remote,omitempty"`
- Backend string `json:"backend,omitempty"`
- RcloneVersion string `json:"rcloneVersion,omitempty"`
- Command []string `json:"command,omitempty"`
- Env map[string]string `json:"env,omitempty"`
-}
-
-var mountsCmd = &cobra.Command{
- Use: "mounts",
- Aliases: []string{"mount"},
- Short: "Manage FUSE-backed remote filesystem mounts inside a sandbox",
- Long: `Mount remote filesystems (S3, GCS, Azure Blob, SFTP, WebDAV, Dropbox)
-inside a running sandbox via rclone+FUSE. Credentials are passed inline and
-never persisted on the worker. Mounts are torn down on hibernate; v1 does NOT
-auto-restore on wake — re-run "oc mounts add" after waking the sandbox.`,
-}
-
-var mountsAddCmd = &cobra.Command{
- Use: "add <sandbox-id>",
- Short: "Add a mount",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- path, _ := cmd.Flags().GetString("path")
- remote, _ := cmd.Flags().GetString("remote")
- backend, _ := cmd.Flags().GetString("backend")
- credsFlag, _ := cmd.Flags().GetStringArray("cred")
- configFile, _ := cmd.Flags().GetString("config-file")
- readWrite, _ := cmd.Flags().GetBool("read-write")
- extraOpts, _ := cmd.Flags().GetStringArray("opt")
- command, _ := cmd.Flags().GetStringArray("command")
- envFlag, _ := cmd.Flags().GetStringArray("env")
- secretFlag, _ := cmd.Flags().GetStringArray("secret")
-
- body := map[string]any{
- "path": path,
- "readOnly": !readWrite,
- }
-
- if len(command) > 0 {
- // command driver — bring your own FUSE daemon / mount command.
- body["driver"] = "command"
- body["command"] = command
- env, err := parseKV(envFlag, "--env")
- if err != nil {
- return err
- }
- if len(env) > 0 {
- body["env"] = env
- }
- secrets, err := parseKV(secretFlag, "--secret")
- if err != nil {
- return err
- }
- if len(secrets) > 0 {
- body["secrets"] = secrets
- }
- } else {
- // rclone driver (default).
- if remote == "" {
- return fmt.Errorf("--remote is required (or pass --command to run your own FUSE daemon)")
- }
- body["remote"] = remote
- creds, err := parseKV(credsFlag, "--cred")
- if err != nil {
- return err
- }
- if backend != "" {
- body["backend"] = backend
- }
- if len(creds) > 0 {
- body["creds"] = creds
- }
- if configFile != "" {
- raw, err := os.ReadFile(configFile)
- if err != nil {
- return fmt.Errorf("read --config-file: %w", err)
- }
- body["rcloneConfig"] = string(raw)
- }
- if len(extraOpts) > 0 {
- body["mountOptions"] = extraOpts
- }
- }
-
- var info MountInfo
- if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/mounts", args[0]), body, &info); err != nil {
- return err
- }
-
- printer.Print(info, func() {
- ro := "rw"
- if info.ReadOnly {
- ro = "ro"
- }
- src := info.Remote
- if info.Driver == "command" {
- src = strings.Join(info.Command, " ")
- }
- fmt.Printf("Mounted %s → %s (%s)\n", src, info.Path, ro)
- })
- return nil
- },
-}
-
-var mountsListCmd = &cobra.Command{
- Use: "list <sandbox-id>",
- Short: "List mounts for a sandbox",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var mounts []MountInfo
- if err := c.Get(cmd.Context(), fmt.Sprintf("/sandboxes/%s/mounts", args[0]), &mounts); err != nil {
- return err
- }
-
- printer.Print(mounts, func() {
- if len(mounts) == 0 {
- fmt.Println("No mounts.")
- return
- }
- headers := []string{"PATH", "DRIVER", "SOURCE", "MODE"}
- var rows [][]string
- for _, m := range mounts {
- mode := "rw"
- if m.ReadOnly {
- mode = "ro"
- }
- driver := m.Driver
- if driver == "" {
- driver = "rclone"
- }
- source := m.Remote
- if m.Driver == "command" {
- source = strings.Join(m.Command, " ")
- }
- rows = append(rows, []string{m.Path, driver, source, mode})
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var mountsRemoveCmd = &cobra.Command{
- Use: "rm <sandbox-id> <path>",
- Aliases: []string{"remove"},
- Short: "Unmount a path in a sandbox",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- target := args[1]
- ep := fmt.Sprintf("/sandboxes/%s/mounts?path=%s", args[0], url.QueryEscape(target))
- if err := c.DeleteIgnoreNotFound(cmd.Context(), ep); err != nil {
- return err
- }
- fmt.Printf("Unmounted %s.\n", target)
- return nil
- },
-}
-
-// parseKV turns repeated "key=value" flag values into a map.
-func parseKV(pairs []string, flag string) (map[string]string, error) {
- out := map[string]string{}
- for _, kv := range pairs {
- i := strings.Index(kv, "=")
- if i <= 0 {
- return nil, fmt.Errorf("%s must be key=value (got %q)", flag, kv)
- }
- out[kv[:i]] = kv[i+1:]
- }
- return out, nil
-}
-
-func init() {
- mountsAddCmd.Flags().String("path", "", "Absolute path inside the sandbox to mount at (required)")
- // rclone driver (default)
- mountsAddCmd.Flags().String("remote", "", "rclone remote spec, e.g. s3:my-bucket (rclone driver)")
- mountsAddCmd.Flags().String("backend", "", "Backend type: s3, gcs, azureblob, sftp, webdav, dropbox")
- mountsAddCmd.Flags().StringArray("cred", nil, "Backend credential as key=value (repeatable; e.g. --cred access_key_id=AKIA...)")
- mountsAddCmd.Flags().String("config-file", "", "Path to a raw rclone config file (overrides --backend/--cred)")
- mountsAddCmd.Flags().StringArray("opt", nil, "Extra args appended to `rclone mount` (repeatable)")
- // command driver (bring your own FUSE)
- mountsAddCmd.Flags().StringArray("command", nil, "FUSE daemon/mount argv (repeatable; switches to the command driver). {mountpoint} is replaced with --path")
- mountsAddCmd.Flags().StringArray("env", nil, "Env var for the command as key=value (repeatable)")
- mountsAddCmd.Flags().StringArray("secret", nil, "Secret env var as key=value (repeatable; injected into the daemon env, never recorded)")
- mountsAddCmd.Flags().Bool("read-write", false, "Mount read-write (default is read-only)")
- _ = mountsAddCmd.MarkFlagRequired("path")
-
- mountsCmd.AddCommand(mountsAddCmd)
- mountsCmd.AddCommand(mountsListCmd)
- mountsCmd.AddCommand(mountsRemoveCmd)
-}
diff --git a/cmd/oc/internal/commands/patch.go b/cmd/oc/internal/commands/patch.go
deleted file mode 100644
index 4278f867..00000000
--- a/cmd/oc/internal/commands/patch.go
+++ /dev/null
@@ -1,135 +0,0 @@
-package commands
-
-import (
- "fmt"
- "io"
- "os"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-// PatchInfo matches the API response for checkpoint patches.
-type PatchInfo struct {
- ID string `json:"id"`
- CheckpointID string `json:"checkpointId"`
- Sequence int `json:"sequence"`
- Script string `json:"script"`
- Description string `json:"description"`
- Strategy string `json:"strategy"`
- CreatedAt time.Time `json:"createdAt"`
-}
-
-// PatchResult wraps the create response.
-type PatchResult struct {
- Patch PatchInfo `json:"patch"`
-}
-
-var patchCmd = &cobra.Command{
- Use: "patch",
- Short: "Manage checkpoint patches",
-}
-
-var patchCreateCmd = &cobra.Command{
- Use: "create <checkpoint-id>",
- Short: "Create a patch for a checkpoint",
- Long: `Create a patch script that will be applied when sandboxes are spawned from this checkpoint.
-
-Examples:
- oc patch create <cp-id> --script=./setup.sh --description="Install deps"
- echo "apt install -y curl" | oc patch create <cp-id> --script=-`,
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- scriptPath, _ := cmd.Flags().GetString("script")
- description, _ := cmd.Flags().GetString("description")
-
- var script string
- if scriptPath == "-" {
- data, err := io.ReadAll(os.Stdin)
- if err != nil {
- return fmt.Errorf("reading stdin: %w", err)
- }
- script = string(data)
- } else {
- data, err := os.ReadFile(scriptPath)
- if err != nil {
- return fmt.Errorf("reading script file: %w", err)
- }
- script = string(data)
- }
-
- req := map[string]string{
- "script": script,
- "description": description,
- }
- var result PatchResult
- if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/checkpoints/%s/patches", args[0]), req, &result); err != nil {
- return err
- }
-
- printer.Print(result, func() {
- fmt.Printf("Patch created: %s (sequence: %d)\n", result.Patch.ID, result.Patch.Sequence)
- })
- return nil
- },
-}
-
-var patchListCmd = &cobra.Command{
- Use: "list <checkpoint-id>",
- Short: "List patches for a checkpoint",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var patches []PatchInfo
- if err := c.Get(cmd.Context(), fmt.Sprintf("/sandboxes/checkpoints/%s/patches", args[0]), &patches); err != nil {
- return err
- }
-
- printer.Print(patches, func() {
- if len(patches) == 0 {
- fmt.Println("No patches found.")
- return
- }
- headers := []string{"ID", "SEQ", "DESCRIPTION", "STRATEGY", "CREATED"}
- var rows [][]string
- for _, p := range patches {
- rows = append(rows, []string{
- p.ID,
- fmt.Sprintf("%d", p.Sequence),
- p.Description,
- p.Strategy,
- p.CreatedAt.Format(time.RFC3339),
- })
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var patchDeleteCmd = &cobra.Command{
- Use: "delete <checkpoint-id> <patch-id>",
- Short: "Delete a patch",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- if err := c.DeleteIgnoreNotFound(cmd.Context(), fmt.Sprintf("/sandboxes/checkpoints/%s/patches/%s", args[0], args[1])); err != nil {
- return err
- }
- fmt.Printf("Patch %s deleted.\n", args[1])
- return nil
- },
-}
-
-func init() {
- patchCreateCmd.Flags().String("script", "", "Path to script file, or '-' for stdin (required)")
- patchCreateCmd.Flags().String("description", "", "Description of the patch")
- patchCreateCmd.MarkFlagRequired("script")
-
- patchCmd.AddCommand(patchCreateCmd)
- patchCmd.AddCommand(patchListCmd)
- patchCmd.AddCommand(patchDeleteCmd)
-}
diff --git a/cmd/oc/internal/commands/preview.go b/cmd/oc/internal/commands/preview.go
deleted file mode 100644
index 7bbf5bc0..00000000
--- a/cmd/oc/internal/commands/preview.go
+++ /dev/null
@@ -1,148 +0,0 @@
-package commands
-
-import (
- "fmt"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-// PreviewURL matches the API response for preview URLs.
-type PreviewURL struct {
- ID string `json:"id"`
- SandboxID string `json:"sandboxId"`
- OrgID string `json:"orgId"`
- Hostname string `json:"hostname"`
- CustomHostname string `json:"customHostname,omitempty"`
- Port int `json:"port"`
- CfHostnameID string `json:"cfHostnameId,omitempty"`
- SSLStatus string `json:"sslStatus"`
- AuthConfig map[string]any `json:"authConfig,omitempty"`
- CreatedAt time.Time `json:"createdAt"`
-}
-
-var previewCmd = &cobra.Command{
- Use: "preview",
- Short: "Manage sandbox preview URLs",
-}
-
-var previewCreateCmd = &cobra.Command{
- Use: "create <sandbox-id>",
- Short: "Create a preview URL for a sandbox port",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- port, _ := cmd.Flags().GetInt("port")
- domain, _ := cmd.Flags().GetString("domain")
-
- req := map[string]any{
- "port": port,
- "authConfig": map[string]any{},
- }
- if domain != "" {
- req["domain"] = domain
- }
-
- var preview PreviewURL
- if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/preview", args[0]), req, &preview); err != nil {
- return err
- }
-
- printer.Print(preview, func() {
- fmt.Printf("Preview URL created:\n")
- fmt.Printf(" Hostname: %s\n", preview.Hostname)
- fmt.Printf(" Port: %d\n", preview.Port)
- fmt.Printf(" SSL: %s\n", preview.SSLStatus)
- if preview.CustomHostname != "" {
- fmt.Printf(" Custom: %s\n", preview.CustomHostname)
- }
- })
- return nil
- },
-}
-
-var previewListCmd = &cobra.Command{
- Use: "list <sandbox-id>",
- Short: "List preview URLs for a sandbox",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var previews []PreviewURL
- if err := c.Get(cmd.Context(), fmt.Sprintf("/sandboxes/%s/preview", args[0]), &previews); err != nil {
- return err
- }
-
- printer.Print(previews, func() {
- if len(previews) == 0 {
- fmt.Println("No preview URLs found.")
- return
- }
- headers := []string{"PORT", "HOSTNAME", "SSL", "CREATED"}
- var rows [][]string
- for _, p := range previews {
- hostname := p.Hostname
- if p.CustomHostname != "" {
- hostname = p.CustomHostname
- }
- rows = append(rows, []string{
- fmt.Sprintf("%d", p.Port),
- hostname,
- p.SSLStatus,
- p.CreatedAt.Format(time.RFC3339),
- })
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var previewDeleteCmd = &cobra.Command{
- Use: "delete <sandbox-id> <port>",
- Short: "Delete a preview URL",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- if err := c.DeleteIgnoreNotFound(cmd.Context(), fmt.Sprintf("/sandboxes/%s/preview/%s", args[0], args[1])); err != nil {
- return err
- }
- fmt.Printf("Preview URL for port %s deleted.\n", args[1])
- return nil
- },
-}
-
-// previewRotateAuthCmd issues a fresh bearer token for the sandbox's
-// edge-enforced preview-URL auth gate. The old token stops working
-// immediately — no dual-token grace period in v1.
-var previewRotateAuthCmd = &cobra.Command{
- Use: "rotate-auth <sandbox-id>",
- Short: "Rotate the sandbox's preview-URL bearer token",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- var resp struct {
- PreviewAuthToken string `json:"previewAuthToken"`
- Scheme string `json:"scheme"`
- }
- if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/preview/rotate", args[0]), nil, &resp); err != nil {
- return err
- }
- printer.Print(resp, func() {
- fmt.Printf("New preview auth token (shown once): %s\n", resp.PreviewAuthToken)
- })
- return nil
- },
-}
-
-func init() {
- previewCreateCmd.Flags().Int("port", 0, "Container port to expose (required)")
- previewCreateCmd.Flags().String("domain", "", "Custom domain")
- previewCreateCmd.MarkFlagRequired("port")
-
- previewCmd.AddCommand(previewCreateCmd)
- previewCmd.AddCommand(previewListCmd)
- previewCmd.AddCommand(previewDeleteCmd)
- previewCmd.AddCommand(previewRotateAuthCmd)
-}
diff --git a/cmd/oc/internal/commands/project.go b/cmd/oc/internal/commands/project.go
deleted file mode 100644
index 816ef8c7..00000000
--- a/cmd/oc/internal/commands/project.go
+++ /dev/null
@@ -1,179 +0,0 @@
-package commands
-
-import (
- "fmt"
- "strings"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-type secretStoreInfo struct {
- ID string `json:"id"`
- OrgID string `json:"orgId"`
- Name string `json:"name"`
- EgressAllowlist []string `json:"egressAllowlist"`
- CreatedAt string `json:"createdAt"`
- UpdatedAt string `json:"updatedAt"`
-}
-
-var secretStoreCmd = &cobra.Command{
- Use: "secret-store",
- Short: "Manage secret stores",
-}
-
-var secretStoreCreateCmd = &cobra.Command{
- Use: "create",
- Short: "Create a new secret store",
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- name, _ := cmd.Flags().GetString("name")
- allowlist, _ := cmd.Flags().GetStringSlice("egress-allowlist")
-
- if name == "" {
- return fmt.Errorf("--name is required")
- }
-
- body := map[string]interface{}{"name": name}
- if len(allowlist) > 0 {
- body["egressAllowlist"] = allowlist
- }
-
- var store secretStoreInfo
- if err := c.Post(cmd.Context(), "/secret-stores", body, &store); err != nil {
- return err
- }
-
- printer.Print(store, func() {
- fmt.Printf("Created secret store %s (id: %s)\n", store.Name, store.ID)
- })
- return nil
- },
-}
-
-var secretStoreListCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List secret stores",
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var stores []secretStoreInfo
- if err := c.Get(cmd.Context(), "/secret-stores", &stores); err != nil {
- return err
- }
-
- printer.Print(stores, func() {
- if len(stores) == 0 {
- fmt.Println("No secret stores found.")
- return
- }
- headers := []string{"ID", "NAME", "EGRESS ALLOWLIST", "CREATED"}
- var rows [][]string
- for _, s := range stores {
- created := s.CreatedAt
- if t, err := time.Parse(time.RFC3339Nano, s.CreatedAt); err == nil {
- created = time.Since(t).Truncate(time.Second).String() + " ago"
- }
- egress := "(all)"
- if len(s.EgressAllowlist) > 0 {
- egress = strings.Join(s.EgressAllowlist, ", ")
- }
- rows = append(rows, []string{
- s.ID,
- s.Name,
- egress,
- created,
- })
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var secretStoreGetCmd = &cobra.Command{
- Use: "get <store-id>",
- Short: "Get secret store details",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var store secretStoreInfo
- if err := c.Get(cmd.Context(), "/secret-stores/"+args[0], &store); err != nil {
- return err
- }
-
- printer.Print(store, func() {
- fmt.Printf("ID: %s\n", store.ID)
- fmt.Printf("Name: %s\n", store.Name)
- if len(store.EgressAllowlist) > 0 {
- fmt.Printf("Egress: %s\n", strings.Join(store.EgressAllowlist, ", "))
- }
- })
- return nil
- },
-}
-
-var secretStoreUpdateCmd = &cobra.Command{
- Use: "update <store-id>",
- Short: "Update a secret store",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- body := map[string]interface{}{}
- if cmd.Flags().Changed("name") {
- v, _ := cmd.Flags().GetString("name")
- body["name"] = v
- }
- if cmd.Flags().Changed("egress-allowlist") {
- v, _ := cmd.Flags().GetStringSlice("egress-allowlist")
- body["egressAllowlist"] = v
- }
-
- if len(body) == 0 {
- return fmt.Errorf("no fields to update (use --name, --egress-allowlist)")
- }
-
- var store secretStoreInfo
- if err := c.PutJSON(cmd.Context(), "/secret-stores/"+args[0], body, &store); err != nil {
- return err
- }
-
- printer.Print(store, func() {
- fmt.Printf("Updated secret store %s\n", store.Name)
- })
- return nil
- },
-}
-
-var secretStoreDeleteCmd = &cobra.Command{
- Use: "delete <store-id>",
- Short: "Delete a secret store and all its secrets",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- if err := c.Delete(cmd.Context(), "/secret-stores/"+args[0]); err != nil {
- return err
- }
- fmt.Printf("Secret store %s deleted.\n", args[0])
- return nil
- },
-}
-
-func init() {
- secretStoreCreateCmd.Flags().String("name", "", "Store name (required)")
- secretStoreCreateCmd.Flags().StringSlice("egress-allowlist", nil, "Allowed egress hosts")
-
- secretStoreUpdateCmd.Flags().String("name", "", "Store name")
- secretStoreUpdateCmd.Flags().StringSlice("egress-allowlist", nil, "Allowed egress hosts")
-
- secretStoreCmd.AddCommand(secretStoreCreateCmd)
- secretStoreCmd.AddCommand(secretStoreListCmd)
- secretStoreCmd.AddCommand(secretStoreGetCmd)
- secretStoreCmd.AddCommand(secretStoreUpdateCmd)
- secretStoreCmd.AddCommand(secretStoreDeleteCmd)
-}
diff --git a/cmd/oc/internal/commands/root.go b/cmd/oc/internal/commands/root.go
deleted file mode 100644
index 3b1cfd07..00000000
--- a/cmd/oc/internal/commands/root.go
+++ /dev/null
@@ -1,99 +0,0 @@
-package commands
-
-import (
- "fmt"
- "os"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/config"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/output"
- "github.com/spf13/cobra"
-)
-
-// Version is set at build time via ldflags.
-var Version = "dev"
-
-var (
- jsonOutput bool
- noColor bool
- printer *output.Printer
-)
-
-var rootCmd = &cobra.Command{
- Use: "oc",
- Short: "OpenComputer CLI — manage cloud sandboxes",
- Long: "Command-line interface for creating and managing OpenComputer sandboxes.",
- Version: Version,
- PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
- cfg := config.Load(cmd)
- if cfg.APIKey == "" && !isOfflineCommand(cmd) && cmd.Name() != "login" && cmd.Name() != "logout" && cmd.Name() != "whoami" && cmd.Name() != "config" && cmd.Name() != "help" && cmd.Name() != "set" && cmd.Name() != "show" {
- fmt.Fprintln(os.Stderr, "Warning: no API key configured. Run 'oc login' or set OPENCOMPUTER_API_KEY")
- }
- c := client.New(cfg.APIURL, cfg.APIKey)
- ctx := client.WithClient(cmd.Context(), c)
-
- // Set up sessions-api client (defaults to api.opencomputer.dev)
- sc := client.NewSessionsAPI(cfg.SessionsAPIURL, cfg.APIKey)
- ctx = client.WithSessionsClient(ctx, sc)
-
- cmd.SetContext(ctx)
- printer = output.New(jsonOutput)
- return nil
- },
- PersistentPostRun: func(cmd *cobra.Command, args []string) {
- if isOfflineCommand(cmd) {
- return
- }
- // One-line nag to stderr when a newer release is available. Skip
- // for `oc update` itself, help, and completion scaffolding — see
- // maybePromptUpdate for the full skip list (dev build, non-TTY,
- // OC_NO_UPDATE_CHECK).
- switch cmd.Name() {
- case "login", "update", "help", "completion", "__complete":
- return
- }
- maybePromptUpdate()
- },
- SilenceUsage: true,
- SilenceErrors: true,
-}
-
-func isOfflineCommand(cmd *cobra.Command) bool {
- return cmd.Annotations != nil && cmd.Annotations[offlineCommandAnnotation] == "true"
-}
-
-func init() {
- rootCmd.PersistentFlags().BoolVar(&jsonOutput, "json", false, "Output as JSON")
- rootCmd.PersistentFlags().BoolVar(&noColor, "no-color", false, "Disable colored output")
- rootCmd.PersistentFlags().String("api-key", "", "API key (overrides OPENCOMPUTER_API_KEY)")
- rootCmd.PersistentFlags().String("api-url", "", "API URL (overrides OPENCOMPUTER_API_URL)")
- rootCmd.PersistentFlags().String("sessions-api-url", "", "Sessions API URL (overrides SESSIONS_API_URL)")
-
- // Register command groups
- rootCmd.AddCommand(sandboxCmd)
- rootCmd.AddCommand(execCmd)
- rootCmd.AddCommand(shellCmd)
- rootCmd.AddCommand(checkpointCmd)
- rootCmd.AddCommand(templateCmd)
- rootCmd.AddCommand(patchCmd)
- rootCmd.AddCommand(previewCmd)
- rootCmd.AddCommand(mountsCmd)
- rootCmd.AddCommand(secretStoreCmd)
- rootCmd.AddCommand(secretCmd)
- rootCmd.AddCommand(configCmd)
- rootCmd.AddCommand(agentCmd)
- rootCmd.AddCommand(logsCmd)
- rootCmd.AddCommand(feedbackCmd)
- rootCmd.AddCommand(loginCmd)
- rootCmd.AddCommand(whoamiCmd)
- rootCmd.AddCommand(logoutCmd)
-
- // Top-level shortcuts
- rootCmd.AddCommand(createShortcut)
- rootCmd.AddCommand(lsShortcut)
-}
-
-// Execute runs the root command.
-func Execute() error {
- return rootCmd.Execute()
-}
diff --git a/cmd/oc/internal/commands/sandbox.go b/cmd/oc/internal/commands/sandbox.go
deleted file mode 100644
index 0bad5e54..00000000
--- a/cmd/oc/internal/commands/sandbox.go
+++ /dev/null
@@ -1,332 +0,0 @@
-package commands
-
-import (
- "fmt"
- "strings"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/pkg/types"
- "github.com/spf13/cobra"
-)
-
-var sandboxCmd = &cobra.Command{
- Use: "sandbox",
- Short: "Manage sandboxes",
-}
-
-var sandboxCreateCmd = &cobra.Command{
- Use: "create",
- Short: "Create a new sandbox",
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- timeout, _ := cmd.Flags().GetInt("timeout")
- cpu, _ := cmd.Flags().GetInt("cpu")
- memory, _ := cmd.Flags().GetInt("memory")
- envSlice, _ := cmd.Flags().GetStringSlice("env")
- metaSlice, _ := cmd.Flags().GetStringSlice("metadata")
- secretStore, _ := cmd.Flags().GetString("secret-store")
- previewAuth, _ := cmd.Flags().GetBool("preview-auth")
- previewAuthToken, _ := cmd.Flags().GetString("preview-auth-token")
-
- config := types.SandboxConfig{
- Timeout: timeout,
- CpuCount: cpu,
- MemoryMB: memory,
- Envs: parseKVSlice(envSlice),
- Metadata: parseKVSlice(metaSlice),
- }
-
- // Build request body — include secret store if set
- body := map[string]interface{}{
- "timeout": config.Timeout,
- }
- if config.CpuCount > 0 {
- body["cpuCount"] = config.CpuCount
- }
- if config.MemoryMB > 0 {
- body["memoryMB"] = config.MemoryMB
- }
- if config.Envs != nil {
- body["envs"] = config.Envs
- }
- if config.Metadata != nil {
- body["metadata"] = config.Metadata
- }
- if secretStore != "" {
- body["secretStore"] = secretStore
- }
- // --preview-auth-token implies --preview-auth. Either flag attaches the
- // previewAuth block to the create payload; only the token-having flag
- // supplies a caller-chosen secret. The plaintext is returned exactly
- // once via the sandbox response's PreviewAuthToken field; print it
- // prominently so a piped/scripted caller can capture it.
- if previewAuth || previewAuthToken != "" {
- pa := map[string]string{"scheme": "bearer"}
- if previewAuthToken != "" {
- pa["token"] = previewAuthToken
- } else {
- pa["token"] = "auto"
- }
- body["previewAuth"] = pa
- }
-
- var sandbox types.Sandbox
- if err := c.Post(cmd.Context(), "/sandboxes", body, &sandbox); err != nil {
- return err
- }
-
- printer.Print(sandbox, func() {
- fmt.Printf("Created sandbox %s (status: %s)\n", sandbox.ID, sandbox.Status)
- if sandbox.PreviewAuthToken != "" {
- fmt.Printf("Preview auth token (shown once): %s\n", sandbox.PreviewAuthToken)
- }
- })
- return nil
- },
-}
-
-var sandboxListCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List sandboxes",
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var sandboxes []types.Sandbox
- if err := c.Get(cmd.Context(), "/sandboxes", &sandboxes); err != nil {
- return err
- }
-
- printer.Print(sandboxes, func() {
- if len(sandboxes) == 0 {
- fmt.Println("No sandboxes found.")
- return
- }
- headers := []string{"ID", "TEMPLATE", "STATUS", "CPU", "MEM", "AGE"}
- var rows [][]string
- for _, s := range sandboxes {
- age := time.Since(s.StartedAt).Truncate(time.Second).String()
- rows = append(rows, []string{
- s.ID,
- s.Template,
- string(s.Status),
- fmt.Sprintf("%d", s.CpuCount),
- fmt.Sprintf("%dMB", s.MemoryMB),
- age,
- })
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var sandboxGetCmd = &cobra.Command{
- Use: "get <sandbox-id>",
- Short: "Get sandbox details",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var sandbox types.Sandbox
- if err := c.Get(cmd.Context(), "/sandboxes/"+args[0], &sandbox); err != nil {
- return err
- }
-
- printer.Print(sandbox, func() {
- fmt.Printf("ID: %s\n", sandbox.ID)
- fmt.Printf("Template: %s\n", sandbox.Template)
- fmt.Printf("Status: %s\n", sandbox.Status)
- fmt.Printf("CPU: %d\n", sandbox.CpuCount)
- fmt.Printf("Memory: %dMB\n", sandbox.MemoryMB)
- fmt.Printf("Started: %s\n", sandbox.StartedAt.Format(time.RFC3339))
- fmt.Printf("Ends: %s\n", sandbox.EndAt.Format(time.RFC3339))
- })
- return nil
- },
-}
-
-var sandboxKillCmd = &cobra.Command{
- Use: "kill <sandbox-id>",
- Short: "Kill and remove a sandbox",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- path := "/sandboxes/" + args[0]
- deleteSecretStore, _ := cmd.Flags().GetBool("delete-secret-store")
- if deleteSecretStore {
- path += "?deleteSecretStore=true"
- }
- if err := c.Delete(cmd.Context(), path); err != nil {
- return err
- }
- fmt.Printf("Sandbox %s killed.\n", args[0])
- return nil
- },
-}
-
-var sandboxHibernateCmd = &cobra.Command{
- Use: "hibernate <sandbox-id>",
- Short: "Hibernate a sandbox",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var info types.HibernationInfo
- if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/hibernate", nil, &info); err != nil {
- return err
- }
-
- printer.Print(info, func() {
- fmt.Printf("Sandbox %s hibernated.\n", args[0])
- if info.SizeBytes > 0 {
- fmt.Printf("Size: %.1f MB\n", float64(info.SizeBytes)/1024/1024)
- }
- })
- return nil
- },
-}
-
-var sandboxWakeCmd = &cobra.Command{
- Use: "wake <sandbox-id>",
- Short: "Wake a hibernated sandbox",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- timeout, _ := cmd.Flags().GetInt("timeout")
-
- req := types.WakeRequest{Timeout: timeout}
- var sandbox types.Sandbox
- if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/wake", req, &sandbox); err != nil {
- return err
- }
-
- printer.Print(sandbox, func() {
- fmt.Printf("Sandbox %s woke up (status: %s)\n", sandbox.ID, sandbox.Status)
- })
- return nil
- },
-}
-
-var sandboxRebootCmd = &cobra.Command{
- Use: "reboot <sandbox-id>",
- Short: "Soft restart of a running sandbox (guest-only kernel reboot, disks preserved)",
- Long: `Soft restart of a running sandbox via in-guest reset.
-
-The QEMU process, network mapping, and persistent disks all stay; only
-the guest CPU is reset and the kernel reboots from scratch. Recovers
-from in-guest wedges: zombie pile-ups, OOM-killed agents, runaway
-processes, broken-but-isolated systemd state.
-
-For the rare case where the QEMU process itself is wedged, use
-'oc sandbox power-cycle' instead.`,
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/reboot", nil, nil); err != nil {
- return err
- }
- fmt.Printf("Sandbox %s rebooted.\n", args[0])
- return nil
- },
-}
-
-var sandboxPowerCycleCmd = &cobra.Command{
- Use: "power-cycle <sandbox-id>",
- Short: "Hard restart of a sandbox (kill QEMU + cold-boot, drives preserved)",
- Long: `Hard restart of a sandbox.
-
-The QEMU process is killed and a fresh one is started with the same
-on-disk drives (rootfs.qcow2 + workspace.qcow2). The sandbox keeps its
-ID, project, secrets, env, and persistent workspace data; gets a new
-external host port and TAP. Use when the QEMU process itself is wedged
-or 'oc sandbox reboot' didn't recover.`,
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/power-cycle", nil, nil); err != nil {
- return err
- }
- fmt.Printf("Sandbox %s power-cycled.\n", args[0])
- return nil
- },
-}
-
-var sandboxSetTimeoutCmd = &cobra.Command{
- Use: "set-timeout <sandbox-id> <seconds>",
- Short: "Update sandbox timeout",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var timeout int
- if _, err := fmt.Sscanf(args[1], "%d", &timeout); err != nil {
- return fmt.Errorf("invalid timeout: %s", args[1])
- }
-
- req := types.TimeoutRequest{Timeout: timeout}
- if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/timeout", req, nil); err != nil {
- return err
- }
-
- fmt.Printf("Timeout updated to %ds for sandbox %s\n", timeout, args[0])
- return nil
- },
-}
-
-// Top-level shortcuts
-var createShortcut = &cobra.Command{
- Use: "create",
- Short: "Create a new sandbox (shortcut for 'sandbox create')",
- RunE: sandboxCreateCmd.RunE,
-}
-
-var lsShortcut = &cobra.Command{
- Use: "ls",
- Short: "List sandboxes (shortcut for 'sandbox list')",
- RunE: sandboxListCmd.RunE,
-}
-
-func init() {
- // sandbox create flags
- for _, cmd := range []*cobra.Command{sandboxCreateCmd, createShortcut} {
- cmd.Flags().Int("timeout", 0, "Idle timeout in seconds before auto-hibernate (0 = never hibernate)")
- cmd.Flags().Int("cpu", 0, "CPU count")
- cmd.Flags().Int("memory", 0, "Memory in MB")
- cmd.Flags().StringSlice("env", nil, "Environment variables (KEY=VALUE)")
- cmd.Flags().StringSlice("metadata", nil, "Metadata (KEY=VALUE)")
- cmd.Flags().String("secret-store", "", "Secret store name (injects encrypted secrets)")
- cmd.Flags().Bool("preview-auth", false, "Require a bearer token on the sandbox's preview URLs (server generates a 256-bit token, printed once)")
- cmd.Flags().String("preview-auth-token", "", "Bring your own preview-URL bearer token (>=16 chars); implies --preview-auth")
- }
-
- // sandbox wake flags
- sandboxWakeCmd.Flags().Int("timeout", 0, "Idle timeout in seconds after wake (0 = never hibernate)")
- sandboxKillCmd.Flags().Bool("delete-secret-store", false, "Also delete the secret store attached to the sandbox")
-
- sandboxCmd.AddCommand(sandboxCreateCmd)
- sandboxCmd.AddCommand(sandboxListCmd)
- sandboxCmd.AddCommand(sandboxGetCmd)
- sandboxCmd.AddCommand(sandboxKillCmd)
- sandboxCmd.AddCommand(sandboxHibernateCmd)
- sandboxCmd.AddCommand(sandboxWakeCmd)
- sandboxCmd.AddCommand(sandboxRebootCmd)
- sandboxCmd.AddCommand(sandboxPowerCycleCmd)
- sandboxCmd.AddCommand(sandboxSetTimeoutCmd)
-}
-
-func parseKVSlice(kvs []string) map[string]string {
- if len(kvs) == 0 {
- return nil
- }
- m := make(map[string]string)
- for _, kv := range kvs {
- parts := strings.SplitN(kv, "=", 2)
- if len(parts) == 2 {
- m[parts[0]] = parts[1]
- }
- }
- return m
-}
diff --git a/cmd/oc/internal/commands/scaling.go b/cmd/oc/internal/commands/scaling.go
deleted file mode 100644
index 29741b4c..00000000
--- a/cmd/oc/internal/commands/scaling.go
+++ /dev/null
@@ -1,206 +0,0 @@
-package commands
-
-import (
- "fmt"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-var sandboxScaleCmd = &cobra.Command{
- Use: "scale <sandbox-id> <memory-mb>",
- Short: "Manually resize a sandbox",
- Long: `Manually resize a sandbox to a specific memory tier. CPU follows memory
-per the platform's tier table (e.g. 8 GB → 2 vCPU, 16 GB → 4 vCPU). Allowed tiers:
-1024, 4096, 8192, 16384 MB. Contact us for enterprise sizing above 16 GB.
-
-A manual scale disables autoscale on this sandbox as a side effect; re-
-enable with 'oc sandbox autoscale --on' if you want it back.
-
-Errors:
- scaling_locked Sandbox has a scaling lock — unlock first.
- 402 Payment... Requested size exceeds your plan cap.`,
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var memoryMB int
- if _, err := fmt.Sscanf(args[1], "%d", &memoryMB); err != nil || memoryMB <= 0 {
- return fmt.Errorf("invalid memory-mb: %s", args[1])
- }
-
- var resp struct {
- SandboxID string `json:"sandboxID"`
- MemoryMB int `json:"memoryMB"`
- CPUPercent int `json:"cpuPercent"`
- }
- if err := c.Post(cmd.Context(), "/sandboxes/"+args[0]+"/scale", map[string]int{"memoryMB": memoryMB}, &resp); err != nil {
- return err
- }
-
- printer.Print(resp, func() {
- fmt.Printf("Scaled %s to %dMB / %d%% CPU\n", resp.SandboxID, resp.MemoryMB, resp.CPUPercent)
- })
- return nil
- },
-}
-
-var sandboxAutoscaleCmd = &cobra.Command{
- Use: "autoscale <sandbox-id>",
- Short: "Configure or inspect per-sandbox autoscale",
- Long: `Configure or inspect per-sandbox autoscale.
-
-Run with no flags to print the current configuration.
-Use --on with --min/--max to enable; --off to disable.
-
-When enabled, the platform resizes the sandbox between min and max based
-on observed memory pressure: scale up fast on a 1-min spike (>75%), scale
-down only after sustained idle (1m + 5m + 15m all below 25%, 5-min
-cooldown).
-
-Errors:
- scaling_locked Sandbox has a scaling lock — unlock first to enable.
- 402 Payment... --max exceeds your plan cap.`,
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- on, _ := cmd.Flags().GetBool("on")
- off, _ := cmd.Flags().GetBool("off")
- minMB, _ := cmd.Flags().GetInt("min")
- maxMB, _ := cmd.Flags().GetInt("max")
-
- // No flags → status
- if !on && !off && minMB == 0 && maxMB == 0 {
- var status struct {
- SandboxID string `json:"sandboxID"`
- Enabled bool `json:"enabled"`
- MinMemoryMB int `json:"minMemoryMB"`
- MaxMemoryMB int `json:"maxMemoryMB"`
- }
- if err := c.Get(cmd.Context(), "/sandboxes/"+args[0]+"/autoscale", &status); err != nil {
- return err
- }
- printer.Print(status, func() {
- if status.Enabled {
- fmt.Printf("Autoscale enabled for %s (%d–%d MB)\n", status.SandboxID, status.MinMemoryMB, status.MaxMemoryMB)
- } else {
- fmt.Printf("Autoscale disabled for %s\n", status.SandboxID)
- }
- })
- return nil
- }
-
- if on && off {
- return fmt.Errorf("--on and --off are mutually exclusive")
- }
-
- body := map[string]interface{}{"enabled": on}
- if on {
- if minMB == 0 || maxMB == 0 {
- return fmt.Errorf("--on requires both --min and --max")
- }
- body["minMemoryMB"] = minMB
- body["maxMemoryMB"] = maxMB
- }
-
- var resp struct {
- SandboxID string `json:"sandboxID"`
- Enabled bool `json:"enabled"`
- MinMemoryMB int `json:"minMemoryMB"`
- MaxMemoryMB int `json:"maxMemoryMB"`
- }
- if err := c.PutJSON(cmd.Context(), "/sandboxes/"+args[0]+"/autoscale", body, &resp); err != nil {
- return err
- }
- printer.Print(resp, func() {
- if resp.Enabled {
- fmt.Printf("Autoscale enabled for %s (%d–%d MB)\n", resp.SandboxID, resp.MinMemoryMB, resp.MaxMemoryMB)
- } else {
- fmt.Printf("Autoscale disabled for %s\n", resp.SandboxID)
- }
- })
- return nil
- },
-}
-
-var sandboxLockCmd = &cobra.Command{
- Use: "lock <sandbox-id>",
- Short: "Pin a sandbox at its current size (block scaling)",
- Long: `Lock the sandbox against any size change. While locked, both 'scale'
-and 'autoscale --on' are rejected with a scaling_locked error, and the
-platform autoscaler skips the sandbox entirely.
-
-Locking ALSO disables autoscale (single-knob: "I don't want this scaling,
-period"). Unlocking does NOT re-enable autoscale; run 'autoscale --on'
-explicitly if you want it back.`,
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- return setScalingLock(cmd, args[0], true)
- },
-}
-
-var sandboxUnlockCmd = &cobra.Command{
- Use: "unlock <sandbox-id>",
- Short: "Allow scaling on a sandbox again (clear the lock)",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- return setScalingLock(cmd, args[0], false)
- },
-}
-
-var sandboxLockStatusCmd = &cobra.Command{
- Use: "lock-status <sandbox-id>",
- Short: "Show the scaling-lock state of a sandbox",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- var resp struct {
- SandboxID string `json:"sandboxID"`
- Locked bool `json:"locked"`
- }
- if err := c.Get(cmd.Context(), "/sandboxes/"+args[0]+"/scaling-lock", &resp); err != nil {
- return err
- }
- printer.Print(resp, func() {
- if resp.Locked {
- fmt.Printf("Sandbox %s is LOCKED (no scaling)\n", resp.SandboxID)
- } else {
- fmt.Printf("Sandbox %s is unlocked\n", resp.SandboxID)
- }
- })
- return nil
- },
-}
-
-func setScalingLock(cmd *cobra.Command, sandboxID string, locked bool) error {
- c := client.FromContext(cmd.Context())
- var resp struct {
- SandboxID string `json:"sandboxID"`
- Locked bool `json:"locked"`
- }
- body := map[string]bool{"locked": locked}
- if err := c.PutJSON(cmd.Context(), "/sandboxes/"+sandboxID+"/scaling-lock", body, &resp); err != nil {
- return err
- }
- printer.Print(resp, func() {
- if resp.Locked {
- fmt.Printf("Sandbox %s locked (scaling disabled)\n", resp.SandboxID)
- } else {
- fmt.Printf("Sandbox %s unlocked\n", resp.SandboxID)
- }
- })
- return nil
-}
-
-func init() {
- sandboxAutoscaleCmd.Flags().Bool("on", false, "Enable autoscale (requires --min and --max)")
- sandboxAutoscaleCmd.Flags().Bool("off", false, "Disable autoscale")
- sandboxAutoscaleCmd.Flags().Int("min", 0, "Minimum memory tier in MB (allowed: 1024, 4096, 8192, 16384)")
- sandboxAutoscaleCmd.Flags().Int("max", 0, "Maximum memory tier in MB (allowed: 1024, 4096, 8192, 16384)")
-
- sandboxCmd.AddCommand(sandboxScaleCmd)
- sandboxCmd.AddCommand(sandboxAutoscaleCmd)
- sandboxCmd.AddCommand(sandboxLockCmd)
- sandboxCmd.AddCommand(sandboxUnlockCmd)
- sandboxCmd.AddCommand(sandboxLockStatusCmd)
-}
diff --git a/cmd/oc/internal/commands/secret.go b/cmd/oc/internal/commands/secret.go
deleted file mode 100644
index 7f0b434e..00000000
--- a/cmd/oc/internal/commands/secret.go
+++ /dev/null
@@ -1,139 +0,0 @@
-package commands
-
-import (
- "bufio"
- "fmt"
- "os"
- "strings"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-var secretCmd = &cobra.Command{
- Use: "secret",
- Short: "Manage secrets in a secret store",
-}
-
-var secretSetCmd = &cobra.Command{
- Use: "set <store-id> <name> [value]",
- Short: "Set a secret in a store (encrypted at rest)",
- Long: `Set a secret in a secret store. The value is encrypted at rest and injected
-as an environment variable into sandboxes created with this store.
-
-Value can be provided as:
- oc secret set <store-id> KEY value # inline
- oc secret set <store-id> KEY --from-stdin # from stdin
- oc secret set <store-id> KEY value --allowed-hosts api.x.com # with host restriction
-
-When --allowed-hosts is set, the secret is only substituted in outbound
-HTTPS requests to matching hosts. Supports wildcards (*.example.com).`,
- Args: cobra.RangeArgs(2, 3),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- storeID := args[0]
- name := args[1]
- fromStdin, _ := cmd.Flags().GetBool("from-stdin")
- allowedHosts, _ := cmd.Flags().GetStringSlice("allowed-hosts")
-
- var value string
- if fromStdin {
- scanner := bufio.NewScanner(os.Stdin)
- var lines []string
- for scanner.Scan() {
- lines = append(lines, scanner.Text())
- }
- if err := scanner.Err(); err != nil {
- return fmt.Errorf("reading stdin: %w", err)
- }
- value = strings.Join(lines, "\n")
- } else if len(args) == 3 {
- value = args[2]
- } else {
- return fmt.Errorf("provide value as argument or use --from-stdin")
- }
-
- if value == "" {
- return fmt.Errorf("secret value cannot be empty")
- }
-
- body := map[string]interface{}{"value": value}
- if len(allowedHosts) > 0 {
- body["allowedHosts"] = allowedHosts
- }
-
- var result map[string]string
- if err := c.PutJSON(cmd.Context(), fmt.Sprintf("/secret-stores/%s/secrets/%s", storeID, name), body, &result); err != nil {
- return err
- }
-
- if len(allowedHosts) > 0 {
- fmt.Printf("Secret %s set on store %s (allowed hosts: %s)\n", name, storeID, strings.Join(allowedHosts, ", "))
- } else {
- fmt.Printf("Secret %s set on store %s\n", name, storeID)
- }
- return nil
- },
-}
-
-type secretEntryInfo struct {
- Name string `json:"name"`
- AllowedHosts []string `json:"allowedHosts"`
-}
-
-var secretListCmd = &cobra.Command{
- Use: "list <store-id>",
- Aliases: []string{"ls"},
- Short: "List secrets in a store (values are never shown)",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var entries []secretEntryInfo
- if err := c.Get(cmd.Context(), fmt.Sprintf("/secret-stores/%s/secrets", args[0]), &entries); err != nil {
- return err
- }
-
- printer.Print(entries, func() {
- if len(entries) == 0 {
- fmt.Println("No secrets found.")
- return
- }
- headers := []string{"NAME", "ALLOWED HOSTS"}
- var rows [][]string
- for _, e := range entries {
- hosts := "(all)"
- if len(e.AllowedHosts) > 0 {
- hosts = strings.Join(e.AllowedHosts, ", ")
- }
- rows = append(rows, []string{e.Name, hosts})
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var secretDeleteCmd = &cobra.Command{
- Use: "delete <store-id> <name>",
- Short: "Delete a secret from a store",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- if err := c.DeleteIgnoreNotFound(cmd.Context(), fmt.Sprintf("/secret-stores/%s/secrets/%s", args[0], args[1])); err != nil {
- return err
- }
- fmt.Printf("Secret %s deleted from store %s\n", args[1], args[0])
- return nil
- },
-}
-
-func init() {
- secretSetCmd.Flags().Bool("from-stdin", false, "Read secret value from stdin")
- secretSetCmd.Flags().StringSlice("allowed-hosts", nil, "Hosts where this secret can be substituted (e.g. api.anthropic.com)")
-
- secretCmd.AddCommand(secretSetCmd)
- secretCmd.AddCommand(secretListCmd)
- secretCmd.AddCommand(secretDeleteCmd)
-}
diff --git a/cmd/oc/internal/commands/session.go b/cmd/oc/internal/commands/session.go
deleted file mode 100644
index ce972b6c..00000000
--- a/cmd/oc/internal/commands/session.go
+++ /dev/null
@@ -1,300 +0,0 @@
-package commands
-
-// `oc session` — Durable Agent Sessions runtime verbs (/v3/sessions/*). A session
-// is one run of an agent's active revision. Distinct from `oc agent`
-// (which manages the behavior); sessions are addressed by id.
-
-import (
- "encoding/json"
- "fmt"
- "strings"
-
- "github.com/spf13/cobra"
-)
-
-type Session struct {
- ID string `json:"id"`
- Status string `json:"status"`
- AgentID string `json:"agent_id,omitempty"`
- CreatedAt string `json:"created_at"`
-}
-
-type SessionEnvelope struct {
- Session Session `json:"session"`
-}
-
-type SessionList struct {
- Data []Session `json:"data"`
-}
-
-type Event struct {
- Seq int `json:"seq"`
- Type string `json:"type"`
- Level string `json:"level"`
- Body interface{} `json:"body"`
- TS string `json:"ts"`
-}
-
-type EventList struct {
- Data []Event `json:"data"`
-}
-
-var sessionCmd = &cobra.Command{
- Use: "session",
- Short: "Run and inspect agent sessions",
-}
-
-var sessionCreateCmd = &cobra.Command{
- Use: "create",
- Short: "Start a session on an agent",
- Example: " oc session create --agent issue-fixer --input \"triage issue #42\"",
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- ref, _ := cmd.Flags().GetString("agent")
- input, _ := cmd.Flags().GetString("input")
- if ref == "" {
- id, rerr := targetAgentID(cmd, sc, nil) // fall back to cwd agent.toml
- if rerr != nil {
- return fmt.Errorf("--agent is required (or run inside an agent directory)")
- }
- ref = id
- } else {
- ref, err = resolveRef(cmd, sc, ref)
- if err != nil {
- return err
- }
- }
- if input == "" {
- return fmt.Errorf("--input is required (the first message to the agent)")
- }
- body := map[string]interface{}{"agent": ref, "input": input}
- specs, _ := cmd.Flags().GetStringArray("source")
- sources, err := parseSources(specs)
- if err != nil {
- return err
- }
- if len(sources) > 0 {
- body["sources"] = sources
- }
- var env SessionEnvelope
- if err := sc.Post(cmd.Context(), "/v3/sessions", body, &env); err != nil {
- return err
- }
- printer.Print(env.Session, func() {
- fmt.Printf("Started session %s (status: %s)\n", env.Session.ID, env.Session.Status)
- fmt.Printf("Follow: oc session logs %s\n", env.Session.ID)
- })
- return nil
- },
-}
-
-var sessionListCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List sessions",
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- path := "/v3/sessions"
- if agent, _ := cmd.Flags().GetString("agent"); agent != "" {
- id, err := resolveRef(cmd, sc, agent)
- if err != nil {
- return err
- }
- path += "?agent=" + id
- }
- var resp SessionList
- if err := sc.Get(cmd.Context(), path, &resp); err != nil {
- return err
- }
- printer.Print(resp.Data, func() {
- if len(resp.Data) == 0 {
- fmt.Println("No sessions found.")
- return
- }
- headers := []string{"ID", "STATUS", "AGENT", "CREATED"}
- var rows [][]string
- for _, s := range resp.Data {
- rows = append(rows, []string{s.ID, s.Status, s.AgentID, formatAge(s.CreatedAt)})
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var sessionGetCmd = &cobra.Command{
- Use: "get <id>",
- Short: "Show a session",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- var raw json.RawMessage
- var s Session
- if err := sc.Get(cmd.Context(), "/v3/sessions/"+args[0], &raw); err != nil {
- return err
- }
- if err := json.Unmarshal(raw, &s); err != nil {
- return fmt.Errorf("decode session: %w", err)
- }
- // Keep the human view compact, but preserve the complete server response
- // for automation: usage, cursors, limits, and future additive fields.
- printer.Print(raw, func() {
- fmt.Printf("ID: %s\n", s.ID)
- fmt.Printf("Status: %s\n", s.Status)
- fmt.Printf("Agent: %s\n", s.AgentID)
- fmt.Printf("Created: %s ago\n", formatAge(s.CreatedAt))
- })
- return nil
- },
-}
-
-var sessionResultCmd = &cobra.Command{
- Use: "result <id>",
- Short: "Show a session's result",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- var res map[string]interface{}
- if err := sc.Get(cmd.Context(), "/v3/sessions/"+args[0]+"/result", &res); err != nil {
- return err
- }
- printer.Print(res, func() {
- for k, v := range res {
- fmt.Printf("%s: %v\n", k, v)
- }
- })
- return nil
- },
-}
-
-var sessionCancelCmd = &cobra.Command{
- Use: "cancel <id>",
- Short: "Cancel a running session",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- if err := sc.Post(cmd.Context(), "/v3/sessions/"+args[0]+"/cancel", nil, nil); err != nil {
- return err
- }
- fmt.Printf("Cancelled %s\n", args[0])
- return nil
- },
-}
-
-var sessionLogsCmd = &cobra.Command{
- Use: "logs <id>",
- Short: "Show a session's event log",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- var resp EventList
- if err := sc.Get(cmd.Context(), "/v3/sessions/"+args[0]+"/events", &resp); err != nil {
- return err
- }
- printer.Print(resp.Data, func() {
- if len(resp.Data) == 0 {
- fmt.Println("No events.")
- return
- }
- for _, e := range resp.Data {
- fmt.Printf("[%d] %s", e.Seq, e.Type)
- if txt, ok := bodyText(e.Body); ok {
- fmt.Printf(" %s", txt)
- }
- fmt.Println()
- }
- })
- return nil
- },
-}
-
-var sessionSteerCmd = &cobra.Command{
- Use: "steer <id> <text>",
- Short: "Send a message to a running session",
- Example: " oc session steer ses_123 \"also check the changelog\"",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- if err := sc.Post(cmd.Context(), "/v3/sessions/"+args[0]+"/messages", map[string]interface{}{"text": args[1]}, nil); err != nil {
- return err
- }
- fmt.Println("Sent.")
- return nil
- },
-}
-
-// parseSources turns --source "owner/repo[@ref]" specs into connection-backed
-// source objects for POST /v3/sessions (validated server-side by sources/validate).
-// A missing @ref defaults to HEAD — the repo's default branch, pinned to a sha at
-// create by the control plane (needs the OpenComputer GitHub App connected).
-func parseSources(specs []string) ([]map[string]interface{}, error) {
- var out []map[string]interface{}
- for _, raw := range specs {
- s := strings.TrimSpace(raw)
- if s == "" {
- continue
- }
- repo, ref := s, "HEAD"
- if at := strings.Index(s, "@"); at >= 0 {
- repo, ref = s[:at], s[at+1:]
- }
- if ref == "" {
- ref = "HEAD"
- }
- if strings.Count(repo, "/") != 1 || strings.HasPrefix(repo, "/") || strings.HasSuffix(repo, "/") {
- return nil, fmt.Errorf("--source %q must be owner/repo[@ref]", raw)
- }
- out = append(out, map[string]interface{}{"repo": repo, "ref": ref})
- }
- return out, nil
-}
-
-// bodyText pulls a short human string out of an event body for the log view.
-func bodyText(body interface{}) (string, bool) {
- m, ok := body.(map[string]interface{})
- if !ok {
- return "", false
- }
- for _, k := range []string{"text", "message", "tool", "yield_reason"} {
- if v, ok := m[k].(string); ok && v != "" {
- return v, true
- }
- }
- return "", false
-}
-
-func init() {
- sessionCreateCmd.Flags().String("agent", "", "Agent id or name to run (else the cwd agent.toml)")
- sessionCreateCmd.Flags().String("input", "", "First message to the agent (required)")
- sessionCreateCmd.Flags().StringArray("source", nil, "Attach a GitHub repo as a working source: owner/repo[@ref] (default ref: HEAD). Repeatable.")
- sessionListCmd.Flags().String("agent", "", "Filter by agent id or name")
-
- sessionCmd.AddCommand(sessionCreateCmd)
- sessionCmd.AddCommand(sessionListCmd)
- sessionCmd.AddCommand(sessionGetCmd)
- sessionCmd.AddCommand(sessionResultCmd)
- sessionCmd.AddCommand(sessionCancelCmd)
- sessionCmd.AddCommand(sessionLogsCmd)
- sessionCmd.AddCommand(sessionSteerCmd)
-}
diff --git a/cmd/oc/internal/commands/session_test.go b/cmd/oc/internal/commands/session_test.go
deleted file mode 100644
index 9af88275..00000000
--- a/cmd/oc/internal/commands/session_test.go
+++ /dev/null
@@ -1,116 +0,0 @@
-package commands
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/output"
- "github.com/spf13/cobra"
-)
-
-func TestSessionCreateDoesNotExposeRevisionFlag(t *testing.T) {
- if flag := sessionCreateCmd.Flags().Lookup("revision"); flag != nil {
- t.Fatal("session create must not expose unsupported revision selection")
- }
-}
-
-func TestSessionGetJSONPreservesCompleteServerResponse(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/v3/sessions/ses_test" {
- http.NotFound(w, r)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- _, _ = w.Write([]byte(`{
- "id":"ses_test","status":"idle","agent_id":"agt_test","created_at":"2026-07-22T00:00:00Z",
- "head":7,"input_cursor":7,"last_turn":{"id":"trn_test","state":"ok"},
- "usage":{"active_seconds":3,"reported_turns":1,"unreported_turns":0,"complete":true,"tokens":42},
- "future_field":{"kept":true}
- }`))
- }))
- defer server.Close()
-
- cmd := &cobra.Command{}
- cmd.SetContext(client.WithSessionsClient(
- context.Background(),
- client.NewSessionsAPI(server.URL, "test-key"),
- ))
-
- previousPrinter, previousJSON := printer, jsonOutput
- var out bytes.Buffer
- printer = output.New(true)
- printer.W = &out
- jsonOutput = true
- defer func() {
- printer = previousPrinter
- jsonOutput = previousJSON
- }()
-
- if err := sessionGetCmd.RunE(cmd, []string{"ses_test"}); err != nil {
- t.Fatalf("session get: %v", err)
- }
- var got map[string]any
- if err := json.Unmarshal(out.Bytes(), &got); err != nil {
- t.Fatalf("decode command output: %v\n%s", err, out.String())
- }
- if got["head"] != float64(7) || got["input_cursor"] != float64(7) {
- t.Fatalf("session cursors were dropped: %#v", got)
- }
- if got["usage"].(map[string]any)["tokens"] != float64(42) {
- t.Fatalf("session usage was dropped: %#v", got)
- }
- if got["future_field"].(map[string]any)["kept"] != true {
- t.Fatalf("unknown server fields were dropped: %#v", got)
- }
-}
-
-func TestParseSources(t *testing.T) {
- ok := []struct {
- in []string
- wantRepo []string
- wantRef []string
- }{
- {[]string{"acme/agents"}, []string{"acme/agents"}, []string{"HEAD"}},
- {[]string{"acme/agents@main"}, []string{"acme/agents"}, []string{"main"}},
- {[]string{"acme/agents@refs/pull/5/head"}, []string{"acme/agents"}, []string{"refs/pull/5/head"}},
- {[]string{" acme/agents "}, []string{"acme/agents"}, []string{"HEAD"}},
- {[]string{"acme/agents@"}, []string{"acme/agents"}, []string{"HEAD"}}, // empty ref → HEAD
- {[]string{"a/b", "c/d@dev"}, []string{"a/b", "c/d"}, []string{"HEAD", "dev"}},
- {[]string{"", " "}, nil, nil}, // blanks skipped
- {nil, nil, nil},
- }
- for _, c := range ok {
- got, err := parseSources(c.in)
- if err != nil {
- t.Fatalf("parseSources(%v) unexpected error: %v", c.in, err)
- }
- if len(got) != len(c.wantRepo) {
- t.Fatalf("parseSources(%v) = %d sources, want %d", c.in, len(got), len(c.wantRepo))
- }
- for i := range got {
- if got[i]["repo"] != c.wantRepo[i] {
- t.Errorf("parseSources(%v)[%d].repo = %v, want %s", c.in, i, got[i]["repo"], c.wantRepo[i])
- }
- if got[i]["ref"] != c.wantRef[i] {
- t.Errorf("parseSources(%v)[%d].ref = %v, want %s", c.in, i, got[i]["ref"], c.wantRef[i])
- }
- }
- }
-
- bad := [][]string{
- {"notarepo"}, // no slash
- {"owner/repo/extra"}, // two slashes
- {"/repo"}, // leading slash
- {"owner/"}, // trailing slash
- }
- for _, in := range bad {
- if _, err := parseSources(in); err == nil {
- t.Errorf("parseSources(%v) expected an error, got nil", in)
- }
- }
-}
diff --git a/cmd/oc/internal/commands/session_watch.go b/cmd/oc/internal/commands/session_watch.go
deleted file mode 100644
index ccb30575..00000000
--- a/cmd/oc/internal/commands/session_watch.go
+++ /dev/null
@@ -1,164 +0,0 @@
-package commands
-
-// `oc session watch|watches|unwatch` — PR watches (design 010). A watch wakes the
-// session when a PR it opened changes (checks finish, a review/comment lands, it
-// merges/closes). Only PRs the same session opened, on OpenComputer-App repos.
-
-import (
- "fmt"
- "strings"
-
- "github.com/spf13/cobra"
-)
-
-type Watch struct {
- ID string `json:"id"`
- Type string `json:"type"`
- Repo string `json:"repo"`
- PR int `json:"pr"`
- WakeOn string `json:"wake_on"`
- Intent string `json:"intent,omitempty"`
- Status string `json:"status"`
- Origin string `json:"origin"`
- LastSnapshotAt string `json:"last_snapshot_at,omitempty"`
- ExpiresAt string `json:"expires_at,omitempty"`
- CreatedAt string `json:"created_at"`
-}
-
-type WatchEnvelope struct {
- Watch Watch `json:"watch"`
-}
-
-type WatchList struct {
- Data []Watch `json:"data"`
-}
-
-var wakeOns = []string{"checks", "review", "comment", "merge"}
-
-var sessionWatchCmd = &cobra.Command{
- Use: "watch <id>",
- Short: "Watch a PR the session opened (wake it on PR changes)",
- Long: "Declare a watch: OpenComputer wakes the session when the watched PR changes.\n\n" +
- "wake_on picks the condition — checks (CI finishes, default), review (a review\n" +
- "decision), comment (a new comment), or merge (the PR merges/closes). --repo/--pr\n" +
- "are optional; omitted, they resolve to the PR this session opened.",
- Example: " oc session watch ses_123 --wake-on review --intent \"address review feedback\"\n" +
- " oc session watch ses_123 # wake_on=checks (default)",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- wakeOn, _ := cmd.Flags().GetString("wake-on")
- if !contains(wakeOns, wakeOn) {
- return fmt.Errorf("--wake-on must be one of %s", strings.Join(wakeOns, ", "))
- }
- repo, _ := cmd.Flags().GetString("repo")
- pr, _ := cmd.Flags().GetInt("pr")
- intent, _ := cmd.Flags().GetString("intent")
-
- body := map[string]interface{}{"type": "github_pr", "wake_on": wakeOn}
- if repo != "" {
- body["repo"] = repo
- }
- if pr > 0 {
- body["pr"] = pr
- }
- if intent != "" {
- body["intent"] = intent
- }
- var env WatchEnvelope
- if err := sc.Post(cmd.Context(), "/v3/sessions/"+args[0]+"/watches", body, &env); err != nil {
- return err
- }
- printer.Print(env.Watch, func() {
- w := env.Watch
- fmt.Printf("Watching %s#%d — wake on %s (%s)\n", w.Repo, w.PR, w.WakeOn, w.Status)
- fmt.Printf("Watch id: %s\n", w.ID)
- if w.Status == "auth_required" {
- fmt.Println("Note: the OpenComputer GitHub App needs its watch permissions re-accepted; re-declare once fixed.")
- }
- })
- return nil
- },
-}
-
-var sessionWatchesCmd = &cobra.Command{
- Use: "watches <id>",
- Short: "List a session's watches",
- Args: cobra.ExactArgs(1),
- Aliases: []string{"watch-list"},
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- var resp WatchList
- if err := sc.Get(cmd.Context(), "/v3/sessions/"+args[0]+"/watches", &resp); err != nil {
- return err
- }
- printer.Print(resp.Data, func() {
- if len(resp.Data) == 0 {
- fmt.Println("No watches.")
- return
- }
- headers := []string{"ID", "REPO", "PR", "WAKE ON", "STATUS", "INTENT"}
- var rows [][]string
- for _, w := range resp.Data {
- rows = append(rows, []string{w.ID, w.Repo, fmt.Sprintf("%d", w.PR), w.WakeOn, w.Status, truncStr(w.Intent, 40)})
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var sessionUnwatchCmd = &cobra.Command{
- Use: "unwatch <id> <watch-id>",
- Short: "Remove a watch",
- Example: " oc session unwatch ses_123 wch_abc",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- if err := sc.Delete(cmd.Context(), "/v3/sessions/"+args[0]+"/watches/"+args[1]); err != nil {
- return err
- }
- fmt.Printf("Removed watch %s\n", args[1])
- return nil
- },
-}
-
-func contains(xs []string, x string) bool {
- for _, v := range xs {
- if v == x {
- return true
- }
- }
- return false
-}
-
-func truncStr(s string, n int) string {
- s = strings.ReplaceAll(s, "\n", " ")
- if len(s) <= n {
- return s
- }
- if n <= 1 {
- return s[:n]
- }
- return s[:n-1] + "…"
-}
-
-func init() {
- sessionWatchCmd.Flags().String("wake-on", "checks", "Wake condition: checks | review | comment | merge")
- sessionWatchCmd.Flags().String("repo", "", "owner/repo (default: the PR this session opened)")
- sessionWatchCmd.Flags().Int("pr", 0, "PR number (default: the session's sole owned PR)")
- sessionWatchCmd.Flags().String("intent", "", "Freeform note (\"why\"), replayed to the agent on wake")
-
- sessionCmd.AddCommand(sessionWatchCmd)
- sessionCmd.AddCommand(sessionWatchesCmd)
- sessionCmd.AddCommand(sessionUnwatchCmd)
-}
diff --git a/cmd/oc/internal/commands/shell.go b/cmd/oc/internal/commands/shell.go
deleted file mode 100644
index ad1868c1..00000000
--- a/cmd/oc/internal/commands/shell.go
+++ /dev/null
@@ -1,178 +0,0 @@
-package commands
-
-import (
- "fmt"
- "io"
- "os"
- "os/signal"
- "regexp"
- "strings"
- "syscall"
-
- "github.com/gorilla/websocket"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/pkg/types"
- "github.com/spf13/cobra"
- "golang.org/x/term"
-)
-
-var uuidPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
-
-var shellCmd = &cobra.Command{
- Use: "shell <sandbox-id>",
- Short: "Open an interactive shell in a sandbox",
- Long: `Open an interactive terminal session in a running sandbox via WebSocket PTY.
-
-Examples:
- oc shell abc123
- oc shell abc123 --shell /bin/zsh`,
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- sandboxID := args[0]
- shellPath, _ := cmd.Flags().GetString("shell")
-
- // If the argument doesn't look like a sandbox ID (full UUID or sb-* short form),
- // try to resolve it as an agent name through sessions-api.
- isSandboxID := uuidPattern.MatchString(sandboxID) || strings.HasPrefix(sandboxID, "sb-")
- if !isSandboxID {
- sc := client.SessionsFromContext(cmd.Context())
- if sc != nil {
- resolved, err := resolveAgentSandbox(cmd, sc, sandboxID)
- if err != nil {
- return fmt.Errorf("failed to resolve agent %q: %w", sandboxID, err)
- }
- sandboxID = resolved
- } else {
- return fmt.Errorf("%q does not look like a sandbox ID. Set SESSIONS_API_URL to resolve agent names.", sandboxID)
- }
- }
-
- // Get sandbox info to resolve connectURL for direct worker access
- var sandbox struct {
- ConnectURL string `json:"connectURL"`
- Token string `json:"token"`
- }
- if err := c.Get(cmd.Context(), fmt.Sprintf("/sandboxes/%s", sandboxID), &sandbox); err != nil {
- return fmt.Errorf("failed to get sandbox: %w", err)
- }
-
- // Use worker client if connectURL is available (server mode)
- ptyClient := c
- if sandbox.ConnectURL != "" {
- ptyClient = client.NewWorker(sandbox.ConnectURL, sandbox.Token)
- }
-
- // Get current terminal size
- cols, rows := 80, 24
- if w, h, err := term.GetSize(int(os.Stdin.Fd())); err == nil {
- cols, rows = w, h
- }
-
- // Create PTY session
- req := types.PTYCreateRequest{
- Cols: cols,
- Rows: rows,
- Shell: shellPath,
- }
- var session types.PTYSession
- if err := ptyClient.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/pty", sandboxID), req, &session); err != nil {
- return fmt.Errorf("failed to create PTY: %w", err)
- }
-
- // Connect WebSocket
- wsPath := fmt.Sprintf("/sandboxes/%s/pty/%s", sandboxID, session.SessionID)
- conn, err := ptyClient.DialWebSocket(cmd.Context(), wsPath)
- if err != nil {
- return fmt.Errorf("failed to connect: %w", err)
- }
- defer conn.Close()
-
- // Enter raw terminal mode
- fd := int(os.Stdin.Fd())
- oldState, err := term.MakeRaw(fd)
- if err != nil {
- return fmt.Errorf("failed to enter raw mode: %w", err)
- }
- defer term.Restore(fd, oldState)
-
- // Handle SIGWINCH for terminal resize
- sigWinch := make(chan os.Signal, 1)
- signal.Notify(sigWinch, syscall.SIGWINCH)
- go func() {
- for range sigWinch {
- if w, h, err := term.GetSize(fd); err == nil {
- resizeReq := map[string]any{"cols": w, "rows": h}
- // Best-effort resize via HTTP POST
- ptyClient.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/pty/%s/resize", sandboxID, session.SessionID), resizeReq, nil)
- }
- }
- }()
-
- done := make(chan struct{})
-
- // Read from WebSocket → stdout
- go func() {
- defer close(done)
- for {
- _, msg, err := conn.ReadMessage()
- if err != nil {
- return
- }
- os.Stdout.Write(msg)
- }
- }()
-
- // Read from stdin → WebSocket
- go func() {
- buf := make([]byte, 1024)
- for {
- n, err := os.Stdin.Read(buf)
- if n > 0 {
- if writeErr := conn.WriteMessage(websocket.BinaryMessage, buf[:n]); writeErr != nil {
- return
- }
- }
- if err != nil {
- if err != io.EOF {
- return
- }
- return
- }
- }
- }()
-
- <-done
-
- // Cleanup: kill PTY session
- signal.Stop(sigWinch)
- ptyClient.Delete(cmd.Context(), fmt.Sprintf("/sandboxes/%s/pty/%s", sandboxID, session.SessionID))
-
- return nil
- },
-}
-
-// resolveAgentSandbox looks up an agent by name through sessions-api and returns
-// the sandbox ID of its first running instance.
-func resolveAgentSandbox(cmd *cobra.Command, sc *client.Client, agentName string) (string, error) {
- var instResp struct {
- Instances []struct {
- ID string `json:"id"`
- Status string `json:"status"`
- SandboxID *string `json:"sandbox_id"`
- } `json:"instances"`
- }
- if err := sc.Get(cmd.Context(), "/v1/agents/"+agentName+"/instances", &instResp); err != nil {
- return "", err
- }
- for _, inst := range instResp.Instances {
- if inst.Status == "running" && inst.SandboxID != nil {
- return *inst.SandboxID, nil
- }
- }
- return "", fmt.Errorf("no running instance found for agent %q", agentName)
-}
-
-func init() {
- shellCmd.Flags().String("shell", "", "Shell to use (default: /bin/bash)")
-}
diff --git a/cmd/oc/internal/commands/template.go b/cmd/oc/internal/commands/template.go
deleted file mode 100644
index 41580968..00000000
--- a/cmd/oc/internal/commands/template.go
+++ /dev/null
@@ -1,128 +0,0 @@
-package commands
-
-import (
- "encoding/json"
- "fmt"
- "net/url"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-// TemplateInfo matches the API response for named snapshots.
-type TemplateInfo struct {
- ID string `json:"id"`
- OrgID string `json:"orgId"`
- ContentHash string `json:"contentHash"`
- CheckpointID string `json:"checkpointId,omitempty"`
- Name string `json:"name,omitempty"`
- Manifest json.RawMessage `json:"manifest"`
- Status string `json:"status"`
- CreatedAt time.Time `json:"createdAt"`
- LastUsedAt time.Time `json:"lastUsedAt"`
-}
-
-var templateCmd = &cobra.Command{
- Use: "template",
- Aliases: []string{"templates", "snapshot", "snapshots"},
- Short: "Manage declarative sandbox templates",
-}
-
-var templateListCmd = &cobra.Command{
- Use: "list",
- Aliases: []string{"ls"},
- Short: "List templates",
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
-
- var templates []TemplateInfo
- if err := c.Get(cmd.Context(), "/snapshots", &templates); err != nil {
- return err
- }
-
- printer.Print(templates, func() {
- if len(templates) == 0 {
- fmt.Println("No templates found.")
- return
- }
- headers := []string{"NAME", "STATUS", "CHECKPOINT", "LAST USED", "CREATED"}
- var rows [][]string
- for _, tmpl := range templates {
- checkpointID := tmpl.CheckpointID
- if checkpointID == "" {
- checkpointID = "-"
- }
- rows = append(rows, []string{
- tmpl.Name,
- tmpl.Status,
- checkpointID,
- formatTemplateTime(tmpl.LastUsedAt),
- formatTemplateTime(tmpl.CreatedAt),
- })
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-var templateGetCmd = &cobra.Command{
- Use: "get <name>",
- Short: "Get template details",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- name := args[0]
-
- var tmpl TemplateInfo
- if err := c.Get(cmd.Context(), "/snapshots/"+url.PathEscape(name), &tmpl); err != nil {
- return err
- }
-
- printer.Print(tmpl, func() {
- fmt.Printf("Name: %s\n", tmpl.Name)
- fmt.Printf("Status: %s\n", tmpl.Status)
- fmt.Printf("ID: %s\n", tmpl.ID)
- fmt.Printf("Checkpoint: %s\n", valueOrDash(tmpl.CheckpointID))
- fmt.Printf("Created: %s\n", formatTemplateTime(tmpl.CreatedAt))
- fmt.Printf("Last used: %s\n", formatTemplateTime(tmpl.LastUsedAt))
- })
- return nil
- },
-}
-
-var templateDeleteCmd = &cobra.Command{
- Use: "delete <name>",
- Short: "Delete a template",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- c := client.FromContext(cmd.Context())
- name := args[0]
- if err := c.DeleteIgnoreNotFound(cmd.Context(), "/snapshots/"+url.PathEscape(name)); err != nil {
- return err
- }
- fmt.Printf("Template %s deleted.\n", name)
- return nil
- },
-}
-
-func formatTemplateTime(t time.Time) string {
- if t.IsZero() {
- return "-"
- }
- return t.Format(time.RFC3339)
-}
-
-func valueOrDash(v string) string {
- if v == "" {
- return "-"
- }
- return v
-}
-
-func init() {
- templateCmd.AddCommand(templateListCmd)
- templateCmd.AddCommand(templateGetCmd)
- templateCmd.AddCommand(templateDeleteCmd)
-}
diff --git a/cmd/oc/internal/commands/update.go b/cmd/oc/internal/commands/update.go
deleted file mode 100644
index 1a8198cd..00000000
--- a/cmd/oc/internal/commands/update.go
+++ /dev/null
@@ -1,258 +0,0 @@
-package commands
-
-import (
- "bufio"
- "context"
- "crypto/sha256"
- "encoding/hex"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/http"
- "os"
- "path/filepath"
- "runtime"
- "strconv"
- "strings"
- "time"
-
- "github.com/spf13/cobra"
-)
-
-// GitHub release metadata — hardcoded to the upstream repo. Centralised here
-// so both `oc update` and the background update-check use the same source.
-const (
- releasesLatestURL = "https://api.github.com/repos/diggerhq/opencomputer/releases/latest"
- releaseUserAgent = "oc-cli"
-)
-
-type githubRelease struct {
- TagName string `json:"tag_name"`
- HTMLURL string `json:"html_url"`
- Assets []releaseAsset `json:"assets"`
-}
-
-type releaseAsset struct {
- Name string `json:"name"`
- BrowserDownloadURL string `json:"browser_download_url"`
- Size int64 `json:"size"`
-}
-
-var updateCmd = &cobra.Command{
- Use: "update",
- Short: "Update the oc CLI to the latest release",
- Long: `Fetch the latest release from GitHub and replace the current binary in place.
-
-Works on macOS and Linux (amd64/arm64). Requires write access to the binary's
-current path; if oc is installed in a system-wide directory, re-run with sudo
-or install into a user-writable location (e.g. ~/.local/bin).`,
- RunE: func(cmd *cobra.Command, args []string) error {
- check, _ := cmd.Flags().GetBool("check")
- yes, _ := cmd.Flags().GetBool("yes")
-
- ctx, cancel := context.WithTimeout(cmd.Context(), 30*time.Second)
- defer cancel()
-
- rel, err := fetchLatestRelease(ctx)
- if err != nil {
- return fmt.Errorf("check latest release: %w", err)
- }
- latest := strings.TrimPrefix(rel.TagName, "v")
-
- fmt.Printf("current: v%s\n", Version)
- fmt.Printf("latest: v%s\n", latest)
- fmt.Printf("release: %s\n", rel.HTMLURL)
-
- if Version == "dev" {
- fmt.Println("\nthis is a dev build — skipping update. Build a tagged binary to enable self-update.")
- return nil
- }
-
- if compareVersions(Version, latest) >= 0 {
- fmt.Println("\nalready up to date.")
- return nil
- }
-
- if check {
- fmt.Printf("\nupdate available: run `oc update` to install v%s\n", latest)
- return nil
- }
-
- if !yes {
- fmt.Printf("\nReplace v%s with v%s? [Y/n] ", Version, latest)
- reader := bufio.NewReader(os.Stdin)
- line, _ := reader.ReadString('\n')
- resp := strings.ToLower(strings.TrimSpace(line))
- if resp != "" && resp != "y" && resp != "yes" {
- fmt.Println("aborted.")
- return nil
- }
- }
-
- if err := installRelease(ctx, rel, latest); err != nil {
- return err
- }
- fmt.Printf("✓ updated v%s → v%s\n", Version, latest)
- return nil
- },
-}
-
-// fetchLatestRelease queries the GitHub Releases API for the latest release
-// of oc. Returns a populated githubRelease on success. Shared by the
-// `update` command and the background update-check.
-func fetchLatestRelease(ctx context.Context) (*githubRelease, error) {
- req, err := http.NewRequestWithContext(ctx, "GET", releasesLatestURL, nil)
- if err != nil {
- return nil, err
- }
- req.Header.Set("Accept", "application/vnd.github+json")
- req.Header.Set("User-Agent", releaseUserAgent)
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
- if resp.StatusCode != 200 {
- body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
- return nil, fmt.Errorf("github api: %s: %s", resp.Status, strings.TrimSpace(string(body)))
- }
- var rel githubRelease
- if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
- return nil, err
- }
- return &rel, nil
-}
-
-// installRelease picks the right asset for the current platform, verifies
-// its SHA256 against the release's `checksums.txt`, and atomically replaces
-// the running binary with the new one.
-func installRelease(ctx context.Context, rel *githubRelease, version string) error {
- assetName := fmt.Sprintf("oc-%s-%s", runtime.GOOS, runtime.GOARCH)
- var binAsset, sumAsset *releaseAsset
- for i := range rel.Assets {
- a := &rel.Assets[i]
- switch a.Name {
- case assetName:
- binAsset = a
- case "checksums.txt":
- sumAsset = a
- }
- }
- if binAsset == nil {
- return fmt.Errorf("no release asset for %s/%s (looked for %q)", runtime.GOOS, runtime.GOARCH, assetName)
- }
- if sumAsset == nil {
- return errors.New("release is missing checksums.txt")
- }
-
- fmt.Printf("downloading %s (%.1f MB)...\n", binAsset.Name, float64(binAsset.Size)/(1<<20))
- binBytes, err := downloadBytes(ctx, binAsset.BrowserDownloadURL)
- if err != nil {
- return fmt.Errorf("download binary: %w", err)
- }
-
- sumBytes, err := downloadBytes(ctx, sumAsset.BrowserDownloadURL)
- if err != nil {
- return fmt.Errorf("download checksums: %w", err)
- }
- expected, ok := parseChecksum(string(sumBytes), assetName)
- if !ok {
- return fmt.Errorf("checksums.txt missing entry for %s", assetName)
- }
- h := sha256.Sum256(binBytes)
- if got := hex.EncodeToString(h[:]); got != expected {
- return fmt.Errorf("checksum mismatch: got %s, expected %s", got, expected)
- }
-
- currentPath, err := os.Executable()
- if err != nil {
- return fmt.Errorf("find current binary: %w", err)
- }
- if resolved, rerr := filepath.EvalSymlinks(currentPath); rerr == nil {
- currentPath = resolved
- }
-
- // Write to <path>.new in the same directory so os.Rename is atomic.
- tmpPath := currentPath + ".new"
- if err := os.WriteFile(tmpPath, binBytes, 0o755); err != nil {
- if errors.Is(err, os.ErrPermission) {
- return fmt.Errorf("no write access to %s (re-run with sudo or install into a user-writable path)", filepath.Dir(currentPath))
- }
- return fmt.Errorf("write new binary (%s): %w", tmpPath, err)
- }
-
- if err := os.Rename(tmpPath, currentPath); err != nil {
- os.Remove(tmpPath)
- return fmt.Errorf("replace %s: %w", currentPath, err)
- }
- return nil
-}
-
-func downloadBytes(ctx context.Context, url string) ([]byte, error) {
- req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
- if err != nil {
- return nil, err
- }
- req.Header.Set("User-Agent", releaseUserAgent)
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
- if resp.StatusCode != 200 {
- return nil, fmt.Errorf("http %s for %s", resp.Status, url)
- }
- return io.ReadAll(resp.Body)
-}
-
-// parseChecksum parses a shasum-style "<hash> <filename>" file and returns
-// the hex digest for the given filename. Accepts the "*filename" binary-mode
-// prefix that GNU shasum emits in some configurations.
-func parseChecksum(body, name string) (string, bool) {
- for _, line := range strings.Split(body, "\n") {
- fields := strings.Fields(strings.TrimSpace(line))
- if len(fields) != 2 {
- continue
- }
- fname := strings.TrimPrefix(fields[1], "*")
- if fname == name {
- return fields[0], true
- }
- }
- return "", false
-}
-
-// compareVersions compares dotted numeric versions ("0.5.0.67"). Returns
-// -1 if a<b, 0 if equal, +1 if a>b. Missing segments are treated as 0 so
-// "0.5.0" < "0.5.0.1". Non-numeric segments sort before numeric ones.
-func compareVersions(a, b string) int {
- as := strings.Split(a, ".")
- bs := strings.Split(b, ".")
- n := len(as)
- if len(bs) > n {
- n = len(bs)
- }
- for i := 0; i < n; i++ {
- av, bv := 0, 0
- if i < len(as) {
- av, _ = strconv.Atoi(as[i])
- }
- if i < len(bs) {
- bv, _ = strconv.Atoi(bs[i])
- }
- if av < bv {
- return -1
- }
- if av > bv {
- return 1
- }
- }
- return 0
-}
-
-func init() {
- updateCmd.Flags().Bool("check", false, "Check for an update without installing")
- updateCmd.Flags().Bool("yes", false, "Skip confirmation prompt")
- rootCmd.AddCommand(updateCmd)
-}
diff --git a/cmd/oc/internal/commands/update_check.go b/cmd/oc/internal/commands/update_check.go
deleted file mode 100644
index f71159b4..00000000
--- a/cmd/oc/internal/commands/update_check.go
+++ /dev/null
@@ -1,129 +0,0 @@
-package commands
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "os"
- "path/filepath"
- "strings"
- "time"
-
- "golang.org/x/term"
-)
-
-// Background update-check: once every 24h at most, cached on disk. Emits
-// a one-line nag to stderr when a newer release is available. Silent on
-// dev builds, non-TTY stderr, or when OC_NO_UPDATE_CHECK is set.
-
-const updateCheckInterval = 24 * time.Hour
-const updateCheckTimeout = 2 * time.Second
-
-type updateCheckCache struct {
- CheckedAt time.Time `json:"checked_at"`
- LatestTag string `json:"latest_tag"`
-}
-
-// maybePromptUpdate runs after every non-update command. Cheap in the
-// common case (reads a small JSON file); does a network call only once
-// per 24h. Any error bails silently — the CLI must never block or warn
-// on a failed version check.
-func maybePromptUpdate() {
- if !isReleaseVersion(Version) {
- return
- }
- if os.Getenv("OC_NO_UPDATE_CHECK") != "" {
- return
- }
- // Only nag humans, never scripts/CI. Stderr is the nag channel because
- // callers often parse stdout; TTY-detecting stderr keeps pipelines clean.
- if !term.IsTerminal(int(os.Stderr.Fd())) {
- return
- }
-
- path, err := updateCheckCachePath()
- if err != nil {
- return
- }
- cached, _ := readUpdateCheckCache(path)
-
- var latestTag string
- if cached != nil && time.Since(cached.CheckedAt) < updateCheckInterval {
- latestTag = cached.LatestTag
- } else {
- ctx, cancel := context.WithTimeout(context.Background(), updateCheckTimeout)
- defer cancel()
- rel, err := fetchLatestRelease(ctx)
- if err != nil {
- return
- }
- latestTag = rel.TagName
- _ = writeUpdateCheckCache(path, &updateCheckCache{
- CheckedAt: time.Now(),
- LatestTag: latestTag,
- })
- }
-
- latest := strings.TrimPrefix(latestTag, "v")
- if latest == "" {
- return
- }
- if compareVersions(Version, latest) < 0 {
- fmt.Fprintf(os.Stderr,
- "\nA new oc release is available: v%s (current: v%s). Run `oc update` to install. Disable this check with OC_NO_UPDATE_CHECK=1.\n",
- latest, Version)
- }
-}
-
-// isReleaseVersion distinguishes published dotted-numeric versions from local
-// builds labelled with a branch, commit, or the default "dev". Comparing a label
-// such as "flue-native-67bf0ee" as numeric zero produces a bogus update nag.
-func isReleaseVersion(version string) bool {
- parts := strings.Split(version, ".")
- if len(parts) < 2 {
- return false
- }
- for _, part := range parts {
- if part == "" {
- return false
- }
- for _, r := range part {
- if r < '0' || r > '9' {
- return false
- }
- }
- }
- return true
-}
-
-func updateCheckCachePath() (string, error) {
- dir, err := os.UserCacheDir()
- if err != nil {
- return "", err
- }
- full := filepath.Join(dir, "opencomputer")
- if err := os.MkdirAll(full, 0o755); err != nil {
- return "", err
- }
- return filepath.Join(full, "update-check.json"), nil
-}
-
-func readUpdateCheckCache(path string) (*updateCheckCache, error) {
- data, err := os.ReadFile(path)
- if err != nil {
- return nil, err
- }
- var c updateCheckCache
- if err := json.Unmarshal(data, &c); err != nil {
- return nil, err
- }
- return &c, nil
-}
-
-func writeUpdateCheckCache(path string, c *updateCheckCache) error {
- data, err := json.Marshal(c)
- if err != nil {
- return err
- }
- return os.WriteFile(path, data, 0o644)
-}
diff --git a/cmd/oc/internal/commands/update_check_test.go b/cmd/oc/internal/commands/update_check_test.go
deleted file mode 100644
index 2e461b02..00000000
--- a/cmd/oc/internal/commands/update_check_test.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package commands
-
-import "testing"
-
-func TestIsReleaseVersion(t *testing.T) {
- t.Parallel()
- cases := map[string]bool{
- "0.6.0.8": true,
- "1.0": true,
- "dev": false,
- "flue-native-67bf0ee": false,
- "0.6.0.8-dirty": false,
- "v0.6.0.8": false,
- "0": false,
- "0..8": false,
- }
- for version, want := range cases {
- version, want := version, want
- t.Run(version, func(t *testing.T) {
- t.Parallel()
- if got := isReleaseVersion(version); got != want {
- t.Fatalf("isReleaseVersion(%q) = %v, want %v", version, got, want)
- }
- })
- }
-}
diff --git a/cmd/oc/internal/config/config.go b/cmd/oc/internal/config/config.go
deleted file mode 100644
index e0bf717d..00000000
--- a/cmd/oc/internal/config/config.go
+++ /dev/null
@@ -1,158 +0,0 @@
-package config
-
-import (
- "encoding/json"
- "fmt"
- "os"
- "path/filepath"
-
- "github.com/spf13/cobra"
-)
-
-const (
- DefaultAPIURL = "https://app.opencomputer.dev"
- DefaultSessionsAPIURL = "https://api.opencomputer.dev"
- configDir = ".oc"
- configFile = "config.json"
-)
-
-type LoginMetadata struct {
- CredentialID string `json:"credential_id"`
- KeyPrefix string `json:"key_prefix"`
- Name string `json:"name"`
- APIURL string `json:"api_url"`
-}
-
-// Config holds the resolved CLI configuration.
-type Config struct {
- APIURL string `json:"api_url,omitempty"`
- APIKey string `json:"api_key,omitempty"`
- SessionsAPIURL string `json:"sessions_api_url,omitempty"`
- Login *LoginMetadata `json:"login,omitempty"`
-}
-
-type CredentialSource string
-
-const (
- CredentialSourceNone CredentialSource = ""
- CredentialSourceFile CredentialSource = "config file"
- CredentialSourceEnvironment CredentialSource = "OPENCOMPUTER_API_KEY"
- CredentialSourceFlag CredentialSource = "--api-key"
-)
-
-// Load resolves configuration from flags > env > config file > defaults.
-func Load(cmd *cobra.Command) Config {
- cfg := LoadFile()
-
- // Apply defaults
- if cfg.APIURL == "" {
- cfg.APIURL = DefaultAPIURL
- }
-
- // Env overrides file
- if v := os.Getenv("OPENCOMPUTER_API_URL"); v != "" {
- cfg.APIURL = v
- }
- if v := os.Getenv("OPENCOMPUTER_API_KEY"); v != "" {
- cfg.APIKey = v
- }
- if cfg.SessionsAPIURL == "" {
- cfg.SessionsAPIURL = DefaultSessionsAPIURL
- }
- if v := os.Getenv("SESSIONS_API_URL"); v != "" {
- cfg.SessionsAPIURL = v
- }
-
- // Flags override env
- if cmd != nil {
- if v, _ := cmd.Flags().GetString("api-url"); v != "" {
- cfg.APIURL = v
- }
- if v, _ := cmd.Flags().GetString("api-key"); v != "" {
- cfg.APIKey = v
- }
- if v, _ := cmd.Flags().GetString("sessions-api-url"); v != "" {
- cfg.SessionsAPIURL = v
- }
- }
-
- return cfg
-}
-
-// EffectiveCredentialSource reports which layer currently controls API-key
-// authentication. Login uses it to avoid claiming it replaced an env/flag
-// override when the saved file would remain ineffective.
-func EffectiveCredentialSource(cmd *cobra.Command) CredentialSource {
- if cmd != nil {
- if v, _ := cmd.Flags().GetString("api-key"); v != "" {
- return CredentialSourceFlag
- }
- }
- if os.Getenv("OPENCOMPUTER_API_KEY") != "" {
- return CredentialSourceEnvironment
- }
- if LoadFile().APIKey != "" {
- return CredentialSourceFile
- }
- return CredentialSourceNone
-}
-
-// ConfigPath returns the path to the config file.
-func ConfigPath() string {
- home, _ := os.UserHomeDir()
- return filepath.Join(home, configDir, configFile)
-}
-
-// LoadFile reads only the persisted configuration, without defaults, env, or
-// flag overrides.
-func LoadFile() Config {
- var cfg Config
- data, err := os.ReadFile(ConfigPath())
- if err != nil {
- return cfg
- }
- json.Unmarshal(data, &cfg)
- return cfg
-}
-
-// Save atomically replaces the config with mode 0600 in a mode-0700 directory.
-func Save(cfg Config) error {
- dir := filepath.Dir(ConfigPath())
- if err := os.MkdirAll(dir, 0700); err != nil {
- return err
- }
- if err := os.Chmod(dir, 0700); err != nil {
- return err
- }
- data, err := json.MarshalIndent(cfg, "", " ")
- if err != nil {
- return err
- }
- data = append(data, '\n')
-
- tmp, err := os.CreateTemp(dir, ".config-*.tmp")
- if err != nil {
- return err
- }
- tmpPath := tmp.Name()
- defer os.Remove(tmpPath)
- if err := tmp.Chmod(0600); err != nil {
- tmp.Close()
- return err
- }
- if _, err := tmp.Write(data); err != nil {
- tmp.Close()
- return err
- }
- if err := tmp.Sync(); err != nil {
- tmp.Close()
- return err
- }
- if err := tmp.Close(); err != nil {
- return err
- }
- if err := os.Rename(tmpPath, ConfigPath()); err != nil {
- return fmt.Errorf("replace config: %w", err)
- }
- return nil
-}
diff --git a/cmd/oc/internal/config/config_test.go b/cmd/oc/internal/config/config_test.go
deleted file mode 100644
index 8bf74d77..00000000
--- a/cmd/oc/internal/config/config_test.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package config
-
-import (
- "os"
- "path/filepath"
- "runtime"
- "testing"
-)
-
-func useTemporaryHome(t *testing.T) string {
- t.Helper()
- home := t.TempDir()
- t.Setenv("HOME", home)
- if runtime.GOOS == "windows" {
- t.Setenv("USERPROFILE", home)
- }
- return home
-}
-
-func TestSaveIsPrivateAndRoundTripsLoginMetadata(t *testing.T) {
- home := useTemporaryHome(t)
- want := Config{
- APIURL: "https://example.test",
- APIKey: "osb_secret",
- Login: &LoginMetadata{
- CredentialID: "key-1",
- KeyPrefix: "osb_abcd",
- Name: "oc CLI on test",
- APIURL: "https://example.test",
- },
- }
- if err := Save(want); err != nil {
- t.Fatalf("Save: %v", err)
- }
- got := LoadFile()
- if got.APIKey != want.APIKey || got.Login == nil || got.Login.CredentialID != "key-1" {
- t.Fatalf("LoadFile() = %#v, want %#v", got, want)
- }
-
- if runtime.GOOS != "windows" {
- dirInfo, err := os.Stat(filepath.Join(home, ".oc"))
- if err != nil {
- t.Fatal(err)
- }
- if got := dirInfo.Mode().Perm(); got != 0o700 {
- t.Fatalf("config dir mode = %o, want 700", got)
- }
- fileInfo, err := os.Stat(ConfigPath())
- if err != nil {
- t.Fatal(err)
- }
- if got := fileInfo.Mode().Perm(); got != 0o600 {
- t.Fatalf("config mode = %o, want 600", got)
- }
- }
-
- matches, err := filepath.Glob(filepath.Join(home, ".oc", ".config-*.tmp"))
- if err != nil {
- t.Fatal(err)
- }
- if len(matches) != 0 {
- t.Fatalf("temporary config files left behind: %v", matches)
- }
-}
-
-func TestEffectiveCredentialSourcePrecedence(t *testing.T) {
- useTemporaryHome(t)
- if got := EffectiveCredentialSource(nil); got != CredentialSourceNone {
- t.Fatalf("empty source = %q", got)
- }
- if err := Save(Config{APIKey: "file"}); err != nil {
- t.Fatal(err)
- }
- if got := EffectiveCredentialSource(nil); got != CredentialSourceFile {
- t.Fatalf("file source = %q", got)
- }
- t.Setenv("OPENCOMPUTER_API_KEY", "environment")
- if got := EffectiveCredentialSource(nil); got != CredentialSourceEnvironment {
- t.Fatalf("env source = %q", got)
- }
-}
diff --git a/cmd/oc/internal/credscan/credscan.go b/cmd/oc/internal/credscan/credscan.go
deleted file mode 100644
index fa6e25ff..00000000
--- a/cmd/oc/internal/credscan/credscan.go
+++ /dev/null
@@ -1,140 +0,0 @@
-// Package credscan is the CLI's PRIMARY credential scan (flue-slice.md
-// contract, design 012 §11.2.6): before a Flue app is bundled and uploaded, walk
-// the user's own source files and refuse to deploy if any looks like a committed
-// provider key. Model credentials come only from the OC credential attached to
-// the agent — never from code.
-//
-// Patterns match the FULL key shape including the body, never a bare prefix. A
-// bare `sk-ant-` grep is a guaranteed false positive: pi-ai's dist ships the
-// literal string "sk-ant-oat" (anthropic-messages.js, apiKey.includes(...)), so
-// a prefix scan fails the unmodified starter. The CLI scans pre-bundle sources
-// (best signal — user code, pre-minification); the deploy's artifact-fileset
-// scan is the entropy-gated backstop for anything that slips through.
-package credscan
-
-import (
- "io/fs"
- "os"
- "path/filepath"
- "regexp"
- "sort"
- "strings"
-)
-
-// Finding is one suspected credential.
-type Finding struct {
- Path string // file, relative to the scanned root
- Line int // 1-based
- Kind string // human label, e.g. "Anthropic API key"
- Match string // the redacted matched token
-}
-
-// patterns are full-key-shape matchers. Each captures enough of the body to be
-// high-confidence; prefixes alone are never used.
-var patterns = []struct {
- kind string
- re *regexp.Regexp
-}{
- // Anthropic: sk-ant-api03-… / sk-ant-oat01-… — prefix + 2 version digits + a
- // long body. The body length is what separates a real key from the literal
- // "sk-ant-oat" that appears (bodiless) in pi-ai's dist.
- {"Anthropic API key", regexp.MustCompile(`sk-ant-(?:api|oat)\d{2}-[A-Za-z0-9_-]{24,}`)},
- // OpenAI: sk-… and project keys sk-proj-… with a long body.
- {"OpenAI project key", regexp.MustCompile(`sk-proj-[A-Za-z0-9_-]{24,}`)},
- {"OpenAI API key", regexp.MustCompile(`sk-[A-Za-z0-9]{32,}`)},
- // OpenRouter.
- {"OpenRouter API key", regexp.MustCompile(`sk-or-v1-[A-Za-z0-9]{32,}`)},
- // Google AI Studio / Gemini.
- {"Google API key", regexp.MustCompile(`AIza[A-Za-z0-9_-]{35}`)},
- // PEM private key block (with a base64 body, not just the header line).
- {"Private key (PEM)", regexp.MustCompile(`-----BEGIN (?:RSA |EC |OPENSSH |PGP |DSA )?PRIVATE KEY-----[A-Za-z0-9+/=\s]{40,}-----END`)},
-}
-
-// scanExts are the text source extensions worth scanning. A Flue app's secrets
-// would live in code/config, not in binary assets.
-var scanExts = map[string]bool{
- ".ts": true, ".tsx": true, ".js": true, ".jsx": true, ".mjs": true, ".cjs": true,
- ".json": true, ".jsonc": true, ".env": true, ".yaml": true, ".yml": true,
- ".toml": true, ".md": true, ".txt": true, ".sh": true, ".bash": true,
-}
-
-// skipDirs are never descended into: build output, deps, vcs.
-var skipDirs = map[string]bool{
- "node_modules": true, "dist-oc": true, "dist": true, ".git": true,
- ".flue": true, "build": true, "coverage": true, ".next": true, "out": true,
-}
-
-const maxFileBytes = 2 << 20 // 2 MiB — skip anything larger (not hand-authored source)
-
-// ScanDir walks root and returns findings from every scannable source file.
-// Build output, node_modules, and VCS dirs are skipped (contract: pre-bundle
-// user sources only).
-func ScanDir(root string) ([]Finding, error) {
- var findings []Finding
- err := filepath.WalkDir(root, func(p string, d fs.DirEntry, walkErr error) error {
- if walkErr != nil {
- return walkErr
- }
- if d.IsDir() {
- if p != root && skipDirs[d.Name()] {
- return fs.SkipDir
- }
- return nil
- }
- if !scanExts[strings.ToLower(filepath.Ext(p))] {
- return nil
- }
- info, err := d.Info()
- if err == nil && info.Size() > maxFileBytes {
- return nil
- }
- content, err := os.ReadFile(p)
- if err != nil {
- return err
- }
- rel, relErr := filepath.Rel(root, p)
- if relErr != nil {
- rel = p
- }
- findings = append(findings, ScanBytes(filepath.ToSlash(rel), content)...)
- return nil
- })
- return findings, err
-}
-
-// ScanBytes scans one file's content. Pure and deterministic — the unit-test
-// entry point. Matching is over the whole content (not line-by-line) so
-// multi-line shapes like PEM blocks are caught; the line number is derived from
-// the match offset. Findings are sorted by line for a stable report.
-func ScanBytes(path string, content []byte) []Finding {
- var out []Finding
- s := string(content)
- for _, p := range patterns {
- for _, loc := range p.re.FindAllStringIndex(s, -1) {
- out = append(out, Finding{
- Path: path,
- Line: 1 + strings.Count(s[:loc[0]], "\n"),
- Kind: p.kind,
- Match: redact(s[loc[0]:loc[1]]),
- })
- }
- }
- sort.SliceStable(out, func(i, j int) bool {
- if out[i].Line != out[j].Line {
- return out[i].Line < out[j].Line
- }
- return out[i].Kind < out[j].Kind
- })
- return out
-}
-
-// redact keeps a short recognizable head + tail so a report is actionable
-// without printing the secret in full.
-func redact(s string) string {
- s = strings.ReplaceAll(s, "\n", "")
- s = strings.ReplaceAll(s, "\r", "")
- if len(s) <= 14 {
- return s[:min(len(s), 8)] + "…"
- }
- return s[:10] + "…" + s[len(s)-4:]
-}
diff --git a/cmd/oc/internal/credscan/credscan_test.go b/cmd/oc/internal/credscan/credscan_test.go
deleted file mode 100644
index c353775b..00000000
--- a/cmd/oc/internal/credscan/credscan_test.go
+++ /dev/null
@@ -1,104 +0,0 @@
-package credscan
-
-import (
- "os"
- "path/filepath"
- "strings"
- "testing"
-)
-
-func TestFlagsRealKeys(t *testing.T) {
- cases := []struct {
- name, kind, content string
- }{
- {"anthropic api", "Anthropic API key", `const c = "sk-ant-api03-AbCdEf0123456789AbCdEf0123456789_-xyzTUV";`},
- {"anthropic oat", "Anthropic API key", `ANTHROPIC_API_KEY=sk-ant-oat01-ZZZ0123456789ABCDEFGHIJ0123456789klmnop`},
- {"openai proj", "OpenAI project key", `key: 'sk-proj-abcdef0123456789ABCDEFGHIJ0123456789xyz'`},
- {"openrouter", "OpenRouter API key", `OPENROUTER_KEY = "sk-or-v1-0123456789abcdef0123456789abcdef0123456789abcdef"`},
- {"google", "Google API key", `AIzaSyA1234567890abcdefghijklmnopqrstuvw`},
- }
- for _, c := range cases {
- f := ScanBytes("x.ts", []byte(c.content))
- if len(f) == 0 {
- t.Errorf("%s: expected a finding, got none", c.name)
- continue
- }
- if f[0].Kind != c.kind {
- t.Errorf("%s: kind = %q, want %q", c.name, f[0].Kind, c.kind)
- }
- if strings.Contains(c.content, f[0].Match) {
- t.Errorf("%s: match %q is not redacted (appears verbatim)", c.name, f[0].Match)
- }
- }
-}
-
-func TestPEMPrivateKeyFlagged(t *testing.T) {
- pem := "-----BEGIN RSA PRIVATE KEY-----\n" +
- "MIIEpAIBAAKCAQEA0Z3VS5JJcds3xfn/ygWyF0qXo3pEGuTs2Z9tWnZ2Vtis3Vs\n" +
- "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6A7B8C9D0E1F2\n" +
- "-----END RSA PRIVATE KEY-----"
- if f := ScanBytes("key.pem", []byte(pem)); len(f) == 0 {
- t.Fatal("expected PEM private key to be flagged")
- }
-}
-
-// The false-positive leg (matrix row 13b): the bare literal "sk-ant-oat" that
-// pi-ai's dist ships (apiKey.includes('sk-ant-oat')) must NOT trip the scan, nor
-// must ordinary starter code.
-func TestNoFalsePositives(t *testing.T) {
- clean := []string{
- `if (apiKey.includes('sk-ant-oat') || apiKey.includes('sk-ant-api')) { /* ... */ }`,
- `// keys look like sk-ant-... — never commit them`,
- `import * as v from 'valibot';`,
- `const orders = await import('../data/orders.json', { with: { type: 'json' } });`,
- `export const model = 'anthropic/claude-sonnet-5';`,
- `-----BEGIN PRIVATE KEY-----`, // header alone, no base64 body
- `const sha = "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0";`, // 40-hex git sha, not sk- shaped
- `const id = "sk";`,
- }
- for _, c := range clean {
- if f := ScanBytes("x.ts", []byte(c)); len(f) != 0 {
- t.Errorf("false positive on %q: %+v", c, f)
- }
- }
-}
-
-func TestScanDirSkipsBuildAndDeps(t *testing.T) {
- root := t.TempDir()
- realKey := "sk-ant-api03-AbCdEf0123456789AbCdEf0123456789_-xyzTUV"
- mustWrite(t, filepath.Join(root, "src", "opencomputer.ts"), "export const ok = 1;\n")
- // A key inside skipped trees must be ignored (bundled deps / build output).
- mustWrite(t, filepath.Join(root, "node_modules", "pi-ai", "dist.js"), "x="+realKey+"\n")
- mustWrite(t, filepath.Join(root, "dist-oc", "oc.js"), "y="+realKey+"\n")
-
- f, err := ScanDir(root)
- if err != nil {
- t.Fatal(err)
- }
- if len(f) != 0 {
- t.Fatalf("expected no findings (keys were only in skipped dirs), got %+v", f)
- }
-
- // The same key in a real source file IS flagged, with a repo-relative path.
- mustWrite(t, filepath.Join(root, "src", "tools", "leak.ts"), "const k = '"+realKey+"';\n")
- f, err = ScanDir(root)
- if err != nil {
- t.Fatal(err)
- }
- if len(f) != 1 {
- t.Fatalf("expected 1 finding, got %d: %+v", len(f), f)
- }
- if f[0].Path != "src/tools/leak.ts" {
- t.Errorf("path = %q, want src/tools/leak.ts", f[0].Path)
- }
-}
-
-func mustWrite(t *testing.T, path, content string) {
- t.Helper()
- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
- t.Fatal(err)
- }
-}
diff --git a/cmd/oc/internal/fluebuild/fluebuild.go b/cmd/oc/internal/fluebuild/fluebuild.go
deleted file mode 100644
index 1dec6ef7..00000000
--- a/cmd/oc/internal/fluebuild/fluebuild.go
+++ /dev/null
@@ -1,753 +0,0 @@
-// Package fluebuild validates, builds, and packages a Flue application without
-// authenticating to or calling any OpenComputer service.
-//
-// It is shared by the local `oc agent deploy` flow and the managed repository
-// builder. Keep the Deployment type as the single Go representation of the
-// deployment.json handoff contract: the deploy runner must not reconstruct it
-// from loosely typed maps.
-package fluebuild
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "io/fs"
- "os"
- "os/exec"
- pathpkg "path"
- "path/filepath"
- "regexp"
- "strings"
- "time"
-
- "github.com/BurntSushi/toml"
- "github.com/Masterminds/semver/v3"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/bundle"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/credscan"
-)
-
-const (
- SchemaVersion = 1
- TargetCloudflare = "cloudflare"
- BundleFilename = "bundle.tgz"
- DeploymentFilename = "deployment.json"
- BuildOutputDir = "dist"
- BundleMaxBytes = 64 << 20
-)
-
-var (
- bindingIdentifier = regexp.MustCompile(`^[A-Za-z_$][A-Za-z0-9_$]*$`)
- compatibilityFlag = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`)
- bundleDigest = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
-)
-
-// Deployment is the versioned, byte-free metadata written to deployment.json.
-// Wrangler and Bundle are absent only from a --check-only projection.
-type Deployment struct {
- SchemaVersion int `json:"schema_version"`
- Flue Flue `json:"flue"`
- Model string `json:"model"`
- Vars Vars `json:"vars"`
- Runtime Runtime `json:"runtime"`
- Bundle *Bundle `json:"bundle,omitempty"`
- Builder Builder `json:"builder"`
-}
-
-type Flue struct {
- Entrypoint string `json:"entrypoint"`
- Wrangler *WranglerDescriptor `json:"wrangler,omitempty"`
-}
-
-type Runtime struct {
- Family string `json:"family" toml:"family"`
- Type string `json:"type" toml:"type"`
-}
-
-type Bundle struct {
- Digest string `json:"digest"`
- SizeBytes int64 `json:"size_bytes"`
-}
-
-type Builder struct {
- Version string `json:"version"`
- SynthesisTemplate string `json:"synthesis_template,omitempty"`
-}
-
-// Vars is named so callers cannot accidentally replace the manifest-derived
-// snapshot with an untyped map. Values are non-secret strings from agent.toml.
-type Vars map[string]string
-
-type DOBinding struct {
- Name string `json:"name"`
- ClassName string `json:"class_name"`
-}
-
-// WranglerDescriptor is the strict Worker-for-Platforms subset accepted from
-// Flue's generated wrangler.json. Raw Wrangler configuration never crosses the
-// builder boundary.
-type WranglerDescriptor struct {
- Main string `json:"main"`
- CompatibilityDate string `json:"compatibility_date"`
- CompatibilityFlags []string `json:"compatibility_flags"`
- NoBundle bool `json:"no_bundle"`
- DurableObjects struct {
- Bindings []DOBinding `json:"bindings"`
- } `json:"durable_objects"`
-}
-
-type manifest struct {
- Name string `toml:"name"`
- Model string `toml:"model"`
- Vars Vars `toml:"vars"`
- Runtime Runtime `toml:"runtime"`
-}
-
-type packageJSON struct {
- Engines map[string]string `json:"engines"`
- Dependencies map[string]string `json:"dependencies"`
- DevDependencies map[string]string `json:"devDependencies"`
-}
-
-type packageLockJSON struct {
- LockfileVersion int `json:"lockfileVersion"`
-}
-
-type generatedWrangler struct {
- Main string `json:"main"`
- CompatibilityDate string `json:"compatibility_date"`
- CompatibilityFlags []string `json:"compatibility_flags"`
- NoBundle bool `json:"no_bundle"`
- DurableObjects struct {
- Bindings []json.RawMessage `json:"bindings"`
- } `json:"durable_objects"`
-}
-
-// Options controls one offline build. NodeVersion may be supplied by a pinned
-// builder snapshot; when empty, the local node binary is queried. OutputDir is
-// optional for in-process callers such as `oc agent deploy`.
-type Options struct {
- Dir string
- Target string
- OutputDir string
- BuilderVersion string
- NodeVersion string
- // SynthesisTemplateVersion is a trusted managed-builder identity; local builds leave it empty.
- SynthesisTemplateVersion string
- CheckOnly bool
- BuildStdout io.Writer
- BuildStderr io.Writer
-}
-
-type Result struct {
- Deployment Deployment
- Bundle []byte
-}
-
-// CredentialError reports redacted credential findings from either source or
-// built modules. It deliberately retains typed findings for CLI presentation.
-type CredentialError struct {
- Stage string
- Findings []credscan.Finding
-}
-
-func (e *CredentialError) Error() string {
- var b strings.Builder
- fmt.Fprintf(&b, "possible credential(s) in %s", e.Stage)
- for _, finding := range e.Findings {
- fmt.Fprintf(&b, "\n %s:%d %s %s", finding.Path, finding.Line, finding.Kind, finding.Match)
- }
- return b.String()
-}
-
-// Build validates the repository projection and, unless CheckOnly is set,
-// invokes the repository-local Flue CLI and returns the canonical artifact.
-// This function performs no source fetch, network request, API authentication,
-// upload, or deployment. Repository code executed by Flue is untrusted and must
-// be isolated by the caller.
-func Build(ctx context.Context, opts Options) (Result, error) {
- if strings.TrimSpace(opts.Dir) == "" {
- opts.Dir = "."
- }
- if opts.Target == "" {
- opts.Target = TargetCloudflare
- }
- if opts.Target != TargetCloudflare {
- return Result{}, fmt.Errorf("unsupported target %q (only %q is supported)", opts.Target, TargetCloudflare)
- }
- if opts.BuilderVersion == "" {
- opts.BuilderVersion = "dev"
- }
- if !strings.HasPrefix(opts.BuilderVersion, "oc@") {
- opts.BuilderVersion = "oc@" + opts.BuilderVersion
- }
-
- projection, err := inspect(ctx, opts.Dir, opts.BuilderVersion, opts.NodeVersion, opts.SynthesisTemplateVersion)
- if err != nil {
- return Result{}, err
- }
- if opts.CheckOnly {
- if err := ValidateDeployment(projection, false); err != nil {
- return Result{}, err
- }
- return Result{Deployment: projection}, nil
- }
-
- stdout := opts.BuildStdout
- if stdout == nil {
- stdout = os.Stderr
- }
- stderr := opts.BuildStderr
- if stderr == nil {
- stderr = os.Stderr
- }
- if err := RunFlue(ctx, opts.Dir, stdout, stderr); err != nil {
- return Result{}, err
- }
-
- files, wrangler, err := ReadBundle(filepath.Join(opts.Dir, BuildOutputDir))
- if err != nil {
- return Result{}, err
- }
- if err := scanBuiltModules(files); err != nil {
- return Result{}, err
- }
- tarGz, err := bundle.Pack(files)
- if err != nil {
- return Result{}, fmt.Errorf("pack bundle: %w", err)
- }
- if len(tarGz) > BundleMaxBytes {
- return Result{}, fmt.Errorf("bundle is %d bytes, over the %d MiB limit", len(tarGz), BundleMaxBytes>>20)
- }
-
- projection.Flue.Wrangler = &wrangler
- projection.Bundle = &Bundle{
- Digest: bundle.Digest(tarGz),
- SizeBytes: int64(len(tarGz)),
- }
- result := Result{Deployment: projection, Bundle: tarGz}
- if err := ValidateDeployment(result.Deployment, true); err != nil {
- return Result{}, err
- }
- if opts.OutputDir != "" {
- if err := WriteOutput(opts.OutputDir, result); err != nil {
- return Result{}, err
- }
- }
- return result, nil
-}
-
-// ParseDeployment decodes deployment.json with unknown-field rejection, then
-// validates either the check-only projection or the complete artifact shape.
-func ParseDeployment(raw []byte, requireArtifact bool) (Deployment, error) {
- decoder := json.NewDecoder(bytes.NewReader(raw))
- decoder.DisallowUnknownFields()
- var deployment Deployment
- if err := decoder.Decode(&deployment); err != nil {
- return Deployment{}, fmt.Errorf("decode deployment metadata: %w", err)
- }
- var trailing any
- if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
- return Deployment{}, fmt.Errorf("decode deployment metadata: trailing JSON value")
- }
- if err := ValidateDeployment(deployment, requireArtifact); err != nil {
- return Deployment{}, err
- }
- return deployment, nil
-}
-
-// ValidateDeployment enforces the frozen schema independently of Build so an
-// artifact consumer can fail closed before trusting the handoff metadata.
-func ValidateDeployment(deployment Deployment, requireArtifact bool) error {
- if deployment.SchemaVersion != SchemaVersion {
- return fmt.Errorf("deployment schema_version %d is unsupported", deployment.SchemaVersion)
- }
- if strings.TrimSpace(deployment.Flue.Entrypoint) == "" {
- return fmt.Errorf("deployment flue.entrypoint is required")
- }
- if strings.TrimSpace(deployment.Model) == "" {
- return fmt.Errorf("deployment model is required")
- }
- if deployment.Vars == nil {
- return fmt.Errorf("deployment vars must be an object")
- }
- if deployment.Runtime.Family != "flue" || deployment.Runtime.Type != "default" {
- return fmt.Errorf("deployment runtime must be family=%q, type=%q", "flue", "default")
- }
- if !strings.HasPrefix(deployment.Builder.Version, "oc@") || strings.TrimPrefix(deployment.Builder.Version, "oc@") == "" {
- return fmt.Errorf("deployment builder.version must use oc@<version>")
- }
- if deployment.Builder.SynthesisTemplate != "" {
- valid := regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,127}$`)
- if !valid.MatchString(deployment.Builder.SynthesisTemplate) {
- return fmt.Errorf("deployment builder.synthesis_template is invalid")
- }
- }
- if !requireArtifact {
- if deployment.Flue.Wrangler != nil || deployment.Bundle != nil {
- return fmt.Errorf("check-only deployment must omit flue.wrangler and bundle")
- }
- return nil
- }
- if deployment.Flue.Wrangler == nil || deployment.Bundle == nil {
- return fmt.Errorf("complete deployment requires flue.wrangler and bundle")
- }
- if !bundleDigest.MatchString(deployment.Bundle.Digest) || deployment.Bundle.SizeBytes <= 0 || deployment.Bundle.SizeBytes > BundleMaxBytes {
- return fmt.Errorf("deployment bundle digest/size is invalid")
- }
- wranglerJSON, err := json.Marshal(deployment.Flue.Wrangler)
- if err != nil {
- return fmt.Errorf("encode deployment wrangler: %w", err)
- }
- if _, err := ExtractWranglerDescriptor(wranglerJSON); err != nil {
- return fmt.Errorf("deployment flue.wrangler: %w", err)
- }
- return nil
-}
-
-func inspect(ctx context.Context, dir, builderVersion, nodeVersion, synthesisTemplateVersion string) (Deployment, error) {
- findings, err := credscan.ScanDir(dir)
- if err != nil {
- return Deployment{}, fmt.Errorf("credential scan: %w", err)
- }
- if len(findings) > 0 {
- return Deployment{}, &CredentialError{Stage: "source", Findings: findings}
- }
-
- manifestBytes, err := readRequiredRegularFile(dir, "agent.toml", 1<<20)
- if err != nil {
- return Deployment{}, err
- }
- var m manifest
- if _, err := toml.Decode(string(manifestBytes), &m); err != nil {
- return Deployment{}, fmt.Errorf("parse agent.toml: %w", err)
- }
- if strings.TrimSpace(m.Name) == "" {
- return Deployment{}, fmt.Errorf("agent.toml needs a `name` Flue entrypoint")
- }
- if strings.TrimSpace(m.Model) == "" {
- return Deployment{}, fmt.Errorf("agent.toml needs a `model`")
- }
- if m.Runtime.Family != "flue" {
- return Deployment{}, fmt.Errorf("agent.toml runtime.family must be %q", "flue")
- }
- if m.Runtime.Type == "" {
- m.Runtime.Type = "default"
- }
- if m.Runtime.Type != "default" {
- return Deployment{}, fmt.Errorf("agent.toml runtime.type %q is unsupported; managed Flue currently requires %q", m.Runtime.Type, "default")
- }
- if m.Vars == nil {
- m.Vars = Vars{}
- }
-
- packageBytes, err := readRequiredRegularFile(dir, "package.json", 2<<20)
- if err != nil {
- return Deployment{}, err
- }
- var pkg packageJSON
- if err := json.Unmarshal(packageBytes, &pkg); err != nil {
- return Deployment{}, fmt.Errorf("parse package.json: %w", err)
- }
- flueVersion := pkg.DevDependencies["@flue/cli"]
- if flueVersion == "" {
- flueVersion = pkg.Dependencies["@flue/cli"]
- }
- if strings.TrimSpace(flueVersion) == "" {
- return Deployment{}, fmt.Errorf("package.json must declare a local @flue/cli dependency")
- }
- nodeEngine := strings.TrimSpace(pkg.Engines["node"])
- if nodeEngine == "" {
- return Deployment{}, fmt.Errorf("package.json must declare engines.node")
- }
- if nodeVersion == "" {
- nodeVersion, err = installedNodeVersion(ctx)
- if err != nil {
- return Deployment{}, err
- }
- }
- if err := validateNodeEngine(nodeEngine, nodeVersion); err != nil {
- return Deployment{}, err
- }
-
- lockBytes, err := readRequiredRegularFile(dir, "package-lock.json", 25<<20)
- if err != nil {
- return Deployment{}, err
- }
- var lock packageLockJSON
- if err := json.Unmarshal(lockBytes, &lock); err != nil {
- return Deployment{}, fmt.Errorf("parse package-lock.json: %w", err)
- }
- if lock.LockfileVersion != 2 && lock.LockfileVersion != 3 {
- return Deployment{}, fmt.Errorf("package-lock.json lockfileVersion %d is unsupported (expected 2 or 3)", lock.LockfileVersion)
- }
-
- return Deployment{
- SchemaVersion: SchemaVersion,
- Flue: Flue{Entrypoint: m.Name},
- Model: m.Model,
- Vars: m.Vars,
- Runtime: m.Runtime,
- Builder: Builder{
- Version: builderVersion,
- SynthesisTemplate: synthesisTemplateVersion,
- },
- }, nil
-}
-
-func readRequiredRegularFile(root, name string, maxBytes int64) ([]byte, error) {
- path := filepath.Join(root, name)
- info, err := os.Lstat(path)
- if err != nil {
- if errors.Is(err, os.ErrNotExist) {
- return nil, fmt.Errorf("required file %s is missing", name)
- }
- return nil, fmt.Errorf("inspect %s: %w", name, err)
- }
- if !info.Mode().IsRegular() {
- return nil, fmt.Errorf("required file %s must be a regular file", name)
- }
- if info.Size() > maxBytes {
- return nil, fmt.Errorf("required file %s is %d bytes, over the %d byte limit", name, info.Size(), maxBytes)
- }
- content, err := os.ReadFile(path)
- if err != nil {
- return nil, fmt.Errorf("read %s: %w", name, err)
- }
- return content, nil
-}
-
-func installedNodeVersion(ctx context.Context) (string, error) {
- cmd := exec.CommandContext(ctx, "node", "--version")
- cmd.Stdin = nil
- out, err := cmd.Output()
- if err != nil {
- return "", fmt.Errorf("read node version: %w", err)
- }
- return strings.TrimSpace(string(out)), nil
-}
-
-func validateNodeEngine(constraint, nodeVersion string) error {
- version, err := semver.NewVersion(strings.TrimPrefix(strings.TrimSpace(nodeVersion), "v"))
- if err != nil {
- return fmt.Errorf("invalid builder node version %q: %w", nodeVersion, err)
- }
- rangeConstraint, err := semver.NewConstraint(constraint)
- if err != nil {
- return fmt.Errorf("invalid package.json engines.node %q: %w", constraint, err)
- }
- if !rangeConstraint.Check(version) {
- return fmt.Errorf("node_unsupported: package engines.node %q does not admit builder node %s", constraint, version.String())
- }
- return nil
-}
-
-// RunFlue invokes only an already-installed repository-local Flue CLI. The
-// npx fallback has --no-install, so this helper never fetches a package.
-func RunFlue(ctx context.Context, dir string, stdout, stderr io.Writer) error {
- args := []string{"build", "--target", TargetCloudflare}
- bin, err := filepath.Abs(filepath.Join(dir, "node_modules", ".bin", "flue"))
- if err != nil {
- return fmt.Errorf("resolve local flue binary: %w", err)
- }
- var cmd *exec.Cmd
- if _, err := os.Stat(bin); err == nil {
- cmd = exec.CommandContext(ctx, bin, args...)
- } else {
- cmd = exec.CommandContext(ctx, "npx", append([]string{"--no-install", "flue"}, args...)...)
- }
- cmd.Dir = dir
- cmd.Env = BuildEnv()
- cmd.Stdin = nil
- cmd.Stdout = stdout
- cmd.Stderr = stderr
- if err := cmd.Run(); err != nil {
- return fmt.Errorf("flue build failed: %w\n(run `npm install` so the flue CLI is available and use a supported Node version)", err)
- }
- return nil
-}
-
-// BuildEnv keeps non-actionable direct-Wrangler warnings out of output while
-// preserving an explicit debugging override.
-func BuildEnv() []string {
- const key = "WRANGLER_LOG"
- const fallback = key + "=error"
- env := os.Environ()
- prefix := key + "="
- for i, value := range env {
- if !strings.HasPrefix(value, prefix) {
- continue
- }
- if value == prefix {
- env[i] = fallback
- }
- return env
- }
- return append(env, fallback)
-}
-
-// ReadBundle extracts a strict descriptor and only regular JavaScript modules
-// from Flue's build output.
-func ReadBundle(distDir string) ([]bundle.File, WranglerDescriptor, error) {
- wranglerPath, err := findGeneratedWrangler(distDir)
- if err != nil {
- return nil, WranglerDescriptor{}, err
- }
- raw, err := os.ReadFile(wranglerPath)
- if err != nil {
- return nil, WranglerDescriptor{}, fmt.Errorf("read %s: %w", wranglerPath, err)
- }
- wrangler, err := ExtractWranglerDescriptor(raw)
- if err != nil {
- return nil, WranglerDescriptor{}, fmt.Errorf("parse %s: %w", wranglerPath, err)
- }
-
- bundleRoot := filepath.Dir(wranglerPath)
- files, err := ReadBundleModules(bundleRoot)
- if err != nil {
- return nil, WranglerDescriptor{}, err
- }
- found := false
- for _, file := range files {
- if file.Path == wrangler.Main {
- found = true
- break
- }
- }
- if !found {
- return nil, WranglerDescriptor{}, fmt.Errorf("entry module %q (wrangler.main) is not in the module output %s", wrangler.Main, bundleRoot)
- }
- return files, wrangler, nil
-}
-
-func safeModulePath(value string) bool {
- if value == "" || strings.HasPrefix(value, "/") || strings.Contains(value, `\`) {
- return false
- }
- if ext := pathpkg.Ext(value); ext != ".js" && ext != ".mjs" {
- return false
- }
- if pathpkg.Clean(value) != value {
- return false
- }
- for _, segment := range strings.Split(value, "/") {
- if segment == "" || segment == "." || segment == ".." {
- return false
- }
- }
- return true
-}
-
-func ExtractWranglerDescriptor(raw []byte) (WranglerDescriptor, error) {
- var generated generatedWrangler
- if err := json.Unmarshal(raw, &generated); err != nil {
- return WranglerDescriptor{}, err
- }
- if !safeModulePath(generated.Main) {
- return WranglerDescriptor{}, fmt.Errorf("main must be a safe relative .js/.mjs module path")
- }
- if parsed, err := time.Parse("2006-01-02", generated.CompatibilityDate); err != nil || parsed.Format("2006-01-02") != generated.CompatibilityDate {
- return WranglerDescriptor{}, fmt.Errorf("compatibility_date must be a valid YYYY-MM-DD date")
- }
- if generated.CompatibilityFlags == nil || len(generated.CompatibilityFlags) > 64 {
- return WranglerDescriptor{}, fmt.Errorf("compatibility_flags must be a unique array of valid flag names")
- }
- seenFlags := map[string]bool{}
- for _, flag := range generated.CompatibilityFlags {
- if !compatibilityFlag.MatchString(flag) || seenFlags[flag] {
- return WranglerDescriptor{}, fmt.Errorf("compatibility_flags must be a unique array of valid flag names")
- }
- seenFlags[flag] = true
- }
- if !generated.NoBundle {
- return WranglerDescriptor{}, fmt.Errorf("no_bundle must be true")
- }
-
- bindings := make([]DOBinding, 0, len(generated.DurableObjects.Bindings))
- names := map[string]bool{}
- classes := map[string]bool{}
- for _, rawBinding := range generated.DurableObjects.Bindings {
- var fields map[string]json.RawMessage
- if err := json.Unmarshal(rawBinding, &fields); err != nil {
- return WranglerDescriptor{}, fmt.Errorf("invalid durable-object binding: %w", err)
- }
- if len(fields) != 2 || fields["name"] == nil || fields["class_name"] == nil {
- return WranglerDescriptor{}, fmt.Errorf("durable-object bindings may contain only name and class_name")
- }
- var binding DOBinding
- if err := json.Unmarshal(rawBinding, &binding); err != nil {
- return WranglerDescriptor{}, fmt.Errorf("invalid durable-object binding: %w", err)
- }
- if !bindingIdentifier.MatchString(binding.Name) || !bindingIdentifier.MatchString(binding.ClassName) {
- return WranglerDescriptor{}, fmt.Errorf("durable-object binding names and class names must be non-empty JavaScript identifiers")
- }
- if names[binding.Name] || classes[binding.ClassName] {
- return WranglerDescriptor{}, fmt.Errorf("durable-object binding names and class names must be unique")
- }
- names[binding.Name] = true
- classes[binding.ClassName] = true
- bindings = append(bindings, binding)
- }
- if len(bindings) == 0 {
- return WranglerDescriptor{}, fmt.Errorf("at least one same-script durable-object binding is required")
- }
-
- var descriptor WranglerDescriptor
- descriptor.Main = generated.Main
- descriptor.CompatibilityDate = generated.CompatibilityDate
- descriptor.CompatibilityFlags = append([]string(nil), generated.CompatibilityFlags...)
- descriptor.NoBundle = true
- descriptor.DurableObjects.Bindings = bindings
- return descriptor, nil
-}
-
-func findGeneratedWrangler(distDir string) (string, error) {
- if info, err := os.Stat(distDir); err != nil || !info.IsDir() {
- return "", fmt.Errorf("build output %s not found — did `flue build --target cloudflare` run?", distDir)
- }
- flat := filepath.Join(distDir, "wrangler.json")
- if _, err := os.Stat(flat); err == nil {
- return flat, nil
- }
- matches, _ := filepath.Glob(filepath.Join(distDir, "*", "wrangler.json"))
- switch len(matches) {
- case 0:
- return "", fmt.Errorf("no wrangler.json under %s — `flue build --target cloudflare` produced no Cloudflare build", distDir)
- case 1:
- return matches[0], nil
- default:
- return "", fmt.Errorf("multiple wrangler.json under %s (%v) — ambiguous flue build output", distDir, matches)
- }
-}
-
-// ReadBundleModules walks one generated output into a normalized module-only
-// fileset. Unsafe links and unrecognized output fail closed.
-func ReadBundleModules(root string) ([]bundle.File, error) {
- if info, err := os.Stat(root); err != nil || !info.IsDir() {
- return nil, fmt.Errorf("build output %s not found — did `flue build --target cloudflare` run?", root)
- }
- var files []bundle.File
- err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error {
- if walkErr != nil {
- return walkErr
- }
- if entry.IsDir() {
- if path != root && entry.Name() == ".vite" {
- return filepath.SkipDir
- }
- return nil
- }
- if entry.Type()&os.ModeSymlink != 0 {
- return fmt.Errorf("build output contains symlink %s; only regular modules are allowed", path)
- }
- rel, err := filepath.Rel(root, path)
- if err != nil {
- return err
- }
- rel = filepath.ToSlash(rel)
- info, err := entry.Info()
- if err != nil {
- return err
- }
- if !info.Mode().IsRegular() {
- return fmt.Errorf("build output contains non-regular file %s", path)
- }
- if rel == "wrangler.json" || strings.HasSuffix(rel, ".map") {
- return nil
- }
- if !safeModulePath(rel) {
- return fmt.Errorf("build output contains unsupported file %q; expected only .js/.mjs modules", rel)
- }
- content, err := os.ReadFile(path)
- if err != nil {
- return err
- }
- files = append(files, bundle.File{
- Path: rel,
- Mode: bundle.NormalizeMode(int(info.Mode().Perm())),
- Content: content,
- })
- return nil
- })
- if err != nil {
- return nil, fmt.Errorf("read %s: %w", root, err)
- }
- if len(files) == 0 {
- return nil, fmt.Errorf("build output %s is empty", root)
- }
- return files, nil
-}
-
-func scanBuiltModules(files []bundle.File) error {
- var findings []credscan.Finding
- for _, file := range files {
- findings = append(findings, credscan.ScanBytes(file.Path, file.Content)...)
- }
- if len(findings) > 0 {
- return &CredentialError{Stage: "built modules", Findings: findings}
- }
- return nil
-}
-
-// WriteOutput atomically replaces the two files in the offline artifact
-// contract. It never writes source paths or bundle bytes into deployment.json.
-func WriteOutput(outputDir string, result Result) error {
- if err := ValidateDeployment(result.Deployment, true); err != nil {
- return err
- }
- if int64(len(result.Bundle)) != result.Deployment.Bundle.SizeBytes || bundle.Digest(result.Bundle) != result.Deployment.Bundle.Digest {
- return fmt.Errorf("bundle bytes do not match deployment metadata")
- }
- if err := os.MkdirAll(outputDir, 0o755); err != nil {
- return fmt.Errorf("create output directory: %w", err)
- }
- info, err := os.Lstat(outputDir)
- if err != nil {
- return fmt.Errorf("inspect output directory: %w", err)
- }
- if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
- return fmt.Errorf("output must be a real directory, not a link")
- }
- metadata, err := json.MarshalIndent(result.Deployment, "", " ")
- if err != nil {
- return fmt.Errorf("encode deployment metadata: %w", err)
- }
- metadata = append(metadata, '\n')
- if err := atomicWrite(filepath.Join(outputDir, BundleFilename), result.Bundle, 0o644); err != nil {
- return err
- }
- if err := atomicWrite(filepath.Join(outputDir, DeploymentFilename), metadata, 0o644); err != nil {
- return err
- }
- return nil
-}
-
-func atomicWrite(path string, content []byte, mode os.FileMode) error {
- tmp, err := os.CreateTemp(filepath.Dir(path), ".oc-build-*")
- if err != nil {
- return fmt.Errorf("create temporary output: %w", err)
- }
- tmpPath := tmp.Name()
- defer os.Remove(tmpPath)
- if err := tmp.Chmod(mode); err != nil {
- _ = tmp.Close()
- return err
- }
- if _, err := tmp.Write(content); err != nil {
- _ = tmp.Close()
- return err
- }
- if err := tmp.Sync(); err != nil {
- _ = tmp.Close()
- return err
- }
- if err := tmp.Close(); err != nil {
- return err
- }
- if err := os.Rename(tmpPath, path); err != nil {
- return fmt.Errorf("replace %s: %w", filepath.Base(path), err)
- }
- return nil
-}
diff --git a/cmd/oc/internal/fluebuild/fluebuild_test.go b/cmd/oc/internal/fluebuild/fluebuild_test.go
deleted file mode 100644
index 56d39366..00000000
--- a/cmd/oc/internal/fluebuild/fluebuild_test.go
+++ /dev/null
@@ -1,271 +0,0 @@
-package fluebuild
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "io/fs"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "testing"
-)
-
-const (
- testBuilderVersion = "0.6.0.9-test"
- testNodeVersion = "v22.19.0"
- testWrangler = `{"name":"fixture","main":"index.js","compatibility_date":"2026-07-01","compatibility_flags":["nodejs_compat"],"no_bundle":true,"durable_objects":{"bindings":[{"name":"AGENT","class_name":"FlueStarterAgent"},{"name":"FLUE_REGISTRY","class_name":"FlueRegistry"}]},"vars":{"MUST_NOT_LEAVE":"raw"},"routes":["example.com/*"]}`
-)
-
-func TestCheckOnlyMatchesFrozenProjectionWithoutExecutingRepositoryCode(t *testing.T) {
- dir := copyFixture(t)
- sentinel := filepath.Join(dir, "executed")
- installFakeFlue(t, dir, "touch "+shellQuote(sentinel))
- t.Setenv("PATH", "") // NodeVersion is pinned by the snapshot; no process is needed.
-
- result, err := Build(context.Background(), Options{
- Dir: dir,
- CheckOnly: true,
- BuilderVersion: testBuilderVersion,
- NodeVersion: testNodeVersion,
- })
- if err != nil {
- t.Fatalf("check-only: %v", err)
- }
- if _, err := os.Stat(sentinel); !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("check-only executed repository code; stat error = %v", err)
- }
- if result.Bundle != nil || result.Deployment.Bundle != nil || result.Deployment.Flue.Wrangler != nil {
- t.Fatalf("check-only returned build-derived fields: %#v", result)
- }
-
- got, err := json.MarshalIndent(result.Deployment, "", " ")
- if err != nil {
- t.Fatal(err)
- }
- got = append(got, '\n')
- want, err := os.ReadFile(filepath.Join("testdata", "check-only.json"))
- if err != nil {
- t.Fatal(err)
- }
- if !bytes.Equal(got, want) {
- t.Fatalf("check-only contract drifted\n--- got ---\n%s\n--- want ---\n%s", got, want)
- }
-}
-
-func TestCheckOnlyCarriesTrustedSynthesisTemplateIdentity(t *testing.T) {
- dir := copyFixture(t)
- result, err := Build(context.Background(), Options{
- Dir: dir,
- CheckOnly: true,
- BuilderVersion: testBuilderVersion,
- NodeVersion: testNodeVersion,
- SynthesisTemplateVersion: "flue-prompt-template-v1",
- })
- if err != nil {
- t.Fatalf("check-only: %v", err)
- }
- if got := result.Deployment.Builder.SynthesisTemplate; got != "flue-prompt-template-v1" {
- t.Fatalf("synthesis template = %q", got)
- }
- raw, err := json.Marshal(result.Deployment)
- if err != nil {
- t.Fatal(err)
- }
- if !bytes.Contains(raw, []byte(`"synthesis_template":"flue-prompt-template-v1"`)) {
- t.Fatalf("deployment omitted synthesis identity: %s", raw)
- }
-}
-
-func TestBuildWritesDeterministicArtifactContract(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("fake Flue binary is a POSIX shell script")
- }
- dir := copyFixture(t)
- installFakeFlue(t, dir, fakeSuccessfulBuildScript())
- out := t.TempDir()
-
- first, err := Build(context.Background(), Options{
- Dir: dir,
- OutputDir: out,
- BuilderVersion: testBuilderVersion,
- NodeVersion: testNodeVersion,
- })
- if err != nil {
- t.Fatalf("build: %v", err)
- }
- second, err := Build(context.Background(), Options{
- Dir: dir,
- BuilderVersion: testBuilderVersion,
- NodeVersion: testNodeVersion,
- })
- if err != nil {
- t.Fatalf("second build: %v", err)
- }
- if !bytes.Equal(first.Bundle, second.Bundle) || first.Deployment.Bundle.Digest != second.Deployment.Bundle.Digest {
- t.Fatal("identical fixture did not produce byte-identical bundle and digest")
- }
- // This pins the canonical transport bytes, not merely the digest shape.
- const goldenDigest = "sha256:169890136b7f3080bdb27dfc7f053e9bb1c31a977febbfbdd1d69c86b00dd5fd"
- if first.Deployment.Bundle.Digest != goldenDigest {
- t.Fatalf("canonical digest = %s, want %s", first.Deployment.Bundle.Digest, goldenDigest)
- }
-
- bundleBytes, err := os.ReadFile(filepath.Join(out, BundleFilename))
- if err != nil {
- t.Fatal(err)
- }
- if !bytes.Equal(bundleBytes, first.Bundle) {
- t.Fatal("bundle.tgz differs from returned canonical bytes")
- }
- metadataBytes, err := os.ReadFile(filepath.Join(out, DeploymentFilename))
- if err != nil {
- t.Fatal(err)
- }
- wantMetadata, err := os.ReadFile(filepath.Join("testdata", "deployment.json"))
- if err != nil {
- t.Fatal(err)
- }
- if !bytes.Equal(metadataBytes, wantMetadata) {
- t.Fatalf("deployment.json contract drifted\n--- got ---\n%s\n--- want ---\n%s", metadataBytes, wantMetadata)
- }
- parsed, err := ParseDeployment(metadataBytes, true)
- if err != nil {
- t.Fatalf("parse deployment.json: %v", err)
- }
- if parsed.Bundle.Digest != goldenDigest || parsed.Bundle.SizeBytes != int64(len(bundleBytes)) {
- t.Fatalf("deployment bundle metadata = %#v", parsed.Bundle)
- }
- if parsed.Flue.Entrypoint != "flue-starter" || parsed.Runtime.Type != "default" || parsed.Flue.Wrangler.Main != "index.js" {
- t.Fatalf("deployment projection drifted: %#v", parsed)
- }
- for _, forbidden := range []string{dir, "MUST_NOT_LEAVE", "example.com"} {
- if strings.Contains(string(metadataBytes), forbidden) {
- t.Fatalf("deployment.json leaked %q: %s", forbidden, metadataBytes)
- }
- }
-}
-
-func TestBuildScansFinalModules(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("fake Flue binary is a POSIX shell script")
- }
- dir := copyFixture(t)
- installFakeFlue(t, dir, fakeSuccessfulBuildScript()+"\n"+
- "printf '%s' 'const key=\"sk-ant-api03-AbCdEf0123456789AbCdEf0123456789_-xyzTUV\";' > dist/fixture/leak.js\n")
-
- _, err := Build(context.Background(), Options{
- Dir: dir, BuilderVersion: testBuilderVersion, NodeVersion: testNodeVersion,
- })
- var credentialErr *CredentialError
- if !errors.As(err, &credentialErr) || credentialErr.Stage != "built modules" {
- t.Fatalf("expected built-module credential error, got %v", err)
- }
-}
-
-func TestCheckOnlyRejectsUnsupportedBuilderNode(t *testing.T) {
- dir := copyFixture(t)
- _, err := Build(context.Background(), Options{
- Dir: dir, CheckOnly: true, BuilderVersion: testBuilderVersion, NodeVersion: "v23.0.0",
- })
- if err == nil || !strings.Contains(err.Error(), "node_unsupported") {
- t.Fatalf("expected node_unsupported, got %v", err)
- }
-}
-
-func TestCheckOnlyRejectsUnsupportedRuntimeType(t *testing.T) {
- dir := copyFixture(t)
- manifestPath := filepath.Join(dir, "agent.toml")
- manifest, err := os.ReadFile(manifestPath)
- if err != nil {
- t.Fatal(err)
- }
- manifest = bytes.Replace(manifest, []byte(`family = "flue"`), []byte("family = \"flue\"\ntype = \"durable\""), 1)
- if err := os.WriteFile(manifestPath, manifest, 0o644); err != nil {
- t.Fatal(err)
- }
-
- _, err = Build(context.Background(), Options{
- Dir: dir, CheckOnly: true, BuilderVersion: testBuilderVersion, NodeVersion: testNodeVersion,
- })
- if err == nil || !strings.Contains(err.Error(), `runtime.type "durable" is unsupported`) || !strings.Contains(err.Error(), `requires "default"`) {
- t.Fatalf("expected actionable runtime.type rejection, got %v", err)
- }
-}
-
-func TestParseDeploymentRejectsUnknownFields(t *testing.T) {
- raw, err := os.ReadFile(filepath.Join("testdata", "check-only.json"))
- if err != nil {
- t.Fatal(err)
- }
- raw = bytes.Replace(raw, []byte(`"schema_version": 1`), []byte(`"schema_version": 1, "source_path": "/tmp/leak"`), 1)
- if _, err := ParseDeployment(raw, false); err == nil || !strings.Contains(err.Error(), "unknown field") {
- t.Fatalf("expected unknown-field rejection, got %v", err)
- }
-}
-
-func TestParseDeploymentRejectsUnsupportedRuntimeType(t *testing.T) {
- raw, err := os.ReadFile(filepath.Join("testdata", "check-only.json"))
- if err != nil {
- t.Fatal(err)
- }
- raw = bytes.Replace(raw, []byte(`"type": "default"`), []byte(`"type": "durable"`), 1)
- if _, err := ParseDeployment(raw, false); err == nil || !strings.Contains(err.Error(), `type="default"`) {
- t.Fatalf("expected frozen runtime type rejection, got %v", err)
- }
-}
-
-func copyFixture(t *testing.T) string {
- t.Helper()
- src := filepath.Join("testdata", "starter")
- dst := t.TempDir()
- err := filepath.WalkDir(src, func(path string, entry fs.DirEntry, walkErr error) error {
- if walkErr != nil {
- return walkErr
- }
- rel, err := filepath.Rel(src, path)
- if err != nil {
- return err
- }
- target := filepath.Join(dst, rel)
- if entry.IsDir() {
- return os.MkdirAll(target, 0o755)
- }
- content, err := os.ReadFile(path)
- if err != nil {
- return err
- }
- return os.WriteFile(target, content, 0o644)
- })
- if err != nil {
- t.Fatal(err)
- }
- return dst
-}
-
-func installFakeFlue(t *testing.T, dir, body string) {
- t.Helper()
- path := filepath.Join(dir, "node_modules", ".bin", "flue")
- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
- t.Fatal(err)
- }
- script := "#!/bin/sh\nset -eu\ntest \"$1\" = build\ntest \"$2\" = --target\ntest \"$3\" = cloudflare\n" + body + "\n"
- if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
- t.Fatal(err)
- }
-}
-
-func fakeSuccessfulBuildScript() string {
- return "mkdir -p dist/fixture/assets dist/fixture/.vite\n" +
- "cat > dist/fixture/index.js <<'JS'\nexport default { fetch() { return new Response(\"ok\"); } };\nJS\n" +
- "cat > dist/fixture/assets/chunk.mjs <<'JS'\nexport const chunk = 1;\nJS\n" +
- "printf '%s' '{\"ignored\":true}' > dist/fixture/index.js.map\n" +
- "printf '%s' '{\"ignored\":true}' > dist/fixture/.vite/manifest.json\n" +
- "cat > dist/fixture/wrangler.json <<'JSON'\n" + testWrangler + "\nJSON"
-}
-
-func shellQuote(value string) string {
- return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'"
-}
diff --git a/cmd/oc/internal/fluebuild/testdata/check-only.json b/cmd/oc/internal/fluebuild/testdata/check-only.json
deleted file mode 100644
index cef0d14f..00000000
--- a/cmd/oc/internal/fluebuild/testdata/check-only.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "schema_version": 1,
- "flue": {
- "entrypoint": "flue-starter"
- },
- "model": "anthropic/claude-sonnet-5",
- "vars": {
- "MAX_ITEMS": "12",
- "PUBLIC_MODE": "careful"
- },
- "runtime": {
- "family": "flue",
- "type": "default"
- },
- "builder": {
- "version": "[email protected]"
- }
-}
diff --git a/cmd/oc/internal/fluebuild/testdata/deployment.json b/cmd/oc/internal/fluebuild/testdata/deployment.json
deleted file mode 100644
index 5590f96f..00000000
--- a/cmd/oc/internal/fluebuild/testdata/deployment.json
+++ /dev/null
@@ -1,42 +0,0 @@
-{
- "schema_version": 1,
- "flue": {
- "entrypoint": "flue-starter",
- "wrangler": {
- "main": "index.js",
- "compatibility_date": "2026-07-01",
- "compatibility_flags": [
- "nodejs_compat"
- ],
- "no_bundle": true,
- "durable_objects": {
- "bindings": [
- {
- "name": "AGENT",
- "class_name": "FlueStarterAgent"
- },
- {
- "name": "FLUE_REGISTRY",
- "class_name": "FlueRegistry"
- }
- ]
- }
- }
- },
- "model": "anthropic/claude-sonnet-5",
- "vars": {
- "MAX_ITEMS": "12",
- "PUBLIC_MODE": "careful"
- },
- "runtime": {
- "family": "flue",
- "type": "default"
- },
- "bundle": {
- "digest": "sha256:169890136b7f3080bdb27dfc7f053e9bb1c31a977febbfbdd1d69c86b00dd5fd",
- "size_bytes": 202
- },
- "builder": {
- "version": "[email protected]"
- }
-}
diff --git a/cmd/oc/internal/fluebuild/testdata/starter/agent.toml b/cmd/oc/internal/fluebuild/testdata/starter/agent.toml
deleted file mode 100644
index c4441217..00000000
--- a/cmd/oc/internal/fluebuild/testdata/starter/agent.toml
+++ /dev/null
@@ -1,9 +0,0 @@
-name = "flue-starter"
-model = "anthropic/claude-sonnet-5"
-
-[runtime]
-family = "flue"
-
-[vars]
-PUBLIC_MODE = "careful"
-MAX_ITEMS = "12"
diff --git a/cmd/oc/internal/fluebuild/testdata/starter/package-lock.json b/cmd/oc/internal/fluebuild/testdata/starter/package-lock.json
deleted file mode 100644
index de727113..00000000
--- a/cmd/oc/internal/fluebuild/testdata/starter/package-lock.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "name": "flue-starter-fixture",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {}
-}
diff --git a/cmd/oc/internal/fluebuild/testdata/starter/package.json b/cmd/oc/internal/fluebuild/testdata/starter/package.json
deleted file mode 100644
index 7a097141..00000000
--- a/cmd/oc/internal/fluebuild/testdata/starter/package.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "name": "flue-starter-fixture",
- "private": true,
- "engines": {
- "node": ">=22.19.0 <23"
- },
- "devDependencies": {
- "@flue/cli": "0.1.0"
- }
-}
diff --git a/cmd/oc/internal/fluebuild/testdata/starter/src/agent.ts b/cmd/oc/internal/fluebuild/testdata/starter/src/agent.ts
deleted file mode 100644
index 24ad2222..00000000
--- a/cmd/oc/internal/fluebuild/testdata/starter/src/agent.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const fixture = "offline-builder";
diff --git a/cmd/oc/internal/output/output.go b/cmd/oc/internal/output/output.go
deleted file mode 100644
index b6c0ad38..00000000
--- a/cmd/oc/internal/output/output.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package output
-
-import (
- "encoding/json"
- "fmt"
- "io"
- "os"
- "text/tabwriter"
-)
-
-// Printer handles output formatting (table or JSON).
-type Printer struct {
- JSON bool
- W io.Writer
-}
-
-// New creates a printer that writes to stdout.
-func New(jsonOutput bool) *Printer {
- return &Printer{JSON: jsonOutput, W: os.Stdout}
-}
-
-// PrintJSON outputs v as indented JSON.
-func (p *Printer) PrintJSON(v interface{}) error {
- enc := json.NewEncoder(p.W)
- enc.SetIndent("", " ")
- return enc.Encode(v)
-}
-
-// Table prints a table with headers and rows.
-func (p *Printer) Table(headers []string, rows [][]string) {
- w := tabwriter.NewWriter(p.W, 0, 4, 2, ' ', 0)
- for i, h := range headers {
- if i > 0 {
- fmt.Fprint(w, "\t")
- }
- fmt.Fprint(w, h)
- }
- fmt.Fprintln(w)
- for _, row := range rows {
- for i, col := range row {
- if i > 0 {
- fmt.Fprint(w, "\t")
- }
- fmt.Fprint(w, col)
- }
- fmt.Fprintln(w)
- }
- w.Flush()
-}
-
-// Print outputs v as JSON if --json is set, otherwise calls the fallback.
-func (p *Printer) Print(v interface{}, tableFn func()) {
- if p.JSON {
- p.PrintJSON(v)
- return
- }
- tableFn()
-}
diff --git a/cmd/oc/main.go b/cmd/oc/main.go
deleted file mode 100644
index e1f12cd1..00000000
--- a/cmd/oc/main.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package main
-
-import (
- "os"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/commands"
-)
-
-func main() {
- // RenderError prints the error (JSON under --json) and returns the classified
- // exit code (0/1/3/4/5); a nil error returns 0. See commands/exit.go.
- os.Exit(commands.RenderError(commands.Execute()))
-}
diff --git a/go.mod b/go.mod
index 849be631..cf7afd33 100644
--- a/go.mod
+++ b/go.mod
@@ -9,8 +9,6 @@ require (
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork v1.1.0
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.4.0
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4
- github.com/BurntSushi/toml v1.6.0
- github.com/Masterminds/semver/v3 v3.5.0
github.com/aws/aws-sdk-go-v2 v1.43.5
github.com/aws/aws-sdk-go-v2/config v1.32.31
github.com/aws/aws-sdk-go-v2/credentials v1.19.30
@@ -33,13 +31,11 @@ require (
github.com/prometheus/client_golang v1.20.5
github.com/redis/go-redis/v9 v9.18.0
github.com/segmentio/analytics-go/v3 v3.3.0
- github.com/spf13/cobra v1.10.2
github.com/stripe/stripe-go/v82 v82.5.1
github.com/workos/workos-go/v4 v4.46.1
golang.org/x/net v0.49.0
golang.org/x/sync v0.20.0
golang.org/x/sys v0.42.0
- golang.org/x/term v0.40.0
google.golang.org/grpc v1.69.4
google.golang.org/protobuf v1.36.3
modernc.org/sqlite v1.50.1
@@ -70,7 +66,6 @@ require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/google/go-querystring v1.0.0 // indirect
- github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
@@ -88,7 +83,6 @@ require (
github.com/prometheus/procfs v0.15.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/segmentio/backo-go v1.0.0 // indirect
- github.com/spf13/pflag v1.0.9 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
go.uber.org/atomic v1.11.0 // indirect
diff --git a/go.sum b/go.sum
index 875b8adf..ea06b5fb 100644
--- a/go.sum
+++ b/go.sum
@@ -28,10 +28,6 @@ github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJ
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 h1:XRzhVemXdgvJqCH0sFfrBUTnUJSBrBf7++ypk+twtRs=
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk=
-github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
-github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
-github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=
-github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
github.com/aws/aws-sdk-go-v2 v1.43.5 h1:yKT5GYnFWhuDo+DqKvE5ZPwVn3RjC4MAeBtZGlh6AVM=
github.com/aws/aws-sdk-go-v2 v1.43.5/go.mod h1:wZjAJppCntyOGgVSmgVTfDyRJK5PHOasO6Wsy8U7Axk=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14 h1:3IZY0XAJquT3aHzbkHfPzy4ACPcEjVG0x87KOwtpqGY=
@@ -88,7 +84,6 @@ github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
-github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -126,8 +121,6 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
-github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
-github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
@@ -189,15 +182,10 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
-github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/segmentio/analytics-go/v3 v3.3.0 h1:8VOMaVGBW03pdBrj1CMFfY9o/rnjJC+1wyQHlVxjw5o=
github.com/segmentio/analytics-go/v3 v3.3.0/go.mod h1:p8owAF8X+5o27jmvUognuXxdtqvSGtD0ZrfY2kcS9bE=
github.com/segmentio/backo-go v1.0.0 h1:kbOAtGJY2DqOR0jfRkYEorx/b18RgtepGtY3+Cpe6qA=
github.com/segmentio/backo-go v1.0.0/go.mod h1:kJ9mm9YmoWSkk+oQ+5Cj8DEoRCX2JT6As4kEtIIOp1M=
-github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
-github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
-github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
-github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
@@ -234,7 +222,6 @@ go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
-go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
@@ -248,8 +235,6 @@ golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
-golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=
-golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg=
diff --git a/scripts/test-cli.sh b/scripts/test-cli.sh
deleted file mode 100755
index 33455676..00000000
--- a/scripts/test-cli.sh
+++ /dev/null
@@ -1,363 +0,0 @@
-#!/bin/bash
-set -euo pipefail
-
-# CLI integration test — runs against a live OpenComputer server.
-# Usage: ./scripts/test-cli.sh [api-url] [api-key]
-# e.g. ./scripts/test-cli.sh https://dev.opensandbox.ai osb_...
-# Defaults to dev.opensandbox.ai if no URL provided.
-
-API_URL="${1:?Usage: $0 <api-url> <api-key>}"
-API_KEY="${2:?Usage: $0 <api-url> <api-key>}"
-
-OC="./bin/oc --api-url $API_URL --api-key $API_KEY"
-
-RED='\033[0;31m'
-GREEN='\033[0;32m'
-YELLOW='\033[0;33m'
-CYAN='\033[0;36m'
-BOLD='\033[1m'
-NC='\033[0m'
-
-PASSED=0
-FAILED=0
-SANDBOX_ID=""
-CHECKPOINT_ID=""
-PATCH_ID=""
-
-info() { echo -e "${CYAN}[INFO]${NC} $*"; }
-ok() { echo -e "${GREEN}[PASS]${NC} $*"; PASSED=$((PASSED + 1)); }
-fail() { echo -e "${RED}[FAIL]${NC} $*"; FAILED=$((FAILED + 1)); }
-header() { echo -e "\n${BOLD}=== $* ===${NC}"; }
-
-cleanup() {
- if [ -n "$SANDBOX_ID" ]; then
- info "Cleaning up sandbox $SANDBOX_ID..."
- $OC sandbox kill "$SANDBOX_ID" 2>/dev/null || true
- fi
- echo
- echo -e "${BOLD}Results: ${GREEN}$PASSED passed${NC}, ${RED}$FAILED failed${NC}"
- if [ "$FAILED" -gt 0 ]; then
- exit 1
- fi
-}
-trap cleanup EXIT
-
-# Build the CLI first
-header "Building oc CLI"
-CGO_ENABLED=0 go build -o ./bin/oc ./cmd/oc
-ok "Built ./bin/oc"
-
-# -------------------------------------------------------
-header "Sandbox Lifecycle"
-# -------------------------------------------------------
-
-# sandbox create
-info "Creating sandbox..."
-CREATE_OUT=$($OC sandbox create --json)
-SANDBOX_ID=$(echo "$CREATE_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])")
-if [ -n "$SANDBOX_ID" ]; then
- ok "sandbox create → $SANDBOX_ID"
-else
- fail "sandbox create — no sandbox ID returned"
-fi
-
-# sandbox list
-info "Listing sandboxes..."
-LIST_OUT=$($OC sandbox list --json)
-if echo "$LIST_OUT" | python3 -c "import sys,json; sandboxes=json.load(sys.stdin); assert any(s['sandboxID']=='$SANDBOX_ID' for s in sandboxes)" 2>/dev/null; then
- ok "sandbox list — found $SANDBOX_ID"
-else
- fail "sandbox list — $SANDBOX_ID not in list"
-fi
-
-# ls shortcut
-LS_OUT=$($OC ls --json)
-if echo "$LS_OUT" | python3 -c "import sys,json; sandboxes=json.load(sys.stdin); assert any(s['sandboxID']=='$SANDBOX_ID' for s in sandboxes)" 2>/dev/null; then
- ok "ls shortcut — found $SANDBOX_ID"
-else
- fail "ls shortcut — $SANDBOX_ID not in list"
-fi
-
-# sandbox get
-info "Getting sandbox..."
-GET_OUT=$($OC sandbox get "$SANDBOX_ID" --json)
-GET_STATUS=$(echo "$GET_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['status'])")
-if [ "$GET_STATUS" = "running" ]; then
- ok "sandbox get — status=running"
-else
- fail "sandbox get — expected running, got $GET_STATUS"
-fi
-
-# sandbox set-timeout
-info "Setting timeout..."
-TIMEOUT_OUT=$($OC sandbox set-timeout "$SANDBOX_ID" 600 2>&1) || true
-if echo "$TIMEOUT_OUT" | grep -qi "updated\|timeout"; then
- ok "sandbox set-timeout 600"
-else
- # Some server modes require direct worker connectURL for set-timeout
- info "sandbox set-timeout skipped (server returned: $(echo "$TIMEOUT_OUT" | head -1))"
-fi
-
-# -------------------------------------------------------
-header "Command Execution"
-# -------------------------------------------------------
-
-# exec
-info "Running command..."
-EXEC_OUT=$($OC exec "$SANDBOX_ID" -- echo hello-from-cli)
-if echo "$EXEC_OUT" | grep -q "hello-from-cli"; then
- ok "exec 'echo hello-from-cli'"
-else
- fail "exec — expected 'hello-from-cli', got: $EXEC_OUT"
-fi
-
-# exec with --json
-EXEC_JSON=$($OC exec "$SANDBOX_ID" --json -- whoami)
-EXEC_EXIT=$(echo "$EXEC_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin)['exitCode'])")
-if [ "$EXEC_EXIT" = "0" ]; then
- ok "exec --json — exitCode=0"
-else
- fail "exec --json — exitCode=$EXEC_EXIT"
-fi
-
-# exec with --cwd
-EXEC_CWD=$($OC exec "$SANDBOX_ID" --cwd /tmp -- pwd)
-if echo "$EXEC_CWD" | grep -q "/tmp"; then
- ok "exec --cwd /tmp — pwd=/tmp"
-else
- fail "exec --cwd — expected /tmp, got: $EXEC_CWD"
-fi
-
-# -------------------------------------------------------
-header "Checkpoints"
-# -------------------------------------------------------
-
-# checkpoint create
-info "Creating checkpoint..."
-CP_OUT=$($OC checkpoint create "$SANDBOX_ID" --name "cli-test-v1" --json)
-CHECKPOINT_ID=$(echo "$CP_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
-if [ -n "$CHECKPOINT_ID" ]; then
- ok "checkpoint create → $CHECKPOINT_ID"
-else
- fail "checkpoint create — no ID returned"
-fi
-
-# Wait for checkpoint to be ready
-info "Waiting for checkpoint to be ready..."
-for i in $(seq 1 30); do
- CP_STATUS=$($OC checkpoint list "$SANDBOX_ID" --json | python3 -c "
-import sys,json
-cps=json.load(sys.stdin)
-for cp in cps:
- if cp['id']=='$CHECKPOINT_ID':
- print(cp['status'])
- break
-" 2>/dev/null || echo "unknown")
- if [ "$CP_STATUS" = "ready" ]; then
- break
- fi
- sleep 2
-done
-
-if [ "$CP_STATUS" = "ready" ]; then
- ok "checkpoint ready after ${i}s"
-else
- fail "checkpoint not ready after 60s (status=$CP_STATUS)"
-fi
-
-# checkpoint list
-CP_LIST=$($OC checkpoint list "$SANDBOX_ID" --json)
-CP_COUNT=$(echo "$CP_LIST" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))")
-if [ "$CP_COUNT" -ge 1 ]; then
- ok "checkpoint list — $CP_COUNT checkpoint(s)"
-else
- fail "checkpoint list — expected >=1, got $CP_COUNT"
-fi
-
-# checkpoint list (table output)
-CP_TABLE=$($OC checkpoint list "$SANDBOX_ID")
-if echo "$CP_TABLE" | grep -q "cli-test-v1"; then
- ok "checkpoint list (table) — shows name"
-else
- fail "checkpoint list (table) — missing name"
-fi
-
-# -------------------------------------------------------
-header "Checkpoint Patches"
-# -------------------------------------------------------
-
-if [ -n "$CHECKPOINT_ID" ]; then
- # patch create
- info "Creating patch..."
- PATCH_SCRIPT=$(mktemp)
- echo '#!/bin/bash
-echo "patched" > /tmp/patch-marker' > "$PATCH_SCRIPT"
-
- PATCH_OUT=$($OC patch create "$CHECKPOINT_ID" --script "$PATCH_SCRIPT" --description "CLI test patch" --json)
- rm -f "$PATCH_SCRIPT"
- PATCH_ID=$(echo "$PATCH_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['patch']['id'])")
- if [ -n "$PATCH_ID" ]; then
- ok "patch create → $PATCH_ID"
- else
- fail "patch create — no ID returned"
- fi
-
- # patch list
- PATCH_LIST=$($OC patch list "$CHECKPOINT_ID" --json)
- PATCH_COUNT=$(echo "$PATCH_LIST" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))")
- if [ "$PATCH_COUNT" -ge 1 ]; then
- ok "patch list — $PATCH_COUNT patch(es)"
- else
- fail "patch list — expected >=1, got $PATCH_COUNT"
- fi
-
- # patch list (table)
- PATCH_TABLE=$($OC patch list "$CHECKPOINT_ID")
- if echo "$PATCH_TABLE" | grep -q "CLI test patch"; then
- ok "patch list (table) — shows description"
- else
- fail "patch list (table) — missing description"
- fi
-
- # patch delete
- if [ -n "$PATCH_ID" ]; then
- info "Deleting patch..."
- if $OC patch delete "$CHECKPOINT_ID" "$PATCH_ID" 2>&1 | grep -qi "deleted"; then
- ok "patch delete"
- else
- fail "patch delete"
- fi
- fi
-fi
-
-# -------------------------------------------------------
-header "Checkpoint Spawn"
-# -------------------------------------------------------
-
-if [ -n "$CHECKPOINT_ID" ] && [ "$CP_STATUS" = "ready" ]; then
- info "Spawning sandbox from checkpoint..."
- SPAWN_OUT=$($OC checkpoint spawn "$CHECKPOINT_ID" --json)
- SPAWN_ID=$(echo "$SPAWN_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])")
- if [ -n "$SPAWN_ID" ]; then
- ok "checkpoint spawn → $SPAWN_ID"
- # Clean up spawned sandbox
- $OC sandbox kill "$SPAWN_ID" 2>/dev/null || true
- ok "killed spawned sandbox"
- else
- fail "checkpoint spawn — no sandbox ID returned"
- fi
-fi
-
-# -------------------------------------------------------
-header "Checkpoint Restore"
-# -------------------------------------------------------
-
-if [ -n "$CHECKPOINT_ID" ] && [ "$CP_STATUS" = "ready" ]; then
- info "Restoring checkpoint..."
- if $OC checkpoint restore "$SANDBOX_ID" "$CHECKPOINT_ID" 2>&1 | grep -qi "restored"; then
- ok "checkpoint restore"
- else
- fail "checkpoint restore"
- fi
-
- # Give restore a moment to complete
- sleep 3
-fi
-
-# -------------------------------------------------------
-header "Checkpoint Delete"
-# -------------------------------------------------------
-
-if [ -n "$CHECKPOINT_ID" ]; then
- info "Deleting checkpoint..."
- CP_DEL_OUT=$($OC checkpoint delete "$SANDBOX_ID" "$CHECKPOINT_ID" 2>&1) || true
- if echo "$CP_DEL_OUT" | grep -qi "deleted"; then
- ok "checkpoint delete"
- else
- # Checkpoint may already be consumed by restore
- info "checkpoint delete skipped ($(echo "$CP_DEL_OUT" | head -1))"
- fi
- CHECKPOINT_ID=""
-fi
-
-# -------------------------------------------------------
-header "Preview URLs"
-# -------------------------------------------------------
-
-# preview create
-info "Creating preview URL on port 8080..."
-PREV_OUT=$($OC preview create "$SANDBOX_ID" --port 8080 --json 2>&1) || true
-if echo "$PREV_OUT" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d.get('hostname','')" 2>/dev/null; then
- PREV_HOST=$(echo "$PREV_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['hostname'])")
- ok "preview create — $PREV_HOST"
-
- # preview list
- PREV_LIST=$($OC preview list "$SANDBOX_ID" --json)
- PREV_COUNT=$(echo "$PREV_LIST" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))")
- if [ "$PREV_COUNT" -ge 1 ]; then
- ok "preview list — $PREV_COUNT URL(s)"
- else
- fail "preview list — expected >=1, got $PREV_COUNT"
- fi
-
- # preview delete
- if $OC preview delete "$SANDBOX_ID" 8080 2>&1 | grep -qi "deleted"; then
- ok "preview delete"
- else
- fail "preview delete"
- fi
-else
- info "preview create skipped (may not be configured on dev server)"
-fi
-
-# -------------------------------------------------------
-header "Hibernate & Wake"
-# -------------------------------------------------------
-
-# hibernate
-info "Hibernating sandbox..."
-HIB_OUT=$($OC sandbox hibernate "$SANDBOX_ID" --json 2>&1) || true
-if echo "$HIB_OUT" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d.get('sandboxId','')" 2>/dev/null; then
- ok "sandbox hibernate"
-
- # Wait a moment for hibernation to complete
- sleep 3
-
- # wake
- info "Waking sandbox..."
- WAKE_OUT=$($OC sandbox wake "$SANDBOX_ID" --json)
- WAKE_STATUS=$(echo "$WAKE_OUT" | python3 -c "import sys,json; print(json.load(sys.stdin)['status'])")
- if [ "$WAKE_STATUS" = "running" ]; then
- ok "sandbox wake — status=running"
- else
- fail "sandbox wake — expected running, got $WAKE_STATUS"
- fi
-else
- info "hibernate skipped (may not be supported in this mode)"
-fi
-
-# -------------------------------------------------------
-header "Config"
-# -------------------------------------------------------
-
-CONFIG_OUT=$($OC config show)
-if echo "$CONFIG_OUT" | grep -q "API URL"; then
- ok "config show"
-else
- fail "config show — missing API URL"
-fi
-
-# -------------------------------------------------------
-header "Cleanup"
-# -------------------------------------------------------
-
-info "Killing sandbox $SANDBOX_ID..."
-if $OC sandbox kill "$SANDBOX_ID" 2>&1 | grep -qi "killed"; then
- ok "sandbox kill"
- SANDBOX_ID="" # Prevent double-cleanup in trap
-else
- fail "sandbox kill"
-fi
-
-echo
-echo -e "${BOLD}All tests complete.${NC}"