Skip to content

An open-source, faster Devin alternative

TypeScript

Deploy-from-GitHub (v1.5): connect-repo UI + oc deploy (#466)

Igor Zalutskic2b6458a5f47
diff --git a/VERSION b/VERSION
index 8f0916f7..a918a2aa 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.5.0
+0.6.0
diff --git a/cmd/oc/internal/client/client.go b/cmd/oc/internal/client/client.go
index fca6dc54..cf24cee7 100644
--- a/cmd/oc/internal/client/client.go
+++ b/cmd/oc/internal/client/client.go
@@ -113,12 +113,23 @@ func (c *Client) do(req *http.Request) (*http.Response, error) {
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 string `json:"error"`
+ Error json.RawMessage `json:"error"`
}
msg := string(body)
- if json.Unmarshal(body, &errResp) == nil && errResp.Error != "" {
- msg = errResp.Error
+ 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}
}
diff --git a/cmd/oc/internal/commands/agent.go b/cmd/oc/internal/commands/agent.go
index b5acabc9..c32a110e 100644
--- a/cmd/oc/internal/commands/agent.go
+++ b/cmd/oc/internal/commands/agent.go
@@ -1,12 +1,15 @@
package commands
-// This file holds the parent `oc agent` cobra command, init() for flag +
-// subcommand registration, shared response types used across multiple agent
-// subcommands, and small formatting helpers. Each subcommand lives in its
-// own file: agent_create.go, agent_get.go, agent_list.go, agent_delete.go,
-// agent_connect.go, agent_packages.go, agent_events.go. Error rendering
-// helpers (LastError, ExitError, codeCatalog, RenderLastError,
-// renderAsyncFallback) live in agent_errors.go.
+// 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 prompt+model+skills behaviors deployed
+// as immutable revisions, a different model entirely.
+//
+// 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"
@@ -19,9 +22,115 @@ import (
"github.com/spf13/cobra"
)
-// stdinIsTTY reports whether stdin is attached to a terminal. Used to gate
-// interactive prompts: if stdin isn't a TTY we refuse to prompt, since the
-// caller is a script or agent that can't respond.
+// ── 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"`
+ 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 {
@@ -30,10 +139,8 @@ func stdinIsTTY() bool {
return (fi.Mode() & os.ModeCharDevice) != 0
}
-// confirmDestructive gates delete/disconnect/uninstall on explicit consent.
-// With --yes: proceed. Without --yes and a TTY: prompt. Without --yes and
-// no TTY: refuse — scripts and agents must pass --yes so accidental
-// invocation can't quietly destroy state.
+// 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
@@ -51,189 +158,20 @@ func confirmDestructive(cmd *cobra.Command, action string) error {
}
}
-// sessionsClient returns the sessions-api client from context, or errors if not configured.
-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
-}
-
-// ── Shared response types ──
-
-// agentResponse is the shape returned by sessions-api for both GET /v1/agents
-// (list rows) and GET /v1/agents/:id (detail). The list endpoint only
-// populates the top half; the detail endpoint additionally populates Status,
-// InstanceID, and LastError.
-type agentResponse struct {
- ID string `json:"id"`
- DisplayName string `json:"display_name"`
- Core *string `json:"core"`
- Model *string `json:"model,omitempty"`
- Channels interface{} `json:"channels"`
- Packages interface{} `json:"packages"`
- SecretStore *string `json:"secret_store"`
- Config interface{} `json:"config"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
-
- // Populated by GET /v1/agents/:id (enriched response); omitted by
- // POST /v1/agents and the list endpoint.
- Status *string `json:"status,omitempty"`
- InstanceID *string `json:"instance_id,omitempty"`
- InstanceStatus *string `json:"instance_status,omitempty"`
- CoreStatus map[string]interface{} `json:"core_status,omitempty"`
- ChannelStatus map[string]map[string]any `json:"channel_status,omitempty"`
- PackageStatus map[string]map[string]any `json:"package_status,omitempty"`
- CurrentOperation *AgentOperation `json:"current_operation,omitempty"`
- Conditions []AgentCondition `json:"conditions,omitempty"`
- LastError *LastError `json:"last_error,omitempty"`
-}
-
-type agentListResponse struct {
- Agents []agentResponse `json:"agents"`
-}
-
-type AgentOperation struct {
- ID string `json:"id"`
- AgentID string `json:"agent_id"`
- InstanceID *string `json:"instance_id,omitempty"`
- Kind string `json:"kind"`
- TargetType *string `json:"target_type,omitempty"`
- TargetKey *string `json:"target_key,omitempty"`
- Status string `json:"status"`
- Phase *string `json:"phase,omitempty"`
- Code *string `json:"code,omitempty"`
- Message *string `json:"message,omitempty"`
- CreatedBy *string `json:"created_by,omitempty"`
- StartedAt *string `json:"started_at,omitempty"`
- CompletedAt *string `json:"completed_at,omitempty"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
-}
-
-type AgentCondition struct {
- Type string `json:"type"`
- Subject string `json:"subject,omitempty"`
- Status string `json:"status"`
- Reason string `json:"reason"`
- Message string `json:"message,omitempty"`
-}
-
-type operationSubmissionResponse struct {
- AgentID string `json:"agent_id"`
- Status string `json:"status"`
- Channel string `json:"channel,omitempty"`
- Package string `json:"package,omitempty"`
- Operation *AgentOperation `json:"operation,omitempty"`
-}
-
// ── Parent command ──
var agentCmd = &cobra.Command{
Use: "agent",
- Short: "Manage agents",
- Long: "Create and manage managed agents on OpenComputer.\n\n" +
- "Exit codes:\n" +
- " 0 Success\n" +
- " 1 General error (unclassified failures, bad args/flags)\n" +
- " 3 Upstream 4xx (not found, unauthorized, org mismatch)\n" +
- " 4 Conflict (already exists, invalid state)\n" +
- " 5 Transient error (timeout, retry-safe)\n\n" +
- "Classes 3-5 are emitted by create/install/get when the failure\n" +
- "carries a known code. Other commands exit 0 on success, 1 on\n" +
- "failure. Agent callers can branch on the class to decide retry\n" +
- "vs surface-to-user vs give-up.",
-}
-
-// ── Formatting helpers ──
-
-func formatList(v interface{}) string {
- if v == nil {
- return "-"
- }
- switch items := v.(type) {
- case []interface{}:
- if len(items) == 0 {
- return "-"
- }
- strs := make([]string, len(items))
- for i, item := range items {
- strs[i] = fmt.Sprintf("%v", item)
- }
- return strings.Join(strs, ", ")
- case []string:
- if len(items) == 0 {
- return "-"
- }
- return strings.Join(items, ", ")
- default:
- return fmt.Sprintf("%v", v)
- }
-}
-
-func listEntries(v interface{}) []string {
- switch items := v.(type) {
- case []interface{}:
- out := make([]string, 0, len(items))
- for _, item := range items {
- out = append(out, fmt.Sprintf("%v", item))
- }
- return out
- case []string:
- return append([]string(nil), items...)
- default:
- return nil
- }
-}
-
-func listIsEmpty(v interface{}) bool {
- return len(listEntries(v)) == 0
+ Short: "Create, deploy, and manage agents",
+ Long: "Manage Durable Agent Sessions agents on OpenComputer.\n\n" +
+ "An agent is a prompt + model + skills behavior. Deploying it produces an\n" +
+ "immutable, 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 formatAge(isoTime string) string {
- t, err := time.Parse(time.RFC3339Nano, isoTime)
- if err != nil {
- return isoTime
- }
- return time.Since(t).Truncate(time.Second).String()
-}
-
-// ── Registration ──
-
func init() {
- // Per-subcommand flags
- agentCreateCmd.Flags().String("core", "", "Managed core (required, e.g. hermes|openclaw)")
- _ = agentCreateCmd.MarkFlagRequired("core")
- agentCreateCmd.Flags().StringSlice("secret", nil, "Secrets (KEY=VALUE)")
- agentCreateCmd.Flags().Bool("no-wait", false, "Don't wait for instance provisioning; exit after agent record is created")
-
- agentConnectCmd.Flags().String("bot-token", "", "Telegram bot token (required for channel=telegram when stdin is not a TTY)")
- agentConnectCmd.Flags().Bool("no-wait", false, "Don't wait for channel orchestration to finish")
-
- agentInstallCmd.Flags().Bool("no-wait", false, "Don't wait for install orchestration to finish")
-
- // Destructive ops — require explicit --yes in non-TTY callers.
- agentDeleteCmd.Flags().Bool("yes", false, "Skip confirmation (required for non-interactive callers)")
- agentDisconnectCmd.Flags().Bool("yes", false, "Skip confirmation (required for non-interactive callers)")
- agentUninstallCmd.Flags().Bool("yes", false, "Skip confirmation (required for non-interactive callers)")
-
- agentEventsCmd.Flags().Int("limit", 0, "Max events to return (1-200, default 50)")
- agentEventsCmd.Flags().String("before", "", "Return events before this ISO timestamp (for pagination)")
-
- // Subcommand registration — each is defined in its own file in this package.
- agentCmd.AddCommand(agentCreateCmd)
- agentCmd.AddCommand(agentListCmd)
- agentCmd.AddCommand(agentGetCmd)
- agentCmd.AddCommand(agentDeleteCmd)
- agentCmd.AddCommand(agentConnectCmd)
- agentCmd.AddCommand(agentDisconnectCmd)
- agentCmd.AddCommand(agentChannelsCmd)
- agentCmd.AddCommand(agentInstallCmd)
- agentCmd.AddCommand(agentUninstallCmd)
- agentCmd.AddCommand(agentPackagesCmd)
- agentCmd.AddCommand(agentEventsCmd)
- agentCmd.AddCommand(agentSendCmd)
- agentCmd.AddCommand(agentChatCmd)
+ registerAgentCrud()
+ registerAgentDeploy()
+ rootCmd.AddCommand(sessionCmd)
}
diff --git a/cmd/oc/internal/commands/agent_chat.go b/cmd/oc/internal/commands/agent_chat.go
deleted file mode 100644
index e0f834fa..00000000
--- a/cmd/oc/internal/commands/agent_chat.go
+++ /dev/null
@@ -1,237 +0,0 @@
-package commands
-
-// `oc agent send` (one-shot) and `oc agent chat` (interactive REPL).
-//
-// Both stream the SSE response from sessions-api's instance-message endpoint
-// (POST /v1/agents/:id/instances/:instId/messages) chunk-by-chunk. The
-// endpoint emits OpenAI-style frames: data: {"type":"text","content":"..."}
-// per chunk, and data: {"type":"done"} on the last frame.
-//
-// `chat` keeps the full message history in memory and resends it every turn
-// — OpenClaw's chat-completions is stateless, so context only persists if
-// the client supplies it.
-
-import (
- "bufio"
- "context"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "os"
- "strings"
-
- "github.com/spf13/cobra"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
-)
-
-type chatTurn struct {
- Role string `json:"role"`
- Content string `json:"content"`
-}
-
-// resolveAgentInstance fetches the agent and returns its current instance
-// ID. Returns a friendly error when the agent has no running instance.
-func resolveAgentInstance(ctx context.Context, sc *client.Client, agentID string) (string, error) {
- var agent agentResponse
- if err := sc.Get(ctx, "/v1/agents/"+agentID, &agent); err != nil {
- return "", err
- }
- if agent.InstanceID == nil || *agent.InstanceID == "" {
- return "", fmt.Errorf("agent %s has no running instance yet (status=%s) — wait for it to come up and retry",
- agentID, derefOrDash(agent.Status))
- }
- return *agent.InstanceID, nil
-}
-
-func derefOrDash(s *string) string {
- if s == nil {
- return "-"
- }
- return *s
-}
-
-// streamChatTurn posts to /messages and prints text chunks as they arrive.
-// Returns the assembled assistant text so callers can append it to a
-// running history (used by `oc agent chat`).
-func streamChatTurn(
- ctx context.Context,
- sc *client.Client,
- agentID, instanceID string,
- history []chatTurn,
- w io.Writer,
-) (string, error) {
- body := map[string]interface{}{
- "messages": history,
- }
- resp, err := sc.PostStream(ctx, "/v1/agents/"+agentID+"/instances/"+instanceID+"/messages", body)
- if err != nil {
- return "", err
- }
- defer resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- buf, _ := io.ReadAll(resp.Body)
- return "", fmt.Errorf("chat failed (HTTP %d): %s", resp.StatusCode, strings.TrimSpace(string(buf)))
- }
-
- var assembled strings.Builder
- reader := bufio.NewReader(resp.Body)
- for {
- line, err := reader.ReadString('\n')
- if line != "" {
- line = strings.TrimRight(line, "\r\n")
- if !strings.HasPrefix(line, "data:") {
- if err == io.EOF {
- break
- }
- continue
- }
- payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
- if payload == "" || payload == "[DONE]" {
- if err == io.EOF {
- break
- }
- continue
- }
- var ev struct {
- Type string `json:"type"`
- Content string `json:"content"`
- Message string `json:"message"`
- Code string `json:"code"`
- }
- if jerr := json.Unmarshal([]byte(payload), &ev); jerr != nil {
- if err == io.EOF {
- break
- }
- continue
- }
- switch ev.Type {
- case "text":
- if ev.Content != "" {
- assembled.WriteString(ev.Content)
- _, _ = io.WriteString(w, ev.Content)
- }
- case "error":
- return assembled.String(), fmt.Errorf("agent error: %s (%s)", ev.Message, ev.Code)
- case "done":
- return assembled.String(), nil
- }
- }
- if err != nil {
- if err == io.EOF {
- break
- }
- return assembled.String(), err
- }
- }
- return assembled.String(), nil
-}
-
-var agentSendCmd = &cobra.Command{
- Use: "send <agent-id> <message>",
- Short: "Send one message to an agent and stream the reply",
- Long: "Send a single message to an agent and stream the reply to stdout.\n" +
- "Convenient for smoke-testing core/gateway changes from a shell:\n\n" +
- " oc agent send my-bot 'hello'\n" +
- " echo 'translate this to french: hello' | oc agent send my-bot",
- Args: cobra.RangeArgs(1, 2),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID := args[0]
-
- var message string
- if len(args) >= 2 {
- message = args[1]
- } else if !stdinIsTTY() {
- buf, rerr := io.ReadAll(os.Stdin)
- if rerr != nil {
- return rerr
- }
- message = strings.TrimRight(string(buf), "\n")
- }
- if strings.TrimSpace(message) == "" {
- return fmt.Errorf("message is required (positional arg or piped stdin)")
- }
-
- instanceID, err := resolveAgentInstance(cmd.Context(), sc, agentID)
- if err != nil {
- return err
- }
-
- history := []chatTurn{{Role: "user", Content: message}}
- _, err = streamChatTurn(cmd.Context(), sc, agentID, instanceID, history, os.Stdout)
- // Trailing newline so shell prompts return cleanly.
- fmt.Println()
- return err
- },
-}
-
-var agentChatCmd = &cobra.Command{
- Use: "chat <agent-id>",
- Short: "Open an interactive chat with an agent",
- Long: "Open an interactive REPL chat with an agent. Each turn streams\n" +
- "the assistant reply live. Type ':exit' or send EOF (Ctrl-D) to quit.\n" +
- "History is kept client-side and resent every turn (OpenClaw's chat-\n" +
- "completions is stateless).",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
- agentID := args[0]
-
- instanceID, err := resolveAgentInstance(cmd.Context(), sc, agentID)
- if err != nil {
- return err
- }
-
- fmt.Fprintf(os.Stderr, "Chat with %s — type ':exit' or Ctrl-D to quit.\n\n", agentID)
-
- history := []chatTurn{}
- reader := bufio.NewReader(os.Stdin)
- for {
- fmt.Fprint(os.Stderr, "you> ")
- line, rerr := reader.ReadString('\n')
- if rerr == io.EOF {
- if strings.TrimSpace(line) == "" {
- fmt.Fprintln(os.Stderr)
- return nil
- }
- } else if rerr != nil {
- return rerr
- }
- msg := strings.TrimRight(line, "\r\n")
- if strings.TrimSpace(msg) == "" {
- if rerr == io.EOF {
- return nil
- }
- continue
- }
- if msg == ":exit" || msg == ":quit" {
- return nil
- }
-
- history = append(history, chatTurn{Role: "user", Content: msg})
- fmt.Fprint(os.Stderr, "bot> ")
- reply, serr := streamChatTurn(cmd.Context(), sc, agentID, instanceID, history, os.Stdout)
- fmt.Println()
- if serr != nil {
- // Drop the unanswered user turn so the next try doesn't
- // re-send the failed pair as context.
- history = history[:len(history)-1]
- fmt.Fprintf(os.Stderr, " error: %v\n", serr)
- continue
- }
- history = append(history, chatTurn{Role: "assistant", Content: reply})
-
- if rerr == io.EOF {
- return nil
- }
- }
- },
-}
diff --git a/cmd/oc/internal/commands/agent_connect.go b/cmd/oc/internal/commands/agent_connect.go
deleted file mode 100644
index a05c45e1..00000000
--- a/cmd/oc/internal/commands/agent_connect.go
+++ /dev/null
@@ -1,206 +0,0 @@
-package commands
-
-// Channel lifecycle: connect, disconnect, list.
-
-import (
- "bufio"
- "fmt"
- "net/url"
- "os"
- "strings"
-
- "github.com/spf13/cobra"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/opensandbox/opensandbox/cmd/oc/internal/config"
-)
-
-// dashboardAgentURL builds the dashboard URL for an agent, used in the
-// CLI's paywall-redirect message. APIURL doubles as the dashboard origin
-// (the OC server serves /api/dashboard/* and the SPA from the same host).
-func dashboardAgentURL(cmd *cobra.Command, agentID string) string {
- cfg := config.Load(cmd)
- base := strings.TrimRight(cfg.APIURL, "/")
- if base == "" {
- base = config.DefaultAPIURL
- }
- return base + "/agents/" + url.PathEscape(agentID)
-}
-
-var agentConnectCmd = &cobra.Command{
- Use: "connect <id> <channel>",
- Short: "Connect a channel to an agent",
- Long: "Connect a messaging channel to a managed agent.\n\n" +
- "Supported channels:\n" +
- " telegram requires --bot-token (or interactive prompt if TTY)",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
-
- agentID := args[0]
- channel := args[1]
- noWait, _ := cmd.Flags().GetBool("no-wait")
-
- body := map[string]interface{}{}
-
- if channel == "telegram" {
- // Pre-flight entitlement check — bail with a clean upgrade
- // message before asking for a bot token if the agent isn't
- // subscribed. The actual connect endpoint also gates, but
- // hitting that path first means the user has to paste a token
- // just to see the paywall, which is jarring.
- var ent struct {
- Entitled bool `json:"entitled"`
- Reason string `json:"reason"`
- PriceMonthlyCents int64 `json:"price_monthly_cents"`
- }
- err := sc.Get(cmd.Context(), "/v1/agents/"+agentID+"/channels/"+channel+"/entitlement", &ent)
- if err != nil {
- if apiErr, ok := err.(*client.APIError); ok && apiErr.StatusCode == 402 {
- upgradeURL := dashboardAgentURL(cmd, agentID)
- price := "$20/mo"
- if ent.PriceMonthlyCents > 0 {
- price = fmt.Sprintf("$%.2f/mo", float64(ent.PriceMonthlyCents)/100)
- }
- fmt.Fprintf(os.Stderr,
- "\nThis agent isn't subscribed to %s yet (%s per agent).\n"+
- "Subscribe in the dashboard, then re-run this command:\n\n"+
- " %s\n\n",
- channel, price, upgradeURL,
- )
- return fmt.Errorf("subscription required for %s on %s", channel, agentID)
- }
- // Soft-fail on other lookup errors — fall through to the
- // real connect, which will surface a more specific error.
- }
-
- token, _ := cmd.Flags().GetString("bot-token")
- if token == "" {
- if !stdinIsTTY() {
- return fmt.Errorf("--bot-token is required when stdin is not a terminal")
- }
- fmt.Println("To connect Telegram:")
- fmt.Println(" 1. Open Telegram and message @BotFather")
- fmt.Println(" 2. Send /newbot, choose a name and username")
- fmt.Println(" 3. Copy the bot token")
- fmt.Println()
- fmt.Print("Paste bot token: ")
-
- reader := bufio.NewReader(os.Stdin)
- line, err := reader.ReadString('\n')
- if err != nil && line == "" {
- return fmt.Errorf("reading bot token: %w", err)
- }
- token = strings.TrimSpace(line)
- }
- if token == "" {
- return fmt.Errorf("bot token is required")
- }
- body["bot_token"] = token
- }
-
- if !jsonOutput {
- fmt.Fprintf(os.Stderr, "Connecting %s to %s\n", channel, agentID)
- }
-
- var result operationSubmissionResponse
- if err := sc.Post(cmd.Context(), "/v1/agents/"+agentID+"/channels/"+channel, body, &result); err != nil {
- // HTTP 402 → paywalled feature. The dashboard owns
- // subscription flow (Stripe Checkout needs a browser);
- // surface a clean message and the upgrade URL instead of
- // a raw API error.
- if apiErr, ok := err.(*client.APIError); ok && apiErr.StatusCode == 402 {
- upgradeURL := dashboardAgentURL(cmd, agentID)
- fmt.Fprintf(os.Stderr,
- "\nThis agent is not subscribed to %s ($20/mo per agent).\n"+
- "Subscribe in the dashboard, then re-run this command:\n"+
- " %s\n\n",
- channel, upgradeURL,
- )
- return fmt.Errorf("subscription required for %s on %s", channel, agentID)
- }
- return err
- }
-
- if noWait || result.Operation == nil {
- note := ""
- if result.Operation != nil {
- note = "Operation: " + result.Operation.ID
- }
- renderAsyncFallback(os.Stdout, jsonOutput, agentID, channel+" connect", note)
- return nil
- }
-
- agent, err := waitForOperation(cmd, sc, agentID, result.Operation, channel+" connect")
- if err != nil {
- return err
- }
- if agent == nil {
- return nil
- }
-
- if jsonOutput {
- printer.Print(agent, func() {})
- return nil
- }
-
- fmt.Printf("%s connected to %s.\n", channel, agentID)
- if channel == "telegram" {
- fmt.Println("Message your bot on Telegram to start chatting.")
- }
- return nil
- },
-}
-
-var agentDisconnectCmd = &cobra.Command{
- Use: "disconnect <id> <channel>",
- Short: "Disconnect a channel from an agent",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
-
- if err := confirmDestructive(cmd, fmt.Sprintf("Disconnect %s from %s", args[1], args[0])); err != nil {
- return err
- }
-
- if err := sc.Delete(cmd.Context(), "/v1/agents/"+args[0]+"/channels/"+args[1]); err != nil {
- return err
- }
-
- fmt.Printf("Channel %s disconnected from %s.\n", args[1], args[0])
- return nil
- },
-}
-
-var agentChannelsCmd = &cobra.Command{
- Use: "channels <id>",
- Short: "List channels connected to an agent",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
-
- var resp map[string]interface{}
- if err := sc.Get(cmd.Context(), "/v1/agents/"+args[0]+"/channels", &resp); err != nil {
- return err
- }
-
- printer.Print(resp, func() {
- channels := formatList(resp["channels"])
- if channels == "-" {
- fmt.Println("No channels connected.")
- } else {
- fmt.Printf("Channels: %s\n", channels)
- }
- })
- return nil
- },
-}
diff --git a/cmd/oc/internal/commands/agent_create.go b/cmd/oc/internal/commands/agent_create.go
deleted file mode 100644
index 84522489..00000000
--- a/cmd/oc/internal/commands/agent_create.go
+++ /dev/null
@@ -1,115 +0,0 @@
-package commands
-
-import (
- "fmt"
- "github.com/spf13/cobra"
- "os"
- "strings"
-)
-
-var agentCreateCmd = &cobra.Command{
- Use: "create <id>",
- Short: "Create a new managed agent",
- Long: "Create a new managed agent. A core (e.g. --core hermes) is required:\n" +
- "without one, the agent has no runtime and cannot connect channels\n" +
- "or install packages.",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
-
- id := args[0]
- core, _ := cmd.Flags().GetString("core")
- secretSlice, _ := cmd.Flags().GetStringSlice("secret")
- noWait, _ := cmd.Flags().GetBool("no-wait")
-
- body := map[string]interface{}{
- "id": id,
- "core": core,
- }
-
- // Parse --secret KEY=VAL flags into secrets map
- if len(secretSlice) > 0 {
- secrets := make(map[string]string)
- for _, s := range secretSlice {
- parts := strings.SplitN(s, "=", 2)
- if len(parts) == 2 {
- secrets[parts[0]] = parts[1]
- }
- }
- body["secrets"] = secrets
- }
-
- var agent agentResponse
- if err := sc.Post(cmd.Context(), "/v1/agents", body, &agent); err != nil {
- return err
- }
-
- // Text-mode preamble (suppressed in --json mode — scripts only want
- // the final JSON object).
- if !jsonOutput {
- fmt.Fprintf(os.Stderr, "Creating agent %s", agent.ID)
- if agent.Core != nil {
- fmt.Fprintf(os.Stderr, " (core: %s)", *agent.Core)
- }
- fmt.Fprintln(os.Stderr)
- fmt.Fprintln(os.Stderr, " ✓ Agent record created")
- }
-
- // --no-wait short-circuits into Mode 3 (async fallback). Scripts
- // that don't want to block use this path.
- if noWait {
- note := ""
- if agent.CurrentOperation != nil {
- note = "Operation: " + agent.CurrentOperation.ID
- }
- renderAsyncFallback(os.Stdout, jsonOutput, id, "Instance provisioning", note)
- return nil
- }
-
- if agent.CurrentOperation == nil {
- printer.Print(agent, func() {})
- return nil
- }
-
- finalAgent, err := waitForOperation(cmd, sc, id, agent.CurrentOperation, "Instance creation")
- if err != nil {
- return err
- }
- if finalAgent == nil {
- return nil
- }
-
- printer.Print(finalAgent, func() {
- fmt.Fprintln(os.Stdout, "Agent ready.")
- renderCreateNextSteps(finalAgent)
- })
- return nil
- },
-}
-
-func renderCreateNextSteps(agent *agentResponse) {
- noChannels := listIsEmpty(agent.Channels)
- noPackages := listIsEmpty(agent.Packages)
- if !noChannels && !noPackages {
- return
- }
-
- fmt.Fprintln(os.Stdout)
- if noChannels {
- fmt.Fprintln(os.Stdout, "No channels connected yet.")
- }
- if noPackages {
- fmt.Fprintln(os.Stdout, "No packages installed yet.")
- }
-
- fmt.Fprintln(os.Stdout, "Next:")
- if noChannels {
- fmt.Fprintf(os.Stdout, " oc agent connect %s telegram\n", agent.ID)
- }
- if noPackages {
- fmt.Fprintf(os.Stdout, " oc agent install %s gbrain\n", agent.ID)
- }
-}
diff --git a/cmd/oc/internal/commands/agent_crud.go b/cmd/oc/internal/commands/agent_crud.go
new file mode 100644
index 00000000..27f1d0c1
--- /dev/null
+++ b/cmd/oc/internal/commands/agent_crud.go
@@ -0,0 +1,125 @@
+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-4-6\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")
+ if prompt == "" {
+ 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}
+ 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)")
+ agentCreateCmd.Flags().String("model", "", "Model, e.g. anthropic/claude-sonnet-4-6 (required)")
+ agentCreateCmd.Flags().String("runtime", "claude", "Runtime family (claude|codex)")
+ 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_delete.go b/cmd/oc/internal/commands/agent_delete.go
deleted file mode 100644
index b8af0f58..00000000
--- a/cmd/oc/internal/commands/agent_delete.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package commands
-
-import (
- "fmt"
-
- "github.com/spf13/cobra"
-)
-
-var agentDeleteCmd = &cobra.Command{
- Use: "delete <id>",
- Short: "Delete an agent",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
-
- if err := confirmDestructive(cmd, fmt.Sprintf("Delete agent %s", args[0])); err != nil {
- return err
- }
-
- if err := sc.Delete(cmd.Context(), "/v1/agents/"+args[0]); err != nil {
- return err
- }
-
- fmt.Printf("Agent %s deleted.\n", args[0])
- return nil
- },
-}
diff --git a/cmd/oc/internal/commands/agent_deploy.go b/cmd/oc/internal/commands/agent_deploy.go
new file mode 100644
index 00000000..63afd69a
--- /dev/null
+++ b/cmd/oc/internal/commands/agent_deploy.go
@@ -0,0 +1,604 @@
+package commands
+
+import (
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/BurntSushi/toml"
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/spf13/cobra"
+)
+
+// ── agent.toml manifest + deploy bundle ──
+
+type manifest struct {
+ Name string `toml:"name"`
+ Model string `toml:"model"`
+ 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"`
+}
+
+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
+}
+
+// ── 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 && stdinIsTTY() && !jsonOutput {
+ fmt.Fprintf(os.Stderr, " … %s\n", 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)
+ }
+}
+
+// ── deploy ──
+
+var agentDeployCmd = &cobra.Command{
+ Use: "deploy [dir]",
+ Short: "Deploy an agent from a directory (agent.toml + prompt.md + skills/)",
+ 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`")
+ }
+ 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 {
+ var a Agent
+ _ = 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() {
+ fmt.Printf("Deployed %s — revision %d (active)\n", a.Name, n)
+ })
+ 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
+ }
+ 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}
+ }
+ printer.Print(d, func() {
+ if d.State == "ready" {
+ n := revisionNumber(cmd, sc, id, d.RevisionID)
+ status := "staged"
+ if d.Active {
+ status = "active"
+ }
+ fmt.Printf("Deployed revision %d — %s\n", n, 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 {
+ return a.ID, false, nil
+ }
+ }
+ body := map[string]interface{}{"name": name, "prompt": prompt, "model": model, "runtime": runtime}
+ 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() {
+ 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")
+
+ 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_errors.go b/cmd/oc/internal/commands/agent_errors.go
deleted file mode 100644
index 97c268f5..00000000
--- a/cmd/oc/internal/commands/agent_errors.go
+++ /dev/null
@@ -1,197 +0,0 @@
-package commands
-
-// Error-rendering helpers for agent commands: LastError / ExitError types,
-// the code→class catalog (mirrored from sessions-api/src/lib/error-codes.ts),
-// and the two renderers used by `agent get`, `agent create`, and
-// `agent install` (RenderLastError + renderAsyncFallback).
-//
-// Scope: agent commands only. If another command family ever needs to render
-// classified errors, lift this into a shared package.
-
-import (
- "encoding/json"
- "fmt"
- "io"
- "strings"
- "time"
-)
-
-// LastError mirrors the JSON shape returned by sessions-api under
-// GET /v1/agents/:id when the backing instance is in an error state.
-// See ws-gstack/work/agent-error-visibility.md
-type LastError struct {
- Phase string `json:"phase"`
- Message string `json:"message"`
- Code string `json:"code"`
- UpstreamStatus int `json:"upstream_status,omitempty"`
- At string `json:"at"`
-}
-
-// errorClass determines the CLI exit code. Mirrors the `class` field of
-// sessions-api's error-codes catalog. Kept as a static mirror rather than
-// fetched from the API: the classification is UX policy, not data.
-type errorClass int
-
-const (
- classGeneral errorClass = 1
- classUpstream4xx errorClass = 3
- classConflict errorClass = 4
- classTransient errorClass = 5
-)
-
-// codeCatalog maps error codes to a class + suggestion + optional docs URL.
-// Keep in sync with sessions-api/src/lib/error-codes.ts. The CLI ships its
-// own mirror so offline suggestions render even if the API doesn't return
-// them in the response (current API returns only code; suggestion/class
-// are client-side concerns).
-var codeCatalog = map[string]struct {
- class errorClass
- suggestion string
- docs string
-}{
- "checkpoint_org_mismatch": {
- class: classUpstream4xx,
- suggestion: "Your OC API key's org doesn't own this core's checkpoint.\n" +
- "Contact an admin to share it, or use an API key from the owning org.",
- docs: "https://docs.opencomputer.dev/errors/checkpoint-org",
- },
- "checkpoint_not_found": {
- class: classUpstream4xx,
- suggestion: "The checkpoint configured for this core no longer exists on OC.\n" +
- "It may have been deleted or replaced. Contact the operator to\n" +
- "rebuild the checkpoint and update the sessions-api config.",
- },
- "telegram_unauthorized": {
- class: classUpstream4xx,
- suggestion: "Telegram rejected the bot token. Verify the token at https://t.me/BotFather.",
- },
- "webhook_register_failed": {
- class: classGeneral,
- suggestion: "Telegram webhook registration failed.\n" +
- "Verify the bot token and retry. If it persists, inspect agent events\n" +
- "for the upstream Telegram response.",
- },
- "secret_store_failed": {
- class: classGeneral,
- suggestion: "The platform could not write channel or package secrets to OC.\n" +
- "Retry once. If it persists, inspect OC secret-store health and permissions.",
- },
- "core_not_ready": {
- class: classTransient,
- suggestion: "The managed core did not become healthy in time.\n" +
- "Retry once the agent is healthy, or inspect `oc agent get <id>` for readiness details.",
- },
- "channel_not_ready": {
- class: classTransient,
- suggestion: "The channel listener did not become ready in time.\n" +
- "Retry once the agent is healthy, or inspect `oc agent get <id>` for channel readiness.",
- },
- "package_verify_failed": {
- class: classGeneral,
- suggestion: "The package did not pass its verification step.\n" +
- "Inspect the package phase in agent events and retry after fixing the underlying issue.",
- },
- "sandbox_provision_timeout": {
- class: classTransient,
- suggestion: "Sandbox provisioning timed out. The OC worker may be unhealthy.\n" +
- "Try `oc agent delete <id>` then recreate — you may land on a different worker.",
- },
- "git_clone_failed": {
- class: classTransient,
- suggestion: "Package clone failed. The sandbox worker may have no outbound internet.\n" +
- "Delete and recreate the agent; you may land on a working worker.",
- },
-}
-
-// ExitError signals the desired process exit code. main.go inspects this
-// to choose between 1 (general), 3 (upstream 4xx), 4 (conflict),
-// 5 (transient). The error message is expected to already be rendered
-// when ExitError is returned — main will not re-print it.
-type ExitError struct{ Code int }
-
-func (e *ExitError) Error() string { return "" }
-
-// ExitCodeFor classifies a LastError into an exit code. Falls back to
-// classGeneral (1) for unknown codes.
-func ExitCodeFor(le *LastError) int {
- if le == nil {
- return 0
- }
- if entry, ok := codeCatalog[le.Code]; ok {
- return int(entry.class)
- }
- return int(classGeneral)
-}
-
-// RenderLastError writes the standard multi-line error block to w.
-// Used by both `agent get` (status block) and the poll loop in
-// create/install (failure case). One shared renderer keeps the CLI's
-// error voice consistent wherever errors appear.
-func RenderLastError(w io.Writer, le *LastError) {
- if le == nil {
- return
- }
-
- title := "Last error"
- if t, err := time.Parse(time.RFC3339Nano, le.At); err == nil {
- title = fmt.Sprintf("Last error (%s ago)", time.Since(t).Truncate(time.Second))
- }
-
- fmt.Fprintf(w, "%s:\n", title)
- fmt.Fprintf(w, " Phase: %s\n", le.Phase)
-
- // Upstream response bodies frequently carry trailing whitespace / newlines
- // that survive the round-trip. Normalize before appending the upstream
- // status so the block renders on one clean line.
- reason := strings.TrimSpace(le.Message)
- if le.UpstreamStatus != 0 {
- reason = fmt.Sprintf("%s (%d from upstream)", reason, le.UpstreamStatus)
- }
- fmt.Fprintf(w, " Reason: %s\n", reason)
-
- if entry, ok := codeCatalog[le.Code]; ok {
- fmt.Fprintln(w)
- for _, line := range strings.Split(entry.suggestion, "\n") {
- fmt.Fprintf(w, " %s\n", line)
- }
- if entry.docs != "" {
- fmt.Fprintf(w, " See: %s\n", entry.docs)
- }
- }
-}
-
-// asyncFallback is the JSON shape emitted for Mode 3 outcomes (--no-wait,
-// poll timeout, poll network error). Scripts branch on the `async` boolean
-// to decide whether to poll.
-type asyncFallback struct {
- ID string `json:"id"`
- Status string `json:"status"`
- Async bool `json:"async"`
- CheckWith string `json:"check_with"`
- Note string `json:"note,omitempty"`
-}
-
-// renderAsyncFallback prints the "work is continuing in background" message
-// (Mode 3). Shared across --no-wait, poll timeout, and poll error so the
-// user sees the same next step regardless of trigger.
-func renderAsyncFallback(stdoutW io.Writer, jsonOut bool, id, op, note string) {
- if jsonOut {
- enc := json.NewEncoder(stdoutW)
- enc.SetIndent("", " ")
- _ = enc.Encode(asyncFallback{
- ID: id,
- Status: "starting",
- Async: true,
- CheckWith: "oc agent get " + id,
- Note: note,
- })
- return
- }
-
- fmt.Fprintf(stdoutW, " ⋯ %s in background.\n", op)
- if note != "" {
- fmt.Fprintf(stdoutW, " %s\n", note)
- }
- fmt.Fprintln(stdoutW)
- fmt.Fprintf(stdoutW, "To check status: oc agent get %s\n", id)
-}
diff --git a/cmd/oc/internal/commands/agent_events.go b/cmd/oc/internal/commands/agent_events.go
deleted file mode 100644
index 4f2abbf8..00000000
--- a/cmd/oc/internal/commands/agent_events.go
+++ /dev/null
@@ -1,91 +0,0 @@
-package commands
-
-// `oc agent events <id>` — time-ordered event history for an agent.
-// Primarily surfaces error events today; as Design 003 adds recovered /
-// health_check_failed events, they flow through the same table and command.
-
-import (
- "fmt"
- "strings"
-
- "github.com/spf13/cobra"
-)
-
-var agentEventsCmd = &cobra.Command{
- Use: "events <id>",
- Short: "Show an agent's event history (errors, recoveries, etc.)",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
-
- limit, _ := cmd.Flags().GetInt("limit")
- before, _ := cmd.Flags().GetString("before")
-
- path := "/v1/agents/" + args[0] + "/events"
- q := []string{}
- if limit > 0 {
- q = append(q, fmt.Sprintf("limit=%d", limit))
- }
- if before != "" {
- q = append(q, "before="+before)
- }
- if len(q) > 0 {
- path += "?" + strings.Join(q, "&")
- }
-
- var resp agentEventsResponse
- if err := sc.Get(cmd.Context(), path, &resp); err != nil {
- return err
- }
-
- printer.Print(resp, func() {
- if len(resp.Events) == 0 {
- fmt.Println("No events.")
- return
- }
- headers := []string{"TIMESTAMP", "TYPE", "PHASE", "MESSAGE"}
- var rows [][]string
- for _, e := range resp.Events {
- rows = append(rows, []string{e.At, e.Type, valueOr(e.Phase, "-"), truncate(valueOr(e.Message, ""), 80)})
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
-
-type agentEventRow struct {
- ID int `json:"id"`
- InstanceID string `json:"instance_id"`
- Type string `json:"type"`
- Phase string `json:"phase"`
- Message string `json:"message"`
- Code string `json:"code"`
- UpstreamStatus int `json:"upstream_status"`
- At string `json:"at"`
-}
-
-type agentEventsResponse struct {
- Events []agentEventRow `json:"events"`
- NextBefore *string `json:"next_before"`
-}
-
-func valueOr(s, fallback string) string {
- if s == "" {
- return fallback
- }
- return s
-}
-
-func truncate(s string, n int) string {
- if len(s) <= n {
- return s
- }
- if n < 1 {
- return ""
- }
- return s[:n-1] + "…"
-}
diff --git a/cmd/oc/internal/commands/agent_get.go b/cmd/oc/internal/commands/agent_get.go
deleted file mode 100644
index a983fc2c..00000000
--- a/cmd/oc/internal/commands/agent_get.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package commands
-
-import (
- "fmt"
- "os"
- "strings"
-
- "github.com/spf13/cobra"
-)
-
-var agentGetCmd = &cobra.Command{
- Use: "get <id>",
- Short: "Get agent details",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
-
- var agent agentResponse
- if err := sc.Get(cmd.Context(), "/v1/agents/"+args[0], &agent); err != nil {
- return err
- }
-
- // /v1/agents/:id returns status + last_error inline so we no longer
- // need a second call to /instances.
- printer.Print(agent, func() {
- fmt.Printf("ID: %s\n", agent.ID)
- fmt.Printf("Name: %s\n", agent.DisplayName)
- coreStr := "-"
- if agent.Core != nil {
- coreStr = *agent.Core
- }
- fmt.Printf("Core: %s\n", coreStr)
- if agent.Status != nil {
- fmt.Printf("Status: %s\n", *agent.Status)
- }
- if agent.InstanceStatus != nil {
- fmt.Printf("Instance: %s\n", *agent.InstanceStatus)
- }
- if agent.CurrentOperation != nil {
- fmt.Printf("Op: %s (%s)\n", humanizePhase(agent.CurrentOperation.Kind), agent.CurrentOperation.Status)
- if progress := operationProgress(*agent.CurrentOperation); progress != "" {
- fmt.Printf("Progress: %s\n", progress)
- }
- }
- fmt.Printf("Channels: %s\n", formatList(agent.Channels))
- fmt.Printf("Packages: %s\n", formatList(agent.Packages))
- fmt.Printf("Created: %s\n", agent.CreatedAt)
-
- if pending := pendingConditions(agent.Conditions); len(pending) > 0 {
- fmt.Println("Conditions:")
- for _, cond := range pending {
- label := cond.Type
- if cond.Subject != "" {
- label += "[" + cond.Subject + "]"
- }
- line := fmt.Sprintf(" %s=%s (%s)", label, cond.Status, cond.Reason)
- if msg := strings.TrimSpace(cond.Message); msg != "" {
- line += ": " + msg
- }
- fmt.Println(line)
- }
- }
-
- if agent.LastError != nil {
- fmt.Println()
- RenderLastError(os.Stdout, agent.LastError)
- }
- })
-
- return nil
- },
-}
-
-func pendingConditions(conditions []AgentCondition) []AgentCondition {
- var pending []AgentCondition
- for _, cond := range conditions {
- if cond.Status != "True" {
- pending = append(pending, cond)
- }
- }
- return pending
-}
diff --git a/cmd/oc/internal/commands/agent_init.go b/cmd/oc/internal/commands/agent_init.go
new file mode 100644
index 00000000..5e4b26ab
--- /dev/null
+++ b/cmd/oc/internal/commands/agent_init.go
@@ -0,0 +1,91 @@
+package commands
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/spf13/cobra"
+)
+
+const agentTomlTmpl = `name = %q
+model = %q
+
+[runtime]
+family = %q # claude | codex
+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-4-6\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++
+ }
+ 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-4-6", "Model")
+ agentInitCmd.Flags().String("runtime", "claude", "Runtime family (claude|codex)")
+}
diff --git a/cmd/oc/internal/commands/agent_list.go b/cmd/oc/internal/commands/agent_list.go
deleted file mode 100644
index 1a4c194f..00000000
--- a/cmd/oc/internal/commands/agent_list.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package commands
-
-import (
- "fmt"
-
- "github.com/spf13/cobra"
-)
-
-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 agentListResponse
- if err := sc.Get(cmd.Context(), "/v1/agents", &resp); err != nil {
- return err
- }
-
- printer.Print(resp.Agents, func() {
- if len(resp.Agents) == 0 {
- fmt.Println("No agents found.")
- return
- }
- headers := []string{"ID", "CORE", "CHANNELS", "PACKAGES", "CREATED"}
- var rows [][]string
- for _, a := range resp.Agents {
- coreStr := "-"
- if a.Core != nil {
- coreStr = *a.Core
- }
- channels := formatList(a.Channels)
- packages := formatList(a.Packages)
- created := formatAge(a.CreatedAt)
- rows = append(rows, []string{a.ID, coreStr, channels, packages, created})
- }
- printer.Table(headers, rows)
- })
- return nil
- },
-}
diff --git a/cmd/oc/internal/commands/agent_operations.go b/cmd/oc/internal/commands/agent_operations.go
deleted file mode 100644
index 300c8d0c..00000000
--- a/cmd/oc/internal/commands/agent_operations.go
+++ /dev/null
@@ -1,168 +0,0 @@
-package commands
-
-import (
- "fmt"
- "os"
- "strings"
- "time"
-
- "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
- "github.com/spf13/cobra"
-)
-
-const (
- pollInterval = 2 * time.Second
- pollTimeout = 180 * time.Second
-)
-
-func waitForOperation(
- cmd *cobra.Command,
- sc *client.Client,
- agentID string,
- operation *AgentOperation,
- opLabel string,
-) (*agentResponse, error) {
- if operation == nil {
- return nil, fmt.Errorf("%s did not return an operation handle", opLabel)
- }
-
- deadline := time.Now().Add(pollTimeout)
- lastProgress := ""
- consecutiveErrors := 0
- const errorThreshold = 3
-
- printProgress := func(progress string) {
- if !jsonOutput && progress != "" {
- fmt.Fprintf(os.Stderr, " ⋯ %s\n", progress)
- }
- }
-
- if progress := operationProgress(*operation); progress != "" {
- printProgress(progress)
- lastProgress = progress
- }
-
- for time.Now().Before(deadline) {
- time.Sleep(pollInterval)
-
- current, err := fetchOperation(cmd, sc, agentID, operation.ID)
- if err != nil {
- consecutiveErrors++
- if consecutiveErrors >= errorThreshold {
- renderAsyncFallback(os.Stdout, jsonOutput, agentID, opLabel+" still in progress", lastProgress)
- return nil, nil
- }
- continue
- }
- consecutiveErrors = 0
-
- progress := operationProgress(current)
- if progress != "" && progress != lastProgress {
- printProgress(progress)
- lastProgress = progress
- }
-
- switch current.Status {
- case "queued", "running":
- continue
- case "succeeded":
- agent, err := fetchAgent(cmd, sc, agentID)
- if err != nil {
- return nil, fmt.Errorf("%s completed but failed to fetch agent state: %w", opLabel, err)
- }
- return agent, nil
- case "failed", "canceled":
- agent, err := fetchAgent(cmd, sc, agentID)
- if err != nil {
- return nil, fmt.Errorf("%s failed (unable to fetch agent state: %w)", opLabel, err)
- }
- lastErr := effectiveLastError(agent, &current)
- if !jsonOutput {
- fmt.Fprintln(os.Stderr, " ✗ "+opLabel+" failed")
- fmt.Fprintln(os.Stderr)
- RenderLastError(os.Stderr, lastErr)
- } else {
- agent.LastError = lastErr
- printer.Print(agent, func() {})
- }
- return nil, &ExitError{Code: ExitCodeFor(lastErr)}
- default:
- continue
- }
- }
-
- renderAsyncFallback(os.Stdout, jsonOutput, agentID, opLabel+" still in progress", lastProgress)
- return nil, nil
-}
-
-func fetchAgent(cmd *cobra.Command, sc *client.Client, agentID string) (*agentResponse, error) {
- var agent agentResponse
- if err := sc.Get(cmd.Context(), "/v1/agents/"+agentID, &agent); err != nil {
- return nil, err
- }
- return &agent, nil
-}
-
-func fetchOperation(cmd *cobra.Command, sc *client.Client, agentID, operationID string) (AgentOperation, error) {
- var operation AgentOperation
- err := sc.Get(cmd.Context(), "/v1/agents/"+agentID+"/operations/"+operationID, &operation)
- return operation, err
-}
-
-func effectiveLastError(agent *agentResponse, operation *AgentOperation) *LastError {
- if agent != nil && agent.LastError != nil {
- return agent.LastError
- }
- if operation == nil {
- return nil
- }
-
- phase := ""
- if operation.Phase != nil {
- phase = *operation.Phase
- }
- message := operationProgress(*operation)
- code := ""
- if operation.Code != nil {
- code = *operation.Code
- }
- at := operation.UpdatedAt
- if operation.CompletedAt != nil && *operation.CompletedAt != "" {
- at = *operation.CompletedAt
- }
-
- return &LastError{
- Phase: phase,
- Message: message,
- Code: code,
- At: at,
- }
-}
-
-func operationProgress(operation AgentOperation) string {
- if operation.Message != nil {
- if trimmed := strings.TrimSpace(*operation.Message); trimmed != "" {
- return trimmed
- }
- }
- if operation.Phase != nil {
- if trimmed := strings.TrimSpace(*operation.Phase); trimmed != "" {
- return humanizePhase(trimmed)
- }
- }
- return humanizePhase(operation.Kind)
-}
-
-func humanizePhase(value string) string {
- if value == "" {
- return ""
- }
- parts := strings.Split(value, "_")
- for i, part := range parts {
- if part == "" {
- continue
- }
- parts[i] = strings.ToUpper(part[:1]) + part[1:]
- }
- return strings.Join(parts, " ")
-}
diff --git a/cmd/oc/internal/commands/agent_packages.go b/cmd/oc/internal/commands/agent_packages.go
deleted file mode 100644
index 49e90de9..00000000
--- a/cmd/oc/internal/commands/agent_packages.go
+++ /dev/null
@@ -1,111 +0,0 @@
-package commands
-
-// Package lifecycle: install, uninstall, list. Install is queued and watched
-// via agent operation resources.
-
-import (
- "fmt"
- "os"
-
- "github.com/spf13/cobra"
-)
-
-var agentInstallCmd = &cobra.Command{
- Use: "install <id> <package>",
- Short: "Install a package on an agent",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
-
- agentID := args[0]
- pkg := args[1]
- noWait, _ := cmd.Flags().GetBool("no-wait")
-
- if !jsonOutput {
- fmt.Fprintf(os.Stderr, "Installing %s on %s\n", pkg, agentID)
- }
-
- var result operationSubmissionResponse
- if err := sc.Post(cmd.Context(), "/v1/agents/"+agentID+"/packages/"+pkg, nil, &result); err != nil {
- return err
- }
-
- if noWait {
- note := ""
- if result.Operation != nil {
- note = "Operation: " + result.Operation.ID
- }
- renderAsyncFallback(os.Stdout, jsonOutput, agentID, "Package install", note)
- return nil
- }
-
- agent, err := waitForOperation(cmd, sc, agentID, result.Operation, "Package install")
- if err != nil {
- return err
- }
- if agent == nil {
- return nil
- }
-
- if jsonOutput {
- printer.Print(agent, func() {})
- return nil
- }
-
- fmt.Fprintf(os.Stderr, " ✓ %s installed\n", pkg)
- return nil
- },
-}
-
-var agentUninstallCmd = &cobra.Command{
- Use: "uninstall <id> <package>",
- Short: "Uninstall a package from an agent",
- Args: cobra.ExactArgs(2),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
-
- if err := confirmDestructive(cmd, fmt.Sprintf("Uninstall %s from %s", args[1], args[0])); err != nil {
- return err
- }
-
- if err := sc.Delete(cmd.Context(), "/v1/agents/"+args[0]+"/packages/"+args[1]); err != nil {
- return err
- }
-
- fmt.Printf("Package %s uninstalled from %s.\n", args[1], args[0])
- return nil
- },
-}
-
-var agentPackagesCmd = &cobra.Command{
- Use: "packages <id>",
- Short: "List packages installed on an agent",
- Args: cobra.ExactArgs(1),
- RunE: func(cmd *cobra.Command, args []string) error {
- sc, err := sessionsClient(cmd)
- if err != nil {
- return err
- }
-
- var resp map[string]interface{}
- if err := sc.Get(cmd.Context(), "/v1/agents/"+args[0]+"/packages", &resp); err != nil {
- return err
- }
-
- printer.Print(resp, func() {
- packages := formatList(resp["packages"])
- if packages == "-" {
- fmt.Println("No packages installed.")
- } else {
- fmt.Printf("Packages: %s\n", packages)
- }
- })
- return nil
- },
-}
diff --git a/cmd/oc/internal/commands/exit.go b/cmd/oc/internal/commands/exit.go
new file mode 100644
index 00000000..37ce9637
--- /dev/null
+++ b/cmd/oc/internal/commands/exit.go
@@ -0,0 +1,65 @@
+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/session.go b/cmd/oc/internal/commands/session.go
new file mode 100644
index 00000000..dedac597
--- /dev/null
+++ b/cmd/oc/internal/commands/session.go
@@ -0,0 +1,263 @@
+package commands
+
+// `oc session` — Durable Agent Sessions runtime verbs (/v3/sessions/*). A session
+// is one run of an agent's active (or pinned) revision. Distinct from `oc agent`
+// (which manages the behavior); sessions are addressed by id.
+
+import (
+ "fmt"
+
+ "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\"\n" +
+ " oc session create --agent issue-fixer --input \"...\" --revision 3 # pin a staged revision",
+ 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")
+ revision, _ := cmd.Flags().GetString("revision")
+ 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}
+ if revision != "" {
+ body["revision"] = revision
+ }
+ 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 s Session
+ if err := sc.Get(cmd.Context(), "/v3/sessions/"+args[0], &s); err != nil {
+ return err
+ }
+ printer.Print(s, 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
+ },
+}
+
+// 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().String("revision", "", "Pin a specific revision (number or rev_ id; default = active)")
+ 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/main.go b/cmd/oc/main.go
index 288f2c84..e1f12cd1 100644
--- a/cmd/oc/main.go
+++ b/cmd/oc/main.go
@@ -1,23 +1,13 @@
package main
import (
- "errors"
- "fmt"
"os"
"github.com/opensandbox/opensandbox/cmd/oc/internal/commands"
)
func main() {
- if err := commands.Execute(); err != nil {
- // An ExitError means the command already rendered its output and
- // just wants a specific exit code (e.g. 3 for user-fixable upstream
- // errors, 5 for transient). Don't reprint the message.
- var exit *commands.ExitError
- if errors.As(err, &exit) {
- os.Exit(exit.Code)
- }
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
+ // 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/docs/agent-sessions/agents.mdx b/docs/agent-sessions/agents.mdx
index 1f3bf26f..c652af14 100644
--- a/docs/agent-sessions/agents.mdx
+++ b/docs/agent-sessions/agents.mdx
@@ -4,7 +4,7 @@ title: "Agents"
description: "Reusable agent configuration"
---
-An **agent** is reusable configuration: `name`, `prompt`, `model`, [`runtime`](/agent-sessions/runtimes), and optional [**skills**](/agent-sessions/revisions). Every [session](/agent-sessions/sessions) runs on an agent, so create one first, then start as many sessions on it as you like. The behavior (`prompt`/`model`/`skills`) is versioned as [**revisions**](/agent-sessions/revisions): every edit deploys a new one, and you can roll back.
+An **agent** is reusable configuration: `name`, `prompt`, `model`, [`runtime`](/agent-sessions/runtimes), and optional [**skills**](/agent-sessions/revisions). Every [session](/agent-sessions/sessions) runs on an agent, so create one first, then start as many sessions on it as you like. The behavior (`prompt`/`model`/`skills`) is versioned as [**revisions**](/agent-sessions/revisions): every [deployment](/agent-sessions/revisions) — from the API, the CLI, or a [GitHub push](/agent-sessions/revisions#deploy-from-a-repo) — appends a new one, and you can roll back instantly.
<Note>You can create and edit agents in the [dashboard](https://app.opencomputer.dev) too — the create dialog also lets you pick or add a [credential](/agent-sessions/credentials) inline.</Note>
@@ -44,6 +44,19 @@ Pass your model `key` inline and it's stored as a [credential](/agent-sessions/c
<Tip>Keep the org key and model key on your backend. Only return session-scoped client tokens to browsers.</Tip>
+## Start simple, add capability as you go
+
+The only thing an agent needs is a **model** and a **prompt** — create one and it runs on a **default, managed runtime that just works**. Everything beyond that is **additive**: reach for a rung only when you need it, and nothing earlier is undone.
+
+| Rung | What you add | What you get |
+|---|---|---|
+| **Default agent** | `name` + `model` (+ a prompt) | a working agent on the default runtime — no setup |
+| **+ Skills** | [`SKILL.md` folders](/agent-sessions/skills) (upload a `.zip`, or include in a repo) | reusable procedures the agent loads when relevant — still the default runtime |
+| **+ Deploy from a repo / CLI** | keep the agent's `prompt.md` + `skills/` in Git and [push to deploy](/agent-sessions/revisions#deploy-from-a-repo) | versioned, push-to-deploy, staged revisions + rollback — still the default runtime |
+| **+ Custom runtime** *(coming soon)* | bring your own runtime image | full control of the execution environment |
+
+At every rung the agent is just a small directory — at most `agent.toml` + `prompt.md` + `skills/`. You can stop at any rung; most agents never go past skills.
+
## Session-pinned config
When a session is created it **freezes** the agent's **active [revision](/agent-sessions/revisions)** — `prompt`, `model`, `runtime`, and `skills` — into the session, and pins the resolved credential too. Editing the named agent afterwards never changes a running or resumed session — its behavior is pinned for its whole life. Update an agent freely: existing sessions keep what they started with, new sessions pick up the change. (Rotating a credential's **key value** is the exception — that flows to running sessions, so a compromised key can be replaced; see [credentials](/agent-sessions/credentials).)
diff --git a/docs/agent-sessions/api-reference.mdx b/docs/agent-sessions/api-reference.mdx
index a6b6099f..b5b37fa3 100644
--- a/docs/agent-sessions/api-reference.mdx
+++ b/docs/agent-sessions/api-reference.mdx
@@ -1,11 +1,11 @@
---
-title: "API / SDK reference"
-description: "Every endpoint in the Durable Agent Sessions API, with its TypeScript SDK call"
+title: "API / SDK / CLI reference"
+description: "Every action in the Durable Agent Sessions API, with its TypeScript SDK call and oc CLI command"
---
Base URL `https://api.opencomputer.dev/v3`. Management calls authenticate with your **org API key**; stream and steer also accept a **[client token](/agent-sessions/authentication#client-tokens)**.
-Each section toggles between the **TypeScript** SDK (`@opencomputer/sdk`) and **REST** — pick one and the whole page follows. In the SDK calls, `oc` is the client and `session` is a handle:
+Each section toggles between the **TypeScript SDK** (`@opencomputer/sdk`), **REST**, and the **`oc` CLI** — pick one and the whole page follows.
```ts
import { OpenComputer, connectSession } from "@opencomputer/sdk";
@@ -15,7 +15,13 @@ const session = await oc.sessions.get("ses_..."); // server, org key
// or, in a browser: await connectSession({ sessionId, clientToken })
```
-<Note>The SDK returns the same objects with **camelCase** fields (`client_token` → `session.clientToken`, `created_at` → `createdAt`, `last_turn` → `lastTurn`, `yield_reason` → `yieldReason`, `turn_seconds` → `turnSeconds`, …) and takes camelCase params (`idempotency_key` → `idempotencyKey`). The wire shapes below are the raw JSON. Truly opaque blobs — your session `metadata`, event `refs`, and event `raw` — pass through **verbatim** (keys untouched) in both directions; everything else, including event `body`, is camelCased like the rest.</Note>
+```bash
+# the oc CLI authenticates with OPENCOMPUTER_API_KEY (or `oc login`); --json on any command
+oc whoami
+oc agent deploy # deploy the agent directory in the cwd
+```
+
+<Note>The SDK uses **camelCase** for fields and params (`last_turn` → `lastTurn`, `idempotency_key` → `idempotencyKey`); the wire shapes below are raw JSON. Opaque blobs — session `metadata`, event `refs`/`raw` — pass through **verbatim**; everything else (incl. event `body`) is camelCased. The CLI prints a table, or raw JSON with `--json`.</Note>
## Sessions
@@ -43,7 +49,7 @@ const session = await oc.sessions.get("ses_..."); // server, org key
| --- | --- |
| `POST /sessions` | Start a session → `{ session, client_token }`. |
| `GET /sessions/:id` | Fetch a session. |
-| `GET /sessions?status=&agent=&key=&after=&before=&limit=&cursor=` | List sessions (filtered, paginated; `cursor` = `nextCursor` from the previous page). |
+| `GET /sessions?status=&agent=&key=&after=&before=&limit=&cursor=` | List sessions (filtered, paginated; `cursor` = `nextCursor`). |
| `POST /sessions/:id/archive` | Cancel any active turn, then close (read-only). |
| `POST /sessions/:id/cancel` | Cooperatively stop the active turn (no-op if not running). |
| `GET /sessions/:id/result` | The result helper — `{ last_turn, result? }`. |
@@ -53,41 +59,80 @@ const session = await oc.sessions.get("ses_..."); // server, org key
</Tab>
-</Tabs>
+<Tab title="oc CLI">
-`agent` is **required** (create a saved [agent](#agents) first); the model must resolve to a source — **Managed** (billed to your credits, the default) or a usable [credential](#credentials) — else `422 no_credential` (or `422 managed_unavailable` if Managed is selected but not active for your org). `key` gives get-or-create (one session per key); a request-level `Idempotency-Key` header makes a keyless create retry-safe. `metadata` is opaque **application routing state** — a JSON object (≤ 16 KB) stored on the session, returned by get/list, and delivered **verbatim in webhooks** so a callback handler can route to the right external record without a lookup; it is **never** shown to the model, **not** indexed/queryable, and distinct from `key` (get-or-create) and `Idempotency-Key` (dedupe). `input` is the task — a string or a full [envelope](/agent-sessions/messaging#message-input). For the managed runtimes (`claude`, `codex`), put all task-critical context in the task text. There's no fixed byte cap on `input`, but it counts against the model's context window — **truncate large inputs** (e.g. a PR diff) and have the agent pull the rest through its [sandbox tools](/agent-sessions/runtime-tools) (clone the repo, read files) rather than inlining it. `limits` `{ tokens, turn_seconds, turns }` are **non-monetary** — token budget, per-turn wall-clock, auto-run count; hitting one ends the turn with a matching `last_turn.yield_reason`. Destinations on an idempotent create-replay are ignored — manage them via the [destinations API](#destinations). `sources` checks out one or more repositories for the agent **before the first turn**; the checkout credential never enters the agent's sandbox (see [Repos & GitHub](#github-apps--repos)). Each entry references a registered [repo](#github-apps--repos) — `{ repo, ref, sha, name? }` — or is inline — `{ url, ref, sha, name?, auth }`. `ref` (the fetch ref, e.g. `refs/pull/N/head`) and `sha` are both **required**: the ref is fetched and the exact `sha` is pinned and verified. The create response echoes sanitized `sources`; poll `GET /sessions/:id/sources` for live status.
+| Command | Purpose |
+| --- | --- |
+| `oc session create --agent <id\|name> [--revision <n>] [--input <text>]` | Start a session (`--revision` pins a specific revision; default = active). |
+| `oc session get <id>` | Fetch a session. |
+| `oc session list [--agent <id>] [--status <s>]` | List sessions. |
+| `oc session cancel <id>` | Cooperatively stop the active turn. |
+| `oc session result <id>` | The resolved final result. |
+| `oc session steer <id> <text>` | Send input to a running or waiting session. |
+| *(archive · turns · sources · client tokens — REST/SDK only)* | |
-Client tokens accept `scopes?` (subset of `read`, `steer`) and `ttl?` seconds, clamped to 60–86400 (SDK: `ttlSeconds`).
+</Tab>
-```
-Session = { id, status, head, input_cursor,
- agent_snapshot: { prompt_hash, model, runtime, revision },
- agent_id, credential_id, // resolved + pinned at create
- last_turn: { id, state, yield_reason?, result_event_id? },
- limits: { tokens?, turn_seconds?, turns? },
- metadata?, // opaque app routing state (null when unset)
- key?, created_at }
-
-Turn = {
- id, state, yield_reason?, result_event_id?, error?,
- started_at?, completed_at?
-}
-
-SessionSource = // a sources[] entry — WIRE shape, snake_case
- { repo, ref, sha, name? } // a registered repo id or "owner/repo" — GitHub App auth
- | { url, ref, sha, name?, auth } // inline shortcut; name defaults to repo name, type defaults "git"
-SourceAuth = // inline path ONLY (GitHub App-backed repos need none)
- { type: "risky_short_lived_token", token, expires_at } // short-lived; can't refresh
-// SDK is camelCase: expiresAt (wire expires_at).
-SourceSummary = { name, status, path, sha,
- resolved_sha?, error_code?, error_message?, retryable? }
-// sanitized; in the create response + GET …/sources
-// status: pending | materializing | resolved | failed | auth_required
-// error_code examples: source.auth_required, source.repo_not_selected,
-// source.permission_missing, source.mint_failed, source.ref_not_found, source.sha_mismatch
-```
+</Tabs>
-`yield_reason` (`completed | needs_input | error | budget_exceeded | deadline_exceeded | max_turns | canceled`) is the machine-readable "why the turn ended" — `needs_input` means the agent asked a question; answer it by [steering](#steer).
+**Create params** — `agent` is **required**; the model resolves to **Managed** (default) or a [credential](#credentials), else `422 no_credential` / `422 managed_unavailable`.
+
+- `input` — the task (string or [envelope](/agent-sessions/messaging#message-input)). Truncate large inputs; let the agent fetch the rest via [sandbox tools](/agent-sessions/runtime-tools).
+- `revision?` — pin a specific revision (number / `rev_…`); default = the agent's active one. Use to test a [staged](/agent-sessions/revisions#staging-vs-activating) revision.
+- `key?` — get-or-create (one session per key). Keyless: an `Idempotency-Key` header makes create retry-safe.
+- `metadata?` — opaque routing state (≤ 16 KB); on get/list + **verbatim in webhooks**; never sent to the model, not indexed.
+- `limits?` `{ tokens, turn_seconds, turns }` — non-monetary; tripping one ends the turn (matching `yield_reason`).
+- `sources?` — repos checked out before turn 1 (the token never enters the sandbox; see [GitHub](#github-apps-and-repos)). Each `{ repo, ref, sha, name? }` or inline `{ url, ref, sha, name?, auth }`; `ref` + `sha` required.
+- Client tokens: `scopes?` (`read`/`steer`), `ttl?` 60–86400 s (SDK `ttlSeconds`).
+
+A session pins the agent's active revision for its whole life — editing the agent later never affects a running one.
+
+**`Session`**
+
+| Field | Type | Notes |
+|---|---|---|
+| `id` `status` `head` `input_cursor` | | id, [lifecycle](/agent-sessions/sessions#lifecycle) status, latest event seq, input cursor |
+| `agent_id` `credential_id` | string | resolved + pinned at create |
+| `agent_snapshot` | object | `{ prompt_hash, model, runtime, revision }` — `revision` = the pinned revision number |
+| `last_turn` | `Turn`-ish | `{ id, state, yield_reason?, result_event_id? }` |
+| `limits?` | object | `{ tokens?, turn_seconds?, turns? }` |
+| `metadata?` | object | opaque app routing state |
+| `key?` `created_at` | | get-or-create key, timestamp |
+
+**`Turn`**
+
+| Field | Notes |
+|---|---|
+| `id` `state` | turn id, current state |
+| `yield_reason?` | why it ended (below) |
+| `result_event_id?` | the event carrying the result |
+| `error?` | failure detail, if any |
+| `started_at?` `completed_at?` | timing |
+
+A turn's **`yield_reason`** tells you why it stopped:
+
+| Value | Meaning |
+|---|---|
+| `completed` | finished normally |
+| `needs_input` | the agent asked a question — answer it by [steering](#steer) |
+| `error` | the turn failed (see `error`) |
+| `budget_exceeded` / `deadline_exceeded` / `max_turns` | a [limit](#sessions) tripped — tokens / wall-clock / auto-runs |
+| `canceled` | you cancelled it |
+
+**`SessionSource`** — one of two variants:
+
+| Variant | Shape |
+|---|---|
+| registered | `{ repo, ref, sha, name? }` — `repo` is a `repo_…` id or `"owner/repo"`; App-backed auth |
+| inline | `{ url, ref, sha, name?, auth }` — `auth = { type:"risky_short_lived_token", token, expires_at }` (can't refresh) |
+
+**`SourceSummary`** (sanitized; on create + `GET …/sources`)
+
+| Field | Notes |
+|---|---|
+| `name` `path` `sha` `resolved_sha?` | checkout identity + resolved commit |
+| `status` | `pending · materializing · resolved · failed · unavailable · auth_required` |
+| `error_code?` `error_message?` `retryable?` | on failure — `source.`-prefixed, e.g. `source.auth_required` (App not installed), `source.repo_not_selected` (install doesn't cover the repo), `source.permission_missing`, `source.mint_failed`, `source.ref_not_found`, `source.sha_mismatch`. [Full list](/agent-sessions/repos) |
## Events
@@ -98,7 +143,7 @@ SourceSummary = { name, status, path, sha,
| Call | Purpose |
| --- | --- |
| `session.listEvents(opts)` | Read events since a cursor. |
-| `session.events(opts)` | Live stream from a cursor — an async iterator that resumes itself. |
+| `session.events(opts)` | Live stream from a cursor — a self-resuming async iterator. |
| `session.event(id)` | Fetch one event (resolve `resultEventId`). |
| `session.eventContent(id)` | Fetch a blob-backed body (large outputs). |
| `session.messages(opts)` | User-message history. |
@@ -111,24 +156,34 @@ SourceSummary = { name, status, path, sha,
| --- | --- |
| `GET /sessions/:id/events?after=<seq>&level=<lvl>` | Read events since a cursor. |
| `GET /sessions/:id/events?…&stream=sse` | Live SSE stream from a cursor. |
-| `GET /sessions/:id/events/:eventId` | Fetch one event (resolve `result_event_id`). |
-| `GET /sessions/:id/events/:eventId/content` | Fetch a blob-backed body (large outputs). |
+| `GET /sessions/:id/events/:eventId` | Fetch one event. |
+| `GET /sessions/:id/events/:eventId/content` | Fetch a blob-backed body. |
| `GET /sessions/:id/messages` | User-message history. |
</Tab>
+<Tab title="oc CLI">
+
+| Command | Purpose |
+| --- | --- |
+| `oc session logs <id> [--follow] [--level <lvl>] [--type <t>]` | Read or live-stream events. |
+| *(single event · event content · messages — REST/SDK only)* | |
+
+</Tab>
+
</Tabs>
-Filter events by `type` (exact or `prefix.*`), `turn_id`, and `limit`. `…/messages` is an alias for `level=user` + `type=*.message`.
+Filter by `type` (exact or `prefix.*`), `turn_id`, `limit`. `after` resumes from a `seq`; `level` is a **visibility threshold** — `user` < `progress` < `internal` (default `internal`; see [visibility levels](/agent-sessions/events#visibility-levels)). Switch on [`type`](/agent-sessions/events#event-shape), don't parse prose. `…/messages` is an alias for `level=user` + `type=*.message`.
-`after` resumes from a `seq`; `level` is a **visibility threshold** — `user` returns only user-facing events, `progress` adds work updates, `internal` adds everything (see [visibility levels](/agent-sessions/events#visibility-levels)). Omitting `level` defaults to `internal` (you get everything). Switch on [`type`](/agent-sessions/events#event-shape), don't parse prose. `type`/`turn_id` filtering applies to the **list** endpoint; the **SSE stream** filters by `level` + `after` server-side, so the SDK's `events({ type })` applies the type filter client-side as events arrive.
+**`Event`**
-```
-Event = {
- id, seq, ts, session, actor, type, level, body, turn_id?,
- content_ref?, body_truncated?, body_bytes?
-}
-```
+| Field | Notes |
+|---|---|
+| `id` `seq` `ts` `session` | id, monotonic seq, timestamp, session id |
+| `actor` `type` `level` | source, event [type](/agent-sessions/events#event-shape), visibility level |
+| `body` | the payload (camelCased; switch on `type`, don't parse prose) |
+| `turn_id?` | the turn it belongs to |
+| `content_ref?` `body_truncated?` `body_bytes?` | large bodies are offloaded — fetch via `…/events/:id/content` |
## Steer
@@ -150,11 +205,19 @@ Event = {
</Tab>
+<Tab title="oc CLI">
+
+| Command | Purpose |
+| --- | --- |
+| `oc session steer <id> <text>` | Append an input message; wakes the session. |
+
+</Tab>
+
</Tabs>
Body: `{ text, idempotency_key? }` or `{ envelope }`. Returns `202` (or `200` on idempotent replay) with `{ event: { id, seq }, session: { id, status, head } }`.
-## Destinations
+## Agents
<Tabs>
@@ -162,10 +225,10 @@ Body: `{ text, idempotency_key? }` or `{ envelope }`. Returns `202` (or `200` on
| Call | Purpose |
| --- | --- |
-| `session.destinations.create(params)` | Register a webhook destination. |
-| `session.destinations.list()` · `.get(did)` | List / fetch. |
-| `session.destinations.update(did, params)` | Pause/resume (`enabled`), retune `level`/`types`, rotate `secret`. |
-| `session.destinations.delete(did)` | Remove. |
+| `oc.agents.create(params)` | Create a reusable agent. |
+| `oc.agents.get(id)` · `oc.agents.list()` | Fetch / list. |
+| `oc.agents.update(id, params)` | Update bindings (credential / limits) — `prompt`/`model` deploy a revision. |
+| `oc.agents.delete(id)` | Delete an agent. |
</Tab>
@@ -173,18 +236,35 @@ Body: `{ text, idempotency_key? }` or `{ envelope }`. Returns `202` (or `200` on
| Method · Path | Purpose |
| --- | --- |
-| `POST /sessions/:id/destinations` | Register a webhook destination. |
-| `GET /sessions/:id/destinations` · `…/:did` | List / fetch. |
-| `PATCH /sessions/:id/destinations/:did` | Pause/resume (`enabled`), retune `level`/`types`, rotate `secret`. |
-| `DELETE /sessions/:id/destinations/:did` | Remove. |
+| `POST /agents` | Create a reusable agent. |
+| `GET /agents/:id` · `GET /agents` | Fetch / list. |
+| `PATCH /agents/:id` | Update bindings; `prompt`/`model` deploy a revision. |
+| `DELETE /agents/:id` | Delete an agent. |
+
+</Tab>
+
+<Tab title="oc CLI">
+
+| Command | Purpose |
+| --- | --- |
+| `oc agent create <name> --model <m> [--runtime claude\|codex]` | Create a reusable agent. |
+| `oc agent get <id\|name>` · `oc agent list` | Fetch / list. |
+| `oc agent update <id> [--credential <c>] [--limits …]` | Update bindings. |
+| `oc agent delete <id>` | Delete an agent. |
</Tab>
</Tabs>
-Destination body: `url`, `secret?`, `level?` (`user`), `types?[]`, `include_raw?` (`false`, SDK: `includeRaw`), `enabled?` (`true`). `types` accepts exact event types or `prefix.*`.
+Body: `name`, `prompt`, `model`, `runtime?` (`claude`|`codex`), `key?`, `credential?`, `limits?`. PATCH takes the same **minus `runtime`** (fixed at create). `runtime`/`model` provider must agree (`claude`↔`anthropic/…`, `codex`↔`openai/…`). `credential`: a `cred_…` id (BYO, provider-matched) **or** `"managed"` (via OpenComputer, billed to credits) — mutually exclusive with `key`.
-## Deliveries
+`POST /agents` is **idempotent by `name`**: fresh → `201`, matching config → `200`, differing → `409`. Editing `prompt`/`model` (here or via [deploy](#deployments-and-revisions)) creates a **revision**; the agent keeps a pointer to its **active revision** (`GET /agents/:id` → `active_revision`) and sessions pin it. The agent row holds only identity + bindings.
+
+## Deployments and revisions
+
+You **deploy** an agent's behavior (`prompt` + `model` + `skills`); each deployment produces an immutable **revision**, and the **active revision** is what new sessions use. See the [Deployments & revisions guide](/agent-sessions/revisions).
+
+### Deploy
<Tabs>
@@ -192,9 +272,9 @@ Destination body: `url`, `secret?`, `level?` (`user`), `types?[]`, `include_raw?
| Call | Purpose |
| --- | --- |
-| `session.deliveries.list(opts)` | List deliveries — status, attempts, last response/error. |
-| `session.deliveries.get(id)` | One delivery, in detail. |
-| `session.deliveries.redeliver(id)` | Re-send any delivery (not just dead-lettered). |
+| `oc.agents.deployments.create(id, { input, activate?, idempotencyKey? })` | Deploy (`input.type: "inline" \| "github"`). |
+| `oc.agents.deployments.list(id)` · `.get(id, depId)` | Deployment history · one deployment. |
+| `oc.agents.deploy(dir)` *(Node)* | Bundle a local directory → inline deployment. |
</Tab>
@@ -202,28 +282,36 @@ Destination body: `url`, `secret?`, `level?` (`user`), `types?[]`, `include_raw?
| Method · Path | Purpose |
| --- | --- |
-| `GET /sessions/:id/deliveries?destination=&status=&after=&limit=` | List deliveries — status, attempts, last response/error. Returns `{ data }`; filter with `after` (a `created_at` cutoff) and `limit`. |
-| `GET /sessions/:id/deliveries/:id` | One delivery, in detail. |
-| `POST /sessions/:id/deliveries/:id/redeliver` | Re-send any delivery (not just dead-lettered). |
+| `POST /agents/:id/deployments` | Deploy → `{ deployment }`. Body: `{ input, activate?=true, idempotency_key?, client_context? }`. |
+| `GET /agents/:id/deployments` · `…/:deploymentId` | History · one deployment (poll async to `ready`\|`failed`). |
+
+</Tab>
+
+<Tab title="oc CLI">
+
+| Command | Purpose |
+| --- | --- |
+| `oc agent deploy [dir] [--agent <id\|name>] [--no-activate]` | Bundle a local directory → inline deployment. |
+| `oc agent deployments [--agent <id>]` · `oc agent deployments get <id>` | History · one deployment. |
</Tab>
</Tabs>
-See [Webhooks](/agent-sessions/webhooks#signing-retries-and-dedupe) for signing, retries, and dedupe.
+`input`: `{ type:"inline", prompt, model?, skills?, runtime? }` (the **complete** behavior — omitted `skills` = none) **or** `{ type:"github", ref?, sha? }` (deploys the [linked repo](#deploy-from-a-repo); `repo`/`path` from the link). `activate:false` **stages** it — but only for `inline`; `github` deploys are **branch-driven** (the production branch activates, others stage) so `activate` is ignored. Inline = sync (`ready` + `revision_id`); GitHub = async (`accepted`, then poll to `ready`). `POST …/revisions` is inline-only sugar.
-```
-Destination = {
- id, session, kind, url, level, types, include_raw, enabled,
- has_secret, created_after_seq, created_at, updated_at
-}
-Delivery = {
- id, session, destination, event_id, event_seq, status, attempts,
- last_attempt_at, response_code?, error?, created_at, updated_at
-}
-```
+**`Deployment`**
-## Agents
+| Field | Notes |
+|---|---|
+| `id` `created_at` | |
+| `state` | `accepted` (async — queued for the deploy worker) → terminal `ready`; other terminals: `failed`, `superseded` (a newer deploy won), `skipped` (content unchanged) |
+| `result` | `created · skipped · superseded · failed` (`null` until terminal) |
+| `revision_id` | the revision it produced (`null` until `ready`) |
+| `active` | whether that revision is the active one |
+| `source?` `error?` | provenance · failure detail |
+
+### Revisions, rollback & promote
<Tabs>
@@ -231,9 +319,9 @@ Delivery = {
| Call | Purpose |
| --- | --- |
-| `oc.agents.create(params)` | Create a reusable agent. |
-| `oc.agents.get(id)` · `oc.agents.list()` | Fetch / list. |
-| `oc.agents.update(id, params)` | Update the agent for future sessions. |
+| `oc.agents.revisions.list(id)` · `.get(id, n)` | History · one revision (+ skill manifest). |
+| `oc.agents.revisions.activate(id, n)` | Set the active revision (rollback **or** promote). |
+| `oc.agents.activations.list(id)` | Active-pointer audit log. |
</Tab>
@@ -241,25 +329,76 @@ Delivery = {
| Method · Path | Purpose |
| --- | --- |
-| `POST /agents` | Create a reusable agent. |
-| `GET /agents/:id` · `GET /agents` | Fetch / list. |
-| `PATCH /agents/:id` | Update the agent for future sessions. |
+| `GET /agents/:id/revisions` · `…/:rev` | History · one revision (+ skill manifest). |
+| `POST /agents/:id/revisions/:rev/activate` | Set the active revision (rollback / promote). |
+| `GET /agents/:id/activations` | Active-pointer audit log. |
+
+</Tab>
+
+<Tab title="oc CLI">
+
+| Command | Purpose |
+| --- | --- |
+| `oc agent revisions [--agent <id>]` · `oc agent revisions get <n>` | History · one revision. |
+| `oc agent rollback <n\|rev_…>` | Set the active revision (rollback / promote). |
+| `oc agent activations` | Active-pointer audit log. |
</Tab>
</Tabs>
-Create body: `name`, `prompt`, `model`, `runtime?` (`claude` | `codex`), `key?`, `credential?`, `limits?`. Patch accepts `prompt?`, `model?`, `key?`, `credential?`, and `limits?` — **not `runtime`, which is fixed at creation**. The `runtime` / `model` provider must agree (`claude`↔`anthropic/…`, `codex`↔`openai/…`), validated at create. `credential` is a closed value: a `cred_…` id (BYO, must match the runtime's provider) **or** the literal `"managed"` — run the model **via OpenComputer, billed to your credits**, which bypasses the credential provider match (the `model` still must match the runtime). `key` and `credential` are mutually exclusive.
+Revisions are **linear** (numbered, immutable). `:rev` is a `number` or `rev_…` id. Activate moves the active pointer instantly (no rebuild); rollback (earlier) and promote (a staged one) are the same call.
+
+**`Revision`**
+
+| Field | Notes |
+|---|---|
+| `id` `number` `created_at` `active` | id, monotonic number, timestamp, is-active flag |
+| `prompt` `model` | the behavior |
+| `skill_bundle_digest?` | content-addressed skills bundle (`null` = no skills) |
+| `digest` | behavior content hash (change detection) |
+| `runtime_ref` | `floating` (latest shared runtime) — `pinned` later (custom runtime) |
+| `files?` | `[{ path, mode, size }]` — only on `GET …/revisions/:rev` |
+
+### Skills
+
+<Tabs>
+
+<Tab title="TypeScript SDK">
+
+| Call | Purpose |
+| --- | --- |
+| `oc.agents.skills.get(id)` | List the active revision's skills (name, description, files). |
+| `oc.agents.skills.put(id, zip)` | Replace skills from a `.zip` → new revision. |
+| `oc.agents.skills.delete(id)` | Remove all skills → new revision. |
+
+</Tab>
+
+<Tab title="REST API">
-`POST /agents` is **idempotent by `name`** — the outcome is in the **status code**, not a body field: a fresh create returns **201**; a repeat with matching non-secret config (`prompt`/`model`/`runtime`/`limits`) returns the existing agent with **200**; differing config returns **409**. Safe to call on every app startup or deploy. (`key` is ignored on a 200 hit — it never silently rotates.)
+| Method · Path | Purpose |
+| --- | --- |
+| `GET /agents/:id/skills` | List the active revision's skills. |
+| `PUT /agents/:id/skills` | Replace skills from a `.zip` (`Content-Type: application/zip`) → new revision. |
+| `DELETE /agents/:id/skills` | Remove all skills → new revision. |
-Pass `key` **or** `credential` (`"managed"` or a `cred_…` id), or neither → org default (Managed when your org has no default key). The agent's `limits` are the defaults for its sessions; a session's own `limits` override. Each agent has a monotonic `revision` (bumped on PATCH) that sessions pin in `agent_snapshot.revision`, so you can tell which version produced a run.
+</Tab>
-## GitHub Apps & Repos
+<Tab title="oc CLI">
-A GitHub App lets OpenComputer obtain short-lived, repo-scoped tokens for the repositories agents may work in. A **Repo** is a stable repository handle that resolves to your configured GitHub App (the OpenComputer App by default, or your own). See the [Repos & GitHub guide](/agent-sessions/repos).
+| Command | Purpose |
+| --- | --- |
+| `oc agent deploy <dir>` | Deploy a directory; a `skills/` folder inside it ships as skills → new revision. |
-During preview, **install the [OpenComputer GitHub App](https://github.com/apps/opencomputerdev/installations/new)** on the repos you want OpenComputer to work with (you pick the exact repos). **No credential passes through this API for the OpenComputer App.** You can also **bring your own GitHub App** (`byo_stored_key`) — register an existing App, or create one in one click via the [manifest flow](/agent-sessions/repos#bring-your-own-github-app); the App key is encrypted at rest and never returned. `byo_broker` is registrable but not yet used for minting.
+Skills have no dedicated CLI verb yet — deploy a directory that contains a `skills/` folder, or use the REST endpoints / dashboard.
+
+</Tab>
+
+</Tabs>
+
+A skill is a folder with a `SKILL.md`; PUT/DELETE are **deployments** (versioned, rollback-able). Limits: 64 files, 256 KiB total, UTF-8, modes `0644`/`0755`. Full guide: [Skills](/agent-sessions/skills).
+
+### Deploy from a repo
<Tabs>
@@ -267,15 +406,143 @@ During preview, **install the [OpenComputer GitHub App](https://github.com/apps/
| Call | Purpose |
| --- | --- |
-| `oc.repos.create(params)` | Register (get-or-create) a repo. |
-| `oc.repos.get(id)` · `oc.repos.list()` | Fetch / list. |
-| `oc.repos.update(id, params)` | Update `name`. |
+| `oc.agents.deploymentSource.link(id, params)` | Link a repo directory → push-to-deploy. |
+| `oc.agents.deploymentSource.get(id)` | The link + status. |
+| `oc.agents.deploymentSource.unlink(id)` | Remove the link (shared App webhook untouched). |
+
+</Tab>
+
+<Tab title="REST API">
+
+| Method · Path | Purpose |
+| --- | --- |
+| `POST /agents/:id/deployment-source` | Link a repo directory. Body: `{ repo, path, production_ref?, deploy_now?=true }`. |
+| `GET /agents/:id/deployment-source` | The link + status. |
+| `DELETE /agents/:id/deployment-source` | Remove the link. |
+
+</Tab>
+
+<Tab title="oc CLI">
+
+| Command | Purpose |
+| --- | --- |
+| `oc agent link <owner/repo> --path <p> [--branch <ref>] [--no-deploy]` | Link a repo directory. |
+| `oc agent status [id\|name]` | The agent's active revision + link status. |
+| `oc agent unlink` | Remove the link. |
+
+</Tab>
+
+</Tabs>
+
+Linking deploys the current production HEAD immediately (unless `deploy_now: false` / `--no-deploy`); a push to the production branch activates, other branches stage. **Scopes:** `deploy_now: false` needs `agents:link`; the default (with an initial deploy) needs `agents:link` + `agents:deploy`, plus `agents:activate` when that deploy auto-activates. Repo/path are server-anchored to the link. Deployment sources use the **OpenComputer App** (no BYO). Full flow + guarantees: [Deploy from a repo](/agent-sessions/revisions#deploy-from-a-repo).
+
+**`DeploymentSource`**
+
+| Field | Notes |
+|---|---|
+| `agent_id` `repo_id` `path` | the linked agent · repo · directory within it |
+| `production_ref` | branch that auto-activates on push |
+| `status` | `active`, or a problem: `path_missing`, `ref_missing` (production branch deleted), `auth_required`, `repo_not_selected`, `app_suspended`, `error` |
+| `latest_seen_sha?` `active_deployed_sha?` | newest sha observed · sha behind the active revision |
+
+## Destinations
+
+*Webhooks are configured via SDK/REST (no `oc` command).*
+
+<Tabs>
+
+<Tab title="TypeScript SDK">
+
+| Call | Purpose |
+| --- | --- |
+| `session.destinations.create(params)` | Register a webhook destination. |
+| `session.destinations.list()` · `.get(did)` | List / fetch. |
+| `session.destinations.update(did, params)` | Pause/resume (`enabled`), retune `level`/`types`, rotate `secret`. |
+| `session.destinations.delete(did)` | Remove. |
+
+</Tab>
+
+<Tab title="REST API">
+
+| Method · Path | Purpose |
+| --- | --- |
+| `POST /sessions/:id/destinations` | Register a webhook destination. |
+| `GET /sessions/:id/destinations` · `…/:did` | List / fetch. |
+| `PATCH /sessions/:id/destinations/:did` | Pause/resume, retune, rotate. |
+| `DELETE /sessions/:id/destinations/:did` | Remove. |
+
+</Tab>
+
+</Tabs>
+
+Destination body: `url`, `secret?`, `level?` (`user`), `types?[]`, `include_raw?` (`false`, SDK: `includeRaw`), `enabled?` (`true`). `types` accepts exact types or `prefix.*`.
+
+## Deliveries
+
+*Delivery records are read via SDK/REST (no `oc` command).*
+
+<Tabs>
+
+<Tab title="TypeScript SDK">
+
+| Call | Purpose |
+| --- | --- |
+| `session.deliveries.list(opts)` | List deliveries — status, attempts, last response/error. |
+| `session.deliveries.get(id)` | One delivery, in detail. |
+| `session.deliveries.redeliver(id)` | Re-send any delivery. |
+
+</Tab>
+
+<Tab title="REST API">
+
+| Method · Path | Purpose |
+| --- | --- |
+| `GET /sessions/:id/deliveries?destination=&status=&after=&limit=` | List deliveries. |
+| `GET /sessions/:id/deliveries/:id` | One delivery. |
+| `POST /sessions/:id/deliveries/:id/redeliver` | Re-send any delivery. |
+
+</Tab>
+
+</Tabs>
+
+See [Webhooks](/agent-sessions/webhooks#signing-retries-and-dedupe) for signing, retries, dedupe.
+
+**`Destination`**
+
+| Field | Notes |
+|---|---|
+| `id` `session` `kind` `created_at` `updated_at` | |
+| `url` | webhook target |
+| `level` `types` | visibility threshold · event-type filter |
+| `include_raw` `enabled` `has_secret` | include raw bodies · paused/active · whether a signing secret is set |
+| `created_after_seq` | only events after this seq are delivered |
+
+**`Delivery`**
+
+| Field | Notes |
+|---|---|
+| `id` `session` `destination` `created_at` `updated_at` | |
+| `event_id` `event_seq` | the event delivered |
+| `status` `attempts` `last_attempt_at` | delivery state, retry count, last try |
+| `response_code?` `error?` | last response · failure detail |
+
+## GitHub Apps and Repos
+
+A GitHub App lets OpenComputer mint short-lived, repo-scoped tokens; a **Repo** is a stable handle resolving to your configured App (the OpenComputer App by default). Used for session [sources](#sessions) (work repos) and [deploy-from-a-repo](#deploy-from-a-repo) (the agent's definition repo). Install the [OpenComputer App](https://github.com/apps/opencomputerdev/installations/new). **Bring-your-own** Apps apply to **session sources / PR publishing** (your users acting on their own repos) — **deployment sources always use the OpenComputer App**.
+
+<Tabs>
+
+<Tab title="TypeScript SDK">
+
+| Call | Purpose |
+| --- | --- |
+| `oc.repos.create(params)` · `.get(id)` · `.list()` · `.update(id, params)` | Register / fetch / list / rename a repo. |
| `oc.github.apps.list()` | List GitHub Apps available to your org. |
| `oc.github.apps.register(params)` | Register your own App (`byo_stored_key` / `byo_broker`). |
-| `oc.github.apps.createManifestUrl(params)` | One-click: get a link to open; OpenComputer hosts the GitHub flow + key capture. |
-| `oc.github.apps.createManifest(params)` · `completeManifest(params)` | Developer-driven manifest flow (you host the redirect). |
-| `oc.github.apps.update(id, params)` · `delete(id)` | Update / rotate / remove a registered App. |
-| `oc.github.installations.list()` | List GitHub App installations visible to OpenComputer. |
+| `oc.github.apps.createManifestUrl(params)` | One-click: a link to open; OpenComputer hosts the flow + key capture. |
+| `oc.github.apps.createManifest/completeManifest(params)` | Developer-driven manifest flow. |
+| `oc.github.apps.update(id, params)` · `delete(id)` | Update / rotate / remove an App. |
+| `oc.github.installations.list()` | List installations visible to OpenComputer. |
</Tab>
@@ -283,31 +550,31 @@ During preview, **install the [OpenComputer GitHub App](https://github.com/apps/
| Method · Path | Purpose |
| --- | --- |
-| `POST /repos` | Register (get-or-create) a repo. |
-| `GET /repos/:id` · `GET /repos` | Fetch / list. |
-| `PATCH /repos/:id` | Update `name`. |
-| `GET /github/apps` | List GitHub Apps available to your org. |
-| `POST /github/apps` | Register your own App (`byo_stored_key` / `byo_broker`). |
-| `PATCH /github/apps/:id` · `DELETE /github/apps/:id` | Update / rotate / remove a registered App. |
-| `POST /github/apps/manifest` | Start the manifest flow → `{ start_url }` (hosted) or `{ manifest, … }` (with `redirect_url`). |
-| `GET /github/apps/manifest/start` · `…/callback` | Hosted pages OpenComputer serves (browser, not called directly). |
-| `POST /github/apps/manifest/conversions` | Developer-driven: exchange the code for a registered App. |
-| `GET /github/installations` | List GitHub App installations visible to OpenComputer. |
+| `POST /repos` · `GET /repos/:id` · `GET /repos` · `PATCH /repos/:id` | Register / fetch / list / rename a repo. |
+| `GET /github/apps` · `POST /github/apps` | List · register your own App. |
+| `PATCH /github/apps/:id` · `DELETE /github/apps/:id` | Update / rotate / remove. |
+| `POST /github/apps/manifest` · `…/manifest/start` · `…/callback` · `…/conversions` | Manifest flow (hosted or developer-driven). |
+| `GET /github/installations` | List installations visible to OpenComputer. |
+
+</Tab>
+
+<Tab title="oc CLI">
+
+| Command | Purpose |
+| --- | --- |
+| `oc repo add <owner/repo>` · `oc repo list` · `oc repo get <id>` | Register / list / fetch a repo. |
+| *(App install + manifest — browser flow; manage in the dashboard or via SDK/REST)* | |
</Tab>
</Tabs>
-Repo create body: `owner`, `repo`, `provider?` (`github`, default), `name?` (a handle). **No `auth`** — auth resolves through your configured GitHub App (the OpenComputer App by default). **Idempotent by `(provider, owner, repo)`** (201 fresh / 200 repeat). (Pinning a repo to a specific App is coming later.)
+Repo body: `owner`, `repo`, `provider?` (`github`), `name?` — **no `auth`** (resolves via your App); **idempotent by `(provider, owner, repo)`**. Registering is **optional** under the OpenComputer App (reference `"owner/repo"` directly). Responses **never** carry a token/secret; App responses have `id, mode, status, github_app_id?, app_name?, is_default?`. [Guide](/agent-sessions/repos).
```
-Repo = { id, provider, owner, repo, name?, created_at, updated_at }
+Repo = { id, provider, owner, repo, name?, created_at, updated_at }
```
-Responses **never** contain a token or secret. Registering a repo is **optional** under the OpenComputer App — a session can reference `"owner/repo"` directly.
-
-`GET /github/apps` lists the GitHub Apps available to your org — the built-in OpenComputer App plus any you register. Register your own with `POST /github/apps` (`byo_stored_key`: `github_app_id` + `private_key`; `byo_broker`: `broker_url` + `broker_secret`), or one-click: `POST /github/apps/manifest` returns a `start_url` to open and OpenComputer hosts the GitHub redirect + key capture (creating an App is a GitHub-UI flow, so it's a link to open, not a fully programmatic call). App responses carry `id`, `mode`, `status`, `github_app_id?`, `app_name?`, `is_default?` — **never** a key or secret. `GET /github/installations` lists installations visible to OpenComputer; it may be **empty** for orgs using only the OpenComputer App. See the [Repos & GitHub guide](/agent-sessions/repos#bring-your-own-github-app) for the full flow.
-
## Credentials
<Tabs>
@@ -318,7 +585,7 @@ Responses **never** contain a token or secret. Registering a repo is **optional*
| --- | --- |
| `oc.credentials.create(params)` | Add a provider key. |
| `oc.credentials.list()` · `oc.credentials.delete(id)` | List / remove. |
-| `oc.credentials.setDefault(params)` | Set the org default to a credential. |
+| `oc.credentials.setDefault(params)` | Set the org default. |
</Tab>
@@ -328,13 +595,23 @@ Responses **never** contain a token or secret. Registering a repo is **optional*
| --- | --- |
| `POST /credentials` | Add a provider key. |
| `GET /credentials` · `DELETE /credentials/:id` | List / remove. |
-| `PUT /credentials/default` | Set the org default to a credential (its provider is derived). |
+| `PUT /credentials/default` | Set the org default (provider derived). |
+
+</Tab>
+
+<Tab title="oc CLI">
+
+| Command | Purpose |
+| --- | --- |
+| `oc credential add --provider <p> --key <k> [--default]` | Add a provider key. |
+| `oc credential list` · `oc credential remove <id>` | List / remove. |
+| `oc credential set-default <id>` | Set the org default. |
</Tab>
</Tabs>
-Credential body: `provider` (`anthropic` | `openai`), `key`, `name?`, `is_default?`. Keys are write-only. A BYO credential is optional — agents can run **Managed** (`credential: "managed"`, billed to your credits, no key), the default for new orgs. See the [Credentials](/agent-sessions/credentials) guide for Managed vs BYO, resolution, rotation, and the dashboard.
+Credential body: `provider` (`anthropic` | `openai`), `key`, `name?`, `is_default?`. Keys are write-only. A BYO credential is optional — agents can run **Managed** (`credential: "managed"`, the default). See [Credentials](/agent-sessions/credentials).
```
Credential = { id, provider, name?, last4, is_default, created_at }
@@ -343,4 +620,4 @@ ClientToken = { token, scopes, expires_at }
## Errors & rate limits
-Errors use one envelope: `{ "error": { "type", "message" } }`; the SDK throws them as typed `OpenComputerError` subclasses (`AuthError`, `NotFoundError`, `ConflictError`, `ValidationError`, `RateLimitError`). Cross-owner resources return `404` (not `403`). Rate and concurrency limits are not enforced at launch (a `429` with a `Retry-After` header may be introduced later; the SDK retries it automatically).
+One envelope: `{ "error": { "type", "message" } }`; the SDK throws typed `OpenComputerError` subclasses (`AuthError`, `NotFoundError`, `ConflictError`, `ValidationError`, `RateLimitError`); the CLI exits non-zero and prints the message (the JSON with `--json`). Cross-owner resources return `404` (not `403`). Rate/concurrency limits aren't enforced at launch (a `429` with `Retry-After` may come later; the SDK retries it).
diff --git a/docs/agent-sessions/overview.mdx b/docs/agent-sessions/overview.mdx
index 59735892..961c6f18 100644
--- a/docs/agent-sessions/overview.mdx
+++ b/docs/agent-sessions/overview.mdx
@@ -37,7 +37,7 @@ Create an agent, start a session, stream its event log, steer it with messages,
<Steps>
<Step title="Define an agent">
- Create a reusable `{ name, model, prompt, runtime }` from your backend — `runtime: "claude"` (Anthropic models) or `"codex"` (OpenAI models). Run **Managed** (`credential: "managed"`, billed to your OpenComputer credits — no key) or pass your own model `key` inline / reference a saved [credential](/agent-sessions/credentials). Every edit is versioned as a [revision](/agent-sessions/revisions), and you can attach [skills](/agent-sessions/revisions#skills). ([Agents](/agent-sessions/agents))
+ Create a reusable `{ name, model, prompt, runtime }` from your backend — `runtime: "claude"` (Anthropic models) or `"codex"` (OpenAI models). Run **Managed** (`credential: "managed"`, billed to your OpenComputer credits — no key) or pass your own model `key` inline / reference a saved [credential](/agent-sessions/credentials). Every [deployment](/agent-sessions/revisions) is versioned as a [revision](/agent-sessions/revisions) (roll back instantly), you can attach [skills](/agent-sessions/revisions#skills), and you can [deploy from a GitHub repo on push](/agent-sessions/revisions#deploy-from-a-repo). ([Agents](/agent-sessions/agents))
</Step>
<Step title="Start a session">
Start a session with `{ agent, input }`. The agent starts immediately and returns a browser-safe `client_token`.
diff --git a/docs/agent-sessions/quickstart.mdx b/docs/agent-sessions/quickstart.mdx
index 7ec20846..569cc878 100644
--- a/docs/agent-sessions/quickstart.mdx
+++ b/docs/agent-sessions/quickstart.mdx
@@ -62,7 +62,7 @@ Content-Type: application/json
Response:
```json
-{ "id": "agt_...", "name": "quickstart-coder", "revision": 1 }
+{ "id": "agt_...", "name": "quickstart-coder", "active_revision": { "number": 1 } }
```
<Note>Your model `key` is held in OpenComputer's [secret store](/sandboxes/secrets) (encrypted, write-only) and **never enters the sandbox**. The agent runs with a placeholder; an **egress proxy substitutes the real key in-flight** on the outbound model-provider call. Reuse one key across agents via a [credential](/agent-sessions/credentials).</Note>
diff --git a/docs/agent-sessions/revisions.mdx b/docs/agent-sessions/revisions.mdx
index 4b99a06f..5ed335a1 100644
--- a/docs/agent-sessions/revisions.mdx
+++ b/docs/agent-sessions/revisions.mdx
@@ -1,140 +1,202 @@
---
-mode: "wide"
-title: "Revisions & skills"
-description: "Versioned agent behavior — deploy, roll back, and manage skills"
+title: "Deployments & revisions"
+description: "Deploy agent behavior, version it as immutable revisions, roll back instantly"
---
-An agent's behavior — its `prompt`, `model`, and **skills** — is versioned as **revisions**. Every change is a **deploy** that appends a new immutable revision; the agent's **active revision** is what new [sessions](/agent-sessions/sessions) use. Rolling back is just re-activating an earlier revision.
+What you deploy is a small directory:
-<Note>Revisions are **linear**: each deploy is a new revision (like a deployment on Vercel/Fly), and the number only goes up. Re-activating an older revision (rollback) moves the **active pointer** back, but never deletes or rewrites history. In-flight sessions keep the revision they started on; only new sessions pick up the change.</Note>
+```
+my-agent/
+├─ agent.toml # name, model, runtime family
+├─ prompt.md # the system prompt
+├─ skills/ # optional — folders the agent loads when it needs them
+└─ runtime/ # optional — a custom runtime image (coming soon)
+```
+
+`agent.toml` + `prompt.md` are all an agent needs; `skills/` and `runtime/` are additive — add them only when you do. A **deployment** packages this directory into an immutable [**revision**](#revisions); the **active revision** is what new [sessions](/agent-sessions/sessions) use, and you roll back by re-activating an earlier one.
+
+Deploy three ways — all the same underneath: the **API/SDK** (send it inline), the **`oc` CLI** (bundle a local directory), or a [**repo push**](#deploy-from-a-repo).
-## What's on a revision
+## Revisions
+
+A **revision** is an immutable snapshot of an agent's behavior — the `prompt`, `model`, and skills from one deployment, frozen and numbered. Every deploy appends a new one (a repo push that changes nothing is skipped); the agent's **active revision** is the one new [sessions](/agent-sessions/sessions) run.
+
+Revisions are **linear** (the number only goes up, like a Vercel/Fly deployment) and never rewritten — [rolling back](#roll-back-and-promote) just moves the active pointer to an earlier one. In-flight sessions keep the revision they started on; only new sessions pick up a change.
| Field | |
|---|---|
| `number` | Monotonic per agent (`1, 2, 3, …`). |
-| `prompt` / `model` | The behavior at deploy time. |
-| `skill_bundle_digest` | Points at the skill files (a content-addressed bundle); `null` when the agent has no skills. |
-| `digest` | A content hash of the behavior — two revisions with the same behavior share a digest (the bundle is also deduplicated in storage), but each deploy is still its own revision. |
+| `prompt` / `model` | The behavior at deployment time. |
+| `skill_bundle_digest` | The skill files (a content-addressed bundle); `null` when there are no skills. |
+| `digest` | A content hash of the behavior (used for change detection). |
-The agent row keeps only **identity + bindings** (`name`, `runtime`, `credential`, `limits`) plus a pointer to the active revision. `prompt`/`model` are served from that revision.
+The agent itself holds only **identity + bindings** (`name`, `runtime`, `credential`, `limits`) plus a pointer to the active revision; `prompt`/`model` are served from that revision.
-## Deploy a revision
+## Deploy
-Editing an agent's `prompt` or `model` deploys a revision automatically (the response shape of [`PATCH /agents/:id`](/agent-sessions/agents) is unchanged):
+`POST /agents/:id/deployments` is the one command. `input.type: "inline"` sends behavior directly (API / CLI / dashboard); `input.type: "github"` deploys a linked repo — see [Deploy from a repo](#deploy-from-a-repo).
-```http REST API
-PATCH https://api.opencomputer.dev/v3/agents/agt_123
-Authorization: Bearer $OPENCOMPUTER_API_KEY
-Content-Type: application/json
+An inline payload is the **complete** behavior — omitted fields aren't inherited (`prompt` is required; omitted `skills` means *no skills*).
-{ "prompt": "You are a meticulous reviewer. Run the tests." }
-```
+<CodeGroup>
-For a full behavior payload (prompt + model + skills in one go), deploy directly. This is the **complete** behavior — omitted fields are not inherited (`prompt` is required; omitted `skills` means *no skills*).
+```ts TypeScript SDK
+const deployment = await oc.agents.deployments.create("agt_123", {
+ input: {
+ type: "inline",
+ prompt: "You triage pull requests.",
+ model: "anthropic/claude-opus-4-8",
+ skills: [{ path: "triage/SKILL.md", content: "---\nname: triage\ndescription: Triage a PR\n---\nSummarize the diff…" }],
+ },
+});
+```
```http REST API
-POST https://api.opencomputer.dev/v3/agents/agt_123/revisions
+POST https://api.opencomputer.dev/v3/agents/agt_123/deployments
Authorization: Bearer $OPENCOMPUTER_API_KEY
Content-Type: application/json
{
- "prompt": "You triage pull requests.",
- "model": "anthropic/claude-opus-4-8",
- "skills": [
- { "path": "triage/SKILL.md", "content": "---\nname: triage\ndescription: Triage a PR\n---\nSummarize the diff…" }
- ],
- "activate": true
+ "input": {
+ "type": "inline",
+ "prompt": "You triage pull requests.",
+ "model": "anthropic/claude-opus-4-8",
+ "skills": [{ "path": "triage/SKILL.md", "content": "---\nname: triage\ndescription: Triage a PR\n---\nSummarize the diff…" }]
+ }
}
```
-```json Response (201)
-{
- "deploy_id": "dep_…",
- "state": "ready",
- "result": "created",
- "revision": { "id": "rev_…", "number": 5, "digest": "sha256:…", "active": true }
-}
+```bash CLI
+# from a directory holding agent.toml + prompt.md + skills/
+oc agent deploy
```
-`activate` defaults to `true` (deploy straight to production). Pass `activate: false` to stage a revision without changing what new sessions use.
-
-## Roll back / promote
+</CodeGroup>
-Re-activate any earlier revision by **number** or `rev_…` id — this moves the active pointer. Running sessions are unaffected; new sessions use it.
+The response is a **deployment**:
-```http REST API
-POST https://api.opencomputer.dev/v3/agents/agt_123/revisions/3/activate
-Authorization: Bearer $OPENCOMPUTER_API_KEY
+```json
+{ "deployment": { "id": "dep_…", "state": "ready", "revision_id": "rev_…", "active": true } }
```
-```json Response (200)
-{ "active_revision_id": "rev_…" }
-```
+Inline deployments finish synchronously (`state: "ready"` with a `revision_id`). Asynchronous deployments (GitHub) return `state: "accepted"` — poll `GET /agents/:id/deployments/:deployment_id` until `ready` (or `failed`/`skipped`/`superseded`); a repo deploy also reports progress as a **commit status** on GitHub.
-## Inspect history
+### Staging vs activating
-```http REST API
-GET /v3/agents/agt_123/revisions # history (newest first; `active` flags the current one)
-GET /v3/agents/agt_123/revisions/5 # one revision + its skill file manifest
-GET /v3/agents/agt_123/deploys # deploy timeline (provenance + state)
-GET /v3/agents/agt_123/activations # pointer-move audit log
+By default a ready deployment is **activated** — its revision becomes what new sessions use. Pass **`activate: false`** to **stage** instead: the revision is created but not made active, so you can test it before it goes live.
+
+```ts
+// 1. stage a revision (not activated)
+const { deployment } = await oc.agents.deployments.create("agt_123", { input: { type: "inline", prompt: "…" }, activate: false });
+
+// 2. test it — a session pins the agent's ACTIVE revision by default; pass `revision`
+// to run the staged one instead
+const session = await oc.sessions.create({ agent: "agt_123", revision: deployment.revision_id, input: "…" });
+
+// 3. happy? promote it
+await oc.agents.revisions.activate("agt_123", deployment.revision_id);
```
-`GET /agents/:id` also includes an `active_revision` summary (`id`, `number`, `digest`).
+So `revision` on [session create](/agent-sessions/sessions) is how you exercise any non-active revision (a staged one, or an old one) without touching what's live.
-## Skills
+For [repo deployments](#deploy-from-a-repo) the **branch decides** and `activate` is ignored: a push to the production branch activates, every other branch stages.
+
+<Tip>Editing `prompt`/`model` via [`PATCH /agents/:id`](/agent-sessions/agents) also deploys a revision — a shorthand for small edits.</Tip>
+
+## Deploy from a repo
-A **skill** is a folder containing a `SKILL.md` (with YAML frontmatter — `name` + `description` — followed by instructions the agent loads at the start of a turn) plus any helper files it references. An agent can have several. Skills are materialized into the runtime when a session runs, so the agent can use them.
+Keep the agent directory (above) in Git and **push to deploy**. [Install the OpenComputer GitHub App](/agent-sessions/repos#connecting-github) on the repo, then connect it to an agent:
-Manage them as a sub-resource of the agent. **List** the active revision's skills:
+<CodeGroup>
+
+```ts TypeScript SDK
+await oc.agents.deploymentSource.link("agt_123", { repo: "acme/agents", path: "issue-fixer", productionRef: "main" });
+```
```http REST API
-GET https://api.opencomputer.dev/v3/agents/agt_123/skills
+POST https://api.opencomputer.dev/v3/agents/agt_123/deployment-source
Authorization: Bearer $OPENCOMPUTER_API_KEY
+Content-Type: application/json
+
+{ "repo": "acme/agents", "path": "issue-fixer", "production_ref": "main" }
```
-```json Response (200)
-{
- "revision": { "id": "rev_…", "number": 5, "digest": "sha256:…" },
- "skill_bundle_digest": "sha256:…",
- "skills": [
- { "name": "triage", "description": "Triage a PR", "files": [{ "path": "triage/SKILL.md", "mode": 420, "size": 812 }] }
- ]
-}
+```bash CLI
+oc agent link acme/agents --path issue-fixer --branch main
```
-**Upload** a `.zip` of your skills — the API unzips, validates, and deploys a new revision with those skills (keeping the agent's current prompt + model). The zip body is sent raw:
+</CodeGroup>
-```http REST API
-PUT https://api.opencomputer.dev/v3/agents/agt_123/skills
-Authorization: Bearer $OPENCOMPUTER_API_KEY
-Content-Type: application/zip
+Linking deploys the current `main` HEAD right away (`deploy_now: false` / `--no-deploy` to skip). Then every push that touches the directory deploys:
+
+- push to **`main`** (production) → a new revision, **activated**.
+- push to **another branch** → a revision **staged** (test, then [promote](#roll-back-and-promote)).
+- a push not touching the directory → **no-op**; identical directory content → **skipped** (no churn).
+
+OpenComputer posts a **commit status** (queued → ready / failed) so a deployment's result shows in GitHub.
-<binary .zip>
+Your **GitHub token never reaches the agent's sandbox** — OpenComputer pulls only the linked directory, at the exact commit, in an isolated worker; a deployment can only target the directory you connected; no code runs at deploy time. (Same token model as [repos](/agent-sessions/repos).)
+
+## Deploy from your machine
+
+No repo needed — the CLI bundles a local agent directory and deploys it:
+
+```bash CLI
+oc agent deploy # deploy ./ (the agent named in agent.toml)
+oc agent deploy ./agents/issue-fixer # a specific directory
+oc agent deploy --no-activate # stage instead of activate
```
-The zip should contain **one folder per skill**, each with a `SKILL.md`:
+Same as a repo push — handy for CI that isn't GitHub, or trying a change before you commit.
+
+## Roll back and promote
+
+Rollback and promote are the **same primitive** — set the active revision. Re-activate any earlier revision (rollback) or a staged one (promote):
+
+<CodeGroup>
+
+```ts TypeScript SDK
+await oc.agents.revisions.activate("agt_123", 3);
+```
+```http REST API
+POST https://api.opencomputer.dev/v3/agents/agt_123/revisions/3/activate
+Authorization: Bearer $OPENCOMPUTER_API_KEY
```
-triage/
- SKILL.md
- checklist.md
-pr-review/
- SKILL.md
+
+```bash CLI
+oc agent rollback 3
```
-A top-level `skills/` wrapper is fine too (it's stripped). **Remove** all skills (deploys a revision with none):
+</CodeGroup>
+
+Instant — no rebuild. Running sessions are unaffected; new sessions use the newly-active revision.
+
+## Inspect
```http REST API
-DELETE https://api.opencomputer.dev/v3/agents/agt_123/skills
-Authorization: Bearer $OPENCOMPUTER_API_KEY
+GET /v3/agents/agt_123/deployments # deployment history (state, source, actor)
+GET /v3/agents/agt_123/deployments/dep_123 # one deployment (poll async ones to ready|failed)
+GET /v3/agents/agt_123/revisions # revision history (newest first; active flagged)
+GET /v3/agents/agt_123/revisions/5 # one revision + its skill file manifest
+GET /v3/agents/agt_123/activations # active-pointer audit log
```
-Uploading and removing are both **deploys** — each is a new revision (not a rollback). Limits: up to 64 files, 256 KiB total, UTF-8 text only, modes `0644`/`0755`.
+`GET /agents/:id` also includes an `active_revision` summary (`id`, `number`, `digest`).
+
+## Skills
+
+Skills — reusable instruction folders the agent loads when relevant — are **part of a revision**, so they're deployed, versioned, and rolled back exactly like the prompt and model. Include them inline in a deployment (`skills:[…]`, above), upload a `.zip` (`PUT …/skills`), or ship a `skills/` directory [from a repo](#deploy-from-a-repo).
+
+See the **[Skills](/agent-sessions/skills)** page for the `SKILL.md` format, how skills are invoked, all three ways to add them, and limits.
+
+## Not yet supported
-<Note>**v1 supports skills on the `claude` runtime only.** Skills on a `codex` agent are rejected; custom runtimes and MCP servers are not yet supported.</Note>
+These are **coming soon** — a deployment that includes them is rejected today:
+- **MCP servers** (`mcp.json`)
+- **Custom runtimes** (a `runtime/` directory)
+- **Skills on `codex` agents** — skills are `claude`-runtime only for now
## Dashboard
-Everything here is in the [dashboard](https://app.opencomputer.dev) on the agent page: a **Revisions** panel (history, the active revision, one-click rollback) and a **Skills** panel (the current skills with descriptions, plus upload-a-`.zip` and remove).
+The agent page in the [dashboard](https://app.opencomputer.dev) mirrors all of this: a **Revisions** panel (history, the active revision, one-click rollback) and a **Skills** panel (current skills, plus upload-`.zip` / remove).
diff --git a/docs/agent-sessions/sessions.mdx b/docs/agent-sessions/sessions.mdx
index c3f9d70b..fbbb2280 100644
--- a/docs/agent-sessions/sessions.mdx
+++ b/docs/agent-sessions/sessions.mdx
@@ -10,7 +10,7 @@ A **session** is an [agent](/agent-sessions/agents) run with an append-only [eve
## Session flow
-1. You create a session from an [agent](/agent-sessions/agents). The model runs **Managed** (billed to your credits, no key — the default) or on a [model credential](/agent-sessions/credentials) you supply. The session starts immediately.
+1. You create a session from an [agent](/agent-sessions/agents). It **pins the agent's active [revision](/agent-sessions/revisions)** (prompt / model / skills) for its whole life — editing the agent later never affects a running session. Pass `revision` to pin a specific one instead (e.g. to test a [staged](/agent-sessions/revisions#staging-vs-activating) revision before promoting). The model runs **Managed** (billed to your credits, no key — the default) or on a [model credential](/agent-sessions/credentials) you supply. The session starts immediately.
2. The [runtime](/agent-sessions/runtimes) executes the agent in a sandbox, appending [events](/agent-sessions/events) to the log as it works.
3. With nothing left to do, the session goes **idle** and the sandbox **hibernates**.
4. A [steer](/agent-sessions/messaging) message wakes it; it resumes with its prior context. Repeat.
diff --git a/docs/agent-sessions/skills.mdx b/docs/agent-sessions/skills.mdx
new file mode 100644
index 00000000..edfa9eaf
--- /dev/null
+++ b/docs/agent-sessions/skills.mdx
@@ -0,0 +1,123 @@
+---
+mode: "wide"
+title: "Skills"
+description: "Reusable instructions an agent loads when it needs them"
+---
+
+A **skill** is a folder of instructions (plus optional helper files) an agent loads **when the task calls for it** — a playbook it reaches for, without bloating every prompt. Skills are the most common way to grow an agent past its base prompt ([the second rung](/agent-sessions/agents#start-simple-add-capability-as-you-go)).
+
+## What a skill is
+
+A folder with a `SKILL.md`:
+
+```
+triage/
+ SKILL.md
+ checklist.md # optional helper the SKILL.md can reference
+```
+
+`SKILL.md` is YAML frontmatter followed by instructions:
+
+```markdown
+---
+name: triage
+description: Triage an incoming pull request
+---
+1. Read the diff and the linked issue.
+2. Label by area, flag risky changes, run the tests.
+3. Summarize in three bullets.
+```
+
+- **`name`** + **`description`** are always visible to the agent; the **body** is loaded only when the agent decides the skill is relevant — progressive disclosure that keeps context lean.
+- Helper files alongside `SKILL.md` (checklists, scripts, references) are available when the skill runs.
+
+## How it works
+
+When a session starts, the agent's skills are **materialized into its runtime**. The model sees each skill's `name` + `description` and **invokes** one when the task matches, then follows its instructions (and can read its helper files). Skills don't run on their own — the agent uses them like tools.
+
+Skills are part of the agent's [revision](/agent-sessions/revisions): they're versioned, rolled back, and activated together with the prompt and model. Changing skills is a [deployment](/agent-sessions/revisions#deploy).
+
+## Add skills
+
+Three ways. Each is a **[deployment](/agent-sessions/revisions)** that creates a new immutable **revision** (your new skills + the agent's current prompt & model) and activates it — so changing skills is **versioned and instantly [reversible](/agent-sessions/revisions#roll-back-and-promote)**, never a destructive edit.
+
+<Tabs>
+<Tab title="Upload a .zip">
+One folder per skill (a top-level `skills/` wrapper is fine — it's stripped):
+
+```
+triage/
+ SKILL.md
+pr-review/
+ SKILL.md
+ checklist.md
+```
+
+<CodeGroup>
+
+```bash CLI
+# Skills ship as part of a deploy — put them in a skills/ folder:
+oc agent deploy ./agent
+```
+
+```http REST API
+PUT https://api.opencomputer.dev/v3/agents/agt_123/skills
+Authorization: Bearer $OPENCOMPUTER_API_KEY
+Content-Type: application/zip
+
+<binary .zip>
+```
+
+</CodeGroup>
+
+In the [dashboard](https://app.opencomputer.dev), the agent's **Skills** panel uploads the same `.zip`. This is a **deployment**: it creates a new **revision** (keeping the current prompt + model, replacing the skills) and activates it. The previous skills aren't lost — **roll back** anytime by re-activating the earlier revision (one click in the Revisions panel, or `oc agent rollback <n>`).
+</Tab>
+
+<Tab title="Inline in a deployment">
+Include `skills` in a [deployment](/agent-sessions/revisions#deploy) payload — the complete behavior in one call:
+
+```ts TypeScript SDK
+await oc.agents.deployments.create("agt_123", {
+ input: {
+ type: "inline",
+ prompt: "You triage pull requests.",
+ skills: [{ path: "triage/SKILL.md", content: "---\nname: triage\ndescription: Triage a PR\n---\n…" }],
+ },
+});
+```
+</Tab>
+
+<Tab title="From a repo / CLI">
+Put a `skills/` directory in your agent directory and [deploy from a repo](/agent-sessions/revisions#deploy-from-a-repo) (push to deploy) or `oc agent deploy` from a local checkout:
+
+```
+issue-fixer/
+ agent.toml
+ prompt.md
+ skills/
+ triage/SKILL.md
+```
+
+Every push that changes `skills/` deploys a new revision.
+</Tab>
+</Tabs>
+
+## List & remove
+
+```http REST API
+GET /v3/agents/agt_123/skills # enumerated: name, description, files
+DELETE /v3/agents/agt_123/skills # remove all skills (deploys a revision with none)
+```
+
+`GET` returns each skill with its parsed `name`/`description` and file list — handy for showing what an agent currently knows.
+
+## Authoring tips
+
+- **One skill, one job.** A sharp `description` is what tells the agent *when* to use it.
+- Keep `SKILL.md` instructions concrete and ordered; move long reference material into helper files the body points to.
+- Skills are instructions, not code — they shape *how* the agent works, using the runtime's own tools.
+
+## Limits & availability
+
+- Up to **64 files**, **256 KiB** total, UTF-8 text, file modes `0644`/`0755`.
+- **`claude` runtime only** today; skills on `codex` agents are [coming soon](/agent-sessions/revisions#not-yet-supported).
diff --git a/docs/docs.json b/docs/docs.json
index bafe7974..4980df39 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -74,6 +74,7 @@
"agent-sessions/quickstart",
"agent-sessions/agents",
"agent-sessions/revisions",
+ "agent-sessions/skills",
"agent-sessions/sessions",
"agent-sessions/credentials",
"agent-sessions/repos",
diff --git a/go.mod b/go.mod
index 7659c2d7..01224b27 100644
--- a/go.mod
+++ b/go.mod
@@ -44,6 +44,7 @@ require (
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
+ github.com/BurntSushi/toml v1.6.0 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.18 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 // indirect
diff --git a/go.sum b/go.sum
index b96ba932..8c8ce537 100644
--- a/go.sum
+++ b/go.sum
@@ -28,6 +28,8 @@ 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/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY=
github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=
diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.json
index a4377dac..02ddd8a0 100644
--- a/sdks/typescript/package-lock.json
+++ b/sdks/typescript/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/sdk",
- "version": "0.9.4",
+ "version": "0.10.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/sdk",
- "version": "0.9.4",
+ "version": "0.10.0",
"license": "MIT",
"devDependencies": {
"@types/node": "^25.3.0",
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index 6d1d6fdf..89739e1a 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/sdk",
- "version": "0.9.4",
+ "version": "0.10.0",
"description": "TypeScript SDK for OpenComputer - cloud sandbox platform",
"type": "module",
"main": "dist/index.js",
diff --git a/sdks/typescript/src/agents/agents.ts b/sdks/typescript/src/agents/agents.ts
index 973667a4..e9784b47 100644
--- a/sdks/typescript/src/agents/agents.ts
+++ b/sdks/typescript/src/agents/agents.ts
@@ -1,5 +1,9 @@
import type { Http, Query } from "./http.js";
import type { Agent, CredentialRef, Limits, Runtime } from "./types.js";
+import {
+ Deployments, Revisions, Activations, Skills, DeploymentSourceResource,
+ type Deployment, type InlineSkillFile,
+} from "./deployments.js";
export interface CreateAgentParams {
name: string;
@@ -54,7 +58,24 @@ export interface ConnectSlackParams {
/** Reusable agents — the "what" a session runs. */
export class Agents {
- constructor(private readonly http: Http) {}
+ /** Deploy behavior (inline or from a linked repo) — each deployment produces a revision. */
+ readonly deployments: Deployments;
+ /** Immutable, numbered revisions + rollback / promote (set the active revision). */
+ readonly revisions: Revisions;
+ /** Active-pointer audit log. */
+ readonly activations: Activations;
+ /** The active revision's skills (zip upload / remove). */
+ readonly skills: Skills;
+ /** Repo linkage for push-to-deploy. */
+ readonly deploymentSource: DeploymentSourceResource;
+
+ constructor(private readonly http: Http) {
+ this.deployments = new Deployments(http);
+ this.revisions = new Revisions(http);
+ this.activations = new Activations(http);
+ this.skills = new Skills(http);
+ this.deploymentSource = new DeploymentSourceResource(http);
+ }
create(params: CreateAgentParams): Promise<Agent> {
// Idempotent by name server-side → safe to auto-retry transient failures.
@@ -90,4 +111,69 @@ export class Agents {
disconnectSlack(id: string): Promise<{ ok: boolean }> {
return this.http.request("DELETE", `/agents/${id}/slack`);
}
+
+ /**
+ * Node-only sugar: bundle a local agent directory (`agent.toml` + `prompt.md` + optional
+ * `skills/`) and deploy it inline. Resolve the target agent from `opts.agentId` or the manifest's
+ * `[agent].id`. Uses dynamic `node:fs`/`node:path` imports so the browser build never loads them.
+ */
+ async deploy(dir = ".", opts: { agentId?: string; activate?: boolean } = {}): Promise<{ deployment: Deployment }> {
+ const fs = await import("node:fs/promises");
+ const path = await import("node:path");
+ const read = (rel: string) => fs.readFile(path.join(dir, rel), "utf8");
+
+ let toml = "";
+ try { toml = await read("agent.toml"); } catch { /* optional when agentId is passed */ }
+ const agentId = opts.agentId ?? tomlSectionValue(toml, "agent", "id");
+ if (!agentId) throw new Error("oc.agents.deploy: pass { agentId } or set [agent].id in agent.toml");
+
+ let prompt: string;
+ try { prompt = await read("prompt.md"); }
+ catch { throw new Error("oc.agents.deploy: prompt.md is required in the agent directory"); }
+ const model = tomlTopLevel(toml, "model");
+
+ const skills: InlineSkillFile[] = [];
+ await walkSkills(fs, path, path.join(dir, "skills"), path.join(dir, "skills"), skills);
+
+ return this.deployments.create(agentId, {
+ input: { type: "inline", prompt, model, skills: skills.length ? skills : undefined },
+ activate: opts.activate,
+ });
+ }
+}
+
+// ── agent.toml helpers (minimal — the manifest is flat; no TOML dep) ──
+
+/** A top-level `key = "value"` before the first [section]. */
+function tomlTopLevel(toml: string, key: string): string | undefined {
+ const head = toml.split(/^\s*\[/m)[0];
+ return new RegExp(`^\\s*${key}\\s*=\\s*["']([^"']*)["']`, "m").exec(head)?.[1];
+}
+
+/** A `key = "value"` inside `[section]`. */
+function tomlSectionValue(toml: string, section: string, key: string): string | undefined {
+ const sec = new RegExp(`\\[${section}\\]([\\s\\S]*?)(?:\\n\\s*\\[|$)`).exec(toml)?.[1];
+ if (!sec) return undefined;
+ return new RegExp(`^\\s*${key}\\s*=\\s*["']([^"']*)["']`, "m").exec(sec)?.[1];
+}
+
+/** Recursively read `skills/` into InlineSkillFile[] (paths relative to the skills root). */
+async function walkSkills(
+ fs: typeof import("node:fs/promises"),
+ path: typeof import("node:path"),
+ root: string,
+ dir: string,
+ out: InlineSkillFile[],
+): Promise<void> {
+ let entries: import("node:fs").Dirent[];
+ try { entries = await fs.readdir(dir, { withFileTypes: true }); }
+ catch { return; } // no skills/ directory
+ for (const e of entries) {
+ const full = path.join(dir, e.name);
+ if (e.isDirectory()) { await walkSkills(fs, path, root, full, out); continue; }
+ if (!e.isFile()) continue;
+ const content = await fs.readFile(full, "utf8");
+ const st = await fs.stat(full);
+ out.push({ path: path.relative(root, full).split(path.sep).join("/"), content, mode: (st.mode & 0o111) ? 0o755 : 0o644 });
+ }
}
diff --git a/sdks/typescript/src/agents/deployments.ts b/sdks/typescript/src/agents/deployments.ts
new file mode 100644
index 00000000..df33dd86
--- /dev/null
+++ b/sdks/typescript/src/agents/deployments.ts
@@ -0,0 +1,191 @@
+// Deploy / revision / skills / deployment-source sub-resources of `oc.agents` (deploy-from-github).
+// You DEPLOY an agent's behavior (inline or from a linked repo); each deployment produces an
+// immutable REVISION, and the ACTIVE revision is what new sessions run. The HTTP layer converts
+// camelCase ⟷ snake_case on the wire, so params/results here are camelCase.
+
+import type { Http } from "./http.js";
+import type { Page } from "./agents.js";
+
+// ── Types ──────────────────────────────────────────────────────────────────────
+
+export interface InlineSkillFile { path: string; content: string; mode?: number | string; }
+
+/** Behavior sent directly (the complete behavior — omitted `skills` means none). */
+export interface InlineDeployInput {
+ type: "inline";
+ prompt?: string;
+ model?: string;
+ skills?: InlineSkillFile[];
+ runtime?: { type?: "default" | "custom" };
+}
+
+/** Deploy the agent's linked repo at a ref/sha (repo/path come from the deployment source). */
+export interface GithubDeployInput { type: "github"; ref?: string; sha?: string; }
+
+export type DeployInput = InlineDeployInput | GithubDeployInput;
+
+export interface CreateDeploymentParams {
+ input: DeployInput;
+ /** Honored for inline only; github deploys are branch-driven (ignored). Default true. */
+ activate?: boolean;
+ /** CI-safe: a re-run with the same key returns the existing deployment. */
+ idempotencyKey?: string;
+ /** Free-form caller note (not provenance). */
+ clientContext?: Record<string, unknown>;
+}
+
+export interface Deployment {
+ id: string;
+ state: string; // accepted|queued|fetching|validating|uploading|ready|failed|superseded|skipped
+ result?: string | null;
+ revisionId?: string | null;
+ active?: boolean;
+ inputType?: string;
+ ref?: string | null;
+ sha?: string | null;
+ error?: unknown;
+ errorClass?: string | null;
+ createdAt?: string;
+}
+
+export interface RevisionFile { path: string; mode: number; size: number; }
+
+export interface Revision {
+ id: string;
+ number: number;
+ digest: string;
+ prompt?: string;
+ model?: string | null;
+ skillBundleDigest?: string | null;
+ runtimeRef?: unknown;
+ active?: boolean;
+ createdAt?: string;
+ files?: RevisionFile[];
+}
+
+export interface Activation {
+ id: string;
+ from?: string | null;
+ to: string;
+ actor?: string | null;
+ reason: string;
+ createdAt?: string;
+}
+
+export interface SkillSummary {
+ name: string;
+ description: string | null;
+ files: { path: string; mode: number; size: number }[];
+}
+
+export interface AgentSkills {
+ revision: { id: string; number: number; digest: string } | null;
+ skillBundleDigest: string | null;
+ skills: SkillSummary[];
+}
+
+export interface DeploymentSource {
+ agentId: string;
+ ownerId?: string;
+ repoId: string;
+ path: string;
+ productionRef: string;
+ status: string; // active|path_missing|ref_missing|auth_required|repo_not_selected|app_suspended|error
+ latestSeenSha?: string | null;
+ activeDeployedSha?: string | null;
+}
+
+export interface LinkParams {
+ /** "owner/repo" slug or a `repo_…` id. */
+ repo: string;
+ /** Agent dir within the repo ("" for the repo root). */
+ path: string;
+ /** Branch that auto-activates on push (default "main"). */
+ productionRef?: string;
+ /** Deploy the production HEAD immediately on link (default true). */
+ deployNow?: boolean;
+}
+
+export interface LinkResult { source: DeploymentSource; deploymentId?: string; deployError?: { type: string; message: string }; }
+
+/** Skill .zip body — a Blob (browser) or bytes (Node). */
+export type SkillZip = Blob | ArrayBuffer | Uint8Array;
+
+// ── Sub-resources ────────────────────────────────────────────────────────────
+
+/** Deploy an agent's behavior; read the deployment history. */
+export class Deployments {
+ constructor(private readonly http: Http) {}
+
+ /** Deploy (`input.type: "inline" | "github"`). Returns the deployment (inline is usually `ready`). */
+ create(agentId: string, params: CreateDeploymentParams): Promise<{ deployment: Deployment }> {
+ return this.http.request("POST", `/agents/${agentId}/deployments`, {
+ body: { input: params.input, activate: params.activate, clientContext: params.clientContext },
+ idempotencyKey: params.idempotencyKey,
+ idempotent: params.idempotencyKey !== undefined,
+ });
+ }
+ list(agentId: string): Promise<Page<Deployment>> {
+ return this.http.request("GET", `/agents/${agentId}/deployments`);
+ }
+ get(agentId: string, deploymentId: string): Promise<Deployment> {
+ return this.http.request("GET", `/agents/${agentId}/deployments/${deploymentId}`);
+ }
+}
+
+/** Immutable, numbered revisions + the active pointer (rollback / promote). */
+export class Revisions {
+ constructor(private readonly http: Http) {}
+
+ list(agentId: string): Promise<Page<Revision>> {
+ return this.http.request("GET", `/agents/${agentId}/revisions`);
+ }
+ /** A revision by number or `rev_…` id (includes its skill file manifest). */
+ get(agentId: string, rev: number | string): Promise<Revision> {
+ return this.http.request("GET", `/agents/${agentId}/revisions/${rev}`);
+ }
+ /** Set the active revision — rollback (an earlier one) or promote (a staged one). */
+ activate(agentId: string, rev: number | string): Promise<{ activeRevisionId: string }> {
+ return this.http.request("POST", `/agents/${agentId}/revisions/${rev}/activate`, { idempotent: true });
+ }
+}
+
+/** Active-pointer audit log. */
+export class Activations {
+ constructor(private readonly http: Http) {}
+ list(agentId: string): Promise<Page<Activation>> {
+ return this.http.request("GET", `/agents/${agentId}/activations`);
+ }
+}
+
+/** The active revision's skills; replace/remove them (each is a deployment → a new revision). */
+export class Skills {
+ constructor(private readonly http: Http) {}
+
+ get(agentId: string): Promise<AgentSkills> {
+ return this.http.request("GET", `/agents/${agentId}/skills`);
+ }
+ /** Replace skills from a `.zip` (one folder per skill, each with a SKILL.md). */
+ put(agentId: string, zip: SkillZip): Promise<unknown> {
+ return this.http.upload("PUT", `/agents/${agentId}/skills`, zip as unknown as BodyInit, "application/zip");
+ }
+ /** Remove all skills (deploys a revision with none). */
+ delete(agentId: string): Promise<unknown> {
+ return this.http.request("DELETE", `/agents/${agentId}/skills`);
+ }
+}
+
+/** Bind the agent to a repo directory for push-to-deploy (always the OpenComputer App). */
+export class DeploymentSourceResource {
+ constructor(private readonly http: Http) {}
+
+ link(agentId: string, params: LinkParams): Promise<LinkResult> {
+ return this.http.request("POST", `/agents/${agentId}/deployment-source`, { body: params });
+ }
+ get(agentId: string): Promise<{ source: DeploymentSource }> {
+ return this.http.request("GET", `/agents/${agentId}/deployment-source`);
+ }
+ unlink(agentId: string): Promise<{ ok: boolean }> {
+ return this.http.request("DELETE", `/agents/${agentId}/deployment-source`);
+ }
+}
diff --git a/sdks/typescript/src/agents/http.ts b/sdks/typescript/src/agents/http.ts
index a5e808e1..1ab504a1 100644
--- a/sdks/typescript/src/agents/http.ts
+++ b/sdks/typescript/src/agents/http.ts
@@ -92,6 +92,13 @@ export class Http {
if (!res.ok) throw errorFromResponse(res.status, (await safeJson(res))?.error, retryAfterSec(res));
return res;
}
+
+ /** Upload a raw (non-JSON) body — e.g. a skill `.zip`. Normalizes the JSON response. */
+ async upload<T>(method: string, path: string, body: BodyInit, contentType: string, signal?: AbortSignal): Promise<T> {
+ const res = await this.doFetch(this.url(path), { method, headers: this.headers({ "Content-Type": contentType }), body, signal });
+ if (!res.ok) throw errorFromResponse(res.status, (await safeJson(res))?.error, retryAfterSec(res));
+ return res.status === 204 ? (undefined as T) : normalize<T>(await res.json());
+ }
}
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
diff --git a/sdks/typescript/src/agents/index.ts b/sdks/typescript/src/agents/index.ts
index bc989197..e56f59f3 100644
--- a/sdks/typescript/src/agents/index.ts
+++ b/sdks/typescript/src/agents/index.ts
@@ -12,6 +12,14 @@ export type {
CreateAgentParams, UpdateAgentParams, Page,
SlackManifest, SlackConnection, ConnectSlackParams,
} from "./agents.js";
+export {
+ Deployments, Revisions, Activations, Skills, DeploymentSourceResource,
+} from "./deployments.js";
+export type {
+ DeployInput, InlineDeployInput, GithubDeployInput, InlineSkillFile, CreateDeploymentParams,
+ Deployment, Revision, RevisionFile, Activation, AgentSkills, SkillSummary,
+ DeploymentSource, LinkParams, LinkResult, SkillZip,
+} from "./deployments.js";
export { Repos, GitHub, GitHubApps, GitHubInstallations } from "./repos.js";
export type {
CreateRepoParams, UpdateRepoParams, Repo,
diff --git a/sdks/typescript/src/agents/sessions.ts b/sdks/typescript/src/agents/sessions.ts
index 4fe441c8..10ccd7f2 100644
--- a/sdks/typescript/src/agents/sessions.ts
+++ b/sdks/typescript/src/agents/sessions.ts
@@ -8,6 +8,11 @@ export type Envelope = { text?: string; [k: string]: unknown };
export interface CreateSessionParams {
agent: string;
input: string | Envelope;
+ /**
+ * Pin a specific revision (number or `rev_…` id) instead of the agent's active one — e.g. to
+ * test a staged revision before promoting it. Defaults to the active revision.
+ */
+ revision?: number | string;
/** get-or-create idempotency/routing key — one session per key. */
key?: string;
webhook?: string;
diff --git a/sdks/typescript/src/agents/types.ts b/sdks/typescript/src/agents/types.ts
index 20445ffb..d1d9ab85 100644
--- a/sdks/typescript/src/agents/types.ts
+++ b/sdks/typescript/src/agents/types.ts
@@ -35,6 +35,8 @@ export interface Agent {
model: string;
runtime: Runtime;
revision?: number;
+ /** The agent's active revision (what new sessions run); `prompt`/`model` are served from it. */
+ activeRevision?: { id: string; number: number; digest: string } | null;
credentialId?: CredentialRef | null;
limits?: Limits;
createdAt?: string;
diff --git a/web/src/App.tsx b/web/src/App.tsx
index d878b3f8..4a1570a9 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -32,6 +32,7 @@ export default function App() {
{/* Agent plane */}
<Route path="agents" element={<Agents />} />
<Route path="agents/:agentId" element={<AgentDetail />} />
+ <Route path="agents/:agentId/:tab" element={<AgentDetail />} />
<Route path="credentials" element={<Credentials />} />
<Route path="sessions" element={<Sessions />} />
<Route path="sessions/:sessionId" element={<SessionDetail />} />
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index d1bc241b..82346842 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -81,6 +81,17 @@ function errorMessage(body: unknown, status: number): string {
return `Request failed: ${status}`
}
+/** An error carrying the HTTP status, so callers can branch (e.g. 404 = not-found vs a real failure). */
+export class ApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message)
+ this.name = 'ApiError'
+ }
+}
+
export async function apiFetch<T>(
path: string,
options: RequestInit = {},
@@ -107,12 +118,12 @@ export async function apiFetch<T>(
if (res.status === 401) {
// Don't auto-redirect — let ProtectedRoute handle auth flow.
// This prevents a redirect loop on the login page.
- throw new Error('Unauthorized')
+ throw new ApiError('Unauthorized', 401)
}
if (!res.ok) {
const body: unknown = await res.json().catch(() => ({}))
- throw new Error(errorMessage(body, res.status))
+ throw new ApiError(errorMessage(body, res.status), res.status)
}
if (res.status === 204) {
@@ -472,6 +483,34 @@ export const putAgentSkills = (agentId: string, zip: File | Blob) =>
export const deleteAgentSkills = (agentId: string) =>
apiFetch(`/v3/agents/${agentId}/skills`, { method: 'DELETE' }, S.DeployResultSchema)
+// The OC GitHub App (deploy) install-state + pickable repos — org-scoped admin read.
+export const getDeployApp = () => apiFetch('/v3/github/deploy-app', {}, S.DeployAppSchema)
+
+// Deployment source — link an agent to a repo dir for push-to-deploy (deploy-from-github).
+export const getDeploymentSource = (agentId: string) =>
+ apiFetch(`/v3/agents/${agentId}/deployment-source`, {}, S.DeploymentSourceResponseSchema)
+
+export const linkDeploymentSource = (
+ agentId: string,
+ body: { repo: string; path: string; production_ref?: string; deploy_now?: boolean },
+) =>
+ apiFetch(
+ `/v3/agents/${agentId}/deployment-source`,
+ { method: 'POST', body: JSON.stringify(body) },
+ S.LinkResultSchema,
+ )
+
+export const unlinkDeploymentSource = (agentId: string) =>
+ apiFetch<void>(`/v3/agents/${agentId}/deployment-source`, { method: 'DELETE' })
+
+// Deploy the linked repo's current production-branch HEAD now (no git push needed).
+// Returns { deployment } — fire-and-refetch, so we don't validate the body.
+export const deployFromGithub = (agentId: string) =>
+ apiFetch<{ deployment?: { id: string; state: string } }>(
+ `/v3/agents/${agentId}/deployments`,
+ { method: 'POST', body: JSON.stringify({ input: { type: 'github' } }) },
+ )
+
// Slack — an agent's BYO Slack app (1 app ⟷ 1 agent ⟷ 1 workspace). Two-step
// connect: START (manifest) returns the app manifest + guided steps; COMPLETE
// posts the three pasted values back. No secrets are ever returned.
diff --git a/web/src/api/mock.ts b/web/src/api/mock.ts
index 6e38a257..607b80b9 100644
--- a/web/src/api/mock.ts
+++ b/web/src/api/mock.ts
@@ -474,6 +474,128 @@ const agents = [
},
]
+// ── Deploy from GitHub (admin) ───────────────────────────────────────────────
+// The AgentDeploySource panel renders one of three states off two endpoints
+// (GET /v3/github/deploy-app + GET …/deployment-source). The backend can't
+// produce these locally yet (no OC-App install record), so flip DEPLOY_PREVIEW
+// to eyeball each state with no backend:
+// 'not_installed' → the "Install GitHub App" CTA
+// 'installed' → the repo picker (App installed, this agent not yet linked)
+// 'connected' → a linked agent showing live status + Disconnect
+const DEPLOY_PREVIEW = 'installed' as
+ | 'not_installed'
+ | 'installed'
+ | 'connected'
+
+const deployAppInstalled = {
+ installed: true,
+ install_url: 'https://github.com/apps/opencomputerdev/installations/new',
+ configure_url:
+ 'https://github.com/apps/opencomputerdev/installations/select_target',
+ account: 'acme',
+ repository_selection: 'selected' as const,
+ repositories: [
+ { full_name: 'acme/agents', default_branch: 'main', private: true },
+ { full_name: 'acme/support-bot', default_branch: 'main', private: false },
+ { full_name: 'acme/infra', default_branch: 'production', private: true },
+ ],
+}
+const deployAppNotInstalled = {
+ installed: false,
+ install_url: 'https://github.com/apps/opencomputerdev/installations/new',
+ configure_url: null,
+ account: null,
+ repository_selection: null,
+ repositories: [],
+}
+const deployApp =
+ DEPLOY_PREVIEW === 'not_installed'
+ ? deployAppNotInstalled
+ : deployAppInstalled
+
+// The linked source for the 'connected' preview (echoed for any agent id).
+const deploymentSource = {
+ agent_id: 'agt_3kf9xz',
+ repo_id: 'repo_acme_agents',
+ path: 'agents/pr-reviewer',
+ production_ref: 'main',
+ status: 'active',
+ latest_seen_sha: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0',
+ active_deployed_sha: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0',
+ full_name: 'acme/agents',
+}
+
+// Revisions / deploys / skills for the agent Overview + Deployments tab.
+const agentRevisions = [
+ {
+ id: 'rev_3',
+ number: 3,
+ digest: 'sha256:c0ffee0011223344',
+ created_at: at(0, 1),
+ active: true,
+ sha: '4a3f654010a5c16a101a6f0b3bf7aec1d3839d4f',
+ ref: 'main',
+ },
+ {
+ id: 'rev_2',
+ number: 2,
+ digest: 'sha256:deadbeef55667788',
+ created_at: at(0, 3),
+ active: false,
+ sha: null,
+ ref: null,
+ },
+ {
+ id: 'rev_1',
+ number: 1,
+ digest: 'sha256:0123456789abcdef',
+ created_at: at(2),
+ active: false,
+ sha: null,
+ ref: null,
+ },
+]
+const agentDeploys = [
+ {
+ id: 'dep_3',
+ state: 'ready',
+ result: 'created',
+ source: { via: 'repo', git_sha: '4a3f654010a5c16a' },
+ actor: null,
+ revision_id: 'rev_3',
+ created_at: at(0, 1),
+ },
+ {
+ id: 'dep_2',
+ state: 'ready',
+ result: 'created',
+ source: { via: 'api' },
+ actor: null,
+ revision_id: 'rev_2',
+ created_at: at(0, 3),
+ },
+ {
+ id: 'dep_1',
+ state: 'failed',
+ result: 'failed',
+ source: { via: 'repo', git_sha: 'badc0ffee1234567' },
+ actor: null,
+ revision_id: null,
+ created_at: at(1),
+ },
+]
+const agentSkills = {
+ revision: { id: 'rev_3', number: 3, digest: 'sha256:c0ffee0011223344' },
+ skill_bundle_digest: 'sha256:c0ffee0011223344',
+ skills: [
+ {
+ name: 'hello',
+ description: 'A trivial example skill.',
+ files: [{ path: 'hello/SKILL.md', mode: 33188, size: 240 }],
+ },
+ ],
+}
+
// A connected Slack app for the first agent (the AgentDetail Slack panel).
const slackConnection = {
id: 'sla_5p6q7r',
@@ -711,6 +833,10 @@ const sandboxWebhookDeliveries = [
type Handler = () => unknown
+// A handler may return NOT_FOUND to mimic a 404 (mockFetch throws, like a real
+// missing resource) — used for an agent with no deployment-source link.
+const NOT_FOUND = Symbol('not_found')
+
// Ordered most-specific first. Matched against the path (without /api/dashboard).
const ROUTES: Array<[RegExp, Handler]> = [
[/^\/me$/, () => me],
@@ -737,6 +863,15 @@ const ROUTES: Array<[RegExp, Handler]> = [
[/^\/agents$/, () => []],
// Durable Agent Sessions — lists return the { data: [...] } envelope.
[/^\/v3\/agents\/[^/]+\/slack$/, () => slackConnection],
+ [/^\/v3\/github\/deploy-app$/, () => deployApp],
+ [
+ /^\/v3\/agents\/[^/]+\/deployment-source$/,
+ () =>
+ DEPLOY_PREVIEW === 'connected' ? { source: deploymentSource } : NOT_FOUND,
+ ],
+ [/^\/v3\/agents\/[^/]+\/deploys$/, () => ({ data: agentDeploys })],
+ [/^\/v3\/agents\/[^/]+\/revisions$/, () => ({ data: agentRevisions })],
+ [/^\/v3\/agents\/[^/]+\/skills$/, () => agentSkills],
[/^\/v3\/agents\/[^/]+$/, () => agents[0]],
[/^\/v3\/agents$/, () => ({ data: agents })],
[/^\/v3\/credentials$/, () => ({ data: credentials })],
@@ -775,7 +910,11 @@ export function mockFetch<T>(path: string, options: RequestInit = {}): T {
return {} as T
}
for (const [re, handler] of ROUTES) {
- if (re.test(path)) return handler() as T
+ if (re.test(path)) {
+ const out = handler()
+ if (out === NOT_FOUND) throw new Error('Not found') // mimic a 404
+ return out as T
+ }
}
// Unknown GET: empty list is the safe default for the list-heavy screens.
return [] as T
diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.ts
index 1efd3e7d..05d8e479 100644
--- a/web/src/api/schemas.ts
+++ b/web/src/api/schemas.ts
@@ -353,6 +353,8 @@ export const AgentRevisionSchema = z.object({
digest: z.string(),
created_at: z.string(),
active: z.boolean(),
+ sha: z.string().nullish(), // commit that produced it (null for dashboard/inline revisions)
+ ref: z.string().nullish(), // branch the commit came from
})
export const AgentRevisionListSchema = z.object({
data: z.array(AgentRevisionSchema),
@@ -400,10 +402,50 @@ export const DeployResultSchema = z.object({
state: z.string(),
result: z.string().nullish(),
revision: z
- .object({ id: z.string(), number: z.number(), digest: z.string(), active: z.boolean() })
+ .object({
+ id: z.string(),
+ number: z.number(),
+ digest: z.string(),
+ active: z.boolean(),
+ })
.nullish(),
})
+// Deployment source — the agent ⟷ repo dir bind for push-to-deploy (deploy-from-github).
+export const DeploymentSourceSchema = z.object({
+ agent_id: z.string(),
+ repo_id: z.string(),
+ path: z.string(),
+ production_ref: z.string(),
+ status: z.string(), // active | path_missing | ref_missing | auth_required | repo_not_selected | app_suspended | error
+ latest_seen_sha: z.string().nullish(),
+ active_deployed_sha: z.string().nullish(),
+ full_name: z.string().nullish(), // "owner/repo" (joined from the repo row)
+})
+export const DeploymentSourceResponseSchema = z.object({
+ source: DeploymentSourceSchema,
+})
+
+// The OC GitHub App (deploy) install-state + pickable repos — admin/operator surface.
+export const DeployAppRepoSchema = z.object({
+ full_name: z.string(),
+ default_branch: z.string().nullish(),
+ private: z.boolean().nullish(),
+})
+export const DeployAppSchema = z.object({
+ installed: z.boolean(),
+ install_url: z.string().nullish(),
+ configure_url: z.string().nullish(),
+ account: z.string().nullish(),
+ repository_selection: z.enum(['all', 'selected']).nullish(),
+ repositories: z.array(DeployAppRepoSchema).default([]),
+})
+export const LinkResultSchema = z.object({
+ source: DeploymentSourceSchema,
+ deployment_id: z.string().nullish(),
+ deploy_error: z.object({ type: z.string(), message: z.string() }).nullish(),
+})
+
// Credentials — the reusable model-provider keys an agent/session resolves. The
// raw key is write-only; the API returns only metadata (last4 for display).
export const CredentialSchema = z.object({
diff --git a/web/src/components/agent-deploy-source.tsx b/web/src/components/agent-deploy-source.tsx
new file mode 100644
index 00000000..84afcb3e
--- /dev/null
+++ b/web/src/components/agent-deploy-source.tsx
@@ -0,0 +1,295 @@
+import { useEffect, useRef, useState } from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { Unplug, ExternalLink, RotateCw } from 'lucide-react'
+import { notifyError, notifySuccess } from '@/lib/errors'
+import {
+ ApiError,
+ getDeployApp,
+ getDeploymentSource,
+ linkDeploymentSource,
+ unlinkDeploymentSource,
+} from '@/api/client'
+import { Panel, PanelContent } from '@/components/panel'
+import { Button } from '@/components/ui/button'
+import { Input, Select } from '@/components/form'
+
+// GitHub mark (lucide's brand `Github` icon is deprecated/unexported — inline the SVG).
+function GithubMark({ className }: { className?: string }) {
+ return (
+ <svg viewBox="0 0 16 16" fill="currentColor" className={className} aria-hidden="true">
+ <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" />
+ </svg>
+ )
+}
+
+/**
+ * Source card (Overview right rail) — minimal. Connect a GitHub repo as the agent's source:
+ * not installed → a single Connect (install) button; installed → an editable repo / directory /
+ * branch picker (pre-filled when already linked) + a quiet Disconnect + an "Add more repos" link.
+ * Pushes to the branch create new revisions; re-applying the picker (Update) pulls HEAD into one.
+ * No card title, no nested borders — just the lightweight controls that matter.
+ */
+export function AgentDeploySource({
+ agentId,
+ autoFocusPicker = false,
+}: {
+ agentId: string
+ autoFocusPicker?: boolean
+}) {
+ const queryClient = useQueryClient()
+ const pickerRef = useRef<HTMLDivElement>(null)
+ const [repo, setRepo] = useState('')
+ const [path, setPath] = useState('')
+ const [branch, setBranch] = useState('main')
+ // "You just connected" is a transient onboarding moment — only true when the App flips to
+ // installed *within this session* (i.e. the user returned from the install tab). NOT set on a
+ // fresh load of an already-installed agent, and cleared on Disconnect — so the "pick a repo"
+ // nudge never lingers on unlinked/inline-only agents or reappears after an explicit disconnect.
+ const [justConnected, setJustConnected] = useState(false)
+
+ const { data: app, isLoading: appLoading } = useQuery({
+ queryKey: ['deploy-app'],
+ queryFn: getDeployApp,
+ // The App is installed in another tab; refetch whenever the user returns so the
+ // card flips to the repo picker immediately (staleTime would otherwise hide it).
+ refetchOnWindowFocus: 'always',
+ })
+ const {
+ data: source,
+ isLoading: srcLoading,
+ isError: srcError,
+ refetch: refetchSource,
+ } = useQuery({
+ queryKey: ['agent-deploy-source', agentId],
+ queryFn: async () => {
+ try {
+ return (await getDeploymentSource(agentId)).source
+ } catch (e) {
+ if (e instanceof ApiError && e.status === 404) return null // not linked
+ throw e // a real failure (500/auth/proxy) must not masquerade as "not connected"
+ }
+ },
+ refetchOnWindowFocus: 'always',
+ })
+
+ // Detect the false→true install transition: latch "just connected" only if we saw the
+ // not-installed state earlier this session (so a fresh load of an already-installed agent
+ // doesn't look like a transition).
+ const seenNotInstalled = useRef(false)
+ useEffect(() => {
+ if (!app) return
+ if (!app.installed) seenNotInstalled.current = true
+ else if (seenNotInstalled.current) setJustConnected(true)
+ }, [app])
+
+ // Pre-fill the picker from the current link once, so "connected" is an editable picker.
+ const hydratedRef = useRef(false)
+ useEffect(() => {
+ if (source && !hydratedRef.current) {
+ hydratedRef.current = true
+ setRepo(source.full_name ?? '')
+ setPath(source.path ?? '')
+ setBranch(source.production_ref || 'main')
+ }
+ }, [source])
+
+ const invalidate = () => {
+ void queryClient.invalidateQueries({
+ queryKey: ['agent-deploy-source', agentId],
+ })
+ void queryClient.invalidateQueries({
+ queryKey: ['agent-revisions', agentId],
+ })
+ void queryClient.invalidateQueries({ queryKey: ['agent', agentId] })
+ }
+
+ const link = useMutation({
+ mutationFn: () =>
+ linkDeploymentSource(agentId, {
+ repo,
+ path: path.trim(),
+ production_ref: branch.trim() || 'main',
+ }),
+ onSuccess: (r) => {
+ invalidate()
+ if (r.deploy_error) {
+ notifyError(
+ `Connected, but the first revision couldn't be created (${r.deploy_error.message}).`,
+ new Error(r.deploy_error.type),
+ )
+ } else {
+ notifySuccess(
+ source
+ ? 'Updated — creating a revision from the latest commit.'
+ : 'Connected — creating the first revision.',
+ )
+ }
+ },
+ onError: (e) => notifyError("Couldn't connect the repo.", e),
+ })
+ const unlink = useMutation({
+ mutationFn: () => unlinkDeploymentSource(agentId),
+ onSuccess: () => {
+ invalidate()
+ hydratedRef.current = false
+ setJustConnected(false) // an explicit disconnect is not an onboarding moment
+ setRepo('')
+ setPath('')
+ setBranch('main')
+ notifySuccess('Disconnected. Existing revisions are unchanged.')
+ },
+ onError: (e) => notifyError("Couldn't disconnect.", e),
+ })
+
+ const pickRepo = (fullName: string) => {
+ setRepo(fullName)
+ const r = app?.repositories.find((x) => x.full_name === fullName)
+ if (r?.default_branch) setBranch(r.default_branch)
+ }
+
+ // Arrived via a setup CTA (?connect=github) → scroll the picker in + focus it (once).
+ const focusedRef = useRef(false)
+ useEffect(() => {
+ if (
+ autoFocusPicker &&
+ !focusedRef.current &&
+ app?.installed &&
+ pickerRef.current
+ ) {
+ focusedRef.current = true
+ pickerRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' })
+ pickerRef.current
+ .querySelector<HTMLElement>('button, [role="combobox"], input, select')
+ ?.focus()
+ }
+ }, [autoFocusPicker, app?.installed])
+
+ // Repo options — include the linked repo even if it's not in the installable list.
+ const repoOptions = (app?.repositories ?? []).map((r) => ({
+ value: r.full_name,
+ label: r.full_name,
+ }))
+ if (
+ source?.full_name &&
+ !repoOptions.some((o) => o.value === source.full_name)
+ ) {
+ repoOptions.unshift({ value: source.full_name, label: source.full_name })
+ }
+
+ return (
+ <Panel className="overflow-hidden">
+ <PanelContent className="space-y-3">
+ {srcLoading || appLoading ? (
+ <p className="text-muted-foreground text-xs">Loading…</p>
+ ) : srcError ? (
+ <div className="space-y-2">
+ <p className="text-xs text-red-600 dark:text-red-500">
+ Couldn’t load the repo connection.
+ </p>
+ <Button size="sm" variant="outline" onClick={() => void refetchSource()}>
+ Retry
+ </Button>
+ </div>
+ ) : !app?.installed ? (
+ <div className="space-y-3">
+ <Button size="sm" variant="outline" disabled={!app?.install_url} asChild>
+ <a href={app?.install_url ?? '#'} target="_blank" rel="noreferrer">
+ <GithubMark className="size-4" />
+ Connect repository
+ </a>
+ </Button>
+ <p className="text-muted-foreground text-xs">
+ Or use the CLI: <code className="font-mono">oc agent deploy</code>
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-3" ref={pickerRef}>
+ {justConnected && !source ? (
+ <p className="text-xs">
+ <span className="font-medium text-green-600 dark:text-green-500">
+ GitHub connected.
+ </span>{' '}
+ <span className="text-muted-foreground">
+ Last step — pick a repo to deploy from.
+ </span>
+ </p>
+ ) : null}
+ <Select
+ value={repo}
+ onValueChange={pickRepo}
+ placeholder={
+ repoOptions.length ? 'Select a repo' : 'No repos available'
+ }
+ disabled={repoOptions.length === 0}
+ options={repoOptions}
+ />
+ <div className="flex gap-2">
+ <Input
+ value={path}
+ onChange={(e) => setPath(e.target.value)}
+ placeholder="directory"
+ />
+ <Input
+ value={branch}
+ onChange={(e) => setBranch(e.target.value)}
+ placeholder="main"
+ className="max-w-28"
+ />
+ </div>
+ <div className="flex items-center gap-2">
+ {source ? (
+ <Button
+ size="sm"
+ variant="outline"
+ title="Redeploy — pull the latest commit into a new revision"
+ disabled={link.isPending || !repo}
+ onClick={() => link.mutate()}
+ >
+ <RotateCw
+ className={`size-4 ${link.isPending ? 'animate-spin' : ''}`}
+ />
+ </Button>
+ ) : (
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={link.isPending || !repo}
+ onClick={() => link.mutate()}
+ >
+ {link.isPending ? 'Deploying…' : 'Deploy'}
+ </Button>
+ )}
+ {source ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-muted-foreground hover:text-foreground"
+ disabled={unlink.isPending}
+ onClick={() => unlink.mutate()}
+ >
+ <Unplug className="size-4" />
+ Disconnect
+ </Button>
+ ) : null}
+ </div>
+ {app.configure_url ? (
+ <a
+ className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs"
+ href={app.configure_url}
+ target="_blank"
+ rel="noreferrer"
+ >
+ <ExternalLink className="size-3" />
+ Add more repos
+ </a>
+ ) : null}
+ <p className="text-muted-foreground text-xs">
+ Or use the CLI:{' '}
+ <code className="font-mono">oc agent deploy</code>
+ </p>
+ </div>
+ )}
+ </PanelContent>
+ </Panel>
+ )
+}
diff --git a/web/src/components/agent-revisions.tsx b/web/src/components/agent-revisions.tsx
index 3b5ec0d5..6e83dcb0 100644
--- a/web/src/components/agent-revisions.tsx
+++ b/web/src/components/agent-revisions.tsx
@@ -1,6 +1,6 @@
import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { History, RotateCcw, ArrowUp } from 'lucide-react'
+import { History, RotateCcw, ArrowUp, GitBranch } from 'lucide-react'
import { notifyError } from '@/lib/errors'
import {
getAgentRevisions,
@@ -42,14 +42,19 @@ export function AgentRevisions({ agentId }: { agentId: string }) {
// we don't need a second, near-duplicate table.
const createdVia = new Map<string, string>()
for (const d of deploys) {
- if (d.revision_id && d.result === 'created') createdVia.set(d.revision_id, sourceVia(d.source))
+ if (d.revision_id && d.result === 'created')
+ createdVia.set(d.revision_id, sourceVia(d.source))
}
const activateMutation = useMutation({
mutationFn: (rev: AgentRevision) => activateRevision(agentId, rev.number),
onSuccess: () => {
- void queryClient.invalidateQueries({ queryKey: ['agent-revisions', agentId] })
- void queryClient.invalidateQueries({ queryKey: ['agent-deploys', agentId] })
+ void queryClient.invalidateQueries({
+ queryKey: ['agent-revisions', agentId],
+ })
+ void queryClient.invalidateQueries({
+ queryKey: ['agent-deploys', agentId],
+ })
// prompt/model are sourced from the active revision → refresh the agent too.
void queryClient.invalidateQueries({ queryKey: ['agent', agentId] })
void queryClient.invalidateQueries({ queryKey: ['agents'] })
@@ -66,17 +71,26 @@ export function AgentRevisions({ agentId }: { agentId: string }) {
key: 'number',
header: 'Revision',
cell: (r) => (
- <span className="text-foreground font-mono text-[13px]">#{r.number}</span>
+ <span className="text-foreground font-mono text-[13px]">
+ #{r.number}
+ </span>
),
},
{
key: 'source',
header: 'Source',
- cell: (r) => (
- <span className="text-muted-foreground text-xs capitalize">
- {createdVia.get(r.id) ?? '—'}
- </span>
- ),
+ cell: (r) =>
+ r.sha ? (
+ <span className="text-muted-foreground inline-flex items-center gap-1 font-mono text-xs">
+ <GitBranch className="size-3 shrink-0" />
+ {r.ref ? `${r.ref} · ` : ''}
+ {r.sha.slice(0, 7)}
+ </span>
+ ) : (
+ <span className="text-muted-foreground text-xs capitalize">
+ {createdVia.get(r.id) ?? 'dashboard'}
+ </span>
+ ),
},
{
key: 'digest',
@@ -118,7 +132,8 @@ export function AgentRevisions({ agentId }: { agentId: string }) {
onClick={() => setPending(r)}
>
<Icon className="size-3.5 shrink-0" />
- <span className="max-w-0 overflow-hidden whitespace-nowrap opacity-0 transition-all duration-200 ease-out group-hover:ml-1.5 group-hover:max-w-[6rem] group-hover:opacity-100 motion-reduce:transition-none motion-reduce:group-hover:ml-1.5">
+ {/* Reserve the label's width always so the reveal-on-hover doesn't reflow the column. */}
+ <span className="ml-1.5 inline-block w-[4.25rem] text-left opacity-0 transition-opacity duration-150 ease-out group-hover:opacity-100 motion-reduce:transition-none">
{label}
</span>
</Button>
@@ -132,7 +147,8 @@ export function AgentRevisions({ agentId }: { agentId: string }) {
<PanelHeader>
<PanelTitle>Revisions</PanelTitle>
<span className="text-muted-foreground text-xs">
- Each deploy is an immutable revision. Rolling back re-points the active one.
+ Each deploy is an immutable revision. Rolling back re-points the
+ active one.
</span>
</PanelHeader>
diff --git a/web/src/components/agent-skills.tsx b/web/src/components/agent-skills.tsx
index c4fb92da..d054fdae 100644
--- a/web/src/components/agent-skills.tsx
+++ b/web/src/components/agent-skills.tsx
@@ -1,6 +1,6 @@
import { useRef } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { FileArchive, Upload } from 'lucide-react'
+import { Upload } from 'lucide-react'
import { notifyError, notifySuccess } from '@/lib/errors'
import { getAgentSkills, putAgentSkills, deleteAgentSkills } from '@/api/client'
import {
@@ -58,23 +58,15 @@ export function AgentSkills({ agentId }: { agentId: string }) {
<Panel className="overflow-hidden">
<PanelHeader>
<PanelTitle>Skills</PanelTitle>
- <span className="text-muted-foreground text-xs">
- Skill files the agent loads at run time.
- </span>
</PanelHeader>
- <PanelContent className="space-y-4">
+ <PanelContent className="space-y-3">
{!isLoading && skills.length === 0 ? (
- <div className="flex items-center justify-between gap-6 rounded-md border border-dashed px-5 py-6">
- <div className="space-y-1.5">
- <div className="text-foreground flex items-center gap-2 text-sm font-medium">
- <FileArchive className="text-muted-foreground size-5" />
- No skills yet
- </div>
- <p className="text-muted-foreground text-xs">
- A skill is a folder with a SKILL.md — upload a .zip like this:
- </p>
- </div>
- <pre className="text-muted-foreground/70 shrink-0 text-left font-mono text-xs leading-relaxed">
+ <div className="flex items-center justify-between gap-6 rounded-md border border-dashed px-4 py-3">
+ <p className="text-muted-foreground text-xs">
+ No skills yet. A skill is a folder with a SKILL.md — upload a .zip
+ like this:
+ </p>
+ <pre className="text-muted-foreground/70 shrink-0 text-left font-mono text-xs leading-snug">
{`skills/
├─ triage/
│ └─ SKILL.md
@@ -84,9 +76,9 @@ export function AgentSkills({ agentId }: { agentId: string }) {
</pre>
</div>
) : (
- <ul className="divide-border divide-y rounded-md border">
+ <ul className="divide-border divide-y">
{skills.map((s) => (
- <li key={s.name} className="px-3 py-2.5">
+ <li key={s.name} className="py-2 first:pt-0">
<div className="flex items-baseline justify-between gap-3">
<span className="text-foreground font-mono text-[13px]">{s.name}</span>
<span className="text-muted-foreground shrink-0 text-xs">
@@ -96,15 +88,13 @@ export function AgentSkills({ agentId }: { agentId: string }) {
</div>
{s.description ? (
<p className="text-muted-foreground mt-0.5 text-xs">{s.description}</p>
- ) : (
- <p className="text-muted-foreground/70 mt-0.5 text-xs italic">no description</p>
- )}
+ ) : null}
</li>
))}
</ul>
)}
- <div className="flex items-center gap-3">
+ <div className="flex items-center gap-2">
<input
ref={inputRef}
type="file"
@@ -116,30 +106,21 @@ export function AgentSkills({ agentId }: { agentId: string }) {
e.target.value = '' // allow re-selecting the same file
}}
/>
- <p className="text-muted-foreground text-xs">
- Deploys a new revision; prompt &amp; model unchanged.
- </p>
- <div className="ml-auto flex items-center gap-2">
- {skills.length > 0 ? (
- <Button
- variant="ghost"
- size="sm"
- className="text-muted-foreground hover:text-foreground"
- disabled={busy}
- onClick={() => remove.mutate()}
- >
- {remove.isPending ? 'Removing…' : 'Remove all'}
- </Button>
- ) : null}
- <Button size="sm" disabled={busy} onClick={() => inputRef.current?.click()}>
- <Upload className="size-4" />
- {upload.isPending
- ? 'Uploading…'
- : skills.length
- ? 'Replace skills (.zip)'
- : 'Upload skills (.zip)'}
+ {skills.length > 0 ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-muted-foreground hover:text-foreground"
+ disabled={busy}
+ onClick={() => remove.mutate()}
+ >
+ {remove.isPending ? 'Removing…' : 'Remove all'}
</Button>
- </div>
+ ) : null}
+ <Button size="sm" variant="outline" className="ml-auto" disabled={busy} onClick={() => inputRef.current?.click()}>
+ <Upload className="size-4" />
+ {upload.isPending ? 'Uploading…' : skills.length ? 'Replace .zip' : 'Upload .zip'}
+ </Button>
</div>
</PanelContent>
</Panel>
diff --git a/web/src/components/slack-connect.tsx b/web/src/components/slack-connect.tsx
index 9ca7da5f..79ecc1ca 100644
--- a/web/src/components/slack-connect.tsx
+++ b/web/src/components/slack-connect.tsx
@@ -1,4 +1,4 @@
-import { useState } from 'react'
+import { useEffect, useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Check, Copy, ExternalLink } from 'lucide-react'
import { notifyError } from '@/lib/errors'
@@ -9,12 +9,7 @@ import {
disconnectSlack,
} from '@/api/client'
import type { SlackManifestResponse } from '@/api/schemas'
-import {
- Panel,
- PanelContent,
- PanelHeader,
- PanelTitle,
-} from '@/components/panel'
+import { Panel, PanelContent } from '@/components/panel'
import { Button } from '@/components/ui/button'
import {
Dialog,
@@ -25,7 +20,6 @@ import {
DialogTitle,
} from '@/components/ui/dialog'
import { Field, Input } from '@/components/form'
-import { StatusBadge } from '@/components/status-badge'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { useTransientFlag } from '@/lib/use-transient-flag'
import { cn } from '@/lib/utils'
@@ -79,12 +73,24 @@ function WizardSteps({ current }: { current: number }) {
)
}
+// Compact one-line progress for the card view (closed wizard): "Step N of 4 · label".
+function CompactSteps({ current }: { current: number }) {
+ const n = Math.min(current + 1, WIZARD_STEPS.length)
+ return (
+ <p className="text-muted-foreground text-xs">
+ Step {n} of {WIZARD_STEPS.length} · {WIZARD_STEPS[current] ?? 'Done'}
+ </p>
+ )
+}
+
export function SlackConnect({
agentId,
agentName,
+ autoOpen = false,
}: {
agentId: string
agentName: string
+ autoOpen?: boolean
}) {
const queryClient = useQueryClient()
const invalidate = () =>
@@ -107,7 +113,6 @@ export function SlackConnect({
const [botToken, setBotToken] = useState('')
const [signingSecret, setSigningSecret] = useState('')
const [confirmDisconnect, setConfirmDisconnect] = useState(false)
- const [confirmReconnect, setConfirmReconnect] = useState(false)
const [copied, markCopied] = useTransientFlag(1500)
const resetWizard = () => {
@@ -179,77 +184,66 @@ export function SlackConnect({
const stepIndex =
step === 'create' ? 0 : step === 'details' ? 1 : step === 'install' ? 2 : 3
+ // Arrived via a setup CTA (?connect=slack) → open the wizard once, unless
+ // already connected. Latched so a re-render / param-clear doesn't re-trigger.
+ const autoOpenedRef = useRef(false)
+ useEffect(() => {
+ if (autoOpen && !autoOpenedRef.current && !isLoading && !isActive) {
+ autoOpenedRef.current = true
+ beginConnect()
+ }
+ // beginConnect is a stable-enough closure; the ref guards single-fire.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [autoOpen, isLoading, isActive])
+
return (
<Panel className="overflow-hidden">
- <PanelHeader>
- <PanelTitle>Slack</PanelTitle>
- {conn ? <StatusBadge status={status ?? 'pending'} /> : null}
- </PanelHeader>
- <PanelContent>
+ <PanelContent className="space-y-3">
+ <div className="text-muted-foreground text-xs font-medium">Slack</div>
{isLoading ? (
- <p className="text-muted-foreground text-sm">Checking Slack…</p>
+ <p className="text-muted-foreground text-xs">Checking…</p>
) : isError ? (
- <p className="text-muted-foreground text-sm">
+ <p className="text-muted-foreground text-xs">
Slack status unavailable.
</p>
) : isActive ? (
- <div className="space-y-3">
- <p className="text-sm">
+ <div className="flex items-center justify-between gap-2">
+ <span className="truncate text-sm">
+ <span className="text-green-600 dark:text-green-500">●</span>{' '}
<span className="text-foreground font-medium">
@{conn?.handle}
- </span>{' '}
- is connected{workspace ? ` to ${workspace}` : ''}.
- </p>
- <p className="text-muted-foreground text-sm">
- Invite the bot to a channel, then <strong>@-mention</strong> it to
- start or steer a session.
- </p>
- <div className="flex gap-2">
- <Button
- variant="outline"
- size="sm"
- onClick={() => setConfirmReconnect(true)}
- >
- Reconnect
- </Button>
- <Button
- variant="outline"
- size="sm"
- onClick={() => setConfirmDisconnect(true)}
- >
- Disconnect
- </Button>
- </div>
+ </span>
+ {workspace ? (
+ <span className="text-muted-foreground"> · {workspace}</span>
+ ) : null}
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-muted-foreground hover:text-foreground shrink-0"
+ onClick={() => setConfirmDisconnect(true)}
+ >
+ Disconnect
+ </Button>
</div>
) : isErrorStatus ? (
- <div className="space-y-3">
- <p className="text-status-error text-sm">
- Slack reported a connection error (the token may have been
- revoked). Reconnect to fix it.
- </p>
- <div className="flex gap-2">
- <Button size="sm" onClick={() => beginConnect()}>
- Reconnect
- </Button>
- <Button
- variant="outline"
- size="sm"
- onClick={() => setConfirmDisconnect(true)}
- >
- Disconnect
- </Button>
- </div>
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-status-error text-sm">● Connection error</span>
+ <Button variant="outline" size="sm" onClick={() => beginConnect()}>
+ Reconnect
+ </Button>
</div>
- ) : (
- <div className="space-y-3">
- <p className="text-muted-foreground text-sm">
- Give this agent its own Slack handle. Members @-mention it to
- start and steer sessions from a channel.
- </p>
- <Button size="sm" onClick={() => beginConnect()}>
- {isPending ? 'Continue Slack setup' : 'Connect Slack'}
+ ) : isPending ? (
+ <div className="space-y-2">
+ <CompactSteps current={stepIndex} />
+ <Button variant="outline" size="sm" onClick={() => beginConnect()}>
+ Continue setup
</Button>
</div>
+ ) : (
+ <Button variant="outline" size="sm" onClick={() => beginConnect()}>
+ Connect Slack
+ </Button>
)}
</PanelContent>
@@ -476,17 +470,6 @@ export function SlackConnect({
onConfirm={() => disconnectMutation.mutate()}
/>
- <ConfirmDialog
- open={confirmReconnect}
- onOpenChange={setConfirmReconnect}
- title="Reconnect Slack?"
- description="This replaces the current Slack app. The agent stops responding in Slack until you finish setting up the new one."
- confirmLabel="Reconnect"
- onConfirm={() => {
- setConfirmReconnect(false)
- beginConnect(true)
- }}
- />
</Panel>
)
}
diff --git a/web/src/pages/AgentDetail.tsx b/web/src/pages/AgentDetail.tsx
index 422bcca3..0dfb9992 100644
--- a/web/src/pages/AgentDetail.tsx
+++ b/web/src/pages/AgentDetail.tsx
@@ -1,7 +1,7 @@
import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Link, useNavigate, useParams } from 'react-router-dom'
-import { ArrowLeft, MessagesSquare, Send } from 'lucide-react'
+import { ArrowLeft, MessagesSquare, Send, GitBranch } from 'lucide-react'
import { notifyError } from '@/lib/errors'
import {
getAgent,
@@ -10,10 +10,10 @@ import {
createSession,
getCredentials,
createCredential,
+ getDeploymentSource,
type Agent,
} from '@/api/client'
import type { Session } from '@/api/schemas'
-import { PageHeader } from '@/components/page-header'
import {
Panel,
PanelContent,
@@ -29,19 +29,41 @@ import { ResourceTable, type Column } from '@/components/resource-table'
import { Skeleton } from '@/components/ui/skeleton'
import { SlackConnect } from '@/components/slack-connect'
import { AgentSkills } from '@/components/agent-skills'
+import { AgentDeploySource } from '@/components/agent-deploy-source'
import { AgentRevisions } from '@/components/agent-revisions'
+import { ApiHint, type ApiRef } from '@/components/api-hint'
import { getRuntime } from '@/lib/runtimes'
-// Sentinels for the non-credential choices in the picker. The model list +
-// credential provider come from the agent's runtime (see @/lib/runtimes).
+const DOCS = 'https://docs.opencomputer.dev/agent-sessions'
+
+// Sentinels for the non-credential choices in the picker.
const ORG_DEFAULT = '__default__' // no pinned credential → org default resolves
const NEW_CRED = '__new__' // create one inline
const MANAGED = 'managed' // run via OpenComputer, no BYO key (token-billing §6.6)
+type Tab = 'overview' | 'revisions' | 'sessions' | 'settings'
+
export default function AgentDetail() {
- const { agentId = '' } = useParams()
+ const { agentId = '', tab } = useParams()
const navigate = useNavigate()
const queryClient = useQueryClient()
+ const active: Tab =
+ tab === 'revisions'
+ ? 'revisions'
+ : tab === 'sessions'
+ ? 'sessions'
+ : tab === 'settings'
+ ? 'settings'
+ : 'overview'
+
+ // Each tab is a thin control panel over one API resource — surface the call it drives
+ // (REST + SDK), same as the other pages, so the dashboard reads as programmable.
+ const tabApi: Record<Tab, ApiRef> = {
+ overview: { method: 'GET', path: `/v3/agents/${agentId}`, sdk: 'oc.agents.get(id)', docs: `${DOCS}/agents` },
+ revisions: { method: 'GET', path: `/v3/agents/${agentId}/revisions`, sdk: 'oc.agents.revisions.list(id)', docs: `${DOCS}/revisions` },
+ sessions: { method: 'POST', path: '/v3/sessions', sdk: 'oc.sessions.create({ agent })', docs: `${DOCS}/sessions` },
+ settings: { method: 'PATCH', path: `/v3/agents/${agentId}`, sdk: 'oc.agents.update(id, …)', docs: `${DOCS}/agents` },
+ }
const {
data: agent,
@@ -53,20 +75,30 @@ export default function AgentDetail() {
enabled: !!agentId,
})
- // This agent's sessions — filtered server-side (not a client slice of an unfiltered
- // first page, which would drop older sessions once the org is busy).
+ // This agent's sessions — filtered server-side.
const { data: sessions = [], isLoading: loadingSessions } = useQuery({
queryKey: ['sessions', { agent: agentId }],
queryFn: () => getSessions({ agent: agentId }),
})
+ // The deployment-source link (shared cache key with the GitHub card). null = not linked.
+ // When linked, the repo is the source of truth, so the inline editor goes read-only.
+ const { data: source } = useQuery({
+ queryKey: ['agent-deploy-source', agentId],
+ queryFn: async () => {
+ try {
+ return (await getDeploymentSource(agentId)).source
+ } catch {
+ return null
+ }
+ },
+ })
+
// Credentials for the switch picker + to label the current one.
const { data: credentials } = useQuery({
queryKey: ['credentials'],
queryFn: getCredentials,
})
- // Model list + credential provider follow the agent's runtime (immutable after
- // create): claude→anthropic, codex→openai. Falls back to claude while loading.
const rt = getRuntime(agent?.runtime)
const providerCreds = (credentials ?? []).filter(
(c) => c.provider === rt.provider,
@@ -79,11 +111,14 @@ export default function AgentDetail() {
}`
}
- // ── Start a session (inline composer) ─────────────────────────────────────
+ // ── Start a session (used by the Sessions tab composer) ────────────────────
const [task, setTask] = useState('')
const startMutation = useMutation({
mutationFn: () =>
- createSession({ agent: agentId, input: task.trim() }, crypto.randomUUID()),
+ createSession(
+ { agent: agentId, input: task.trim() },
+ crypto.randomUUID(),
+ ),
onSuccess: (session) => {
void queryClient.invalidateQueries({ queryKey: ['sessions'] })
void navigate(`/sessions/${session.id}`)
@@ -91,14 +126,13 @@ export default function AgentDetail() {
onError: (e) => notifyError("Couldn't start the session.", e),
})
- // ── Live config controls (no edit mode) ───────────────────────────────────
- // Dropdowns autosave on change (optimistic → no flicker); the prompt is a draft
- // with Save/Discard that enable only when it differs from what's saved.
+ // ── Live config controls ───────────────────────────────────────────────────
const settleAgent = () => {
void queryClient.invalidateQueries({ queryKey: ['agent', agentId] })
void queryClient.invalidateQueries({ queryKey: ['agents'] })
- // A prompt/model save creates a new revision → refresh the Revisions panel too.
- void queryClient.invalidateQueries({ queryKey: ['agent-revisions', agentId] })
+ void queryClient.invalidateQueries({
+ queryKey: ['agent-revisions', agentId],
+ })
void queryClient.invalidateQueries({ queryKey: ['agent-deploys', agentId] })
}
const optimistic = async (patch: Partial<Agent>) => {
@@ -131,7 +165,7 @@ export default function AgentDetail() {
rollback(prev)
notifyError("Couldn't update the prompt.", e)
},
- onSuccess: () => setPromptDraft(undefined), // re-sync to saved
+ onSuccess: () => setPromptDraft(undefined),
onSettled: settleAgent,
})
@@ -146,7 +180,6 @@ export default function AgentDetail() {
onSettled: settleAgent,
})
- // Create a new credential inline, then switch the agent to it.
const [credNew, setCredNew] = useState(false)
const [newCredName, setNewCredName] = useState('')
const [newCredKey, setNewCredKey] = useState('')
@@ -170,7 +203,6 @@ export default function AgentDetail() {
},
onError: (e) => notifyError("Couldn't add the credential.", e),
})
-
const credSaving = switchCredMutation.isPending || addCredMutation.isPending
// Derived control values.
@@ -183,14 +215,12 @@ export default function AgentDetail() {
const credSelectValue = credNew
? NEW_CRED
: (agent?.credential_id ?? ORG_DEFAULT)
- // Managed is always offered (every org carries a managed credential); it has no provider.
const credOptions = [
{ value: ORG_DEFAULT, label: 'Org default (no pinned credential)' },
{ value: MANAGED, label: 'Managed · no key needed' },
...providerCreds.map((c) => ({ value: c.id, label: credLabel(c.id) })),
{ value: NEW_CRED, label: '+ New credential…' },
]
- // ORG_DEFAULT → clear the pin (null); MANAGED → the "managed" sentinel; else a cred id.
const onCredChange = (v: string) => {
if (v === NEW_CRED) {
setCredNew(true)
@@ -200,48 +230,18 @@ export default function AgentDetail() {
switchCredMutation.mutate(v === ORG_DEFAULT ? null : v)
}
- const sessionColumns: Column<Session>[] = [
- {
- key: 'id',
- header: 'Session',
- cell: (s) => (
- <Link
- to={`/sessions/${s.id}`}
- className="text-foreground font-mono text-[13px] underline-offset-4 hover:underline"
- >
- {s.id}
- </Link>
- ),
- },
- {
- key: 'status',
- header: 'Status',
- cell: (s) => <StatusBadge status={s.status} />,
- },
- {
- key: 'created',
- header: 'Created',
- cell: (s) => (
- <span className="text-muted-foreground font-mono text-xs">
- {new Date(s.created_at).toLocaleString()}
- </span>
- ),
- },
- ]
-
- return (
- <div className="max-w-4xl">
- <Link
- to="/agents"
- className="text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1.5 text-sm"
- >
- <ArrowLeft className="size-4" />
- Agents
- </Link>
-
- {isLoading ? (
+ if (isLoading) {
+ return (
+ <div className="mx-auto max-w-5xl">
+ <BackLink />
<Skeleton className="h-40 w-full" />
- ) : isError || !agent ? (
+ </div>
+ )
+ }
+ if (isError || !agent) {
+ return (
+ <div className="mx-auto max-w-5xl">
+ <BackLink />
<EmptyState
icon={MessagesSquare}
title="Agent not found"
@@ -252,97 +252,246 @@ export default function AgentDetail() {
</Button>
}
/>
- ) : (
- <div className="space-y-6">
- <PageHeader
- title={agent.name}
- description="A reusable definition. Sessions pin a snapshot of it at create time."
- api={{
- method: 'GET',
- path: '/v3/agents/{id}',
- sdk: 'oc.agents.get()',
- docs: 'https://docs.opencomputer.dev/agent-sessions/agents',
- }}
+ </div>
+ )
+ }
+
+ const activeRev = agent.active_revision?.number ?? agent.revision ?? 1
+ const base = `/agents/${agent.id}`
+
+ return (
+ <div className="mx-auto max-w-5xl">
+ <BackLink />
+
+ {/* Sticky header: identity + status + primary action, with the tab bar. */}
+ <div className="bg-background sticky top-0 z-20 border-b">
+ <div className="flex flex-wrap items-start justify-between gap-3 pb-3">
+ <div className="min-w-0 space-y-1.5">
+ <h1 className="text-foreground truncate text-lg font-semibold">
+ {agent.name}
+ </h1>
+ <div className="text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
+ <span className="font-mono">{agent.id}</span>
+ <span className="capitalize">{agent.runtime}</span>
+ <span className="font-mono">rev #{activeRev}</span>
+ <SourceChip source={source ?? null} />
+ </div>
+ </div>
+ <Button asChild size="sm">
+ <Link to={`${base}/sessions`}>
+ <Send className="size-4" />
+ New session
+ </Link>
+ </Button>
+ </div>
+ <nav className="-mb-px flex gap-1">
+ <TabLink to={base} label="Overview" current={active === 'overview'} />
+ <TabLink
+ to={`${base}/revisions`}
+ label="Revisions"
+ current={active === 'revisions'}
+ />
+ <TabLink
+ to={`${base}/sessions`}
+ label="Sessions"
+ current={active === 'sessions'}
+ />
+ <TabLink
+ to={`${base}/settings`}
+ label="Settings"
+ current={active === 'settings'}
/>
+ </nav>
+ </div>
- {/* Configuration — live controls; changes save in place. */}
- <Panel className="space-y-5 p-5">
- <div className="text-muted-foreground grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5 text-xs">
- <span>Agent ID</span>
- <span className="text-foreground font-mono">{agent.id}</span>
- <span>Runtime</span>
- <span className="text-foreground capitalize">{agent.runtime}</span>
- <span>Active revision</span>
- <span className="text-foreground font-mono">
- #{agent.active_revision?.number ?? agent.revision ?? 1}
- </span>
- <span>Created</span>
- <span className="text-foreground">
- {new Date(agent.created_at).toLocaleString()}
- </span>
+ <div className="py-6">
+ <div className="mb-4">
+ <ApiHint {...tabApi[active]} />
+ </div>
+ {active === 'overview' && (
+ <div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
+ {/* Left: behavior (model/prompt) + skills — read-only when a repo drives the agent. */}
+ <div className="space-y-6">
+ <Panel>
+ <PanelContent className="space-y-5">
+ {source ? (
+ <div className="space-y-4">
+ <div className="border-border bg-panel-2 flex items-start gap-2 rounded-md border px-3 py-2.5 text-xs">
+ <GitBranch className="text-muted-foreground mt-0.5 size-3.5 shrink-0" />
+ <div className="space-y-0.5">
+ <p className="text-foreground">
+ Managed from a connected repo —{' '}
+ <span className="font-mono">
+ {source.full_name ?? source.path ?? 'repo'}
+ {source.full_name && source.path
+ ? `/${source.path}`
+ : ''}
+ @{source.production_ref}
+ </span>
+ </p>
+ <p className="text-muted-foreground">
+ The repo is the source of truth. Edit there and
+ push, or{' '}
+ <Link
+ className="underline underline-offset-4"
+ to={`${base}/revisions`}
+ >
+ browse revisions
+ </Link>
+ .
+ </p>
+ </div>
+ </div>
+ <ReadOnlyField label="Model" value={agent.model} mono />
+ <ReadOnlyField
+ label="System prompt"
+ value={savedPrompt || '—'}
+ pre
+ />
+ </div>
+ ) : (
+ <>
+ <Field label="Model" htmlFor="agent-model">
+ <div className="flex items-center gap-3">
+ <Select
+ id="agent-model"
+ value={agent.model}
+ onValueChange={(m) => modelMutation.mutate(m)}
+ options={modelOptions}
+ className="max-w-xs"
+ />
+ <Saving show={modelMutation.isPending} />
+ </div>
+ </Field>
+ <Field label="System prompt" htmlFor="agent-prompt">
+ <Textarea
+ id="agent-prompt"
+ value={promptValue}
+ onChange={(e) => setPromptDraft(e.target.value)}
+ placeholder="You are a meticulous code reviewer…"
+ className="min-h-32"
+ />
+ <div className="mt-2 flex items-center gap-3">
+ <p className="text-muted-foreground text-xs">
+ How the agent behaves. Saving bumps the agent's
+ revision.
+ </p>
+ <div className="ml-auto flex items-center gap-2">
+ <Saving show={promptMutation.isPending} />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={
+ !promptDirty || promptMutation.isPending
+ }
+ onClick={() => setPromptDraft(undefined)}
+ >
+ Discard
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={
+ !promptDirty ||
+ promptMutation.isPending ||
+ !promptValue.trim()
+ }
+ onClick={() =>
+ promptMutation.mutate(promptValue.trim())
+ }
+ >
+ Save prompt
+ </Button>
+ </div>
+ </div>
+ </Field>
+ </>
+ )}
+ </PanelContent>
+ </Panel>
+ <AgentSkills agentId={agent.id} />
</div>
+ {/* Right rail: connect-or-status for the agent's source + Slack. */}
+ <div className="space-y-4">
+ <AgentDeploySource agentId={agent.id} />
+ <SlackConnect agentId={agent.id} agentName={agent.name} />
+ </div>
+ </div>
+ )}
- <div className="space-y-5 border-t pt-5">
- {/* Model — autosaves */}
- <Field label="Model" htmlFor="agent-model">
- <div className="flex items-center gap-3">
- <Select
- id="agent-model"
- value={agent.model}
- onValueChange={(m) => modelMutation.mutate(m)}
- options={modelOptions}
- className="max-w-xs"
- />
- <Saving show={modelMutation.isPending} />
- </div>
- </Field>
+ {active === 'revisions' && <AgentRevisions agentId={agent.id} />}
- {/* Prompt — draft with Save/Discard */}
- <Field label="System prompt" htmlFor="agent-prompt">
- <Textarea
- id="agent-prompt"
- value={promptValue}
- onChange={(e) => setPromptDraft(e.target.value)}
- placeholder="You are a meticulous code reviewer…"
- className="min-h-32"
+ {active === 'sessions' && (
+ <Panel className="overflow-hidden">
+ <PanelHeader>
+ <PanelTitle>Sessions</PanelTitle>
+ <Link
+ to="/sessions"
+ className="text-muted-foreground hover:text-foreground text-xs underline-offset-4 hover:underline"
+ >
+ All sessions
+ </Link>
+ </PanelHeader>
+ <PanelContent className="border-b">
+ <form
+ className="space-y-2"
+ onSubmit={(e) => {
+ e.preventDefault()
+ if (task.trim()) startMutation.mutate()
+ }}
+ >
+ <ChatTextarea
+ value={task}
+ onChange={(e) => setTask(e.target.value)}
+ onSend={() => {
+ if (task.trim() && !startMutation.isPending)
+ startMutation.mutate()
+ }}
+ placeholder="Give this agent a task — it runs durably as a new session…"
+ className="min-h-20"
/>
- <div className="mt-2 flex items-center gap-3">
- <p className="text-muted-foreground text-xs">
- How the agent behaves. Saving bumps the agent's revision.
- </p>
- <div className="ml-auto flex items-center gap-2">
- <Saving show={promptMutation.isPending} />
- <Button
- type="button"
- variant="ghost"
- size="sm"
- disabled={!promptDirty || promptMutation.isPending}
- onClick={() => setPromptDraft(undefined)}
- >
- Discard
- </Button>
- <Button
- type="button"
- size="sm"
- disabled={
- !promptDirty ||
- promptMutation.isPending ||
- !promptValue.trim()
- }
- onClick={() => promptMutation.mutate(promptValue.trim())}
- >
- Save prompt
- </Button>
- </div>
+ <div className="flex justify-end">
+ <Button
+ type="submit"
+ size="sm"
+ title="Enter to start · Shift+Enter for newline"
+ disabled={startMutation.isPending || !task.trim()}
+ >
+ <Send className="size-4" />
+ {startMutation.isPending ? 'Starting…' : 'Start session'}
+ </Button>
</div>
- </Field>
+ </form>
+ </PanelContent>
+ <ResourceTable
+ columns={sessionColumns}
+ rows={sessions}
+ rowKey={(s) => s.id}
+ loading={loadingSessions}
+ empty={
+ <EmptyState
+ icon={MessagesSquare}
+ title="No sessions yet"
+ description="Start a session above to give this agent a durable task."
+ />
+ }
+ />
+ </Panel>
+ )}
- {/* Credential — switch (autosaves) or create new inline */}
- <Field
- label="Credential"
- htmlFor="agent-cred"
- description="Which credential this agent runs on. To change a key's value, rotate it on the Credentials page."
- >
+ {active === 'settings' && (
+ <div className="space-y-6">
+ {/* Credential — which key the agent runs on. */}
+ <Panel>
+ <PanelHeader>
+ <PanelTitle>Credential</PanelTitle>
+ <span className="text-muted-foreground text-xs">
+ Which key this agent runs on.
+ </span>
+ </PanelHeader>
+ <PanelContent className="space-y-3">
<div className="flex items-center gap-3">
<Select
id="agent-cred"
@@ -354,7 +503,7 @@ export default function AgentDetail() {
<Saving show={credSaving} />
</div>
{credNew ? (
- <div className="border-border bg-panel-2 mt-3 grid grid-cols-1 gap-3 rounded-md border p-3 sm:grid-cols-2">
+ <div className="border-border bg-panel-2 grid grid-cols-1 gap-3 rounded-md border p-3 sm:grid-cols-2">
<Field label="Credential name" htmlFor="new-cred-name">
<Input
id="new-cred-name"
@@ -391,6 +540,7 @@ export default function AgentDetail() {
</Button>
<Button
type="button"
+ variant="outline"
size="sm"
disabled={
!newCredKey.trim() || addCredMutation.isPending
@@ -402,86 +552,141 @@ export default function AgentDetail() {
</div>
</div>
) : null}
- </Field>
- </div>
- </Panel>
+ <p className="text-muted-foreground text-xs">
+ To change a key's value, rotate it on the Credentials page.
+ </p>
+ </PanelContent>
+ </Panel>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
- {/* Slack — kept above Sessions so it's visible without scrolling */}
- <SlackConnect agentId={agent.id} agentName={agent.name} />
+// ── Small building blocks ─────────────────────────────────────────────────────
- {/* Skills — current files + upload-a-zip to deploy a new revision */}
- <AgentSkills agentId={agent.id} />
+function BackLink() {
+ return (
+ <Link
+ to="/agents"
+ className="text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1.5 text-sm"
+ >
+ <ArrowLeft className="size-4" />
+ Agents
+ </Link>
+ )
+}
- {/* Revisions — deploy history + active pointer + rollback */}
- <AgentRevisions agentId={agent.id} />
+function TabLink({
+ to,
+ label,
+ current,
+}: {
+ to: string
+ label: string
+ current: boolean
+}) {
+ return (
+ <Link
+ to={to}
+ aria-current={current ? 'page' : undefined}
+ className={
+ 'border-b-2 px-3 py-2 text-sm transition-colors ' +
+ (current
+ ? 'border-foreground text-foreground font-medium'
+ : 'text-muted-foreground hover:text-foreground border-transparent')
+ }
+ >
+ {label}
+ </Link>
+ )
+}
- {/* Sessions */}
- <Panel className="overflow-hidden">
- <PanelHeader>
- <PanelTitle>Sessions</PanelTitle>
- <Link
- to="/sessions"
- className="text-muted-foreground hover:text-foreground text-xs underline-offset-4 hover:underline"
- >
- All sessions
- </Link>
- </PanelHeader>
+function SourceChip({
+ source,
+}: {
+ source: {
+ full_name?: string | null
+ path: string
+ production_ref: string
+ } | null
+}) {
+ if (!source) {
+ return null
+ }
+ const label = source.full_name ?? (source.path || 'repo')
+ return (
+ <span className="inline-flex items-center gap-1">
+ <GitBranch className="size-3" />
+ <span className="font-mono">
+ {label}@{source.production_ref}
+ </span>
+ </span>
+ )
+}
- <PanelContent className="border-b">
- <form
- className="space-y-2"
- onSubmit={(e) => {
- e.preventDefault()
- if (task.trim()) startMutation.mutate()
- }}
- >
- <ChatTextarea
- value={task}
- onChange={(e) => setTask(e.target.value)}
- onSend={() => {
- if (task.trim() && !startMutation.isPending) {
- startMutation.mutate()
- }
- }}
- placeholder="Give this agent a task — it runs durably as a new session…"
- className="min-h-20"
- />
- <div className="flex justify-end">
- <Button
- type="submit"
- size="sm"
- title="Enter to start · Shift+Enter for newline"
- disabled={startMutation.isPending || !task.trim()}
- >
- <Send className="size-4" />
- {startMutation.isPending ? 'Starting…' : 'Start session'}
- </Button>
- </div>
- </form>
- </PanelContent>
+function Saving({ show }: { show: boolean }) {
+ if (!show) return null
+ return <span className="text-muted-foreground text-xs">Saving…</span>
+}
- <ResourceTable
- columns={sessionColumns}
- rows={sessions}
- rowKey={(s) => s.id}
- loading={loadingSessions}
- empty={
- <EmptyState
- icon={MessagesSquare}
- title="No sessions yet"
- description="Start a session above to give this agent a durable task."
- />
- }
- />
- </Panel>
+function ReadOnlyField({
+ label,
+ value,
+ mono,
+ pre,
+}: {
+ label: string
+ value: string
+ mono?: boolean
+ pre?: boolean
+}) {
+ return (
+ <div className="space-y-1.5">
+ <div className="text-foreground text-sm font-medium">{label}</div>
+ {pre ? (
+ <pre className="text-muted-foreground max-h-40 overflow-auto text-xs whitespace-pre-wrap">
+ {value}
+ </pre>
+ ) : (
+ <div
+ className={
+ 'text-muted-foreground text-sm' + (mono ? ' font-mono' : '')
+ }
+ >
+ {value}
</div>
)}
</div>
)
}
-// Subtle inline "Saving…" shown while an autosave is in flight.
-function Saving({ show }: { show: boolean }) {
- if (!show) return null
- return <span className="text-muted-foreground text-xs">Saving…</span>
-}
+const sessionColumns: Column<Session>[] = [
+ {
+ key: 'id',
+ header: 'Session',
+ cell: (s) => (
+ <Link
+ to={`/sessions/${s.id}`}
+ className="text-foreground font-mono text-[13px] underline-offset-4 hover:underline"
+ >
+ {s.id}
+ </Link>
+ ),
+ },
+ {
+ key: 'status',
+ header: 'Status',
+ cell: (s) => <StatusBadge status={s.status} />,
+ },
+ {
+ key: 'created',
+ header: 'Created',
+ cell: (s) => (
+ <span className="text-muted-foreground font-mono text-xs">
+ {new Date(s.created_at).toLocaleString()}
+ </span>
+ ),
+ },
+]
diff --git a/web/src/pages/Agents.tsx b/web/src/pages/Agents.tsx
index 4500335a..f34ec482 100644
--- a/web/src/pages/Agents.tsx
+++ b/web/src/pages/Agents.tsx
@@ -39,6 +39,23 @@ const NEW_CRED = '__new__'
// Sent to the API as the reserved credential value "managed" (token-billing §6.6).
const MANAGED = 'managed'
+// Friendly starting defaults so "Create agent" works with a single click: a memorable
+// random name (adjective-noun) + a usable general-purpose prompt the user can keep or edit.
+const NAME_ADJECTIVES = [
+ 'swift', 'calm', 'bright', 'clever', 'bold', 'quiet', 'keen', 'brave',
+ 'nimble', 'sunny', 'lucid', 'witty', 'deft', 'mellow', 'crisp', 'vivid',
+]
+const NAME_NOUNS = [
+ 'otter', 'harbor', 'falcon', 'cedar', 'comet', 'delta', 'ember', 'fjord',
+ 'grove', 'heron', 'lynx', 'maple', 'nova', 'quartz', 'sparrow', 'willow',
+]
+function randomAgentName(): string {
+ const pick = (a: readonly string[]) => a[Math.floor(Math.random() * a.length)]
+ return `${pick(NAME_ADJECTIVES)}-${pick(NAME_NOUNS)}`
+}
+const DEFAULT_PROMPT =
+ 'You are a helpful AI assistant working in a sandboxed computer. Complete tasks end to end, use the tools available to you, and keep your answers clear and concise. When something is ambiguous, make a sensible assumption and say so.'
+
export default function Agents() {
const queryClient = useQueryClient()
const navigate = useNavigate()
@@ -87,6 +104,9 @@ export default function Agents() {
}
const openCreate = () => {
+ // Pre-fill so the form is submittable immediately — a fresh random name each open.
+ setName(randomAgentName())
+ setPrompt(DEFAULT_PROMPT)
setCredChoice(defaultCredFor(providerCreds))
setShowCreate(true)
}