Skip to content

An open-source, faster Devin alternative

TypeScript

sdks: Usage + Tags stubs (TS + Python)

Igor Zalutski008486c595be
diff --git a/sdks/python/opencomputer/__init__.py b/sdks/python/opencomputer/__init__.py
index d6bdbc06..abccfd8a 100644
--- a/sdks/python/opencomputer/__init__.py
+++ b/sdks/python/opencomputer/__init__.py
@@ -9,6 +9,18 @@ from opencomputer.pty import Pty, PtySession
from opencomputer.template import Template
from opencomputer.project import SecretStore
from opencomputer.snapshot import Snapshots
+from opencomputer.usage import (
+ Usage,
+ Tags,
+ UsageSandboxItem,
+ UsageTagItem,
+ UsageTotals,
+ UsageUntaggedBucket,
+ UsageBySandboxResponse,
+ UsageByTagResponse,
+ SandboxUsageResponse,
+ TagKeyInfo,
+)
__all__ = [
"Sandbox",
@@ -26,6 +38,16 @@ __all__ = [
"Template",
"SecretStore",
"Snapshots",
+ "Usage",
+ "Tags",
+ "UsageSandboxItem",
+ "UsageTagItem",
+ "UsageTotals",
+ "UsageUntaggedBucket",
+ "UsageBySandboxResponse",
+ "UsageByTagResponse",
+ "SandboxUsageResponse",
+ "TagKeyInfo",
]
__version__ = "0.5.2"
diff --git a/sdks/python/opencomputer/usage.py b/sdks/python/opencomputer/usage.py
new file mode 100644
index 00000000..2cd44190
--- /dev/null
+++ b/sdks/python/opencomputer/usage.py
@@ -0,0 +1,287 @@
+"""Usage + tags — per-sandbox and per-tag spend attribution.
+
+All numeric fields are GB-seconds. Dollars live in Stripe; the SDK
+mirrors the server's physical-quantity model so invoices stay the
+source of truth for currency.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+import httpx
+
+
+@dataclass
+class UsageSandboxItem:
+ sandbox_id: str
+ memory_gb_seconds: float
+ disk_overage_gb_seconds: float
+ tags: dict[str, str] = field(default_factory=dict)
+ tags_last_updated_at: str | None = None
+ alias: str | None = None
+ status: str | None = None
+
+
+@dataclass
+class UsageTagItem:
+ tag_key: str
+ tag_value: str
+ memory_gb_seconds: float
+ disk_overage_gb_seconds: float
+ sandbox_count: int
+
+
+@dataclass
+class UsageTotals:
+ memory_gb_seconds: float
+ disk_overage_gb_seconds: float
+
+
+@dataclass
+class UsageUntaggedBucket:
+ memory_gb_seconds: float
+ disk_overage_gb_seconds: float
+ sandbox_count: int
+
+
+@dataclass
+class UsageBySandboxResponse:
+ from_: str
+ to: str
+ total: UsageTotals
+ items: list[UsageSandboxItem]
+ next_cursor: str | None
+
+
+@dataclass
+class UsageByTagResponse:
+ from_: str
+ to: str
+ group_by: str
+ total: UsageTotals
+ untagged: UsageUntaggedBucket
+ items: list[UsageTagItem]
+ next_cursor: str | None
+
+
+@dataclass
+class SandboxUsageResponse:
+ sandbox_id: str
+ from_: str
+ to: str
+ memory_gb_seconds: float
+ disk_overage_gb_seconds: float
+ tags: dict[str, str]
+ tags_last_updated_at: str | None
+ first_started_at: str | None
+ last_ended_at: str | None
+ alias: str | None = None
+ status: str | None = None
+
+
+@dataclass
+class TagKeyInfo:
+ key: str
+ sandbox_count: int
+ value_count: int
+
+
+def _build_params(
+ *,
+ group_by: str | None = None,
+ from_: str | None = None,
+ to: str | None = None,
+ sort: str | None = None,
+ limit: int | None = None,
+ cursor: str | None = None,
+ filter: dict[str, str] | None = None,
+) -> list[tuple[str, str]]:
+ """Build a flat list of (key, value) query params. httpx preserves
+ duplicate keys when passed as a list of tuples, which is what
+ `filter[tag:<key>]=...` with multiple keys expects."""
+ params: list[tuple[str, str]] = []
+ if group_by is not None:
+ params.append(("groupBy", group_by))
+ if from_ is not None:
+ params.append(("from", from_))
+ if to is not None:
+ params.append(("to", to))
+ if sort is not None:
+ params.append(("sort", sort))
+ if limit is not None:
+ params.append(("limit", str(limit)))
+ if cursor is not None:
+ params.append(("cursor", cursor))
+ if filter:
+ for k, v in filter.items():
+ params.append((f"filter[{k}]", v))
+ return params
+
+
+@dataclass
+class Usage:
+ """Usage aggregator. ``by_sandbox`` / ``by_tag`` call
+ ``GET /usage``; ``for_sandbox`` is the drilldown."""
+
+ _client: httpx.AsyncClient
+
+ @classmethod
+ def _from_client(cls, client: httpx.AsyncClient) -> "Usage":
+ return cls(_client=client)
+
+ async def by_sandbox(
+ self,
+ *,
+ from_: str | None = None,
+ to: str | None = None,
+ filter: dict[str, str] | None = None,
+ sort: str | None = None,
+ limit: int | None = None,
+ cursor: str | None = None,
+ ) -> UsageBySandboxResponse:
+ params = _build_params(
+ group_by="sandbox",
+ from_=from_,
+ to=to,
+ sort=sort,
+ limit=limit,
+ cursor=cursor,
+ filter=filter,
+ )
+ resp = await self._client.get("/usage", params=params)
+ resp.raise_for_status()
+ body = resp.json()
+ return UsageBySandboxResponse(
+ from_=body["from"],
+ to=body["to"],
+ total=UsageTotals(**_camel_to_snake(body["total"])),
+ items=[
+ UsageSandboxItem(
+ sandbox_id=i["sandboxId"],
+ memory_gb_seconds=i["memoryGbSeconds"],
+ disk_overage_gb_seconds=i["diskOverageGbSeconds"],
+ tags=i.get("tags") or {},
+ tags_last_updated_at=i.get("tagsLastUpdatedAt"),
+ alias=i.get("alias"),
+ status=i.get("status"),
+ )
+ for i in body.get("items") or []
+ ],
+ next_cursor=body.get("nextCursor"),
+ )
+
+ async def by_tag(
+ self,
+ tag_key: str,
+ *,
+ from_: str | None = None,
+ to: str | None = None,
+ filter: dict[str, str] | None = None,
+ sort: str | None = None,
+ limit: int | None = None,
+ cursor: str | None = None,
+ ) -> UsageByTagResponse:
+ params = _build_params(
+ group_by=f"tag:{tag_key}",
+ from_=from_,
+ to=to,
+ sort=sort,
+ limit=limit,
+ cursor=cursor,
+ filter=filter,
+ )
+ resp = await self._client.get("/usage", params=params)
+ resp.raise_for_status()
+ body = resp.json()
+ u = body.get("untagged") or {"memoryGbSeconds": 0, "diskOverageGbSeconds": 0, "sandboxCount": 0}
+ return UsageByTagResponse(
+ from_=body["from"],
+ to=body["to"],
+ group_by=body["groupBy"],
+ total=UsageTotals(**_camel_to_snake(body["total"])),
+ untagged=UsageUntaggedBucket(
+ memory_gb_seconds=u["memoryGbSeconds"],
+ disk_overage_gb_seconds=u["diskOverageGbSeconds"],
+ sandbox_count=u["sandboxCount"],
+ ),
+ items=[
+ UsageTagItem(
+ tag_key=i["tagKey"],
+ tag_value=i["tagValue"],
+ memory_gb_seconds=i["memoryGbSeconds"],
+ disk_overage_gb_seconds=i["diskOverageGbSeconds"],
+ sandbox_count=i["sandboxCount"],
+ )
+ for i in body.get("items") or []
+ ],
+ next_cursor=body.get("nextCursor"),
+ )
+
+ async def for_sandbox(
+ self,
+ sandbox_id: str,
+ *,
+ from_: str | None = None,
+ to: str | None = None,
+ ) -> SandboxUsageResponse:
+ params = _build_params(from_=from_, to=to)
+ resp = await self._client.get(f"/sandboxes/{sandbox_id}/usage", params=params)
+ resp.raise_for_status()
+ b = resp.json()
+ return SandboxUsageResponse(
+ sandbox_id=b["sandboxId"],
+ from_=b["from"],
+ to=b["to"],
+ memory_gb_seconds=b["memoryGbSeconds"],
+ disk_overage_gb_seconds=b["diskOverageGbSeconds"],
+ tags=b.get("tags") or {},
+ tags_last_updated_at=b.get("tagsLastUpdatedAt"),
+ first_started_at=b.get("firstStartedAt"),
+ last_ended_at=b.get("lastEndedAt"),
+ alias=b.get("alias"),
+ status=b.get("status"),
+ )
+
+
+@dataclass
+class Tags:
+ """Tag management. ``list_keys`` is org-wide discovery;
+ ``get`` and ``set`` operate on one sandbox."""
+
+ _client: httpx.AsyncClient
+
+ @classmethod
+ def _from_client(cls, client: httpx.AsyncClient) -> "Tags":
+ return cls(_client=client)
+
+ async def list_keys(self) -> list[TagKeyInfo]:
+ resp = await self._client.get("/tags")
+ resp.raise_for_status()
+ return [
+ TagKeyInfo(key=k["key"], sandbox_count=k["sandboxCount"], value_count=k["valueCount"])
+ for k in resp.json().get("keys") or []
+ ]
+
+ async def get(self, sandbox_id: str) -> tuple[dict[str, str], str | None]:
+ """Return (tags, tagsLastUpdatedAt)."""
+ resp = await self._client.get(f"/sandboxes/{sandbox_id}/tags")
+ resp.raise_for_status()
+ body = resp.json()
+ return body.get("tags") or {}, body.get("tagsLastUpdatedAt")
+
+ async def set(self, sandbox_id: str, tags: dict[str, str]) -> tuple[dict[str, str], str | None]:
+ """Full replace. ``{}`` clears all tags."""
+ resp = await self._client.put(f"/sandboxes/{sandbox_id}/tags", json=tags)
+ resp.raise_for_status()
+ body = resp.json()
+ return body.get("tags") or {}, body.get("tagsLastUpdatedAt")
+
+
+def _camel_to_snake(d: dict[str, Any]) -> dict[str, Any]:
+ """Narrow helper — only covers the two keys on UsageTotals."""
+ return {
+ "memory_gb_seconds": d.get("memoryGbSeconds", 0.0),
+ "disk_overage_gb_seconds": d.get("diskOverageGbSeconds", 0.0),
+ }
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index 22156171..bd0bc801 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -5,6 +5,20 @@ export { Exec, type ProcessResult, type RunOpts, type ExecSession, type ExecSess
export { Pty, type PtySession, type PtyOpts } from "./pty.js";
export { Templates, type TemplateInfo } from "./template.js";
export { SecretStore, type SecretStoreInfo, type SecretEntryInfo, type SecretStoreOpts, type CreateSecretStoreOpts, type UpdateSecretStoreOpts } from "./project.js";
+export {
+ Usage,
+ Tags,
+ type UsageSandboxItem,
+ type UsageTagItem,
+ type UsageTotals,
+ type UsageUntaggedBucket,
+ type UsageBySandboxResponse,
+ type UsageByTagResponse,
+ type UsageQueryOpts,
+ type UsageFilterMap,
+ type SandboxUsageResponse,
+ type TagKeyInfo,
+} from "./usage.js";
// Node.js-only modules (use crypto, fs, path) — import via "@opencomputer/sdk/node".
export type { ImageManifest, ImageStep } from "./image.js";
export type { SnapshotInfo, CreateSnapshotOpts } from "./snapshot.js";
diff --git a/sdks/typescript/src/usage.ts b/sdks/typescript/src/usage.ts
new file mode 100644
index 00000000..352aad90
--- /dev/null
+++ b/sdks/typescript/src/usage.ts
@@ -0,0 +1,189 @@
+// Usage + tags — TypeScript SDK surface.
+//
+// All numeric fields are GB-seconds. Dollars live in Stripe; the SDK
+// intentionally mirrors the server's "physical quantity" model so
+// the invoice stays the source of truth for currency.
+
+export interface UsageSandboxItem {
+ sandboxId: string;
+ alias?: string;
+ status?: string;
+ tags: Record<string, string>;
+ tagsLastUpdatedAt: string | null;
+ memoryGbSeconds: number;
+ diskOverageGbSeconds: number;
+}
+
+export interface UsageTagItem {
+ tagKey: string;
+ tagValue: string;
+ memoryGbSeconds: number;
+ diskOverageGbSeconds: number;
+ sandboxCount: number;
+}
+
+export interface UsageTotals {
+ memoryGbSeconds: number;
+ diskOverageGbSeconds: number;
+}
+
+export interface UsageUntaggedBucket extends UsageTotals {
+ sandboxCount: number;
+}
+
+export interface UsageBySandboxResponse {
+ from: string;
+ to: string;
+ groupBy: "sandbox";
+ total: UsageTotals;
+ items: UsageSandboxItem[];
+ nextCursor: string | null;
+}
+
+export interface UsageByTagResponse {
+ from: string;
+ to: string;
+ groupBy: string; // "tag:<key>"
+ total: UsageTotals;
+ untagged: UsageUntaggedBucket;
+ items: UsageTagItem[];
+ nextCursor: string | null;
+}
+
+export interface UsageFilterMap {
+ /** `filter[tag:<key>]=v1,v2` — repeatable, AND'd. Empty string = "key absent." */
+ [tagFilter: string]: string;
+}
+
+export interface UsageQueryOpts {
+ from?: string; // RFC3339; default: now - 30d
+ to?: string;
+ filter?: UsageFilterMap;
+ sort?: "-memoryGbSeconds" | "-diskOverageGbSeconds";
+ limit?: number;
+ cursor?: string;
+}
+
+export interface SandboxUsageResponse {
+ sandboxId: string;
+ alias?: string;
+ status?: string;
+ from: string;
+ to: string;
+ memoryGbSeconds: number;
+ diskOverageGbSeconds: number;
+ tags: Record<string, string>;
+ tagsLastUpdatedAt: string | null;
+ firstStartedAt: string | null;
+ lastEndedAt: string | null;
+}
+
+export interface TagKeyInfo {
+ key: string;
+ sandboxCount: number;
+ valueCount: number;
+}
+
+export class Usage {
+ constructor(
+ private apiUrl: string,
+ private apiKey: string,
+ ) {}
+
+ private get headers(): Record<string, string> {
+ const h: Record<string, string> = { "Content-Type": "application/json" };
+ if (this.apiKey) h["X-API-Key"] = this.apiKey;
+ return h;
+ }
+
+ private buildQueryString(params: Record<string, string | undefined>, filter?: UsageFilterMap): string {
+ const u = new URLSearchParams();
+ for (const [k, v] of Object.entries(params)) {
+ if (v !== undefined && v !== "") u.set(k, v);
+ }
+ if (filter) {
+ for (const [k, v] of Object.entries(filter)) {
+ u.append(`filter[${k}]`, v);
+ }
+ }
+ const s = u.toString();
+ return s ? `?${s}` : "";
+ }
+
+ /** `GET /usage?groupBy=sandbox` — top sandboxes by spend. */
+ async bySandbox(opts: UsageQueryOpts = {}): Promise<UsageBySandboxResponse> {
+ const qs = this.buildQueryString({
+ groupBy: "sandbox",
+ from: opts.from,
+ to: opts.to,
+ sort: opts.sort,
+ limit: opts.limit?.toString(),
+ 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}`);
+ return resp.json();
+ }
+
+ /** `GET /usage?groupBy=tag:<key>` — spend per tag value, plus untagged sibling bucket. */
+ async byTag(tagKey: string, opts: UsageQueryOpts = {}): Promise<UsageByTagResponse> {
+ const qs = this.buildQueryString({
+ groupBy: `tag:${tagKey}`,
+ from: opts.from,
+ to: opts.to,
+ sort: opts.sort,
+ limit: opts.limit?.toString(),
+ 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}`);
+ return resp.json();
+ }
+
+ /** `GET /sandboxes/:id/usage` — per-sandbox drilldown. */
+ 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}`);
+ return resp.json();
+ }
+}
+
+export class Tags {
+ constructor(
+ private apiUrl: string,
+ private apiKey: string,
+ ) {}
+
+ private get headers(): Record<string, string> {
+ const h: Record<string, string> = { "Content-Type": "application/json" };
+ if (this.apiKey) h["X-API-Key"] = this.apiKey;
+ return h;
+ }
+
+ /** `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}`);
+ const body = await resp.json();
+ return body.keys;
+ }
+
+ /** `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}`);
+ return resp.json();
+ }
+
+ /** `PUT /sandboxes/:id/tags` — full replace. `{}` clears all tags. */
+ async set(sandboxId: string, tags: Record<string, string>): Promise<{ tags: Record<string, string>; tagsLastUpdatedAt: string | null }> {
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${sandboxId}/tags`, {
+ method: "PUT",
+ headers: this.headers,
+ body: JSON.stringify(tags),
+ });
+ if (!resp.ok) throw new Error(`Failed to set tags: ${resp.status}`);
+ return resp.json();
+ }
+}