Skip to content

An open-source, faster Devin alternative

TypeScript

feat(dashboard): add Agents page proxied to sessions-api

motatoescddc6bbb01bf
diff --git a/internal/api/dashboard_agents.go b/internal/api/dashboard_agents.go
new file mode 100644
index 00000000..1c95676a
--- /dev/null
+++ b/internal/api/dashboard_agents.go
@@ -0,0 +1,168 @@
+package api
+
+import (
+ "io"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/auth"
+)
+
+const (
+ // inboundJWTTTL is the lifetime of the bearer token sessions-api verifies
+ // on the proxied request. Sessions-api validates once at the route entry,
+ // so this only needs to cover the initial verification — keep it tight.
+ inboundJWTTTL = 90 * time.Second
+
+ // downstreamJWTTTL is the lifetime of the JWT sessions-api forwards on
+ // its OC API calls (sandbox creation, secret stores, exec.run via SDK).
+ // Has to outlast the longest single agent operation: managed-core boot
+ // involves checkpoint restore + entrypoint start + adapter waitReady,
+ // which can take several minutes. 10m is a comfortable upper bound.
+ downstreamJWTTTL = 10 * time.Minute
+
+ // downstreamHeaderName is the header sessions-api relays as a Bearer
+ // token on its calls back into OC's /api/sandboxes and /api/secret-stores.
+ // Sessions-api never mints; OC pre-mints both tokens here.
+ downstreamHeaderName = "X-OC-Downstream-Token"
+)
+
+// sessionsAPIBaseURL returns the upstream URL for the agents service. The env
+// var matches the CLI's SESSIONS_API_URL (cmd/oc/internal/config) so a single
+// value drives both surfaces.
+func sessionsAPIBaseURL() string {
+ if v := os.Getenv("SESSIONS_API_URL"); v != "" {
+ return strings.TrimRight(v, "/")
+ }
+ return "https://api.opencomputer.dev"
+}
+
+// dashboardAgentsProxy is a thin reverse proxy from /api/dashboard/agents/*
+// → ${SESSIONS_API_URL}/v1/agents/*. It runs after the WorkOS cookie
+// middleware, so the request is already authenticated as a real user.
+//
+// Auth handling:
+// - Mint two identity JWTs (sessions-api inbound, opencomputer-api downstream)
+// using the user's identity from the echo context.
+// - Strip Cookie / X-API-Key on the way out (sessions-api should rely on the
+// Bearer token, never the dashboard cookie).
+// - Set Authorization: Bearer <inbound-jwt>.
+// - Set X-OC-Downstream-Token: <downstream-jwt> for sessions-api to relay.
+//
+// The CLI continues to use sessions-api directly with X-API-Key — that path
+// is untouched.
+func (s *Server) dashboardAgentsProxy(c echo.Context) error {
+ if s.jwtIssuer == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "agents proxy unavailable: jwt issuer not configured",
+ })
+ }
+
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{
+ "error": "org context required",
+ })
+ }
+
+ in := auth.IdentityTokenInput{OrgID: orgID.String(), Audience: auth.AudSessionsAPI}
+ if userID := auth.GetUserID(c); userID != nil {
+ userStr := userID.String()
+ in.UserID = &userStr
+ }
+ if email, ok := c.Get("user_email").(string); ok && email != "" {
+ in.Email = &email
+ }
+ // Lookup workos_user_id (best-effort — used for analytics attribution).
+ if s.store != nil {
+ if userID := auth.GetUserID(c); userID != nil {
+ if user, err := s.store.GetUserByID(c.Request().Context(), *userID); err == nil {
+ if user.WorkOSUserID != nil && *user.WorkOSUserID != "" {
+ in.WorkOSUserID = user.WorkOSUserID
+ }
+ }
+ }
+ }
+
+ inboundToken, err := s.jwtIssuer.IssueIdentityToken(in, inboundJWTTTL)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "failed to mint inbound token",
+ })
+ }
+
+ downstreamIn := in
+ downstreamIn.Audience = auth.AudOpenComputerAPI
+ downstreamToken, err := s.jwtIssuer.IssueIdentityToken(downstreamIn, downstreamJWTTTL)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "failed to mint downstream token",
+ })
+ }
+
+ // Map /api/dashboard/agents[/...] → /v1/agents[/...]
+ upstreamPath := "/v1/agents"
+ if rest := strings.TrimPrefix(c.Request().URL.Path, "/api/dashboard/agents"); rest != "" {
+ upstreamPath += rest
+ }
+ upstream, err := url.Parse(sessionsAPIBaseURL() + upstreamPath)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "invalid upstream URL",
+ })
+ }
+ upstream.RawQuery = c.Request().URL.RawQuery
+
+ req, err := http.NewRequestWithContext(c.Request().Context(), c.Request().Method, upstream.String(), c.Request().Body)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "failed to build upstream request",
+ })
+ }
+
+ // Forward request headers, but drop the ones that should not cross the
+ // service boundary. The cookie carries the dashboard session; sessions-api
+ // must rely on the Bearer token instead.
+ for k, v := range c.Request().Header {
+ switch strings.ToLower(k) {
+ case "cookie", "authorization", "x-api-key", "host", "content-length":
+ continue
+ }
+ req.Header[k] = v
+ }
+ req.Header.Set("Authorization", "Bearer "+inboundToken)
+ req.Header.Set(downstreamHeaderName, downstreamToken)
+ if ct := c.Request().Header.Get("Content-Type"); ct != "" {
+ req.Header.Set("Content-Type", ct)
+ }
+
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ log.Printf("dashboard_agents: upstream call failed: %v", err)
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": "upstream request failed",
+ })
+ }
+ defer resp.Body.Close()
+
+ for k, v := range resp.Header {
+ // Hop-by-hop headers shouldn't be forwarded.
+ switch strings.ToLower(k) {
+ case "transfer-encoding", "connection", "keep-alive":
+ continue
+ }
+ c.Response().Header()[k] = v
+ }
+ c.Response().WriteHeader(resp.StatusCode)
+ if _, err := io.Copy(c.Response().Writer, resp.Body); err != nil {
+ log.Printf("dashboard_agents: copy upstream body failed: %v", err)
+ }
+ return nil
+}
+
diff --git a/internal/api/identity.go b/internal/api/identity.go
index f862e28b..3d66fd18 100644
--- a/internal/api/identity.go
+++ b/internal/api/identity.go
@@ -29,7 +29,7 @@ func (s *Server) createAuthToken(c echo.Context) error {
})
}
- in := auth.IdentityTokenInput{OrgID: orgID.String()}
+ in := auth.IdentityTokenInput{OrgID: orgID.String(), Audience: auth.AudSessionsAPI}
if userID := auth.GetUserID(c); userID != nil {
userStr := userID.String()
in.UserID = &userStr
diff --git a/internal/api/router.go b/internal/api/router.go
index afc63fd7..5cee5d09 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -188,7 +188,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// API routes (with API key auth)
api := e.Group("/api")
- api.Use(auth.PGAPIKeyMiddleware(s.store, apiKey))
+ api.Use(auth.PGAPIKeyMiddleware(s.store, apiKey, s.jwtIssuer))
// Identity
api.POST("/auth/token", s.createAuthToken)
@@ -403,6 +403,13 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// Admin endpoints
+ // Agents — reverse-proxy to sessions-api. Mints short-lived identity
+ // JWTs for the inbound (sessions-api) and downstream (OC API) hops so
+ // no API key is needed end-to-end. CLI users bypass this and hit
+ // sessions-api directly with X-API-Key.
+ dash.Any("/agents", s.dashboardAgentsProxy)
+ dash.Any("/agents/*", s.dashboardAgentsProxy)
+
// Session detail + stats
dash.GET("/sessions/:sandboxId", s.dashboardGetSession)
dash.GET("/sessions/:sandboxId/stats", s.dashboardGetSessionStats)
diff --git a/internal/auth/jwt.go b/internal/auth/jwt.go
index 7e8d26d1..8da98c2a 100644
--- a/internal/auth/jwt.go
+++ b/internal/auth/jwt.go
@@ -45,10 +45,20 @@ func (j *JWTIssuer) IssueSandboxToken(orgID uuid.UUID, sandboxID, workerID strin
return token.SignedString(j.secret)
}
+// Audience constants for identity tokens. Each consumer requires its own
+// audience so that a token minted for one surface cannot be replayed against
+// another (e.g. a token meant for sessions-api can't be used to call OC's
+// sandbox API directly).
+const (
+ AudSessionsAPI = "sessions-api"
+ AudOpenComputerAPI = "opencomputer-api"
+)
+
// IdentityClaims are the JWT claims for identity tokens issued to downstream
-// services (e.g. sessions-api). They carry the caller's org and user identity
-// so the downstream can authorize and attribute analytics events without
-// calling back to the control plane.
+// services (e.g. sessions-api, OC's own /api/sandboxes when called by
+// sessions-api). They carry the caller's org and user identity so the
+// downstream can authorize and attribute analytics events without calling
+// back to the control plane.
type IdentityClaims struct {
jwt.RegisteredClaims
OrgID string `json:"org_id"`
@@ -58,16 +68,21 @@ type IdentityClaims struct {
}
// IdentityTokenInput bundles the identity fields embedded in an identity JWT.
-// Nil pointers are omitted from the resulting token.
+// Nil pointers are omitted from the resulting token. Audience is required —
+// see the Aud* constants.
type IdentityTokenInput struct {
OrgID string
UserID *string
Email *string
WorkOSUserID *string
+ Audience string
}
// IssueIdentityToken creates a short-lived JWT carrying the caller's identity.
func (j *JWTIssuer) IssueIdentityToken(in IdentityTokenInput, ttl time.Duration) (string, error) {
+ if in.Audience == "" {
+ return "", fmt.Errorf("audience is required")
+ }
now := time.Now()
claims := IdentityClaims{
RegisteredClaims: jwt.RegisteredClaims{
@@ -75,6 +90,7 @@ func (j *JWTIssuer) IssueIdentityToken(in IdentityTokenInput, ttl time.Duration)
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
Issuer: "opensandbox",
+ Audience: jwt.ClaimStrings{in.Audience},
},
OrgID: in.OrgID,
UserID: in.UserID,
@@ -86,14 +102,15 @@ func (j *JWTIssuer) IssueIdentityToken(in IdentityTokenInput, ttl time.Duration)
return token.SignedString(j.secret)
}
-// ValidateIdentityToken parses and validates an identity JWT.
-func (j *JWTIssuer) ValidateIdentityToken(tokenStr string) (*IdentityClaims, error) {
+// ValidateIdentityToken parses and validates an identity JWT, requiring the
+// expected audience. Pass one of the Aud* constants.
+func (j *JWTIssuer) ValidateIdentityToken(tokenStr, expectedAudience string) (*IdentityClaims, error) {
token, err := jwt.ParseWithClaims(tokenStr, &IdentityClaims{}, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return j.secret, nil
- })
+ }, jwt.WithIssuer("opensandbox"), jwt.WithAudience(expectedAudience))
if err != nil {
return nil, fmt.Errorf("invalid token: %w", err)
}
diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go
index f98730b7..c6a01ab1 100644
--- a/internal/auth/middleware.go
+++ b/internal/auth/middleware.go
@@ -53,7 +53,13 @@ func GetUserID(c echo.Context) *uuid.UUID {
// PGAPIKeyMiddleware validates API keys against PostgreSQL.
// Falls back to static API key comparison if store is nil (combined/dev mode).
-func PGAPIKeyMiddleware(store *db.Store, staticKey string) echo.MiddlewareFunc {
+//
+// Also accepts an identity JWT (aud=opencomputer-api) when jwtIssuer is non-nil.
+// The JWT can arrive either in `Authorization: Bearer <jwt>` or as the X-API-Key
+// value (JWTs are detected by the two-dot signature: "header.payload.signature").
+// This lets sessions-api act on behalf of a dashboard user without holding a
+// long-lived API key — see internal/auth/jwt.go for the audience constants.
+func PGAPIKeyMiddleware(store *db.Store, staticKey string, jwtIssuer *JWTIssuer) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// Try static API key first (backward compat for combined mode)
@@ -61,12 +67,32 @@ func PGAPIKeyMiddleware(store *db.Store, staticKey string) echo.MiddlewareFunc {
return APIKeyMiddleware(staticKey)(next)(c)
}
+ // Identity-JWT path: Authorization: Bearer <jwt> with aud=opencomputer-api.
+ if jwtIssuer != nil {
+ authHeader := c.Request().Header.Get("Authorization")
+ if strings.HasPrefix(authHeader, "Bearer ") {
+ tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
+ if claims, err := jwtIssuer.ValidateIdentityToken(tokenStr, AudOpenComputerAPI); err == nil {
+ return applyIdentityClaims(c, claims, next)
+ }
+ }
+ }
+
// Get API key from header or query
key := c.Request().Header.Get("X-API-Key")
if key == "" {
key = c.QueryParam("api_key")
}
+ // JWTs may also arrive in the X-API-Key slot (the OC SDK takes a single
+ // `apiKey` field and ships it as X-API-Key — no Authorization option).
+ // Detect JWT by the two-dot signature; opaque API keys never contain dots.
+ if jwtIssuer != nil && key != "" && strings.Count(key, ".") == 2 {
+ if claims, err := jwtIssuer.ValidateIdentityToken(key, AudOpenComputerAPI); err == nil {
+ return applyIdentityClaims(c, claims, next)
+ }
+ }
+
// If no key and no store, pass through (dev mode)
if key == "" && store == nil && staticKey == "" {
return next(c)
@@ -99,6 +125,25 @@ func PGAPIKeyMiddleware(store *db.Store, staticKey string) echo.MiddlewareFunc {
}
}
+func applyIdentityClaims(c echo.Context, claims *IdentityClaims, next echo.HandlerFunc) error {
+ orgID, err := uuid.Parse(claims.OrgID)
+ if err != nil {
+ return c.JSON(http.StatusForbidden, map[string]string{
+ "error": "identity token: invalid org_id",
+ })
+ }
+ SetOrgID(c, orgID)
+ if claims.UserID != nil {
+ if userID, err := uuid.Parse(*claims.UserID); err == nil {
+ SetUserID(c, userID)
+ }
+ }
+ if claims.Email != nil {
+ c.Set("user_email", *claims.Email)
+ }
+ return next(c)
+}
+
// SandboxJWTMiddleware validates sandbox-scoped JWTs for direct worker access.
// It verifies the token and checks that the sandbox_id in the token matches the :id URL param.
func SandboxJWTMiddleware(jwtIssuer *JWTIssuer) echo.MiddlewareFunc {
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index 6ec984c2..142afc3d 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -52,7 +52,7 @@ func NewServer(store *db.Store, jwtIssuer *auth.JWTIssuer, registry *WorkerRegis
// Auth middleware
api := e.Group("")
- api.Use(auth.PGAPIKeyMiddleware(store, apiKey))
+ api.Use(auth.PGAPIKeyMiddleware(store, apiKey, jwtIssuer))
// Sandbox lifecycle (control plane only handles create/destroy/discover)
api.POST("/sandboxes", s.createSandbox)
@@ -99,13 +99,21 @@ func (s *Server) createSandbox(c echo.Context) error {
MemoryMB int `json:"memoryMB"`
CpuCount int `json:"cpuCount"`
Metadata map[string]string `json:"metadata"`
- NetworkEnabled bool `json:"networkEnabled"`
+ NetworkEnabled *bool `json:"networkEnabled"`
SecretStore string `json:"secretStore"` // secret store name — resolves secrets + egress config
}
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request: " + err.Error()})
}
+ // Default networkEnabled to true when caller omits the field. The worker
+ // currently sets up networking unconditionally, so a missing field that
+ // marshaled to false caused the UI to mislabel sandboxes as "Disabled".
+ if req.NetworkEnabled == nil {
+ t := true
+ req.NetworkEnabled = &t
+ }
+
orgID, ok := auth.GetOrgID(c)
if !ok {
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})
@@ -194,7 +202,7 @@ func (s *Server) createSandbox(c echo.Context) error {
Envs: req.Envs,
MemoryMb: int32(req.MemoryMB),
CpuCount: int32(req.CpuCount),
- NetworkEnabled: req.NetworkEnabled,
+ NetworkEnabled: *req.NetworkEnabled,
EgressAllowlist: egressAllowlist,
SecretAllowedHosts: secretAllowedHosts,
})
diff --git a/web/src/App.tsx b/web/src/App.tsx
index f9737438..ce088215 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -5,6 +5,7 @@ import Layout from './components/Layout'
import Login from './pages/Login'
import Dashboard from './pages/Dashboard'
import Sessions from './pages/Sessions'
+import Agents from './pages/Agents'
import APIKeys from './pages/APIKeys'
import Checkpoints from './pages/Checkpoints'
import Templates from './pages/Templates'
@@ -22,6 +23,7 @@ export default function App() {
<Route index element={<Dashboard />} />
<Route path="sessions" element={<Sessions />} />
<Route path="sessions/:sandboxId" element={<SessionDetail />} />
+ <Route path="agents" element={<Agents />} />
<Route path="checkpoints" element={<Checkpoints />} />
<Route path="templates" element={<Templates />} />
<Route path="api-keys" element={<APIKeys />} />
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index 50cbc5b0..2e4ddec2 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -310,3 +310,94 @@ export const redeemPromoCode = (code: string) =>
method: 'POST',
body: JSON.stringify({ code }),
})
+
+// ── Agents (proxied to sessions-api at /api/dashboard/agents/*) ──
+
+export interface Agent {
+ id: string
+ display_name: string
+ core: string | null
+ model: string | null
+ channels: Array<{ name: string; bot_username?: string | null; connected_at?: string }>
+ packages: Array<{ name: string; installed_at?: string }>
+ secret_store: string | null
+ config: Record<string, unknown>
+ created_at: string
+ updated_at: string
+}
+
+export interface AgentDetail extends Agent {
+ status: 'ready' | 'starting' | 'degraded' | 'error' | 'unknown'
+ instance_id: string | null
+ instance_status: string | null
+ core_status: { status: string; reason?: string; message?: string; updated_at?: string } | null
+ channel_status: Record<string, { status: string; phase?: string; message?: string }>
+ package_status: Record<string, { status: string; phase?: string; message?: string }>
+ conditions: Array<{ type: string; status: string; reason?: string; message?: string }>
+ current_operation: AgentOperation | null
+ last_error: { phase: string; message: string; at: string } | null
+}
+
+export interface AgentOperation {
+ id: string
+ agent_id: string
+ kind: string
+ target_type?: string | null
+ target_key?: string | null
+ phase: string
+ state: 'queued' | 'running' | 'success' | 'error' | 'canceled'
+ message?: string | null
+ created_at: string
+ updated_at: string
+}
+
+export const listAgents = () =>
+ apiFetch<{ agents: Agent[] }>('/agents')
+
+export const getAgent = (id: string) =>
+ apiFetch<AgentDetail>(`/agents/${encodeURIComponent(id)}`)
+
+export const createAgent = (input: {
+ id: string
+ display_name?: string
+ core?: string
+ model?: string
+ config?: Record<string, unknown>
+ secrets?: Record<string, string>
+}) =>
+ apiFetch<AgentDetail>('/agents', {
+ method: 'POST',
+ body: JSON.stringify(input),
+ })
+
+export const deleteAgent = (id: string) =>
+ apiFetch<{ id: string; deleted: boolean }>(`/agents/${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+ })
+
+export const installGbrain = (agentId: string) =>
+ apiFetch<{ agent_id: string; package: string; status: string; operation: AgentOperation }>(
+ `/agents/${encodeURIComponent(agentId)}/packages/gbrain`,
+ { method: 'POST' },
+ )
+
+export const uninstallGbrain = (agentId: string) =>
+ apiFetch<{ agent_id: string; package: string; status: string }>(
+ `/agents/${encodeURIComponent(agentId)}/packages/gbrain`,
+ { method: 'DELETE' },
+ )
+
+export const connectTelegram = (agentId: string, botToken: string) =>
+ apiFetch<{ agent_id: string; channel: string; status: string; operation: AgentOperation }>(
+ `/agents/${encodeURIComponent(agentId)}/channels/telegram`,
+ {
+ method: 'POST',
+ body: JSON.stringify({ bot_token: botToken }),
+ },
+ )
+
+export const disconnectTelegram = (agentId: string) =>
+ apiFetch<{ agent_id: string; channel: string; status: string }>(
+ `/agents/${encodeURIComponent(agentId)}/channels/telegram`,
+ { method: 'DELETE' },
+ )
diff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsx
index ce51bd8a..3a79697b 100644
--- a/web/src/components/Layout.tsx
+++ b/web/src/components/Layout.tsx
@@ -44,6 +44,16 @@ const icons = {
<line x1="1" y1="10" x2="23" y2="10" />
</svg>
),
+ bot: (
+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
+ <rect x="4" y="7" width="16" height="12" rx="2" />
+ <path d="M12 7V3" />
+ <circle cx="12" cy="3" r="1" />
+ <circle cx="9" cy="13" r="1" fill="currentColor" />
+ <circle cx="15" cy="13" r="1" fill="currentColor" />
+ <path d="M9 17h6" />
+ </svg>
+ ),
gear: (
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="3" />
@@ -62,6 +72,7 @@ const icons = {
const navItems = [
{ to: '/', label: 'Dashboard', end: true, icon: icons.grid },
{ to: '/sessions', label: 'Sessions', icon: icons.clock },
+ { to: '/agents', label: 'Agents', icon: icons.bot },
{ to: '/checkpoints', label: 'Checkpoints', icon: icons.layers },
{ to: '/templates', label: 'Templates', icon: icons.box },
{ to: '/api-keys', label: 'API Keys', icon: icons.key },
diff --git a/web/src/pages/Agents.tsx b/web/src/pages/Agents.tsx
new file mode 100644
index 00000000..36d42744
--- /dev/null
+++ b/web/src/pages/Agents.tsx
@@ -0,0 +1,569 @@
+import { useEffect, useState } from 'react'
+import {
+ listAgents,
+ getAgent,
+ createAgent,
+ deleteAgent,
+ installGbrain,
+ uninstallGbrain,
+ connectTelegram,
+ disconnectTelegram,
+ type Agent,
+ type AgentDetail,
+} from '../api/client'
+
+type Banner = { kind: 'info' | 'error' | 'success'; text: string } | null
+
+const statusColor: Record<string, string> = {
+ ready: 'var(--accent-emerald, #34d399)',
+ starting: 'var(--accent-amber, #fbbf24)',
+ degraded: 'var(--accent-amber, #fbbf24)',
+ error: 'var(--accent-rose, #f87171)',
+ unknown: 'var(--text-tertiary)',
+}
+
+export default function Agents() {
+ const [agents, setAgents] = useState<Agent[]>([])
+ const [details, setDetails] = useState<Record<string, AgentDetail>>({})
+ const [loading, setLoading] = useState(true)
+ const [banner, setBanner] = useState<Banner>(null)
+ const [showCreate, setShowCreate] = useState(false)
+ const [drawer, setDrawer] = useState<string | null>(null)
+
+ async function refresh() {
+ try {
+ const { agents } = await listAgents()
+ setAgents(agents)
+ const detailMap: Record<string, AgentDetail> = {}
+ await Promise.all(
+ agents.map(async (a) => {
+ try {
+ detailMap[a.id] = await getAgent(a.id)
+ } catch {
+ // best-effort: skip if detail fetch fails
+ }
+ }),
+ )
+ setDetails(detailMap)
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err)
+ setBanner({ kind: 'error', text: `Failed to load agents: ${msg}` })
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ useEffect(() => {
+ void refresh()
+ // Poll every 5s while the page is open — operation states change fast.
+ const interval = setInterval(() => void refresh(), 5000)
+ return () => clearInterval(interval)
+ }, [])
+
+ async function handleDelete(id: string) {
+ if (!window.confirm(`Delete agent "${id}"? The sandbox will be killed.`)) return
+ try {
+ await deleteAgent(id)
+ setBanner({ kind: 'success', text: `Agent ${id} deleted.` })
+ await refresh()
+ } catch (err) {
+ setBanner({ kind: 'error', text: `Delete failed: ${(err as Error).message}` })
+ }
+ }
+
+ return (
+ <div>
+ <header style={{ marginBottom: 28, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
+ <div>
+ <h1 style={{ fontSize: 22, margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700 }}>Agents</h1>
+ <p style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 6 }}>
+ Managed agent runtimes (Hermes, OpenClaw). Add channels and packages to extend what they do.
+ </p>
+ </div>
+ <button onClick={() => setShowCreate(true)} style={primaryButton}>+ New agent</button>
+ </header>
+
+ {banner && (
+ <div
+ style={{
+ padding: '10px 14px',
+ borderRadius: 6,
+ marginBottom: 16,
+ fontSize: 13,
+ background:
+ banner.kind === 'error'
+ ? 'rgba(248,113,113,0.08)'
+ : banner.kind === 'success'
+ ? 'rgba(52,211,153,0.08)'
+ : 'rgba(99,102,241,0.08)',
+ border: `1px solid ${
+ banner.kind === 'error'
+ ? 'rgba(248,113,113,0.3)'
+ : banner.kind === 'success'
+ ? 'rgba(52,211,153,0.3)'
+ : 'rgba(99,102,241,0.3)'
+ }`,
+ color: 'var(--text-primary)',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ }}
+ >
+ <span>{banner.text}</span>
+ <button onClick={() => setBanner(null)} style={iconButton}>×</button>
+ </div>
+ )}
+
+ {loading ? (
+ <div style={{ color: 'var(--text-tertiary)', fontSize: 13, padding: '32px 0' }}>Loading…</div>
+ ) : agents.length === 0 ? (
+ <EmptyState onCreate={() => setShowCreate(true)} />
+ ) : (
+ <div style={{ display: 'grid', gap: 10 }}>
+ {agents.map((a) => {
+ const d = details[a.id]
+ return (
+ <div
+ key={a.id}
+ style={{
+ background: 'rgba(255,255,255,0.02)',
+ border: '1px solid var(--border-subtle)',
+ borderRadius: 10,
+ padding: '14px 18px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: 16,
+ }}
+ >
+ <div
+ style={{
+ width: 8,
+ height: 8,
+ borderRadius: '50%',
+ background: statusColor[d?.status ?? 'unknown'] ?? statusColor.unknown,
+ flexShrink: 0,
+ }}
+ title={d?.status ?? 'unknown'}
+ />
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
+ <span style={{ fontWeight: 600, fontSize: 14 }}>{a.display_name}</span>
+ <span style={{ fontSize: 11, color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)' }}>
+ {a.id}
+ </span>
+ </div>
+ <div style={{ fontSize: 11, color: 'var(--text-secondary)', marginTop: 4, display: 'flex', gap: 12 }}>
+ {a.core && <span>core: <code style={codeInline}>{a.core}</code></span>}
+ <span>
+ packages: {a.packages.length === 0 ? '—' : a.packages.map((p) => p.name).join(', ')}
+ </span>
+ <span>
+ channels: {a.channels.length === 0 ? '—' : a.channels.map((c) => c.name).join(', ')}
+ </span>
+ </div>
+ {d?.current_operation && (
+ <div style={{ fontSize: 11, color: 'var(--accent-amber, #fbbf24)', marginTop: 4 }}>
+ {d.current_operation.kind} · {d.current_operation.phase}
+ {d.current_operation.message ? ` — ${d.current_operation.message}` : ''}
+ </div>
+ )}
+ {d?.last_error && d.status !== 'ready' && (
+ <div style={{ fontSize: 11, color: 'var(--accent-rose, #f87171)', marginTop: 4 }}>
+ {d.last_error.phase}: {d.last_error.message}
+ </div>
+ )}
+ </div>
+ <div style={{ display: 'flex', gap: 6 }}>
+ <button onClick={() => setDrawer(a.id)} style={secondaryButton}>Manage</button>
+ <button onClick={() => handleDelete(a.id)} style={dangerButton}>Delete</button>
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )}
+
+ {showCreate && (
+ <CreateAgentModal
+ onClose={() => setShowCreate(false)}
+ onCreated={(msg) => {
+ setShowCreate(false)
+ setBanner({ kind: 'success', text: msg })
+ void refresh()
+ }}
+ onError={(msg) => setBanner({ kind: 'error', text: msg })}
+ />
+ )}
+
+ {drawer && details[drawer] && (
+ <ManageDrawer
+ detail={details[drawer]!}
+ onClose={() => setDrawer(null)}
+ onAction={(b) => {
+ setBanner(b)
+ void refresh()
+ }}
+ />
+ )}
+ </div>
+ )
+}
+
+function EmptyState({ onCreate }: { onCreate: () => void }) {
+ return (
+ <div
+ style={{
+ textAlign: 'center',
+ padding: '60px 24px',
+ border: '1px dashed var(--border-subtle)',
+ borderRadius: 12,
+ }}
+ >
+ <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 8 }}>No agents yet</div>
+ <p style={{ color: 'var(--text-secondary)', fontSize: 13, marginBottom: 20 }}>
+ Spin up a managed Hermes agent and connect it to Telegram. Add gbrain to give it long-term memory.
+ </p>
+ <button onClick={onCreate} style={primaryButton}>Create your first agent</button>
+ </div>
+ )
+}
+
+function CreateAgentModal({
+ onClose,
+ onCreated,
+ onError,
+}: {
+ onClose: () => void
+ onCreated: (msg: string) => void
+ onError: (msg: string) => void
+}) {
+ const [id, setId] = useState('')
+ const [displayName, setDisplayName] = useState('')
+ const [core, setCore] = useState<'hermes' | 'openclaw' | ''>('hermes')
+ const [model, setModel] = useState('')
+ const [submitting, setSubmitting] = useState(false)
+
+ async function submit(e: React.FormEvent) {
+ e.preventDefault()
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(id)) {
+ onError('id must be lowercase alphanumeric + hyphens, starting with a letter or digit')
+ return
+ }
+ setSubmitting(true)
+ try {
+ await createAgent({
+ id,
+ display_name: displayName || id,
+ core: core || undefined,
+ model: model || undefined,
+ })
+ onCreated(`Agent "${id}" created. Sandbox is provisioning.`)
+ } catch (err) {
+ onError(`Create failed: ${(err as Error).message}`)
+ } finally {
+ setSubmitting(false)
+ }
+ }
+
+ return (
+ <ModalShell onClose={onClose} title="Create agent">
+ <form onSubmit={submit} style={{ display: 'grid', gap: 14 }}>
+ <Field label="Agent ID" hint="lowercase, hyphens, must be unique">
+ <input
+ autoFocus
+ value={id}
+ onChange={(e) => setId(e.target.value)}
+ placeholder="my-bot"
+ style={input}
+ required
+ />
+ </Field>
+ <Field label="Display name (optional)">
+ <input value={displayName} onChange={(e) => setDisplayName(e.target.value)} placeholder={id || 'My Bot'} style={input} />
+ </Field>
+ <Field label="Core" hint="Hermes is the standard chat agent. Leave blank for a bare sandbox.">
+ <select value={core} onChange={(e) => setCore(e.target.value as 'hermes' | 'openclaw' | '')} style={input}>
+ <option value="hermes">hermes</option>
+ <option value="openclaw">openclaw</option>
+ <option value="">(none — bare sandbox)</option>
+ </select>
+ </Field>
+ <Field label="Model (optional)">
+ <input value={model} onChange={(e) => setModel(e.target.value)} placeholder="anthropic/claude-3-5-sonnet" style={input} />
+ </Field>
+ <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
+ <button type="button" onClick={onClose} style={secondaryButton}>Cancel</button>
+ <button type="submit" disabled={submitting || !id} style={primaryButton}>
+ {submitting ? 'Creating…' : 'Create agent'}
+ </button>
+ </div>
+ </form>
+ </ModalShell>
+ )
+}
+
+function ManageDrawer({
+ detail,
+ onClose,
+ onAction,
+}: {
+ detail: AgentDetail
+ onClose: () => void
+ onAction: (b: { kind: 'info' | 'error' | 'success'; text: string }) => void
+}) {
+ const [busy, setBusy] = useState<string | null>(null)
+ const [botToken, setBotToken] = useState('')
+
+ const hasGbrain = detail.packages.some((p) => p.name === 'gbrain')
+ const telegramConnected = detail.channels.some((c) => c.name === 'telegram')
+ const canMutate = detail.core !== null
+
+ async function run<T>(label: string, fn: () => Promise<T>, success: string) {
+ setBusy(label)
+ try {
+ await fn()
+ onAction({ kind: 'success', text: success })
+ onClose()
+ } catch (err) {
+ onAction({ kind: 'error', text: `${label} failed: ${(err as Error).message}` })
+ } finally {
+ setBusy(null)
+ }
+ }
+
+ return (
+ <ModalShell onClose={onClose} title={`Manage: ${detail.display_name}`}>
+ <div style={{ display: 'grid', gap: 18 }}>
+ <Section title="Status">
+ <KV k="status" v={detail.status} mono />
+ <KV k="core" v={detail.core ?? '—'} mono />
+ <KV k="instance" v={detail.instance_status ?? '—'} mono />
+ {detail.core_status && <KV k="core status" v={`${detail.core_status.status} (${detail.core_status.reason ?? ''})`} mono />}
+ </Section>
+
+ {!canMutate && (
+ <p style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
+ This agent has no managed core. Channels and packages require a core (e.g. hermes).
+ </p>
+ )}
+
+ {canMutate && (
+ <>
+ <Section title="gbrain (long-term memory)">
+ {hasGbrain ? (
+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
+ <span style={pill('emerald')}>installed</span>
+ <button
+ onClick={() => run('uninstall gbrain', () => uninstallGbrain(detail.id), 'gbrain uninstalled.')}
+ disabled={busy !== null}
+ style={dangerButton}
+ >
+ {busy === 'uninstall gbrain' ? 'Working…' : 'Uninstall'}
+ </button>
+ </div>
+ ) : (
+ <button
+ onClick={() => run('install gbrain', () => installGbrain(detail.id), 'gbrain install queued.')}
+ disabled={busy !== null}
+ style={primaryButton}
+ >
+ {busy === 'install gbrain' ? 'Queueing…' : 'Install gbrain'}
+ </button>
+ )}
+ </Section>
+
+ <Section title="Telegram">
+ {telegramConnected ? (
+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
+ <span style={pill('emerald')}>connected</span>
+ <button
+ onClick={() => run('disconnect telegram', () => disconnectTelegram(detail.id), 'Telegram disconnected.')}
+ disabled={busy !== null}
+ style={dangerButton}
+ >
+ {busy === 'disconnect telegram' ? 'Working…' : 'Disconnect'}
+ </button>
+ </div>
+ ) : (
+ <div style={{ display: 'grid', gap: 8 }}>
+ <Field label="Bot token" hint="From @BotFather. Stored in this agent's secret store.">
+ <input
+ value={botToken}
+ onChange={(e) => setBotToken(e.target.value)}
+ placeholder="1234567890:AAA…"
+ style={input}
+ />
+ </Field>
+ <button
+ onClick={() =>
+ run(
+ 'connect telegram',
+ () => connectTelegram(detail.id, botToken.trim()),
+ 'Telegram connect queued — webhook will register shortly.',
+ )
+ }
+ disabled={busy !== null || !botToken.trim()}
+ style={primaryButton}
+ >
+ {busy === 'connect telegram' ? 'Queueing…' : 'Connect Telegram'}
+ </button>
+ </div>
+ )}
+ </Section>
+ </>
+ )}
+ </div>
+ </ModalShell>
+ )
+}
+
+function ModalShell({ children, title, onClose }: { children: React.ReactNode; title: string; onClose: () => void }) {
+ return (
+ <div
+ onClick={onClose}
+ style={{
+ position: 'fixed',
+ inset: 0,
+ background: 'rgba(0,0,0,0.5)',
+ zIndex: 100,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 20,
+ }}
+ >
+ <div
+ onClick={(e) => e.stopPropagation()}
+ style={{
+ background: 'var(--bg-deep)',
+ border: '1px solid var(--border-subtle)',
+ borderRadius: 12,
+ width: '100%',
+ maxWidth: 480,
+ maxHeight: '90vh',
+ overflowY: 'auto',
+ padding: 22,
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
+ <h2 style={{ fontSize: 16, margin: 0, fontFamily: 'var(--font-display)' }}>{title}</h2>
+ <button onClick={onClose} style={iconButton}>×</button>
+ </div>
+ {children}
+ </div>
+ </div>
+ )
+}
+
+function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
+ return (
+ <label style={{ display: 'grid', gap: 4 }}>
+ <span style={{ fontSize: 12, color: 'var(--text-secondary)', fontWeight: 500 }}>{label}</span>
+ {children}
+ {hint && <span style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>{hint}</span>}
+ </label>
+ )
+}
+
+function Section({ title, children }: { title: string; children: React.ReactNode }) {
+ return (
+ <div>
+ <h3 style={{ fontSize: 12, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-tertiary)', marginBottom: 10, fontFamily: 'var(--font-mono)' }}>
+ {title}
+ </h3>
+ <div style={{ display: 'grid', gap: 8 }}>{children}</div>
+ </div>
+ )
+}
+
+function KV({ k, v, mono }: { k: string; v: string; mono?: boolean }) {
+ return (
+ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
+ <span style={{ color: 'var(--text-tertiary)' }}>{k}</span>
+ <span style={{ color: 'var(--text-primary)', fontFamily: mono ? 'var(--font-mono)' : undefined }}>{v}</span>
+ </div>
+ )
+}
+
+function pill(tone: 'emerald' | 'amber' | 'rose'): React.CSSProperties {
+ const palette = {
+ emerald: { bg: 'rgba(52,211,153,0.12)', border: 'rgba(52,211,153,0.35)', fg: '#34d399' },
+ amber: { bg: 'rgba(251,191,36,0.12)', border: 'rgba(251,191,36,0.35)', fg: '#fbbf24' },
+ rose: { bg: 'rgba(248,113,113,0.12)', border: 'rgba(248,113,113,0.35)', fg: '#f87171' },
+ }[tone]
+ return {
+ background: palette.bg,
+ border: `1px solid ${palette.border}`,
+ color: palette.fg,
+ padding: '3px 9px',
+ borderRadius: 999,
+ fontSize: 11,
+ fontWeight: 500,
+ fontFamily: 'var(--font-mono)',
+ }
+}
+
+const primaryButton: React.CSSProperties = {
+ background: 'var(--gradient-primary, #6366f1)',
+ color: '#fff',
+ padding: '8px 14px',
+ border: 'none',
+ borderRadius: 6,
+ cursor: 'pointer',
+ fontSize: 13,
+ fontWeight: 600,
+ fontFamily: 'var(--font-body)',
+}
+
+const secondaryButton: React.CSSProperties = {
+ background: 'rgba(255,255,255,0.04)',
+ color: 'var(--text-primary)',
+ padding: '7px 12px',
+ border: '1px solid var(--border-subtle)',
+ borderRadius: 6,
+ cursor: 'pointer',
+ fontSize: 12,
+ fontFamily: 'var(--font-body)',
+}
+
+const dangerButton: React.CSSProperties = {
+ background: 'rgba(248,113,113,0.08)',
+ color: '#f87171',
+ padding: '7px 12px',
+ border: '1px solid rgba(248,113,113,0.35)',
+ borderRadius: 6,
+ cursor: 'pointer',
+ fontSize: 12,
+ fontFamily: 'var(--font-body)',
+}
+
+const iconButton: React.CSSProperties = {
+ background: 'none',
+ border: 'none',
+ color: 'var(--text-tertiary)',
+ cursor: 'pointer',
+ fontSize: 22,
+ padding: 0,
+ width: 22,
+ height: 22,
+ lineHeight: 1,
+}
+
+const input: React.CSSProperties = {
+ background: 'rgba(255,255,255,0.02)',
+ border: '1px solid var(--border-subtle)',
+ borderRadius: 6,
+ padding: '8px 10px',
+ color: 'var(--text-primary)',
+ fontSize: 13,
+ fontFamily: 'var(--font-body)',
+ outline: 'none',
+}
+
+const codeInline: React.CSSProperties = {
+ fontFamily: 'var(--font-mono)',
+ background: 'rgba(255,255,255,0.04)',
+ padding: '1px 5px',
+ borderRadius: 3,
+ fontSize: 10.5,
+}