### Setup and development commands Source: https://github.com/agent37-platform/starter-kit/blob/main/AGENTS.md Run these commands in order to install dependencies, configure Supabase, start the dev server, build, and typecheck. The setup command is idempotent and requires the SUPABASE_ACCESS_TOKEN environment variable. There is no test suite; the gate before shipping is a clean npm run typecheck and npm run build. ```bash npm install npm run setup # configure Supabase end-to-end (idempotent; needs SUPABASE_ACCESS_TOKEN) npm run dev # http://localhost:3000 npm run build npm run typecheck # tsc --noEmit ``` -------------------------------- ### Manual local setup commands Source: https://github.com/agent37-platform/starter-kit/blob/main/SETUP.md Run these commands in order to set up the project locally. The first `npm run setup` creates `.env.local` and prints two keys to paste; the second run creates/configures Supabase, runs the migration, and sets up auth. `npm run dev` starts the app at http://localhost:3000. ```bash npm install npm run setup # first run creates .env.local and prints the two keys to paste # → paste both into .env.local, then: npm run setup # creates/configures Supabase, runs the migration, sets up auth npm run dev # http://localhost:3000 → sign up with email + password ``` -------------------------------- ### agent37.start Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/agent37.md Starts an agent instance. ```APIDOC ## agent37.start ### Description Starts an agent instance. ### Method POST ### Endpoint /instances/{id}/start ### Parameters #### Path Parameters - **id** (string) - Required - The agent instance ID. ### Response #### Success Response (200) - **id** (string) - The agent instance ID. - **status** (string) - The new status. #### Response Example { "id": "string", "status": "running" } ``` -------------------------------- ### startWhatsappPairing Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/hermes-messaging.md Starts a WhatsApp pairing session for the given agent. It sends a POST request to the onboarding start endpoint with a self-chat mode. ```APIDOC ## POST /api/messaging/whatsapp/onboarding/start ### Description Starts a WhatsApp pairing session for the specified agent. The harness runs the pairing and the app relays it. ### Method POST ### Endpoint /api/messaging/whatsapp/onboarding/start ### Parameters #### Path Parameters - **agentId** (string) - Required - The ID of the agent for which to start pairing. #### Request Body - **mode** (string) - Required - The pairing mode, set to "self-chat". ### Request Example { "mode": "self-chat" } ### Response #### Success Response (200) - **WhatsappPairing** (object) - The pairing record returned by the harness. #### Response Example { "pairingId": "string", "qrCode": "string" } ### Error Handling Throws `ApiError(502, "channel_unavailable", ...)` on transport/parse failures. ``` -------------------------------- ### npm run setup Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/scripts.md CLI command to provision and configure Supabase for the starter kit. ```APIDOC ## [CLI] npm run setup ### Description Provisions and configures Supabase for the starter kit. Reads `.env.local` and uses `SUPABASE_ACCESS_TOKEN` to run migrations, configure auth, and fill in environment variables. ### Method CLI ### Endpoint `npm run setup` ### Parameters #### CLI Flags - `--no-create` (boolean) - Optional - Don't create a project; fail if none is configured - `-h`, `--help` (boolean) - Optional - Print help #### Environment Variables - `SUPABASE_ACCESS_TOKEN` (string) - Required - Personal access token (`sbp_…`) - `SUPABASE_PROJECT_REF` (string) - Optional - Target an existing project by ref instead of URL - `SUPABASE_ORG` (string) - Optional - Org slug to create the project under (required when the account has more than one org) - `SUPABASE_REGION` (string) - Optional - `americas | emea | apac` (default `americas`) ### Behavior Notes - First run with no `.env.local` copies `.env.example` and exits asking for the two secrets — that exit is expected, not an error. - Idempotent: fills only blank values; re-running configures an existing project. - The created project's generated DB password is **not stored** (nothing uses a direct Postgres connection; all DB access is via the service-role key over HTTPS). - Auth config written by `configureAuth`: `site_url`, `uri_allow_list` (adds `{siteUrl}/**`, `{siteUrl}/auth/callback`, `http://localhost:3000/**`, `http://localhost:3000/auth/callback`), `external_email_enabled: true`, `mailer_autoconfirm: true` (signUp returns a session immediately). - Fatal paths: `401` (token rejected), `404` (project not visible), `403`/free-project limit (cannot create), multiple orgs with no `SUPABASE_ORG`. ``` -------------------------------- ### start(id) / stop(id) / restart(id) Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/agent37.md Starts, stops, or restarts an agent instance. ```APIDOC ## POST /v1/instances/{id}/{start|stop|restart} ### Description Starts, stops, or restarts an agent instance. ### Method POST ### Endpoint /v1/instances/{id}/{start|stop|restart} ### Parameters #### Path Parameters - **id** (string) - Required - The agent instance ID. - **action** (string) - Required - The action to perform: `start`, `stop`, or `restart`. ### Response #### Success Response (200) - **id** (string) - The instance ID. - **status** (string) - The new status of the instance. #### Response Example { "id": "string", "status": "running" } ``` -------------------------------- ### useChat hook usage with send example Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/chat-hooks.md Example of using the useChat hook with agentId, sessionId, and callbacks. Shows how to send a message with model, provider, reasoning effort, and file attachments. ```ts const chat = useChat({ agentId: "a1b2", sessionId: activeSessionId, onSessionCreated: (sid, title, opts) => onSessionCreated(sid, title, opts), onActivity: (sid) => bumpSession(sid), }); const onSend = async (text: string) => { await chat.send(text, { model: settings.model, provider: settings.provider, reasoningEffort: settings.reasoningEffort, files: attachments.map((a) => a.path), }); }; ``` -------------------------------- ### Input usage example Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/ui-components.md Example usage of the Input component with email type and required attribute. ```tsx setEmail(e.target.value)} required /> ``` -------------------------------- ### agentTabPath usage example Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/dashboard-tabs.md Example call to agentTabPath with agentId 'a1b2' and tab 'files', returning '/dashboard/agents/a1b2/files'. ```typescript agentTabPath("a1b2", "files"); // "/dashboard/agents/a1b2/files" ``` -------------------------------- ### Label usage example Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/ui-components.md Example usage of the Label component, a forwardRef wrapper around Radix UI label root. ```tsx ``` -------------------------------- ### Dialog usage example Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/ui-components.md Shows how to compose the Dialog components to create a dialog with a header, title, description, input, and footer with cancel and save buttons. ```tsx Rename chat Give this conversation a title. ``` -------------------------------- ### Button usage examples Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/ui-components.md Shows how to use the Button component with different variants and props, including disabled, outline, and destructive styles. ```tsx import { Button } from "@/components/ui/button"; ``` -------------------------------- ### DropdownMenu usage example Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/ui-components.md Shows how to compose the DropdownMenu components to create a menu with a trigger button and content containing rename and delete items. ```tsx Rename Delete ``` -------------------------------- ### Using json helper Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/http.md Usage examples of the json helper: default 200 status and explicit 201 for created resources. ```typescript return json({ agents, role }); // 200 return json({ workspace: data }, 201); // 201 created ``` -------------------------------- ### POST /api/agents/{id}/{action} Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/endpoints.md Performs a lifecycle action (start, stop, restart, update) on an agent. ```APIDOC ## POST /api/agents/{id}/{action} ### Description Performs a lifecycle action on an agent: start, stop, restart, or update. ### Method POST ### Endpoint /api/agents/{id}/{action} ### Parameters #### Path Parameters - **id** (string) - Required - Agent identifier. - **action** (string) - Required - One of: start, stop, restart, update. ### Response #### Success Response (200) - **id** (string) - Agent identifier. - **status** (string) - New status. - **image_ref** (string) - Only for update action. - **image_digest** (string) - Only for update action. - **template_revision** (string) - Only for update action. ### Errors - **401** - unauthorized - **403** - forbidden - **404** - not_found (unknown action) - **500** - db_error ``` -------------------------------- ### Use loadEnv, setEnv, saveEnv from setup.mjs Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/scripts.md Example usage of the exported helpers: load a .env file, set a key, and save it back to disk. Requires the setup.mjs module. ```javascript import { loadEnv, setEnv, saveEnv } from "../scripts/setup.mjs"; const env = loadEnv(path.join(root, ".env.local")); setEnv(env, "NEXT_PUBLIC_SUPABASE_URL", "https://abc.supabase.co"); saveEnv(env); ``` -------------------------------- ### POST /api/agents/{id}/channels/{channel} Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/endpoints.md Performs guided flows for a messaging channel, such as checking a Telegram bot token, retrieving its owner, or starting WhatsApp pairing. Behavior depends on the channel and action. Authentication: admin. ```APIDOC ## POST /api/agents/{id}/channels/{channel} ### Description Performs guided flows for a messaging channel, such as checking a Telegram bot token, retrieving a bot owner, or starting WhatsApp pairing. The behavior depends on the channel and action specified in the request body. Authentication: admin. ### Method POST ### Endpoint /api/agents/{id}/channels/{channel} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the agent. - **channel** (string) - Required - The messaging platform identifier (e.g., telegram, whatsapp). #### Request Body - **action** (string) - Required - The action to perform: "check", "owner", or "pair". - **token** (string) - Optional - The bot token (used for telegram check/owner actions). - **pairing_id** (string) - Optional - The pairing session identifier for WhatsApp pairing progress. - **finish** (boolean) - Optional - If true, finalizes the WhatsApp pairing by saving the landed scan. ### Request Example ```json { "action": "pair", "pairing_id": "abc123", "finish": true } ``` ### Response #### Success Response (200) The response depends on the channel and action: - **telegram** with `action: "check"` returns `TelegramBotCheck`: - **username** (string) - The bot's username. - **name** (string) - The bot's display name. - **telegram** with `action: "owner"` returns `TelegramOwnerLookup`: - **owner** (string) - The owner identifier. - **unavailable** (boolean) - Whether the owner is unavailable. - **whatsapp** with `action: "pair"` returns `WhatsappPairingState`: - **pairing_id** (string) - The session identifier. - **status** (string) - Pairing status (e.g., "preparing"). - **qr_data_url** (string, optional) - Data URL for QR code. - **phone** (string, optional) - The paired phone number. #### Response Example ```json { "pairing_id": "abc123", "status": "preparing", "qr_data_url": "data:image/png;base64,..." } ``` ### Errors - **400 invalid_request** - If the action is unsupported for the channel or required fields are missing. - **502 pairing_failed** - If pairing fails. ``` -------------------------------- ### agent37 client object definition Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/agent37.md The full agent37 client object definition from src/lib/agent37.ts:148-260. It provides methods for managing agent instances (list, get, create, delete, start, stop, restart, update, resize, exec, signedUrl, budget, usage), templates, sessions, files, and integrations. Each method returns a typed call result. ```typescript export const agent37 = { listAgents: () => call<{ data: Agent[] }>("/instances"), getAgent: (id: string) => call(`/instances/${id}`), createAgent: (body: CreateAgentInput) => call("/instances", { method: "POST", body: JSON.stringify(body) }), deleteAgent: (id: string) => call<{ id: string; deleted: boolean }>(`/instances/${id}`, { method: "DELETE" }), start: (id: string) => call<{ id: string; status: string }>(`/instances/${id}/start`, { method: "POST" }), stop: (id: string) => call<{ id: string; status: string }>(`/instances/${id}/stop`, { method: "POST" }), restart: (id: string) => call<{ id: string; status: string }>(`/instances/${id}/restart`, { method: "POST" }), update: (id: string) => call<{ id: string; status: string; image_ref: string | null; image_digest: string | null; template_revision: number | null; }>(`/instances/${id}/update`, { method: "POST" }), resize: (id: string, body: ResizeInput) => call<{ id: string; status: string; resources: { cpu: number; memory: number; disk: number } }>( `/instances/${id}/resize`, { method: "POST", body: JSON.stringify(body) } ), exec: (id: string, command: string, user?: "root") => call<{ exit_code: number; stdout: string; stderr: string; truncated: boolean }>( `/instances/${id}/exec`, { method: "POST", body: JSON.stringify({ command, ...(user ? { user } : {}) }) } ), signedUrl: (id: string, port: number, ttlSeconds?: number) => call<{ url: string; port: number; expires_at: number }>(`/instances/${id}/signed-url`, { method: "POST", body: JSON.stringify({ port, ...(ttlSeconds ? { ttl_seconds: ttlSeconds } : {}) }), }), getBudget: (id: string) => call(`/instances/${id}/budget`), setBudget: (id: string, body: { monthly_cap_micros: number }) => call(`/instances/${id}/budget`, { method: "PATCH", body: JSON.stringify(body) }), getUsage: (id: string, month?: string) => call(`/instances/${id}/usage${month ? `?month=${encodeURIComponent(month)}` : ""}`), listTemplates: () => call<{ data: Template[] }>("/templates"), listModels: (id: string) => instanceCall(id, "/v1/models"), listSessions: (id: string) => instanceCall(id, "/v1/sessions"), getSession: (id: string, sessionId: string) => instanceCall(id, `/v1/sessions/${encodeURIComponent(sessionId)}`), deleteSession: (id: string, sessionId: string) => instanceCall<{ id: string; deleted: boolean }>( id, `/v1/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" } ), renameSession: (id: string, sessionId: string, title: string) => instanceCall<{ id: string; agent: string; renamed: boolean }>( id, `/v1/sessions/${encodeURIComponent(sessionId)}`, { method: "PATCH", body: JSON.stringify({ title }) } ), cancelResponse: (id: string, responseId: string) => instanceCall<{ id: string; status: string }>( id, `/v1/responses/${encodeURIComponent(responseId)}/cancel`, { method: "POST" } ), listFiles: (id: string, path?: string) => instanceCall(id, `/v1/files${path ? `?path=${encodeURIComponent(path)}` : ""}`), deleteFile: (id: string, path: string) => instanceCall<{ ok: boolean }>(id, `/v1/files?path=${encodeURIComponent(path)}`, { method: "DELETE" }), moveFile: (id: string, from: string, to: string) => instanceCall(id, "/v1/files", { method: "PATCH", body: JSON.stringify({ from, to }) }), makeDir: (id: string, path: string) => instanceCall(id, `/v1/files/dir?path=${encodeURIComponent(path)}`, { method: "POST" }), listIntegrationToolkits: (id: string, opts: { search?: string } = {}) => { const q = opts.search ? `?search=${encodeURIComponent(opts.search)}` : ""; return call(`/instances/${id}/integrations/toolkits${q}`); }, connectIntegration: (id: string, body: { toolkit: string }) => call(`/instances/${id}/integrations/connect`, { method: "POST", body: JSON.stringify(body), }), listIntegrationConnections: (id: string) => call(`/instances/${id}/integrations/connections`), disconnectIntegration: (id: string, connectedAccountId: string) => call<{ id: string; deleted: boolean }>( `/instances/${id}/integrations/connections/${connectedAccountId}`, { method: "DELETE" } ), }; ``` -------------------------------- ### Prompt for coding agent to set up the repo Source: https://github.com/agent37-platform/starter-kit/blob/main/README.md Paste this prompt into Claude Code or Codex to have the coding agent set up the repository locally, following SETUP.md, requesting the two login-gated keys (AGENT37_API_KEY and SUPABASE_ACCESS_TOKEN) and reporting the local URL. ```text Set this repo up and run it locally, end to end — follow SETUP.md. Ask me for the two login-gated keys it needs, then do everything else and tell me the local URL. ``` -------------------------------- ### Badge usage examples Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/ui-components.md Example usage of the Badge component with success and warning variants. ```tsx Running Starting ``` -------------------------------- ### instanceFetch(id, path, init?) Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/agent37.md Documentation for the instanceFetch function, which performs authenticated fetch requests to an agent instance's data plane. ```APIDOC ## `instanceFetch(id, path, init?)` ### Description Performs a fetch against an agent instance's data plane, targeting `https://{id}.agent37.app` with the given path. It injects the `X-Agent37-Key` header for authentication and buffers `ReadableStream` request bodies to avoid chunked transfer issues. ### Signature ```ts export async function instanceFetch(id: string, path: string, init?: RequestInit): Promise ``` ### Parameters - **id** (`string`) - Required - Instance id; the fetch targets `https://{id}.agent37.app` - **path** (`string`) - Required - Data-plane path, e.g. `/v1/responses` - **init** (`RequestInit`) - Optional - Standard fetch options (`method`, `headers`, `body`, `signal`, …) ### Returns - **Promise** - The raw `Response` (not parsed) so callers can stream an SSE body, upload bytes, or stream a download. ### Throws - **Agent37Error** - Throws `Agent37Error(500, "config_error", …)` if `AGENT37_API_KEY` is unset. HTTP errors are **not** thrown — the caller reads `res.ok`/`res.status`. ### Behavior Notes - A `ReadableStream` request body is buffered to an `ArrayBuffer` first (undici would otherwise send `Transfer-Encoding: chunked`, which the instance-host proxy drops, producing 0-byte writes); sized bodies pass through. - Data-plane auth is the raw key in `X-Agent37-Key` (no `Bearer` prefix). ### Example: Stream a chat turn ```ts const upstream = await instanceFetch(agentId, "/v1/responses", { method: "POST", headers: { "Content-Type": "application/json", Accept: "text/event-stream" }, body: JSON.stringify({ input: "summarize README.md", stream: true }), }); if (!upstream.ok || !upstream.body) throw new Error("upstream failed"); return new Response(upstream.body, { headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache, no-transform" }, }); ``` ### Example: Error handling ```ts const upstream = await instanceFetch(agentId, "/v1/responses", { method: "POST", body: JSON.stringify(payload) }); if (upstream.status === 409) { throw new Error("The agent is still finishing the previous message."); } ``` ``` -------------------------------- ### parseAgentTab usage examples Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/dashboard-tabs.md Example calls to parseAgentTab showing default, valid, and invalid segment handling. ```typescript parseAgentTab([]) // "chat" parseAgentTab(["files"]) // "files" parseAgentTab(["chat", "x"]) // null parseAgentTab(["bogus"]) // null ``` -------------------------------- ### POST /api/invitations/ Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/endpoints.md Accepts an invitation using a token fastest way to join a workspace. Runs the accept_invitation RPC with the verified user id. ```APIDOC ## POST /api/invitations/ ### Description Accepts an invitation and adds the signed-in user to the workspace. ### Method POST ### Endpoint /api/invitations/ ### Parameters #### Path Parameters - **token** (string) - Required - Invitation token ### Response #### Success Response (200) - **workspace_id** (string) - The workspace the user was added to #### Response Example { "workspace_id": "ws_123" } ### Error Responses - **400 invalid_request** - If the token is invalid or expired ``` -------------------------------- ### neutralizeHarnessName usage example Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/channels.md Example call showing the function replaces 'Hermes' with 'your agent' in a sample string. ```TypeScript neutralizeHarnessName("Connect Hermes to Discord DMs"); // "Connect your agent to Discord DMs" ``` -------------------------------- ### Build email-link callback URL with publicSiteOrigin Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/site-url.md Example of constructing the /auth/callback URL with the next parameter, as done in the login page. Uses publicSiteOrigin with window.location.origin as fallback. ```TypeScript // Build the email-link callback URL (as the login page does in src/app/login/page.tsx). const url = new URL("/auth/callback", publicSiteOrigin(window.location.origin)); url.searchParams.set("next", next); // -> https://{site}/auth/callback?next=… ``` -------------------------------- ### usd() function and usage examples Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/format.md Converts micro-dollars to a USD string with two decimals. The example calls show expected outputs. ```ts export function usd(micros: number): string { return `$${(micros / 1_000_000).toFixed(2)}`; } ``` ```ts usd(5_000_000); // "$5.00" usd(1_250_000); // "$1.25" ``` -------------------------------- ### createAdminClient() Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/supabase.md Documentation for the createAdminClient function, which returns a privileged Supabase client for server-side use. ```APIDOC ## createAdminClient() ### Description Creates and returns a cached, privileged Supabase admin client that uses the service-role key and bypasses Row Level Security (RLS). It is intended for server-only use and must never be imported into client components. ### Method Function ### Signature `createAdminClient(): SupabaseClient` ### Parameters None ### Returns - **SupabaseClient** - A Supabase client instance configured with the service-role key, with `persistSession` and `autoRefreshToken` set to `false`. ### Throws - **Error** - If `NEXT_PUBLIC_SUPABASE_URL` or `SUPABASE_SERVICE_ROLE_KEY` environment variables are missing. ### Usage Example ```ts import { createAdminClient } from "@/lib/supabase/admin"; const db = createAdminClient(); const { data, error } = await db.from("agents").select("*").eq("agent37_id", agentId).maybeSingle(); ``` ### Notes - The client is cached module-side and reused across requests. - All queries must be gated by TypeScript checks in `src/lib/auth.ts` first. - The `server-only` import ensures the client cannot be used in client components. ``` -------------------------------- ### Export helpers from scripts/setup.mjs Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/scripts.md Exports the helper functions from scripts/setup.mjs for use in other modules. The final line of the file. ```javascript export { loadEnv, setEnv, saveEnv, unquote, refFromUrl, pickPublicKey, pickServiceKey, isBlank }; ``` -------------------------------- ### Template interface Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/types.md An agent image template returned by GET /v1/templates. Used by GET /api/agents to compute update_available; registry templates compare image_ref, cloud-built ones compare revision vs the instance's template_revision. ```ts export interface Template { name: string; scope: "system" | "workspace"; // Absent for templates published by a cloud build, which carry image_digest instead. image_ref?: string; image_digest?: string; revision: number | null; default_port: number | null; agents: string[]; description: string; created: number | null; updated: number | null; } ``` -------------------------------- ### Create Supabase server client with createServerClient Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/supabase.md Creates an async Supabase server client bound to the request cookie store via next/headers cookies(). Reads the same NEXT_PUBLIC_ env vars. Cookie writes are best-effort: in read-only contexts like Server Components, cookies().set throws and is swallowed, so session refresh is handled by middleware. Used by getSession/requireUser and /auth/callback. ```ts export async function createClient() { const cookieStore = await cookies(); return createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, { cookies: { getAll() { return cookieStore.getAll(); }, setAll(cookiesToSet: { name: string; value: string; options: CookieOptions }[]) { try { cookiesToSet.forEach(({ name, value, options }) => cookieStore.set(name, value, options) ); } catch { // Read-only cookies in a Server Component; middleware handles refresh. } }, }, } ); } ``` -------------------------------- ### Agent interface Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/types.md A live Agent37 instance returned by GET /v1/instances, GET /v1/instances/{id}, and POST /v1/instances. Key fields include status, nested status_reason, resources, ports (null on current API versions), and metadata. ```ts export interface Agent { id: string; status: string; status_reason: { code: string; message: string; operation: string; at: number; } | null; template: string; // Null for images published by a cloud build; compare template_revision instead. image_ref: string | null; template_revision: number | null; resources: { cpu: number; memory: number; disk: number }; // Older API versions reported the instance's ports; current ones return null — // any port is reachable at a preview URL, nothing is declared. ports: { port: number; default: boolean; url: string }[] | null; user: string | null; name: string | null; metadata: Record | null; paid_through: number | null; past_due: boolean; created: number | null; } ``` -------------------------------- ### useAsyncAction usage with save button Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/providers-and-hooks.md Usage example for `useAsyncAction`: destructure `busy` and `run`, wrap an async operation in `run`, and disable the button while `busy` is true. The example shows a save action that calls `apiFetch` and shows a success toast. ```tsx const { busy, run } = useAsyncAction(); const save = () => run(async () => { await apiFetch(...); toast.success("Saved"); }); ``` -------------------------------- ### Mutation route with requireAgentAccess Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/auth.md Example mutation route using requireAgentAccess with 'admin' access. Demonstrates the admin-gated preamble and error handling pattern for BFF routes. ```ts // Mutation route: admin-gated access preamble. export async function POST(request: Request, { params }: Ctx) { try { const { id } = await params; const { db } = await requireAgentAccess(id, "admin"); // …perform the mutation… return json(result); } catch (e) { return handleError(e); } } ``` -------------------------------- ### listIntegrationToolkits(id, opts) Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/agent37.md Lists available integration toolkits for an agent instance. ```APIDOC ## GET /v1/instances/{id}/integrations/toolkits ### Description Lists available integration toolkits for an agent instance. ### Method GET ### Endpoint /v1/instances/{id}/integrations/toolkits ### Parameters #### Path Parameters - **id** (string) - Required - The agent instance ID. #### Query Parameters - **search** (string) - Optional - Search filter for toolkits. ### Response #### Success Response (200) - **IntegrationToolkitsResult** - The toolkits result object. #### Response Example { "data": [] } ``` -------------------------------- ### GET /api/workspaces/[id]/members Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/README.md Lists members of a workspace. ```APIDOC ## GET /api/workspaces/[id]/members ### Description Lists members of a workspace. ### Method GET ### Endpoint /api/workspaces/[id]/members ### Parameters #### Path Parameters - **id** (string) - Required - The workspace ID. ### Response #### Success Response (200) - **members** (array) - List of members. #### Response Example ```json [ { "userId": "string", "role": "member" } ] ``` ``` -------------------------------- ### GET /api/agents/{id}/budget Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/endpoints.md Retrieves the budget for an agent. ```APIDOC ## GET /api/agents/{id}/budget ### Description Gets the budget for an agent. ### Method GET ### Endpoint /api/agents/{id}/budget ### Parameters #### Path Parameters - **id** (string) - Required - Agent identifier. ### Response #### Success Response (200) Returns the Budget object. ### Errors - **401** - unauthorized - **403** - forbidden - **404** - not_found - **500** - db_error ``` -------------------------------- ### useFileBrowser: navigate, upload, mutate, and build content URLs Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/file-browser.md Shows the main usage of the useFileBrowser hook: navigate to a directory, upload files, create/rename/delete entries, and generate preview/download URLs via the BFF. The hook is multi-agent aware, so pass the active agent ID. Uploads PUT each file to /api/agents/{id}/files/content?path=…&overwrite=true with concurrency capped at 4; a failed file is toasted but doesn't abort the batch. ```ts const fb = useFileBrowser("a1b2"); // Navigate and upload await fb.navigate("/home/user/projects"); fb.uploadFiles(fileList); // Create + rename + delete await fb.createDir("src"); await fb.rename(entry, "new-name.ts"); await fb.remove(entry); // Redirect the file's bytes through the BFF const previewUrl = contentUrl("a1b2", entry.path, "inline"); const downloadUrl = archiveUrl("a1b2", "/home/user"); ``` -------------------------------- ### GET /api/workspaces Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/endpoints.md Retrieves all workspaces for the signed-in user with their role in each workspace. ```APIDOC ## GET /api/workspaces ### Description Returns all workspaces for the authenticated user, sorted by creation date. ### Method GET ### Endpoint /api/workspaces ### Response #### Success Response (200) - **workspaces** (array of WorkspaceWithRole) - List of workspaces with user role #### Response Example { "workspaces": [] } ``` -------------------------------- ### makeDir(id, path) Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/agent37.md Creates a directory on an agent instance (data-plane). ```APIDOC ## POST /v1/files/dir ### Description Creates a directory on an agent instance (data-plane). ### Method POST ### Endpoint /v1/files/dir ### Parameters #### Path Parameters - **id** (string) - Required - The agent instance ID (used to determine the instance host). #### Query Parameters - **path** (string) - Required - The directory path to create. ### Response #### Success Response (200) - **FileEntry** - The created directory entry. #### Response Example { "path": "/new/dir" } ``` -------------------------------- ### GET /api/agents/{id}/files/list Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/endpoints.md Lists files and directories for an agent. ```APIDOC ## GET /api/agents//files/list?path= ### Description Lists files in a directory for an agent. Member access. Returns a FileListResponse with resolved paths. ### Method GET ### Endpoint /api/agents/{id}/files/list ### Parameters #### Path Parameters - **id** (string) - Required - The agent ID. #### Query Parameters - **path** (string) - Optional - Directory path; defaults to agent workspace. ### Response #### Success Response (200) - **path** (string) - Resolved absolute path. - **parentPath** (string) - Parent directory path. - **entries** (array) - List of file entries. - **truncated** (boolean) - Whether listing was truncated. ``` -------------------------------- ### GET /api/agents/{id}/files/archive Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/endpoints.md Downloads a .tar.gz archive of files for an agent. ```APIDOC ## GET /api/agents//files/archive?path= ### Description Downloads a tar.gz archive of a directory or the entire agent workspace. Member access. Streams the archive with appropriate headers. ### Method GET ### Endpoint /api/agents/{id}/files/archive ### Parameters #### Path Parameters - **id** (string) - Required - The agent ID. #### Query Parameters - **path** (string) - Optional - Directory path; defaults to agent workspace. ### Response #### Success Response (200) - **Content-Type** (string) - Archive media type. - **Content-Disposition** (string) - Attachment filename. - **Cache-Control** (string) - `no-store`. - Body: streamed .tar.gz. ``` -------------------------------- ### listTemplates() Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/agent37.md Lists all available agent templates. ```APIDOC ## GET /v1/templates ### Description Lists all available agent templates. ### Method GET ### Endpoint /v1/templates ### Parameters None ### Response #### Success Response (200) - **data** (Template[]) - Array of Template objects. #### Response Example { "data": [] } ``` -------------------------------- ### GET /api/agents/{id}/usage Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/endpoints.md Retrieves usage for an agent for a given month. ```APIDOC ## GET /api/agents/{id}/usage ### Description Gets usage for an agent for a specific month. ### Method GET ### Endpoint /api/agents/{id}/usage ### Parameters #### Path Parameters - **id** (string) - Required - Agent identifier. #### Query Parameters - **month** (string) - Optional - Month in YYYY-MM format. ### Response #### Success Response (200) Returns the Usage object. ### Errors - **401** - unauthorized - **403** - forbidden - **404** - not_found - **500** - db_error ``` -------------------------------- ### agent37.listIntegrationToolkits Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/agent37.md Lists available integration toolkits for an agent instance. ```APIDOC ## agent37.listIntegrationToolkits ### Description Lists available integration toolkits for an agent instance. ### Method GET ### Endpoint /instances/{id}/integrations/toolkits?search={search} ### Parameters #### Path Parameters - **id** (string) - Required - The agent instance ID. #### Query Parameters - **search** (string) - Optional - Search query. ### Response #### Success Response (200) - **IntegrationToolkitsResult** (IntegrationToolkitsResult) - The toolkits result. #### Response Example { "data": [] } ``` -------------------------------- ### Using apiError Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/http.md Usage example: returns a 400 error with a custom message and code. ```typescript return apiError("monthly_cap_usd must be a non-negative number", 400, "invalid_request"); ``` -------------------------------- ### GET /api/agents/[id]/chat/responses/[responseId]/stream Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/README.md Streams a chat response (SSE). ```APIDOC ## GET /api/agents/[id]/chat/responses/[responseId]/stream ### Description Streams a chat response (SSE). ### Method GET ### Endpoint /api/agents/[id]/chat/responses/[responseId]/stream ### Parameters #### Path Parameters - **id** (string) - Required - The agent ID. - **responseId** (string) - Required - The response ID. ### Response #### Success Response (200) - **stream** (SSE) - Server-sent events stream. #### Response Example ```text SSE stream ``` ``` -------------------------------- ### agent37.makeDir Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/agent37.md Creates a directory in an agent instance's filesystem. ```APIDOC ## agent37.makeDir ### Description Creates a directory in an agent instance's filesystem. ### Method POST ### Endpoint /instances/{id}/v1/files/dir?path={path} ### Parameters #### Path Parameters - **id** (string) - Required - The agent instance ID. #### Query Parameters - **path** (string) - Required - The directory path to create. ### Response #### Success Response (200) - **FileEntry** (FileEntry) - The created directory entry. #### Response Example { "path": "/tmp/newdir" } ``` -------------------------------- ### Query agents with createAdminClient Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/supabase.md Shows how to use the admin client to query the agents table by agent37_id. The client bypasses RLS, so queries must be gated by TypeScript checks in src/lib/auth.ts. ```ts import { createAdminClient } from "@/lib/supabase/admin"; const db = createAdminClient(); const { data, error } = await db.from("agents").select("*").eq("agent37_id", agentId).maybeSingle(); ``` -------------------------------- ### GET /api/agents//integrations/connections Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/endpoints.md Retrieves the list of integration connections for a specific agent. ```APIDOC ## GET /api/agents//integrations/connections ### Description Lists all integration connections for a specific agent. ### Method GET ### Endpoint /api/agents//integrations/connections ### Parameters #### Path Parameters - **id** (string) - Required - Agent identifier ### Response #### Success Response (200) - **connections** (array) - List of integration connections #### Response Example { "connections": [] } ``` -------------------------------- ### loadEnv(file) Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/scripts.md Exported helper function to parse a `.env`-style file. ```APIDOC ## [Function] loadEnv(file) ### Description Parse a `.env`-style file into a `{ file, lines: string[], map: Record, dirty: boolean }` record. ### Signature `(file: string) => { file, lines, map, dirty }` ### Parameters - `file` (string) - Required - Path to the `.env` file ### Returns - `file` (string) - The file path - `lines` (string[]) - The lines of the file - `map` (Record) - Key-value map of environment variables - `dirty` (boolean) - Whether the record has been modified ### Example ```js import { loadEnv } from "../scripts/setup.mjs"; const env = loadEnv(path.join(root, ".env.local")); ``` ``` -------------------------------- ### ChatHistoryMessage interface Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/types.md One message in a conversation's history (GET /v1/sessions/{id}). ```ts export interface ChatHistoryMessage { id: string; session_id: string; role: "user" | "assistant" | "system"; content: string; thinking?: string; created_at: number; } ``` -------------------------------- ### makeDir Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/agent37.md Creates a directory in the agent's file system. Surfaces upstream typed errors as Agent37Error. ```APIDOC ## makeDir ### Description Creates a directory in the agent's file system. Surfaces upstream typed errors as `Agent37Error`. ### Method makeDir ### Parameters - **path** (string) - Required - The directory path to create. ### Response No return value. ### Errors - **Agent37Error** - Preserves `code` and `status` from upstream errors. ``` -------------------------------- ### createAgent Source: https://github.com/agent37-platform/starter-kit/blob/main/_autodocs/api-reference/agent37.md Creates a new agent instance with specified template, resources, user, and budget. ```APIDOC ## createAgent ### Description Creates a new agent instance using a specified template and resource configuration. ### Method createAgent ### Parameters - **template** (string) - Required - The template to use for the agent (e.g., "agent37-hermes"). - **resources** (object) - Required - Resource allocation for the agent. - **cpu** (number) - Required - Number of CPU cores. - **memory** (number) - Required - Memory in GB. - **disk** (number) - Required - Disk space in GB. - **user** (string) - Required - User identifier. - **budget** (object) - Optional - Budget configuration. - **monthly_cap_micros** (number) - Required - Monthly spending cap in micros (e.g., 5,000,000 for $5). ### Request Example ```ts const agent = await agent37.createAgent({ template: "agent37-hermes", resources: { cpu: 2, memory: 4, disk: 6 }, user: userId, budget: { monthly_cap_micros: 5_000_000 }, }); ``` ### Response Returns an agent object with an `id` property. ### Errors - **Agent37Error** with status 402 - Insufficient wallet funds. - **Agent37Error** with code "config_error" - AGENT37_API_KEY is not set on the server. ```