The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Add org-wide Devin Cloud telemetry connector (beacon cloud devin pull)
shukieshah421894ca402e
diff --git a/README.md b/README.mdindex 885e3e40..56824e58 100644--- a/README.md+++ b/README.md@@ -113,6 +113,7 @@ CI, and cloud surfaces.| [Claude Agent SDK](https://docs.asymptotelabs.ai/sdk/integrations-claude-agent-sdk) | Query wrapper through `Observe.wrapClaudeAgentQuery()` | Query root spans with Beacon-compatible prompt attributes || [Claude Code Cloud Agents](https://docs.asymptotelabs.ai/claude-code-cloud-agents) | Cloud sandbox hooks with GCS upload | Session, prompt, tool, command, file, and lifecycle telemetry where Claude Code cloud hook payloads expose it || [Cursor Cloud Agents](https://docs.asymptotelabs.ai/cursor-cloud-agents) | Cloud sandbox hooks with GCS upload | Tool, shell command, file, subagent, and compaction telemetry where Cursor cloud hook payloads expose it |+| [Devin Cloud Agents](https://docs.asymptotelabs.ai/devin-cloud-agents) | Org-wide API poll via `beacon cloud devin pull`, with GCS upload | Session, prompt, agent message, status, pull request, and ACU usage telemetry the Devin sessions API exposes (message-level; the autonomous agent runs no in-sandbox hooks) || [OpenAI](https://docs.asymptotelabs.ai/sdk/integrations-openai) | OpenLLMetry instrumentation through `@asymptote/sdk` | Supported OpenAI model call spans, errors, and OpenTelemetry attributes || [Vercel AI SDK](https://docs.asymptotelabs.ai/sdk/integrations-vercel-ai-sdk) | Tracer handoff through `experimental_telemetry` | AI SDK model call and tool spans where telemetry is enabled |diff --git a/cli/beacon/cmd/cloud_devin_pull.go b/cli/beacon/cmd/cloud_devin_pull.gonew file mode 100644index 00000000..1fb73ad4--- /dev/null+++ b/cli/beacon/cmd/cloud_devin_pull.go@@ -0,0 +1,171 @@+package cmd++import (+ "context"+ "fmt"+ "os"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/devincloud"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"+ "github.com/spf13/cobra"+)++var cloudDevinCmd = &cobra.Command{+ Use: "devin",+ Short: "Devin Cloud agent telemetry",+}++var devinPullOpts struct {+ org string+ baseURL string+ state string+ logPath string+ print bool+ once bool+ watch bool+ interval time.Duration+ noUpload bool+ userMode bool+ systemMode bool+}++var cloudDevinPullCmd = &cobra.Command{+ Use: "pull",+ Short: "Pull all org Devin Cloud sessions and forward them as Beacon telemetry",+ Long: `Pull Devin Cloud (autonomous agent) telemetry org-wide via the Devin v3 API+and convert it into Beacon endpoint events.++Authenticates with an organization service key (cog_ prefix) so a single+centralized run captures every user's cloud sessions — no per-user or+per-sandbox setup. Set DEVIN_API_KEY (the service key) and DEVIN_ORG_ID+(or --org). When BEACON_CLOUD_GCS_* are set, each session's snapshot is also+uploaded to GCS, matching the layout used by the in-sandbox hook providers.++This command reaches the Devin API over the network; it is explicit and opt-in.`,+ SilenceUsage: true,+ RunE: runCloudDevinPull,+}++func init() {+ cloudCmd.AddCommand(cloudDevinCmd)+ cloudDevinCmd.AddCommand(cloudDevinPullCmd)++ f := cloudDevinPullCmd.Flags()+ f.StringVar(&devinPullOpts.org, "org", "", "Devin organization id (or DEVIN_ORG_ID)")+ f.StringVar(&devinPullOpts.baseURL, "base-url", devincloud.DefaultBaseURL, "Devin API base URL")+ f.StringVar(&devinPullOpts.state, "state", "", "Dedup state file path (default ~/.beacon/cloud/devin/<org>/state.json)")+ f.StringVar(&devinPullOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")+ f.BoolVar(&devinPullOpts.print, "print", false, "Print mapped events as JSON without writing or uploading (dry run)")+ f.BoolVar(&devinPullOpts.once, "once", true, "Run a single sweep and exit")+ f.BoolVar(&devinPullOpts.watch, "watch", false, "Poll continuously on --interval")+ f.DurationVar(&devinPullOpts.interval, "interval", time.Minute, "Poll interval for --watch")+ f.BoolVar(&devinPullOpts.noUpload, "no-upload", false, "Never upload to GCS even when BEACON_CLOUD_GCS_* is set")+ f.BoolVar(&devinPullOpts.userMode, "user", true, "Use per-user endpoint log paths")+ f.BoolVar(&devinPullOpts.systemMode, "system", false, "Use system endpoint log paths")+}++func runCloudDevinPull(cmd *cobra.Command, args []string) error {+ apiKey := strings.TrimSpace(os.Getenv("DEVIN_API_KEY"))+ if apiKey == "" {+ return fmt.Errorf("DEVIN_API_KEY is required (organization service key, cog_ prefix)")+ }+ org := strings.TrimSpace(devinPullOpts.org)+ if org == "" {+ org = strings.TrimSpace(os.Getenv("DEVIN_ORG_ID"))+ }+ if org == "" {+ return fmt.Errorf("--org or DEVIN_ORG_ID is required")+ }++ client := devincloud.New(org, apiKey, devincloud.WithBaseURL(devinPullOpts.baseURL))++ userMode := endpointDevinUserMode()+ opts := devincloud.PullOptions{+ Print: devinPullOpts.print,+ Out: cmd.OutOrStdout(),+ Write: !devinPullOpts.print,+ UserMode: userMode,+ UploadPrefix: devincloud.GCSPrefixFromEnv(),+ }+ // --print is a dry run: do not read or write dedup state (so every event is+ // shown on each run) and do not resolve a log path to write to.+ if !devinPullOpts.print {+ opts.StatePath = resolveDevinStatePath(devinPullOpts.state, org)+ opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, devinPullOpts.logPath).EffectiveLogPath+ }++ // Upload is optional: enabled when GCS env is configured and not in dry-run / --no-upload.+ if !devinPullOpts.print && !devinPullOpts.noUpload {+ uploader, ok, err := devincloud.NewGCSUploaderFromEnv()+ if err != nil {+ return err+ }+ if ok {+ opts.Upload = uploader+ }+ }++ ctx := cmd.Context()+ if ctx == nil {+ ctx = context.Background()+ }++ if devinPullOpts.watch && !devinPullOpts.print {+ return watchDevin(ctx, cmd, client, opts)+ }++ sum, err := devincloud.PullOnce(ctx, client, opts)+ if err != nil {+ return err+ }+ reportDevinSweep(cmd, sum)+ return nil+}++func watchDevin(ctx context.Context, cmd *cobra.Command, client *devincloud.Client, opts devincloud.PullOptions) error {+ interval := devinPullOpts.interval+ if interval < 5*time.Second {+ interval = 5 * time.Second+ }+ for {+ sum, err := devincloud.PullOnce(ctx, client, opts)+ if err != nil {+ fmt.Fprintf(cmd.ErrOrStderr(), "devin pull error: %v\n", err)+ } else {+ reportDevinSweep(cmd, sum)+ }+ select {+ case <-ctx.Done():+ return nil+ case <-time.After(interval):+ }+ }+}++func reportDevinSweep(cmd *cobra.Command, sum devincloud.Summary) {+ if devinPullOpts.print {+ return+ }+ fmt.Fprintf(cmd.OutOrStdout(), "devin pull: %d sessions, %d changed, %d events, %d uploaded\n",+ sum.Sessions, sum.SessionsChanged, sum.EventsEmitted, sum.Uploaded)+}++func endpointDevinUserMode() bool {+ if devinPullOpts.systemMode {+ return false+ }+ return devinPullOpts.userMode+}++func resolveDevinStatePath(override, org string) string {+ if strings.TrimSpace(override) != "" {+ return override+ }+ home, err := os.UserHomeDir()+ if err != nil {+ return ""+ }+ return fmt.Sprintf("%s/.beacon/cloud/devin/%s/state.json", home, org)+}diff --git a/cli/beacon/cmd/cloud_test.go b/cli/beacon/cmd/cloud_test.goindex ddc1d84b..8fe46e50 100644--- a/cli/beacon/cmd/cloud_test.go+++ b/cli/beacon/cmd/cloud_test.go@@ -13,6 +13,7 @@ func TestCloudCommandsRegistered(t *testing.T) {{"cloud", "claude-web", "print-setup"},{"cloud", "cursor", "print-hooks"},{"cloud", "cursor", "print-setup"},+ {"cloud", "devin", "pull"},{"cloud", "gcs", "setup"},} {cmd, _, err := rootCmd.Find(path)diff --git a/cli/beacon/internal/devincloud/client.go b/cli/beacon/internal/devincloud/client.gonew file mode 100644index 00000000..7fb353c4--- /dev/null+++ b/cli/beacon/internal/devincloud/client.go@@ -0,0 +1,235 @@+// Package devincloud pulls Devin Cloud (autonomous agent) telemetry from the+// Devin v3 organization API and maps it into Beacon endpoint events.+//+// The autonomous Devin Cloud agent does not run the Devin CLI hook engine, so+// in-sandbox capture is not possible. Instead an org-scoped service key+// (cog_ prefix) is used from a central runner to enumerate every user's+// sessions org-wide, which is what lets an organization self-manage telemetry+// capture for all of its cloud sessions from one place.+package devincloud++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strings"+ "time"+)++// DefaultBaseURL is the Devin API root.+const DefaultBaseURL = "https://api.devin.ai"++// Client is a read-only client for the Devin v3 organization API.+type Client struct {+ baseURL string+ orgID string+ apiKey string+ httpClient *http.Client+ maxRetries int+ retryWait time.Duration+}++// Option configures a Client.+type Option func(*Client)++// WithBaseURL overrides the API root (used in tests).+func WithBaseURL(u string) Option {+ return func(c *Client) {+ if strings.TrimSpace(u) != "" {+ c.baseURL = strings.TrimRight(u, "/")+ }+ }+}++// WithHTTPClient overrides the HTTP client.+func WithHTTPClient(h *http.Client) Option {+ return func(c *Client) {+ if h != nil {+ c.httpClient = h+ }+ }+}++// WithRetry tunes retry behaviour (0 wait disables sleeping, for tests).+func WithRetry(maxRetries int, wait time.Duration) Option {+ return func(c *Client) {+ c.maxRetries = maxRetries+ c.retryWait = wait+ }+}++// New constructs a Client. orgID is the "org-..." id; apiKey is the cog_ key.+func New(orgID, apiKey string, opts ...Option) *Client {+ c := &Client{+ baseURL: DefaultBaseURL,+ orgID: strings.TrimSpace(orgID),+ apiKey: strings.TrimSpace(apiKey),+ httpClient: &http.Client{Timeout: 30 * time.Second},+ maxRetries: 3,+ retryWait: 2 * time.Second,+ }+ for _, opt := range opts {+ opt(c)+ }+ return c+}++// Session is a Devin org session (verified shape from GET .../sessions).+type Session struct {+ SessionID string `json:"session_id"`+ URL string `json:"url"`+ Status string `json:"status"`+ StatusDetail string `json:"status_detail"`+ Title string `json:"title"`+ Tags []string `json:"tags"`+ UserID string `json:"user_id"`+ OrgID string `json:"org_id"`+ CreatedAt int64 `json:"created_at"`+ UpdatedAt int64 `json:"updated_at"`+ AcusConsumed float64 `json:"acus_consumed"`+ PullRequests []PullRequest `json:"pull_requests"`+ ParentSessionID *string `json:"parent_session_id"`+ ChildSessionIDs []string `json:"child_session_ids"`+ Origin string `json:"origin"`+ IsArchived bool `json:"is_archived"`+}++// PullRequest is a pull request attached to a session. Unknown fields are+// tolerated by the JSON decoder.+type PullRequest struct {+ URL string `json:"url"`+ Number int `json:"number,omitempty"`+}++// Message is a single session message (GET .../sessions/{id}/messages).+type Message struct {+ EventID string `json:"event_id"`+ Source string `json:"source"` // "user" | "devin"+ Message string `json:"message"`+ CreatedAt int64 `json:"created_at"`+}++type sessionsPage struct {+ Items []Session `json:"items"`+ EndCursor *string `json:"end_cursor"`+ HasNextPage bool `json:"has_next_page"`+ Total int `json:"total"`+}++type messagesPage struct {+ Items []Message `json:"items"`+ EndCursor *string `json:"end_cursor"`+ HasNextPage bool `json:"has_next_page"`+}++// ListSessions returns every session visible to the org service key, following+// cursor pagination.+func (c *Client) ListSessions(ctx context.Context) ([]Session, error) {+ var all []Session+ cursor := ""+ for {+ var page sessionsPage+ q := url.Values{}+ if cursor != "" {+ q.Set("cursor", cursor)+ }+ path := fmt.Sprintf("/v3/organizations/%s/sessions", url.PathEscape(c.orgID))+ if err := c.getJSON(ctx, path, q, &page); err != nil {+ return nil, err+ }+ all = append(all, page.Items...)+ if !page.HasNextPage || page.EndCursor == nil || *page.EndCursor == "" || *page.EndCursor == cursor {+ break+ }+ cursor = *page.EndCursor+ }+ return all, nil+}++// SessionMessages returns all messages for a session, following pagination.+func (c *Client) SessionMessages(ctx context.Context, sessionID string) ([]Message, error) {+ var all []Message+ cursor := ""+ for {+ var page messagesPage+ q := url.Values{}+ if cursor != "" {+ q.Set("cursor", cursor)+ }+ path := fmt.Sprintf("/v3/organizations/%s/sessions/%s/messages", url.PathEscape(c.orgID), url.PathEscape(sessionID))+ if err := c.getJSON(ctx, path, q, &page); err != nil {+ return nil, err+ }+ all = append(all, page.Items...)+ if !page.HasNextPage || page.EndCursor == nil || *page.EndCursor == "" || *page.EndCursor == cursor {+ break+ }+ cursor = *page.EndCursor+ }+ return all, nil+}++func (c *Client) getJSON(ctx context.Context, path string, q url.Values, out interface{}) error {+ if c.orgID == "" {+ return fmt.Errorf("devin org id is required")+ }+ if c.apiKey == "" {+ return fmt.Errorf("devin api key is required (set DEVIN_API_KEY)")+ }+ endpoint := c.baseURL + path+ if len(q) > 0 {+ endpoint += "?" + q.Encode()+ }++ var lastErr error+ for attempt := 0; attempt <= c.maxRetries; attempt++ {+ if attempt > 0 && c.retryWait > 0 {+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(c.retryWait * time.Duration(attempt)):+ }+ }+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)+ if err != nil {+ return err+ }+ req.Header.Set("Authorization", "Bearer "+c.apiKey)+ req.Header.Set("Accept", "application/json")++ resp, err := c.httpClient.Do(req)+ if err != nil {+ lastErr = err+ continue+ }+ body, readErr := io.ReadAll(io.LimitReader(resp.Body, 16*1024*1024))+ resp.Body.Close()+ if readErr != nil {+ lastErr = readErr+ continue+ }+ if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {+ lastErr = fmt.Errorf("devin api %s: %s", resp.Status, snippet(body))+ continue+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return fmt.Errorf("devin api %s: %s", resp.Status, snippet(body))+ }+ if err := json.Unmarshal(body, out); err != nil {+ return fmt.Errorf("decode devin response: %w", err)+ }+ return nil+ }+ return fmt.Errorf("devin api request failed after %d attempts: %w", c.maxRetries+1, lastErr)+}++func snippet(body []byte) string {+ s := strings.TrimSpace(string(body))+ if len(s) > 300 {+ return s[:300]+ }+ return s+}diff --git a/cli/beacon/internal/devincloud/client_test.go b/cli/beacon/internal/devincloud/client_test.gonew file mode 100644index 00000000..6d7b63d0--- /dev/null+++ b/cli/beacon/internal/devincloud/client_test.go@@ -0,0 +1,132 @@+package devincloud++import (+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"+)++const testOrg = "org-test123"++// fakeDevinAPI serves canned v3 responses for one org with the given sessions+// and per-session messages.+func fakeDevinAPI(t *testing.T, sessionsJSON string, messagesJSON map[string]string) *httptest.Server {+ t.Helper()+ mux := http.NewServeMux()+ mux.HandleFunc("/v3/organizations/"+testOrg+"/sessions", func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("Authorization") != "Bearer cog_test" {+ http.Error(w, `{"detail":"unauthorized"}`, http.StatusForbidden)+ return+ }+ _, _ = w.Write([]byte(sessionsJSON))+ })+ for sid, body := range messagesJSON {+ b := body+ mux.HandleFunc("/v3/organizations/"+testOrg+"/sessions/"+sid+"/messages", func(w http.ResponseWriter, r *http.Request) {+ _, _ = w.Write([]byte(b))+ })+ }+ return httptest.NewServer(mux)+}++func testClient(t *testing.T, srv *httptest.Server) *Client {+ t.Helper()+ return New(testOrg, "cog_test", WithBaseURL(srv.URL), WithRetry(1, 0))+}++func TestListSessionsParsesFields(t *testing.T) {+ srv := fakeDevinAPI(t, `{+ "items": [+ {"session_id":"s1","status":"suspended","status_detail":"inactivity","title":"T","user_id":"u1","org_id":"org-test123","created_at":100,"updated_at":200,"acus_consumed":1.5,"pull_requests":[{"url":"https://github.com/acme/widgets/pull/7","number":7}],"child_session_ids":["c1"]}+ ],+ "end_cursor": null,+ "has_next_page": false,+ "total": 1+ }`, nil)+ defer srv.Close()++ sessions, err := testClient(t, srv).ListSessions(context.Background())+ if err != nil {+ t.Fatalf("ListSessions: %v", err)+ }+ if len(sessions) != 1 {+ t.Fatalf("got %d sessions, want 1", len(sessions))+ }+ s := sessions[0]+ if s.SessionID != "s1" || s.Status != "suspended" || s.UserID != "u1" || s.AcusConsumed != 1.5 {+ t.Fatalf("unexpected session: %+v", s)+ }+ if s.CreatedAt != 100 || s.UpdatedAt != 200 {+ t.Fatalf("timestamps = %d/%d, want 100/200", s.CreatedAt, s.UpdatedAt)+ }+ if len(s.PullRequests) != 1 || s.PullRequests[0].Number != 7 {+ t.Fatalf("pull_requests = %+v", s.PullRequests)+ }+}++func TestListSessionsFollowsCursor(t *testing.T) {+ var calls int+ mux := http.NewServeMux()+ mux.HandleFunc("/v3/organizations/"+testOrg+"/sessions", func(w http.ResponseWriter, r *http.Request) {+ calls+++ if r.URL.Query().Get("cursor") == "" {+ _, _ = w.Write([]byte(`{"items":[{"session_id":"s1"}],"end_cursor":"CUR","has_next_page":true,"total":2}`))+ return+ }+ _, _ = w.Write([]byte(`{"items":[{"session_id":"s2"}],"end_cursor":null,"has_next_page":false,"total":2}`))+ })+ srv := httptest.NewServer(mux)+ defer srv.Close()++ sessions, err := New(testOrg, "cog_test", WithBaseURL(srv.URL), WithRetry(0, 0)).ListSessions(context.Background())+ if err != nil {+ t.Fatalf("ListSessions: %v", err)+ }+ if len(sessions) != 2 || sessions[0].SessionID != "s1" || sessions[1].SessionID != "s2" {+ t.Fatalf("pagination failed: %+v", sessions)+ }+ if calls != 2 {+ t.Fatalf("expected 2 page fetches, got %d", calls)+ }+}++func TestSessionMessagesParses(t *testing.T) {+ srv := fakeDevinAPI(t, `{"items":[],"has_next_page":false}`, map[string]string{+ "s1": `{"items":[+ {"event_id":"e1","source":"user","message":"hi","created_at":100},+ {"event_id":"e2","source":"devin","message":"hello","created_at":101}+ ],"end_cursor":null,"has_next_page":false}`,+ })+ defer srv.Close()++ msgs, err := testClient(t, srv).SessionMessages(context.Background(), "s1")+ if err != nil {+ t.Fatalf("SessionMessages: %v", err)+ }+ if len(msgs) != 2 || msgs[0].Source != "user" || msgs[1].Source != "devin" || msgs[0].EventID != "e1" {+ t.Fatalf("unexpected messages: %+v", msgs)+ }+}++func TestGetJSONErrorsOnForbidden(t *testing.T) {+ srv := fakeDevinAPI(t, `{"items":[]}`, nil)+ defer srv.Close()+ c := New(testOrg, "wrong-key", WithBaseURL(srv.URL), WithRetry(0, 0))+ _, err := c.ListSessions(context.Background())+ if err == nil || !strings.Contains(err.Error(), "403") {+ t.Fatalf("expected 403 error, got %v", err)+ }+}++func TestGetJSONRequiresOrgAndKey(t *testing.T) {+ if _, err := New("", "k").ListSessions(context.Background()); err == nil {+ t.Fatal("expected error for missing org")+ }+ if _, err := New("org-x", "").ListSessions(context.Background()); err == nil {+ t.Fatal("expected error for missing key")+ }+ _ = time.Second+}diff --git a/cli/beacon/internal/devincloud/mapper.go b/cli/beacon/internal/devincloud/mapper.gonew file mode 100644index 00000000..659f33be--- /dev/null+++ b/cli/beacon/internal/devincloud/mapper.go@@ -0,0 +1,182 @@+package devincloud++import (+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+)++// Provider is the BEACON_RUN_PROVIDER value for Devin Cloud telemetry. It+// partitions GCS objects and tags events, matching the value used by the+// in-sandbox hook providers for consistency.+const Provider = "devin_cloud"++// Harness is the harness name recorded on every Devin Cloud event.+const Harness = "devin"++// terminalStatuses mean the session is no longer actively working and a+// session.ended event should be emitted. Devin suspends sessions on inactivity+// once they finish a turn, so "suspended" is the common end state. "blocked"+// (awaiting input) and "working" are active and are not terminal.+var terminalStatuses = map[string]bool{+ "finished": true,+ "expired": true,+ "suspended": true,+}++// finalStatuses mean the session can never resume, so the connector can stop+// polling it. A "suspended" session may be resumed, so it is terminal (ended is+// emitted) but not final (keep polling cheaply via the updated_at check).+var finalStatuses = map[string]bool{+ "finished": true,+ "expired": true,+}++// MappedEvent pairs a Beacon event with a stable dedup id. Lifecycle events use+// synthetic ids (e.g. "<session>:started"); message events use the Devin+// event_id so re-polling never double-emits.+type MappedEvent struct {+ DedupID string+ Event schema.Event+}++// IsTerminal reports whether a session status means the session has ended (so+// a session.ended event should be emitted).+func IsTerminal(status string) bool {+ return terminalStatuses[strings.ToLower(strings.TrimSpace(status))]+}++// IsFinal reports whether a session can never resume, so the connector can stop+// polling it entirely.+func IsFinal(status string) bool {+ return finalStatuses[strings.ToLower(strings.TrimSpace(status))]+}++// MapSession converts a session and its messages into ordered Beacon events:+// session.started, one event per message (prompt.submitted / agent.message),+// and session.ended when the session has reached a terminal status.+func MapSession(s Session, msgs []Message) []MappedEvent {+ var out []MappedEvent++ out = append(out, MappedEvent{+ DedupID: s.SessionID + ":started",+ Event: sessionLifecycleEvent(s, "session.started", "Devin Cloud session started", s.CreatedAt),+ })++ for _, m := range msgs {+ switch strings.ToLower(m.Source) {+ case "user":+ ev := baseEvent(s, "prompt.submitted", "prompt", schema.SeverityInfo, m.CreatedAt)+ ev.Prompt = &schema.PromptInfo{Text: m.Message}+ ev.Content = &schema.ContentInfo{Retention: schema.ContentRetentionFull, Included: true}+ ev.Message = "Devin Cloud user prompt"+ out = append(out, MappedEvent{DedupID: m.EventID, Event: ev})+ default: // "devin" (assistant) and any future agent-side source+ ev := baseEvent(s, "agent.message", "session", schema.SeverityInfo, m.CreatedAt)+ ev.Content = &schema.ContentInfo{Retention: schema.ContentRetentionFull, Included: true}+ ev.Message = m.Message+ out = append(out, MappedEvent{DedupID: m.EventID, Event: ev})+ }+ }++ if IsTerminal(s.Status) {+ out = append(out, MappedEvent{+ DedupID: s.SessionID + ":ended",+ Event: sessionLifecycleEvent(s, "session.ended", "Devin Cloud session ended", s.UpdatedAt),+ })+ }+ return out+}++// sessionLifecycleEvent builds a started/ended event carrying session metadata.+func sessionLifecycleEvent(s Session, action, message string, tsUnix int64) schema.Event {+ ev := baseEvent(s, action, "session", schema.SeverityInfo, tsUnix)+ ev.Message = message+ meta := map[string]interface{}{+ "status": s.Status,+ "status_detail": s.StatusDetail,+ "acus_consumed": s.AcusConsumed,+ "url": s.URL,+ }+ if s.Title != "" {+ meta["title"] = s.Title+ }+ if len(s.Tags) > 0 {+ meta["tags"] = s.Tags+ }+ if s.ParentSessionID != nil && *s.ParentSessionID != "" {+ meta["parent_session_id"] = *s.ParentSessionID+ }+ if len(s.ChildSessionIDs) > 0 {+ meta["child_session_ids"] = s.ChildSessionIDs+ }+ if action == "session.ended" && s.CreatedAt > 0 && s.UpdatedAt >= s.CreatedAt {+ meta["duration_seconds"] = s.UpdatedAt - s.CreatedAt+ }+ if len(s.PullRequests) > 0 {+ prs := make([]map[string]interface{}, 0, len(s.PullRequests))+ for _, pr := range s.PullRequests {+ prs = append(prs, map[string]interface{}{"url": pr.URL, "number": pr.Number})+ }+ meta["pull_requests"] = prs+ }+ ev.Raw = map[string]interface{}{"devin": meta}+ return ev+}++// baseEvent constructs an event with the fields common to every Devin Cloud+// record: cloud origin, devin harness, run provider/id/actor, and the session+// id. ACUs are Devin compute units (not tokens or USD), so they are recorded in+// the devin-specific raw block rather than gen_ai.usage.+func baseEvent(s Session, action, category string, severity schema.Severity, tsUnix int64) schema.Event {+ repo := repoFromPullRequests(s.PullRequests)+ ev := schema.NewEvent(schema.NewEventOptions{+ Action: action,+ Category: category,+ Severity: severity,+ Harness: schema.HarnessInfo{Name: Harness},+ Origin: schema.OriginCloud,+ Run: &schema.RunInfo{+ Provider: Provider,+ RunID: s.SessionID,+ Actor: s.UserID,+ Repository: repo,+ },+ })+ if tsUnix > 0 {+ ev.Timestamp = time.Unix(tsUnix, 0).UTC().Format(time.RFC3339)+ }+ ev.Session = &schema.SessionInfo{ID: s.SessionID}+ if repo != "" {+ ev.Repository = repo+ }+ return ev+}++// repoFromPullRequests extracts "owner/repo" from the first GitHub-style PR URL.+func repoFromPullRequests(prs []PullRequest) string {+ for _, pr := range prs {+ if owner, repo, ok := parseRepoFromPRURL(pr.URL); ok {+ return owner + "/" + repo+ }+ }+ return ""+}++func parseRepoFromPRURL(prURL string) (owner, repo string, ok bool) {+ prURL = strings.TrimSpace(prURL)+ if prURL == "" {+ return "", "", false+ }+ idx := strings.Index(prURL, "://")+ if idx >= 0 {+ prURL = prURL[idx+3:]+ }+ parts := strings.Split(prURL, "/")+ // host/owner/repo/pull/<n>+ if len(parts) >= 3 && parts[1] != "" && parts[2] != "" {+ return parts[1], parts[2], true+ }+ return "", "", false+}diff --git a/cli/beacon/internal/devincloud/mapper_test.go b/cli/beacon/internal/devincloud/mapper_test.gonew file mode 100644index 00000000..000079d7--- /dev/null+++ b/cli/beacon/internal/devincloud/mapper_test.go@@ -0,0 +1,122 @@+package devincloud++import "testing"++func TestMapSessionProducesLifecycleAndMessages(t *testing.T) {+ s := Session{+ SessionID: "sess1",+ Status: "suspended",+ UserID: "user-1",+ CreatedAt: 1000,+ UpdatedAt: 1600,+ AcusConsumed: 2.5,+ PullRequests: []PullRequest{{URL: "https://github.com/acme/widgets/pull/7", Number: 7}},+ }+ msgs := []Message{+ {EventID: "e1", Source: "user", Message: "do the thing", CreatedAt: 1000},+ {EventID: "e2", Source: "devin", Message: "done", CreatedAt: 1100},+ }++ mapped := MapSession(s, msgs)+ if len(mapped) != 4 {+ t.Fatalf("got %d events, want 4 (started, prompt, agent, ended)", len(mapped))+ }++ wantActions := []string{"session.started", "prompt.submitted", "agent.message", "session.ended"}+ for i, want := range wantActions {+ if mapped[i].Event.Event.Action != want {+ t.Fatalf("event %d action = %q, want %q", i, mapped[i].Event.Event.Action, want)+ }+ }++ // Dedup ids: lifecycle synthetic, messages use event_id.+ wantIDs := []string{"sess1:started", "e1", "e2", "sess1:ended"}+ for i, want := range wantIDs {+ if mapped[i].DedupID != want {+ t.Fatalf("event %d dedup id = %q, want %q", i, mapped[i].DedupID, want)+ }+ }++ // Common fields.+ for _, me := range mapped {+ ev := me.Event+ if ev.Origin != "cloud" {+ t.Fatalf("origin = %q, want cloud", ev.Origin)+ }+ if ev.Harness.Name != "devin" {+ t.Fatalf("harness = %q, want devin", ev.Harness.Name)+ }+ if ev.Run == nil || ev.Run.Provider != "devin_cloud" || ev.Run.RunID != "sess1" || ev.Run.Actor != "user-1" {+ t.Fatalf("run = %+v", ev.Run)+ }+ if ev.Run.Repository != "acme/widgets" {+ t.Fatalf("repository = %q, want acme/widgets", ev.Run.Repository)+ }+ if err := ev.Validate(); err != nil {+ t.Fatalf("event %q failed Validate: %v", ev.Event.Action, err)+ }+ }++ // Prompt text + devin message content.+ if mapped[1].Event.Prompt == nil || mapped[1].Event.Prompt.Text != "do the thing" {+ t.Fatalf("prompt text not mapped: %+v", mapped[1].Event.Prompt)+ }+ if mapped[2].Event.Message != "done" {+ t.Fatalf("agent message = %q, want done", mapped[2].Event.Message)+ }++ // Timestamps come from the source unix times.+ if mapped[0].Event.Timestamp != "1970-01-01T00:16:40Z" {+ t.Fatalf("started ts = %q, want session created_at", mapped[0].Event.Timestamp)+ }++ // Ended carries metadata.+ ended := mapped[3].Event+ devin, _ := ended.Raw["devin"].(map[string]interface{})+ if devin == nil || devin["acus_consumed"] != 2.5 {+ t.Fatalf("ended raw.devin = %+v", ended.Raw)+ }+ if devin["duration_seconds"] != int64(600) {+ t.Fatalf("duration = %v, want 600", devin["duration_seconds"])+ }+}++func TestMapSessionNonTerminalHasNoEnded(t *testing.T) {+ s := Session{SessionID: "sess2", Status: "working", UserID: "u", CreatedAt: 10}+ mapped := MapSession(s, nil)+ if len(mapped) != 1 || mapped[0].Event.Event.Action != "session.started" {+ t.Fatalf("working session should only emit session.started, got %d events", len(mapped))+ }+}++func TestStatusClassification(t *testing.T) {+ for _, st := range []string{"finished", "expired", "suspended"} {+ if !IsTerminal(st) {+ t.Fatalf("IsTerminal(%q) = false, want true", st)+ }+ }+ for _, st := range []string{"working", "blocked"} {+ if IsTerminal(st) {+ t.Fatalf("IsTerminal(%q) = true, want false", st)+ }+ }+ if IsFinal("suspended") {+ t.Fatal("suspended should not be final (may resume)")+ }+ if !IsFinal("finished") {+ t.Fatal("finished should be final")+ }+}++func TestObjectNameLayout(t *testing.T) {+ got := ObjectName("agent-traces/team=x", "devin_cloud", "user-1", "sess-9")+ want := "agent-traces/team=x/provider=devin_cloud/user_id=user-1/run_id=sess-9/runtime.jsonl"+ if got != want {+ t.Fatalf("ObjectName = %q, want %q", got, want)+ }+ got2 := ObjectName("", "devin_cloud", "", "")+ want2 := "provider=devin_cloud/user_id=unknown/run_id=unknown/runtime.jsonl"+ if got2 != want2 {+ t.Fatalf("ObjectName empties = %q, want %q", got2, want2)+ }+}diff --git a/cli/beacon/internal/devincloud/pull.go b/cli/beacon/internal/devincloud/pull.gonew file mode 100644index 00000000..137cb390--- /dev/null+++ b/cli/beacon/internal/devincloud/pull.go@@ -0,0 +1,187 @@+package devincloud++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "path"+ "sort"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"+)++// Uploader uploads one session's full JSONL snapshot to a destination (GCS).+type Uploader interface {+ Upload(ctx context.Context, objectName string, data []byte) error+}++// PullOptions configures a single pull sweep.+type PullOptions struct {+ Print bool // print mapped events as JSON to Out (dry run)+ Out io.Writer // where --print writes (defaults handled by caller)+ Write bool // append new events to the local runtime JSONL+ LogPath string // runtime JSONL path (resolved by caller)+ UserMode bool // writer user/system mode+ StatePath string // dedup state file (empty = no persistence)++ Upload Uploader // optional GCS uploader+ UploadPrefix string // GCS object prefix (e.g. "agent-traces")+}++// Summary reports what a sweep did.+type Summary struct {+ Sessions int+ SessionsChanged int+ EventsEmitted int+ Uploaded int+}++// PullOnce performs one sweep: list sessions, fetch messages for changed+// sessions, map to Beacon events, emit new ones (print/write), and upload each+// changed session's full snapshot. State makes it idempotent across runs.+func PullOnce(ctx context.Context, client *Client, opts PullOptions) (Summary, error) {+ var sum Summary++ state, err := LoadState(opts.StatePath)+ if err != nil {+ return sum, fmt.Errorf("load state: %w", err)+ }++ sessions, err := client.ListSessions(ctx)+ if err != nil {+ return sum, err+ }+ sum.Sessions = len(sessions)++ for _, s := range sessions {+ ss := state.get(s.SessionID)+ // Skip sessions already finalized, or unchanged since last sweep.+ if ss.Done {+ continue+ }+ if _, seen := state.Sessions[s.SessionID]; seen && ss.UpdatedAt == s.UpdatedAt && ss.Status == s.Status && len(ss.Emitted) > 0 {+ continue+ }++ msgs, err := client.SessionMessages(ctx, s.SessionID)+ if err != nil {+ return sum, fmt.Errorf("session %s messages: %w", s.SessionID, err)+ }+ sort.SliceStable(msgs, func(i, j int) bool { return msgs[i].CreatedAt < msgs[j].CreatedAt })++ mapped := MapSession(s, msgs)+ sum.SessionsChanged++++ for _, me := range mapped {+ if ss.Emitted[me.DedupID] {+ continue+ }+ if err := emit(me.Event, opts); err != nil {+ return sum, err+ }+ ss.Emitted[me.DedupID] = true+ sum.EventsEmitted+++ }++ if opts.Upload != nil {+ data, err := marshalEvents(mapped)+ if err != nil {+ return sum, err+ }+ obj := ObjectName(opts.UploadPrefix, Provider, s.UserID, s.SessionID)+ if err := opts.Upload.Upload(ctx, obj, data); err != nil {+ return sum, fmt.Errorf("upload session %s: %w", s.SessionID, err)+ }+ sum.Uploaded+++ }++ ss.UpdatedAt = s.UpdatedAt+ ss.Status = s.Status+ if IsFinal(s.Status) && ss.Emitted[s.SessionID+":ended"] {+ ss.Done = true+ }+ }++ if err := state.Save(opts.StatePath); err != nil {+ return sum, fmt.Errorf("save state: %w", err)+ }+ return sum, nil+}++func emit(ev schema.Event, opts PullOptions) error {+ if opts.Print && opts.Out != nil {+ data, err := json.Marshal(ev)+ if err != nil {+ return err+ }+ if _, err := opts.Out.Write(append(data, '\n')); err != nil {+ return err+ }+ }+ if opts.Write {+ if _, err := writer.AppendEvent(ev, writer.Options{Path: opts.LogPath, UserMode: opts.UserMode}); err != nil {+ return err+ }+ }+ return nil+}++func marshalEvents(mapped []MappedEvent) ([]byte, error) {+ var buf []byte+ for _, me := range mapped {+ data, err := json.Marshal(me.Event)+ if err != nil {+ return nil, err+ }+ buf = append(buf, data...)+ buf = append(buf, '\n')+ }+ return buf, nil+}++// ObjectName builds the GCS object path, matching the layout used by the+// in-sandbox hook providers: {prefix}/provider=.../user_id=.../run_id=.../runtime.jsonl+func ObjectName(prefix, provider, userID, sessionID string) string {+ parts := []string{}+ for _, p := range splitNonEmpty(prefix) {+ parts = append(parts, p)+ }+ parts = append(parts, "provider="+defaultIfEmpty(provider, "unknown"))+ parts = append(parts, "user_id="+defaultIfEmpty(userID, "unknown"))+ parts = append(parts, "run_id="+defaultIfEmpty(sessionID, "unknown"))+ parts = append(parts, "runtime.jsonl")+ return path.Join(parts...)+}++func splitNonEmpty(prefix string) []string {+ var out []string+ for _, p := range splitSlash(prefix) {+ if p != "" {+ out = append(out, p)+ }+ }+ return out+}++func splitSlash(s string) []string {+ var out []string+ cur := ""+ for _, r := range s {+ if r == '/' {+ out = append(out, cur)+ cur = ""+ continue+ }+ cur += string(r)+ }+ return append(out, cur)+}++func defaultIfEmpty(v, d string) string {+ if v == "" {+ return d+ }+ return v+}diff --git a/cli/beacon/internal/devincloud/pull_test.go b/cli/beacon/internal/devincloud/pull_test.gonew file mode 100644index 00000000..820c658f--- /dev/null+++ b/cli/beacon/internal/devincloud/pull_test.go@@ -0,0 +1,123 @@+package devincloud++import (+ "context"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++type fakeUploader struct {+ objects map[string][]byte+ calls int+}++func (f *fakeUploader) Upload(_ context.Context, objectName string, data []byte) error {+ if f.objects == nil {+ f.objects = map[string][]byte{}+ }+ f.objects[objectName] = data+ f.calls+++ return nil+}++func pullTestServer(t *testing.T) *Client {+ srv := fakeDevinAPI(t, `{"items":[+ {"session_id":"s1","status":"suspended","user_id":"user-1","created_at":1000,"updated_at":1600,"acus_consumed":1}+ ],"has_next_page":false,"total":1}`, map[string]string{+ "s1": `{"items":[+ {"event_id":"e1","source":"user","message":"prompt one","created_at":1000},+ {"event_id":"e2","source":"devin","message":"reply one","created_at":1100}+ ],"has_next_page":false}`,+ })+ t.Cleanup(srv.Close)+ return testClient(t, srv)+}++func TestPullOnceWritesAndUploads(t *testing.T) {+ dir := t.TempDir()+ logPath := filepath.Join(dir, "runtime.jsonl")+ statePath := filepath.Join(dir, "state.json")+ up := &fakeUploader{}++ client := pullTestServer(t)+ sum, err := PullOnce(context.Background(), client, PullOptions{+ Write: true,+ LogPath: logPath,+ StatePath: statePath,+ Upload: up,+ UploadPrefix: "agent-traces",+ })+ if err != nil {+ t.Fatalf("PullOnce: %v", err)+ }+ // started + prompt + agent + ended = 4+ if sum.EventsEmitted != 4 || sum.SessionsChanged != 1 || sum.Uploaded != 1 {+ t.Fatalf("summary = %+v, want 4 events / 1 changed / 1 uploaded", sum)+ }++ lines := nonEmptyLines(t, logPath)+ if len(lines) != 4 {+ t.Fatalf("log has %d lines, want 4", len(lines))+ }++ wantObj := "agent-traces/provider=devin_cloud/user_id=user-1/run_id=s1/runtime.jsonl"+ body, ok := up.objects[wantObj]+ if !ok {+ t.Fatalf("uploaded object %q missing; have %v", wantObj, keys(up.objects))+ }+ if got := len(nonEmptyLinesBytes(body)); got != 4 {+ t.Fatalf("uploaded object has %d lines, want 4", got)+ }+}++func TestPullOnceDedupsAcrossRuns(t *testing.T) {+ dir := t.TempDir()+ logPath := filepath.Join(dir, "runtime.jsonl")+ statePath := filepath.Join(dir, "state.json")+ client := pullTestServer(t)++ opts := PullOptions{Write: true, LogPath: logPath, StatePath: statePath}+ if _, err := PullOnce(context.Background(), client, opts); err != nil {+ t.Fatalf("first PullOnce: %v", err)+ }+ sum, err := PullOnce(context.Background(), client, opts)+ if err != nil {+ t.Fatalf("second PullOnce: %v", err)+ }+ // Unchanged session → skipped entirely on the second sweep.+ if sum.EventsEmitted != 0 || sum.SessionsChanged != 0 {+ t.Fatalf("second sweep emitted %+v, want zero (dedup)", sum)+ }+ if len(nonEmptyLines(t, logPath)) != 4 {+ t.Fatalf("log grew on re-run; dedup failed")+ }+}++func nonEmptyLines(t *testing.T, path string) []string {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ return nonEmptyLinesBytes(data)+}++func nonEmptyLinesBytes(data []byte) []string {+ var out []string+ for _, l := range strings.Split(string(data), "\n") {+ if strings.TrimSpace(l) != "" {+ out = append(out, l)+ }+ }+ return out+}++func keys(m map[string][]byte) []string {+ var out []string+ for k := range m {+ out = append(out, k)+ }+ return out+}diff --git a/cli/beacon/internal/devincloud/state.go b/cli/beacon/internal/devincloud/state.gonew file mode 100644index 00000000..b0c10270--- /dev/null+++ b/cli/beacon/internal/devincloud/state.go@@ -0,0 +1,75 @@+package devincloud++import (+ "encoding/json"+ "os"+ "path/filepath"+)++// State tracks, per org, which session events have already been emitted so that+// re-polling is idempotent. It is a small JSON file managed by the connector.+type State struct {+ Sessions map[string]*SessionState `json:"sessions"`+}++// SessionState records progress for one session.+type SessionState struct {+ UpdatedAt int64 `json:"updated_at"`+ Status string `json:"status"`+ Done bool `json:"done"` // terminal status + ended emitted; skip henceforth+ Emitted map[string]bool `json:"emitted"`+}++// LoadState reads state from path. A missing file yields empty state. An empty+// path yields empty, non-persisted state.+func LoadState(path string) (*State, error) {+ s := &State{Sessions: map[string]*SessionState{}}+ if path == "" {+ return s, nil+ }+ data, err := os.ReadFile(path)+ if err != nil {+ if os.IsNotExist(err) {+ return s, nil+ }+ return nil, err+ }+ if err := json.Unmarshal(data, s); err != nil {+ return nil, err+ }+ if s.Sessions == nil {+ s.Sessions = map[string]*SessionState{}+ }+ return s, nil+}++// Save writes state to path atomically. A nil/empty path is a no-op.+func (s *State) Save(path string) error {+ if path == "" {+ return nil+ }+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ return err+ }+ data, err := json.MarshalIndent(s, "", " ")+ if err != nil {+ return err+ }+ tmp := path + ".tmp"+ if err := os.WriteFile(tmp, data, 0o600); err != nil {+ return err+ }+ return os.Rename(tmp, path)+}++func (s *State) get(sessionID string) *SessionState {+ ss := s.Sessions[sessionID]+ if ss == nil {+ ss = &SessionState{Emitted: map[string]bool{}}+ s.Sessions[sessionID] = ss+ }+ if ss.Emitted == nil {+ ss.Emitted = map[string]bool{}+ }+ return ss+}diff --git a/cli/beacon/internal/devincloud/upload.go b/cli/beacon/internal/devincloud/upload.gonew file mode 100644index 00000000..cedcd87a--- /dev/null+++ b/cli/beacon/internal/devincloud/upload.go@@ -0,0 +1,230 @@+package devincloud++import (+ "bytes"+ "context"+ "crypto"+ "crypto/rand"+ "crypto/rsa"+ "crypto/sha256"+ "crypto/x509"+ "encoding/base64"+ "encoding/json"+ "encoding/pem"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "os"+ "strings"+ "time"+)++const (+ defaultGCSEndpoint = "https://storage.googleapis.com"+ gcsScope = "https://www.googleapis.com/auth/devstorage.read_write"+ uploadContentType = "text/plain; charset=utf-8"+ // DefaultGCSPrefix matches the prefix used by the in-sandbox hook providers.+ DefaultGCSPrefix = "agent-traces"+)++// GCSUploader PUTs JSONL snapshots to a GCS bucket using a service-account key+// (signed-JWT auth). It is a self-contained port of the beacon-hooks+// cloudshuttle uploader, which lives in an internal package the beacon CLI+// cannot import. Auth uses BEACON_CLOUD_GCS_CREDENTIALS_B64 — the same secret+// the hook providers use — so the binary needs no gcloud and no Google SDK.+type GCSUploader struct {+ bucket string+ endpoint string+ account serviceAccount+ httpClient *http.Client++ token string+ tokenAt time.Time+}++type serviceAccount struct {+ ClientEmail string `json:"client_email"`+ PrivateKey string `json:"private_key"`+ TokenURI string `json:"token_uri"`+}++type tokenResponse struct {+ AccessToken string `json:"access_token"`+ ExpiresIn int `json:"expires_in"`+}++// GCSPrefixFromEnv returns the configured object prefix or the default.+func GCSPrefixFromEnv() string {+ if p := strings.Trim(strings.TrimSpace(os.Getenv("BEACON_CLOUD_GCS_PREFIX")), "/"); p != "" {+ return p+ }+ return DefaultGCSPrefix+}++// NewGCSUploaderFromEnv builds an uploader from BEACON_CLOUD_GCS_* env vars.+// The bool is false (with nil uploader, nil error) when GCS is not configured,+// so callers can treat upload as optional.+func NewGCSUploaderFromEnv() (*GCSUploader, bool, error) {+ bucket := strings.TrimSpace(os.Getenv("BEACON_CLOUD_GCS_BUCKET"))+ credsB64 := strings.TrimSpace(os.Getenv("BEACON_CLOUD_GCS_CREDENTIALS_B64"))+ if bucket == "" && credsB64 == "" {+ return nil, false, nil+ }+ if bucket == "" || credsB64 == "" {+ return nil, false, errors.New("both BEACON_CLOUD_GCS_BUCKET and BEACON_CLOUD_GCS_CREDENTIALS_B64 are required for upload")+ }+ credsJSON, err := base64.StdEncoding.DecodeString(credsB64)+ if err != nil {+ return nil, false, fmt.Errorf("decode BEACON_CLOUD_GCS_CREDENTIALS_B64: %w", err)+ }+ var acct serviceAccount+ if err := json.Unmarshal(credsJSON, &acct); err != nil {+ return nil, false, fmt.Errorf("parse GCS credentials JSON: %w", err)+ }+ if acct.ClientEmail == "" || acct.PrivateKey == "" || acct.TokenURI == "" {+ return nil, false, errors.New("GCS credentials missing client_email/private_key/token_uri")+ }+ endpoint := strings.TrimSpace(os.Getenv("BEACON_CLOUD_GCS_ENDPOINT"))+ if endpoint == "" {+ endpoint = defaultGCSEndpoint+ }+ return &GCSUploader{+ bucket: bucket,+ endpoint: endpoint,+ account: acct,+ httpClient: &http.Client{Timeout: 30 * time.Second},+ }, true, nil+}++// Upload PUTs data to {endpoint}/{bucket}/{objectName}.+func (u *GCSUploader) Upload(ctx context.Context, objectName string, data []byte) error {+ token, err := u.accessToken(ctx)+ if err != nil {+ return err+ }+ uploadURL := strings.TrimRight(u.endpoint, "/") + "/" + escapePath(u.bucket) + "/" + escapeObjectName(objectName)+ req, err := http.NewRequestWithContext(ctx, http.MethodPut, uploadURL, bytes.NewReader(data))+ if err != nil {+ return err+ }+ req.ContentLength = int64(len(data))+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("Content-Type", uploadContentType)+ resp, err := u.httpClient.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 64*1024))+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return fmt.Errorf("GCS upload failed: %s: %s", resp.Status, strings.TrimSpace(string(body)))+ }+ return nil+}++func (u *GCSUploader) accessToken(ctx context.Context) (string, error) {+ if u.token != "" && time.Since(u.tokenAt) < 45*time.Minute {+ return u.token, nil+ }+ assertion, err := signedJWT(u.account)+ if err != nil {+ return "", err+ }+ form := url.Values{}+ form.Set("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer")+ form.Set("assertion", assertion)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.account.TokenURI, strings.NewReader(form.Encode()))+ if err != nil {+ return "", err+ }+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ resp, err := u.httpClient.Do(req)+ if err != nil {+ return "", err+ }+ defer resp.Body.Close()+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 64*1024))+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return "", fmt.Errorf("GCS token exchange failed: %s: %s", resp.Status, strings.TrimSpace(string(body)))+ }+ var tok tokenResponse+ if err := json.Unmarshal(body, &tok); err != nil {+ return "", fmt.Errorf("parse GCS token response: %w", err)+ }+ if tok.AccessToken == "" {+ return "", errors.New("GCS token response missing access_token")+ }+ u.token = tok.AccessToken+ u.tokenAt = time.Now()+ return u.token, nil+}++func signedJWT(account serviceAccount) (string, error) {+ now := time.Now().Unix()+ header := map[string]string{"alg": "RS256", "typ": "JWT"}+ claims := map[string]interface{}{+ "iss": account.ClientEmail,+ "scope": gcsScope,+ "aud": account.TokenURI,+ "iat": now,+ "exp": now + 3600,+ }+ encodedHeader, err := encodeJSONSegment(header)+ if err != nil {+ return "", err+ }+ encodedClaims, err := encodeJSONSegment(claims)+ if err != nil {+ return "", err+ }+ signingInput := encodedHeader + "." + encodedClaims+ privateKey, err := parseRSAPrivateKey(account.PrivateKey)+ if err != nil {+ return "", err+ }+ sum := sha256.Sum256([]byte(signingInput))+ signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, sum[:])+ if err != nil {+ return "", err+ }+ return signingInput + "." + base64.RawURLEncoding.EncodeToString(signature), nil+}++func encodeJSONSegment(value interface{}) (string, error) {+ data, err := json.Marshal(value)+ if err != nil {+ return "", err+ }+ return base64.RawURLEncoding.EncodeToString(data), nil+}++func parseRSAPrivateKey(raw string) (*rsa.PrivateKey, error) {+ block, _ := pem.Decode([]byte(raw))+ if block == nil {+ return nil, errors.New("GCS private key is not PEM encoded")+ }+ if key, err := x509.ParsePKCS8PrivateKey(block.Bytes); err == nil {+ if rsaKey, ok := key.(*rsa.PrivateKey); ok {+ return rsaKey, nil+ }+ return nil, errors.New("GCS private key is not RSA")+ }+ if key, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {+ return key, nil+ }+ return nil, errors.New("parse GCS private key")+}++func escapeObjectName(objectName string) string {+ parts := strings.Split(objectName, "/")+ for i, part := range parts {+ parts[i] = escapePath(part)+ }+ return strings.Join(parts, "/")+}++func escapePath(value string) string {+ return (&url.URL{Path: value}).EscapedPath()+}diff --git a/cli/beacon/internal/devincloud/upload_test.go b/cli/beacon/internal/devincloud/upload_test.gonew file mode 100644index 00000000..b9af7fc0--- /dev/null+++ b/cli/beacon/internal/devincloud/upload_test.go@@ -0,0 +1,101 @@+package devincloud++import (+ "context"+ "crypto/rand"+ "crypto/rsa"+ "crypto/x509"+ "encoding/base64"+ "encoding/json"+ "encoding/pem"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestGCSUploaderSignsJWTAndPuts(t *testing.T) {+ key, err := rsa.GenerateKey(rand.Reader, 2048)+ if err != nil {+ t.Fatalf("gen key: %v", err)+ }+ pkcs8, err := x509.MarshalPKCS8PrivateKey(key)+ if err != nil {+ t.Fatalf("marshal key: %v", err)+ }+ keyPEM := string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}))++ var gotPath, gotAuth, gotType, gotBody string+ var tokenForm string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case strings.HasSuffix(r.URL.Path, "/token"):+ _ = r.ParseForm()+ tokenForm = r.Form.Encode()+ _ = json.NewEncoder(w).Encode(map[string]interface{}{"access_token": "tkn", "expires_in": 3600})+ default:+ gotPath = r.URL.EscapedPath()+ gotAuth = r.Header.Get("Authorization")+ gotType = r.Header.Get("Content-Type")+ b, _ := io.ReadAll(r.Body)+ gotBody = string(b)+ w.WriteHeader(http.StatusOK)+ }+ }))+ defer srv.Close()++ creds := serviceAccount{+ ClientEmail: "[email protected]",+ PrivateKey: keyPEM,+ TokenURI: srv.URL + "/token",+ }+ credsJSON, _ := json.Marshal(creds)++ t.Setenv("BEACON_CLOUD_GCS_BUCKET", "bucket")+ t.Setenv("BEACON_CLOUD_GCS_CREDENTIALS_B64", base64.StdEncoding.EncodeToString(credsJSON))+ t.Setenv("BEACON_CLOUD_GCS_ENDPOINT", srv.URL)++ up, ok, err := NewGCSUploaderFromEnv()+ if err != nil || !ok {+ t.Fatalf("NewGCSUploaderFromEnv ok=%v err=%v", ok, err)+ }++ obj := ObjectName("agent-traces", Provider, "user-1", "sess-1")+ if err := up.Upload(context.Background(), obj, []byte("{\"event\":\"ok\"}\n")); err != nil {+ t.Fatalf("Upload: %v", err)+ }++ if !strings.Contains(tokenForm, "grant_type=urn") || !strings.Contains(tokenForm, "assertion=") {+ t.Fatalf("token form unexpected: %s", tokenForm)+ }+ if gotAuth != "Bearer tkn" {+ t.Fatalf("auth = %q, want Bearer tkn", gotAuth)+ }+ if gotType != uploadContentType {+ t.Fatalf("content-type = %q, want %q", gotType, uploadContentType)+ }+ if !strings.Contains(gotPath, "/bucket/agent-traces/provider=devin_cloud/user_id=user-1/run_id=sess-1/runtime.jsonl") {+ t.Fatalf("upload path = %q", gotPath)+ }+ if gotBody != "{\"event\":\"ok\"}\n" {+ t.Fatalf("body = %q", gotBody)+ }+}++func TestNewGCSUploaderUnconfigured(t *testing.T) {+ t.Setenv("BEACON_CLOUD_GCS_BUCKET", "")+ t.Setenv("BEACON_CLOUD_GCS_CREDENTIALS_B64", "")+ up, ok, err := NewGCSUploaderFromEnv()+ if up != nil || ok || err != nil {+ t.Fatalf("unconfigured = (%v,%v,%v), want (nil,false,nil)", up, ok, err)+ }+}++func TestNewGCSUploaderPartialConfigErrors(t *testing.T) {+ t.Setenv("BEACON_CLOUD_GCS_BUCKET", "bucket")+ t.Setenv("BEACON_CLOUD_GCS_CREDENTIALS_B64", "")+ if _, _, err := NewGCSUploaderFromEnv(); err == nil {+ t.Fatal("expected error when only bucket is set")+ }+}