An open-source, faster Devin alternative
TypeScript
Document usage SDK and harden usage API
Igor Zalutski0faece570ef6
diff --git a/docs/api-reference/sandboxes/set-tags.mdx b/docs/api-reference/sandboxes/set-tags.mdxindex 84f47602..b4e0509c 100644--- a/docs/api-reference/sandboxes/set-tags.mdx+++ b/docs/api-reference/sandboxes/set-tags.mdx@@ -36,6 +36,6 @@ supported — GET, modify, PUT. `{}` clears all tags.Retagging rewrites attribution going forward: a sandbox re-taggedfrom `team=payments` to `team=growth` will appear under `growth` inevery subsequent /usage query, including for time before the retag.-Surface `tagsLastUpdatedAt` alongside spend in dashboards so readers+Surface `tagsLastUpdatedAt` alongside usage in dashboards so readerscan see when tags changed.</Note>diff --git a/docs/api-reference/usage/get-sandbox-usage.mdx b/docs/api-reference/usage/get-sandbox-usage.mdxindex fda4f967..0618b01b 100644--- a/docs/api-reference/usage/get-sandbox-usage.mdx+++ b/docs/api-reference/usage/get-sandbox-usage.mdx@@ -15,13 +15,11 @@ resident memory consumed by the sandbox process, sampled every 60s.</ParamField><ParamField query="from" type="string">- Lower bound. Accepts either a date (`2026-05-27`, treated as UTC- midnight) or a full RFC3339 timestamp. Default: now minus 1 hour.+ RFC3339 lower bound. Default: now minus 1 hour.</ParamField><ParamField query="to" type="string">- Upper bound. Same format as `from`. Default: now. Window must be ≤- 30 days.+ RFC3339 upper bound. Default: now. Window must be ≤ 30 days.</ParamField>## Response@@ -185,7 +183,7 @@ running for one minute, `memoryAllocatedGbSeconds` is### Use the aggregator for cross-sandbox questions-To rank sandboxes by spend, use [`GET /api/usage`](/api-reference/usage/get-usage)+To rank sandboxes by usage, use [`GET /api/usage`](/api-reference/usage/get-usage)— that endpoint serves cross-sandbox aggregates and supportsfilter/sort/cursor. The per-sandbox endpoint here is for "look atthis one sandbox in detail."diff --git a/docs/api-reference/usage/get-usage.mdx b/docs/api-reference/usage/get-usage.mdxindex 7f21f19b..d3d0b93b 100644--- a/docs/api-reference/usage/get-usage.mdx+++ b/docs/api-reference/usage/get-usage.mdx@@ -3,7 +3,7 @@ title: 'Usage Aggregator'api: 'GET /api/usage'----Aggregate spend grouped by sandbox or by tag. Dollars are not exposed+Aggregate usage grouped by sandbox or by tag. Dollars are not exposed— the platform returns the same physical quantities the invoice iscomputed from. For per-sandbox time-series drilldown (memoryutilization over time, 1-minute resolution), see@@ -25,20 +25,19 @@ billing pipeline uses, so the numbers here match the invoice.## Request<ParamField query="groupBy" type="string" required>- `sandbox` for top sandboxes, or `tag:<key>` for spend by tag value.+ `sandbox` for top sandboxes, or `tag:<key>` for usage by tag value.Keys may contain `:` — everything after the first `:` is the tagkey (so `groupBy=tag:team:payments` groups by the key`team:payments`).</ParamField><ParamField query="from" type="string">- Inclusive lower bound. Accepts either a date (`2026-05-27`, treated- as UTC midnight) or a full RFC3339 timestamp. Default: now minus- 30 days. Max window: 90 days.+ RFC3339 inclusive lower bound. Default: now minus 30 days. Max+ window: 90 days.</ParamField><ParamField query="to" type="string">- Exclusive upper bound. Same format as `from`. Default: now.+ RFC3339 exclusive upper bound. Default: now.</ParamField><ParamField query="filter[tag:<key>]" type="string">diff --git a/docs/docs.json b/docs/docs.jsonindex faedda7b..95750f67 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -124,6 +124,7 @@"reference/typescript-sdk/overview","reference/typescript-sdk/sandbox","reference/typescript-sdk/scaling",+ "reference/typescript-sdk/usage","reference/typescript-sdk/exec","reference/typescript-sdk/filesystem","reference/typescript-sdk/pty",diff --git a/docs/reference/typescript-sdk.mdx b/docs/reference/typescript-sdk.mdxindex 15340a01..b2ae66f6 100644--- a/docs/reference/typescript-sdk.mdx+++ b/docs/reference/typescript-sdk.mdx@@ -10,7 +10,7 @@ npm install @opencomputer/sdk``````typescript-import { Sandbox } from "@opencomputer/sdk";+import { Sandbox, Usage, Tags } from "@opencomputer/sdk";import { Image } from "@opencomputer/sdk/dist/image.js";import { Snapshots } from "@opencomputer/sdk/dist/snapshot.js";```@@ -34,7 +34,7 @@ Create a new sandbox.| `envs` | Record\<string, string\> | — | Environment variables || `metadata` | Record\<string, string\> | — | Arbitrary metadata || `cpuCount` | number | — | CPU cores (1, 2, or 4) |-| `memoryMB` | number | — | Memory in MB (1024, 4096, 8192, or 16384) |+| `memoryMB` | number | — | Memory in MB (1024, 4096, 8192, 16384, 32768, or 65536) || `image` | Image | — | Declarative image definition (see [Image](#image)) || `snapshot` | string | — | Name of a pre-built snapshot || `onBuildLog` | `(log: string) => void` | — | Build log callback (when using `image`) |@@ -246,6 +246,86 @@ interface PreviewURLResult {---+## Usage & Tags++Query billing-aligned usage, inspect per-sandbox memory points, and+manage sandbox tags used for grouping. Full reference:+[Usage & Tags](/reference/typescript-sdk/usage).++```typescript+const usage = new Usage("https://app.opencomputer.dev", process.env.OPENCOMPUTER_API_KEY!);+const tags = new Tags("https://app.opencomputer.dev", process.env.OPENCOMPUTER_API_KEY!);+```++### `usage.forSandbox(sandboxId, opts?): Promise<SandboxUsageResponse>`++Return 1-minute allocated and used memory points for one sandbox.+`from` and `to` are optional RFC3339 timestamps; default window is the+last hour.++```typescript+const r = await usage.forSandbox("sb-abc123", {+ from: "2026-05-27T00:00:00Z",+ to: "2026-05-27T01:00:00Z",+});++console.log(r.totals.memoryAllocatedGbSeconds, r.totals.memoryUsedGbSeconds);+```++### `usage.bySandbox(opts?): Promise<UsageBySandboxResponse>`++Rank sandboxes by usage. Supports RFC3339 `from` / `to`,+`filter`, `sort`, `limit`, and `cursor`.++```typescript+const page = await usage.bySandbox({+ filter: { "tag:team": "payments" },+ limit: 20,+});+```++### `usage.byTag(tagKey, opts?): Promise<UsageByTagResponse>`++Group usage by one tag key, with an `untagged` sibling bucket.++```typescript+const byTeam = await usage.byTag("team", {+ filter: { "tag:env": "prod" },+});+```++### `tags.set(sandboxId, tags): Promise<{ tags; tagsLastUpdatedAt }>`++Replace the full tag set for a sandbox. `{}` clears all tags.++```typescript+await tags.set("sb-abc123", {+ team: "payments",+ env: "prod",+});+```++### `tags.get(sandboxId): Promise<{ tags; tagsLastUpdatedAt }>`++Read the current tag set for a sandbox.++```typescript+const current = await tags.get("sb-abc123");+```++### `tags.listKeys(): Promise<TagKeyInfo[]>`++List tag keys seen in the organization.++```typescript+const keys = await tags.listKeys();+```++All `*GbSeconds` fields are GiB-seconds. For example, 4096 MiB+provisioned for one minute reports `240` `memoryAllocatedGbSeconds`.++---+## AgentAccessed via `sandbox.agent`.diff --git a/docs/reference/typescript-sdk/overview.mdx b/docs/reference/typescript-sdk/overview.mdxindex 3c86f0e8..cc41a1ac 100644--- a/docs/reference/typescript-sdk/overview.mdx+++ b/docs/reference/typescript-sdk/overview.mdx@@ -30,6 +30,9 @@ import { Image, Snapshots } from "@opencomputer/sdk/node";<Card title="Sandbox" icon="box" href="/reference/typescript-sdk/sandbox">Create, connect, and manage sandbox lifecycle</Card>+ <Card title="Usage & Tags" icon="gauge" href="/reference/typescript-sdk/usage">+ Query usage, group by tag, and manage sandbox tags+ </Card><Card title="Exec" icon="terminal" href="/reference/typescript-sdk/exec">Run commands and manage exec sessions</Card>diff --git a/docs/reference/typescript-sdk/usage.mdx b/docs/reference/typescript-sdk/usage.mdxnew file mode 100644index 00000000..309bab75--- /dev/null+++ b/docs/reference/typescript-sdk/usage.mdx@@ -0,0 +1,285 @@+---+title: "Usage & Tags"+description: "Query sandbox usage, group by tag, and manage sandbox tags"+---++Use `Usage` for billing-aligned usage queries and per-sandbox+time-series drilldowns. Use `Tags` to set and read sandbox tags used+by the usage aggregator.++```typescript+import { Usage, Tags } from "@opencomputer/sdk";++const usage = new Usage("https://app.opencomputer.dev", process.env.OPENCOMPUTER_API_KEY!);+const tags = new Tags("https://app.opencomputer.dev", process.env.OPENCOMPUTER_API_KEY!);+```++The `apiUrl` may include or omit `/api`; both+`https://app.opencomputer.dev` and `https://app.opencomputer.dev/api`+work.++## `usage.forSandbox(sandboxId, opts?)`++Return 1-minute memory points plus envelope totals for one sandbox.+[HTTP API ->](/api-reference/usage/get-sandbox-usage)++<ParamField body="sandboxId" type="string" required>+ Sandbox ID.+</ParamField>++<ParamField body="from" type="string">+ RFC3339 lower bound. Default: now minus 1 hour.+</ParamField>++<ParamField body="to" type="string">+ RFC3339 upper bound. Default: now. Window must be at most 30 days.+</ParamField>++**Returns:** `Promise<SandboxUsageResponse>`++```typescript+const r = await usage.forSandbox("sb-abc123", {+ from: "2026-05-27T00:00:00Z",+ to: "2026-05-27T01:00:00Z",+});++const utilization =+ r.totals.memoryAllocatedGbSeconds === 0+ ? 0+ : r.totals.memoryUsedGbSeconds / r.totals.memoryAllocatedGbSeconds;++console.log(`${(utilization * 100).toFixed(0)}% memory utilization`);++for (const point of r.points) {+ // point.ts, point.allocatedMemoryMb, point.usedMemoryMbAvg+ // are ready to render as chart series.+}+```++## `usage.bySandbox(opts?)`++Rank sandboxes by usage for an organization. [HTTP API ->](/api-reference/usage/get-usage)++<ParamField body="from" type="string">+ RFC3339 lower bound. Default: now minus 30 days.+</ParamField>++<ParamField body="to" type="string">+ RFC3339 upper bound. Default: now. Window must be at most 90 days.+</ParamField>++<ParamField body="filter" type="Record<string, string>">+ Tag filters. Keys are dimensions such as `"tag:team"`. Values are+ exact tag values, comma-separated OR values, or `""` to match+ sandboxes without that tag key.+</ParamField>++<ParamField body="sort" type="string">+ `"-memoryGbSeconds"` (default) or `"-diskOverageGbSeconds"`.+</ParamField>++<ParamField body="limit" type="number">+ Max rows per page. Default 50, max 500.+</ParamField>++<ParamField body="cursor" type="string">+ Cursor returned by the previous page's `nextCursor`.+</ParamField>++**Returns:** `Promise<UsageBySandboxResponse>`++```typescript+const page = await usage.bySandbox({+ from: "2026-05-01T00:00:00Z",+ to: "2026-06-01T00:00:00Z",+ filter: { "tag:team": "payments" },+ limit: 20,+});++for (const item of page.items) {+ console.log(item.sandboxId, item.memoryGbSeconds, item.tags);+}++if (page.nextCursor) {+ const next = await usage.bySandbox({+ from: "2026-05-01T00:00:00Z",+ to: "2026-06-01T00:00:00Z",+ filter: { "tag:team": "payments" },+ cursor: page.nextCursor,+ });+}+```++## `usage.byTag(tagKey, opts?)`++Group usage by the value of one tag key. Tag keys may contain `:`.+[HTTP API ->](/api-reference/usage/get-usage)++<ParamField body="tagKey" type="string" required>+ Tag key to group by, for example `"team"` or `"team:subsystem"`.+</ParamField>++<ParamField body="filter" type="Record<string, string>">+ Optional tag filters applied before grouping.+</ParamField>++<ParamField body="from" type="string">+ RFC3339 lower bound. Default: now minus 30 days.+</ParamField>++<ParamField body="to" type="string">+ RFC3339 upper bound. Default: now. Window must be at most 90 days.+</ParamField>++<ParamField body="sort" type="string">+ `"-memoryGbSeconds"` (default) or `"-diskOverageGbSeconds"`.+</ParamField>++<ParamField body="limit" type="number">+ Max rows per page. Default 50, max 500.+</ParamField>++<ParamField body="cursor" type="string">+ Cursor returned by the previous page's `nextCursor`.+</ParamField>++**Returns:** `Promise<UsageByTagResponse>`++```typescript+const byTeam = await usage.byTag("team", {+ filter: { "tag:env": "prod" },+});++for (const row of byTeam.items) {+ console.log(row.tagValue, row.memoryGbSeconds, row.sandboxCount);+}++console.log("untagged", byTeam.untagged.memoryGbSeconds);++const bySubsystem = await usage.byTag("team:subsystem");+```++## `tags.set(sandboxId, tags)`++Replace the full tag set for a sandbox. Partial updates are not+supported: read, modify, then write the full map. [HTTP API ->](/api-reference/sandboxes/set-tags)++<ParamField body="sandboxId" type="string" required>+ Sandbox ID.+</ParamField>++<ParamField body="tags" type="Record<string, string>" required>+ Flat tag map. `{}` clears all tags.+</ParamField>++**Returns:** `Promise<{ tags: Record<string, string>; tagsLastUpdatedAt: string | null }>`++```typescript+await tags.set("sb-abc123", {+ team: "payments",+ env: "prod",+ "team:subsystem": "checkout",+});+```++## `tags.get(sandboxId)`++Read the current tag set for a sandbox. [HTTP API ->](/api-reference/sandboxes/get-tags)++**Returns:** `Promise<{ tags: Record<string, string>; tagsLastUpdatedAt: string | null }>`++```typescript+const current = await tags.get("sb-abc123");+console.log(current.tags);+```++## `tags.listKeys()`++List tag keys seen in the organization, with counts for tagged+sandboxes and distinct values. [HTTP API ->](/api-reference/usage/list-tags)++**Returns:** `Promise<TagKeyInfo[]>`++```typescript+const keys = await tags.listKeys();+for (const key of keys) {+ console.log(key.key, key.sandboxCount, key.valueCount);+}+```++## Units++All `*GbSeconds` fields are **GiB-seconds**. For example, a sandbox+provisioned at `4096` MiB for one minute reports `240`+`memoryAllocatedGbSeconds`.++`memoryAllocatedGbSeconds` is billing-aligned provisioned memory.+`memoryUsedGbSeconds` is measured resident memory from the worker+collector, so it can lag by a few minutes after a sandbox starts.++## Types++<Accordion title="SandboxUsageResponse">+```typescript+interface SandboxUsageResponse {+ sandboxId: string;+ alias?: string;+ from: string;+ to: string;+ totals: SandboxUsageTotals;+ points: SandboxUsagePoint[];+}+```+</Accordion>++<Accordion title="SandboxUsagePoint">+```typescript+interface SandboxUsagePoint {+ ts: string;+ memoryAllocatedGbSeconds: number;+ memoryUsedGbSeconds: number;+ uptimeSeconds: number;+ allocatedMemoryMb: number;+ usedMemoryMbAvg: number;+ usedMemoryMbPeak: number;+}+```+</Accordion>++<Accordion title="SandboxUsageTotals">+```typescript+interface SandboxUsageTotals {+ memoryAllocatedGbSeconds: number;+ memoryUsedGbSeconds: number;+ uptimeSeconds: number;+ memoryAllocatedPeakMb: number;+ memoryUsedPeakMb: number;+}+```+</Accordion>++<Accordion title="UsageSandboxItem">+```typescript+interface UsageSandboxItem {+ sandboxId: string;+ alias?: string;+ status?: string;+ tags: Record<string, string>;+ tagsLastUpdatedAt: string | null;+ memoryGbSeconds: number;+ diskOverageGbSeconds: number;+}+```+</Accordion>++<Accordion title="UsageTagItem">+```typescript+interface UsageTagItem {+ tagKey: string;+ tagValue: string;+ memoryGbSeconds: number;+ diskOverageGbSeconds: number;+ sandboxCount: number;+}+```+</Accordion>diff --git a/docs/sandboxes/usage.mdx b/docs/sandboxes/usage.mdxindex 489aa2fd..fdb443c9 100644--- a/docs/sandboxes/usage.mdx+++ b/docs/sandboxes/usage.mdx@@ -8,7 +8,7 @@ returns a per-minute time series of a sandbox's memory — both thetier you provisioned and what the process actually consumed —together with envelope totals. Use it to answer "am I over-paying forthis sandbox" or "when did memory spike?" For cross-sandbox-leaderboards (rank by spend, group by tag) see the aggregator at+leaderboards (rank by usage, group by tag) see the aggregator at[`GET /api/usage`](/api-reference/usage/get-usage) instead.## Example@@ -85,13 +85,12 @@ falls out of `points[]` directly: `allocatedMemoryMb` is the step,## Request```http-GET /api/sandboxes/sb-abc/usage?from=2026-05-27&to=2026-05-28+GET /api/sandboxes/sb-abc/usage?from=2026-05-27T00:00:00Z&to=2026-05-27T01:00:00Z```-Path carries the sandbox ID. `from` and `to` accept either a date-(`2026-05-27`, interpreted as UTC midnight) or a full timestamp-(`2026-05-27T15:30:00Z`). Both are optional — omit for the last-hour. Max window is **30 days**. Full param reference: the+Path carries the sandbox ID. `from` and `to` are optional RFC3339+timestamps; omit them for the last hour. Max window is **30 days**.+Full param reference: the[API page](/api-reference/usage/get-sandbox-usage).## Response@@ -141,7 +140,10 @@ Both are in **GiB-seconds** (binary, 2<sup>30</sup> bytes/GiB), so```typescript TypeScriptimport { Usage } from "@opencomputer/sdk";-const usage = new Usage("https://app.opencomputer.dev", process.env.OC_API_KEY!);+const usage = new Usage(+ "https://app.opencomputer.dev",+ process.env.OPENCOMPUTER_API_KEY!,+);// Default window = last 1 hour. Pass `from`/`to` for up to 30 days.const r = await usage.forSandbox("sb-abc");@@ -154,12 +156,14 @@ for (const p of r.points) {``````bash cURL-curl -s "$OC_API_URL/api/sandboxes/sb-abc/usage?from=2026-05-27T00:00:00Z&to=2026-05-27T01:00:00Z" \- -H "X-API-Key: $OC_API_KEY" | jq '.totals'+curl -s "$OPENCOMPUTER_API_URL/api/sandboxes/sb-abc/usage?from=2026-05-27T00:00:00Z&to=2026-05-27T01:00:00Z" \+ -H "X-API-Key: $OPENCOMPUTER_API_KEY" | jq '.totals'```</CodeGroup>+Full TypeScript SDK reference: [Usage & Tags](/reference/typescript-sdk/usage).+## Bucket semantics- Buckets are **1 minute, UTC-aligned**; boundary buckets clamp todiff --git a/internal/api/sandbox_tags.go b/internal/api/sandbox_tags.goindex 2d57d728..48632fea 100644--- a/internal/api/sandbox_tags.go+++ b/internal/api/sandbox_tags.go@@ -52,27 +52,28 @@ func validateTags(tags map[string]string) error {return nil}-// ownsSandbox returns nil when the caller's org has a session for the-// given sandbox ID, otherwise returns a 404 response. Uses the+// ownsSandbox returns true when the caller's org has a session for the+// given sandbox ID, otherwise writes the appropriate error response and+// returns false. Uses the// org-scoped session lookup (design F12) — querying by sandbox_id// alone could return another org's row on an ID collision, which// would cause the rightful owner to be denied access to their own// sandbox. 404 in both "doesn't exist" and "not your org" paths so// we don't leak cross-tenant existence.-func (s *Server) ownsSandbox(c echo.Context, sandboxID string) error {+func (s *Server) ownsSandbox(c echo.Context, sandboxID string) (bool, error) {if s.store == nil {- return c.JSON(http.StatusServiceUnavailable, map[string]string{+ return false, c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured",})}orgID, ok := auth.GetOrgID(c)if !ok {- return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ return false, c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})}if _, err := s.store.GetSandboxSessionInOrg(c.Request().Context(), orgID, sandboxID); err != nil {- return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ return false, c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})}- return nil+ return true, nil}type tagsResponse struct {@@ -90,7 +91,7 @@ func tagsResponseFromSet(tags map[string]string, lastUpdated *string) tagsRespon// getSandboxTags → GET /api/sandboxes/:id/tagsfunc (s *Server) getSandboxTags(c echo.Context) error {sandboxID := c.Param("id")- if err := s.ownsSandbox(c, sandboxID); err != nil {+ if ok, err := s.ownsSandbox(c, sandboxID); err != nil || !ok {return err}orgID, _ := auth.GetOrgID(c)@@ -109,7 +110,7 @@ func (s *Server) getSandboxTags(c echo.Context) error {// putSandboxTags → PUT /api/sandboxes/:id/tags — full replace.func (s *Server) putSandboxTags(c echo.Context) error {sandboxID := c.Param("id")- if err := s.ownsSandbox(c, sandboxID); err != nil {+ if ok, err := s.ownsSandbox(c, sandboxID); err != nil || !ok {return err}diff --git a/internal/db/usage_points.go b/internal/db/usage_points.goindex dc4fb5d8..75dfb06f 100644--- a/internal/db/usage_points.go+++ b/internal/db/usage_points.go@@ -138,6 +138,7 @@ allocated AS (SELECTbucket_ts,SUM(memory_mb::float * overlap_seconds) / 60.0 AS weighted_memory_mb,+ MAX(memory_mb) FILTER (WHERE overlap_seconds > 0) AS peak_memory_mb,SUM(memory_mb::float / 1024.0 * overlap_seconds) AS gb_seconds,COALESCE(SUM(overlap_seconds)::int, 0) AS uptime_secondsFROM event_overlap@@ -147,6 +148,7 @@ SELECTb.ts,COALESCE(a.gb_seconds, 0)::float AS memory_allocated_gb_seconds,COALESCE(a.weighted_memory_mb, 0)::int AS allocated_memory_mb,+ COALESCE(a.peak_memory_mb, 0)::int AS allocated_memory_peak_mb,COALESCE(s.memory_bytes_avg::float / 1073741824.0 * 60, 0) AS memory_used_gb_seconds,COALESCE((s.memory_bytes_avg / 1024 / 1024)::int, 0) AS used_memory_mb_avg,COALESCE((s.memory_bytes_peak / 1024 / 1024)::int, 0) AS used_memory_mb_peak,@@ -193,10 +195,12 @@ func (s *Store) SandboxUsagePoints(ctx context.Context, orgID uuid.UUID, sandboxvar totals SandboxUsageTotalsfor rows.Next() {var p UsagePoint+ var allocatedMemoryPeakMb intif err := rows.Scan(&p.Timestamp,&p.MemoryAllocatedGbSeconds,&p.AllocatedMemoryMb,+ &allocatedMemoryPeakMb,&p.MemoryUsedGbSeconds,&p.UsedMemoryMbAvg,&p.UsedMemoryMbPeak,@@ -209,8 +213,8 @@ func (s *Store) SandboxUsagePoints(ctx context.Context, orgID uuid.UUID, sandboxtotals.MemoryAllocatedGbSeconds += p.MemoryAllocatedGbSecondstotals.MemoryUsedGbSeconds += p.MemoryUsedGbSecondstotals.UptimeSeconds += p.UptimeSeconds- if p.AllocatedMemoryMb > totals.MemoryAllocatedPeakMb {- totals.MemoryAllocatedPeakMb = p.AllocatedMemoryMb+ if allocatedMemoryPeakMb > totals.MemoryAllocatedPeakMb {+ totals.MemoryAllocatedPeakMb = allocatedMemoryPeakMb}if p.UsedMemoryMbPeak > totals.MemoryUsedPeakMb {totals.MemoryUsedPeakMb = p.UsedMemoryMbPeakdiff --git a/internal/db/usage_points_pgfixture_test.go b/internal/db/usage_points_pgfixture_test.goindex 02588865..1e150aed 100644--- a/internal/db/usage_points_pgfixture_test.go+++ b/internal/db/usage_points_pgfixture_test.go@@ -7,8 +7,9 @@// or the reconciliation invariant against GetOrgUsage. Those live here.//// Run locally:-// TEST_DATABASE_URL=postgres://user:pass@localhost:5432/dbname?sslmode=disable \-// go test -tags=pgfixture ./internal/db/ -run UsagePoints -v+//+// TEST_DATABASE_URL=postgres://user:pass@localhost:5432/dbname?sslmode=disable \+// go test -tags=pgfixture ./internal/db/ -run UsagePoints -vpackage dbimport (@@ -81,10 +82,10 @@ func seedSandboxUsagePointsFixture(t *testing.T, store *Store, orgID uuid.UUID,insertSE(2048, t0.Add(-1*time.Hour), resizeAt)insertSE(4096, resizeAt, stoppedAt)- insertSamples(0, 6*60, 2048, 1_400_000_000) // Phase A- insertSamples(6*60, 8*60, 4096, 2_800_000_000) // Phase B+ insertSamples(0, 6*60, 2048, 1_400_000_000) // Phase A+ insertSamples(6*60, 8*60, 4096, 2_800_000_000) // Phase B// Gap: 8*60..9*60 — no samples- insertSamples(9*60, 18*60, 4096, 3_500_000_000) // Phase C+ insertSamples(9*60, 18*60, 4096, 3_500_000_000) // Phase C}// TestSandboxUsagePoints_Shape_pgfixture asserts the bucket grid, the@@ -178,6 +179,40 @@ func TestSandboxUsagePoints_Shape_pgfixture(t *testing.T) {}}+func TestSandboxUsagePoints_PartialBucketAllocatedPeak_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)++ orgID := uuid.New()+ sandboxID := freshSandboxID("sbx-usage-partial-peak")+ t0 := time.Now().UTC().Truncate(time.Hour).Add(-24 * time.Hour)+ seedSandboxUsagePointsFixture(t, store, orgID, sandboxID, t0)++ // The fixture resizes from 2048MB to 4096MB at t0+6h30s.+ // Query only 5 seconds inside the post-resize side of that bucket.+ // allocatedMemoryMb remains the bucket-normalized chart value, but+ // the envelope peak should still report the actual tier encountered.+ from := t0.Add(6*time.Hour + 45*time.Second)+ to := t0.Add(6*time.Hour + 50*time.Second)+ points, totals, err := store.SandboxUsagePoints(ctx, orgID, sandboxID, from, to)+ if err != nil {+ t.Fatalf("SandboxUsagePoints: %v", err)+ }+ if got, want := len(points), 1; got != want {+ t.Fatalf("len(points) = %d, want %d", got, want)+ }+ if points[0].UptimeSeconds != 5 {+ t.Errorf("points[0].UptimeSeconds = %d, want 5", points[0].UptimeSeconds)+ }+ assertClose(t, "points[0].MemoryAllocatedGbSeconds", 20, points[0].MemoryAllocatedGbSeconds)+ if points[0].AllocatedMemoryMb != 341 {+ t.Errorf("points[0].AllocatedMemoryMb = %d, want 341 (4096MB * 5/60)", points[0].AllocatedMemoryMb)+ }+ if totals.MemoryAllocatedPeakMb != 4096 {+ t.Errorf("totals.MemoryAllocatedPeakMb = %d, want 4096", totals.MemoryAllocatedPeakMb)+ }+}+// TestSandboxUsagePoints_SumInvariant_pgfixture pins the contract that// Σ points.* == totals.* exactly (Go-side sum, not a separate query),// for every additive field. If this drifts, the response shape breaks@@ -265,7 +300,7 @@ func TestSandboxUsagePoints_Boundary_pgfixture(t *testing.T) {// Anchor everything to a known minute so the fractional math is// reproducible regardless of when the test runs.anchor := time.Now().UTC().Truncate(time.Hour)- from := anchor.Add(30 * time.Second) // mid-minute lower bound+ from := anchor.Add(30 * time.Second) // mid-minute lower boundto := anchor.Add(1*time.Minute + 45*time.Second) // mid-minute upper bound; 75s window total// Scale event covers the entire window and beyond.diff --git a/internal/db/usage_points_test.go b/internal/db/usage_points_test.goindex b6571e91..c17e092d 100644--- a/internal/db/usage_points_test.go+++ b/internal/db/usage_points_test.go@@ -32,6 +32,7 @@ func TestBuildSandboxUsagePointsQuery_Shape(t *testing.T) {"scale-event filter org-scoped": "e.org_id = $1","scale-event filter sandbox-scoped": "e.sandbox_id = $2","weighted memory_mb computation": "weighted_memory_mb",+ "peak memory_mb computation": "peak_memory_mb","gb-seconds integration": "memory_mb::float / 1024.0","used GiB-seconds from memory_bytes": "memory_bytes_avg::float / 1073741824.0","uptime derived from overlap": "a.uptime_seconds",diff --git a/sdks/typescript/src/usage.ts b/sdks/typescript/src/usage.tsindex 2dcc71d0..b1ca329e 100644--- a/sdks/typescript/src/usage.ts+++ b/sdks/typescript/src/usage.ts@@ -4,6 +4,17 @@// intentionally mirrors the server's "physical quantity" model so// the invoice stays the source of truth for currency.+function resolveApiUrl(url: string): string {+ const base = url.replace(/\/+$/, "");+ return base.endsWith("/api") ? base : `${base}/api`;+}++async function throwApiError(resp: Response, action: string): Promise<never> {+ const body = await resp.text();+ const detail = body ? ` ${body}` : "";+ throw new Error(`Failed to ${action}: ${resp.status}${detail}`);+}+export interface UsageSandboxItem {sandboxId: string;alias?: string;@@ -122,10 +133,14 @@ export interface TagKeyInfo {}export class Usage {+ private apiUrl: string;+constructor(- private apiUrl: string,+ apiUrl: string,private apiKey: string,- ) {}+ ) {+ this.apiUrl = resolveApiUrl(apiUrl);+ }private get headers(): Record<string, string> {const h: Record<string, string> = { "Content-Type": "application/json" };@@ -147,7 +162,7 @@ export class Usage {return s ? `?${s}` : "";}- /** `GET /usage?groupBy=sandbox` — top sandboxes by spend. */+ /** `GET /usage?groupBy=sandbox` — top sandboxes by usage. */async bySandbox(opts: UsageQueryOpts = {}): Promise<UsageBySandboxResponse> {const qs = this.buildQueryString({groupBy: "sandbox",@@ -158,11 +173,11 @@ export class Usage {cursor: opts.cursor,}, opts.filter);const resp = await fetch(`${this.apiUrl}/usage${qs}`, { headers: this.headers });- if (!resp.ok) throw new Error(`Failed to fetch usage: ${resp.status}`);+ if (!resp.ok) await throwApiError(resp, "fetch usage");return resp.json();}- /** `GET /usage?groupBy=tag:<key>` — spend per tag value, plus untagged sibling bucket. */+ /** `GET /usage?groupBy=tag:<key>` — usage per tag value, plus untagged sibling bucket. */async byTag(tagKey: string, opts: UsageQueryOpts = {}): Promise<UsageByTagResponse> {const qs = this.buildQueryString({groupBy: `tag:${tagKey}`,@@ -173,7 +188,7 @@ export class Usage {cursor: opts.cursor,}, opts.filter);const resp = await fetch(`${this.apiUrl}/usage${qs}`, { headers: this.headers });- if (!resp.ok) throw new Error(`Failed to fetch usage: ${resp.status}`);+ if (!resp.ok) await throwApiError(resp, "fetch usage");return resp.json();}@@ -181,16 +196,20 @@ export class Usage {async forSandbox(sandboxId: string, opts: Pick<UsageQueryOpts, "from" | "to"> = {}): Promise<SandboxUsageResponse> {const qs = this.buildQueryString({ from: opts.from, to: opts.to });const resp = await fetch(`${this.apiUrl}/sandboxes/${sandboxId}/usage${qs}`, { headers: this.headers });- if (!resp.ok) throw new Error(`Failed to fetch sandbox usage: ${resp.status}`);+ if (!resp.ok) await throwApiError(resp, "fetch sandbox usage");return resp.json();}}export class Tags {+ private apiUrl: string;+constructor(- private apiUrl: string,+ apiUrl: string,private apiKey: string,- ) {}+ ) {+ this.apiUrl = resolveApiUrl(apiUrl);+ }private get headers(): Record<string, string> {const h: Record<string, string> = { "Content-Type": "application/json" };@@ -201,7 +220,7 @@ export class Tags {/** `GET /tags` — discovery of all tag keys across the org. */async listKeys(): Promise<TagKeyInfo[]> {const resp = await fetch(`${this.apiUrl}/tags`, { headers: this.headers });- if (!resp.ok) throw new Error(`Failed to list tag keys: ${resp.status}`);+ if (!resp.ok) await throwApiError(resp, "list tag keys");const body = await resp.json();return body.keys;}@@ -209,7 +228,7 @@ export class Tags {/** `GET /sandboxes/:id/tags` — current tag set. */async get(sandboxId: string): Promise<{ tags: Record<string, string>; tagsLastUpdatedAt: string | null }> {const resp = await fetch(`${this.apiUrl}/sandboxes/${sandboxId}/tags`, { headers: this.headers });- if (!resp.ok) throw new Error(`Failed to get tags: ${resp.status}`);+ if (!resp.ok) await throwApiError(resp, "get tags");return resp.json();}@@ -220,7 +239,7 @@ export class Tags {headers: this.headers,body: JSON.stringify(tags),});- if (!resp.ok) throw new Error(`Failed to set tags: ${resp.status}`);+ if (!resp.ok) await throwApiError(resp, "set tags");return resp.json();}}