An open-source, faster Devin alternative
TypeScript
feat(billing): exempt subscribed-agent sandboxes from usage metering
motatoes33266f67901f
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 111a8693..017bcb8a 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -136,7 +136,7 @@ func (s *Server) createSandbox(c echo.Context) error {// on the fork. User envs override checkpoint's stored envs.// Secret store: if checkpoint has none, user can attach one at fork time.// If checkpoint already has one, user cannot override it.- result, status, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore)+ result, status, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata)if cpErr != nil {return c.JSON(status, map[string]string{"error": cpErr.Error()})}@@ -292,7 +292,7 @@ func (s *Server) createSandboxWithSSE(c echo.Context, ctx context.Context, orgIDc.SetParamNames("checkpointId")c.SetParamValues(checkpointID.String())- result, _, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore)+ result, _, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata)if cpErr != nil {emit("error", map[string]string{"error": cpErr.Error()})return nil@@ -2090,15 +2090,19 @@ func (s *Server) restoreCheckpoint(c echo.Context) error {// createFromCheckpoint creates a new sandbox from an existing checkpoint (fork).func (s *Server) createFromCheckpoint(c echo.Context) error {- // Direct route (POST /sandboxes/from-checkpoint/:checkpointId): only the- // envs override is currently supported on the fork path; everything else- // is inherited from the checkpoint's stored config.+ // Direct route (POST /sandboxes/from-checkpoint/:checkpointId): the+ // envs / secretStore / metadata fields are supported on the fork path;+ // everything else is inherited from the checkpoint's stored config.+ // Metadata is merged onto the checkpoint's persisted metadata+ // (caller wins) so callers can stamp identifiers like agent_id without+ // losing whatever the snapshot author originally set.var body struct {Envs map[string]string `json:"envs"`SecretStore string `json:"secretStore"`+ Metadata map[string]string `json:"metadata"`}_ = c.Bind(&body)- result, httpStatus, err := s.createFromCheckpointCore(c, body.Envs, body.SecretStore)+ result, httpStatus, err := s.createFromCheckpointCore(c, body.Envs, body.SecretStore, body.Metadata)if err != nil {return c.JSON(httpStatus, map[string]string{"error": err.Error()})}@@ -2119,7 +2123,12 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {//// userEnvs (may be nil) overrides the envs from the checkpoint's stored config.// User keys win over keys re-resolved from the secret store.-func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]string, userSecretStore string) (map[string]interface{}, int, error) {+//+// userMetadata (may be nil) is merged into the checkpoint's persisted+// metadata before the sandbox session row is recorded — so callers can+// stamp request-time identifiers (e.g. agent_id) without losing whatever+// the snapshot author baked in.+func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]string, userSecretStore string, userMetadata map[string]string) (map[string]interface{}, int, error) {checkpointIDStr := c.Param("checkpointId")ctx := c.Request().Context()@@ -2378,7 +2387,17 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]sttemplate = "default"}cfgJSON, _ := json.Marshal(cfgForPersistence(originalCfg))- metadataJSON, _ := json.Marshal(originalCfg.Metadata)+ // Merge user-supplied metadata onto the snapshot's metadata (user wins)+ // so request-time labels (e.g. agent_id) end up on the session row,+ // where the billing path can find them via metadata->>'agent_id'.+ mergedMeta := map[string]string{}+ for k, v := range originalCfg.Metadata {+ mergedMeta[k] = v+ }+ for k, v := range userMetadata {+ mergedMeta[k] = v+ }+ metadataJSON, _ := json.Marshal(mergedMeta)_, _ = s.store.CreateSandboxSession(ctx, sandboxID, orgID, auth.GetUserID(c), template, region, workerID, cfgJSON, metadataJSON)// Set golden version from worker heartbeatif s.workerRegistry != nil {diff --git a/internal/db/billable_events.go b/internal/db/billable_events.goindex 48549d82..a0bc014a 100644--- a/internal/db/billable_events.go+++ b/internal/db/billable_events.go@@ -297,13 +297,28 @@ func (s *Store) GetReservedGBForBucket(ctx context.Context, orgID uuid.UUID, buc// overlaps `[bucketStart, bucketEnd)` for the given org. Open events// (`ended_at IS NULL`) are returned with `EndedAt = nil`; the caller// clips them to the bucket boundary.+//+// Sandboxes that back a managed agent with an active per-agent+// subscription are excluded — their compute is paid for by the+// subscription, so they must not also flow through reserved/overage+// metering. See the same NOT EXISTS in GetOrgUsage for rationale.func (s *Store) GetScaleEventsForBucket(ctx context.Context, orgID uuid.UUID, bucketStart, bucketEnd time.Time) ([]ScaleEvent, error) {rows, err := s.pool.Query(ctx, `SELECT id, sandbox_id, org_id, memory_mb, cpu_percent, disk_mb, started_at, ended_at- FROM sandbox_scale_events+ FROM sandbox_scale_events seWHERE org_id = $1AND started_at < $3AND (ended_at IS NULL OR ended_at > $2)+ AND NOT EXISTS (+ SELECT 1+ FROM sandbox_sessions ss+ JOIN agent_subscriptions asub+ ON asub.org_id = ss.org_id+ AND asub.agent_id = ss.metadata->>'agent_id'+ AND asub.status IN ('active', 'trialing', 'past_due', 'incomplete')+ WHERE ss.sandbox_id = se.sandbox_id+ AND ss.metadata->>'agent_id' IS NOT NULL+ )ORDER BY started_at`, orgID, bucketStart, bucketEnd)if err != nil {diff --git a/internal/db/usage.go b/internal/db/usage.goindex 2260d533..5f172ce6 100644--- a/internal/db/usage.go+++ b/internal/db/usage.go@@ -172,14 +172,35 @@ type OrgUsageSummary struct {}// GetOrgUsage returns billing summary for an org.+//+// Sandboxes that back a managed agent with an active per-agent subscription+// (e.g. the $20/mo Telegram plan) are *excluded* from this aggregation —+// the subscription is meant to cover the underlying compute, so we mustn't+// also bill the org's compute meter or deduct trial credits for it.+//+// The link is sandbox_sessions.metadata.agent_id, which sessions-api stamps+// at sandbox-create time for managed agents. If a sandbox row is missing+// (rare race during creation) or has no agent_id, the EXISTS check+// short-circuits and the scale event is billed normally — i.e. the default+// is "bill it", which keeps us safe in all the unknown cases.func (s *Store) GetOrgUsage(ctx context.Context, orgID string, from, to time.Time) ([]OrgUsageSummary, error) {rows, err := s.pool.Query(ctx, `SELECT memory_mb, cpu_percent, disk_mb,SUM(EXTRACT(EPOCH FROM (COALESCE(ended_at, LEAST(now(), $3)) - GREATEST(started_at, $2)))) as total_seconds- FROM sandbox_scale_events+ FROM sandbox_scale_events seWHERE org_id = $1AND started_at < $3AND (ended_at IS NULL OR ended_at > $2)+ AND NOT EXISTS (+ SELECT 1+ FROM sandbox_sessions ss+ JOIN agent_subscriptions asub+ ON asub.org_id = ss.org_id+ AND asub.agent_id = ss.metadata->>'agent_id'+ AND asub.status IN ('active', 'trialing', 'past_due', 'incomplete')+ WHERE ss.sandbox_id = se.sandbox_id+ AND ss.metadata->>'agent_id' IS NOT NULL+ )GROUP BY memory_mb, cpu_percent, disk_mbORDER BY memory_mb, disk_mb`,orgID, from, to)