An open-source, faster Devin alternative
TypeScript
feat: expose agent URLs and hooks in SDK and CLI
Igor Zalutski8801e5e56f3f
diff --git a/cmd/oc/internal/commands/agent.go b/cmd/oc/internal/commands/agent.goindex cf230107..95e0834e 100644--- a/cmd/oc/internal/commands/agent.go+++ b/cmd/oc/internal/commands/agent.go@@ -33,6 +33,7 @@ type RevisionRef struct {type Agent struct {ID string `json:"id"`Name string `json:"name"`+ InvokeURL string `json:"invoke_url"`Prompt string `json:"prompt,omitempty"`Model string `json:"model"`Runtime string `json:"runtime"`@@ -175,5 +176,7 @@ func init() {registerAgentDeploy()registerAgentConfig()registerAgentSchedules()+ registerAgentInvoke()+ registerAgentHooks()rootCmd.AddCommand(sessionCmd)}diff --git a/cmd/oc/internal/commands/agent_hooks.go b/cmd/oc/internal/commands/agent_hooks.gonew file mode 100644index 00000000..d45e8e07--- /dev/null+++ b/cmd/oc/internal/commands/agent_hooks.go@@ -0,0 +1,277 @@+package commands++import (+ "fmt"+ "net/url"+ "strings"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"+ "github.com/spf13/cobra"+)++type AgentHook struct {+ ID string `json:"id"`+ AgentID string `json:"agent_id"`+ Name string `json:"name"`+ Status string `json:"status"`+ SecretLast4 string `json:"secret_last4"`+ RevokedReason *string `json:"revoked_reason"`+ ExpiresAt *string `json:"expires_at"`+ CreatedAt string `json:"created_at"`+}++type AgentHookCreateResponse struct {+ Hook AgentHook `json:"hook"`+ HookURL string `json:"hook_url"`+}++type agentHookListResponse struct {+ Data []AgentHook `json:"data"`+ NextCursor *string `json:"next_cursor"`+}++func agentHookListPath(agentID string, includeRevoked bool, cursor string, limit int) string {+ query := url.Values{}+ if includeRevoked {+ query.Set("include_revoked", "true")+ }+ if cursor != "" {+ query.Set("cursor", cursor)+ }+ if limit > 0 {+ query.Set("limit", fmt.Sprintf("%d", limit))+ }+ path := "/v3/agents/" + agentID + "/hooks"+ if encoded := query.Encode(); encoded != "" {+ path += "?" + encoded+ }+ return path+}++func resolveHookID(cmd *cobra.Command, sc *client.Client, agentID, ref string) (string, error) {+ if strings.HasPrefix(ref, "hk_") {+ return ref, nil+ }+ var current []AgentHook+ var revoked []AgentHook+ cursor := ""+ for {+ var response agentHookListResponse+ if err := sc.Get(+ cmd.Context(),+ agentHookListPath(agentID, true, cursor, 100),+ &response,+ ); err != nil {+ return "", err+ }+ for _, hook := range response.Data {+ if hook.Name != ref {+ continue+ }+ if hook.Status == "revoked" {+ revoked = append(revoked, hook)+ } else {+ current = append(current, hook)+ }+ }+ if response.NextCursor == nil || *response.NextCursor == "" {+ break+ }+ cursor = *response.NextCursor+ }+ if len(current) == 1 {+ return current[0].ID, nil+ }+ if len(current) > 1 {+ return "", fmt.Errorf("multiple current Hooks named %q; use a Hook id", ref)+ }+ if len(revoked) == 1 {+ return revoked[0].ID, nil+ }+ if len(revoked) > 1 {+ return "", fmt.Errorf("multiple revoked Hooks named %q; use a Hook id", ref)+ }+ return "", fmt.Errorf("no Hook named %q on this agent", ref)+}++func hookReason(reason *string) string {+ if reason == nil || *reason == "" {+ return "-"+ }+ if *reason == "secret_exposure" {+ return "secret exposure"+ }+ return *reason+}++func hookExpiry(expiresAt *string) string {+ if expiresAt == nil || *expiresAt == "" {+ return "never"+ }+ return *expiresAt+}++var agentHooksCmd = &cobra.Command{+ Use: "hooks",+ Short: "List an agent's Hook URLs",+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, _ []string) error {+ sc, err := sessionsClient(cmd)+ if err != nil {+ return err+ }+ agentID, err := targetAgentID(cmd, sc, nil)+ if err != nil {+ return err+ }+ includeRevoked, _ := cmd.Flags().GetBool("include-revoked")+ cursor, _ := cmd.Flags().GetString("cursor")+ limit, _ := cmd.Flags().GetInt("limit")+ var response agentHookListResponse+ if err := sc.Get(+ cmd.Context(),+ agentHookListPath(agentID, includeRevoked, cursor, limit),+ &response,+ ); err != nil {+ return err+ }+ printer.Print(response, func() {+ if len(response.Data) == 0 {+ fmt.Println("No Hook URLs.")+ return+ }+ rows := make([][]string, 0, len(response.Data))+ for _, hook := range response.Data {+ rows = append(rows, []string{+ hook.Name,+ hook.ID,+ hook.Status,+ hook.SecretLast4,+ hookExpiry(hook.ExpiresAt),+ hookReason(hook.RevokedReason),+ })+ }+ printer.Table([]string{"NAME", "ID", "STATUS", "LAST4", "EXPIRES", "REVOKED"}, rows)+ if response.NextCursor != nil {+ fmt.Printf("More: oc agent hooks --agent %s --cursor %s\n", agentID, *response.NextCursor)+ }+ })+ return nil+ },+}++var agentHookCmd = &cobra.Command{+ Use: "hook",+ Short: "Create, inspect, and revoke Agent Hook URLs",+}++var agentHookCreateCmd = &cobra.Command{+ Use: "create <name>",+ Short: "Create a named Hook URL",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ sc, err := sessionsClient(cmd)+ if err != nil {+ return err+ }+ agentID, err := targetAgentID(cmd, sc, nil)+ if err != nil {+ return err+ }+ body := map[string]interface{}{"name": args[0]}+ if expiresAt, _ := cmd.Flags().GetString("expires-at"); expiresAt != "" {+ body["expires_at"] = expiresAt+ }+ var response AgentHookCreateResponse+ if err := sc.Post(cmd.Context(), "/v3/agents/"+agentID+"/hooks", body, &response); err != nil {+ return err+ }+ printer.Print(response, func() {+ fmt.Printf("Created Hook %s (%s)\n", response.Hook.Name, response.Hook.ID)+ fmt.Printf("URL: %s\n", response.HookURL)+ fmt.Println("Copy it now. The complete URL cannot be retrieved again.")+ })+ return nil+ },+}++var agentHookGetCmd = &cobra.Command{+ Use: "get <id|name>",+ Short: "Show a Hook without its secret URL",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ sc, err := sessionsClient(cmd)+ if err != nil {+ return err+ }+ agentID, err := targetAgentID(cmd, sc, nil)+ if err != nil {+ return err+ }+ hookID, err := resolveHookID(cmd, sc, agentID, args[0])+ if err != nil {+ return err+ }+ var hook AgentHook+ if err := sc.Get(cmd.Context(), "/v3/agents/"+agentID+"/hooks/"+hookID, &hook); err != nil {+ return err+ }+ printer.Print(hook, func() {+ fmt.Printf("Name: %s\n", hook.Name)+ fmt.Printf("ID: %s\n", hook.ID)+ fmt.Printf("Status: %s\n", hook.Status)+ fmt.Printf("Last 4: %s\n", hook.SecretLast4)+ fmt.Printf("Expires: %s\n", hookExpiry(hook.ExpiresAt))+ fmt.Printf("Revoked: %s\n", hookReason(hook.RevokedReason))+ })+ return nil+ },+}++var agentHookRevokeCmd = &cobra.Command{+ Use: "revoke <id|name>",+ Short: "Permanently revoke a Hook URL",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ sc, err := sessionsClient(cmd)+ if err != nil {+ return err+ }+ agentID, err := targetAgentID(cmd, sc, nil)+ if err != nil {+ return err+ }+ hookID, err := resolveHookID(cmd, sc, agentID, args[0])+ if err != nil {+ return err+ }+ if err := confirmDestructive(cmd, fmt.Sprintf("Permanently revoke Hook %s", args[0])); err != nil {+ return err+ }+ if err := sc.Delete(cmd.Context(), "/v3/agents/"+agentID+"/hooks/"+hookID); err != nil {+ return err+ }+ printer.Print(map[string]string{"id": hookID, "status": "revoked"}, func() {+ fmt.Printf("Revoked Hook %s.\n", hookID)+ })+ return nil+ },+}++func registerAgentHooks() {+ for _, command := range []*cobra.Command{+ agentHooksCmd,+ agentHookCreateCmd,+ agentHookGetCmd,+ agentHookRevokeCmd,+ } {+ command.Flags().String("agent", "", "Agent id or name (else the cwd agent.toml)")+ }+ agentHooksCmd.Flags().Bool("include-revoked", false, "Include revoked Hooks")+ agentHooksCmd.Flags().String("cursor", "", "Continue a previous list page")+ agentHooksCmd.Flags().Int("limit", 0, "Maximum Hooks to return (server caps at 100)")+ agentHookCreateCmd.Flags().String("expires-at", "", "RFC 3339 expiry (default: no expiry)")+ agentHookRevokeCmd.Flags().Bool("yes", false, "Skip the confirmation prompt")+ agentHookCmd.AddCommand(agentHookCreateCmd, agentHookGetCmd, agentHookRevokeCmd)+ agentCmd.AddCommand(agentHooksCmd, agentHookCmd)+}diff --git a/cmd/oc/internal/commands/agent_hooks_test.go b/cmd/oc/internal/commands/agent_hooks_test.gonew file mode 100644index 00000000..5cb9eae6--- /dev/null+++ b/cmd/oc/internal/commands/agent_hooks_test.go@@ -0,0 +1,102 @@+package commands++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"+ "github.com/spf13/cobra"+)++func TestResolveHookIDPrefersCurrentHookAcrossPages(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("X-API-Key") != "osb_test" {+ t.Errorf("missing sessions API key")+ }+ if r.URL.Query().Get("include_revoked") != "true" || r.URL.Query().Get("limit") != "100" {+ t.Errorf("query = %q", r.URL.RawQuery)+ }+ w.Header().Set("Content-Type", "application/json")+ if r.URL.Query().Get("cursor") == "" {+ _, _ = io.WriteString(w, `{"data":[{"id":"hk_aaaaaaaaaaaaaaaaaaaaaaaa","agent_id":"agt_0123456789abcdef01234567","name":"grafana","status":"revoked","secret_last4":"old1","revoked_reason":"manual","expires_at":null,"created_at":"2026-07-20T00:00:00Z"}],"next_cursor":"next"}`)+ return+ }+ _, _ = io.WriteString(w, `{"data":[{"id":"hk_bbbbbbbbbbbbbbbbbbbbbbbb","agent_id":"agt_0123456789abcdef01234567","name":"grafana","status":"active","secret_last4":"new1","revoked_reason":null,"expires_at":null,"created_at":"2026-07-21T00:00:00Z"}],"next_cursor":null}`)+ }))+ defer server.Close()++ command := &cobra.Command{}+ command.SetContext(context.Background())+ hookID, err := resolveHookID(+ command,+ client.NewSessionsAPI(server.URL, "osb_test"),+ "agt_0123456789abcdef01234567",+ "grafana",+ )+ if err != nil {+ t.Fatal(err)+ }+ if hookID != "hk_bbbbbbbbbbbbbbbbbbbbbbbb" {+ t.Fatalf("hook id = %q", hookID)+ }+}++func TestResolveHookIDRejectsAmbiguousRevokedNames(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = io.WriteString(w, `{"data":[{"id":"hk_aaaaaaaaaaaaaaaaaaaaaaaa","name":"grafana","status":"revoked"},{"id":"hk_bbbbbbbbbbbbbbbbbbbbbbbb","name":"grafana","status":"revoked"}],"next_cursor":null}`)+ }))+ defer server.Close()++ command := &cobra.Command{}+ command.SetContext(context.Background())+ _, err := resolveHookID(+ command,+ client.NewSessionsAPI(server.URL, "osb_test"),+ "agt_0123456789abcdef01234567",+ "grafana",+ )+ if err == nil || !strings.Contains(err.Error(), "multiple revoked Hooks") {+ t.Fatalf("error = %v", err)+ }+}++func TestAgentHookPublicMetadataCannotCarryTheSecretURL(t *testing.T) {+ response := AgentHookCreateResponse{+ Hook: AgentHook{+ ID: "hk_aaaaaaaaaaaaaaaaaaaaaaaa",+ AgentID: "agt_0123456789abcdef01234567",+ Name: "grafana",+ Status: "active",+ SecretLast4: "last",+ },+ HookURL: "https://example.test/hooks/ochk_v1_secret",+ }+ encoded, err := json.Marshal(response.Hook)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(encoded), "ochk_v1_") || strings.Contains(string(encoded), "hook_url") {+ t.Fatalf("Hook metadata leaked credential material: %s", encoded)+ }+ if !strings.Contains(response.HookURL, "ochk_v1_") {+ t.Fatal("create response should retain its copy-once URL")+ }+}++func TestAgentHookCommandShape(t *testing.T) {+ if agentHooksCmd.Use != "hooks" {+ t.Fatalf("list command use = %q", agentHooksCmd.Use)+ }+ if agentHookCreateCmd.Flags().Lookup("expires-at") == nil {+ t.Fatal("hook create must expose --expires-at")+ }+ if agentHookRevokeCmd.Flags().Lookup("yes") == nil {+ t.Fatal("hook revoke must require or accept explicit confirmation")+ }+}diff --git a/cmd/oc/internal/commands/agent_invoke.go b/cmd/oc/internal/commands/agent_invoke.gonew file mode 100644index 00000000..2e2d380a--- /dev/null+++ b/cmd/oc/internal/commands/agent_invoke.go@@ -0,0 +1,248 @@+package commands++import (+ "bytes"+ "context"+ "crypto/rand"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "os"+ "strconv"+ "strings"+ "time"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"+ "github.com/opensandbox/opensandbox/cmd/oc/internal/config"+ "github.com/spf13/cobra"+)++const agentInvokeResponseMaxBytes = 1 << 20++type AgentInvokeReceipt struct {+ RequestID string `json:"request_id"`+ Session struct {+ ID string `json:"id"`+ Status string `json:"status"`+ Head int `json:"head"`+ } `json:"session"`+ ClientToken string `json:"client_token,omitempty"`+ Links struct {+ Events string `json:"events"`+ Messages string `json:"messages"`+ } `json:"links"`+ Replayed bool `json:"replayed"`+}++type invokeWait func(context.Context, time.Duration) error++func waitForInvokeRetry(ctx context.Context, duration time.Duration) error {+ timer := time.NewTimer(duration)+ defer timer.Stop()+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-timer.C:+ return nil+ }+}++func generatedInvokeKey() (string, error) {+ var value [16]byte+ if _, err := rand.Read(value[:]); err != nil {+ return "", fmt.Errorf("generate idempotency key: %w", err)+ }+ return "oc-cli-" + hex.EncodeToString(value[:]), nil+}++func invokeRetryDelay(response *http.Response, attempt int) time.Duration {+ if raw := response.Header.Get("Retry-After"); raw != "" {+ if seconds, err := strconv.Atoi(raw); err == nil && seconds > 0 {+ return min(time.Duration(seconds)*time.Second, 8*time.Second)+ }+ }+ return min(250*time.Millisecond*time.Duration(1<<attempt), 2*time.Second)+}++func readBoundedResponse(response *http.Response) ([]byte, error) {+ defer response.Body.Close()+ body, err := io.ReadAll(io.LimitReader(response.Body, agentInvokeResponseMaxBytes+1))+ if err != nil {+ return nil, err+ }+ if len(body) > agentInvokeResponseMaxBytes {+ return nil, fmt.Errorf("Agent URL response exceeds %d bytes", agentInvokeResponseMaxBytes)+ }+ return body, nil+}++func invokeAgentURL(+ ctx context.Context,+ httpClient *http.Client,+ apiKey string,+ invokeURL string,+ body []byte,+ idempotencyKey string,+ maxRetries int,+ wait invokeWait,+) (AgentInvokeReceipt, error) {+ var receipt AgentInvokeReceipt+ target := strings.TrimRight(invokeURL, "/") + "/"++ for attempt := 0; ; attempt++ {+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, target, bytes.NewReader(body))+ if err != nil {+ return receipt, err+ }+ request.Header.Set("Authorization", "Bearer "+apiKey)+ request.Header.Set("Content-Type", "application/json")+ request.Header.Set("Idempotency-Key", idempotencyKey)++ response, err := httpClient.Do(request)+ if err != nil {+ if attempt < maxRetries && ctx.Err() == nil {+ if waitErr := wait(ctx, min(250*time.Millisecond*time.Duration(1<<attempt), 2*time.Second)); waitErr != nil {+ return receipt, waitErr+ }+ continue+ }+ return receipt, err+ }++ retryable := response.StatusCode == http.StatusTooManyRequests || response.StatusCode >= 500+ if retryable && attempt < maxRetries {+ delay := invokeRetryDelay(response, attempt)+ _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, agentInvokeResponseMaxBytes))+ response.Body.Close()+ if err := wait(ctx, delay); err != nil {+ return receipt, err+ }+ continue+ }++ responseBody, err := readBoundedResponse(response)+ if err != nil {+ return receipt, err+ }+ if response.StatusCode < 200 || response.StatusCode >= 300 {+ var envelope struct {+ Error struct {+ Message string `json:"message"`+ } `json:"error"`+ }+ message := strings.TrimSpace(string(responseBody))+ if json.Unmarshal(responseBody, &envelope) == nil && envelope.Error.Message != "" {+ message = envelope.Error.Message+ }+ return receipt, &client.APIError{StatusCode: response.StatusCode, Message: message}+ }+ if err := json.Unmarshal(responseBody, &receipt); err != nil {+ return receipt, fmt.Errorf("decode Agent URL response: %w", err)+ }+ return receipt, nil+ }+}++func agentInvokeInput(cmd *cobra.Command) ([]byte, error) {+ data, _ := cmd.Flags().GetString("data")+ path, _ := cmd.Flags().GetString("file")+ fromStdin, _ := cmd.Flags().GetBool("stdin")+ selected := 0+ if cmd.Flags().Changed("data") {+ selected+++ }+ if path != "" {+ selected+++ }+ if fromStdin {+ selected+++ }+ if selected > 1 {+ return nil, fmt.Errorf("use only one of --data, --file, or --stdin")+ }++ var body []byte+ var err error+ switch {+ case path != "":+ body, err = os.ReadFile(path)+ case fromStdin:+ body, err = io.ReadAll(os.Stdin)+ default:+ body = []byte(data)+ }+ if err != nil {+ return nil, err+ }+ if !json.Valid(body) {+ return nil, fmt.Errorf("invocation body must be valid JSON")+ }+ return body, nil+}++var agentInvokeCmd = &cobra.Command{+ Use: "invoke <id|name>",+ Short: "Start a session through an agent's canonical URL",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ sc, err := sessionsClient(cmd)+ if err != nil {+ return err+ }+ agentID, err := resolveRef(cmd, sc, args[0])+ if err != nil {+ return err+ }+ var agent Agent+ if err := sc.Get(cmd.Context(), "/v3/agents/"+agentID, &agent); err != nil {+ return err+ }+ if agent.InvokeURL == "" {+ return fmt.Errorf("agent response did not include invoke_url")+ }++ body, err := agentInvokeInput(cmd)+ if err != nil {+ return err+ }+ key, _ := cmd.Flags().GetString("idempotency-key")+ if key == "" {+ key, err = generatedInvokeKey()+ if err != nil {+ return err+ }+ }+ cfg := config.Load(cmd)+ if cfg.APIKey == "" {+ return fmt.Errorf("OpenComputer API key is required")+ }+ httpClient := &http.Client{+ Timeout: 30 * time.Second,+ CheckRedirect: func(_ *http.Request, _ []*http.Request) error {+ return fmt.Errorf("Agent URL must not redirect")+ },+ }+ receipt, err := invokeAgentURL(+ cmd.Context(), httpClient, cfg.APIKey, agent.InvokeURL, body, key, 2, waitForInvokeRetry,+ )+ if err != nil {+ return err+ }+ printer.Print(receipt, func() {+ fmt.Printf("Accepted session %s (status: %s)\n", receipt.Session.ID, receipt.Session.Status)+ fmt.Printf("Follow: oc session logs %s\n", receipt.Session.ID)+ fmt.Printf("Steer: oc session steer %s \"message\"\n", receipt.Session.ID)+ })+ return nil+ },+}++func registerAgentInvoke() {+ agentInvokeCmd.Flags().String("data", "{}", "JSON request body")+ agentInvokeCmd.Flags().String("file", "", "Read the JSON request body from a file")+ agentInvokeCmd.Flags().Bool("stdin", false, "Read the JSON request body from stdin")+ agentInvokeCmd.Flags().String("idempotency-key", "", "Reuse a logical invocation across retries")+ agentCmd.AddCommand(agentInvokeCmd)+}diff --git a/cmd/oc/internal/commands/agent_invoke_test.go b/cmd/oc/internal/commands/agent_invoke_test.gonew file mode 100644index 00000000..359c3dfe--- /dev/null+++ b/cmd/oc/internal/commands/agent_invoke_test.go@@ -0,0 +1,113 @@+package commands++import (+ "context"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/spf13/cobra"+)++func noInvokeWait(context.Context, time.Duration) error { return nil }++func TestInvokeAgentURLUsesExactRootBearerAndStableIdempotencyKey(t *testing.T) {+ var requests int+ var firstKey string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests+++ if r.URL.Path != "/" || r.URL.RawQuery != "" {+ t.Errorf("request target = %q, want exact root", r.URL.RequestURI())+ }+ if got := r.Header.Get("Authorization"); got != "Bearer osb_test" {+ t.Errorf("Authorization = %q", got)+ }+ if got := r.Header.Get("X-API-Key"); got != "" {+ t.Errorf("X-API-Key must be absent, got %q", got)+ }+ key := r.Header.Get("Idempotency-Key")+ if requests == 1 {+ firstKey = key+ } else if key != firstKey {+ t.Errorf("retry key = %q, want %q", key, firstKey)+ }+ body, _ := io.ReadAll(r.Body)+ if string(body) != `{"task":"triage"}` {+ t.Errorf("body = %q", body)+ }+ if requests == 1 {+ http.Error(w, "temporary", http.StatusServiceUnavailable)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusAccepted)+ _, _ = io.WriteString(w, `{"request_id":"req_1","session":{"id":"ses_1","status":"running","head":1},"replayed":false}`)+ }))+ defer server.Close()++ receipt, err := invokeAgentURL(+ context.Background(),+ server.Client(),+ "osb_test",+ server.URL,+ []byte(`{"task":"triage"}`),+ "stable-key",+ 2,+ noInvokeWait,+ )+ if err != nil {+ t.Fatal(err)+ }+ if requests != 2 {+ t.Fatalf("requests = %d, want 2", requests)+ }+ if receipt.Session.ID != "ses_1" || receipt.Session.Status != "running" {+ t.Fatalf("receipt = %#v", receipt)+ }+}++func TestAgentInvokeInputValidatesJSONAndExclusiveSources(t *testing.T) {+ command := &cobra.Command{}+ command.Flags().String("data", "{}", "")+ command.Flags().String("file", "", "")+ command.Flags().Bool("stdin", false, "")++ if err := command.Flags().Set("data", `{"ok":true}`); err != nil {+ t.Fatal(err)+ }+ body, err := agentInvokeInput(command)+ if err != nil || string(body) != `{"ok":true}` {+ t.Fatalf("body = %q, err = %v", body, err)+ }++ if err := command.Flags().Set("stdin", "true"); err != nil {+ t.Fatal(err)+ }+ if _, err := agentInvokeInput(command); err == nil || !strings.Contains(err.Error(), "only one") {+ t.Fatalf("exclusive source error = %v", err)+ }++ invalid := &cobra.Command{}+ invalid.Flags().String("data", "{}", "")+ invalid.Flags().String("file", "", "")+ invalid.Flags().Bool("stdin", false, "")+ if err := invalid.Flags().Set("data", "not-json"); err != nil {+ t.Fatal(err)+ }+ if _, err := agentInvokeInput(invalid); err == nil || !strings.Contains(err.Error(), "valid JSON") {+ t.Fatalf("JSON validation error = %v", err)+ }+}++func TestGeneratedInvokeKeyHasStablePublicShape(t *testing.T) {+ key, err := generatedInvokeKey()+ if err != nil {+ t.Fatal(err)+ }+ if len(key) != len("oc-cli-")+32 || !strings.HasPrefix(key, "oc-cli-") {+ t.Fatalf("generated key = %q", key)+ }+}diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.jsonindex 9e6ef24b..265f43f2 100644--- a/sdks/typescript/package-lock.json+++ b/sdks/typescript/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/sdk",- "version": "0.13.1",+ "version": "0.14.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/sdk",- "version": "0.13.1",+ "version": "0.14.0","license": "MIT","devDependencies": {"@types/node": "^25.3.0",diff --git a/sdks/typescript/package.json b/sdks/typescript/package.jsonindex dbac9735..113a0715 100644--- a/sdks/typescript/package.json+++ b/sdks/typescript/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/sdk",- "version": "0.13.1",+ "version": "0.14.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.tsindex 0f592aca..74c7eca4 100644--- a/sdks/typescript/src/agents/agents.ts+++ b/sdks/typescript/src/agents/agents.ts@@ -6,6 +6,7 @@ import {} from "./deployments.js";import { Schedules } from "./schedules.js";import { AgentRepository } from "./repository-agents.js";+import { AgentHooks } from "./hooks.js";export interface CreateAgentParams {name: string;@@ -138,6 +139,8 @@ export class Agents {readonly schedules: Schedules;/** Review and import an agent from an existing repository. */readonly repository: AgentRepository;+ /** Named, revocable URLs for external systems that should only start this agent. */+ readonly hooks: AgentHooks;constructor(private readonly http: Http) {this.deployments = new Deployments(http);@@ -147,6 +150,7 @@ export class Agents {this.deploymentSource = new DeploymentSourceResource(http);this.schedules = new Schedules(http);this.repository = new AgentRepository(http);+ this.hooks = new AgentHooks(http);}create(params: CreateAgentParams): Promise<Agent> {diff --git a/sdks/typescript/src/agents/hooks.test.ts b/sdks/typescript/src/agents/hooks.test.tsnew file mode 100644index 00000000..0f7cbc7a--- /dev/null+++ b/sdks/typescript/src/agents/hooks.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it, vi } from "vitest";+import { OpenComputer } from "./client.js";++function client(fetcher: typeof fetch) {+ return new OpenComputer({+ apiKey: "test-key",+ baseUrl: "https://api.example.test/v3",+ fetch: fetcher,+ maxRetries: 0,+ });+}++describe("Agent URLs and Hooks", () => {+ it("maps the canonical Agent URL without adding an invoke helper", async () => {+ const fetcher = vi.fn(async () => Response.json({+ id: "agt_0123456789abcdef01234567",+ name: "triage",+ invoke_url: "https://agt-0123456789abcdef01234567.agents.opencomputer.dev",+ model: "anthropic/claude-sonnet-5",+ runtime: "claude",+ }));+ const oc = client(fetcher as typeof fetch);++ const agent = await oc.agents.get("agt_0123456789abcdef01234567");++ expect(agent.invokeUrl).toBe(+ "https://agt-0123456789abcdef01234567.agents.opencomputer.dev",+ );+ expect("invoke" in oc.agents).toBe(false);+ });++ it("returns the complete Hook URL only from create", async () => {+ const fetcher = vi.fn(async () => Response.json({+ hook: {+ id: "hk_0123456789abcdef01234567",+ agent_id: "agt_0123456789abcdef01234567",+ name: "grafana-prod",+ status: "active",+ secret_last4: "dHh8",+ revoked_reason: null,+ expires_at: null,+ created_at: "2026-07-22T12:00:00.000Z",+ },+ hook_url: "https://agt-0123456789abcdef01234567.agents.opencomputer.dev/hooks/ochk_v1_secret",+ }, { status: 201 }));+ const oc = client(fetcher as typeof fetch);++ const created = await oc.agents.hooks.create(+ "agt_0123456789abcdef01234567",+ { name: "grafana-prod", expiresAt: null },+ );++ expect(created.hookUrl).toContain("/hooks/ochk_v1_");+ expect(created.hook).toMatchObject({+ agentId: "agt_0123456789abcdef01234567",+ secretLast4: "dHh8",+ revokedReason: null,+ });+ expect(JSON.stringify(created.hook)).not.toContain("ochk_v1_");+ expect(fetcher).toHaveBeenCalledWith(+ "https://api.example.test/v3/agents/agt_0123456789abcdef01234567/hooks",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({ name: "grafana-prod", expires_at: null }),+ }),+ );+ });++ it("lists, gets, and revokes without a credential recovery surface", async () => {+ const responses = [+ Response.json({+ data: [{+ id: "hk_0123456789abcdef01234567",+ agent_id: "agt_0123456789abcdef01234567",+ name: "grafana-prod",+ status: "revoked",+ secret_last4: "dHh8",+ revoked_reason: "secret_exposure",+ expires_at: null,+ created_at: "2026-07-22T12:00:00.000Z",+ }],+ next_cursor: "cursor-2",+ }),+ Response.json({+ id: "hk_0123456789abcdef01234567",+ agent_id: "agt_0123456789abcdef01234567",+ name: "grafana-prod",+ status: "revoked",+ secret_last4: "dHh8",+ revoked_reason: "secret_exposure",+ expires_at: null,+ created_at: "2026-07-22T12:00:00.000Z",+ }),+ new Response(null, { status: 204 }),+ ];+ const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>+ responses.shift()!+ );+ const oc = client(fetcher as typeof fetch);++ const page = await oc.agents.hooks.list(+ "agt_0123456789abcdef01234567",+ { includeRevoked: true, cursor: "cursor-1", limit: 10 },+ );+ const hook = await oc.agents.hooks.get(+ "agt_0123456789abcdef01234567",+ "hk_0123456789abcdef01234567",+ );+ await oc.agents.hooks.delete(+ "agt_0123456789abcdef01234567",+ "hk_0123456789abcdef01234567",+ );++ expect(page.nextCursor).toBe("cursor-2");+ expect(page.data[0].revokedReason).toBe("secret_exposure");+ expect(hook).not.toHaveProperty("hookUrl");+ expect(fetcher.mock.calls[0][0]).toContain(+ "include_revoked=true&cursor=cursor-1&limit=10",+ );+ expect(fetcher.mock.calls[2][1]).toMatchObject({ method: "DELETE" });+ });+});diff --git a/sdks/typescript/src/agents/hooks.ts b/sdks/typescript/src/agents/hooks.tsnew file mode 100644index 00000000..5ec9f644--- /dev/null+++ b/sdks/typescript/src/agents/hooks.ts@@ -0,0 +1,56 @@+import type { Http, Query } from "./http.js";+import type { Page } from "./agents.js";++export type HookStatus = "active" | "expired" | "revoked";+export type HookRevokedReason = "manual" | "secret_exposure";++export interface AgentHook {+ id: string;+ agentId: string;+ name: string;+ status: HookStatus;+ secretLast4: string;+ revokedReason: HookRevokedReason | null;+ expiresAt: string | null;+ createdAt: string;+}++export interface CreateAgentHookParams {+ name: string;+ expiresAt?: string | null;+}++export interface ListAgentHooksParams {+ includeRevoked?: boolean;+ cursor?: string;+ limit?: number;+}++export interface CreatedAgentHook {+ hook: AgentHook;+ /** Complete secret URL. Returned once, only by create. */+ hookUrl: string;+}++/** Named, independently revocable URLs that can only start this agent. */+export class AgentHooks {+ constructor(private readonly http: Http) {}++ create(agentId: string, params: CreateAgentHookParams): Promise<CreatedAgentHook> {+ return this.http.request("POST", `/agents/${agentId}/hooks`, { body: params });+ }++ list(agentId: string, params: ListAgentHooksParams = {}): Promise<Page<AgentHook>> {+ return this.http.request("GET", `/agents/${agentId}/hooks`, {+ query: params as Query,+ });+ }++ get(agentId: string, hookId: string): Promise<AgentHook> {+ return this.http.request("GET", `/agents/${agentId}/hooks/${hookId}`);+ }++ delete(agentId: string, hookId: string): Promise<void> {+ return this.http.request("DELETE", `/agents/${agentId}/hooks/${hookId}`);+ }+}diff --git a/sdks/typescript/src/agents/index.ts b/sdks/typescript/src/agents/index.tsindex 4acefb22..42873461 100644--- a/sdks/typescript/src/agents/index.ts+++ b/sdks/typescript/src/agents/index.ts@@ -15,6 +15,11 @@ export type {RepositoryAccessPolicy, RepositoryAccessGrant, RepositoryAccessRepository,UnavailableSelectedRepository, RepositoryAccess,} from "./agents.js";+export { AgentHooks } from "./hooks.js";+export type {+ AgentHook, HookStatus, HookRevokedReason, CreateAgentHookParams,+ ListAgentHooksParams, CreatedAgentHook,+} from "./hooks.js";export { AgentRepository } from "./repository-agents.js";export type {SourceProfileId, RepositoryAgentSource, ReviewRepositoryAgentParams,diff --git a/sdks/typescript/src/agents/types.ts b/sdks/typescript/src/agents/types.tsindex 5b0bf8f8..aabce0e5 100644--- a/sdks/typescript/src/agents/types.ts+++ b/sdks/typescript/src/agents/types.ts@@ -32,6 +32,8 @@ export interface Actor {export interface Agent {id: string;name: string;+ /** Canonical application URL for trusted-backend JSON invocation. */+ invokeUrl: string;promptHash?: string;model: string;runtime: Runtime;