Skip to content

An open-source, faster Devin alternative

TypeScript

feat(cli): Flue deploy flow — artifact build, digest, upload, --source

Igor Zalutski150ba5952f00
diff --git a/cmd/oc/internal/commands/agent_crud.go b/cmd/oc/internal/commands/agent_crud.go
index e5eb2c5a..2c9015a9 100644
--- a/cmd/oc/internal/commands/agent_crud.go
+++ b/cmd/oc/internal/commands/agent_crud.go
@@ -21,13 +21,18 @@ var agentCreateCmd = &cobra.Command{
model, _ := cmd.Flags().GetString("model")
runtime, _ := cmd.Flags().GetString("runtime")
credential, _ := cmd.Flags().GetString("credential")
- if prompt == "" {
+ // 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], "prompt": prompt, "model": model}
+ body := map[string]interface{}{"name": args[0], "model": model}
+ if prompt != "" {
+ body["prompt"] = prompt
+ }
if runtime != "" {
body["runtime"] = runtime
}
@@ -113,9 +118,9 @@ var agentGetCmd = &cobra.Command{
}
func registerAgentCrud() {
- agentCreateCmd.Flags().String("prompt", "", "System prompt (required)")
+ 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)")
+ 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)")
diff --git a/cmd/oc/internal/commands/agent_deploy.go b/cmd/oc/internal/commands/agent_deploy.go
index 63afd69a..ee6d96ae 100644
--- a/cmd/oc/internal/commands/agent_deploy.go
+++ b/cmd/oc/internal/commands/agent_deploy.go
@@ -210,6 +210,11 @@ var agentDeployCmd = &cobra.Command{
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)
@@ -302,7 +307,10 @@ func ensureAgentByName(cmd *cobra.Command, sc *client.Client, name, prompt, mode
return a.ID, false, nil
}
}
- body := map[string]interface{}{"name": name, "prompt": prompt, "model": model, "runtime": runtime}
+ 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
@@ -579,6 +587,7 @@ func registerAgentDeploy() {
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)")
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)")
diff --git a/cmd/oc/internal/commands/agent_deploy_flue.go b/cmd/oc/internal/commands/agent_deploy_flue.go
new file mode 100644
index 00000000..0c5c62c9
--- /dev/null
+++ b/cmd/oc/internal/commands/agent_deploy_flue.go
@@ -0,0 +1,242 @@
+package commands
+
+// Flue deploy flow (design 012 §11.7.8, flue-slice.md W4 + contracts 3/4/5/10).
+// When agent.toml declares `[runtime] family = "flue"`, `oc agent deploy` does
+// NOT read prompt.md/skills/; instead it builds the app into a content-addressed
+// artifact, uploads it via a presigned PUT, and references the digest in the
+// deployment. The host boot-verifies the artifact (a ~30–60s scratch-sandbox
+// probe) before activating the revision — the existing poll absorbs that latency.
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "io/fs"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "time"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/credscan"
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/filesetdigest"
+ "github.com/spf13/cobra"
+)
+
+const (
+ flueBuildOutputDir = "dist-oc" // oc-flue-build's output (gitignored in the app)
+ flueArtifactMaxBytes = 64 << 20 // contract 3: server caps at 64 MiB — fail early
+)
+
+// artifactUploadResponse is the reply from POST /v3/agents/:id/artifacts (contract 3).
+type artifactUploadResponse struct {
+ URL string `json:"url"`
+ ExpiresAt string `json:"expires_at"`
+}
+
+func deployFlue(cmd *cobra.Command, sc *client.Client, dir string, m *manifest, noActivate bool) error {
+ // 1. Primary credential scan over the user's pre-bundle sources (§11.2.6):
+ // model keys come from the OC credential, never from committed code.
+ findings, err := credscan.ScanDir(dir)
+ if err != nil {
+ return fmt.Errorf("credential scan: %w", err)
+ }
+ if len(findings) > 0 {
+ fmt.Fprintln(os.Stderr, "Refusing to deploy — possible credential(s) in source (model keys come from the OC credential, never code):")
+ for _, f := range findings {
+ fmt.Fprintf(os.Stderr, " %s:%d %s %s\n", f.Path, f.Line, f.Kind, f.Match)
+ }
+ return &ExitError{Code: 1}
+ }
+
+ // 2. Build the artifact with the app's own @opencomputer/flue devDependency.
+ if err := runFlueBuild(cmd.Context(), dir); err != nil {
+ return err
+ }
+
+ // 3. Hash dist-oc/ into the content-addressed digest + canonical tar.gz.
+ outDir := filepath.Join(dir, flueBuildOutputDir)
+ files, err := readArtifactFiles(outDir)
+ if err != nil {
+ return err
+ }
+ digest := filesetdigest.Digest(files)
+ tarGz, err := filesetdigest.CanonicalTarGz(files)
+ if err != nil {
+ return fmt.Errorf("pack artifact: %w", err)
+ }
+ if len(tarGz) > flueArtifactMaxBytes {
+ return fmt.Errorf("artifact is %d bytes, over the %d MiB limit", len(tarGz), flueArtifactMaxBytes>>20)
+ }
+
+ // 4. Resolve the target agent (create with runtime=flue + no prompt if new).
+ id, err := resolveDeployAgent(cmd, sc, m)
+ if err != nil {
+ return err
+ }
+
+ // 5. Upload: presigned PUT (contract 3).
+ if err := uploadArtifact(cmd.Context(), sc, id, digest, tarGz); err != nil {
+ return err
+ }
+
+ // 6. Deployment referencing the digest (contract 10 — no prompt/skills path).
+ rt := m.Runtime.Type
+ if rt == "" {
+ rt = "default"
+ }
+ input := map[string]interface{}{
+ "type": "inline",
+ "model": m.Model,
+ "runtime": map[string]string{"type": rt},
+ "framework_artifact_digest": digest,
+ }
+ 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 — deploy boots a verify sandbox before activating.
+ 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}
+ }
+ printer.Print(d, func() {
+ n := revisionNumber(cmd, sc, id, d.RevisionID)
+ status := "staged"
+ if d.Active {
+ status = "active"
+ }
+ fmt.Printf("Deployed revision %d — %s (%s)\n", n, status, shortDigest(digest))
+ })
+ return nil
+}
+
+// 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
+}
+
+// runFlueBuild runs the app's oc-flue-build (its own devDependency). Prefers the
+// locally-installed bin (avoids npx fetching an arbitrary package from the
+// registry); falls back to `npx oc-flue-build`. Build output goes to stderr so
+// stdout stays clean for --json.
+func runFlueBuild(ctx context.Context, dir string) error {
+ bin := filepath.Join(dir, "node_modules", ".bin", "oc-flue-build")
+ var c *exec.Cmd
+ if _, err := os.Stat(bin); err == nil {
+ c = exec.CommandContext(ctx, bin)
+ } else {
+ c = exec.CommandContext(ctx, "npx", "oc-flue-build")
+ }
+ c.Dir = dir
+ c.Stdout = os.Stderr
+ c.Stderr = os.Stderr
+ c.Stdin = os.Stdin
+ if err := c.Run(); err != nil {
+ return fmt.Errorf("oc-flue-build failed: %w\n(run `npm install` so @opencomputer/flue is available, node >= 22)", err)
+ }
+ return nil
+}
+
+// readArtifactFiles walks the build output into a fileset with normalized modes,
+// requiring artifact.json (the manifest the host validates + pins).
+func readArtifactFiles(outDir string) ([]filesetdigest.File, error) {
+ if info, err := os.Stat(outDir); err != nil || !info.IsDir() {
+ return nil, fmt.Errorf("build output %s not found — did oc-flue-build run?", outDir)
+ }
+ var files []filesetdigest.File
+ hasManifest := false
+ err := filepath.WalkDir(outDir, func(p string, d fs.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return walkErr
+ }
+ if d.IsDir() {
+ return nil
+ }
+ rel, err := filepath.Rel(outDir, p)
+ if err != nil {
+ return err
+ }
+ rel = filepath.ToSlash(rel)
+ content, err := os.ReadFile(p)
+ if err != nil {
+ return err
+ }
+ st, err := d.Info()
+ if err != nil {
+ return err
+ }
+ if rel == "artifact.json" {
+ hasManifest = true
+ }
+ files = append(files, filesetdigest.File{
+ Path: rel,
+ Mode: filesetdigest.NormalizeMode(int(st.Mode().Perm())),
+ Content: content,
+ })
+ return nil
+ })
+ if err != nil {
+ return nil, fmt.Errorf("read %s: %w", outDir, err)
+ }
+ if len(files) == 0 {
+ return nil, fmt.Errorf("build output %s is empty", outDir)
+ }
+ if !hasManifest {
+ return nil, fmt.Errorf("%s/artifact.json missing — build did not produce a valid artifact", outDir)
+ }
+ return files, nil
+}
+
+// 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 artifact upload url: %w", err)
+ }
+ if resp.URL == "" {
+ return fmt.Errorf("artifact upload url response was empty")
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPut, resp.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 artifact: %w", err)
+ }
+ defer put.Body.Close()
+ if put.StatusCode >= 300 {
+ snippet, _ := io.ReadAll(io.LimitReader(put.Body, 512))
+ return fmt.Errorf("artifact upload failed (HTTP %d): %s", put.StatusCode, string(snippet))
+ }
+ return nil
+}
diff --git a/cmd/oc/internal/commands/session.go b/cmd/oc/internal/commands/session.go
index dedac597..b87121ee 100644
--- a/cmd/oc/internal/commands/session.go
+++ b/cmd/oc/internal/commands/session.go
@@ -6,6 +6,7 @@ package commands
import (
"fmt"
+ "strings"
"github.com/spf13/cobra"
)
@@ -74,6 +75,14 @@ var sessionCreateCmd = &cobra.Command{
if revision != "" {
body["revision"] = revision
}
+ 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
@@ -233,6 +242,32 @@ var sessionSteerCmd = &cobra.Command{
},
}
+// 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{})
@@ -251,6 +286,7 @@ 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().String("revision", "", "Pin a specific revision (number or rev_ id; default = active)")
+ 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)
diff --git a/cmd/oc/internal/commands/session_test.go b/cmd/oc/internal/commands/session_test.go
new file mode 100644
index 00000000..fbfd597d
--- /dev/null
+++ b/cmd/oc/internal/commands/session_test.go
@@ -0,0 +1,49 @@
+package commands
+
+import "testing"
+
+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/credscan/credscan.go b/cmd/oc/internal/credscan/credscan.go
new file mode 100644
index 00000000..fa6e25ff
--- /dev/null
+++ b/cmd/oc/internal/credscan/credscan.go
@@ -0,0 +1,140 @@
+// 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
new file mode 100644
index 00000000..c353775b
--- /dev/null
+++ b/cmd/oc/internal/credscan/credscan_test.go
@@ -0,0 +1,104 @@
+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/filesetdigest/filesetdigest.go b/cmd/oc/internal/filesetdigest/filesetdigest.go
new file mode 100644
index 00000000..964bef36
--- /dev/null
+++ b/cmd/oc/internal/filesetdigest/filesetdigest.go
@@ -0,0 +1,121 @@
+// Package filesetdigest is the Go implementation of the OpenComputer bundle
+// fileset digest + canonical tar.gz — the content-addressing scheme shared by
+// skill bundles and Flue framework artifacts.
+//
+// This is the THIRD implementation of one contract (flue-slice.md contract 4).
+// It MUST stay byte-identical to:
+// - TS runtime: oc-runtimes/adapter-core/src/skills.ts (computeFilesetDigest)
+// - TS host: sessions-api/src/v3/core/skill-bundle-canonical.ts
+//
+// A shared golden vector (a fixed fileset → a fixed digest) locks the three in
+// lockstep; see filesetdigest_test.go. If you change anything here, re-run the
+// golden across all three repos.
+//
+// Digest (contract 4): sha256 over the bytewise-sorted, fixed-order entry list
+// [{"path":…,"mode":…,"sha256":…}, …] serialized as JSON with no whitespace,
+// mode as a bare decimal integer, sha256 the hex of sha256(content). The JSON is
+// hand-built (not encoding/json) so string escaping matches JavaScript's
+// JSON.stringify exactly — the digest is a cross-language content address, and
+// Go's default JSON escaping (HTML entities, / , U+2028/U+2029)
+// diverges from JS.
+package filesetdigest
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+// File is one entry in a bundle fileset. Mode is the POSIX file mode, normalized
+// to 0o644 or 0o755 by the caller (NormalizeMode) — the digest and the tar must
+// use the same value.
+type File struct {
+ Path string // bundle-root-relative, forward-slash separated (e.g. "skills/triage/SKILL.md")
+ Mode int // 0o644 | 0o755
+ Content []byte
+}
+
+// NormalizeMode collapses an on-disk mode to the two the contract allows:
+// 0o755 if any execute bit is set, else 0o644. Matches the CLI/worker skill
+// reader convention (agent.go readSkills).
+func NormalizeMode(mode int) int {
+ if mode&0o111 != 0 {
+ return 0o755
+ }
+ return 0o644
+}
+
+// Digest returns the fileset digest ("sha256:" + hex). Byte-for-byte identical
+// to the TS computeFilesetDigest for the same fileset.
+func Digest(files []File) string {
+ type entry struct {
+ path string
+ mode int
+ sha string
+ }
+ entries := make([]entry, len(files))
+ for i, f := range files {
+ sum := sha256.Sum256(f.Content)
+ entries[i] = entry{path: f.Path, mode: f.Mode, sha: hex.EncodeToString(sum[:])}
+ }
+ // Bytewise sort by path. Go string comparison is bytewise over the UTF-8
+ // bytes, matching Node's Buffer.compare(Buffer.from(path, "utf8"), …).
+ sort.Slice(entries, func(i, j int) bool { return entries[i].path < entries[j].path })
+
+ var b strings.Builder
+ b.WriteByte('[')
+ for i, e := range entries {
+ if i > 0 {
+ b.WriteByte(',')
+ }
+ b.WriteString(`{"path":`)
+ b.WriteString(jsMarshalString(e.path))
+ b.WriteString(`,"mode":`)
+ b.WriteString(strconv.Itoa(e.mode))
+ b.WriteString(`,"sha256":`)
+ b.WriteString(jsMarshalString(e.sha))
+ b.WriteByte('}')
+ }
+ b.WriteByte(']')
+
+ sum := sha256.Sum256([]byte(b.String()))
+ return "sha256:" + hex.EncodeToString(sum[:])
+}
+
+// jsMarshalString serializes s to a JSON string literal byte-for-byte as
+// JavaScript's JSON.stringify would (ECMA-262 QuoteJSONString): escape " and \,
+// the short forms \b \t \n \f \r, other C0 controls as \u00xx (lowercase), and
+// emit everything else — including non-ASCII and U+2028/U+2029 — as raw UTF-8.
+func jsMarshalString(s string) string {
+ var b strings.Builder
+ b.WriteByte('"')
+ for _, r := range s {
+ switch r {
+ case '"':
+ b.WriteString(`\"`)
+ case '\\':
+ b.WriteString(`\\`)
+ case '\b':
+ b.WriteString(`\b`)
+ case '\f':
+ b.WriteString(`\f`)
+ case '\n':
+ b.WriteString(`\n`)
+ case '\r':
+ b.WriteString(`\r`)
+ case '\t':
+ b.WriteString(`\t`)
+ default:
+ if r < 0x20 {
+ fmt.Fprintf(&b, `\u%04x`, r)
+ } else {
+ b.WriteRune(r)
+ }
+ }
+ }
+ b.WriteByte('"')
+ return b.String()
+}
diff --git a/cmd/oc/internal/filesetdigest/filesetdigest_test.go b/cmd/oc/internal/filesetdigest/filesetdigest_test.go
new file mode 100644
index 00000000..9cd6e827
--- /dev/null
+++ b/cmd/oc/internal/filesetdigest/filesetdigest_test.go
@@ -0,0 +1,192 @@
+package filesetdigest
+
+import (
+ "bytes"
+ "compress/gzip"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// goldenFiles is the SHARED cross-repo golden vector (flue-slice.md contract 4).
+// The same fileset must produce goldenDigest in all three implementations:
+// this package, oc-runtimes/adapter-core, and sessions-api. The digest was
+// generated by the reference JS computeFilesetDigest.
+var goldenFiles = []File{
+ {Path: "artifact.json", Mode: 0o644, Content: []byte("{\"entry\":\"oc.js\",\"profile_version\":1}\n")},
+ {Path: "oc.js", Mode: 0o644, Content: []byte("export const x = 1;\n")},
+ {Path: "skills/triage/SKILL.md", Mode: 0o644, Content: []byte("---\nname: triage\n---\nhello\n")},
+ {Path: "bin/run.sh", Mode: 0o755, Content: []byte("#!/bin/sh\necho hi\n")},
+}
+
+const goldenDigest = "sha256:1fe94fec330dfaf6deef0774e2fd55cfc2f29ba8fb37f03db13e21cd49cfe5ba"
+
+func TestGoldenDigest(t *testing.T) {
+ if got := Digest(goldenFiles); got != goldenDigest {
+ t.Fatalf("digest mismatch\n got: %s\nwant: %s", got, goldenDigest)
+ }
+}
+
+func TestDigestIndependentOfInputOrder(t *testing.T) {
+ // Reversed input must yield the same digest (entries are bytewise-sorted).
+ rev := make([]File, len(goldenFiles))
+ for i, f := range goldenFiles {
+ rev[len(goldenFiles)-1-i] = f
+ }
+ if got := Digest(rev); got != goldenDigest {
+ t.Fatalf("digest is order-dependent: got %s want %s", got, goldenDigest)
+ }
+}
+
+// TestCanonicalTarGzRoundTrip reproduces the SERVER's verify path: unpack the
+// tar.gz with a minimal POSIX-ustar reader (a port of adapter-core parseTar) and
+// recompute the digest from the unpacked bytes. It must equal Digest(files) —
+// this is exactly the check the deploy-verify executor performs before pinning.
+func TestCanonicalTarGzRoundTrip(t *testing.T) {
+ tarGz, err := CanonicalTarGz(goldenFiles)
+ if err != nil {
+ t.Fatalf("CanonicalTarGz: %v", err)
+ }
+ unpacked, err := parseTarGz(tarGz)
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if len(unpacked) != len(goldenFiles) {
+ t.Fatalf("unpacked %d files, want %d", len(unpacked), len(goldenFiles))
+ }
+ if got := Digest(unpacked); got != goldenDigest {
+ t.Fatalf("round-trip digest mismatch: got %s want %s", got, goldenDigest)
+ }
+ byPath := map[string]File{}
+ for _, f := range unpacked {
+ byPath[f.Path] = f
+ }
+ for _, want := range goldenFiles {
+ got, ok := byPath[want.Path]
+ if !ok {
+ t.Fatalf("missing %q after round trip", want.Path)
+ }
+ if got.Mode != want.Mode {
+ t.Errorf("%q mode = %o, want %o", want.Path, got.Mode, want.Mode)
+ }
+ if !bytes.Equal(got.Content, want.Content) {
+ t.Errorf("%q content changed", want.Path)
+ }
+ }
+}
+
+func TestCanonicalTarGzDeterministic(t *testing.T) {
+ a, err := CanonicalTarGz(goldenFiles)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := CanonicalTarGz(goldenFiles)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(a, b) {
+ t.Fatal("CanonicalTarGz is not deterministic")
+ }
+}
+
+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)
+ }
+ }
+}
+
+// TestJSMarshalString locks the JS-faithful escaping (the reason we hand-roll
+// instead of using encoding/json). Expected values are JSON.stringify output.
+func TestJSMarshalString(t *testing.T) {
+ cases := []struct{ in, want string }{
+ {"abc", `"abc"`},
+ {`a"b\c`, `"a\"b\\c"`},
+ {"tab\tnl\n", `"tab\tnl\n"`},
+ {"\b\f\r", `"\b\f\r"`},
+ // / < > & and non-ASCII are emitted RAW (Go's default JSON would escape some).
+ {"a<b>&/z", `"a<b>&/z"`},
+ {"café/☃", `"café/☃"`},
+ }
+ for _, c := range cases {
+ if got := jsMarshalString(c.in); got != c.want {
+ t.Errorf("jsMarshalString(%q) = %s, want %s", c.in, got, c.want)
+ }
+ }
+ // C0 control chars without a short form -> lowercase \u00xx (matches JS
+ // JSON.stringify). Checked via the property to avoid hand-typing escapes.
+ for _, b := range []byte{0x00, 0x01, 0x1f} {
+ got := jsMarshalString(string(rune(b)))
+ want := "\"" + fmt.Sprintf("\\u%04x", b) + "\""
+ if got != want {
+ t.Errorf("jsMarshalString(%#x) = %s, want %s", b, got, want)
+ }
+ }
+}
+
+// ── minimal ustar reader for the round-trip test (mirror of adapter-core parseTar) ──
+
+func parseTarGz(tarGz []byte) ([]File, error) {
+ zr, err := gzip.NewReader(bytes.NewReader(tarGz))
+ if err != nil {
+ return nil, err
+ }
+ tar, err := io.ReadAll(zr)
+ if err != nil {
+ return nil, err
+ }
+ readStr := func(o, n int) string {
+ s := tar[o : o+n]
+ if i := bytes.IndexByte(s, 0); i >= 0 {
+ s = s[:i]
+ }
+ return string(s)
+ }
+ var out []File
+ off := 0
+ for off+512 <= len(tar) {
+ header := tar[off : off+512]
+ if isAllZero(header) {
+ break
+ }
+ name := readStr(off+0, 100)
+ prefix := readStr(off+345, 155)
+ path := name
+ if prefix != "" {
+ path = prefix + "/" + name
+ }
+ mode, _ := strconv.ParseInt(strings.TrimSpace(readStr(off+100, 8)), 8, 32)
+ size, _ := strconv.ParseInt(strings.TrimSpace(readStr(off+124, 12)), 8, 64)
+ typeflag := tar[off+156]
+ off += 512
+ if typeflag == '0' || typeflag == 0 {
+ content := make([]byte, size)
+ copy(content, tar[off:off+int(size)])
+ out = append(out, File{Path: path, Mode: int(mode) & 0o7777, Content: content})
+ }
+ off += int((size+511)/512) * 512
+ }
+ return out, nil
+}
+
+func isAllZero(b []byte) bool {
+ for _, x := range b {
+ if x != 0 {
+ return false
+ }
+ }
+ return true
+}
+
+func TestContentShaSanity(t *testing.T) {
+ sum := sha256.Sum256([]byte("hello"))
+ if hex.EncodeToString(sum[:]) != "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" {
+ t.Fatal("sha256 sanity failed")
+ }
+}
diff --git a/cmd/oc/internal/filesetdigest/tar.go b/cmd/oc/internal/filesetdigest/tar.go
new file mode 100644
index 00000000..0c45ce1a
--- /dev/null
+++ b/cmd/oc/internal/filesetdigest/tar.go
@@ -0,0 +1,117 @@
+package filesetdigest
+
+import (
+ "bytes"
+ "compress/gzip"
+ "fmt"
+ "sort"
+ "strconv"
+ "time"
+)
+
+// CanonicalTarGz builds the deterministic tar.gz transport container for a
+// fileset: entries bytewise-sorted by path, fixed mode/uid/gid/mtime, gzip
+// mtime zeroed. Mirrors buildCanonicalTarGz in
+// sessions-api/src/v3/core/skill-bundle-canonical.ts.
+//
+// The tar bytes are NOT the content address — the digest is over the fileset
+// (Digest), and the server re-derives it from the UNPACKED bytes with its own
+// minimal POSIX-ustar reader (adapter-core parseTar). This writer emits exactly
+// what that reader consumes: typeflag '0' regular files, ustar name/prefix split
+// for long paths, octal numeric fields. No PAX/GNU extensions (Go's archive/tar
+// would add extension records the minimal reader can't parse), which is why this
+// is hand-rolled.
+func CanonicalTarGz(files []File) ([]byte, error) {
+ sorted := append([]File(nil), files...)
+ sort.Slice(sorted, func(i, j int) bool { return sorted[i].Path < sorted[j].Path })
+
+ var tar bytes.Buffer
+ for _, f := range sorted {
+ hdr, err := tarHeader(f.Path, f.Mode, len(f.Content))
+ if err != nil {
+ return nil, err
+ }
+ tar.Write(hdr)
+ tar.Write(f.Content)
+ if pad := (512 - (len(f.Content) % 512)) % 512; pad > 0 {
+ tar.Write(make([]byte, pad))
+ }
+ }
+ tar.Write(make([]byte, 1024)) // two zero blocks = end of archive
+
+ var gz bytes.Buffer
+ zw, err := gzip.NewWriterLevel(&gz, gzip.BestCompression)
+ if err != nil {
+ return nil, err
+ }
+ zw.ModTime = time.Time{} // zero → gzip MTIME field written as 0 (determinism)
+ if _, err := zw.Write(tar.Bytes()); err != nil {
+ return nil, err
+ }
+ if err := zw.Close(); err != nil {
+ return nil, err
+ }
+ return gz.Bytes(), nil
+}
+
+// tarHeader builds a 512-byte POSIX ustar header for a regular file with
+// uid/gid/mtime = 0 (deterministic). Matches tarHeader in skill-bundle-canonical.ts.
+func tarHeader(path string, mode, size int) ([]byte, error) {
+ buf := make([]byte, 512)
+ pathBytes := []byte(path)
+ if len(pathBytes) <= 100 {
+ copy(buf[0:100], pathBytes)
+ } else {
+ // ustar name(100)/prefix(155) split: cut at a '/' in the last 100 bytes.
+ cut := -1
+ for i := len(pathBytes) - 100; i < len(pathBytes); i++ {
+ if pathBytes[i] == '/' {
+ cut = i
+ break
+ }
+ }
+ if cut < 0 || cut > 155 {
+ return nil, fmt.Errorf("path too long for tar: %q", path)
+ }
+ copy(buf[0:100], pathBytes[cut+1:]) // name
+ copy(buf[345:500], pathBytes[:cut]) // prefix
+ }
+ writeOctal(buf, 100, 8, mode&0o7777)
+ writeOctal(buf, 108, 8, 0) // uid
+ writeOctal(buf, 116, 8, 0) // gid
+ writeOctal(buf, 124, 12, size)
+ writeOctal(buf, 136, 12, 0) // mtime
+ for i := 148; i < 156; i++ {
+ buf[i] = ' ' // checksum field = spaces while summing
+ }
+ buf[156] = '0' // typeflag '0' (regular file)
+ copy(buf[257:263], "ustar\x00") // magic
+ copy(buf[263:265], "00") // version
+
+ sum := 0
+ for i := 0; i < 512; i++ {
+ sum += int(buf[i])
+ }
+ cs := padOctal(sum, 6)
+ copy(buf[148:154], cs) // 6 octal digits
+ buf[154] = 0
+ buf[155] = ' '
+ return buf, nil
+}
+
+// writeOctal writes value as octal into buf[off:off+length): (length-1)
+// zero-padded digits, then a NUL. Matches writeOctal in the TS canonicalizer.
+func writeOctal(buf []byte, off, length, value int) {
+ s := padOctal(value, length-1)
+ copy(buf[off:off+length-1], s)
+ buf[off+length-1] = 0
+}
+
+// padOctal renders value in octal, left-padded with '0' to at least width digits.
+func padOctal(value, width int) string {
+ s := strconv.FormatInt(int64(value), 8)
+ for len(s) < width {
+ s = "0" + s
+ }
+ return s
+}