/** * `list_devices` (handlers/devices.rs). `list_agent_accounts` was retired with the AI-account tables * (OPEN TABLES, owner, 24 Nov 2026; assets/design/shared/OPEN-TABLES.md). * * Two places differ from the Rust, both because the Worker has no such rail: * - `capabilities` reads no `cotton_machine_runners` (the personal package has * no runner table), so every device holds the default declaration — enabled, * the checks label only — and is never a "builder"; "signer" is read from * `agents` as in Rust. * - `reportedState.sync` gets no `words`: those are the Mac sync engine's line * rendered in the shell's words, and nothing on the Worker reports one. * And one quirk is not kept: Rust's SELECT left out `scope` and the three * `runner_*` columns, so it always answered null for them; here they are read. */ import { fail, type Data, type ToolContext } from "../../context.ts"; import { typeOf, type Cond, type StoredRow } from "../../../store.ts"; import { isNull, rfc3339, text } from "./common.ts"; import { appReports } from "../../../device_reports.ts"; const SIGNING_IDENTITY_KEY = "developer-id"; function number(d: Data, key: string): unknown { return d[key] === undefined ? null : d[key]; } function isObject(v: unknown): v is Data { return !!v && typeof v === "object" && !Array.isArray(v); } /** A JSON object column, stored as text or as an object; anything else is `{}`. */ function object(d: Data, key: string): Data { const v = d[key]; if (typeof v === "string") { try { const parsed: unknown = JSON.parse(v); return isObject(parsed) ? parsed : {}; } catch { return {}; } } return isObject(v) ? v : {}; } function nullableObject(d: Data, key: string): Data | null { return isNull(d, key) ? null : object(d, key); } /** `AiHold::from_json` then serialised back: `{ held_until, reason }` or null. */ function aiHold(d: Data): Data | null { const said = text(d, "ai_holds"); if (said === null) return null; let parsed: unknown; try { parsed = JSON.parse(said); } catch { return null; } if (!isObject(parsed) || parsed.reason !== "anthropic_credits" || typeof parsed.held_until !== "string") return null; const at = rfc3339(parsed.held_until); if (!at) return null; const whole = new Date(Math.floor(at.ms / 1000) * 1000).toISOString().slice(0, 19); const nanos = at.nanos; const fraction = nanos === 0 ? "" : nanos % 1_000_000 === 0 ? `.${String(nanos / 1_000_000).padStart(3, "0")}` : nanos % 1000 === 0 ? `.${String(nanos / 1000).padStart(6, "0")}` : `.${String(nanos).padStart(9, "0")}`; return { held_until: `${whole}${fraction}Z`, reason: "anthropic_credits" }; } function capabilities(d: Data): string[] { const agents = typeof d.agents === "string" ? safeParse(d.agents) : d.agents; const signer = isObject(agents) && agents[SIGNING_IDENTITY_KEY] !== undefined && agents[SIGNING_IDENTITY_KEY] !== null; return signer ? ["signer"] : []; } function safeParse(v: string): unknown { try { return JSON.parse(v); } catch { return null; } } /** `approved_at DESC`, nulls last as SQLite orders them. */ function byApprovedDesc(a: StoredRow, b: StoredRow): number { const x = text(a.data, "approved_at"); const y = text(b.data, "approved_at"); if (x === y) return 0; if (x === null) return 1; if (y === null) return -1; return x < y ? 1 : -1; } /** A device not revoked: `revoked_at` absent or null. */ const UNREVOKED: Cond = { sql: `${typeOf("revoked_at")} = 'null'`, args: [] }; export function listDevices(ctx: ToolContext, args: Data): Data { if (args.includeRevoked !== undefined && typeof args.includeRevoked !== "boolean") fail("includeRevoked must be true or false"); const includeRevoked = args.includeRevoked !== false; const rows = [...ctx.scan("device", includeRevoked ? [] : [UNREVOKED])].sort(byApprovedDesc); const devices = rows.map((row) => { const d = row.data; return { id: row.id, deviceId: text(d, "device_id"), name: text(d, "name"), platform: text(d, "platform"), appVersion: text(d, "app_version"), pushAuthorization: text(d, "push_authorization"), publishesRelayIdentity: text(d, "relay_identity_key") !== null, approvedAt: text(d, "approved_at"), approvedBy: text(d, "approved_by_device"), revokedAt: text(d, "revoked_at"), revokedBy: text(d, "revoked_by_device"), revokedReason: text(d, "revoked_reason"), cpuCount: number(d, "cpu_count"), memTotalGb: number(d, "mem_total_gb"), memFreePct: number(d, "mem_free_pct"), load1: number(d, "load1"), diskFreeGb: number(d, "disk_free_gb"), sessionsRunning: number(d, "sessions_running"), sessionsCap: number(d, "sessions_cap"), buildLockHeld: number(d, "build_lock_held"), memCommittedGb: number(d, "mem_committed_gb"), memBudgetGb: number(d, "mem_budget_gb"), sessionPeakGb: number(d, "session_peak_gb"), sessionPeakSamples: number(d, "session_peak_samples"), servingRank: number(d, "serving_rank"), schemaVersion: number(d, "schema_version"), copyAsOf: text(d, "copy_as_of"), agents: object(d, "agents"), capabilities: capabilities(d), accountIds: object(d, "account_ids"), repos: nullableObject(d, "repos"), hostVersion: text(d, "host_version"), sampledAt: text(d, "sampled_at"), chip: text(d, "chip"), osVersion: text(d, "os_version"), diskTotalGb: number(d, "disk_total_gb"), updateHold: text(d, "update_hold"), scope: text(d, "scope"), runnerOrderedAt: text(d, "runner_ordered_at"), runnerConfirmedAt: text(d, "runner_confirmed_at"), runnerProblem: text(d, "runner_problem"), aiHolds: aiHold(d), aiSpend: nullableObject(d, "ai_spend"), aiDayCapUsd: number(d, "ai_day_cap_usd"), reportedState: nullableObject(d, "reported_state"), // Not in the Rust: each app on a shared credential, its own report, newest first (src/device_reports.ts). apps: appReports(nullableObject(d, "reported_state")), }; }); return { devices }; }