Custom-app development
Custom-app bundles are arbitrary JS apps served by Oxy at
https://<env>/customer-apps/<org>/<slug>/. Oxy is a data gateway:
serves static assets, gates cookie auth, and proxies queries. The
bundle is opaque above the data plane — no per-app server config.
This file is the contract. The detail lives in references/ — see
Read next for which file answers what.
The Oxy App Kit (use it)
Two small packages remove the footguns — default to them rather than wiring a
bundle by hand:
@oxy-hq/sdk — the data layer (useQuery, useSemanticQuery,
useAgentRun, <OxyChat>); see rule 2 and the @oxy-hq/sdk README.
@oxy-hq/vite-plugin (oxyApp() in vite.config.ts) — bakes the asset
base path from the manifest, copies oxy-app.json into out/, proxies
/api in dev, and injects the window.__OXY_APP__ shim. Dropping it
re-introduces the #1 bug — asset 404s → blank dashboard (rule 3).
Scaffold both with pnpm create @oxy-hq/oxy-app my-app (templates vite — the
default — functions, dashboard, single-store; -t functions adds Oxy
Functions). The platform is kit-agnostic (any bundle with a correct base path
works), but hand-rolling means owning the base-path + dev-proxy wiring yourself.
Three rules
oxy-app.json (project root, not public/) is identity only.
Schema:
{
"$schema": "https://unpkg.com/@oxy-hq/sdk/schema/oxy-app.schema.json",
"schemaVersion": 2,
"slug": "url-slug",
"orgSlug": "your-org",
"name": "Display Name"
}
Required: schemaVersion (must be 2), slug (1–63 lowercase
letters, digits and single hyphens — it becomes the served path and
the OLTP schema name).
Strongly recommended: orgSlug (lets @oxy-hq/vite-plugin derive
the asset base path automatically, so plain pnpm build produces
a bundle ready to drop into the linked org with no env var, and lets
pnpm dev and oxyc publish find the app without --org / OXY_ORG;
create-oxy-app --org <slug> writes it).
Optional: name (display), description, icon, art, status
(launcher card), projectId (dev-time hint), build (what oxyc publish runs — install, command, outDir; the plugin reads
outDir too), functions, env, storage, notifications, widgets, …
One contract. The file is validated against the JSON Schema
@oxy-hq/sdk ships (schema/oxy-app.schema.json, generated from the
SDK's OxyAppManifest type; $schema gives your editor completion)
by oxyc validate, oxyc publish, the Vite plugin and the SDK's own
loader — the same check, the same words. A wrong type, a bad name or
a missing required field is refused; a field the schema does not know
is a warning (the platform ignores what it does not read — so a
typo'd timeoutSecond is said, not silently dropped). Every field and
what the server does with it: OxyAppManifest in
@oxy-hq/sdk/manifest, which also exports the schema, isValidSlug
/ isValidFunctionName and validateOxyAppManifest for a tool of
your own.
At serve time, oxy injects the authoritative org + project from
the admin row via window.__OXY_APP__ — the manifest's orgSlug
and projectId are advisory hints only, never enforcement.
Do not invent products, writers, or from:-blocks. Those
don't exist in v2 and the schema rejects them.
File location: <root>/oxy-app.json, sibling to
vite.config.ts. The vite-plugin reads it from there, and so does
oxyc publish (only from the directory it runs in); legacy bundles
that kept it under public/ get neither the plugin's base-path
derivation nor the publish's slug / orgSlug.
All data flows through SDK hooks → oxy HTTP endpoints. The
surface is intentionally small:
| Hook / component |
Endpoint |
When |
useQuery({sql}) |
POST /api/projects/:id/query |
Raw SQL, 10k row cap |
useSemanticQuery({topic, …}) |
POST /api/projects/:id/semantic-query |
Reference topics/measures by name |
useAgentRun({agentId}) |
POST /api/projects/:id/agents/:id/asks + SSE |
Streaming chat / Q&A |
useAskAgent() |
POST /api/projects/:id/agents/:id/asks with wait_seconds |
One-call answer (≤45 s) for a button or a batch; status: "running" when the wait runs out |
useProcedureRun({procedureId}) |
POST /api/projects/:id/procedures/:id/runs ⚠️ beta |
Long-running batch |
useFunction(name) |
POST /customer-apps/<org>/<slug>/fn/<name> + SSE |
Invoke a server-side Oxy Function (see below) |
<OxyChat agentId="…"/> |
wraps useAgentRun |
Drop-in chat UI |
<OxyAnswer {...run}/> |
renders any run |
Drop-in answer renderer |
import { OxyChat, useQuery } from "@oxy-hq/sdk";
const { rows } = useQuery({
sql: "SELECT col FROM t WHERE x = {{ params.x | sqlquote }}",
}, { params: { x: someState } });
// ...
<OxyChat agentId="analytics" />
To try an agent from a terminal the same way: oxyc ask <workspace-id> <agent> "<question>" --json (one request, answer on stdout; --thread <id> to reply
to a clarifying question).
See the @oxy-hq/sdk README for the full reference, including
OxyApiError parsing and beta-surface caveats.
Server-side work → Oxy Functions, not the browser. useQuery &
friends run in the client; for work the browser shouldn't do
(warehouse writes, ELT kick-offs, external API calls, secret-bearing
logic) ship a TypeScript handler under functions/ and invoke it
with useFunction(name).invoke(body?). Declare it in oxy-app.json:
{ "schemaVersion": 2, "slug": "my-app",
"functions": { "daily-rollup": { "route": true, "timeoutSeconds": 30 } } }
// functions/daily-rollup.ts — runs on Oxy's isolate runtime
export default async (req, ctx) => {
const { rows } = await ctx.query("SELECT … FROM …"); // data-plane ctx
return Response.json({ rows });
};
ctx bridges to the data plane: ctx.query / ctx.queryStream,
ctx.semantic.query, ctx.warehouse.query,
ctx.warehouse.{insert,exec,upsert} (to Airhouse, or to a customer
warehouse the function names in customerWarehouseWrites), ctx.airway.run,
ctx.fetch (SSRF-allowlisted), ctx.env, ctx.user, ctx.log.
What the app STORES picks its surface by shape — facts through
ctx.airhouse, records through ctx.oltp, files through
ctx.storage — and customer warehouses are read-only. See
Where data goes below before writing anything.
oxyc publish bundles functions/*.ts with
esbuild — no separate backend to stand up. Author-facing types:
OxyFunctionContext / OxyFunctionRequest from @oxy-hq/sdk; a worked
example ships in the functions template (pnpm create @oxy-hq/oxy-app my-app -t functions).
OXY_APP_BASE_PATH must match the path the bundle is linked
under. @oxy-hq/vite-plugin resolves it from (in order):
OXY_APP_BASE_PATH env → orgSlug + slug in oxy-app.json →
/. oxyc publish sets that env to /customer-apps/<org>/<slug>/
for the build automatically, and the vite-plugin derives the same
from the manifest for pnpm dev / pnpm build. Mismatch → asset
404s → blank dashboard.
Where data goes (the shape of the data picks the store)
| The data |
Store |
In a function |
In oxy-app.json |
| Facts — something happened and won't change: an order, a completed checklist, a delivery, a reading |
The workspace's Airhouse, in your schema app_<writer> |
ctx.airhouse.append(table, rows) · ctx.airhouse.query(sql) · ctx.airhouse.exec(sql) |
function: "airhouse": { "enabled": true } · app: "airhouseMigrations": { "dir": "airhouse-migrations" } |
| Records your app edits — bookings, assignments, templates, counts |
The org's OLTP Postgres, in your schema app_<writer> |
ctx.oltp.query/exec(sql, params) · ctx.oltp.tx(async (tx) => …) |
function: "oltp": { "enabled": true } · app: "migrations": { "dir": "migrations" } |
| Files — photos, PDFs, exports |
Your app's storage silo |
ctx.storage |
function: "storage": { "read": true, "write": true } |
| The customer's warehouse — ClickHouse, Snowflake, BigQuery, their Postgres |
Theirs |
ctx.query · ctx.warehouse.query(db, sql) |
read-only: a write is refused unless the function declares "customerWarehouseWrites": { "<db>": "<why>" } |
Three questions, in order: Is it bytes? → storage (keep the key in a record
or fact). Does it change after it's written? No → a fact; yes → a record;
both when you need history (the record says what is true now, the fact says
what changed). Is it already in the customer's warehouse? → read it there.
<writer> is your slug with - → _ (my-app → app_my_app); a slug
with _ can't back a schema. Both stores are written as the app, whoever
invoked the function, so a scheduled run writes like a click.
A store has to exist before your schema can. The org's OLTP Postgres is bought
and provisioned for the account, not created by publishing, so on a new or
part-provisioned account ctx.oltp fails for a reason that is nothing to do with your
code — and the same is true of a secret that was set in staging but never in
production. You cannot provision it yourself. What to ask for by name: Oxy staff run
oxyc bootstrap verify <org>, which reports every account-level step as landed,
missing or unreadable and names the command that fixes each one. Quote the phase it
reports (oltp, secrets, airhouse) and you will get a straight answer instead of
a round trip.
Facts, in practice. Airhouse is DuckLake: no PRIMARY KEY, UNIQUE,
indexes or foreign keys — publish refuses a migration carrying one. So:
- Give every fact the id its source assigned and a
recorded_at. A retried
function appends twice; readers keep one row per id:
QUALIFY row_number() OVER (PARTITION BY completion_id ORDER BY recorded_at DESC) = 1.
- A correction is a new fact (
voided, amended), not an UPDATE.
- Name tables
app_<writer>.<table> in migrations and in exec/query
(ctx.airhouse.schema has the name). append takes the bare table name.
- One statement per call, nothing bound: request data goes through
append,
never into exec SQL. exec runs no DDL — tables come from migrations.
Records, in practice. Bound parameters ($1, $2) always. Several
statements that must land together go in one ctx.oltp.tx. The store is
provisioned per org by an operator; until then calls fail naming that step.
Where ctx.env comes from. The app's own secrets (its Secrets panel,
oxyc env secret set), plus any workspace secret a workspace admin has shared
with the app in Settings → Secrets — read under the secret's own name, so one
SLACK_BOT_TOKEN can serve every app that needs it and rotates once. The app's
own value of a key wins over a shared one. Nothing else of the workspace is
visible, and the manifest cannot ask for more: declaring a key in env only
makes it show as missing until someone sets or shares it. ctx.secrets.set
refuses a key the run read from a shared workspace secret; rotate it in Settings.
Not a store: ctx.secrets holds credentials you rotate. A cursor, a
counter or a JSON blob is a record. oxyc validate warns about it, about
keys in Airhouse migrations, and lists every customer-warehouse write exception.
// A checklist is finished: the record changes, and a fact is appended.
async function completeChecklist(ctx, runId: string, storeGuid: string) {
await ctx.oltp.tx(async (tx) => {
await tx.exec("UPDATE checklist_runs SET status = 'done', completed_at = now() WHERE id = $1", [runId]);
await tx.exec("DELETE FROM open_reminders WHERE run_id = $1", [runId]);
});
await ctx.airhouse.append("checklist_completions", [
{ completion_id: runId, store_guid: storeGuid, completed_by: ctx.user.id, recorded_at: new Date().toISOString() },
]);
}
Telling people something
Name people; the platform reaches them. Don't build a recipient table, a
"sent" log or a Slack webhook helper:
await ctx.notify({
to: { role: "Store Manager", location: storeId }, // or { userId } · { team }
kind: "list_overdue", // declared in oxy-app.json
title: "Opening list is 30 minutes late",
link: `/lists/${listId}`, // a path inside the app
email: true, // optional; slack: true too
idempotencyKey: `overdue:${occurrenceId}`, // retry-safe
});
oxy-app.json: "notify": { "kinds": { "list_overdue": {} } } on the function
({ "critical": true } for a kind people must not mute). Everyone lands in
their Oxygen inbox — frontline crew too, who have no email — and is pushed,
emailed or Slacked where they can be. slack: true DMs each person's own Slack
account (found by their email once the org has connected Slack), so an app
never holds a Slack token or maps users to Slack ids. Needs the org's OLTP
store. Use
ctx.email.send only for addresses outside the org (a vendor, an
accountant), and give it an idempotencyKey in a scheduled function.
Categories, levels, threads and actions
Describe your kinds once, at the top level of oxy-app.json. It is the tree
people mute in (a whole app, a category, or one kind) and the one a phone groups
by, so declare it with the first ctx.notify, not later:
"notifications": {
"categories": {
"operations": { "label": "Store operations" },
"operations/food-safety": { "label": "Food safety" }
},
"kinds": {
"list_overdue": { "category": "operations", "label": "Overdue lists", "level": "time_sensitive" },
"temp_alarm": { "category": "operations/food-safety", "label": "Temperature alarm", "level": "critical",
"actions": [{ "id": "ack", "label": "Acknowledge", "function": "ack-alarm" }] }
}
}
- Category: a path of up to 3 segments (
a-z0-9, _, -); a declared
path's parents need no entry. A kind with none is in general.
- Level:
passive, active (default), time_sensitive, critical. Only
critical ignores mutes; a function's "critical": true still makes it so.
- Actions: at most 3, label ≤ 24 characters. With
function (one this app
declares), a tap calls it as the person with { notificationId, action, link }
and marks it read; without, it opens the link.
- Thread:
ctx.notify({ …, thread: `store:${storeId}` }) (≤ 128
characters) folds a run of notifications about one thing into the newest.
- The function's
notify.kinds still decides what it may send; a kind it sends
that the catalogue leaves out gets the defaults. oxyc validate, the Vite
plugin (pnpm dev / pnpm build) and oxyc publish refuse a malformed or
unknown category, a bad level, more than 3 actions, an action naming an
undeclared function, a misspelt field and any oxy. kind — every problem at
once; a catalogue kind no function sends is a warning.
The dock. Wrap the app in <OxyShell> (every create-oxy-app template
does) so it shows Oxygen's rail: HQ, Chat and the viewer's other apps, each
opening in this tab and warmed on hover. Pass hideTopBar if the app draws its
own header. Link to another app with a plain <a href>, never target="_blank";
moving between apps is meant to feel like one product.
Motion. shell.css loads @oxy-hq/sdk/motion.css (SDK ≥ 2.24), Oxygen's
own motion language, so shadcn dialogs, menus and tooltips already open and
close like Oxygen's. Time your own transitions with its tokens
(var(--oxy-duration-fast), var(--oxy-ease-out); the templates map them into
Tailwind's @theme) rather than inventing durations, keep them short (most
are 120–240 ms), and give every slide or zoom a motion-reduce: counterpart.
import { OxyShell } from "@oxy-hq/sdk/shell";
import "@oxy-hq/sdk/shell.css";
<OxyAppProvider>
<OxyShell hideTopBar>
<App />
</OxyShell>
</OxyAppProvider>
A pushState before the person has touched the page (a default redirect,
filters written to the query string on mount) is turned into a replace by the
platform, so Back still leaves the app; write such URL syncs as replaces anyway. An app that pushes on
purpose before any interaction (a dialog route opened on load and closed with
history.back(), a kiosk's Back trap) adds
<meta name="oxy-history" content="native"> to its index.html, and its pushes
are left alone.
PhoneSheet and the shell's drawer hold their own entries this way and need nothing
from the app.
The app is its own page, outside Oxygen's shell, so show the inbox in the
app — people who live in it (crew on a kiosk) never see Oxygen's bell:
import { NotificationsBell } from "@oxy-hq/sdk";
<NotificationsBell => navigate(link)} /> // in the header
It lists this app's notifications (scope="all" for the whole inbox), each
with its category under the title, critical and time_sensitive ones marked,
and threads folded; a tap
hands the link you passed to ctx.notify to onNavigate (without it, the
page loads that path under the app's base). It renders nothing where there is
no inbox (signed out, an older server, pnpm dev). useNotifications() gives
{ items, unread, markRead, markAllRead, refresh, … } to draw your own, and
takes { category, kind, thread } to narrow it. Theme
it with --oxy-notifications-* CSS variables. Push sign-up and mutes stay in
Oxygen's Settings → Notifications — don't build them. In tests,
createTestInbox({ manifest }) from @oxy-hq/sdk/testing is a fake inbox to pass as
<OxyAppProvider fetcher={inbox.fetcher}>.
Home widgets (a live card on the Oxygen home)
A widget puts what needs doing in your app on the Oxygen home, with the button
that does it ("19 stores ready to post" and Post 19 ready). It is data, not
a page: a function of yours returns a small JSON view and the home draws it. The
function runs as the person looking, so app access and rate limits apply.
"widgets": {
"close": {
"title": "Month-end close", // ≤ 40 characters
"function": "close-widget", // declared under functions; returns the view
"size": "wide", // default size: "regular" (default), "wide" or "full"
"sizes": ["regular", "wide", "full"], // sizes a layout may pick; default [size]; must include size
"params": { "type": "object", "required": ["store"], "properties": { // settings per copy
"store": { "type": "string", "title": "Store", "description": "A store slug" } } },
"actions": {
"post-ready": { "function": "post-ready-jes", "confirm": true } // destructive: true for red
}
}
}
At most 6 widgets per app and 3 actions per widget; ids are lowercase
letters, digits, - and _. params is a flat JSON Schema: up to 8 properties, each
string, integer, number or boolean with optional title, description, default,
enum, minimum/maximum (numbers), minLength/maxLength (strings), plus required;
no nesting, no $ref. oxyc validate and oxyc publish refuse an unknown key, a bad id,
a bad size/sizes (widget_size_invalid), a bad params (widget_params_invalid) and an
undeclared function.
The function is called with { widget, size, params } (WidgetInput; size is how wide
it is drawn, so say more when wide or full; params are this copy's settings with
defaults filled in, {} if it declares none) and returns a WidgetView:
import type { WidgetInput, WidgetView } from "@oxy-hq/sdk";
export default async (req, ctx) => {
const { widget, size, params } = JSON.parse(req.body || "{}") as WidgetInput; // params.store
const view: WidgetView = {
headline: "19 stores ready to post", // required, ≤ 80; none = "nothing to show"
detail: "September · 61 of 84 posted", // ≤ 120
level: "attention", // ok | info | attention | critical
progress: { done: 61, total: 84 },
metric: { value: "$48,210", label: "Posted", delta: "+12%", trend: "up", spark: [31, 35, 41, 48] },
rows: [{ title: "Valencia", detail: "Not mapped", state: "blocked" }], // ≤ 8
buttons: [{ // ≤ 2, each naming a declared action
action: "post-ready", label: "Post 19 ready", input: { period: "2026-09" },
key: "2026-09", confirm: "Post 19 journal entries to QuickBooks?"
}],
link: "/?month=2026-09", badge: 19, // "Open" (app-relative: / or ?), and a count
refresh_after: 300, // read again after N seconds (60–86400)
};
return Response.json(view);
};
A widget's kind is what its view carries: metric makes a KPI card (value ≤ 24,
label ≤ 40, delta ≤ 24, trend up/down/flat, spark ≤ 30 points), progress a
progress card, rows with buttons a to-do. Text and lists past their limits are cut, and a
non-app-relative link or a button naming an undeclared action is dropped.
level decides the room a card gets. Widgets live in the home's Today area (a rail
beside the apps on a wide screen, under them on a phone), one column wide. An ok or info
view with no button folds to one line (its headline) in an "All clear" list after every card
that needs someone; attention and critical keep the full card. So say all-is-well in the
headline alone, and raise the level when the rows matter. progress is always a ring beside
the headline holding done/total, so don't repeat the count in detail. A regular card
shows three rows, wide and full all of them: size is how much a card shows, not its width.
Pressing a button calls the action's function with { widget, action, input } and
an Idempotency-Key built from widget, action and the button's key (none: a hash of
input), so a double click or stale card replays the first answer. Give every button
a key that names the thing done ("2026-09"), not a timestamp. The action's return
decides the card: { view } re-renders, { message } shows a line, anything else
re-reads the widget; a throw or non-2xx leaves it as it was, with the reason shown.
Widgets show in production only, on the apps-first home. One that should not run on every home load declares
cache: { ttlSeconds } on its function.
Laying out the home
The org's home is one layout document, written by an org owner or admin (not by an
app): the widget groups of Today in order, and the widgets as <app>/<widget> at a size
from that widget's sizes. The apps always come first and are always drawn; apps and
insights entries are accepted but place nothing, and leaving insights out hides it. No coordinates; an edit is a list move. widgets sections may repeat,
each a group with an optional title (≤ 40); others goes on the first only. An item
may add params, a title and an id, so one widget can appear as several copies
(one per store), each with its own id.
Who a widget is for. A group or an item may add for:
{ "people": ["scott@acme.com"], "teams": ["Office"] } (emails, and org team names; at
least one list non-empty, at most 50 each, matched case-insensitively). Only those people
see it. It only narrows: app access applies first, and an item's for narrows its
group's. Use it when someone may open the app but its widget is noise to them ("show
Bookkeeping's cards only to Scott and Dylan"), rather than changing who can open the app.
Widgets the layout does not list stay everyone's. Each person can also hide a widget or
turn Today off on their own home; a layout cannot undo that.
{ "version": 1, "sections": [
{ "kind": "apps" },
{ "kind": "widgets", "items": [ { "widget": "warehouse/receiving", "hidden": true } ],
"others": "show" },
{ "kind": "widgets", "title": "Back office",
"for": { "people": ["scott@acme.com", "dylan@acme.com"] },
"items": [ { "widget": "bookkeeping/close", "size": "full" } ] },
{ "kind": "widgets", "title": "Stores", "items": [
{ "widget": "store-ops/today", "id": "mission", "title": "Mission St",
"params": { "store": "mission" } } ] },
{ "kind": "insights" } ] }
Get, edit, preview, then apply:
oxyc home show --org acme # what a person sees: widgets, sizes, headlines
oxyc home get --org acme > layout.json # { revision, layout }: edit the layout
oxyc home apply --org acme -f layout.json --dry-run # resulting home as text, nothing saved
oxyc home apply --org acme -f layout.json # save (sends the file's revision)
A refused layout (exit 6) lists every problem as path: message (fix); fix them all.
Exit 8 means someone saved since your get: home get again and redo the edit
(--force overwrites). oxyc home reset restores the default. A widget not listed
still shows after the first group's items unless others is "hide", except one with a
required setting and no default: it needs an entry that sets params.
Phone layout
People open these apps on their phones. A desktop layout squeezed into one column
is not a phone layout: tables scroll sideways, tabs get cut, the answer sits under a
map. Give each screen people use on a phone a phone view built from the phone
kit in @oxy-hq/sdk/shell, beside the desktop component, from the same hooks:
const phone = usePhoneLayout();
return phone ? <OrdersPhone {...data} /> : <OrdersDesktop {...data} />;
The desktop layout stays exactly as it is. On the phone: a PhoneTabBar for
sections, the answer first (PhoneKpiStrip, "needs you" PhoneRows), table rows
as PhoneCards (never a sideways-scrolling table), details in a PhoneSheet,
maps as their own tab, PhoneHint instead of hover tooltips. The mapping from each
desktop part, the type and touch floor, and how to check it at 390×844 and 844×390:
references/phone-layout.md.
Four pitfalls
CORS errors are usually wrong-URL errors in disguise. The SDK's
base URL must be ${OXY_URL}/api, not OXY_URL bare. The API
router (which carries CORS headers) lives under /api/*. Hitting
/<projectId>/... lands in the static fallback and the missing
headers look like a CORS failure.
Cookie auth requires credentials: "include". The SDK's
useQuery sets this. If you fetch directly, set it yourself or the
oxy_session cookie won't be forwarded.
projectId in the manifest is advisory, not enforcement. The
SDK uses it to construct the query URL. Authorization is the user's
cookie → user → org_member of the project's org, decided
server-side. A bundle that ships a stolen projectId can't read
data the user can't already read.
Cloud mode is the target. Don't branch on local vs. cloud; don't
rely on the nil UUID 00000000-... as a default project; don't
assume OXY_STATE_DIR is writable.
Two more that read as bugs — useTrackEvent("oxy-…") is refused (400,
the prefix is reserved), and a hovered-but-never-opened app records no view —
are in references/performance-and-usage.md.
Run a function locally
oxyc fn dev <name> runs one handler from your source in-process, in seconds,
with no publish. It bundles the handler with the same esbuild call oxyc publish
uses, then invokes it on createTestContext seeded from oxy-app.json: the
function's capabilities, ctx.env from the env file, and its destinations. It
prints the response, then the host ops the handler made.
oxyc fn dev notify --input '{"name":"Ada"}' # a literal, @file, or - for stdin
oxyc fn dev notify --input @sample.json --env-file .env.dev --watch
oxyc fn dev report --read-through --env dev # reads hit that deployment; writes stay stubbed
- Run it from the app directory (the one with
oxy-app.json). --env-file
defaults to .env; ctx.env holds that file's keys and nothing from your
shell. A required secret the file lacks is a warning.
--watch re-runs when a file in the app changes, reading the manifest,
env file and @file input afresh. A broken edit prints its error and waits
for the next save. Exit with Ctrl-C.
- Exit codes:
0 for a 2xx Response; 1 when the handler throws or
answers non-2xx (as fn call); 2 for a function the manifest does not
declare, or a missing env file.
- A local run is not the isolate. There is no timeout, memory or log cap;
Buffer, TextEncoder and process exist where the isolate lacks them; and
every warehouse, semantic, storage, fetch and email call is a stub in memory,
so (without --read-through) nothing reaches a deployment. The context does refuse what the manifest
does not grant, in the host's words. A ctx.warehouse destination's engine is
assumed (a customerWarehouseWrites entry is a customer Postgres, any other
is Airhouse), because the workspace config is not read.
--read-through reads real data, and only reads. It sends ctx.query,
ctx.warehouse.query and ctx.semantic.query to the deployment --env <name|url>
(or --target) names, through the app's own POST /api/projects/{project}/query
and /semantic-query, with your oxyc login bearer or OXY_TOKEN (the way
oxyc api authenticates). What you may read is the server's decision. The
project is --project / OXY_PROJECT, else looked up from oxy-app.json
slug + orgSlug. Every other call (warehouse writes, ctx.tx, ctx.oltp,
ctx.airhouse, storage, fetch, email, notify, and ctx.queryStream) stays a
stub in memory and never leaves your machine. Each call in the report is marked
real or stubbed. --env defaults to production, so name a dev environment
when you can. A sandbox agent token is refused: use a person's login.
ctx.semantic.query row keys are view__member in the isolate but the route
strips the prefix, so read-through puts it back from your spec; a key it could
not map unambiguously stays as the route named it, so confirm that one with
fn call on a sandbox. Still not the isolate.
- Before you ship, run it where it really runs: publish to your sandbox and
oxyc fn call, or oxyc checks run. For a committed regression test use
createTestContext from @oxy-hq/sdk/testing in vitest, as the functions
template does.
Publishing
These commands are a person's, or an agent's on a token that person
approved. oxyc login is the engineer's own browser login, and a publish to
a channel or a promote is refused under a sandbox agent token. As an agent,
iterate in your own sandbox
(references/sandbox-agent-loop.md). Ship
only when your engineer asked you to, on an agent token they approved
(oxyc tokens create --agent, plus --standing for staff access): it
publishes and promotes as them. With no browser on your machine, see
Headless and cloud sessions: a token approved
there never carries staff access.
Ship with oxyc publish (npm i -g @oxy-hq/cli) — no CI step, no S3 sync,
no folder picker. From the app directory:
oxyc login --env production # once; browser flow, caches a token,
# and prints whether you're an app-admin
oxyc validate # schema, data-placement and function checks first
oxyc publish --env production # build → bundle functions → tar → upload (draft = staging)
oxyc promote <org>/<app> --env production --dry-run # the plan: changes, migrations, blockers
oxyc promote <org>/<app> --env production # staging's build → production (asks first)
oxyc rollback <org>/<app> --env production --app-env production # back to the build before
Production only ever serves a build staging has served, and every way of
moving it — oxyc promote, oxyc rollback, the console's Promote draft
and Roll back to…, a promoting publish — applies the build's pending migrations before it moves
(a failure leaves the old build live). promote and rollback print the plan
first and refuse on a blocker: staging_never_served, required_secrets_unset
(set the key in production first), schedule_removal_unconfirmed (pass
--remove-schedule <function>). Off a terminal pass --yes.
oxyc publish --promote still works and warns that it is deprecated: it shows
nobody the plan.
- Identity, for each half, is
--app / --org, then OXY_APP /
OXY_ORG, then the manifest's slug + orgSlug, then an
apps/<org>/<app>/ working directory. --org takes a slug or a UUID; pass
the slug whenever oxyc runs the build, because the asset base path is
baked from what you pass. With no org from any of those, the build stops
with missing org: the app's base path needs it (exit 2): add
"orgSlug" to oxy-app.json (create-oxy-app --org <slug> writes it)
or --org <org-slug>, and --app <slug> when the directory has no
manifest. The server upserts the app row — there is no separate create
step.
- First publish of a new app is one step. The app is not registered
yet, so the build-config lookup 404s; with your login
oxyc publish then
lists the org's workspaces, and when there is exactly one (a freshly
provisioned org) publishes into it and says which. With several it prints
them with their uuids beside the flag to pass — --project <workspace-uuid> (or OXY_PROJECT), which also supplies the org. Drop
the flag after the first publish — it's auto-resolved from then on.
Trusted publishing (CI) only ever publishes a registered app.
- Old kit. Before the build, an app whose
@oxy-hq/sdk or
@oxy-hq/vite-plugin is more than one minor behind the versions this
oxyc was built with gets one warning naming the pnpm add — the
manifest contract and the function runtime move with them.
--env targets: local → a local Oxy web-app Vite dev server :5173
(it serves /cli-auth and proxies /api to oxy on :3000), dev →
aip.dev.oxy.tech, staging → aip.staging.oxy.tech, production (the
default) → app.oxygen-hq.com. A value with a ., / or : is read as a
URL.
- Function lint. Before the build, each Oxy Function's source is checked
for what the host would refuse at the first call: a
ctx.* call whose
capability the manifest lacks, a global the isolate does not have
(Buffer, TextEncoder, process, …), a write outside destinations. A finding fails
the publish (exit 1); --allow-function-lint publishes past a false
positive.
--dir out skips the build and uploads a prebuilt directory (declared
functions are still bundled into it); --build-only builds and bundles
without a credential or an upload; --prebuilt (with --dir) uploads a
directory whose functions are already bundled. Server warnings print on
stderr; --json prints the result.
.env.local / .env are loaded from the app directory and its parents
(never overriding what is already set), so a stray OXY_PROJECT there
retargets a publish.
- Credential:
OXY_TOKEN, then oxyc login's cache — or, in a GitHub
Actions job with id-token: write, the job's OIDC identity.
oxyc init-ci writes a workflow that publishes with no stored secret.
- Promote / roll back / unpublish from the oxy admin app-detail console;
every publish is audited (who shipped each build, when).
- What is live now:
oxyc apps show <org>/<app> prints the live build, the
commit it was built from, a newer draft if there is one, and its health;
oxyc apps builds <org>/<app> is the history. oxyc apps drift <org>/<app>
lists the commits in your checkout that touch the app after the live build's
commit — unknown there means it could not compare, not that nothing changed.
- A customer's own domain (
app.acme.com) serves production only:
oxyc apps domains add <org>/<app> app.acme.com prints a CNAME and a TXT
record for the customer to create, then oxyc apps domains verify …. Build
nothing differently — the bundle keeps its /customer-apps/<org>/<app>/ base
and its same-origin /api calls work on the domain. A visitor signs in once
through the Oxygen login; on that domain the session reaches only the app's
workspace, so a call to another workspace there is refused by design.
The build is not the check: after a publish, drive the page
(references/verifying-in-the-browser.md).
Headless and cloud sessions
A Claude Code cloud session (claude.ai/code), a CI runner or any machine with
no browser can mint a token, iterate in a sandbox and publish. A person
approves once, from any device.
The cloud environment. Its owner sets this once in the environment's
settings. Under Network access → Custom, allow app.oxygen-hq.com and
*.oxy.tech, and keep the default package-manager list ticked so npm can
install oxyc. Optionally add OXY_APPROVER=<their email> under
environment variables, so each approval request is pushed to them.
The repo's SessionStart hook, .claude/hooks/oxyc-cloud-session.sh,
with its entry in .claude/settings.json. In a cloud session it installs
oxyc and routes it through the session's proxy. It also makes a minted
token reach every later command, which an export in one shell call cannot
do. What it prints at session start says what is missing.
- A customer repo that
oxyc new or oxyc adopt made has both files.
- In an existing customer repo,
oxyc update --apply adds the script but
only reports the settings entry, because the team may have their own
settings. Add the entry by hand:{ "hooks": { "SessionStart": [ { "matcher": "", "hooks": [ { "type": "command",
"command": "\"${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/oxyc-cloud-session.sh\"",
"timeout": 120 } ] } ] } }
- Any other repo can copy both from the
template/.claude/ directory of the
installed @oxy-hq/cli package.
The credential. Run this in the background, because the approval can
outlast a two-minute shell limit:
mkdir -p ~/.config/oxy && (umask 077; oxyc tokens create --agent --no-browser \
--env production >~/.config/oxy/agent-token.env)
Give your engineer the URL and the code it prints on stderr. The token goes
to that file and never into your context. The hook loads the file before
every later command. To iterate in a sandbox, mint
--sandbox-agent --app <org>/<app> into the same file instead. A token
lasts 8 hours by default (--hours, up to 168). On exit 4, mint again.
Or a network secret, which nobody approves per session. The
environment's owner adds one in its settings: Allowed websites
app.oxygen-hq.com (and *.oxy.tech), header Authorization, prefix
Bearer, and a personal access token or service account token as the
value. They also set OXY_TOKEN=from-proxy in its environment variables.
The proxy then adds the token to each request after it leaves the VM, so it
is never in a file, a variable or your context, and oxyc sends none.
The hook checks it with oxyc whoami and says if it is not attached. On
exit 4, report it: the secret's hosts, header or token are wrong, and
only the owner can fix them. Do not mint a token over it unasked. A sandbox
still needs an --sandbox-agent token minted into the file, which replaces
the sentinel.
Ship with the commands above, each with --token-env OXY_TOKEN.
promote and `rollba
…(truncated)
1---2name: oxy-custom-apps3description: >-4 Use when building, debugging, reviewing, shipping, or verifying an Oxy5 custom-app bundle (a code-first React/Vite app served by Oxy at6 /customer-apps/<org>/<slug>/), including writing Oxy Functions, driving them7 from the UI, and checking a published app in the browser with the Playwright8 MCP server (no CI checks a published bundle). Covers the oxy-app.json9 contract, @oxy-hq/sdk and @oxy-hq/vite-plugin, where app data goes10 (ctx.airhouse, ctx.oltp, ctx.storage), pitfalls, performance guardrails, load11 speed and usage tracking (service worker, Activity tab, useTrackEvent), the12 self-serve oxyc publish ship flow, dev-<handle> sandboxes and workspace13 previews, how an AI agent gets its own short-lived credential (oxyc tokens14 create --sandbox-agent or --agent, never the engineer's oxyc login), and15 reading a deployment's live data with oxyc api and oxyc proxy (the oxy binary16 has no HTTP-API commands; every one of them is oxyc).17metadata:18 source: https://skillmd.com/skills/oxy-hq/oxy-custom-apps19---2021# Custom-app development2223Custom-app bundles are arbitrary JS apps served by Oxy at24`https://<env>/customer-apps/<org>/<slug>/`. Oxy is a data gateway:25serves static assets, gates cookie auth, and proxies queries. The26bundle is opaque above the data plane — no per-app server config.2728This file is the contract. The detail lives in `references/` — see29[Read next](#read-next) for which file answers what.3031## The Oxy App Kit (use it)3233Two small packages remove the footguns — default to them rather than wiring a34bundle by hand:3536- **`@oxy-hq/sdk`** — the data layer (`useQuery`, `useSemanticQuery`,37 `useAgentRun`, `<OxyChat>`); see rule 2 and the `@oxy-hq/sdk` README.38- **`@oxy-hq/vite-plugin`** (`oxyApp()` in `vite.config.ts`) — bakes the asset39 **base path** from the manifest, copies `oxy-app.json` into `out/`, proxies40 `/api` in dev, and injects the `window.__OXY_APP__` shim. Dropping it41 re-introduces the #1 bug — asset 404s → blank dashboard (rule 3).4243Scaffold both with `pnpm create @oxy-hq/oxy-app my-app` (templates `vite` — the44default — `functions`, `dashboard`, `single-store`; `-t functions` adds Oxy45Functions). The platform is kit-agnostic (any bundle with a correct base path46works), but hand-rolling means owning the base-path + dev-proxy wiring yourself.4748## Three rules49501. **`oxy-app.json` (project root, not `public/`) is identity only.**51 Schema:5253 ```json54 {55 "$schema": "https://unpkg.com/@oxy-hq/sdk/schema/oxy-app.schema.json",56 "schemaVersion": 2,57 "slug": "url-slug",58 "orgSlug": "your-org",59 "name": "Display Name"60 }61 ```6263 Required: `schemaVersion` (must be `2`), `slug` (1–63 lowercase64 letters, digits and single hyphens — it becomes the served path and65 the OLTP schema name).66 Strongly recommended: `orgSlug` (lets `@oxy-hq/vite-plugin` derive67 the asset base path automatically, so plain `pnpm build` produces68 a bundle ready to drop into the linked org with no env var, and lets69 `pnpm dev` and `oxyc publish` find the app without `--org` / `OXY_ORG`;70 `create-oxy-app --org <slug>` writes it).71 Optional: `name` (display), `description`, `icon`, `art`, `status`72 (launcher card), `projectId` (dev-time hint), `build` (what `oxyc73 publish` runs — `install`, `command`, `outDir`; the plugin reads74 `outDir` too), `functions`, `env`, `storage`, `notifications`, `widgets`, …7576 **One contract.** The file is validated against the JSON Schema77 `@oxy-hq/sdk` ships (`schema/oxy-app.schema.json`, generated from the78 SDK's `OxyAppManifest` type; `$schema` gives your editor completion)79 by `oxyc validate`, `oxyc publish`, the Vite plugin and the SDK's own80 loader — the same check, the same words. A wrong type, a bad name or81 a missing required field is refused; a field the schema does not know82 is a **warning** (the platform ignores what it does not read — so a83 typo'd `timeoutSecond` is said, not silently dropped). Every field and84 what the server does with it: `OxyAppManifest` in85 `@oxy-hq/sdk/manifest`, which also exports the schema, `isValidSlug`86 / `isValidFunctionName` and `validateOxyAppManifest` for a tool of87 your own.8889 At serve time, oxy injects the authoritative org + project from90 the admin row via `window.__OXY_APP__` — the manifest's `orgSlug`91 and `projectId` are advisory hints only, never enforcement.9293 Do not invent `products`, `writers`, or `from:`-blocks. Those94 don't exist in v2 and the schema rejects them.9596 File location: **`<root>/oxy-app.json`**, sibling to97 `vite.config.ts`. The vite-plugin reads it from there, and so does98 `oxyc publish` (only from the directory it runs in); legacy bundles99 that kept it under `public/` get neither the plugin's base-path100 derivation nor the publish's `slug` / `orgSlug`.1011022. **All data flows through SDK hooks → oxy HTTP endpoints.** The103 surface is intentionally small:104105 | Hook / component | Endpoint | When |106 | ---- | -------- | ---- |107 | `useQuery({sql})` | `POST /api/projects/:id/query` | Raw SQL, 10k row cap |108 | `useSemanticQuery({topic, …})` | `POST /api/projects/:id/semantic-query` | Reference topics/measures by name |109 | `useAgentRun({agentId})` | `POST /api/projects/:id/agents/:id/asks` + SSE | Streaming chat / Q&A |110 | `useAskAgent()` | `POST /api/projects/:id/agents/:id/asks` with `wait_seconds` | One-call answer (≤45 s) for a button or a batch; `status: "running"` when the wait runs out |111 | `useProcedureRun({procedureId})` | `POST /api/projects/:id/procedures/:id/runs` ⚠️ beta | Long-running batch |112 | `useFunction(name)` | `POST /customer-apps/<org>/<slug>/fn/<name>` + SSE | Invoke a server-side **Oxy Function** (see below) |113 | `<OxyChat agentId="…"/>` | wraps `useAgentRun` | Drop-in chat UI |114 | `<OxyAnswer {...run}/>` | renders any run | Drop-in answer renderer |115116 ```tsx117 import { OxyChat, useQuery } from "@oxy-hq/sdk";118 const { rows } = useQuery({119 sql: "SELECT col FROM t WHERE x = {{ params.x | sqlquote }}",120 }, { params: { x: someState } });121 // ...122 <OxyChat agentId="analytics" />123 ```124125 To try an agent from a terminal the same way: `oxyc ask <workspace-id> <agent>126 "<question>" --json` (one request, answer on stdout; `--thread <id>` to reply127 to a clarifying question).128129 See the `@oxy-hq/sdk` README for the full reference, including130 `OxyApiError` parsing and beta-surface caveats.131132 **Server-side work → Oxy Functions, not the browser.** `useQuery` &133 friends run in the client; for work the browser shouldn't do134 (warehouse writes, ELT kick-offs, external API calls, secret-bearing135 logic) ship a **TypeScript handler under `functions/`** and invoke it136 with `useFunction(name).invoke(body?)`. Declare it in `oxy-app.json`:137138 ```json139 { "schemaVersion": 2, "slug": "my-app",140 "functions": { "daily-rollup": { "route": true, "timeoutSeconds": 30 } } }141 ```142143 ```ts144 // functions/daily-rollup.ts — runs on Oxy's isolate runtime145 export default async (req, ctx) => {146 const { rows } = await ctx.query("SELECT … FROM …"); // data-plane ctx147 return Response.json({ rows });148 };149 ```150151 `ctx` bridges to the data plane: `ctx.query` / `ctx.queryStream`,152 `ctx.semantic.query`, `ctx.warehouse.query`,153 `ctx.warehouse.{insert,exec,upsert}` (to Airhouse, or to a customer154 warehouse the function names in `customerWarehouseWrites`), `ctx.airway.run`,155 `ctx.fetch` (SSRF-allowlisted), `ctx.env`, `ctx.user`, `ctx.log`.156 What the app STORES picks its surface by shape — facts through157 `ctx.airhouse`, records through `ctx.oltp`, files through158 `ctx.storage` — and customer warehouses are read-only. See159 **Where data goes** below before writing anything.160 `oxyc publish` bundles `functions/*.ts` with161 esbuild — no separate backend to stand up. Author-facing types:162 `OxyFunctionContext` / `OxyFunctionRequest` from `@oxy-hq/sdk`; a worked163 example ships in the `functions` template (`pnpm create @oxy-hq/oxy-app164 my-app -t functions`).1651663. **`OXY_APP_BASE_PATH` must match the path the bundle is linked167 under.** `@oxy-hq/vite-plugin` resolves it from (in order):168 `OXY_APP_BASE_PATH` env → `orgSlug + slug` in `oxy-app.json` →169 `/`. `oxyc publish` sets that env to `/customer-apps/<org>/<slug>/`170 for the build automatically, and the vite-plugin derives the same171 from the manifest for `pnpm dev` / `pnpm build`. Mismatch → asset172 404s → blank dashboard.173174## Where data goes (the shape of the data picks the store)175176| The data | Store | In a function | In `oxy-app.json` |177| --- | --- | --- | --- |178| **Facts** — something happened and won't change: an order, a completed checklist, a delivery, a reading | The workspace's Airhouse, in your schema `app_<writer>` | `ctx.airhouse.append(table, rows)` · `ctx.airhouse.query(sql)` · `ctx.airhouse.exec(sql)` | function: `"airhouse": { "enabled": true }` · app: `"airhouseMigrations": { "dir": "airhouse-migrations" }` |179| **Records** your app edits — bookings, assignments, templates, counts | The org's OLTP Postgres, in your schema `app_<writer>` | `ctx.oltp.query/exec(sql, params)` · `ctx.oltp.tx(async (tx) => …)` | function: `"oltp": { "enabled": true }` · app: `"migrations": { "dir": "migrations" }` |180| **Files** — photos, PDFs, exports | Your app's storage silo | `ctx.storage` | function: `"storage": { "read": true, "write": true }` |181| **The customer's warehouse** — ClickHouse, Snowflake, BigQuery, their Postgres | Theirs | `ctx.query` · `ctx.warehouse.query(db, sql)` | read-only: a write is refused unless the function declares `"customerWarehouseWrites": { "<db>": "<why>" }` |182183Three questions, in order: **Is it bytes?** → storage (keep the key in a record184or fact). **Does it change after it's written?** No → a fact; yes → a record;185both when you need history (the record says what is true now, the fact says186what changed). **Is it already in the customer's warehouse?** → read it there.187188`<writer>` is your slug with `-` → `_` (`my-app` → `app_my_app`); a slug189with `_` can't back a schema. Both stores are written **as the app**, whoever190invoked the function, so a scheduled run writes like a click.191192**A store has to exist before your schema can.** The org's OLTP Postgres is bought193and provisioned for the account, not created by publishing, so on a new or194part-provisioned account `ctx.oltp` fails for a reason that is nothing to do with your195code — and the same is true of a secret that was set in staging but never in196production. You cannot provision it yourself. What to ask for by name: Oxy staff run197`oxyc bootstrap verify <org>`, which reports every account-level step as landed,198missing or unreadable and names the command that fixes each one. Quote the phase it199reports (`oltp`, `secrets`, `airhouse`) and you will get a straight answer instead of200a round trip.201202**Facts, in practice.** Airhouse is DuckLake: no `PRIMARY KEY`, `UNIQUE`,203indexes or foreign keys — publish refuses a migration carrying one. So:204205- Give every fact the id its source assigned and a `recorded_at`. A retried206 function appends twice; readers keep one row per id:207 `QUALIFY row_number() OVER (PARTITION BY completion_id ORDER BY recorded_at DESC) = 1`.208- A correction is a new fact (`voided`, `amended`), not an `UPDATE`.209- Name tables `app_<writer>.<table>` in migrations and in `exec`/`query`210 (`ctx.airhouse.schema` has the name). `append` takes the bare table name.211- One statement per call, nothing bound: request data goes through `append`,212 never into `exec` SQL. `exec` runs no DDL — tables come from migrations.213214**Records, in practice.** Bound parameters (`$1`, `$2`) always. Several215statements that must land together go in one `ctx.oltp.tx`. The store is216provisioned per org by an operator; until then calls fail naming that step.217218**Where `ctx.env` comes from.** The app's own secrets (its Secrets panel,219`oxyc env secret set`), plus any workspace secret a workspace admin has shared220with the app in Settings → Secrets — read under the secret's own name, so one221`SLACK_BOT_TOKEN` can serve every app that needs it and rotates once. The app's222own value of a key wins over a shared one. Nothing else of the workspace is223visible, and the manifest cannot ask for more: declaring a key in `env` only224makes it show as missing until someone sets or shares it. `ctx.secrets.set`225refuses a key the run read from a shared workspace secret; rotate it in Settings.226227**Not a store:** `ctx.secrets` holds credentials you rotate. A cursor, a228counter or a JSON blob is a record. `oxyc validate` warns about it, about229keys in Airhouse migrations, and lists every customer-warehouse write exception.230231```ts232// A checklist is finished: the record changes, and a fact is appended.233async function completeChecklist(ctx, runId: string, storeGuid: string) {234 await ctx.oltp.tx(async (tx) => {235 await tx.exec("UPDATE checklist_runs SET status = 'done', completed_at = now() WHERE id = $1", [runId]);236 await tx.exec("DELETE FROM open_reminders WHERE run_id = $1", [runId]);237 });238 await ctx.airhouse.append("checklist_completions", [239 { completion_id: runId, store_guid: storeGuid, completed_by: ctx.user.id, recorded_at: new Date().toISOString() },240 ]);241}242```243244## Telling people something245246Name **people**; the platform reaches them. Don't build a recipient table, a247"sent" log or a Slack webhook helper:248249```ts250await ctx.notify({251 to: { role: "Store Manager", location: storeId }, // or { userId } · { team }252 kind: "list_overdue", // declared in oxy-app.json253 title: "Opening list is 30 minutes late",254 link: `/lists/${listId}`, // a path inside the app255 email: true, // optional; slack: true too256 idempotencyKey: `overdue:${occurrenceId}`, // retry-safe257});258```259260`oxy-app.json`: `"notify": { "kinds": { "list_overdue": {} } }` on the function261(`{ "critical": true }` for a kind people must not mute). Everyone lands in262their Oxygen inbox — frontline crew too, who have no email — and is pushed,263emailed or Slacked where they can be. `slack: true` DMs each person's own Slack264account (found by their email once the org has connected Slack), so an app265never holds a Slack token or maps users to Slack ids. Needs the org's OLTP266store. Use267`ctx.email.send` only for addresses **outside** the org (a vendor, an268accountant), and give it an `idempotencyKey` in a scheduled function.269270### Categories, levels, threads and actions271272Describe your kinds once, at the top level of `oxy-app.json`. It is the tree273people mute in (a whole app, a category, or one kind) and the one a phone groups274by, so declare it with the first `ctx.notify`, not later:275276```json277"notifications": {278 "categories": {279 "operations": { "label": "Store operations" },280 "operations/food-safety": { "label": "Food safety" }281 },282 "kinds": {283 "list_overdue": { "category": "operations", "label": "Overdue lists", "level": "time_sensitive" },284 "temp_alarm": { "category": "operations/food-safety", "label": "Temperature alarm", "level": "critical",285 "actions": [{ "id": "ack", "label": "Acknowledge", "function": "ack-alarm" }] }286 }287}288```289290- **Category**: a path of up to 3 segments (`a-z0-9`, `_`, `-`); a declared291 path's parents need no entry. A kind with none is in `general`.292- **Level**: `passive`, `active` (default), `time_sensitive`, `critical`. Only293 `critical` ignores mutes; a function's `"critical": true` still makes it so.294- **Actions**: at most 3, label ≤ 24 characters. With `function` (one this app295 declares), a tap calls it as the person with `{ notificationId, action, link }`296 and marks it read; without, it opens the link.297- **Thread**: ``ctx.notify({ …, thread: `store:${storeId}` })`` (≤ 128298 characters) folds a run of notifications about one thing into the newest.299- The function's `notify.kinds` still decides what it may send; a kind it sends300 that the catalogue leaves out gets the defaults. `oxyc validate`, the Vite301 plugin (`pnpm dev` / `pnpm build`) and `oxyc publish` refuse a malformed or302 unknown category, a bad level, more than 3 actions, an action naming an303 undeclared function, a misspelt field and any `oxy.` kind — every problem at304 once; a catalogue kind no function sends is a warning.305306**The dock.** Wrap the app in `<OxyShell>` (every `create-oxy-app` template307does) so it shows Oxygen's rail: HQ, Chat and the viewer's other apps, each308opening in this tab and warmed on hover. Pass `hideTopBar` if the app draws its309own header. Link to another app with a plain `<a href>`, never `target="_blank"`;310moving between apps is meant to feel like one product.311312**Motion.** `shell.css` loads `@oxy-hq/sdk/motion.css` (SDK ≥ 2.24), Oxygen's313own motion language, so shadcn dialogs, menus and tooltips already open and314close like Oxygen's. Time your own transitions with its tokens315(`var(--oxy-duration-fast)`, `var(--oxy-ease-out)`; the templates map them into316Tailwind's `@theme`) rather than inventing durations, keep them short (most317are 120–240 ms), and give every slide or zoom a `motion-reduce:` counterpart.318319```tsx320import { OxyShell } from "@oxy-hq/sdk/shell";321import "@oxy-hq/sdk/shell.css";322323<OxyAppProvider>324 <OxyShell hideTopBar>325 <App />326 </OxyShell>327</OxyAppProvider>328```329330A `pushState` before the person has touched the page (a default redirect,331filters written to the query string on mount) is turned into a replace by the332platform, so Back still leaves the app; write such URL syncs as replaces anyway. An app that pushes on333purpose before any interaction (a dialog route opened on load and closed with334`history.back()`, a kiosk's Back trap) adds335`<meta name="oxy-history" content="native">` to its `index.html`, and its pushes336are left alone.337`PhoneSheet` and the shell's drawer hold their own entries this way and need nothing338from the app.339340The app is its own page, outside Oxygen's shell, so show the inbox **in the341app** — people who live in it (crew on a kiosk) never see Oxygen's bell:342343```tsx344import { NotificationsBell } from "@oxy-hq/sdk";345346<NotificationsBell onNavigate={(link) => navigate(link)} /> // in the header347```348349It lists this app's notifications (`scope="all"` for the whole inbox), each350with its category under the title, `critical` and `time_sensitive` ones marked,351and threads folded; a tap352hands the `link` you passed to `ctx.notify` to `onNavigate` (without it, the353page loads that path under the app's base). It renders nothing where there is354no inbox (signed out, an older server, `pnpm dev`). `useNotifications()` gives355`{ items, unread, markRead, markAllRead, refresh, … }` to draw your own, and356takes `{ category, kind, thread }` to narrow it. Theme357it with `--oxy-notifications-*` CSS variables. Push sign-up and mutes stay in358Oxygen's Settings → Notifications — don't build them. In tests,359`createTestInbox({ manifest })` from `@oxy-hq/sdk/testing` is a fake inbox to pass as360`<OxyAppProvider fetcher={inbox.fetcher}>`.361362## Home widgets (a live card on the Oxygen home)363364A widget puts what needs doing in your app on the Oxygen home, with the button365that does it ("19 stores ready to post" and **Post 19 ready**). It is **data, not366a page**: a function of yours returns a small JSON view and the home draws it. The367function runs as the person looking, so app access and rate limits apply.368369```json370"widgets": {371 "close": {372 "title": "Month-end close", // ≤ 40 characters373 "function": "close-widget", // declared under functions; returns the view374 "size": "wide", // default size: "regular" (default), "wide" or "full"375 "sizes": ["regular", "wide", "full"], // sizes a layout may pick; default [size]; must include size376 "params": { "type": "object", "required": ["store"], "properties": { // settings per copy377 "store": { "type": "string", "title": "Store", "description": "A store slug" } } },378 "actions": {379 "post-ready": { "function": "post-ready-jes", "confirm": true } // destructive: true for red380 }381 }382}383```384385At most **6 widgets** per app and **3 actions** per widget; ids are lowercase386letters, digits, `-` and `_`. `params` is a flat JSON Schema: up to 8 properties, each387`string`, `integer`, `number` or `boolean` with optional `title`, `description`, `default`,388`enum`, `minimum`/`maximum` (numbers), `minLength`/`maxLength` (strings), plus `required`;389no nesting, no `$ref`. `oxyc validate` and `oxyc publish` refuse an unknown key, a bad id,390a bad `size`/`sizes` (`widget_size_invalid`), a bad `params` (`widget_params_invalid`) and an391undeclared `function`.392393The function is called with `{ widget, size, params }` (`WidgetInput`; `size` is how wide394it is drawn, so say more when `wide` or `full`; `params` are this copy's settings with395defaults filled in, `{}` if it declares none) and returns a `WidgetView`:396397```ts398import type { WidgetInput, WidgetView } from "@oxy-hq/sdk";399400export default async (req, ctx) => {401 const { widget, size, params } = JSON.parse(req.body || "{}") as WidgetInput; // params.store402 const view: WidgetView = {403 headline: "19 stores ready to post", // required, ≤ 80; none = "nothing to show"404 detail: "September · 61 of 84 posted", // ≤ 120405 level: "attention", // ok | info | attention | critical406 progress: { done: 61, total: 84 },407 metric: { value: "$48,210", label: "Posted", delta: "+12%", trend: "up", spark: [31, 35, 41, 48] },408 rows: [{ title: "Valencia", detail: "Not mapped", state: "blocked" }], // ≤ 8409 buttons: [{ // ≤ 2, each naming a declared action410 action: "post-ready", label: "Post 19 ready", input: { period: "2026-09" },411 key: "2026-09", confirm: "Post 19 journal entries to QuickBooks?"412 }],413 link: "/?month=2026-09", badge: 19, // "Open" (app-relative: / or ?), and a count414 refresh_after: 300, // read again after N seconds (60–86400)415 };416 return Response.json(view);417};418```419420A widget's kind is what its view carries: `metric` makes a **KPI card** (`value` ≤ 24,421`label` ≤ 40, `delta` ≤ 24, `trend` up/down/flat, `spark` ≤ 30 points), `progress` a422progress card, rows with buttons a to-do. Text and lists past their limits are cut, and a423non-app-relative link or a button naming an undeclared action is dropped.424425**`level` decides the room a card gets.** Widgets live in the home's Today area (a rail426beside the apps on a wide screen, under them on a phone), one column wide. An `ok` or `info`427view with no button folds to one line (its headline) in an "All clear" list after every card428that needs someone; `attention` and `critical` keep the full card. So say all-is-well in the429headline alone, and raise the level when the rows matter. `progress` is always a ring beside430the headline holding `done/total`, so don't repeat the count in `detail`. A `regular` card431shows three rows, `wide` and `full` all of them: size is how much a card shows, not its width.432433**Pressing a button** calls the action's function with `{ widget, action, input }` and434an `Idempotency-Key` built from widget, action and the button's `key` (none: a hash of435`input`), so a double click or stale card replays the first answer. **Give every button436a `key` that names the thing done** (`"2026-09"`), not a timestamp. The action's return437decides the card: `{ view }` re-renders, `{ message }` shows a line, anything else438re-reads the widget; a throw or non-2xx leaves it as it was, with the reason shown.439Widgets show **in production only**, on the apps-first home. One that should not run on every home load declares440`cache: { ttlSeconds }` on its function.441442### Laying out the home443444The org's home is one layout document, written by an org owner or admin (not by an445app): the widget groups of Today in order, and the widgets as `<app>/<widget>` at a size446from that widget's `sizes`. The apps always come first and are always drawn; `apps` and447`insights` entries are accepted but place nothing, and leaving `insights` out hides it. No coordinates; an edit is a list move. `widgets` sections may repeat,448each a group with an optional `title` (≤ 40); `others` goes on the first only. An item449may add `params`, a `title` and an `id`, so one widget can appear as several copies450(one per store), each with its own `id`.451452**Who a widget is for.** A group or an item may add `for`:453`{ "people": ["scott@acme.com"], "teams": ["Office"] }` (emails, and org team names; at454least one list non-empty, at most 50 each, matched case-insensitively). Only those people455see it. It only narrows: app access applies first, and an item's `for` narrows its456group's. Use it when someone may open the app but its widget is noise to them ("show457Bookkeeping's cards only to Scott and Dylan"), rather than changing who can open the app.458Widgets the layout does not list stay everyone's. Each person can also hide a widget or459turn Today off on their own home; a layout cannot undo that.460461```json462{ "version": 1, "sections": [463 { "kind": "apps" },464 { "kind": "widgets", "items": [ { "widget": "warehouse/receiving", "hidden": true } ],465 "others": "show" },466 { "kind": "widgets", "title": "Back office",467 "for": { "people": ["scott@acme.com", "dylan@acme.com"] },468 "items": [ { "widget": "bookkeeping/close", "size": "full" } ] },469 { "kind": "widgets", "title": "Stores", "items": [470 { "widget": "store-ops/today", "id": "mission", "title": "Mission St",471 "params": { "store": "mission" } } ] },472 { "kind": "insights" } ] }473```474475Get, edit, preview, then apply:476477```bash478oxyc home show --org acme # what a person sees: widgets, sizes, headlines479oxyc home get --org acme > layout.json # { revision, layout }: edit the layout480oxyc home apply --org acme -f layout.json --dry-run # resulting home as text, nothing saved481oxyc home apply --org acme -f layout.json # save (sends the file's revision)482```483484A refused layout (exit 6) lists every problem as `path: message (fix)`; fix them all.485Exit 8 means someone saved since your `get`: `home get` again and redo the edit486(`--force` overwrites). `oxyc home reset` restores the default. A widget not listed487still shows after the first group's items unless `others` is `"hide"`, except one with a488required setting and no default: it needs an entry that sets `params`.489490## Phone layout491492People open these apps on their phones. A desktop layout squeezed into one column493is not a phone layout: tables scroll sideways, tabs get cut, the answer sits under a494map. Give each screen people use on a phone a **phone view** built from the phone495kit in `@oxy-hq/sdk/shell`, beside the desktop component, from the same hooks:496497```tsx498const phone = usePhoneLayout();499return phone ? <OrdersPhone {...data} /> : <OrdersDesktop {...data} />;500```501502The desktop layout stays exactly as it is. On the phone: a `PhoneTabBar` for503sections, the answer first (`PhoneKpiStrip`, "needs you" `PhoneRow`s), table rows504as `PhoneCard`s (**never a sideways-scrolling table**), details in a `PhoneSheet`,505maps as their own tab, `PhoneHint` instead of hover tooltips. The mapping from each506desktop part, the type and touch floor, and how to check it at 390×844 and 844×390:507[references/phone-layout.md](references/phone-layout.md).508509## Four pitfalls510511- **CORS errors are usually wrong-URL errors in disguise.** The SDK's512 base URL must be `${OXY_URL}/api`, not `OXY_URL` bare. The API513 router (which carries CORS headers) lives under `/api/*`. Hitting514 `/<projectId>/...` lands in the static fallback and the missing515 headers look like a CORS failure.516517- **Cookie auth requires `credentials: "include"`.** The SDK's518 `useQuery` sets this. If you fetch directly, set it yourself or the519 `oxy_session` cookie won't be forwarded.520521- **`projectId` in the manifest is advisory, not enforcement.** The522 SDK uses it to construct the query URL. Authorization is the user's523 cookie → user → org_member of the project's org, decided524 server-side. A bundle that ships a stolen `projectId` can't read525 data the user can't already read.526527- **Cloud mode is the target.** Don't branch on local vs. cloud; don't528 rely on the nil UUID `00000000-...` as a default project; don't529 assume `OXY_STATE_DIR` is writable.530531Two more that read as bugs — `useTrackEvent("oxy-…")` is refused (`400`,532the prefix is reserved), and a hovered-but-never-opened app records no view —533are in [references/performance-and-usage.md](references/performance-and-usage.md).534535## Run a function locally536537`oxyc fn dev <name>` runs one handler from your source in-process, in seconds,538with no publish. It bundles the handler with the same esbuild call `oxyc publish`539uses, then invokes it on `createTestContext` seeded from `oxy-app.json`: the540function's capabilities, `ctx.env` from the env file, and its destinations. It541prints the response, then the host ops the handler made.542543```bash544oxyc fn dev notify --input '{"name":"Ada"}' # a literal, @file, or - for stdin545oxyc fn dev notify --input @sample.json --env-file .env.dev --watch546oxyc fn dev report --read-through --env dev # reads hit that deployment; writes stay stubbed547```548549- **Run it from the app directory** (the one with `oxy-app.json`). `--env-file`550 defaults to `.env`; `ctx.env` holds that file's keys and nothing from your551 shell. A `required` secret the file lacks is a warning.552- **`--watch` re-runs** when a file in the app changes, reading the manifest,553 env file and `@file` input afresh. A broken edit prints its error and waits554 for the next save. Exit with Ctrl-C.555- **Exit codes:** `0` for a 2xx `Response`; `1` when the handler throws or556 answers non-2xx (as `fn call`); `2` for a function the manifest does not557 declare, or a missing env file.558- **A local run is not the isolate.** There is no timeout, memory or log cap;559 `Buffer`, `TextEncoder` and `process` exist where the isolate lacks them; and560 every warehouse, semantic, storage, fetch and email call is a stub in memory,561 so (without `--read-through`) nothing reaches a deployment. The context does refuse what the manifest562 does not grant, in the host's words. A `ctx.warehouse` destination's engine is563 assumed (a `customerWarehouseWrites` entry is a customer Postgres, any other564 is Airhouse), because the workspace config is not read.565- **`--read-through` reads real data, and only reads.** It sends `ctx.query`,566 `ctx.warehouse.query` and `ctx.semantic.query` to the deployment `--env <name|url>`567 (or `--target`) names, through the app's own `POST /api/projects/{project}/query`568 and `/semantic-query`, with your `oxyc login` bearer or `OXY_TOKEN` (the way569 `oxyc api` authenticates). What you may read is the server's decision. The570 project is `--project` / `OXY_PROJECT`, else looked up from `oxy-app.json`571 `slug` + `orgSlug`. Every other call (warehouse writes, `ctx.tx`, `ctx.oltp`,572 `ctx.airhouse`, storage, fetch, email, notify, and `ctx.queryStream`) stays a573 stub in memory and never leaves your machine. Each call in the report is marked574 `real` or `stubbed`. `--env` defaults to production, so name a dev environment575 when you can. A sandbox agent token is refused: use a person's login.576 `ctx.semantic.query` row keys are `view__member` in the isolate but the route577 strips the prefix, so read-through puts it back from your spec; a key it could578 not map unambiguously stays as the route named it, so confirm that one with579 `fn call` on a sandbox. Still not the isolate.580- Before you ship, run it where it really runs: publish to your sandbox and581 `oxyc fn call`, or `oxyc checks run`. For a committed regression test use582 `createTestContext` from `@oxy-hq/sdk/testing` in vitest, as the functions583 template does.584585## Publishing586587**These commands are a person's, or an agent's on a token that person588approved.** `oxyc login` is the engineer's own browser login, and a publish to589a channel or a promote is refused under a sandbox agent token. As an agent,590iterate in your own sandbox591([references/sandbox-agent-loop.md](references/sandbox-agent-loop.md)). Ship592only when your engineer asked you to, on an agent token they approved593(`oxyc tokens create --agent`, plus `--standing` for staff access): it594publishes and promotes as them. With no browser on your machine, see595[Headless and cloud sessions](#headless-and-cloud-sessions): a token approved596there never carries staff access.597598Ship with `oxyc publish` (`npm i -g @oxy-hq/cli`) — **no CI step, no S3 sync,599no folder picker**. From the app directory:600601```bash602oxyc login --env production # once; browser flow, caches a token,603 # and prints whether you're an app-admin604oxyc validate # schema, data-placement and function checks first605oxyc publish --env production # build → bundle functions → tar → upload (draft = staging)606oxyc promote <org>/<app> --env production --dry-run # the plan: changes, migrations, blockers607oxyc promote <org>/<app> --env production # staging's build → production (asks first)608oxyc rollback <org>/<app> --env production --app-env production # back to the build before609```610611Production only ever serves a build staging has served, and every way of612moving it — `oxyc promote`, `oxyc rollback`, the console's **Promote draft**613and **Roll back to…**, a promoting publish — applies the build's pending migrations **before** it moves614(a failure leaves the old build live). `promote` and `rollback` print the plan615first and refuse on a blocker: `staging_never_served`, `required_secrets_unset`616(set the key in production first), `schedule_removal_unconfirmed` (pass617`--remove-schedule <function>`). Off a terminal pass `--yes`.618`oxyc publish --promote` still works and warns that it is deprecated: it shows619nobody the plan.620621- **Identity**, for each half, is `--app` / `--org`, then `OXY_APP` /622 `OXY_ORG`, then the manifest's `slug` + `orgSlug`, then an623 `apps/<org>/<app>/` working directory. `--org` takes a slug or a UUID; pass624 the slug whenever `oxyc` runs the build, because the asset base path is625 baked from what you pass. With no org from any of those, the build stops626 with `missing org: the app's base path needs it` (exit `2`): add627 `"orgSlug"` to `oxy-app.json` (`create-oxy-app --org <slug>` writes it)628 or `--org <org-slug>`, and `--app <slug>` when the directory has no629 manifest. The server upserts the app row — there is no separate create630 step.631- **First publish of a new app is one step.** The app is not registered632 yet, so the build-config lookup 404s; with your login `oxyc publish` then633 lists the org's workspaces, and when there is exactly one (a freshly634 provisioned org) publishes into it and says which. With several it prints635 them with their uuids beside the flag to pass — `--project636 <workspace-uuid>` (or `OXY_PROJECT`), which also supplies the org. Drop637 the flag after the first publish — it's auto-resolved from then on.638 Trusted publishing (CI) only ever publishes a registered app.639- **Old kit.** Before the build, an app whose `@oxy-hq/sdk` or640 `@oxy-hq/vite-plugin` is more than one minor behind the versions this641 `oxyc` was built with gets one warning naming the `pnpm add` — the642 manifest contract and the function runtime move with them.643- **`--env` targets:** `local` → a local Oxy web-app Vite dev server `:5173`644 (it serves `/cli-auth` and proxies `/api` to oxy on `:3000`), `dev` →645 `aip.dev.oxy.tech`, `staging` → `aip.staging.oxy.tech`, `production` (the646 default) → `app.oxygen-hq.com`. A value with a `.`, `/` or `:` is read as a647 URL.648- **Function lint.** Before the build, each Oxy Function's source is checked649 for what the host would refuse at the first call: a `ctx.*` call whose650 capability the manifest lacks, a global the isolate does not have651 (`Buffer`, `TextEncoder`, `process`, …), a write outside `destinations`. A finding fails652 the publish (exit `1`); `--allow-function-lint` publishes past a false653 positive.654- `--dir out` skips the build and uploads a prebuilt directory (declared655 functions are still bundled into it); `--build-only` builds and bundles656 without a credential or an upload; `--prebuilt` (with `--dir`) uploads a657 directory whose functions are already bundled. Server warnings print on658 stderr; `--json` prints the result.659- `.env.local` / `.env` are loaded from the app directory and its parents660 (never overriding what is already set), so a stray `OXY_PROJECT` there661 retargets a publish.662- **Credential:** `OXY_TOKEN`, then `oxyc login`'s cache — or, in a GitHub663 Actions job with `id-token: write`, the job's OIDC identity.664 `oxyc init-ci` writes a workflow that publishes with no stored secret.665- Promote / roll back / unpublish from the oxy admin app-detail console;666 every publish is audited (who shipped each build, when).667- **What is live now:** `oxyc apps show <org>/<app>` prints the live build, the668 commit it was built from, a newer draft if there is one, and its health;669 `oxyc apps builds <org>/<app>` is the history. `oxyc apps drift <org>/<app>`670 lists the commits in your checkout that touch the app after the live build's671 commit — `unknown` there means it could not compare, not that nothing changed.672- **A customer's own domain** (`app.acme.com`) serves production only:673 `oxyc apps domains add <org>/<app> app.acme.com` prints a CNAME and a TXT674 record for the customer to create, then `oxyc apps domains verify …`. Build675 nothing differently — the bundle keeps its `/customer-apps/<org>/<app>/` base676 and its same-origin `/api` calls work on the domain. A visitor signs in once677 through the Oxygen login; on that domain the session reaches only the app's678 workspace, so a call to another workspace there is refused by design.679680The build is not the check: after a publish, drive the page681([references/verifying-in-the-browser.md](references/verifying-in-the-browser.md)).682683## Headless and cloud sessions684685A Claude Code cloud session (claude.ai/code), a CI runner or any machine with686no browser can mint a token, iterate in a sandbox and publish. A person687approves once, from any device.6886891. **The cloud environment.** Its owner sets this once in the environment's690 settings. Under **Network access → Custom**, allow `app.oxygen-hq.com` and691 `*.oxy.tech`, and keep the default package-manager list ticked so npm can692 install `oxyc`. Optionally add `OXY_APPROVER=<their email>` under693 environment variables, so each approval request is pushed to them.6942. **The repo's SessionStart hook,** `.claude/hooks/oxyc-cloud-session.sh`,695 with its entry in `.claude/settings.json`. In a cloud session it installs696 `oxyc` and routes it through the session's proxy. It also makes a minted697 token reach every later command, which an `export` in one shell call cannot698 do. What it prints at session start says what is missing.699 - A customer repo that `oxyc new` or `oxyc adopt` made has both files.700 - In an existing customer repo, `oxyc update --apply` adds the script but701 only reports the settings entry, because the team may have their own702 settings. Add the entry by hand:703 ```json704 { "hooks": { "SessionStart": [ { "matcher": "", "hooks": [ { "type": "command",705 "command": "\"${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/oxyc-cloud-session.sh\"",706 "timeout": 120 } ] } ] } }707 ```708 - Any other repo can copy both from the `template/.claude/` directory of the709 installed `@oxy-hq/cli` package.7103. **The credential.** Run this in the background, because the approval can711 outlast a two-minute shell limit:712 ```bash713 mkdir -p ~/.config/oxy && (umask 077; oxyc tokens create --agent --no-browser \714 --env production >~/.config/oxy/agent-token.env)715 ```716 Give your engineer the URL and the code it prints on stderr. The token goes717 to that file and never into your context. The hook loads the file before718 every later command. To iterate in a sandbox, mint719 `--sandbox-agent --app <org>/<app>` into the same file instead. A token720 lasts 8 hours by default (`--hours`, up to 168). On exit `4`, mint again.721722 **Or a network secret, which nobody approves per session.** The723 environment's owner adds one in its settings: Allowed websites724 `app.oxygen-hq.com` (and `*.oxy.tech`), header `Authorization`, prefix725 `Bearer`, and a personal access token or service account token as the726 value. They also set `OXY_TOKEN=from-proxy` in its environment variables.727 The proxy then adds the token to each request after it leaves the VM, so it728 is never in a file, a variable or your context, and `oxyc` sends none.729 The hook checks it with `oxyc whoami` and says if it is not attached. On730 exit `4`, report it: the secret's hosts, header or token are wrong, and731 only the owner can fix them. Do not mint a token over it unasked. A sandbox732 still needs an `--sandbox-agent` token minted into the file, which replaces733 the sentinel.7344. **Ship** with the commands above, each with `--token-env OXY_TOKEN`.735 `promote` and `rollba736737…(truncated)