# AGENT.md — somewhere.tech for coding agents ## Getting started — build, deploy, verify `somewhere init --name ` in an empty folder writes a local React + TypeScript starter without login. The default includes working sign-in; extend it using the README file map. Minimal/bare starters omit auth. `init --catalog --json` lists modules for `--features`. No account yet? `npx @somewhere-tech/cli deploy` publishes a temporary app and prints its live URL, claim URL, and expiry. Login is needed for account-owned operations, the email test inbox and cron. On a hosted VM, after consent, `somewhere login` prints a code a human approves in their browser; the machine stays signed in. Ask `somewhere advisor ""` how to build or fix it. For a reference, use `somewhere docs --section ` (MCP: `advisor({ question })`, `docs({ topic })`, `catalog`). After every change: 1. `somewhere typecheck`, then `somewhere deploy` (do not build first). Deploy runs the platform compile, schema and secret checks and refuses a blank page before going live; `somewhere deploy-check` runs them without publishing (diagnosis, review, `--run /api/x`). 2. `somewhere verify` — desktop and phone screenshots, console and network health; `somewhere verify --flow flow.json` fills and clicks. Several users: `actors` + `journey` (`somewhere docs browser`). 3. `somewhere browser` inspects a page; `somewhere logs --tail 10`, then `somewhere errors`: read the failure first. 4. Email: sign up as `@.test.somewhere.site`, then `somewhere email test-inbox ` prints the message and its magic link. Routes: `index.html` loads `src/main.tsx`; every extensionless path with no file (`/signin`) serves `index.html`, so one app routes by `location.pathname`. `api/notes/[id].ts` is `/api/notes/:id`; `_`-prefixed names are import-only helpers. Avoid names differing only in letter case (`SignIn.tsx`, `signin.tsx`). With auth enabled, `api/auth/[...path].ts` is `export { somewhereAuth as default } from '@somewhere-tech/sdk/server'`; pages use `createSomewhereAuth()` from `@somewhere-tech/sdk/auth` (no SDK: `docs({ topic: 'auth-client' })`). `auth.signUp({ email, password, displayName? })` / `auth.signIn({ email, password })` return the user or throw with the message. Gate pages on `auth.getState().status` (React: `useAuthState()`) as the auth starter's `src/App.tsx` does. Sign-up signs the user in with `email_verified: false`; unverified users can sign in and pass `auth: 'required'`. `sw.auth.requireUser(req)` returns `{ id, email, role, email_verified, … }` or throws 401 `AUTH_REQUIRED`; `sw.auth.fromRequest(req)` returns it or `null`. Functions: a bare `export default async function (req, sw)` returning a `Response` is always valid. The optional wrapper `sw.endpoint({ auth: 'none' | 'optional' | 'required', body, rateLimit, handler: async ({ body, user, params }, sw) => value })` answers 401/400 itself and sends `value` as JSON. Params: `params.id` there, `sw.params.id` bare. `somewhere typecheck` types bare handlers as `(req: Request, sw: SomewhereRuntimeContext)`. Data: tables in `db/schema.ts` — `owner()` (each user's own rows; no auth guard), `shared()` or `serverOnly()` — with a `client` block for browser access via `somewhere:data`; a custom endpoint enforces its own caller policy. `sw.db.from` / `insert` / `update` / `remove` return `{ data: rows[], count, changes }`; `where: { a: 1, b: { in: ids }, c: { gte: 2 }, d: null }` (one operator per column). Raw `sw.db.query(sql, params)` runs as written (add `WHERE user_id = ?`; managed projects refuse it). Independent reads: one `Promise.all`. ## Function format ```js export default async function (req, sw) { const body = await req.json(); const r = await sw.db.from('users', { where: { id: body.id }, limit: 1 }); // r.data = array of row objects (NOT .rows, NOT .results) // r.count = number of rows returned // r.changes = rows affected by INSERT / UPDATE / DELETE return Response.json({ user: r.data[0] ?? null }); } ``` ## What somewhere.tech provides somewhere.tech is a full-stack application platform for coding agents. One project holds raw frontend source, `api/*` functions, a database, files, auth, email, AI, background work, live updates, payments, logs, domains, and deploy history. The platform compiles source on deploy. The normal project shape is: - `index.html` and `src/*` for the browser application. - `api/*.ts` for server functions; `api/hello.ts` becomes `/api/hello`. - `db/schema.ts` when the platform should manage declared table structure. - `package.json` for dependencies, plus `package-lock.json` (v2/v3) when versions must be exact. Do not upload `node_modules`. Deploy raw source with `somewhere deploy`, or use MCP `project_deploy` without a shell. Never deploy `dist/` or `build/`: bundled output deploys with a warning and loses source round-trips (export, find/replace, visual editing); `--prebuilt` accepts that. Keep large binaries in project files. Project inventory is render-ready in one call: `GET /v1/projects` and `project_list()` include each project's status, `last_deployed_at`, `latest_screenshot_url`, and `favicon_url`. The asset URLs are null until the corresponding live release exists; the screenshot URL is a temporary signed capability that an image element can render directly. For a new project, `somewhere deploy` first and verify the live URL; that deploy is the backend. `somewhere dev` is optional frontend hot reload on localhost against it. Once the app has real users or data to protect, `somewhere preview` sends saves to a private platform URL while the published release stays unchanged. See `docs({ topic: 'local-dev' })` and `docs({ topic: 'dev-environments' })`. ## GitHub: connect once, deploy HEAD, then deploy every push `somewhere git connect owner/repo` uses the GitHub App: a human grants repository access once — no personal access token, no manually configured webhook — and the command deploys the selected branch's current HEAD, waits for that exact commit, then prints its status, logs link, and live URL. Later pushes to the tracked branch deploy through the same pipeline with deploy source `github`. `somewhere git status` and `somewhere git disconnect` manage the connection; disconnect leaves the deployed site live. Without a shell, `github_app_install`, `github_installations`, `github_list_repos`, and `github_connect` do the same. `docs({ topic: 'github' })` has the flags, the REST and MCP shapes, and the PAT and manual-webhook fallbacks. ## Database: choose the interface that fits the operation Both paths share one database: - **Structured queries and managed tables:** `sw.db.from(...)`, `insert`, `update`, `remove`, and schemas declared in `db/schema.ts` make table intent visible. Structured operations can apply declared owner/member scope. Empty managed tables can change among `owner()`, `shared()`, and `serverOnly()` on production when no links, views/triggers, or raw SQL name them. Managed schemas can add, adopt, rename, or mark removals during deploy; and `sw.db.live(name, sw.db.from(...))` can declare a bounded server-side live view on owner/shared tables. That signed channel carries invalidation only, so the browser re-calls its function and never applies a row from the wire. Member-scoped live declarations are refused for now. A declared live view is the only live path a browser can subscribe to: there is no caller-named channel API in deployed functions, and raw SQL is never subscribable. - **Raw SQL:** On a SQL-mode project, `sw.db.query(sql, params)` and `sw.db.batch(statements)` run directly. Managed projects refuse ordinary raw calls with `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY`; use declared operations normally. For an exceptional raw read, authorize the caller and choose `sw.db.server.query` / `batch`. Declared row permissions do not apply there, and managed raw writes remain refused. CLI, MCP, and dashboard SQL is unaffected. `docs({ topic: 'sw.db' })` covers both interfaces, `docs({ topic: 'database-engine' })` limits and concurrency, and `docs({ topic: 'sql-compatibility' })` Postgres-oriented SQL. Run schema changes with `db/schema.ts`, `somewhere call db_migrate ''`, MCP `db_migrate`, or dashboard. DDL inside a deployed function is rejected. `db_migrate` defaults to production; `target:"preview"` also needs `preview_session_id`. Ambiguity never falls back, and preview DDL dies with the session. A managed schema changes only with a release: `somewhere deploy` applies `db/schema.ts` to production and a preview release applies it to the preview copy, with the production-deploy planner — additive changes apply, removing or renaming a table or column is refused on production (preview only), and a later deploy of the same schema is a no-op. There is no separate schema-apply command. Until a deploy runs, a structured query on a declared-only table fails with `TABLE_INTENT_REQUIRED`. ## Defaults every app needs - **Files:** `sw.fs` inside functions, `somewhere fs` for common shell operations, `somewhere call fs_ ''` for the complete file-tool surface, or the matching MCP file tool without a shell. Signed and public URLs have explicit authority and expiry rules. - **Environment:** `sw.env.NAME` reads server keys. Browser keys need `public: true` plus a `VITE_`/`REACT_APP_` prefix; visitors can read them. - **Background work:** jobs when callers need durable status/results, queues for fire-and-forget work, cron for schedules (plan-minimum fire interval — `docs({ topic: 'cron' })`). - **Observability:** write structured `sw.logs` entries and inspect deploy logs, runtime errors, screenshots, and smoke results before claiming success. - **Verification:** run `somewhere typecheck`, deploy, then `somewhere verify --flow flow.json` (or MCP `site_verify`) for named steps, health, and desktop + phone screenshots. `somewhere deploy --verify flow.json` chains it after deploy; omit the flow for the default check. Browser actions use `[{"fill":"#email","value":"a@b.co"}]`; `--flow` wraps them as `{"actions":[{"fill":"#email","value":"a@b.co"}]}`. ## Working rules 1. Components and browser code call same-origin `api/*`; functions use `sw.*`. 2. Inspect source and live state before patching a project you did not build. 3. Treat error codes and `hint` fields as contracts; follow the linked docs topic. ## Recent behaviour changes Dated, newest first: `docs({ topic: 'changes' })` — read it before assuming a new failure is in your code. Latest: **2026-09-02** local dev now reaches your project's database and files on every plan (`docs({ topic: 'local-dev' })`). ## Complete capability index Every documented capability is listed here. Use the exact topic pointer for signatures, examples, limits, and failure modes. ### Start, SDKs, and local workflow - **Getting Started — Build an app in 10 minutes** — Build, deploy, and verify a first app. `docs({ topic: 'getting-started' })` - **Handled for you — the foundation behind your app** — Built-in work and the choices your app owns. `docs({ topic: 'handled-for-you' })` - **Setup — Use the CLI, or connect MCP without a shell** — Connect with CLI or MCP. `docs({ topic: 'setup' })` - **@somewhere-tech/cli — full command reference** — CLI commands and JSON output. `docs({ topic: 'cli' })` - **@somewhere-tech/sdk — optional adapter, one auth path** — Optional SDK for browser and server code. `docs({ topic: 'sdk' })` - **Client SDKs — languages and status** — See the supported client SDK languages, maturity, and authentication shapes. `docs({ topic: 'sdks' })` - **Local dev — `somewhere dev`** — Run locally with `somewhere dev`; pull, typecheck, inspect. `docs({ topic: 'local-dev' })` - **Verify before deploy** — Source, dependency, route, and deploy checks before publishing. `docs({ topic: 'verify-before-deploy' })` ### Functions, deploys, and projects - **Deployed Functions** — Server routes: standard Request/Response handlers plus the sw runtime. `docs({ topic: 'functions' })` - **Typed functions — one contract, both sides** — A handler contract generates a typed browser client and change warnings. `docs({ topic: 'typed-functions' })` - **sw.endpoint — declarative endpoint wrapper** — Optional authentication, validation, and rate limiting around a handler. `docs({ topic: 'sw.endpoint' })` - **sw.fetch — outbound HTTP fetch from a function** — Policy-checked outbound HTTP requests from deployed functions. `docs({ topic: 'sw.fetch' })` - **Deploy** — Deploy raw source, inspect compilation, promote, roll back, undeploy. `docs({ topic: 'deploy' })` - **Limits** — Function, record, env, upload, and deploy ceilings. `docs({ topic: 'limits' })` - **Preview — `somewhere preview` (Builder, Pro and Scale)** — Use hosted previews, then promote (Builder and higher). `docs({ topic: 'dev-environments' })` - **Deploy intelligence — what happens after every deploy** — The analysis and diagnostics produced after each deploy. `docs({ topic: 'deploy-intelligence' })` - **Projects — Full Lifecycle** — Create, inspect, patch, export, transfer, archive, restore, delete. `docs({ topic: 'projects' })` - **Project groups** — Organize projects into groups with shared ownership and configuration. `docs({ topic: 'groups' })` - **GitHub push-to-deploy** — Connect a repository for push-triggered deployments and deployment status. `docs({ topic: 'github' })` - **Inspect — Read live state before writing** — Read source, versions, routes, logs, and live state before changing a project. `docs({ topic: 'inspect' })` - **Smoke tests — deploy and recurring checks** — Configure and inspect automatic uptime and behavior checks. `docs({ topic: 'smoke' })` - **What the platform guarantees — what your code can't get wrong** — See which runtime, deployment, and safety responsibilities the platform owns. `docs({ topic: 'guarantees' })` ### Database, identity, and security - **sw.db — Database (inside deployed functions)** — Raw SQL or structured operations, atomic batches, per-user scoping. `docs({ topic: 'sw.db' })` - **Declared data — the schema file is the contract** — Tables, browser columns, visitors in db/schema.ts; generated client; server authority. `docs({ topic: 'declared-data' })` - **Database — SQL support, capabilities, and limits** — Capabilities, limits, concurrency, supported SQL. `docs({ topic: 'database-engine' })` - **SQL compatibility — what Postgres code ports, and what doesn't** — How Postgres-style SQL translates and where it differs. `docs({ topic: 'sql-compatibility' })` - **PostgreSQL** — Attach an external PostgreSQL database you own; query it with its own driver. `docs({ topic: 'postgres' })` - **Live data — one poller, fan out to every client** — Fan one server-side data poller out to many connected clients. `docs({ topic: 'live-data' })` - **Portability — getting your data out** — Export data, move to another database, and what is not exported. `docs({ topic: 'portability' })` - **Migrating a Supabase app** — Move a Supabase-shaped application and data onto somewhere.tech. `docs({ topic: 'migration-supabase' })` - **Auth — End-User Authentication** — End-user sign-in, sessions, OAuth, MFA, verification, account lifecycle. `docs({ topic: 'sw.auth' })` - **Auth on the client — the correct session code** — Implement browser authentication with same-origin httpOnly cookie sessions. `docs({ topic: 'auth-client' })` - **auth.md — letting AI agents register as end-users** — Let authorized AI agents register and sign in as application end users. `docs({ topic: 'auth-md' })` - **Security model — who can read/write what** — Developer, project, end-user, and server authority boundaries. `docs({ topic: 'security-model' })` - **CORS — which browser origins may call your `/api/*` functions** — Your own origins already work; add a third-party origin. `docs({ topic: 'cors' })` ### Files, content, and the web - **sw.fs — File Storage (inside deployed functions)** — Store, read, version, search, publish, sign, move, and upload files. `docs({ topic: 'sw.fs' })` - **Declared files** — Who reads, uploads, replaces, deletes files; somewhere:files. `docs({ topic: 'declared-files' })` - **Search — Two Surfaces** — Search project files or create semantic indexes for application data. `docs({ topic: 'search' })` - **Render — PDFs** — Render HTML or URLs into PDF documents. `docs({ topic: 'render' })` - **Browser — your live app's eyes, ears, and hands** — Inspect and exercise live sites: screenshots, console output, interactions. `docs({ topic: 'browser' })` - **sw.web — Read pages from the public web** — Read and extract content from public web pages. `docs({ topic: 'sw.web' })` - **sw.image — Image transformations** — Transform, resize, convert, and optimize image assets. `docs({ topic: 'sw.image' })` - **Video — Upload, Stream, Manage** — Upload, process, stream, inspect, and manage video (new uploads on Pro and Scale). `docs({ topic: 'video' })` - **Design System — Read before generating UI** — Apply the platform design guidance when generating or editing interfaces. `docs({ topic: 'design-system' })` ### Email, notifications, live updates, and calls - **sw.email — Send Email (inside deployed functions)** — Outbound transactional email is available on Free, Builder, Pro, Scale, and Enterprise. Managed sender: project users/owner only; a verified sender domain reaches anyone. Caps: `/v1/pricing`. `docs({ topic: 'sw.email' })` - **Inbox — Inbound Email** — Receive, search, thread, reply to, and route inbound email. `docs({ topic: 'inbox' })` - **sw.notifications — unified notify primitive** — One notification through bell, push, or zero-setup email. `docs({ topic: 'sw.notifications' })` - **sw.push — Web Push notifications** — Send web push to subscriptions registered with developer authority. `docs({ topic: 'sw.push' })` - **Live updates — a browser subscribing to a declared database view** — Subscribe a browser to a declared live view; inspect signed platform channels. `docs({ topic: 'live' })` - **Calls — Real-Time Audio/Video Sessions** — Create and manage realtime audio and video call sessions. `docs({ topic: 'calls' })` ### AI - **sw.ai — AI Models (inside deployed functions)** — Call text, embedding, image, speech, moderation, memory, and agent models. `docs({ topic: 'sw.ai' })` - **Somewhere agent loop — sw.agent** — Run model-and-tool loops inline or durably; inspect or cancel durable runs. `docs({ topic: 'sw.agent' })` ### Background work and traffic controls - **sw.jobs — Background Jobs (inside deployed functions)** — Run durable background work with status, retries, results, and cancellation. `docs({ topic: 'sw.jobs' })` - **sw.queue — Fire-and-Forget Background Work** — Enqueue fire-and-forget work for asynchronous handlers. `docs({ topic: 'sw.queue' })` - **Cron — Scheduled Tasks** — Schedule recurring function execution with cron expressions. `docs({ topic: 'cron' })` - **sw.rateLimit — Rate limiting** — Apply application-level request and action rate limits. `docs({ topic: 'sw.rateLimit' })` ### Calendar, payments, billing, and pricing - **Calendar — atomic holds and reservations** — Reserve time atomically with holds, availability, confirmation, and release. `docs({ topic: 'calendar' })` - **Payments — Stripe Connect** — Onboard sellers and create, inspect, refund, and reconcile payments. `docs({ topic: 'payments' })` - **sw.billing — plans & feature gating for YOUR app's users** — Define and enforce plans and entitlements for an application’s own users. `docs({ topic: 'sw.billing' })` - **Pricing** — Read the authoritative current somewhere.tech plans and limits. `docs({ topic: 'pricing' })` - **Plans & Pricing** — Understand somewhere.tech usage, plan activation, and account billing. `docs({ topic: 'billing' })` - **Pricing comparison — somewhere.tech vs the stack** — Compare costs with a conventional assembled stack. `docs({ topic: 'pricing-comparison' })` ### Configuration, domains, and operations - **sw.env — Environment Variables (inside deployed functions)** — Set server keys and deliberate public browser keys in one project store. `docs({ topic: 'sw.env' })` - **Custom Domains** — Attach, verify, inspect, and remove custom domains. `docs({ topic: 'domains' })` - **You own your domain** — Understand domain custody, portability, renewal, and detachment. `docs({ topic: 'domain-ownership' })` - **sw.logs — Application Logging (inside deployed functions)** — Write structured application logs and inspect runtime failures. `docs({ topic: 'sw.logs' })` - **Analytics — Track Events, Query Aggregates** — Track events and query aggregates for an application. `docs({ topic: 'analytics' })` - **Tasks — Per-project ticketing** — Per-project work, comments, relationships, and completion records. `docs({ topic: 'tasks' })` - **Recent behaviour changes** — Read the dated log of behaviour changes, newest first. `docs({ topic: 'changes' })` - **Platform Feedback — Bug? Doc gap? Tell us.** — Report platform defects or documentation gaps and follow their resolution. `docs({ topic: 'feedback' })` ### Architecture, troubleshooting, and comparisons - **Architecture Patterns — How to wire common app shapes** — Compose primitives into common application architectures. `docs({ topic: 'architecture-patterns' })` - **Speed** — Where a request spends its time, and how to make an app faster. `docs({ topic: 'speed' })` - **Common Mistakes — Things real users have hit** — Avoid recurring deploy, auth, database, and file mistakes. `docs({ topic: 'common-mistakes' })` - **Troubleshooting — Common errors and what to do** — Diagnose common platform errors and follow their recovery paths. `docs({ topic: 'troubleshooting' })` - **Discovered API surface** — The generated call-level REST, runtime, and MCP surface. `docs({ topic: 'api-surface' })` - **somewhere.tech vs Supabase — honest comparison** — Compare capabilities and operating tradeoffs with Supabase. `docs({ topic: 'vs-supabase' })` - **somewhere.tech vs Vercel — honest comparison** — Compare capabilities and operating tradeoffs with Vercel. `docs({ topic: 'vs-vercel' })` ### Guides and recipes - **Recipe — Sign-in, email alerts, daily reminder** — Owner rows, a public form that emails the owner, a daily reminder. `docs({ topic: 'recipe-signed-in-app' })` - **Recipe — AI agent with tool calls** — AI app with tool calls and persisted conversation state. `docs({ topic: 'recipe-ai-agent' })` - **Recipe — Booking / calendar app** — Start booking checkout with a calendar hold. `docs({ topic: 'recipe-booking' })` - **Recipe — Fixed-price catalog checkout** — Start a fixed-price catalog checkout. `docs({ topic: 'recipe-ecommerce' })` - **Recipe — Multi-chat (Claude.ai-style conversation list)** — Build a multi-conversation chat application with history and search. `docs({ topic: 'recipe-multi-chat' })` - **Recipe — Cheap model escalates to smart model when stuck** — Escalate from a low-cost model to a stronger model when a task stalls. `docs({ topic: 'recipe-escalation' })` ## More information - Anonymous quickstart: - Agent contract (the file project initialization writes): - Security practices: - Migration and portability: - Long-form reference: For current plans, prices, and limits, see https://somewhere.tech/pricing. If a documented contract appears wrong, call `support_ticket({ message })` with the smallest reproduction; read it back later with `support_ticket({ ticket_id })`.