From 1e84023a446d6f833d5ead6da42ced6d964ba3c2 Mon Sep 17 00:00:00 2001 From: Bkk1234 Date: Sun, 1 Nov 2026 17:24:44 +0700 Subject: [PATCH] reboot alterflixhub --- .agents/skills/actions/SKILL.md | 214 + .../actions/references/action-fields.md | 145 + .agents/skills/actions/references/examples.md | 96 + .../actions/references/provider-apis.md | 95 + .agents/skills/adding-a-feature/SKILL.md | 236 + .agents/skills/agent-engines/SKILL.md | 232 + .agents/skills/agent-native-docs/SKILL.md | 161 + .agents/skills/agent-native-toolkit/SKILL.md | 314 + .agents/skills/authentication/SKILL.md | 271 + .agents/skills/build-an-app/SKILL.md | 200 + .../references/data-and-access.md | 91 + .../references/edit-points-default.md | 23 + .../build-an-app/references/rooms-example.md | 1027 ++ .../build-an-app/references/verification.md | 57 + .agents/skills/client-side-routing/SKILL.md | 87 + .agents/skills/context-awareness/SKILL.md | 282 + .../skills/customizing-agent-native/SKILL.md | 219 + .agents/skills/delegate-to-agent/SKILL.md | 62 + .agents/skills/frontend-design/SKILL.md | 109 + .../references/visual-direction.md | 102 + .agents/skills/inline-embeds/SKILL.md | 88 + .agents/skills/integration-webhooks/SKILL.md | 364 + .agents/skills/internationalization/SKILL.md | 48 + .agents/skills/multi-app-workspace/SKILL.md | 337 + .agents/skills/notifications/SKILL.md | 95 + .agents/skills/onboarding/SKILL.md | 56 + .agents/skills/performance/SKILL.md | 79 + .agents/skills/progress/SKILL.md | 99 + .agents/skills/real-time-collab/SKILL.md | 392 + .agents/skills/real-time-sync/SKILL.md | 146 + .agents/skills/reliable-mutations/SKILL.md | 72 + .agents/skills/secrets/SKILL.md | 82 + .agents/skills/security/SKILL.md | 80 + .agents/skills/shadcn-ui/SKILL.md | 71 + .agents/skills/sharing/SKILL.md | 289 + .agents/skills/storing-data/SKILL.md | 223 + .claude/skills | 1 + .env.example | 8 + .gitignore | 43 + .ignore | 1 + .mcp.json | 8 + .oxfmtrc.json | 8 + AGENTS.md | 47 + CLAUDE.md | 5 + DECISIONS.md | 31 + DESIGN.md | 209 + DEVELOPING.md | 363 + README.md | 77 + actions/hello.spec.ts | 17 + actions/hello.ts | 14 + actions/navigate.ts | 40 + actions/provider-api-request.spec.ts | 35 + actions/provider-api-request.ts | 48 + actions/run.ts | 2 + actions/view-screen.spec.ts | 36 + actions/view-screen.ts | 31 + agent-native.config.ts | 7 + agent-native.json | 9 + app/components/admin/AboutEditor.tsx | 300 + app/components/admin/AdminSection.tsx | 51 + app/components/admin/ChipPicker.tsx | 82 + .../admin/CinemaFacilitiesEditor.tsx | 105 + app/components/admin/CinemaList.tsx | 253 + app/components/admin/CommaListInput.tsx | 64 + app/components/admin/ContactsEditor.tsx | 113 + app/components/admin/PhotosEditor.tsx | 106 + app/components/admin/SlugInput.tsx | 120 + app/components/admin/TransportEditor.tsx | 116 + app/components/admin/admin-helpers.spec.ts | 83 + app/components/cinema/CinemaNotFound.tsx | 26 + app/components/cinema/CinemaSummary.tsx | 60 + app/components/cinema/ContactPanel.tsx | 73 + app/components/cinema/FacilitiesSection.tsx | 77 + app/components/cinema/Gallery.tsx | 97 + app/components/cinema/LocationPanel.tsx | 93 + app/components/cinema/TransportList.tsx | 49 + app/components/home/HeroSection.tsx | 97 + app/components/layout/Layout.tsx | 28 + app/components/site/CinemaCard.tsx | 98 + app/components/site/CinemaGrid.tsx | 66 + app/components/site/LocaleSwitcher.tsx | 86 + app/components/site/Logo.spec.ts | 35 + app/components/site/Logo.tsx | 26 + app/components/site/SiteFooter.tsx | 55 + app/components/site/SiteHeader.tsx | 39 + app/components/site/SiteShell.tsx | 73 + app/components/site/footer-icons.ts | 33 + app/components/ui/button.tsx | 1 + app/components/ui/toolkit-provider.tsx | 20 + app/design-system.ts | 3 + app/entry.client.tsx | 10 + app/entry.server.tsx | 10 + app/global.css | 263 + app/hooks/use-navigation-state.ts | 73 + app/hooks/use-near-me.tsx | 124 + app/lib/admin-auth.server.ts | 72 + app/lib/analytics-client.ts | 41 + app/lib/analytics-types.ts | 53 + app/lib/analytics.server.ts | 173 + app/lib/analytics.spec.ts | 70 + app/lib/app-config.ts | 11 + app/lib/cinemas-visibility.spec.ts | 83 + app/lib/cinemas.spec.ts | 62 + app/lib/cinemas.ts | 401 + app/lib/content-context.tsx | 24 + app/lib/content-seed.ts | 115 + app/lib/content-types.ts | 54 + app/lib/content.server.ts | 264 + app/lib/daily-order.spec.ts | 79 + app/lib/daily-order.ts | 99 + app/lib/design-tokens.ts | 42 + app/lib/gallery.spec.ts | 38 + app/lib/gallery.ts | 24 + app/lib/geo.spec.ts | 96 + app/lib/geo.ts | 127 + app/lib/i18n/index.tsx | 164 + app/lib/i18n/locale.spec.ts | 26 + app/lib/i18n/merge.ts | 55 + app/lib/i18n/messages.spec.ts | 32 + app/lib/i18n/messages.ts | 403 + app/lib/map-embed.spec.ts | 100 + app/lib/map-embed.ts | 69 + app/lib/popularity.server.ts | 102 + app/lib/popularity.spec.ts | 94 + app/lib/tab-id.ts | 3 + app/lib/utils.ts | 1 + app/root.tsx | 115 + app/routes.ts | 6 + app/routes/_index.tsx | 144 + app/routes/about.tsx | 121 + app/routes/admin.tsx | 1221 ++ app/routes/admin_.login.tsx | 86 + app/routes/cinema.$slug.tsx | 97 + app/vite-env.d.ts | 6 + builder.config.json | 21 + components.json | 20 + docs/admin-guide.md | 152 + docs/api.md | 51 + docs/architecture.html | 774 + docs/push-to-gitea.md | 45 + drizzle.config.ts | 14 + drizzle/START_HERE.md | 42 + drizzle/migrations/meta/_journal.json | 5 + drizzle/schema.ts | 27 + learnings.defaults.md | 5 + netlify.toml | 18 + package.json | 125 + pnpm-lock.yaml | 13778 ++++++++++++++++ pnpm-workspace.yaml | 70 + prototype/Details cenima-desktop.jpg | Bin 0 -> 9050268 bytes prototype/Details cenima-mobile.jpg | Bin 0 -> 325046 bytes prototype/Home-desktop.jpg | Bin 0 -> 9864543 bytes prototype/home-mobile.jpg | Bin 0 -> 339296 bytes public/favicon.svg | 1 + public/icon-180.svg | 1 + public/icon-192.svg | 1 + public/icon-512.svg | 1 + public/images/hero.png | Bin 0 -> 430161 bytes public/manifest.json | 20 + react-router.config.ts | 8 + scripts/add-cinemas-batch.py | 238 + scripts/maybe-migrate.mjs | 35 + scripts/migrate-production.ts | 53 + server/agent/app-operation-guard.ts | 119 + server/db.ts | 30 + server/mcp-provider-schemas.spec.ts | 31 + server/middleware/auth.ts | 6 + server/plugins/agent-chat.ts | 24 + server/plugins/agent-native-email-branding.ts | 14 + server/plugins/auth.ts | 8 + server/plugins/config.ts | 15 + server/plugins/otel.ts | 6 + server/routes/[...page].get.ts | 24 + server/routes/api/admin/analytics.get.ts | 13 + .../routes/api/admin/cinemas/import.post.ts | 41 + server/routes/api/admin/content.get.ts | 9 + server/routes/api/admin/content.put.ts | 41 + server/routes/api/admin/login.post.ts | 22 + server/routes/api/admin/logout.post.ts | 8 + server/routes/api/admin/session.get.ts | 7 + server/routes/api/analytics/collect.post.ts | 80 + server/routes/index.get.ts | 2 + ssr-entry.ts | 11 + tests/use-navigation-state.spec.ts | 163 + tsconfig.json | 31 + vite.config.ts | 25 + vitest.config.spec.ts | 9 + vitest.config.ts | 20 + 188 files changed, 31629 insertions(+) create mode 100644 .agents/skills/actions/SKILL.md create mode 100644 .agents/skills/actions/references/action-fields.md create mode 100644 .agents/skills/actions/references/examples.md create mode 100644 .agents/skills/actions/references/provider-apis.md create mode 100644 .agents/skills/adding-a-feature/SKILL.md create mode 100644 .agents/skills/agent-engines/SKILL.md create mode 100644 .agents/skills/agent-native-docs/SKILL.md create mode 100644 .agents/skills/agent-native-toolkit/SKILL.md create mode 100644 .agents/skills/authentication/SKILL.md create mode 100644 .agents/skills/build-an-app/SKILL.md create mode 100644 .agents/skills/build-an-app/references/data-and-access.md create mode 100644 .agents/skills/build-an-app/references/edit-points-default.md create mode 100644 .agents/skills/build-an-app/references/rooms-example.md create mode 100644 .agents/skills/build-an-app/references/verification.md create mode 100644 .agents/skills/client-side-routing/SKILL.md create mode 100644 .agents/skills/context-awareness/SKILL.md create mode 100644 .agents/skills/customizing-agent-native/SKILL.md create mode 100644 .agents/skills/delegate-to-agent/SKILL.md create mode 100644 .agents/skills/frontend-design/SKILL.md create mode 100644 .agents/skills/frontend-design/references/visual-direction.md create mode 100644 .agents/skills/inline-embeds/SKILL.md create mode 100644 .agents/skills/integration-webhooks/SKILL.md create mode 100644 .agents/skills/internationalization/SKILL.md create mode 100644 .agents/skills/multi-app-workspace/SKILL.md create mode 100644 .agents/skills/notifications/SKILL.md create mode 100644 .agents/skills/onboarding/SKILL.md create mode 100644 .agents/skills/performance/SKILL.md create mode 100644 .agents/skills/progress/SKILL.md create mode 100644 .agents/skills/real-time-collab/SKILL.md create mode 100644 .agents/skills/real-time-sync/SKILL.md create mode 100644 .agents/skills/reliable-mutations/SKILL.md create mode 100644 .agents/skills/secrets/SKILL.md create mode 100644 .agents/skills/security/SKILL.md create mode 100644 .agents/skills/shadcn-ui/SKILL.md create mode 100644 .agents/skills/sharing/SKILL.md create mode 100644 .agents/skills/storing-data/SKILL.md create mode 100644 .claude/skills create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 .ignore create mode 100644 .mcp.json create mode 100644 .oxfmtrc.json create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100644 DECISIONS.md create mode 100644 DESIGN.md create mode 100644 DEVELOPING.md create mode 100644 README.md create mode 100644 actions/hello.spec.ts create mode 100644 actions/hello.ts create mode 100644 actions/navigate.ts create mode 100644 actions/provider-api-request.spec.ts create mode 100644 actions/provider-api-request.ts create mode 100644 actions/run.ts create mode 100644 actions/view-screen.spec.ts create mode 100644 actions/view-screen.ts create mode 100644 agent-native.config.ts create mode 100644 agent-native.json create mode 100644 app/components/admin/AboutEditor.tsx create mode 100644 app/components/admin/AdminSection.tsx create mode 100644 app/components/admin/ChipPicker.tsx create mode 100644 app/components/admin/CinemaFacilitiesEditor.tsx create mode 100644 app/components/admin/CinemaList.tsx create mode 100644 app/components/admin/CommaListInput.tsx create mode 100644 app/components/admin/ContactsEditor.tsx create mode 100644 app/components/admin/PhotosEditor.tsx create mode 100644 app/components/admin/SlugInput.tsx create mode 100644 app/components/admin/TransportEditor.tsx create mode 100644 app/components/admin/admin-helpers.spec.ts create mode 100644 app/components/cinema/CinemaNotFound.tsx create mode 100644 app/components/cinema/CinemaSummary.tsx create mode 100644 app/components/cinema/ContactPanel.tsx create mode 100644 app/components/cinema/FacilitiesSection.tsx create mode 100644 app/components/cinema/Gallery.tsx create mode 100644 app/components/cinema/LocationPanel.tsx create mode 100644 app/components/cinema/TransportList.tsx create mode 100644 app/components/home/HeroSection.tsx create mode 100644 app/components/layout/Layout.tsx create mode 100644 app/components/site/CinemaCard.tsx create mode 100644 app/components/site/CinemaGrid.tsx create mode 100644 app/components/site/LocaleSwitcher.tsx create mode 100644 app/components/site/Logo.spec.ts create mode 100644 app/components/site/Logo.tsx create mode 100644 app/components/site/SiteFooter.tsx create mode 100644 app/components/site/SiteHeader.tsx create mode 100644 app/components/site/SiteShell.tsx create mode 100644 app/components/site/footer-icons.ts create mode 100644 app/components/ui/button.tsx create mode 100644 app/components/ui/toolkit-provider.tsx create mode 100644 app/design-system.ts create mode 100644 app/entry.client.tsx create mode 100644 app/entry.server.tsx create mode 100644 app/global.css create mode 100644 app/hooks/use-navigation-state.ts create mode 100644 app/hooks/use-near-me.tsx create mode 100644 app/lib/admin-auth.server.ts create mode 100644 app/lib/analytics-client.ts create mode 100644 app/lib/analytics-types.ts create mode 100644 app/lib/analytics.server.ts create mode 100644 app/lib/analytics.spec.ts create mode 100644 app/lib/app-config.ts create mode 100644 app/lib/cinemas-visibility.spec.ts create mode 100644 app/lib/cinemas.spec.ts create mode 100644 app/lib/cinemas.ts create mode 100644 app/lib/content-context.tsx create mode 100644 app/lib/content-seed.ts create mode 100644 app/lib/content-types.ts create mode 100644 app/lib/content.server.ts create mode 100644 app/lib/daily-order.spec.ts create mode 100644 app/lib/daily-order.ts create mode 100644 app/lib/design-tokens.ts create mode 100644 app/lib/gallery.spec.ts create mode 100644 app/lib/gallery.ts create mode 100644 app/lib/geo.spec.ts create mode 100644 app/lib/geo.ts create mode 100644 app/lib/i18n/index.tsx create mode 100644 app/lib/i18n/locale.spec.ts create mode 100644 app/lib/i18n/merge.ts create mode 100644 app/lib/i18n/messages.spec.ts create mode 100644 app/lib/i18n/messages.ts create mode 100644 app/lib/map-embed.spec.ts create mode 100644 app/lib/map-embed.ts create mode 100644 app/lib/popularity.server.ts create mode 100644 app/lib/popularity.spec.ts create mode 100644 app/lib/tab-id.ts create mode 100644 app/lib/utils.ts create mode 100644 app/root.tsx create mode 100644 app/routes.ts create mode 100644 app/routes/_index.tsx create mode 100644 app/routes/about.tsx create mode 100644 app/routes/admin.tsx create mode 100644 app/routes/admin_.login.tsx create mode 100644 app/routes/cinema.$slug.tsx create mode 100644 app/vite-env.d.ts create mode 100644 builder.config.json create mode 100644 components.json create mode 100644 docs/admin-guide.md create mode 100644 docs/api.md create mode 100644 docs/architecture.html create mode 100644 docs/push-to-gitea.md create mode 100644 drizzle.config.ts create mode 100644 drizzle/START_HERE.md create mode 100644 drizzle/migrations/meta/_journal.json create mode 100644 drizzle/schema.ts create mode 100644 learnings.defaults.md create mode 100644 netlify.toml create mode 100644 package.json create mode 100644 pnpm-lock.yaml create mode 100644 pnpm-workspace.yaml create mode 100644 prototype/Details cenima-desktop.jpg create mode 100644 prototype/Details cenima-mobile.jpg create mode 100644 prototype/Home-desktop.jpg create mode 100644 prototype/home-mobile.jpg create mode 100644 public/favicon.svg create mode 100644 public/icon-180.svg create mode 100644 public/icon-192.svg create mode 100644 public/icon-512.svg create mode 100644 public/images/hero.png create mode 100644 public/manifest.json create mode 100644 react-router.config.ts create mode 100644 scripts/add-cinemas-batch.py create mode 100644 scripts/maybe-migrate.mjs create mode 100644 scripts/migrate-production.ts create mode 100644 server/agent/app-operation-guard.ts create mode 100644 server/db.ts create mode 100644 server/mcp-provider-schemas.spec.ts create mode 100644 server/middleware/auth.ts create mode 100644 server/plugins/agent-chat.ts create mode 100644 server/plugins/agent-native-email-branding.ts create mode 100644 server/plugins/auth.ts create mode 100644 server/plugins/config.ts create mode 100644 server/plugins/otel.ts create mode 100644 server/routes/[...page].get.ts create mode 100644 server/routes/api/admin/analytics.get.ts create mode 100644 server/routes/api/admin/cinemas/import.post.ts create mode 100644 server/routes/api/admin/content.get.ts create mode 100644 server/routes/api/admin/content.put.ts create mode 100644 server/routes/api/admin/login.post.ts create mode 100644 server/routes/api/admin/logout.post.ts create mode 100644 server/routes/api/admin/session.get.ts create mode 100644 server/routes/api/analytics/collect.post.ts create mode 100644 server/routes/index.get.ts create mode 100644 ssr-entry.ts create mode 100644 tests/use-navigation-state.spec.ts create mode 100644 tsconfig.json create mode 100644 vite.config.ts create mode 100644 vitest.config.spec.ts create mode 100644 vitest.config.ts diff --git a/.agents/skills/actions/SKILL.md b/.agents/skills/actions/SKILL.md new file mode 100644 index 0000000..8399f0c --- /dev/null +++ b/.agents/skills/actions/SKILL.md @@ -0,0 +1,214 @@ +--- +name: actions +description: >- + How to create and run agent actions. Actions are the single source of truth + for app operations — the agent calls them as tools and frontend code calls + them through client hooks. Use when creating a new action, adding an API + integration, or wiring up frontend data fetching. +scope: dev +metadata: + internal: true +--- + +# Agent Actions + +## Rule + +Actions in `actions/` are the **single source of truth** for app operations. The agent calls them as tools, the frontend calls them through `useActionQuery` / `useActionMutation`, and the framework owns the HTTP transport behind those hooks — no duplicate `/api/` routes. + +Before creating any custom route for app data, check `actions/` and the action table in `AGENTS.md`. An action already exists? Call it directly. Missing? Create or update a `defineAction`. **Stop trigger:** about to add a file under `server/routes/api/` (or middleware to guard one)? Check it against the exception list in *Custom `/api/` Routes* below first — even if you already started the route. + +## Keep Actions Deterministic + +An action may call a provider API, validate data, and persist records without being an AI feature — keep it deterministic, focused, and independently useful to the agent. Don't put LLM calls or a second model runtime in app actions. + +When a workflow is research, analysis, generation, recommendation, or synthesis — or spans several provider calls and writes — route it to the AgentSidebar via `sendToAgentChat({ openSidebar: true })` and let the agent orchestrate focused actions instead of hiding an AI-shaped workflow behind one opaque `generate-*`/`create-*` action just because its implementation happens to be deterministic. + +## How to Create an Action + +**One action per file, default-exported. The filename is the action name** (kebab-case): `actions/list-meals.ts` is the `list-meals` action. Don't put several `defineAction`s as named exports in one file — the registry keys actions by filename and only the default export is registered, so extra named exports never become callable and won't match `.generated/action-types.d.ts`. + +```ts +// actions/list-meals.ts +import { z } from "zod"; +import { defineAction } from "@agent-native/core/action"; +import { getDb } from "../server/db/index.js"; +import { meals } from "../server/db/schema.js"; + +export default defineAction({ + description: "List all meals", + schema: z.object({}), + http: { method: "GET" }, + run: async () => { + const db = getDb(); + const rows = await db.select().from(meals); + return rows; // Return objects/arrays, NOT JSON.stringify() + }, +}); +``` + +`schema` (Zod or Standard Schema-compatible) gives runtime validation, TS inference for `run()` args, and an auto-generated JSON Schema for the tool. Write it so an agent can call the tool correctly on the first try: `.describe()` every param and state enum values and the default in that text (`z.enum(["open","closed"]).default("open").describe('Filter status: "open" or "closed"; defaults to "open"')`); mark a field `.optional()` only when the action truly tolerates its absence — a silent default the caller cannot see is a required field in disguise; name the primary id the same way across a family (`create-/get-/update-/delete-` all take `id`, not a mix of `id` and `Id`), and if one action must differ, accept both with `.or()`; give nested objects a real schema, never a prose description; keep the one-line `description` complete enough to call the tool without a second lookup, because compact catalogs and `tool-search` show only that line. Use `z.coerce.number()` for numeric HTTP params, but write an explicit boolean parser instead of `z.coerce.boolean()`, which treats `"false"` as truthy. + +Use Drizzle's PostgreSQL query builder, not raw SQL/`getDbExec()` or direct driver imports, unless Drizzle can't express the query. Never hardcode API keys/tokens/secrets - read via `readAppSecret` / `resolveCredential` / OAuth helpers; `process.env` is deploy-level config only. + +**Decision order:** existing action → extend/create a `defineAction` → custom route as last resort (*Custom `/api/` Routes* below). Actions are already callable by agents, CLIs, hooks, HTTP, and MCP/A2A — don't wrap them in an umbrella REST API. + +## Keep the Action Surface Small and Orthogonal + +Every agent-exposed action is a tool in the model's context window; more tools degrades tool-selection quality. Add the fewest, most orthogonal actions that cover the capability. + +- **One orthogonal `update` per resource**, not one per field — `update-` taking an optional-fields patch, not `update--name` + `update--order` + … +- **Reach for a generic escape hatch before minting a new read action** — the `provider-api-catalog`/`docs`/`request` trio for provider data (`references/provider-apis.md`), `db-query` for ad hoc app-data reads in dev. +- **`agentTool: false`** hides a UI-only/programmatic action from the model while keeping it frontend/HTTP-callable — not `toolCallable: false`, which only blocks the sandboxed extension bridge and leaves the action visible everywhere else; reserve that one for high-blast-radius operations. +- **Delete or hide stale actions** once you confirm neither the UI nor an agent workflow uses them. + +## Key Actions — One Index, Every Surface + +Document the app's primary actions in the `AGENTS.md` action table. For first-turn loading, add those action names to the plugin's `initialToolNames` (`INITIAL_TOOL_NAMES` in some templates), or mark the full starter set `deferLoading: false` on the actions. When one action opts into per-action eager loading, unmarked actions are deferred; the remaining actions stay discoverable through `tool-search`. + +When MCP is enabled, its `Key tools` line is generated from `mcp.keyToolNames ?? initialToolNames` and filtered to the actions served on that surface. A configured `mcp.keyToolNames` overrides the advertised MCP/WebMCP key list; it does not change the in-app agent's first-turn list. Keep the advertised subset consistent with the primary actions in the `AGENTS.md` table and the external catalog; the table may also document other in-app actions. Do not hand-write another action list in `mcp.instructions`, a skill, or an external skill; describe when to use actions there. + +## The `http` Option + +Controls HTTP exposure: + +| Value | Behavior | Use for | +| --- | --- | --- | +| _(omitted)_ | `POST /_agent-native/actions/:name` | Write operations (default) | +| `{ method: "GET" }` | `GET /_agent-native/actions/:name` | Read-only queries | +| `{ method: "PUT"/"DELETE" }` | matching verb | Update / delete | +| `{ method: "GET", path: "x" }` | custom route path | Non-default path | +| `false` | never exposed as HTTP | `navigate`, `view-screen`, internal | + +Mutating actions (anything but `GET`) auto-refresh the UI on success — don't call `refresh-screen` after a normal action. Overrides (`readOnly`, `parallelSafe`) and exact trigger rules: `references/action-fields.md`. + +## Return Values + +Return **structured data** (objects, arrays), never `JSON.stringify()` — the framework serializes the response and only tries to parse a returned string as JSON, which isn't the same contract. + +```ts +run: async (args) => await fetchEvents(args.from, args.to); // good +run: async (args) => JSON.stringify(await fetchEvents(...)); // bad +``` + +A create/update result is read by more than the caller. These keys are well-known and survive result truncation: + +- `id` — the created or updated record. Pair it with a pure, synchronous `link` builder on the action (`link: (result) => ({ url: buildDeepLink({ app, view, params: { id: result.id } }), label })`) so MCP hosts and the desktop app surface an "Open …" deep link that lands in the editing view focused on the record; returning `url`/`urlPath` in the result works too. +- `nextRequiredAction` — the name of the next **tool** to call when the operation is one step of a flow the agent should keep driving (`nextRequiredAction: "update-slide"`). Never phrase it as waiting for the user: an MCP/WebMCP/A2A caller cannot receive an in-app answer. The agent loop keeps this field in continuation prompts even when the rest of a large result is dropped, and MCP callers see it as `Next: …`. +- `message`/`summary` — the one-line status external callers read; everything else stays in the structured result. +- `designSystem` — when a record can link a brand or design system, expose it as `designSystem: AgentDesignSystemContext | null` via `loadAgentDesignSystemContext(id, getDesignSystemAction)` from core's shared `design-system-agent-context`. Reads get the bounded summary (`scope: "summary"`, with a `next` line naming the full read); only the create action and `get-design-system` itself pass `{ full: true }`. `status: "unavailable"` is not `null`: keep the id and the message. Print it in text results with `formatAgentDesignSystemContext`; do not name the field anything else. + +For actions that attach a `chatUI` renderer, use `chatUI.projectResult` to return +only the small structured fields the renderer needs. `chatUI.when` is evaluated +against the full successful result first; the projection is used live and saved +for interrupted-run recovery. + +An action that hands control back to the user (question form, intake dialog) sets `endsTurn: true`; that hides it from MCP/WebMCP/A2A unless `mcpTool: true` is explicit — `references/action-fields.md`. For external-agent integrations, use the external-agents documentation slug listed by `agent-native-docs`. + +Reach for `outputSchema` (validate the return), `_agentImages` (attach images the agent can see), `authorize` (gate who may call it), or `needsApproval` (require human sign-off per call) only when the action needs that guarantee — examples in `references/action-fields.md`. + +### Write receipts + +A write action that can check its own effect returns a plain-object result with a reserved `_receipt`, so the final answer is reconciled with what the write did, not with the model's reading of a JSON string that may be truncated: + +```ts +import type { WriteReceipt } from "@agent-native/core/action"; + +const _receipt: WriteReceipt = { + changed: true, + verified: false, + summary: "Saved; panel 3 returned no rows.", + checks: [{ id: "panel-3", ok: false, detail: "0 rows" }], +}; +return { id, _receipt }; +``` + +`verified` is `true` (the effect was observed), `false` (checked and did not hold), or `"unverified"` (could not be checked); `checks` and `warnings` are optional. The agent loop reads the receipt before the result is stringified and truncated (summary 200 chars, 8 checks, 5 warnings): + +- `verified: false` or `changed: false` forces one honest-reconciliation retry per turn: the model must say what the receipt shows and may not call the change visible or working. If the retry is spent, the answer is prefixed with the receipt block. +- `verified: "unverified"` only prefixes that note; no retry. +- A receipt that is present but malformed counts as `unverified`, never clean. `changed: false` also records the call as `completedSideEffect: false`, unless a write nested in the action also entered its handler: a receipt, like `retrySafe`, speaks only for the action's own write. +- Set `subject` (the stable target, such as a dashboard id) so a later `changed: true, verified: true` receipt for the same subject can supersede an earlier flagged one in the same turn. When the earlier receipt had failing or unverified `checks`, the later receipts (from this action or another that writes the same subject) must carry an `ok: true` check with the same `id` for each; a receipt without checks never clears one that had them. A flagged receipt with no failing checks is superseded only by the same action. Receipts without a `subject` are never superseded. + +A receipt is not an error channel. A write that did not achieve the requested state throws (`fail()`); return `changed: false` only for a benign no-op, such as the record already being in the requested state. + +## Frontend Hooks + +Import from focused `@agent-native/core/client/*` entry points; the broad +`@agent-native/core/client` barrel is deprecated. Use action hooks, not +hand-written `fetch("/_agent-native/actions/...")`. + +```ts +import { useActionQuery, useActionMutation, callAction } from "@agent-native/core/client/hooks"; + +const { data: meals } = useActionQuery("list-meals", { date: "2025-01-01" }); // GET, types auto-inferred +const { mutate } = useActionMutation("log-meal"); // POST/PUT/DELETE +mutate({ name: "Salad", calories: 350 }); +const people = await callAction("search-people", { query }, { method: "GET" }); // imperative (debounce, prefetch) +``` + +Don't add manual generics like `useActionQuery(...)` — types come from `.generated/action-types.d.ts`. Mutations auto-invalidate all `["action"]` query keys, so GET queries refetch. A revisit paints the persisted result for the signed-in user and org before that refetch; see `references/action-fields.md` for `persistInBrowser: false`. + +When a query result varies by viewer or another client context that is not part of the action arguments, pass that stable context through `queryKeyScope`. It partitions only the local query cache; it is not sent to the action and never replaces server-side authorization. + +## How to Run (Agent) + +```bash +pnpm action log-meal --name "Salad" --calories 350 +``` + +CLI flags become action input fields (`--key value` or `--key=value`); the runner does not read or write files for `--input` or `--output`. The default template dispatches through core's `runScript()` in `actions/run.ts`. Action names are lowercase-with-hyphens (`pnpm action my-action` → `actions/my-action.ts`). + +After adding or changing several related actions, smoke-test **once** (one +happy-path call that proves the wire-up), then typecheck once. Do not run +`pnpm action …` for every method unless a smoke test failed and you need to +isolate which action broke. + +## CRUD + Drizzle in this starter + +Before hunting through `node_modules` for DB helpers, read: + +1. `drizzle/START_HERE.md` — where tables live + migrate commands +2. `drizzle/crud-action-example.ts` — copy-paste list/create/update/delete pattern + +DB client: `getDb` / `schema` from `server/db.ts`. + +## Custom `/api/` Routes + +Complete exception list — justified only when the caller isn't your own UI/agent, or the payload isn't JSON: **file uploads** (actions take JSON, not multipart), **streaming** (SSE/chunked needing direct H3 control), **webhooks**, **OAuth callbacks** (fixed redirect URL patterns), **public unauthenticated endpoints** (SEO/OG images, share links), **binary/non-JSON responses**. + +Everything else — CRUD, settings, search, list/detail reads, auth state, anything the UI fetches as JSON — is an action. Needing middleware to scope a route to the current user is itself a signal it should be an action. Existing template `/api/*` CRUD routes are being migrated; do not add new ones. + +## Do / Don't + +- **Do** keep one action, one job; document a reusable action (when to use it, key args, return fields to preserve) in `AGENTS.md` once it's called from outside one narrow screen; promote workflow-heavy actions (provider-backed, cross-app, MCP/A2A, multi-step) into a skill. +- **Do** use `fail(message, { errorCode, statusCode })` for user-friendly errors and import primitives from `@agent-native/core`(`/action`) instead of redefining them; use the core `upload-image` action or `uploadFile()` for durable images/files — never base64 into SQL, markdown, or action results. +- **Do** signal failure by throwing, using `fail()` for expected caller-readable failures. Never return `{ error: ... }` as a failure result: a normal return is treated as a successful action. Reserve bare errors for unexpected internal faults. +- **Do** use `fail()` rather than a bare `Error` for caller-readable failures. It carries the action's message, `errorCode`, and `details` to the browser and to agents; unexpected errors become a generic 500. Reserve bare throws for internal faults. +- **Do** give `fail()` the status that matches the cause: it defaults to `400`, and `useActionQuery` retries only `429`, `502`, `503`, and `504`. Mutations do not retry; use transient statuses only for retryable failures. +- **Do** throw `NoWriteError(message, { errorCode, statusCode })` instead of `fail()` for a rejection raised before the action's first write, such as an edit that matches nothing or a missing target. The agent then retries with corrected arguments instead of stopping on a write whose outcome is unknown. Throw it only before the first write: the framework rejects the claim when a nested write action ran, but it cannot see the handler's own writes. +- **Do** render `actionErrorMessage(error) ?? yourCopy` in UI, never bare `error.message`. The message keeps an `Action failed:` prefix that belongs in a console, so a toast built from it reads "Action update-brand-kit failed: That name is taken." The helper returns only what the action wrote, and `undefined` when nothing did (network drop, proxy HTML page), which is why the fallback is not optional. +- **Do** pass a real `errorCode` when the agent should branch on the failure rather than re-read it. Codes other than the default `action_failed` are appended to the tool result as `(errorCode: not_found)`, on both the in-app agent and MCP. `details` follow as an `Error details: {...}` JSON line, and as `structuredContent.error` over MCP, capped at 2,000 characters, so keep them to what the agent acts on next: ids, limits, field names. The status never reaches either. +- **Don't** re-export actions as REST — `/_agent-native/actions/:name` is already the REST surface; duplicating it under `/api/*` hides the operation from agents. +- **Don't** reach for provider integrations, `outputSchema`, `authorize`, `needsApproval`, or `_agentImages` without checking `references/` first — each has sharp edges covered there, not here. + +## Troubleshooting + +- **Action not found / type mismatch** — filename must match the command (`pnpm action foo-bar` → `actions/foo-bar.ts`), and the action must be the file's **default** export. Multiple `defineAction` named exports in one file register only the default; split them into one file each. +- **Args not parsing** — use `--key value` / `--key=value`; boolean flags are `--flag` (sets `"true"`). +- **Frontend 405** — `http.method` doesn't match the hook (`useActionQuery` for GET, `useActionMutation` for POST/PUT/DELETE). +- **Frontend gets undefined** — action must return structured data, not `JSON.stringify()`. + +## References + +- `references/provider-apis.md` — wiring a credentialed provider (HubSpot, Gong, Slack, …) for querying, reporting, or cross-source research. +- `references/action-fields.md` — `outputSchema`, `authorize`, `needsApproval`, `_agentImages`, and exact auto-refresh rules. +- `references/examples.md` — a second worked example and legacy bare-export patterns. + +## Related Skills + +- **storing-data** — Actions read/write data in SQL +- **delegate-to-agent** — The agent invokes actions via `pnpm action ` +- **real-time-sync** — Database writes from actions trigger change events to update the UI +- **adding-a-feature** — Actions are area 2 of the four-area checklist +- **client-methods** — Client code uses named helpers/hooks instead of raw REST calls diff --git a/.agents/skills/actions/references/action-fields.md b/.agents/skills/actions/references/action-fields.md new file mode 100644 index 0000000..de7d257 --- /dev/null +++ b/.agents/skills/actions/references/action-fields.md @@ -0,0 +1,145 @@ +# Action Field Reference + +Full detail on the less-common `defineAction` fields and automatic behaviors. +Read this when you need output validation, authorization, human approval, +image results, or the exact rules for the auto-refresh behavior — the happy +path in SKILL.md doesn't need any of these. + +## Screen Refresh (automatic) + +The framework auto-refreshes the UI after any successful mutating action. On completion of a non-`GET` action, the framework emits a change event with `source: "action"` that the client's `useDbSync` picks up and uses to invalidate `["action"]` React Query keys — so `list-*` / `get-*` hooks refetch without a full page reload. In-process calls emit directly; dev-mode `pnpm action ...` calls also write a durable marker so the web server sees child-process action changes. + +Rules: + +- `http: { method: "GET" }` → read-only, does NOT trigger a refresh (inferred automatically). +- Any other action (default `POST`, `PUT`, `DELETE`, or `http: false`) → treated as mutating, triggers a refresh on success. +- To override the inference on an unusual action (e.g. a `POST` that only reads), pass `readOnly: true` on the action definition. +- To let a mutating action run concurrently with other same-turn tool calls, pass `parallelSafe: true`. Only do this when the action is internally concurrency-safe and order-independent (for example, it uses an app-level lock or idempotent upsert semantics). Mutating actions remain serialized by default. +- If a successful call hands control to the user — it renders a question, an intake form, or anything else the turn must wait on — pass `endsTurn: true` and make it the first or only call in the turn. It stops subsequent model steps and later calls, but cannot undo calls emitted before it. Without it a completion guard sees a turn that legitimately paused as one that failed to finish. `endsTurn: true` also hides the action from MCP, WebMCP, and A2A callers by default (`isActionExposedToExternalAgents` in core `action.ts`) — an external host has no in-app chat to receive the answer on. Pass `mcpTool: true` alongside it only when an external caller can complete the same operation without that answer. +- Read results persist in the browser per signed-in user and org, so a revisit paints the last result before it refetches. Pass `persistInBrowser: false` on a read that must not outlive the page (secrets, one-time codes, another user's private data). Mutations never persist. +- MCP hosts read tool annotations to decide how carefully to treat a call. Every MCP catalog advertises declared `mcpAnnotations` (`readOnlyHint`, `destructiveHint`, `openWorldHint`, optional `idempotentHint`); otherwise `/mcp` derives only `readOnlyHint` and an approval-based `destructiveHint`. Declare them on every action MCP advertises that is not read-only, with `destructiveHint: true` when it removes, overwrites, or replaces user content — recoverable Trash included — and mark idempotency-key-guarded writes `idempotentHint: true`. A contract test fails on a new undeclared write. + +Agents do NOT need to call `refresh-screen` after a normal action — it's already handled. `refresh-screen` is only needed when the agent mutates data via a path the framework can't see (e.g. writing to an external system the app mirrors) or when the agent wants to pass a `scope` hint for narrower invalidation. + +## Returning Images the Agent Can See (`_agentImages`) + +An action's return object may include the well-known optional field +`_agentImages` to attach vision images (screenshots, chart previews, rendered +designs) to the tool result. The agent literally sees them — enabling visual +self-review loops — while the field itself is stripped from the JSON text the +model reads. + +```ts +run: async ({ dashboardId }) => { + const shot = await renderDashboardPng(dashboardId); // Buffer + return { + dashboardId, + panelCount: 6, + _agentImages: [ + // Either a public https URL (preferred — the provider fetches it)… + { url: "https://cdn.example.com/previews/dash-1.png", label: "overview" }, + // …or base64 without a data: prefix (mediaType required; a full + // data:image/png;base64,… URL in `data` is also accepted and parsed). + { data: shot.toString("base64"), mediaType: "image/png" }, + ], + }; +}, +``` + +Rules and limits: + +- Shape: `Array<{ url?: string; data?: string; mediaType?: string; label?: string }>`. + Each entry needs `url` (https only) **or** `data`. Supported media types: + `image/jpeg`, `image/png`, `image/gif`, `image/webp`. +- Caps: max **4 images** per result; max **~2MB of base64** per image. + Over-cap or invalid entries never fail the call — they become text notes in + the result telling the model what was dropped and why. +- Persistence: the run ledger stores only the string result plus compact + `[image: …]` notes (URLs verbatim; base64 as a byte-count placeholder) — + never the payload. Images are re-attached only for the live turn; replayed + history is text-only, so prefer stable `url` images the model can re-request. +- Engine support: native Anthropic and vision-capable AI-SDK providers + (anthropic, openai, google, openrouter) receive real image blocks; other + paths (Builder gateway, non-vision providers) degrade to the text notes. +- External MCP tools need no changes — standard MCP `image` content parts are + converted automatically under the same caps. + +## Validating Return Values (`outputSchema`) + +`schema` validates inputs; `outputSchema` validates what the action **returns**. Pass any Standard Schema-compatible schema (Zod, Valibot, ArkType) and the framework validates the result _after_ `run()` resolves — input validated before `run`, output after. + +```ts +export default defineAction({ + description: "Summarize a thread.", + schema: z.object({ threadId: z.string() }), + outputSchema: z.object({ summary: z.string(), messageCount: z.number() }), + outputErrorStrategy: "warn", // default; "strict" | "fallback" + // outputFallback: { summary: "", messageCount: 0 }, // used only by "fallback" + run: async ({ threadId }) => { + /* ... */ + }, +}); +``` + +- `"warn"` (default) — `console.warn` the issues and return the **original** result unchanged. Non-breaking, with one exception: a connection request or stop signal thrown while the result is checked (from a transform or refinement) still ends the call as that signal, with a framework message in place of its own. +- `"strict"` — throw `ActionOutputContractError` (`errorCode: "output_contract_violation"`) so a buggy action surfaces loudly. +- `"fallback"` — return `outputFallback` in place of the invalid result. + +On success the validated value is returned, so coercion/defaults on `outputSchema` apply. Omit `outputSchema` and behavior is byte-for-byte unchanged (no wrapping). + +The strict error and such a signal run after `run()`, so they carry `effect`: `"committed"` once a write entered its handler, in the call or in one nested in it (even under a read-only action), and `"none"` otherwise. Writes are classified from the validated arguments, defaults applied. The agent loop, the plan-mode registry, HTTP action routes, and MCP prepare each call once (validated arguments plus that classification) and run exactly that preparation: approval, plan mode, write blocking, batching, and replay all read it, and the run does not parse the arguments again. Preparation reads the validated arguments once into a frozen, plain-data snapshot and hashes it; each gate and `run()` gets its own copy of that snapshot, never the snapshot itself, so mutating `args` in a gate or a handler changes nothing anyone else reads. Validated arguments must therefore be plain data: objects, arrays, strings, numbers, booleans, `null`, `undefined`, BigInts, and valid Dates. A schema whose output holds anything else (a getter or setter, a `Map` or `Set`, a class instance, a function) makes every call fail as invalid. Preparation, its refusals and the per-consumer copies cover calls the agent loop, plan mode, HTTP action routes, and MCP dispatch; a direct `action.run()` (one action composing another, the dev action bridge) gets schema validation only. A call whose arguments are invalid fails before any of them and never reaches the handler. Every reuse of a call's outcome keys on the snapshot's hash, never on the raw input: a continued turn replays a call only when it recorded a committed effect for the same hash, reads are reused only for the same hash, and an interrupted write recovers only a result recorded for the same hash, otherwise it stops instead of running again. The message names only declared field paths and issue codes, never output values, and tells the caller not to retry a committed write. A connection request keeps its `provider`, `reason`, `appId`, and `source` in its fields, in its message, and in HTTP `details`. + +MCP clients see no `outputSchema` by default. Set `mcpOutputSchema: true` (requires `outputErrorStrategy: "strict"`) only after auditing that every real result matches: the tool then advertises the schema as MCP sees it (an array root becomes `{ items }`, linked actions gain `openLink`/`url`), and each `structuredContent` is validated against it before it is returned. Roots must be an object, an object-only union, or an array, and schemas with transforms cannot opt in. The advertised schema allows for MCP's redaction (embed ticket fields dropped; a string holding an embed start URL arrives as `"[hidden embed URL]"`, so required fields stay required). A schema is refused at definition time if it uses a keyword or `format` the check cannot enforce (`not`, `$async`, an unknown format), if redaction could break its `const`, `enum`, or `uniqueItems`, or if a linked action's root limits its property names or count. + +## Authorization (`authorize`) + +`authorize` decides whether the caller may run the action at all. It wraps +`run`, so it holds at **all six dispatch sites** — agent tool, HTTP, frontend +hook, MCP, A2A, CLI. Use `authorize` for "not everyone may do this"; use +`needsApproval` to ask a human to bless one call a permitted caller is already +allowed to make. + +```ts +import { coachAccess } from "../lib/access.js"; // defineAppRoles(...) + +export default defineAction({ + description: "Archive a client roster.", + schema: z.object({ id: z.string() }), + authorize: coachAccess.requireAny("coach-admin"), + run: async (args) => { + /* ... */ + }, +}); +``` + +The wrappers compose as `validate input -> authorize -> run -> validate output +-> audit`: the gate sits inside input validation, so a guard reading `args` gets +the parsed, coerced value, and auditing is outermost, so denials are recorded. + +A guard that throws denies with its own message; returning `false` denies +generically; anything else (including `undefined`) allows. A guarded action +needs a user identity, so an unattended CLI/cron caller with no user email is +denied. `authorize` gates the operation; `accessFilter` / `assertAccess` still +scope which rows a permitted caller may touch. Use `agent-native-docs` to find +the current authentication and sharing documentation when adding role checks. + +## Human-in-the-Loop Approval (`needsApproval`) + +For high-consequence, outward-facing, hard-to-undo actions (sending an email, charging a card, deleting an account), set `needsApproval` so the agent **cannot** run the action without a human approving the specific call: + +```ts +export default defineAction({ + description: "Send an email via Gmail.", + schema: z.object({ to: z.string(), subject: z.string(), body: z.string() }), + needsApproval: true, // boolean, or (args, ctx) => boolean | Promise + run: async (args) => { + /* ...actually send... */ + }, +}); +``` + +When the gate is truthy and the call isn't yet approved, the loop emits an `approval_required` event and **stops the turn — `run()` never executes**. A predicate gates conditionally (e.g. only external recipients) and **fails closed**: a throw is treated as "approval required". It receives its own copy of the prepared snapshot of the validated arguments, defaults applied, and the approval binds to the snapshot's hash, so an approved call runs only with the arguments that were approved (a Date binds by its time). The human approves via the chat UI's Approve affordance, which re-issues the turn with the call's `approvalKey`, and only then does the action run. + +Approval is given in the app, so HTTP never grants it. The HTTP action route and the generated Workers entry run a gated call only for the proven app UI (a frontend call from the signed-in user, same origin, holding the short-lived UI capability; `isProvenUiRequest`, the proof `uiOnly` uses) or the app's MCP directory widget. Every other direct HTTP caller (bearer or API key, MCP OAuth token, org service token, extension iframe, or mobile app) gets `409 approval_required`, and a service identity can never approve. A2A tasks use their separate approval flow. The task pauses until its owner approves, then replays the approved tool call under its approval lease. The shared client presents the capability with every write from a signed-in session (minted once per user, reused for nine minutes, never for reads or public pages), so a gated button works on its first request. A call without proof gets `403 ui_capability_required`; the client then re-mints and retries once, which is only the fallback for an expired or rejected capability. The agent loop, plan mode registry, HTTP action route, generated Workers entry, and MCP dispatch evaluate the gate through `preparedCallNeedsApproval`, so a throwing predicate asks there too. The local `pnpm action ...` CLI calls `handler.run()` directly and does not evaluate `needsApproval`. Treat it as a local development tool, not an approval boundary. A caller that must run unattended needs a different action, never a bypass of the gate. + +**Keep approvals rare** — the default is off and almost every action should leave it off. The canonical example is Mail's `send-email` (`needsApproval: true`). See the `security` skill and the Human Approval doc. diff --git a/.agents/skills/actions/references/examples.md b/.agents/skills/actions/references/examples.md new file mode 100644 index 0000000..48a32ec --- /dev/null +++ b/.agents/skills/actions/references/examples.md @@ -0,0 +1,96 @@ +# Extra Action Examples and Compatibility Patterns + +Read this for a second worked example beyond the one in SKILL.md, for the +legacy `parameters` form or CLI-only bare-export action you may find in +existing code. + +## Common Patterns + +**Read action (GET):** + +```ts +import { z } from "zod"; +import { defineAction } from "@agent-native/core/action"; + +export default defineAction({ + description: "List calendar events", + schema: z.object({ + from: z.string().describe("Start date"), + to: z.string().describe("End date"), + }), + http: { method: "GET" }, + run: async (args) => { + return await fetchEvents(args.from, args.to); + }, +}); +``` + +**Write action (POST, default):** + +```ts +import { z } from "zod"; +import { defineAction } from "@agent-native/core/action"; + +export default defineAction({ + description: "Log a meal", + schema: z.object({ + name: z.string().describe("Meal name"), + calories: z.coerce.number().describe("Calorie count"), + }), + run: async (args) => { + // args.calories is a number — z.coerce.number() handles string-to-number conversion from HTTP + const meal = await insertMeal(args); + return meal; + }, +}); +``` + +**Agent-only action:** + +```ts +import { z } from "zod"; +import { defineAction, fail } from "@agent-native/core/action"; +import { writeAppStateForCurrentTab } from "@agent-native/core/application-state"; + +export default defineAction({ + description: "Navigate the UI to a view or path", + schema: z.object({ + view: z.string().optional().describe("Target view"), + path: z.string().optional().describe("URL path to navigate to"), + }), + http: false, + run: async (args) => { + if (!args.view && !args.path) { + fail("At least --view or --path is required.", { + errorCode: "invalid_navigation", + }); + } + const navigation: Record = {}; + if (args.view) navigation.view = args.view; + if (args.path) navigation.path = args.path; + navigation._writeId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + await writeAppStateForCurrentTab("navigate", navigation); + return { message: `Navigating to ${args.view || args.path}` }; + }, +}); +``` + +## Legacy `parameters` Field + +The older `defineAction` form accepts a JSON Schema object through `parameters`. It still supplies the agent's input schema and infers TypeScript args for supported parameter shapes, but does not provide the Standard Schema validation and transforms of `schema`. Prefer `schema: z.object({...})` for new actions and when updating existing ones. + +## Legacy Pattern (bare export) + +Older actions use a bare async function export with `parseArgs`: + +```ts +import { parseArgs, loadEnv, fail } from "@agent-native/core"; + +export default async function myAction(args: string[]) { + loadEnv(); + const parsed = parseArgs(args); + // ... +} +``` + +The CLI runner still accepts this function form, but it is CLI-only: it is not registered as an agent tool, does not mount an HTTP endpoint, and has no typed frontend hook. Prefer `defineAction` for actions shared with the agent or UI. See `actions-advanced` for this legacy form and its helpers. diff --git a/.agents/skills/actions/references/provider-apis.md b/.agents/skills/actions/references/provider-apis.md new file mode 100644 index 0000000..83857e5 --- /dev/null +++ b/.agents/skills/actions/references/provider-apis.md @@ -0,0 +1,95 @@ +# Provider API Integrations + +Read this when an action needs to call an external provider API — HubSpot, +Gong, Slack, any credentialed third-party service — for ad hoc analysis, +querying, reporting, or cross-source research. + +For provider integrations used in ad hoc analysis, querying, reporting, or +cross-source research, do not hardcode every provider endpoint as a separate +rigid action and do not encode one lookback window, filter shape, or pagination +strategy as the only path the agent can take. Expose the shared provider API +action trio instead: + +- `provider-api-catalog`: lists provider base URLs, auth style, credential keys, + docs/spec URLs, placeholders, and examples without exposing secrets. +- `provider-api-docs`: fetches public provider docs/spec/changelog URLs when + the exact endpoint, filter operator, payload shape, or pagination contract is + uncertain. Registered docs URLs are curated starting points. Use + `responseMode: "markdown"` for clean readable docs, or + `responseMode: "matches"` with `search: { query | terms | regex }` for + compact snippets instead of flooding context with raw HTML. +- `provider-api-request`: makes a constrained authenticated HTTP request to the + provider host, injects configured credentials, blocks private/internal URLs, + and redacts secrets. + +Use `@agent-native/core/provider-api` as the shared substrate, and build these +actions as thin factory imports rather than copying `defineAction` schemas and +handlers into each template: + +```ts +import { + createProviderApiCatalogAction, + createProviderApiDocsAction, + createProviderApiRequestAction, +} from "@agent-native/core/provider-api/actions/provider-api"; +import { + createDeleteStagedDatasetAction, + createListStagedDatasetsAction, + createQueryStagedDatasetAction, +} from "@agent-native/core/provider-api/actions/staged-datasets"; +``` + +Pass the app's existing provider runtime to the provider factories, and pass +its app id to the staged-dataset factories. Keep app-specific descriptions, +provider allow-lists, HTTP/tool-callability settings, and credential adapters +as factory options. Only add a thin credential adapter when the app has +app-specific credential lookup rules. If the app stores a built-in provider's +OAuth grant under a narrower local provider id, use the runtime's +`oauthProviderOverrides` instead of duplicating provider config. If credentials +are stored on shareable/resource rows rather than in the shared credential or +OAuth-token stores, build a resolver that enforces those access checks before +exposing raw provider requests. Keep `provider-api-request` `http: false` +unless a separate UI permission model authorizes arbitrary provider writes. +Specific actions such as `search-records`, `search-emails`, or `sync-source` +are convenience shortcuts, not capability limits; agents should fall back to +the provider API trio when a question requires an endpoint or filter that the +shortcut does not model. + +This is a framework tenet. The safety boundary should be provider host +allow-listing, credential scoping, auth injection, private-network blocking, +secret redaction, and user/org access checks, not an artificially small set of +hand-authored read actions. If the upstream provider API supports a capability, +the agent should normally be able to reach it through `provider-api-request` +with the user's configured credentials. For large responses, expose staging +(`stageAs`, `itemsPath`, pagination, and `query-staged-dataset`) or sandboxed +code execution so the agent can reduce data without flooding context. + +For broad provider questions, cross-source joins, corpus-wide mention/search +work, classification, or any answer where absence matters, design the action +surface for full coverage instead of convenience-only samples. The agent should +be able to fetch every relevant page or an explicitly bounded cohort, stage or +save the raw provider response outside chat, and then use +`query-staged-dataset`, `run-code`, or provider-side search to count, join, +grep, classify, and aggregate. Tool descriptions and AGENTS.md guidance should +teach agents to report source, filters, time window, row/record counts, +pagination status, truncation, failed pages, and uncovered gaps. They must not +turn default limits, sampled rows, truncated excerpts, or aborted calls into a +confident "none found", "all records", or exhaustive conclusion. + +For public web pages and docs, prefer the token-efficient path: `web-search` +to find likely URLs, `web-request` or `provider-api-docs` with clean +`responseMode` output to read a page, and `run-code` with `webRead()` / +`webFetch()` when you need to grep, aggregate, or compare many pages before +returning a small result. + +For LONG compute, `run-code` supports durable background executions: pass +`background: true` and the code is enqueued to a `sandbox_executions` row and +executed out-of-band with a generous budget (default 10 min), surviving the +hosted agent run's ~40s soft timeout. The call returns +`{ executionId, status: "queued" }` immediately with polling guidance; check +progress with `run-code` `{ executionId }` (or the `get-code-execution` tool +where registered) — results persist after completion. Use background for big +cross-source joins, multi-page provider sweeps, and heavy analysis scripts; +keep quick scripts in the default foreground mode. Agents should continue +other work between polls, and on `failed`/`timed_out` split the computation or +persist intermediate progress with `workspaceWrite` and re-run. diff --git a/.agents/skills/adding-a-feature/SKILL.md b/.agents/skills/adding-a-feature/SKILL.md new file mode 100644 index 0000000..36d6c58 --- /dev/null +++ b/.agents/skills/adding-a-feature/SKILL.md @@ -0,0 +1,236 @@ +--- +name: adding-a-feature +description: >- + The four-area checklist every new feature must complete. Use when adding any + feature, integration, or capability to ensure the agent and UI stay in parity. +scope: dev +metadata: + internal: true +--- + +# Adding a Feature — The Four-Area Checklist + +## Rule + +Every new feature MUST update all four areas. Skipping any one breaks the agent-native contract — the agent and UI must always be equal partners. + +Scope check first: this is the checklist for a feature that adds app data or a new capability. A restyle, a copy change, or a screen with no new data model and no new agent-visible operation only needs the areas it actually touches — do not manufacture actions, state keys, or a skill for it. + +## Why + +Agent-Native apps are defined by parity: everything the UI can do, the agent can do, and vice versa. A feature that only has UI is invisible to the agent. A feature that only has scripts is invisible to the user. A feature without app-state sync means the agent is blind to what the user is doing. + +## The Checklist + +When you add a new feature, work through these four areas in order: + +### 1. UI Component + +Build the user-facing interface — a page, component, dialog, or route. Use `useActionQuery` and `useActionMutation` from `@agent-native/core/client/hooks` to call actions for data fetching and mutations. Do not create a custom REST endpoint just so React can call action-backed data; the action endpoint already exists. + +**Agent edits must refresh the UI without a background poll.** Local chat-run +tool completions invalidate action queries and source counters after each +side-effecting tool and again at run end. There are two query paths: + +- **`useActionQuery` / `useActionMutation`** — local action mutations invalidate `['action']` observers, and chat-run tool completions invalidate them for agent writes. No background sync opt-in is needed for the current user's agent run. **Prefer this path.** +- **Raw `useQuery` with custom keys** — fold `useChangeVersions([, "action"])` from `@agent-native/core/client/hooks` into the `queryKey` and set `placeholderData: (prev) => prev`. Local chat-run side effects bump those counters too. Remote changes require the page's explicit `useDbSync({ realtime: { reason } })` opt-in only when data changes without the current user acting and must appear before refresh. + +Never opt in public, anonymous, marketing, docs, or SSR routes, settings, +forms, or read-mostly lists. Refetch those on focus or navigation. Shared Slides +editing and the Mail inbox are the current first-party examples that need +remote updates. Each opted-in open tab adds a shared background transport and +one poll per idle interval; hidden tabs pause, and idle polling backs off to 1, +2, then 5 minutes. See `real-time-sync` for the decision rule and examples. + + ```tsx + import { useChangeVersions } from "@agent-native/core/client/hooks"; + import { useQuery } from "@tanstack/react-query"; + + const v = useChangeVersions(["dashboards", "action"]); + useQuery({ + queryKey: ["dashboard", id, v], + queryFn: () => fetchDashboard(id), + placeholderData: (prev) => prev, // no flicker on refetch + }); + ``` + + See the `real-time-sync` skill for the full pattern and source catalog. + +### 2. Action + +Create an action in `actions/` using `defineAction`. This serves double duty: the agent calls it as a tool, and the UI calls it through `useActionQuery` / `useActionMutation` while the framework owns the HTTP transport. Set `http: { method: "GET" }` for read actions, leave default for writes, or set `http: false` for agent-only actions like `navigate` and `view-screen`. + +Before adding a new route or endpoint, inspect the existing actions. Reuse an +action if it already covers the business operation, extend it if the shared +contract is incomplete, or create a new `defineAction` if the agent and UI both +need the capability. Do not add pass-through `/api/*` routes that re-export +actions. If client code needs a new framework/app route, expose a named helper +or hook first and use that helper from components and docs. + +For provider-backed analysis/query/reporting integrations, do not turn every +provider endpoint or filter into a rigid action. Prefer the shared +`provider-api-catalog` / `provider-api-docs` / `provider-api-request` pattern +from `@agent-native/core/provider-api`, then add narrow convenience actions only +for workflows that truly deserve a first-class shortcut. Treat this as a +capability requirement, not a nice-to-have: convenience actions must not become +the ceiling of what the agent can ask the provider to do. Pair broad provider +access with staging or sandboxed code execution when responses may be too large +for chat context. If provider credentials live on resource/share rows, add the +scoped resolver first so broad access preserves the same ownership boundary as +the app UI. + +If the feature needs credentials, design the credential path in the same change. +Never hardcode credentials or include personal or customer data in source, +fixtures, docs, prompts, or generated app content. Register required secrets, +use OAuth helpers, or read scoped values from the credential store. + +Before writing custom setup or credential UI, perform the shared-primitive +preflight from `agent-native-toolkit`: inspect the workspace/provider connection +catalog first, then settings, secrets/vault, OAuth, onboarding, and provider API +support. Reuse an existing connection's app grant and scoped credential +resolver; only use app-local vault or OAuth primitives when no reusable +connection exists. Keep any wizard thin and provider-specific - it may explain +prerequisites, ordering, or readiness, but must not become a second vault or +custom credential transport. Do not mark each field `required` by reflex; +model onboarding around the logical connection outcome. + +If the feature involves attachments, images, recordings, screenshots, exports, +or other file-like payloads, design the upload path in the same change: +provider upload first, then URL/id/blob handle in SQL. Do not add base64/binary +columns or stuff files into `application_state`. + +If the feature adds a heavy server-side dependency, read the startup guidance in +`performance` before adding it. Keep expensive setup and processing out of +request-startup paths; use a background job when the work does not need to block +the current request. + +**If the action produces or lists a navigable resource**, add a `link` builder that returns `{ url: buildDeepLink({ app, view, params }), label }`. MCP hosts can surface a deep link that returns the user to the running app at that record. If a compatible host should render an inline review or edit surface, also add `mcpApp` with `embedApp()` so the action embeds the real app route. Keep `link` and `mcpApp` metadata pure and synchronous. Use the external-agent documentation when exposing actions to other agent hosts. + +Scaffolding a new app of a known type (slides, design, content, forms)? Start from that template's `AGENTS.md` and `.agents/skills/`, not a blank app. + +### 3. Skills / Instructions + +Update `AGENTS.md` and/or create a skill in `.agents/skills/` if the feature introduces patterns the agent needs to know. At minimum, add the new actions to the action table in the template's `AGENTS.md`. + +Before completing this area, identify the feature's primary actions: + +- Document primary workflows in the `AGENTS.md` action table. +- If the app configures `initialToolNames` (`INITIAL_TOOL_NAMES` in some + templates), add the primary actions there. If it uses per-action loading, + mark the complete starter set `deferLoading: false`; once one action opts in, + unmarked actions are deferred. The remaining actions stay discoverable through + `tool-search`. +- If `mcp.keyToolNames` is configured, align it with primary actions actually + served on MCP/WebMCP. It controls the external key-tools list and does not + change the in-app agent's first-turn list. + +Reusable actions are part of the app contract, not just implementation detail. When an action is useful outside one screen, update agent instructions in the same change so app agents know when to call it, which arguments matter, and what output to preserve. If the capability is workflow-heavy, cross-app, provider-backed, or has a non-obvious sequence of actions, add or update a skill instead of burying the behavior in one long `AGENTS.md` paragraph. + +- For chat prompt dispatch, put the readiness gate at the shared dispatch boundary and cover submits, retries, edits/forks, queue drains, continuations, and imperative sends. Dispatch only after readiness is authoritatively configured; return a typed setup-required error and preserve the draft when readiness is missing or unavailable. Composer checks and setup cards are UX, not enforcement, and no new `...ChecksEnabled={false}` bypass is allowed. + +Instruction examples may name secret keys like `SLACK_WEBHOOK`, but must use +placeholders such as `${keys.SLACK_WEBHOOK}` or ``. Do not paste +real keys, internal data, or customer data into instructions as examples. + +If the feature adds or changes visible UI copy, prompts, toasts, labels, empty +states, or formatting, edit the English strings inline in components. Do **not** +add i18n catalogs unless the user explicitly asks for localization; only then +read the `internationalization` skill. + +For app-backed skills, declare skill visibility in the app-skill manifest: + +- `internal` — only the app's own agents should use it. +- `exported` — marketplace installs receive it, but the app does not need it loaded internally. +- `both` — shared between the app's internal agents and exported marketplace bundles. + +### 4. Application State Sync + +Expose navigation and selection state so the agent knows what the user is looking at. Write to the `navigation` app-state key on route changes. Update the `view-screen` action to fetch relevant data for the new feature. Add a `navigate` command if the agent needs to open the new view. Text resources participate in `export-resource-pack`; binaries and secrets do not. + +## Examples + +### Adding "compose email" to a mail app + +| Area | What to build | +| --- | --- | +| UI | Compose panel with tabs, to/cc/bcc fields, body editor. Use `useActionQuery`/`useActionMutation` for data. | +| Action | `manage-draft` action (create/update/delete drafts), `send-email` action | +| Skills/AGENTS | Document compose state shape, draft lifecycle, action args in AGENTS.md | +| App-state sync | `compose-{id}` keys for each draft tab, `navigation` includes compose state | + +### Adding "create form" to a forms app + +| Area | What to build | +| --- | --- | +| UI | Form builder page with drag-and-drop fields, preview, settings. Use `useActionQuery` for lists. | +| Action | `create-form` action, `update-form` action, `list-forms` action (GET) | +| Skills/AGENTS | Document form schema shape, field types, validation rules in AGENTS.md | +| App-state sync | `navigation` includes `{ view: "form-builder", formId: "..." }`, `view-screen` fetches form data | + +### Adding "chart type" to an analytics app + +| Area | What to build | +| --- | --- | +| UI | New chart component, chart type selector in dashboard | +| Action | `create-chart` or `update-dashboard` action that sets chart type and config | +| Skills/AGENTS | Document supported chart types, config options, data requirements | +| App-state sync | `navigation` includes selected chart/dashboard, `view-screen` returns chart config | + +## Adding a new route + +Templates are single-page apps with client-side routing. The app shell (AgentSidebar + top-level nav) MUST persist across navigation — it is mounted once, either in `root.tsx` around `` or via a pathless `_app.tsx` layout route that all authed routes nest under. + +**Never wrap each new route in its own `` / ``.** That causes React to unmount the entire app shell on every navigation, reloading the agent sidebar and destroying in-progress work. + +- If the template has `` in `root.tsx` — just render page content in your new route file, nothing else. +- If the template has `app/routes/_app.tsx` (pathless layout) — name your new route `_app..tsx` to inherit the shell, or bare `.tsx` for public routes that should NOT have the shell. +- If a page needs per-route data (e.g. highlighting the active item in the sidebar), read it in the layout from `useParams()` / `useLocation()`. Don't pass it as a prop through every route file. + +See the "Client-Side Routing" section in the root `CLAUDE.md` for full details. + +## Anti-Patterns + +- **Per-route `` wrappers** — Every route file wraps its content in `` or ``. React sees a different component at the outlet on each nav and unmounts the whole shell, causing the agent sidebar to reload on every click. Mount the shell once above `` (root.tsx or `_app.tsx` pathless layout). +- **UI without actions** — The user can create forms but the agent cannot. The agent says "I don't have access to that" when it should be able to do it. +- **Actions without AGENTS.md** — The actions exist but the agent doesn't know about them because they're not documented. The agent reinvents solutions instead of using the actions. +- **Duplicate API routes** — Creating `/api/` routes for operations that actions already handle, including pass-through routes that just call or repackage an action. Use `useActionQuery`/`useActionMutation` instead. +- **Raw client route calls** — Teaching or adding `fetch("/_agent-native/...")`, + `fetch(agentNativePath(...))`, or template `/api/*` calls in components for + normal app work. Add a named client helper/hook and call that instead. +- **Features without app-state** — The agent cannot see that the user is looking at a specific form, email, or chart. It asks "which one?" instead of acting on the current selection. +- **Actions without UI** — The agent can do something the user cannot. This is less common but still breaks parity. + +## Verification + +After completing all four areas, verify: + +1. Can the user perform the operation from the UI? +2. Can the agent perform the same operation via actions? +3. Does `pnpm action view-screen` show the relevant state when the user is using the feature? +4. Can the agent navigate to the feature view via the `navigate` action? +5. Is the feature documented in AGENTS.md with action names and args? +6. Are credentials supplied through approved runtime channels, with no + hardcoded keys, tokens, or user data? + +## One more area — sharing + +If the feature stores **user-authored resources** (documents, dashboards, forms, decks, etc.), make them ownable so they get private-by-default semantics and a share dialog for free. See the `sharing` skill. + +TL;DR: spread `ownableColumns()` into the resource table, pair it with `createSharesTable(...)`, call `registerShareableResource(...)`, wrap list/read queries with `accessFilter`, guard writes with `assertAccess`, and drop `` in the resource header. The `share-resource`, `unshare-resource`, `list-resource-shares`, and `set-resource-visibility` actions are auto-mounted framework-wide. + +## One more area — who inside the app may do it + +If only some teammates may perform a feature (such as an admin-only import), use a per-app role rather than creating an organization or using a share grant. Use `agent-native-docs` to find the current role guide if needed. + +TL;DR: declare the vocabulary once with `defineAppRoles({ appId, roles, defaultRole })`, guard the action with `authorize: appAccess.requireAny("...")`, and render the picker with ``. `defaultRole` is display only — it never satisfies a guard — and `authorize` gates the operation while `accessFilter` / `assertAccess` still scope the rows. + +## Related Skills + +- **sharing** — How to make a new resource ownable (private by default, share with users/orgs/public) +- **context-awareness** — How to expose UI state to the agent (area 4 in detail) +- **actions** — How to create actions with `defineAction` and the `http` option (area 2 in detail) +- **build-an-app** — Start a complete app from a vague domain prompt +- **storing-data** — Where to store the feature's data +- **real-time-sync** — How the UI stays in sync when the agent writes data +- **performance** — Query/load cost and expensive startup work +- **agent-native-docs** — Find current docs for roles, external agents, or localization diff --git a/.agents/skills/agent-engines/SKILL.md b/.agents/skills/agent-engines/SKILL.md new file mode 100644 index 0000000..f76e468 --- /dev/null +++ b/.agents/skills/agent-engines/SKILL.md @@ -0,0 +1,232 @@ +--- +name: agent-engines +description: >- + How to inspect and configure the AI engine (model provider) powering the + agent. Use when the user asks to switch models, check which engine is active, + test a new provider, or register a custom engine. +--- + +# Agent Engines + +## Overview + +The framework supports pluggable AI engines beneath the agent loop. The **Anthropic engine** is the default and best-in-class path (Claude models). Additional engines can be added via the Vercel AI SDK (OpenAI, Google Gemini, Groq, Mistral, Cohere, Ollama). + +## Available Tools + +| Tool | Purpose | +|---|---| +| `list-agent-engines` | List all registered engines, their capabilities, the current selection, and whether you can change the organization default (`canUpdateDefault`) | +| `set-agent-engine` | Set the organization's default engine and model (owners and admins only) | +| `test-agent-engine` | Send a trivial prompt to verify the engine works (connectivity + API key) | +| `check-provider-key` | Check a provider API key by listing the models it reaches, before saving it | +| `get-provider-models` | Read which models each provider shows in the model picker and default-model select | +| `manage-provider-models` | Choose those models (`set`) or go back to the recommended ones (`reset`) | +| `list-model-providers` | What Settings › Model shows: each provider's organization and personal key (masked), rejections, the restriction, and the stored default | + +## Checking the Current Engine + +``` +list-agent-engines +``` + +Returns the registry of all engines (name, label, capabilities, supported models) plus the currently active engine and model. `supportedModels` is what the model picker offers: the provider's checked models when `modelSelection.state` is `"selected"`, otherwise its `recommendedModels`. `credentialRejected: true` means the provider rejected that engine's saved key (`credentialRejectedAt` says when); chats with it stop until the key is replaced, so tell the user. + +## Switching Engines + +``` +set-agent-engine --engine "ai-sdk:openai" --model "gpt-4o" +``` + +Changes take effect on the next conversation. The default belongs to the organization (the `agent-engine` org setting), and only owners and admins can change it. A member's call is refused with an error to relay: ask an owner or admin, or pick a model for this chat in the model picker. A user with no organization sets their own default. + +Resolution order (highest priority first): +1. Explicit `engine` option passed to `createAgentChatPlugin()` in the server plugin +2. The organization's default (`agent-engine` org setting) +3. `AGENT_ENGINE` environment variable +4. Default: `"anthropic"` (requires `ANTHROPIC_API_KEY`) + +## Settings › Model + +The Model page (`/settings/model`, page id `model`) has three groups: + +- **Organization providers:** the organization's Builder.io connection and each organization key. Owners and admins manage them; members see only "N models". +- **Personal providers:** a member's own Builder.io connection, their own keys, and the ChatGPT subscription while its lab is on. A personal key is used before the organization's, for that person only. +- **Organization settings:** Default model (`manage-agent-engine` `set`, organization models only), Restrict personal API keys (`manage-provider-key-policy`), and Max iterations (`manage-agent-loop-settings`, 1 to 1000). Owners and admins change them; members see the values. + +Read the page's state with `list-model-providers`, and the models each provider shows with `get-provider-models`. Keys are added and replaced in the provider dialog, which checks a pasted key by listing its models; you can't save a key for the user, so check one with `check-provider-key` and send them to Model (`open-settings-page`) to paste it. Before they remove a provider, run `preview-secret-removal` with the provider's key name and scope and tell them what stops. + +## Restricting Personal API Keys + +`manage-provider-key-policy` reads or changes the organization's "Restrict personal API keys" setting. While it is on, members (not owners or admins) can't use or save their own provider keys or a personal Builder.io connection, so their chats use organization providers; with none, a chat fails with "Owners and admins restricted personal API keys." Nothing is deleted, and turning it off restores their keys. + +``` +manage-provider-key-policy # read; owners/admins also get affectedMembers +manage-provider-key-policy --set true # owners and admins only +``` + +Read it first and tell the user which members lose which providers before turning it on. + +## Testing a New Engine + +Before switching, verify the engine is working: + +``` +test-agent-engine --engine "ai-sdk:openai" --model "gpt-4o" +``` + +Returns `{ ok, latencyMs, response, capabilities }`. If `ok: false`, the error message explains what's wrong (missing API key, package not installed, etc.). + +To check a key without sending a prompt, for example one the user just gave you: + +``` +check-provider-key --provider "anthropic" --key "" +``` + +Returns `{ ok: true, models }` or `{ ok: false, code, reason }` (`rejected`, `wrong-provider`, `missing-key`, `invalid-endpoint`, `unreachable`, `provider-error`). Relay the reason. Omit `--key` to re-check the saved key; it is only checked against its saved endpoint, so `--baseUrl` needs `--key` (except for Ollama). `--scope org` is for owners and admins. + +## Choosing Which Models Show + +Each provider (Builder.io included) keeps the models its owner checked. Only checked models appear in the chat model picker and the default-model select; Builder.io and providers with their own key show side by side. + +``` +get-provider-models --provider "openai" +manage-provider-models --action "set" --provider "openai" --models '["gpt-6-sol"]' +manage-provider-models --action "reset" --provider "openai" +``` + +- A selection lives at the same scope as the provider's key: `--scope user` is the caller's own, `--scope org` is the organization's (owners and admins only; members get an error to relay). Without `--scope`, the call changes the selection in effect, which follows the key in effect (a member's personal key uses their personal selection). +- A member's personal selection never changes the organization's. The default-model select always offers the organization's checked models. +- `set` with an empty list hides the provider's chat models, for a key used only by services. Builder.io accepts only its own catalog. +- A chat already on an unchecked model keeps running on it. When nothing picked a model and the engine default is unchecked, chats use the first checked model. +- A row with `models: null` has nothing chosen and shows the recommended models. `state: "unreadable"` means the selection couldn't be read, not that it is empty. + +## Built-in Engines + +| Engine Name | Provider | Requires | +|---|---|---| +| `anthropic` | Anthropic Claude SDK | `ANTHROPIC_API_KEY` | +| `ai-sdk:anthropic` | Claude via Vercel AI SDK | `ANTHROPIC_API_KEY` | +| `ai-sdk:openai` | OpenAI via Vercel AI SDK | `OPENAI_API_KEY` | +| `ai-sdk:openrouter` | 300+ models (Anthropic, OpenAI, Google, Meta, …) routed through OpenRouter | `OPENROUTER_API_KEY` | +| `ai-sdk:google` | Google Gemini via Vercel AI SDK | `GOOGLE_GENERATIVE_AI_API_KEY` | +| `ai-sdk:groq` | Groq LPU via Vercel AI SDK | `GROQ_API_KEY` | +| `ai-sdk:mistral` | Mistral via Vercel AI SDK | `MISTRAL_API_KEY` | +| `ai-sdk:cohere` | Cohere via Vercel AI SDK | `COHERE_API_KEY` | +| `ai-sdk:ollama` | Local Ollama via Vercel AI SDK | None (local) | + +## Engine Capabilities + +Each engine advertises its capabilities: + +| Capability | Anthropic | AI SDK: Anthropic | AI SDK: OpenAI | AI SDK: Google | +|---|---|---|---|---| +| `thinking` | ✓ | ✓ | ✗ | ✓ | +| `promptCaching` | ✓ | ✓ | ✗ | ✗ | +| `vision` | ✓ | ✓ | ✓ | ✓ | +| `computerUse` | ✓ | ✗ | ✗ | ✗ | +| `parallelToolCalls` | ✓ | ✓ | ✓ | ✓ | + +## Anthropic-Exclusive Features + +When using the `anthropic` engine (or `ai-sdk:anthropic`): + +- **Prompt caching** is applied automatically to the system prompt — cutting latency and cost on repeated turns. +- **Extended thinking** can be enabled via `providerOptions.anthropic.thinking` — the agent reasons longer before responding. + +These features are silently ignored when a non-Anthropic engine is active (capability-gated, no breakage). + +## Using OpenRouter + +`ai-sdk:openrouter` gives access to 300+ models from many providers through a single API. Model IDs use the `vendor/model` form: + +``` +set-agent-engine --engine "ai-sdk:openrouter" --model "anthropic/claude-sonnet-4.5" +set-agent-engine --engine "ai-sdk:openrouter" --model "openai/gpt-4o" +set-agent-engine --engine "ai-sdk:openrouter" --model "google/gemini-2.5-pro" +``` + +Any `vendor/model` string from [openrouter.ai/models](https://openrouter.ai/models) works — the `supportedModels` list in the registry is a UI hint, not an allow-list. + +**App attribution** (optional): pass `appName` / `appUrl` in the engine config to set the `X-OpenRouter-Title` / `HTTP-Referer` headers — useful to see your app on the OpenRouter dashboard and leaderboards: + +```ts +createAISDKEngine("openrouter", { + apiKey: process.env.OPENROUTER_API_KEY, + appName: "My App", + appUrl: "https://myapp.example", +}); +``` + +## Registering a Custom Engine + +Register custom engines in a server plugin at startup. Import from the +`@agent-native/core/agent/engine` subpath: + +```ts +// server/plugins/my-engine.ts +import { + registerAgentEngine, + type AgentEngine, + type EngineEvent, + type EngineStreamOptions, +} from "@agent-native/core/agent/engine"; + +registerAgentEngine({ + name: "my-engine", + label: "My Custom Engine", + description: "...", + capabilities: { + thinking: false, + promptCaching: false, + vision: false, + computerUse: false, + parallelToolCalls: true, + }, + defaultModel: "my-model-v1", + supportedModels: ["my-model-v1", "my-model-v2"], + requiredEnvVars: ["MY_ENGINE_API_KEY"], + create: (config): AgentEngine => ({ + name: "my-engine", + label: "My Custom Engine", + defaultModel: "my-model-v1", + supportedModels: ["my-model-v1", "my-model-v2"], + capabilities: { + /* same shape as above */ + } as any, + async *stream(opts: EngineStreamOptions): AsyncIterable { + // yield text-delta / thinking-delta / tool-call / usage events + // as they arrive, then: + yield { type: "assistant-content", parts: /* final content parts */ [] }; + yield { type: "stop", reason: "end_turn" }; + }, + }), +}); +``` + +### Engine stream contract + +Every engine's `stream(opts)` MUST emit, in order: + +1. Zero or more `text-delta`, `thinking-delta`, `tool-call`, and `usage` + events as they arrive from the model. +2. Exactly one `{ type: "assistant-content", parts }` event with the + structured content for the turn. `runAgentLoop` reads this to + reconstruct the assistant message for the next turn. +3. Exactly one terminal `{ type: "stop", reason }` event. + +After registering, the engine appears in `list-agent-engines` output and can +be selected via `set-agent-engine`. + +## Env Vars Reference + +| Variable | Purpose | +|---|---| +| `ANTHROPIC_API_KEY` | Required for `anthropic` and `ai-sdk:anthropic` engines | +| `OPENAI_API_KEY` | Required for `ai-sdk:openai` | +| `OPENROUTER_API_KEY` | Required for `ai-sdk:openrouter` | +| `GOOGLE_GENERATIVE_AI_API_KEY` | Required for `ai-sdk:google` | +| `GROQ_API_KEY` | Required for `ai-sdk:groq` | +| `MISTRAL_API_KEY` | Required for `ai-sdk:mistral` | +| `COHERE_API_KEY` | Required for `ai-sdk:cohere` | +| `AGENT_ENGINE` | Default engine name (overridden by settings store) | diff --git a/.agents/skills/agent-native-docs/SKILL.md b/.agents/skills/agent-native-docs/SKILL.md new file mode 100644 index 0000000..e8488e7 --- /dev/null +++ b/.agents/skills/agent-native-docs/SKILL.md @@ -0,0 +1,161 @@ +--- +name: agent-native-docs +description: >- + How to find version-matched Agent-Native framework docs and source bundled in + node_modules. Use before implementing or answering questions about + @agent-native/core APIs, generated apps, workspaces, templates, or advanced + features. +scope: dev +metadata: + internal: true +--- + +# Agent-Native Docs Lookup + +## Rule + +Before implementing or explaining non-trivial Agent-Native behavior, read the +version-matched docs installed with `@agent-native/core`. When examples, +imports, or implementation details matter, inspect the packaged source corpus +too. + +## Why + +Generated apps and workspaces may be on a different framework version than the +public docs or model memory. The installed package is the source that matches +the app in front of you. A version-matched `@agent-native/core-corpus` package +provides first-party template source when an app needs those examples, without +adding the corpus to every Core installation. + +## How + +From a generated app directory: + +```bash +pnpm action framework-search --pattern "defineAction" +pnpm action framework-search \ + --pattern "defineAction" \ + --scope source \ + --path "templates/*/actions/*.ts" +pnpm action framework-search --pattern "Agent(?:Panel|Sidebar)" --mode regex --scope source +``` + +Use `framework-search` first when a question may cross the docs and source +boundary. It searches version-matched framework docs, runtime-visible skills, +readable Core or Toolkit package source, and first-party template source when +the optional corpus is installed, in one bounded read-only call. Use +`scope: docs` or `scope: source` to narrow it, then use the focused readers for +the page or file you need. + +The headless `pnpm agent` loop and built-in app agents expose read-only +`framework-search`, `docs-search`, and `source-search` tools when Core's docs +scripts are bundled. The default substring mode is safest for ordinary +questions; use `glob` for wildcard paths, `sql-like` for `%` and `_` wildcards, +and `regex` for precise structural matches. Results are bounded, so refine the +pattern or path instead of treating a truncated result as exhaustive. + +From a generated app directory, the lower-level readers remain available: + +```bash +pnpm action docs-search --query "actions" +pnpm action docs-search --slug actions-defining +pnpm action docs-search --list +pnpm action source-search --query "defineAction" +pnpm action source-search --path templates/plan/AGENTS.md +pnpm action source-search --path templates/chat/actions/hello.ts +pnpm action source-search --list +``` + +If a search reports that the optional first-party template corpus is not +installed, add it at the same version as Core: + +```bash +core_version=$(node -p 'require("./node_modules/@agent-native/core/package.json").version') +pnpm add -D "@agent-native/core-corpus@$core_version" +``` + +Use the unified tool for discovery, then the focused tools for full page or +file reads. + +If the action runner is unavailable, search the package directly: + +```bash +rg -n "actions|automations|a2a|sharing" node_modules/@agent-native/core/docs +rg -n "defineAction|useActionQuery" node_modules/@agent-native/core-corpus/corpus +``` + +Then read `node_modules/@agent-native/core/docs/AGENTS.md` or the matching file +under `node_modules/@agent-native/core/docs/content/`. For template examples, +read files under `node_modules/@agent-native/core-corpus/corpus/templates/`. The corpus +carries templates only; for Core's own implementation read +`node_modules/@agent-native/core/dist/` (compiled sources plus `.d.ts`). + +Toolkit ships readable TypeScript under +`node_modules/@agent-native/toolkit/src/`. Read +`customizing-agent-native` before taking ownership of a shared component: inspect package +source as a read-only reference, then configure, compose, or eject the smallest +supported unit into app-owned source. Preserve public actions, application +state, auth, and agent-chat runtime contracts. Never edit `node_modules` or +deep-import its private source. Manual copying is only the fallback described by +an unknown third-party package's add-style blueprint. + +## Reuse Proven Patterns (rg + cp) + +Version-matched installed source outranks web docs or memory: it is the exact +code shipping with this app. `node_modules/@agent-native/core-corpus/corpus/templates/` +holds source for every first-party template, not just the one this app started +from, so a pattern from the mail template is fair game for a tasks app. Grep +across it, then copy a whole file as a starting point instead of writing the +pattern from scratch: + +```bash +# Find how other templates solved a similar problem +rg -n "drag.*drop|reorder" node_modules/@agent-native/core-corpus/corpus/templates + +# Grab a proven action file as a starting point, then adapt names/schema +cp node_modules/@agent-native/core-corpus/corpus/templates/chat/actions/hello.ts \ + actions/greet.ts + +# Read the framework's own implementation behind an API +rg -n "defineAction" node_modules/@agent-native/core/dist/action.js +``` + +Copying template-level app code (actions, components, skill files) is the +expected reuse path — templates exist to be forked. This is different from +copying `core`/`toolkit` **runtime internals**: for those, follow +`customizing-agent-native`'s configure/compose/eject ladder instead of +hand-duplicating framework logic. + +## Useful Slugs + +| Need | Slugs | +| ------------------------------ | ----- | +| Define and call actions | `actions-overview`, `actions-defining`, `actions-advanced` | +| Typed client calls and data | `client-overview`, `client-entry-points`, `client-data` | +| SQL, auth, access, sharing | `postgres`, `server-database`, `authentication`, `security`, `sharing` | +| UI state visible to the agent | `context-awareness` | +| Headless and chat-first apps | `pure-agent-apps`, `agent-surfaces`, `using-your-agent` | +| Automations and schedules | `automations`, `recurring-jobs` | +| Cross-app and external agents | `a2a-protocol`, `external-agents`, `mcp-protocol`, `mcp-apps` | +| Skills and instructions | `skills-guide`, `writing-agent-instructions` | + +## Don't + +- Do not rely on memory for framework APIs when package docs are present. +- Do not add custom REST wrappers for app data before reading + `actions-overview` and `actions-defining`. +- Do not add inline LLM calls before reading `using-your-agent` and + `agent-surfaces`. +- Do not copy framework runtime internals when a public API or narrow UI copy + will do; read `customizing-agent-native` for the supported override ladder. + +## Authoring visual docs blocks + +Treat the shared `Diagram` block as a renderer, not as a reason to style every +docs UI as a sketch. Use the hand-drawn font and Rough.js only for actual +diagrams or wireframes that communicate structure, flow, or a design draft. +For polished UI-like content - cards, logo walls, tables, controls, or product +shells — set `renderMode="design"` (and usually `frame="hide"` when the block +is the content itself). Design mode preserves normal docs typography and +disables the Rough.js overlay. Keep `data-rough` only on elements intentionally +sketched inside a real diagram. diff --git a/.agents/skills/agent-native-toolkit/SKILL.md b/.agents/skills/agent-native-toolkit/SKILL.md new file mode 100644 index 0000000..4c6c2f9 --- /dev/null +++ b/.agents/skills/agent-native-toolkit/SKILL.md @@ -0,0 +1,314 @@ +--- +name: agent-native-toolkit +description: >- + Inventory and ownership rules for shared Agent-Native workspace UI. Use + before building app chrome, settings, navigation, sharing, collaboration, + setup, history, comments, chat rails, agent UX, or repeated workspace behavior. +scope: dev +metadata: + internal: true +--- + +# Agent-Native Toolkit + +Use this skill when deciding whether app chrome, settings, collaboration, +sharing, navigation, organization, setup, history, comments, or agent UX should +be built app-locally or moved into reusable framework/toolkit pieces. + +## Core Rule + +Apps own domain models, domain actions, and product-specific workflows. The +framework and `@agent-native/toolkit` own repeated workspace behavior users +expect to work the same everywhere. + +Move behavior into shared toolkit primitives when it is: + +- workspace-wide, such as settings, nav, search, org membership, or setup +- agent-visible, such as context, actions, run progress, or proof-of-done +- governed, such as secrets, permissions, sharing, audit, or billing +- repeated by two or more apps +- not tied to one domain model + +Keep behavior app-local when the abstraction would hide important domain +language or make a simple app-specific workflow harder to understand. + +## Agent Surface Contract + +When using the shared app shell, keep its two navigation surfaces distinct: + +- The left rail owns domain destinations and chat history when the app has a + full-page chat route. Do not label a domain workflow as `Chat` just because + the app was scaffolded from the chat template. +- Settings is not a rail item. It opens from the account menu (`OrgSwitcher` + in the sidebar footer) and from ⌘, (Ctrl+, elsewhere), which `AppProviders` + binds. Keep the `/settings` route; don't add a Settings entry to `items`, + `secondaryItems`, or the footer. +- The right `AgentSidebar` owns contextual agent work. Domain buttons that call + `sendToAgentChat` should open it (`openSidebar: true`) so the user can see, + steer, and review the agent without losing the page they were using. +- Keep `/` or `/chat/*` as the full-page chat surface when the starter provides + one. Put domain workflows on named routes and wire the shell's route checks, + navigation labels, and handoffs to those routes together. +- Use familiar message or neutral action icons for agent affordances. Never use + sparkle, wand, magic, or robot icons as an AI label; the copy should carry the + meaning. +- Give the right rail a quiet visual boundary with a subtle surface shift, + divider, or both. The domain page and AgentSidebar should not collapse into a + single undifferentiated background. +- Any button labeled as agent work must use `sendToAgentChat` with bounded + context and `openSidebar: true`; local deterministic analysis should be + labeled as local, preview, or analyze. For original/generated review, stack + the source above the result by default and use side-by-side only for short, + highly scannable content. +- Deterministic implementation does not make an AI-shaped experience + deterministic. If the user expects research, analysis, generation, + recommendation, synthesis, visible progress, or steering, route the button + to the AgentSidebar and let the agent call focused actions. Keep revisions in + the same thread instead of adding a second freeform prompt box. +- Standalone apps with `AgentSidebar` must use one AgentKit controller and + transport. Core's `AssistantChat` export remains supported as an alias for + `AgentKitAssistantChat`; use AgentKit slots and registries for custom message + UI. Keep assistant-ui transcript/runtime imports inside the shared composer + integration; when linked dependencies need Vite aliases, resolve one + `@agent-native/agentkit` context and verify a real handoff. + +Contextual agent UI is not a reason to expose every option at once. Start with +the domain task's primary action, reveal review or configuration only when the +current state needs it, and let the sidebar carry conversational depth. + +When an app exposes context sources or integration shortcuts, show only +capabilities available to that app and the current caller. Keep retrieving +context distinct from asking the agent to invoke an integration, and recheck +availability when the user submits. Do not infer agent-tool access from a +connected messaging account or expose credential values. Link to shared +Integrations settings when a required connection is missing. + +## Visual Direction And Workspace Variety + +Shared workspace behavior should be consistent without forcing every app into +the same visual skin. Keep shell and component tokens semantic, then let each +app record a visual direction in `DESIGN.md` before styling. Choose its palette +and composition from the product context, and keep semantic states accessible. + +Do not make warm beige plus terracotta the workspace fallback. Preserve a +workspace-level brand when one exists; otherwise keep shared chrome neutral and +allow app-owned accents to distinguish products while retaining accessible +semantic states and the shared AgentSidebar contract. + +## Discover Before Building + +Before creating an app-local version of repeated workspace or agent UI: + +1. Check the reusable kits below and the installed package documentation. +2. Search installed public components and source with `docs-search` and + `source-search`. +3. Run `agent-native eject --list` to see the version-matched units published + by the packages installed in this app. +4. Read `customizing-agent-native` and configure, compose, or eject the + smallest unit instead of recreating shared behavior from memory. + +Use public package exports at runtime. Published source and ejection manifests +are discovery and ownership-transfer mechanisms, not private runtime APIs. + +## Design-System Boundary + +For apps with a UI, keep an explicit design-system seam in +`app/design-system.ts` using `defineDesignSystem` from +`@agent-native/toolkit/design-system`, and supply it to `ToolkitProvider`. The +semantic contract contains: + +- nine leaf components: `ActionButton`, `IconButton`, `TextField`, `TextArea`, + `Spinner`, `Skeleton`, `Status`, `Surface`, and `Avatar` +- eight behavior components: `Tooltip`, `Menu`, `Popover`, `Dialog`, `Picker`, + `Checkbox`, `Switch`, and `Tabs` + +These are semantic contracts, not styling contracts. An adapter may use +Tailwind/shadcn, MUI-style theme providers, React Aria, CSS modules, CSS-in-JS, +or another React design system. Do not assume CVA, utility classes, or even a +`className`; behavior adapters may supply their overlay and focus +implementation wholesale while honoring portal, focus-restoration, keyboard, +dismissal, ARIA, and z-index interoperability. + +Pages, routes, and domain components import ordinary controls through the app's +local adapter layer, usually `@/components/ui/*`. They must not import +`@agent-native/toolkit/ui/*` directly. Toolkit feature exports are still the +right home for shared workspace behavior; their presentation flows through the +registered semantic components, feature controller, and product-level slots. + +Import any design-system adapter explicitly; do not auto-detect it or load React +components from JSON. Run a custom adapter against +`@agent-native/toolkit/conformance` in the app's CI before adopting it. + +## Settings Direction + +Durable settings belong in Settings. The agent sidebar should not become a +second settings app; it can show contextual quick controls and deep links. +Settings has the same groups in every app, and page ids are stable URL segments +(`/settings//`): + +- Account: `profile`, `preferences`, `security` +- Connections: `integrations` (`integrations/builder`), `api-keys` +- Agent: `model`, `instructions`, `memory`, `skills`, `files`, `sub-agents` +- Organization: `org`, `members`, `usage`, and for owners and admins `auth`, + `apps`, `infra`, `audit` +- The app's group: `app` (areas at `app/`), `notifications`, + `automations`, `channels` (`channels/`), `mcp`, `creative-context` +- Footer: `labs`, `whats-new` + +Link with `buildSettingsRoute(page, sub?, { anchor? })`; older tab and section +ids continue to resolve through framework redirects. Account › Profile is the +canonical profile surface (`get-user-profile`, `update-user-profile`); don't +build an app-local profile page. Read the `toolkit-settings` documentation for +the current route and page ids. + +When adding a new API key, OAuth grant, provider connection, model selector, app +preference, notification preference, or usage/billing surface, find the page +that owns that kind of setting first: provider keys go through the one provider +dialog on Model, other keys on API keys, channels on Channels, and app-only +preferences in the app's group. Only add sidebar UI when it is needed in the +moment of agent use. + +### The app's group in Settings + +Settings has a group named after the app. +Core owns its pages: General, Notifications, Automations, Channels, MCP server, +Creative context, plus Labs and What's new in the footer. A template supplies +only its own content, through these `SettingsTabsPage` props: + +- `generalGroups`: the app's own `SettingsGroup`s on its General page. Core puts + Agent › Default model above them (owners and admins change it; the agent + uses `manage-agent-engine` `set-app-default`) and This browser › Demo mode + below. Until a template passes it, today's `general` shows there. +- `appAreas`: `[{ id, label, content, visible?, keywords?, searchEntries? }]`, + tabs on the General page routed `/settings/app/`. Set `visible: false` + while the lab behind an area is off. A tab with + `settingsPlacement: "app-area"` in `extraTabs` works the same. +- `notifications` (plus `notificationsSearchEntries`): the Notifications page + shows only when this is passed. +- `mcpAbout`: the MCP server page's about line, naming what an MCP host can do + in this app. +- Labs come from `labs`; What's new comes from `whatsNewMarkdown`, or from the + `ChangelogSettingsCard` passed as `whatsNew`. +- Any other `extraTabs` item becomes its own page in the app's group. To swap a + core page for a variant, `registerSettingsPages([{ ...corePage, component }])` + at module scope (Dispatch's Members keeps its app-role column this way). To + add a group to one channel's page, `registerChannelSettingsExtensions`. + +The route needs a `settings.$.tsx` splat next to `settings.tsx`, and the layout +hides its own sidebar and header on Settings routes while the flag is on or +loading (`isSettingsPathname`), because the shell brings its own. + +Search entries per area: each `searchEntries` item's `hash` is the row's +`SettingsRow` id, and a hit opens that area's tab and scrolls to the row. With +the flag off, the same props render as today's tabs, so a migrated template +works either way. Link with `buildSettingsRoute("app", "")`, never a +hand-written path. + +Gate UI on a lab with `useLab(LAB_DEFINITION)` rather than `useLab(key)`: a +definition reads as its `defaultEnabled` until the server answers, while a bare +key reads as on. + +## Integration Setup Preflight + +Before building any setup, settings, credential, OAuth, or connection surface, +search the workspace/provider connection catalog first. If the provider already +has a reusable connection, use its catalog, app grant, and scoped credential +resolver rather than registering a parallel secret. Only then classify fields +that still need app-local setup by lifecycle and scope: + +| Need | Default primitive | +| --- | --- | +| Deploy- or app-level configuration | Runtime configuration or deployment env vars | +| Existing workspace/provider connection | Workspace-connection catalog/grant plus `resolveWorkspaceConnectionCredential(s)ForApp` | +| App-local API/service key with no reusable connection | `registerRequiredSecret({ kind: "api-key" })` and the vault | +| Authorization-code or refresh-token flow | `kind: "oauth"` with `@agent-native/core/oauth-tokens` | +| Account, customer, or other non-secret identifiers | Scoped connection metadata or app data | +| Provider-specific prerequisites, sequencing, or health | A thin app-local guide over the shared primitives | + +Do not register every provider field as a generic secret, mark every field as +required, or create a second credential-management surface. One logical +connection should normally produce one onboarding outcome. A custom setup page +is appropriate only when it adds domain-specific guidance or readiness checks; +it should link to or call the shared settings, OAuth, and action surfaces rather +than duplicating their storage or transport. + +## Reusable Kits + +- **Settings kit**: one searchable Settings page with Account, Connections, + Agent, and Organization groups plus a group for the app's own settings. The + index is built from page declarations; give every row a search entry whose + anchor is its `SettingsRow` id so users find settings by name. +- **Collaboration kit**: Yjs docs, presence, agent presence, live cursors, + remote selections, recent edit highlights, real-time sync indicators, and + undo/redo grouping. +- **Sharing kit**: private/workspace/org/public-link access, invites, roles, + expirations, agent-readable links, and resource registration. +- **Navigation and command kit**: app shell, side nav, breadcrumbs, app switcher, + command palette entries, recent resources, pinned resources, and global search. +- **Organization kit**: folders, tags, favorites, archive, trash, ownership, + membership, and common resource metadata. +- **Setup and connections kit**: declarative setup requirements, model readiness, + missing-secret states, OAuth grants, and provider connection health. +- **Agent UX kit**: sidebar, composer, staged context, mentions, voice, human + approval, generative UI, progress, and screen-state exposure. +- **Custom block kit**: optional, sandboxed extensions for one-off behavior or + views. Apps opt in; Core owns sandboxing, storage, and access checks, while + Toolkit provides reusable adoption UI. Promote repeated or durable workflows + to app-owned actions and UI. +- **Chat history kit**: presentational chat lists and recent-chat rails belong + in Toolkit; Core keeps thread persistence, agent execution, transport, and + page-to-sidebar handoff. Apps provide routing, labels, and domain actions. +- **Data grid kit**: provider-agnostic spreadsheet mechanics belong in + `@agent-native/toolkit/data-grid`. Apps provide rows, typed columns, editor + slots, selection and width state, persistence callbacks, and product-level + row/body slots. Keep database models, access checks, grouping, drag/drop, + and domain actions in the app adapter. +- **Agent page kit**: the full-page Agent surface (`AgentTabsPage` from + `@agent-native/toolkit/app/agent-page`) for agent resources, context + snapshots, integrations, automations, settings, and MCP access. The page + supports app-provided tabs. Use `agent-native-docs` to find current guidance + before adding it. +- **History and recovery kit**: audit log, activity feed, version history, + checkpoints, undo, redo, restore, and proof-of-done. +- **Comments and review kit**: anchored comments, pins, mentions, review + requests, resolved threads, agent follow-up tasks, and notifications. +- **Workflow and observability kit**: notifications, approvals, scheduled work, + background runs, recurring jobs, traces, evals, feedback, and run timelines. + +## Implementation Checklist + +When adding or refactoring one of these areas: + +1. Search app code and installed package documentation/source for an existing + feature before building an app-local version. +2. Configure the public feature through its data, action, controller, semantic + component, and product-level render seams. +3. Keep shared data provider-agnostic and scoped by auth/sharing rules. +4. Expose the same capability to the UI and agent through actions or documented + client helpers. +5. Keep app-specific labels, routes, resource adapters, and settings panels in + the app integration instead of forking shared UI for one app. +6. Document app-specific configuration for the next contributor; use + `agent-native-docs` when the installed package behavior is unclear. +7. Prefer public props and slots; if they cannot express the need, use the + smallest supported ejection unit. See `customizing-agent-native` for the + configure → compose → eject → propose seam ladder. +8. Keep one controller as the source of truth for the default and custom render + paths. A custom design must not fork actions, analytics, async state, or + accessibility behavior. +9. If the app registers a custom adapter, verify it with the conformance kit, + including focus, keyboard, dismissal, and portal behavior where components + meet framework surfaces. + +## Related Skills + +Read these alongside this skill when the work touches the specific area: + +- `sharing` +- `secrets` +- `adding-a-feature` +- `agent-native-docs` + +Use `agent-native-docs` to find installed-version guidance for navigation, +screen context, collaboration, visual direction, and other capabilities not +included in your scaffold's skill set. diff --git a/.agents/skills/authentication/SKILL.md b/.agents/skills/authentication/SKILL.md new file mode 100644 index 0000000..8f0be9c --- /dev/null +++ b/.agents/skills/authentication/SKILL.md @@ -0,0 +1,271 @@ +--- +name: authentication +description: >- + How to wire this app's login experience through the framework's + createAuthPlugin — branded loginHtml, public paths, and signup/logout UI. + Read before creating or editing server/plugins/auth.ts, or before adding + gated routes / a public marketing page. +scope: dev +metadata: + internal: true +--- + +# Authentication + +## Rule + +If a user requests authentication or login or other similar terms, you should setup +authentication in their app using this skill. + +`server/plugins/auth.ts` exports `createAuthPlugin(options)` from +`@agent-native/core/server` — that plugin is the app's auth. Do not hand-roll +session cookies, a parallel login route, or a custom auth backend; configure +the existing plugin instead. + +## Choose the landing route before wiring auth + +Before writing `loginHtml` or the sign-in journey, inspect `app/routes`, the +app's navigation, and any existing `app.homePath` in +`server/plugins/config.ts`. Preserve a valid existing `homePath`; otherwise +pick the app's actual primary authenticated route (`/`, `/dashboard`, +`/tasks`, ...) and persist it there — never assume `/home` unless that route +really exists. `loginHtml` and the journey script below both need this value: +a hardcoded `/` only works for apps whose real landing page is root. + +## Branded login page + +Pass `loginHtml: string` — a full HTML document that replaces the built-in +login page and its framework chrome entirely, so it can carry this app's own +layout, fonts, colors, and copy. Write it to match this app's actual look and +feel (its palette, type, and voice) — do not ship the generic framework login +page, and do not reuse another app's `loginHtml` verbatim without replacing +its copy and styling first. + +The login HTML must call the framework's own auth endpoints, so behavior +matches the built-in page: + +- `POST /_agent-native/auth/register { email, password, callbackURL? }` → + `{ ok: true }` or `{ error }`. **`{ ok: true }` only means the account was + created — register does NOT set a session cookie, so the visitor is still + signed out at this point.** +- `POST /_agent-native/auth/login { email, password }` → sets the session + cookie and returns `{ ok: true }` or `{ error }`. This is the only + endpoint that establishes a session. +- `GET /_agent-native/google/auth-url?return=` → `{ url }` to send the + browser to for Google sign-in (only relevant when Google OAuth is + configured) + +**Sign-up must chain register → login before treating the user as signed +in.** A custom `loginHtml` that posts to `/register` and redirects on that +response's `{ ok: true }` alone creates the account but leaves the visitor +logged out — they land back on the app, still unauthenticated, and have to +log in separately right after signing up. The framework's own built-in login +page (not the custom `loginHtml` you write) already does this chaining +internally, which is why this bug only shows up once an app supplies its own +`loginHtml`. Every sign-up handler must call login immediately after a +successful register, with the same email/password, and only redirect once +*that* call also returns `{ ok: true }`: + +```js +function submitSignup(email, password) { + return postJson("/_agent-native/auth/register", email, password).then( + function (data) { + if (!(data && data.ok)) throw new Error(data && data.error); + // Register succeeded but did not sign the visitor in — log in now. + return postJson("/_agent-native/auth/login", email, password); + }, + ); +} +``` + +On success there is no redirect to follow — reload the current URL (e.g. +`location.reload()`) and it now passes the auth guard. + +**This shortcut only works at the root path.** For any other gated route +(e.g. `/toppings`), the client `` gate does not serve +`loginHtml` in place at that URL — it navigates the browser to +`/sign-in?c=` first, so `location.reload()` there just +re-shows the login form forever instead of returning the visitor to +`/toppings`. To resume the original page, decode that continuation with the +framework's own helper instead of hand-rolling redirect logic: + +```html + + + +``` + +`resumeHref` decodes the `c` continuation back to the originally-requested +path, falling back to that configured `homePath` when there isn't one — +hardcoding `/` here silently sends visitors to the wrong page on any app +whose real landing route isn't root. Embed `signInJourneyInlineScript()` in +every custom `loginHtml` that guards more than just `/`. + +The login page must include: + +- A **sign-in** form (email/password) posting to `/_agent-native/auth/login`. +- A **sign-up** control — a visible "Sign up" / "Create account" affordance + that posts to `/_agent-native/auth/register`. Never ship a login-only page + with no way to register. + +## Logging out + +Once a user is signed in, the app's authenticated UI must include a **logout** +control — do not leave users with no way to sign out. Use the framework's +`signOut()` helper from `@agent-native/core/client` rather than posting to +`/_agent-native/auth/logout` directly; it revokes the server session and only +then navigates, avoiding a stale authenticated screen that renders against a +dead cookie: + +```ts +import { signOut } from "@agent-native/core/client"; + +; +``` + +## Separating a public marketing page from the private app + +When an app needs a public landing surface in front of a gated authenticated +app, keep the two on different routes rather than gating everything or exposing +everything. The blank starter ships `app/routes/_index.tsx` as a placeholder +canvas at `/`; a common split is: + +- **Public marketing page** at `/` — listed in `workspaceAppPublicPaths` (and + `PUBLIC_PATHS` in `app/root.tsx`, see below) so signed-out visitors can reach + it. +- **Private app** behind auth at a separate route (e.g. `/dashboard`), used as + `app.homePath`. + +For the public page, prefer the framework's ready-made shell +`MarketingHome` from `@agent-native/toolkit/marketing` instead of hand-rolling +a hero. It renders a branded landing shell with a hero, value props, and CTA +buttons that can deep-link into sign-in and the app: + +```tsx +import { MarketingHome } from "@agent-native/toolkit/marketing"; +import { appPath } from "@agent-native/core/client/api-path"; +import { APP_TITLE } from "@/lib/app-config"; + +export default function MarketingHomeRoute() { + return ( + + ); +} +``` + +Point `primaryActionHref` at the app's actual authenticated landing route (the +same value chosen for `app.homePath`), not a hardcoded `/home`. Pass +`variant="auth"` with an `auth` node to compose the login form beside the +marketing copy on a single public page. Only reach for `MarketingHome` when the +app actually wants a public marketing surface — a purely private app needs no +public landing page at all. + +## Public paths + +`workspaceAppPublicPaths: string[]` exempts page-route prefixes from the +private-app auth gate, e.g. `["/"]` so a logged-out visitor hitting the +marketing root gets the SPA (which renders the public landing page) instead of +being redirected to sign-in. Every route not listed here — and every +action/API — stays gated and requires a session. Set this explicitly for any +route a signed-out visitor should be able to reach; use +`workspaceAppProtectedPaths` for the inverse (an otherwise-public audience +with specific pages, e.g. an admin screen, that must still require a session). + +**This only configures the server.** There is a SEPARATE client-side gate in +`app/root.tsx`: `` defaults its `isPublicPath` +prop to `false`, which wraps the *entire* app in `` + +`` — every route, including ones already listed in +`workspaceAppPublicPaths`. Setting `workspaceAppPublicPaths` alone does +**not** make a page public; the two must be kept in sync by hand: + +```tsx +// app/root.tsx — must match workspaceAppPublicPaths in server/plugins/auth.ts +const PUBLIC_PATHS = ["/", "/menu", "/order"]; + +export default function Root() { + const location = useLocation(); + const isPublicPath = PUBLIC_PATHS.includes(location.pathname); + return ( + + {/* ... */} + + ); +} +``` + +Forgetting this makes every route require sign-in even when the server +config says otherwise — the symptom is public marketing pages redirecting to +login for no apparent reason. When adding or changing +`workspaceAppPublicPaths`, always update this array in `app/root.tsx` too. + +**Setting `isPublicPath={true}` streams real SSR markup for that route +instead of a `` shell** (see `AppProviders`'s own doc comment). +Most generated `root.tsx` files already mount router-dependent app-shell +services next to `` — e.g. a `DbSyncSetup`-style component calling +`useNavigationState` / `useLocation`, or anything else needing Router +context. Those services were only ever exercised inside the `` +branch before; once a route becomes public, they render during SSR too, +where that context may not be established, and the whole page 500s with +`Error: useLocation() may be used only in the context of a +component`, repeated several times in the server log. Wrap any such service +in `` explicitly so it keeps deferring to the client regardless +of `isPublicPath`: + +```tsx +import { ClientOnly } from "@agent-native/core/client/ui"; + + + + + + + + +; +``` + +Do this once when first adding any public path, not per-route — the app +shell services live above the routed `` regardless of which page +is loading. + +## Example + +```ts +import { createAuthPlugin } from "@agent-native/core/server"; + +export default createAuthPlugin({ + workspaceAppPublicPaths: ["/"], + loginHtml: ` + + + Sign in — Acme + + + + + + + +`, +}); +``` diff --git a/.agents/skills/build-an-app/SKILL.md b/.agents/skills/build-an-app/SKILL.md new file mode 100644 index 0000000..b370d0a --- /dev/null +++ b/.agents/skills/build-an-app/SKILL.md @@ -0,0 +1,200 @@ +--- +name: build-an-app +description: >- + Fast end-to-end workflow for turning this starter into a working domain app + from a short or vague request. Use when asked to build, make, create, or + prototype an app, tool, tracker, dashboard, booking, inventory, or CRM + system with Agent-Native. Read before the first edit. +scope: both +metadata: + internal: true +--- + +# Build an App + +Done means one useful domain workflow with a designed route, shared UI/agent +actions, correct access, agent context, and a smoke run that proves its key +rule. Finish a narrow slice before expanding it. + +This skill edits source files. If this session cannot write files (a deployed +app's runtime agent), say the change needs a code session and stop. + +The four-area parity rule from `adding-a-feature` (UI, action, instructions, +application state) applies to everything you add. This skill supplies the +order and decisions; use the edit-point reference for the scaffold you have. + +## 1. Orient + +Read `AGENTS.md`, this skill, and only the files you will edit. Skip broad repo +surveys, `README.md`, and `DESIGN.md`. Use the bundled docs/source commands in +`AGENTS.md` only to answer a concrete API question; do not web-research +framework APIs. + +## 2. Decide + +Choose these six things before writing code: + +1. **Slice**: the one workflow that proves the app. For a booking app: create a + booking, reject an overlap, cancel, weekly grid per room. Name what you are + deferring (recurrence, notifications, roles, integrations) unless requested. +2. **Who sees each table**: pick one row of the access table in + `references/data-and-access.md`: private, team-visible, shared on invite, or a + child that inherits its parent's access. Making a team resource private per + user is the usual wrong turn. Everyone then sees an empty list, and no + conflict check can see anyone else's rows. Give each table `owner_email` + and/or `org_id`, directly or via `ownableColumns()`; `org_id` alone passes + `[db-tool-scoping]`. Doctor checks the schema marker, not query authorization; + never denylist or opt out `rooms` or `bookings`. +3. **Invariants**: rules that must hold under concurrent requests (no overlap, + stock never negative, unique slug). Enforce them in a write action inside a + transaction or with a database constraint; the UI alone is insufficient. +4. **Actions**: `list-`, `create-`, a single `update-` + patch per resource, and the domain verbs (`cancel-booking`). Fewer, + orthogonal tools make the agent choose better. +5. **Route**: give the domain its own route (for example, `/rooms`). Preserve + existing routes and set `app.homePath` so sign-in lands on the domain when + that is the requested home screen. +6. **Agent context**: URL ids and filters (for example `roomId`, `week`) that + belong in `navigation`. + +## 3. Build: write everything, then verify once + +In a generated app, read `package.json` at +`["agent-native"].scaffold.template` and choose the matching reference: + +- `builder-code-starter`: this starter has no Chat shell. Use `AGENTS.md`, + `DEVELOPING.md`, and `drizzle/START_HERE.md` for edit points. +- `default`: `references/edit-points-default.md` +- workspace root: use `adding-workspace-apps` to create an app, then follow the + new app's own `AGENTS.md` and scaffold reference. +- another domain template: use its `AGENTS.md` and `adding-a-feature`; do not + apply Chat or default shell instructions to it. + +If metadata is absent, inspect the actual route, layout, plugin, and navigation +files before choosing an edit point. Do not infer a shell from the app name. + +Write the UI, actions, instructions, and state before running the verification +steps below. Do not leave placeholder or comment-only screens. + +`references/rooms-example.md` gives a booking slice to adapt. It was verified +against the Chat starter; use the selected edit-point reference for the shell. +Use `frontend-design` for a deliberate visual direction and finish the +requested screens and interactions. + +### Data + +- Use PostgreSQL only, and keep migrations additive: new columns are nullable + or have a default, and nothing is dropped or renamed. Never edit an applied + entry; append a new named one. +- Set `ownerEmail` from `ctx.userEmail` and `orgId` from `ctx.orgId` on inserts + where those columns exist. Never rely on a development identity fallback. +- Ids are text from `crypto.randomUUID()`. +- Bound every list (a time range or `.limit()`), select only the columns it + renders, and index the columns it filters and sorts on. +- Store normalized UTC ISO timestamps; collect/display local times in the + user's timezone. Validate offsets at the action boundary before parsing. + +The access table, the concurrency pattern, and the security rules are in +`references/data-and-access.md`. + +### Actions + +- `schema` is zod, with `.describe()` on every field stating its units and + format (for example, "ISO 8601 date-time with offset"). +- Reads use `http: { method: "GET" }` and `readOnly: true`. Leave writes on the + default POST so `useActionMutation` needs no `method`. +- Reject with `fail(message, { errorCode, statusCode })` from + `@agent-native/core/action`: 409 for a conflict, 404 for not found, 403 for + forbidden. A returned `{ error }` is counted as success everywhere, and a + bare `throw` reaches the browser as a generic 500. +- Return plain objects that include the `id`. Keep LLM calls out of actions; + AI-shaped work belongs in the agent chat. +- When the request is batch-shaped ("add these 20"), write one action that + takes an array and writes it in one transaction. + +### UI + +- Load and write data with `useActionQuery` and `useActionMutation` from + `@agent-native/core/client/hooks`. No `fetch`, and no `/api/*` routes for app + data. Those routes are only for uploads, webhooks, OAuth callbacks, and streaming. +- While data loads, show a `Skeleton` in the shape of the final layout, not a + spinner or "Loading…". +- Writes should feel instant. In `onMutate`, update `["action", "", params]` + with `setQueryData`; in `onError`, roll back and show + `toast.error(actionErrorMessage(error) ?? "")`. +- Import controls from `@/components/ui/*`. When one is missing (dialog, + select, skeleton, alert-dialog), add a one-line re-export like `button.tsx`: + `export * from "@agent-native/toolkit/ui/dialog";`. +- Use Tabler icons only. Confirm with `AlertDialog`; never use `window.confirm`, + `alert`, or `prompt`. +- Don't add a page title that repeats the nav item, a subtitle under a title, + or a stats strip. The data is the page. For visual direction, see `frontend-design`. +- Follow the app's existing localization pattern for user-facing copy. +- Add a pure `link` builder with `buildDeepLink()` to actions that create or + list navigable resources; see `adding-a-feature` for the shape. + +### Agent instructions + +Append one section of about 1,500 characters at most to `AGENTS.md`. The +runtime prompt cuts the file off at 6,000 characters. Cover: + +- a one-line purpose with the routes +- the invariants, and how to report a rejection +- time and format conventions +- the new `navigation` fields +- an action table with unpadded cells + +Keep the action table aligned with the scaffold's primary tool list when one +exists; other actions should remain discoverable through `tool-search`. Leave +unrelated AGENTS.md sections, README, and DESIGN.md as they are. + +### Real-time + +Agent writes need no wiring, because the chat run refreshes action queries +after each tool. Add `useDbSync({ realtime: { reason } })` to a page only when +other people change its data while it is open and the user must see the change +before refreshing. A booking grid doesn't qualify: the server rejects bookings +made from a stale view. See `real-time-sync`. + +## 4. Verify, once, in this order + +1. Start `pnpm exec agent-native dev` in the background, without `--open`, and + wait for the ready URL. Startup regenerates `.generated/action-types.d.ts` + and the actions registry, so a typecheck run before this is meaningless. + On loopback, automatic dev sign-in works when the local database has no real + users. If the sign-in page appears, use an existing local account or switch + to a separate disposable local database; do not create accounts or set + `AUTH_DISABLED`. +2. Run `pnpm typecheck`, then `pnpm agent-native:doctor`. Plain `pnpm doctor` + runs pnpm's own command and exits 0 without running Agent-Native Doctor. Fix + every finding, then rerun only what failed. +3. Check the agent path. Call a guarded write twice with the same input via + `pnpm action --key value`. The second call must fail with the expected + message; read back the saved state through the matching list/get action. + The CLI prints the failure message, not its structured `errorCode`, so also + verify any code-specific behavior in the action contract or browser. +4. Run one browser smoke on the domain route: + - create a record + - trigger the rejection: a toast appears and nothing is written + - cancel or undo, repeat the previously rejected write, and confirm it + succeeds + + Inspect console and network failures. Fix errors from the new route or actions + and identify existing scaffold messages separately. The only expected 4xx/5xx + is the rejection being tested. Capture the finished workflow. +5. Stop the dev server and close the tab. + +Skip the production build, unrelated test suites, and README or DESIGN rewrites. +To triage failures, see `references/verification.md`. + +## 5. Report + +State what works and the proof, what you deferred, and anything the user still +has to do (for example, set `DATABASE_URL` before deploying). Never report a +check you didn't run. + +## Related + +- `adding-a-feature`: the parity checklist for each later feature in this app. +- `frontend-design`, `actions`, `sharing`, `real-time-sync`, and `security`: + go deeper on one area when the references aren't enough. diff --git a/.agents/skills/build-an-app/references/data-and-access.md b/.agents/skills/build-an-app/references/data-and-access.md new file mode 100644 index 0000000..af77bc8 --- /dev/null +++ b/.agents/skills/build-an-app/references/data-and-access.md @@ -0,0 +1,91 @@ +# Data and access decisions + +Use this when choosing who may see a row or when adding a schema/migration. A +table's columns control framework SQL-tool scoping; app actions still need their +own access checks for the people and records they return. + +## Choose the row model + +| Data | Columns | App action behavior | +| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Private to its creator (notes, drafts) | `owner_email` | Filter reads and writes by `ctx.userEmail`; set the owner on insert. | +| Shareable resource (documents, dashboards) | `...ownableColumns()` plus `createSharesTable()` and `registerShareableResource()` | Use `accessFilter(table, shares)` for lists; use `assertAccess(type, id, role)` before reads/writes by id. Choose `private`, `org`, or `public` visibility deliberately. | +| Team resource (rooms, products, customers) | Same shareable-resource columns | Use `visibility: "org"` when an org is active. Without an org, choose a deliberate private or no-create behavior. | +| Child of a resource (bookings in a room, line items in an order) | `parent_id`, `owner_email`, and the parent's `org_id` when present | Check access to the parent in the action, then scope every child query by parent id and tenant. Apply child-specific rules in the write action. | +| Organization-only rows (for example, membership records) | `org_id` only | Filter each app action by the active org; this does not support private ownership or per-user share grants. | +| Public URL (published form or booking page) | Separate slug/token | Use a public route with its own validation and read policy; sharing visibility does not create anonymous URL access. | + +Do not make a shared team resource private by adding only `owner_email`: that +causes normal app actions and lists to hide coworkers' rows. Use +`ownableColumns()` and the registered sharing helpers. Conversely, a room's +bookings can inherit the room's access if the booking actions check the room +before returning its rows. + +### What agent SQL tools can see + +`db-query`/`db-exec` create scoped views: an `owner_email` table is limited to +the current owner. If the caller has an active org and the table also has +`org_id`, rows are further limited to that org or a null org; without an active +org, only the owner filter applies. An `org_id`-only table is limited to the +current org and denied when there is no org. A table with neither column is +denied. This is deliberately narrower than share grants, so use typed app +actions to list team-shared records or children that inherit parent access. +Do not add filters to raw SQL that duplicate these views. + +The same row scoping does not replace action authorization. `accessFilter` +resolves resource visibility/share grants; `assertAccess` checks one resource +and role. The person who owns a row and a person with an org role are different +access concepts. + +## Schema and migrations + +- PostgreSQL only. Define tables with `drizzle-orm/pg-core`; use + `drizzle-orm` query operators. Import framework sharing helpers from + `@agent-native/core/db/schema` only for ownable resources. +- Chat has no database files or Drizzle migration config. Add + `server/db/schema.ts`, `server/db/index.ts` with `createGetDb(schema)`, and + `server/plugins/db.ts` with `runMigrations([...], { table })`. Follow the + bundled Database docs. Other starters may document their own migration path. +- Each migration entry needs a unique stable `{ version, name, sql }`. Never + renumber or edit an applied entry; append a new additive migration. +- Additive only: new columns are nullable or have a default, and nothing is + dropped, renamed, or retyped. Keep SQL DDL aligned with the Drizzle schema. +- Use text ids from `crypto.randomUUID()`. For sortable time text, normalize + every input to UTC `Date#toISOString()` before storing or comparing it. +- Use a `CHECK` or `UNIQUE` constraint for single-row rules such as valid + status, `end > start`, or unique slugs. + +`ownableColumns()` provides a development fallback owner value for framework +compatibility. App actions must still set the authenticated `ownerEmail` from +`ctx.userEmail`; never rely on that fallback to identify a real user. + +## Invariants across rows + +For rules such as no overlapping bookings or no overselling: + +1. Validate and normalize input, then check the caller's access to the parent. +2. Start `getDb().transaction(async (tx) => { ... })`. +3. Lock the parent row with `tx.select(...).from(parent).where(...).for("update")` + so concurrent writers for that parent serialize. +4. Query for conflicts with `tx`; if one exists, use `fail()` with a stable + `errorCode`, `statusCode: 409`, and a safe conflict identifier. +5. Insert with `tx` and return the saved result. Do not open a separate query + or call another action from inside the transaction callback. + +The lock is effective only when every writer follows the same parent-lock +protocol. Put the invariant in one action and use a database constraint when a +single-row constraint can express it. + +## Query and security defaults + +- Give every action a zod schema. Bound every list with a time range, `.limit()`, + or pagination; select only fields the caller needs; index hot filters/sorts. +- Use parameterized Drizzle queries. Never concatenate user input into SQL. +- Keep secrets in workspace connections or the vault, not source, SQL, seeds, or + instructions. See the `secrets` skill before adding credentials. +- Put file/image/audio/video/PDF payloads in configured blob storage and save + only the returned URL or opaque id in SQL. +- Add a custom `/api/*` route only for uploads, webhooks, OAuth callbacks, + streaming, or public unauthenticated responses. Use actions for app data. +- Keep startup limited to framework/plugin initialization and migrations; + put imports, backfills, and provider calls behind an action or job. diff --git a/.agents/skills/build-an-app/references/edit-points-default.md b/.agents/skills/build-an-app/references/edit-points-default.md new file mode 100644 index 0000000..0b21de4 --- /dev/null +++ b/.agents/skills/build-an-app/references/edit-points-default.md @@ -0,0 +1,23 @@ +# Default scaffold edit points + +Use only when `package.json["agent-native"].scaffold.template` is `default`. +This scaffold has a document/provider root and a sample `/home` route. It has +no Chat sidebar, `Layout.tsx`, `server/plugins/agent-chat.ts`, or +`INITIAL_TOOL_NAMES` list. + +| File | Change | +| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `server/db/schema.ts` (new) | Define PostgreSQL tables with `drizzle-orm/pg-core`; use the shared schema helpers when access/sharing needs them | +| `server/db/index.ts` (new) | Export `getDb = createGetDb(schema)` and register shareable resources as needed | +| `server/plugins/db.ts` (new) | Add named, additive migrations with `runMigrations` | +| `actions/-.ts` | One default-exported `defineAction` per file; the filename becomes the tool name | +| `app/routes.ts` and `app/routes/.tsx` | `flatRoutes()` discovers route files; add the domain route and nested routes using the filename conventions already present | +| `app/root.tsx` | Keep the document, providers, and ``; do not replace it with a domain shell | +| `app/hooks/use-navigation-state.ts` | Extend the current path-derived navigation state only when the agent needs selected domain ids or filters beyond the current URL | +| `server/plugins/agent-native-email-branding.ts` | Set `app.homePath` to the requested authenticated home route; the create command adds this plugin when it renames the scaffold | +| `AGENTS.md` | Add a concise domain section with routes, invariants, state, and primary actions | + +`app/routes/_index.tsx` is the sign-in landing route. `app/routes/home.tsx` +is the authenticated sample page. Preserve both unless the requested workflow +specifically replaces the home experience. The default template has no app +navigation shell to extend; add only the navigation the product needs. diff --git a/.agents/skills/build-an-app/references/rooms-example.md b/.agents/skills/build-an-app/references/rooms-example.md new file mode 100644 index 0000000..314bc44 --- /dev/null +++ b/.agents/skills/build-an-app/references/rooms-example.md @@ -0,0 +1,1027 @@ +# Worked example: meeting-room booking slice + +Request: "Build a meeting room booking app that prevents double-bookings and +shows a weekly grid per room." Adapt the access and invariant patterns; build +complete screens for the requested workflow. + +Plan (step 2): + +1. Slice: create room, book a slot, reject overlap, cancel, weekly grid. Defer + recurrence, invites, and notifications. +2. Access: rooms are org-visible when an org is active, and private to their + creator otherwise. Bookings inherit room visibility; only the booker can + cancel their booking. +3. Invariant: confirmed bookings for one room never overlap. Enforced in + `create-booking` inside a transaction that locks the room row. +4. Actions: `list-rooms`, `create-room`, `list-bookings`, `create-booking`, + `cancel-booking`. +5. Route: `/rooms` and `/rooms/:roomId?week=YYYY-MM-DD`, nested under a layout + route with an ``. Set `homePath: "/rooms"`. +6. Navigation: `roomId`, `week`. + +## Schema: `server/db/schema.ts` + +```ts +import { sql } from "drizzle-orm"; +import { integer, pgTable, text } from "drizzle-orm/pg-core"; +import { + createSharesTable, + ownableColumns, +} from "@agent-native/core/db/schema"; + +export const rooms = pgTable("rooms", { + id: text("id").primaryKey(), + name: text("name").notNull(), + capacity: integer("capacity"), + createdAt: text("created_at") + .notNull() + .default(sql`now()`), + ...ownableColumns(), // owner_email, org_id, visibility +}); +export const roomShares = createSharesTable("room_shares"); + +// Times are ISO text (same as the Calendar template's bookings). Always store +// Date#toISOString() output so string order equals time order. +export const bookings = pgTable("bookings", { + id: text("id").primaryKey(), + roomId: text("room_id").notNull(), + title: text("title").notNull(), + startsAt: text("starts_at").notNull(), + endsAt: text("ends_at").notNull(), + status: text("status", { enum: ["confirmed", "cancelled"] }) + .notNull() + .default("confirmed"), + ownerEmail: text("owner_email").notNull(), // the booker + orgId: text("org_id"), // copied from the parent room for tenant scoping + createdAt: text("created_at") + .notNull() + .default(sql`now()`), +}); +``` + +## Client and sharing registration: `server/db/index.ts` + +```ts +import { createGetDb } from "@agent-native/core/db"; +import { registerShareableResource } from "@agent-native/core/sharing"; + +import * as schema from "./schema.js"; + +export const getDb = createGetDb(schema); +export { schema }; + +registerShareableResource({ + type: "room", + resourceTable: schema.rooms, + sharesTable: schema.roomShares, + displayName: "Room", + titleColumn: "name", + getResourcePath: (room) => `/rooms/${room.id}`, + getDb, +}); +``` + +## Migration: `server/plugins/db.ts` + +```ts +import { runMigrations } from "@agent-native/core/db"; + +export default runMigrations( + [ + { + version: 1, + name: "rooms-and-bookings", + sql: `CREATE TABLE IF NOT EXISTS rooms ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + capacity INTEGER, + created_at TEXT NOT NULL DEFAULT (now()), + owner_email TEXT NOT NULL DEFAULT 'local@localhost', + org_id TEXT, + visibility TEXT NOT NULL DEFAULT 'private' +); +CREATE TABLE IF NOT EXISTS room_shares ( + id TEXT PRIMARY KEY, + resource_id TEXT NOT NULL, + principal_type TEXT NOT NULL, + principal_id TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'viewer', + created_by TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (now()), + notified_at TEXT +); +CREATE TABLE IF NOT EXISTS bookings ( + id TEXT PRIMARY KEY, + room_id TEXT NOT NULL REFERENCES rooms(id), + title TEXT NOT NULL, + starts_at TEXT NOT NULL, + ends_at TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'confirmed' CHECK (status IN ('confirmed', 'cancelled')), + owner_email TEXT NOT NULL, + org_id TEXT, + created_at TEXT NOT NULL DEFAULT (now()), + CHECK (ends_at > starts_at) +); +CREATE INDEX IF NOT EXISTS rooms_owner_org_name_idx ON rooms (owner_email, org_id, name); +CREATE INDEX IF NOT EXISTS room_shares_resource_idx ON room_shares (resource_id, principal_type, principal_id); +CREATE INDEX IF NOT EXISTS bookings_room_starts_idx ON bookings (room_id, starts_at); +CREATE INDEX IF NOT EXISTS bookings_org_room_starts_idx ON bookings (org_id, room_id, starts_at)`, + }, + ], + { table: "rooms_app_migrations" }, +); +``` + +Later schema changes are new entries (`version: 2, name: "bookings-notes"`, +`ALTER TABLE bookings ADD COLUMN IF NOT EXISTS notes TEXT`). Never edit entry 1 +once it has run. + +## Shared helper: `server/lib/bookings.ts` + +```ts +import { fail } from "@agent-native/core/action"; +import { and, eq, gt, isNull, lt } from "drizzle-orm"; + +import { schema } from "../db/index.js"; + +export function toIso(value: string, field: string): string { + if (!/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)) { + fail(`${field} must include a time and UTC offset.`, { + errorCode: "invalid_time", + }); + } + const ms = Date.parse(value); + if (Number.isNaN(ms)) { + fail(`${field} must be an ISO 8601 date-time.`, { + errorCode: "invalid_time", + }); + } + return new Date(ms).toISOString(); +} + +/** Confirmed bookings in `roomId` that intersect [from, to). */ +export function overlapping( + roomId: string, + orgId: string | null, + from: string, + to: string, +) { + const b = schema.bookings; + return and( + eq(b.roomId, roomId), + orgId ? eq(b.orgId, orgId) : isNull(b.orgId), + eq(b.status, "confirmed"), + lt(b.startsAt, to), + gt(b.endsAt, from), + ); +} +``` + +## Actions + +`actions/list-rooms.ts` + +```ts +import { defineAction } from "@agent-native/core/action"; +import { buildDeepLink } from "@agent-native/core/server"; +import { accessFilter } from "@agent-native/core/sharing"; +import { z } from "zod"; + +import { getDb, schema } from "../server/db/index.js"; + +export default defineAction({ + description: "List the rooms the current user can see and book.", + schema: z.object({}), + http: { method: "GET" }, + readOnly: true, + link: () => ({ + url: buildDeepLink({ view: "rooms", to: "/rooms" }), + label: "Open Rooms", + }), + run: async () => { + const { rooms, roomShares } = schema; + const rows = await getDb() + .select({ id: rooms.id, name: rooms.name, capacity: rooms.capacity }) + .from(rooms) + .where(accessFilter(rooms, roomShares)) + .orderBy(rooms.name) + .limit(200); + return { rooms: rows }; + }, +}); +``` + +`actions/create-room.ts` + +```ts +import { defineAction, fail } from "@agent-native/core/action"; +import { buildDeepLink } from "@agent-native/core/server"; +import { z } from "zod"; + +import { getDb, schema } from "../server/db/index.js"; + +export default defineAction({ + description: + "Create a bookable room. It is visible to the organization when one is active, otherwise only to its creator.", + schema: z.object({ + name: z.string().min(1).describe('Room name, e.g. "Atlas"'), + capacity: z.coerce + .number() + .int() + .min(1) + .optional() + .describe("Seats; omit when unknown"), + }), + link: ({ result }) => ({ + url: buildDeepLink({ + view: "rooms", + to: `/rooms/${encodeURIComponent(result.id)}`, + params: { roomId: result.id }, + }), + label: `Open ${result.name}`, + }), + run: async (args, ctx) => { + const ownerEmail = + ctx?.userEmail ?? fail("Sign in to create rooms.", { statusCode: 401 }); + const orgId = ctx?.orgId ?? null; + const room = { + id: crypto.randomUUID(), + name: args.name, + capacity: args.capacity ?? null, + ownerEmail, + orgId, + visibility: orgId ? ("org" as const) : ("private" as const), + }; + await getDb().insert(schema.rooms).values(room); + return { id: room.id, name: room.name, capacity: room.capacity }; + }, +}); +``` + +`actions/list-bookings.ts` + +```ts +import { defineAction, fail } from "@agent-native/core/action"; +import { buildDeepLink } from "@agent-native/core/server"; +import { accessFilter } from "@agent-native/core/sharing"; +import { and, eq } from "drizzle-orm"; +import { z } from "zod"; + +import { getDb, schema } from "../server/db/index.js"; +import { overlapping, toIso } from "../server/lib/bookings.js"; + +export default defineAction({ + description: + "List confirmed bookings for a room that overlap a time range (for example, one week).", + schema: z.object({ + roomId: z.string().describe("Room id from list-rooms"), + from: z + .string() + .datetime({ offset: true }) + .describe("Range start, ISO 8601 with offset"), + to: z + .string() + .datetime({ offset: true }) + .describe("Range end (exclusive), ISO 8601 with offset"), + }), + http: { method: "GET" }, + readOnly: true, + link: ({ args }) => ({ + url: buildDeepLink({ + view: "rooms", + to: `/rooms/${encodeURIComponent(args.roomId)}?week=${encodeURIComponent(args.from.slice(0, 10))}`, + params: { roomId: args.roomId, week: args.from.slice(0, 10) }, + }), + label: "Open room schedule", + }), + run: async (args) => { + const { rooms, roomShares, bookings } = schema; + const [room] = await getDb() + .select({ orgId: rooms.orgId }) + .from(rooms) + .where(and(eq(rooms.id, args.roomId), accessFilter(rooms, roomShares))) + .limit(1); + if (!room) + fail("Room not found.", { errorCode: "not_found", statusCode: 404 }); + const b = bookings; + const rows = await getDb() + .select({ + id: b.id, + title: b.title, + startsAt: b.startsAt, + endsAt: b.endsAt, + }) + .from(b) + .where( + overlapping( + args.roomId, + room.orgId, + toIso(args.from, "from"), + toIso(args.to, "to"), + ), + ) + .orderBy(b.startsAt) + .limit(500); + return { bookings: rows }; + }, +}); +``` + +`actions/create-booking.ts`: the invariant lives here and nowhere else. + +```ts +import { defineAction, fail } from "@agent-native/core/action"; +import { buildDeepLink } from "@agent-native/core/server"; +import { accessFilter } from "@agent-native/core/sharing"; +import { and, eq } from "drizzle-orm"; +import { z } from "zod"; + +import { getDb, schema } from "../server/db/index.js"; +import { overlapping, toIso } from "../server/lib/bookings.js"; + +export default defineAction({ + description: + "Book a room for a time range. Fails with errorCode booking_conflict (409) if it overlaps a confirmed booking; report the conflict instead of retrying.", + schema: z.object({ + roomId: z.string().describe("Room id from list-rooms"), + title: z.string().min(1).describe("What the booking is for"), + startsAt: z + .string() + .datetime({ offset: true }) + .describe("Start, ISO 8601 with offset, e.g. 2026-10-06T09:00:00-07:00"), + endsAt: z + .string() + .datetime({ offset: true }) + .describe("End, ISO 8601 with offset; must be after startsAt"), + }), + link: ({ args }) => ({ + url: buildDeepLink({ + view: "rooms", + to: `/rooms/${encodeURIComponent(args.roomId)}`, + params: { roomId: args.roomId }, + }), + label: "Open room schedule", + }), + run: async (args, ctx) => { + const ownerEmail = + ctx?.userEmail ?? fail("Sign in to book a room.", { statusCode: 401 }); + const startsAt = toIso(args.startsAt, "startsAt"); + const endsAt = toIso(args.endsAt, "endsAt"); + if (endsAt <= startsAt) + fail("endsAt must be after startsAt.", { errorCode: "invalid_range" }); + + return getDb().transaction(async (tx) => { + const { rooms, roomShares, bookings } = schema; + // Locking the room row serializes bookings per room; without it two + // simultaneous requests both pass the overlap check. + const [room] = await tx + .select({ id: rooms.id, orgId: rooms.orgId }) + .from(rooms) + .where(and(eq(rooms.id, args.roomId), accessFilter(rooms, roomShares))) + .for("update"); + if (!room) + fail("Room not found.", { errorCode: "not_found", statusCode: 404 }); + + const [clash] = await tx + .select({ + id: bookings.id, + title: bookings.title, + startsAt: bookings.startsAt, + endsAt: bookings.endsAt, + }) + .from(bookings) + .where(overlapping(args.roomId, room.orgId, startsAt, endsAt)) + .limit(1); + if (clash) { + fail( + `Overlaps "${clash.title}" (${clash.startsAt} to ${clash.endsAt}).`, + { + errorCode: "booking_conflict", + statusCode: 409, + details: { conflictId: clash.id }, + }, + ); + } + + const booking = { + id: crypto.randomUUID(), + roomId: args.roomId, + title: args.title, + startsAt, + endsAt, + ownerEmail, + orgId: room.orgId, + }; + await tx.insert(bookings).values(booking); + return { + id: booking.id, + roomId: booking.roomId, + title: booking.title, + startsAt: booking.startsAt, + endsAt: booking.endsAt, + status: "confirmed" as const, + }; + }); + }, +}); +``` + +Inside the transaction callback, use only `tx`. Run any other lookups +(`assertAccess`, other actions) before you open it. + +`actions/cancel-booking.ts` + +```ts +import { defineAction, fail } from "@agent-native/core/action"; +import { and, eq } from "drizzle-orm"; +import { z } from "zod"; + +import { getDb, schema } from "../server/db/index.js"; + +export default defineAction({ + description: "Cancel a booking made by the current user.", + schema: z.object({ id: z.string().describe("Booking id") }), + run: async ({ id }, ctx) => { + const email = ctx?.userEmail ?? fail("Sign in first.", { statusCode: 401 }); + const b = schema.bookings; + const [cancelled] = await getDb() + .update(b) + .set({ status: "cancelled" }) + .where( + and(eq(b.id, id), eq(b.ownerEmail, email), eq(b.status, "confirmed")), + ) + .returning({ id: b.id }); + if (!cancelled) { + fail("Booking not found or you cannot cancel it.", { + errorCode: "not_found", + statusCode: 404, + }); + } + return { id, status: "cancelled" as const }; + }, +}); +``` + +## Screens + +`app/components/ui/skeleton.tsx` (one line, like the shipped `button.tsx`): + +```ts +export * from "@agent-native/toolkit/ui/skeleton"; +``` + +`app/routes/rooms.tsx` is a nested route layout that renders ``. +`app/routes/rooms._index.tsx` lists rooms with an inline add form using +`useActionQuery("list-rooms", {})`, a `` per row, +and `useActionMutation("create-room")`. The underscore keeps the index as the +parent's index route in React Router's file-based config. + +`app/routes/rooms.$roomId.tsx` is a complete weekly grid with local-time inputs, +seven responsive day columns, optimistic booking/cancel updates, conflict feedback, +and a confirmation dialog. It uses the Chat starter route imports; other starters +should follow their edit-point reference for route layout and component paths. + +Add the UI strings used by this route and the room list to the existing English +message catalog under `rooms`: `addRoom`, `addingRoom`, `backToRooms`, `book`, +`booking`, `bookingCreated`, `bookingName`, `cancel`, `cancelBookingDescription`, +`cancelBookingTitle`, `cancelFailed`, `cancelling`, `capacity`, `confirmCancel`, +`conflict`, `createFailed`, `emptyDay`, `emptyRooms`, `end`, `invalidRange`, +`keepBooking`, `nav`, `nextWeek`, `previousWeek`, `roomCreated`, `roomName`, +`roomNotFound`, `seats`, and `start`. Follow the scaffold localization pattern +for any additional configured locales. + +```tsx +import { + actionErrorMessage, + useActionMutation, + useActionQuery, +} from "@agent-native/core/client/hooks"; +import { useT } from "@agent-native/core/client/i18n"; +import { + IconChevronLeft, + IconChevronRight, + IconClock, + IconUsers, +} from "@tabler/icons-react"; +import { useQueryClient } from "@tanstack/react-query"; +import { useMemo, useState } from "react"; +import { Link, useParams, useSearchParams } from "react-router"; +import { toast } from "sonner"; + +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Skeleton } from "@/components/ui/skeleton"; + +type Booking = { + id: string; + title: string; + startsAt: string; + endsAt: string; + status?: string; +}; + +function startOfWeek(date: Date) { + const start = new Date(date); + start.setHours(0, 0, 0, 0); + start.setDate(start.getDate() - ((start.getDay() + 6) % 7)); + return start; +} + +function dateKey(date: Date) { + return [ + date.getFullYear(), + String(date.getMonth() + 1).padStart(2, "0"), + String(date.getDate()).padStart(2, "0"), + ].join("-"); +} + +function weekRange(week: string) { + const parsed = new Date(week + "T00:00:00"); + const start = startOfWeek( + Number.isNaN(parsed.getTime()) ? new Date() : parsed, + ); + const end = new Date(start); + end.setDate(end.getDate() + 7); + return { start, from: start.toISOString(), to: end.toISOString() }; +} + +function localInputValue(date: Date) { + return new Date(date.getTime() - date.getTimezoneOffset() * 60_000) + .toISOString() + .slice(0, 16); +} + +function initialTimes() { + const start = new Date(); + start.setMinutes(0, 0, 0); + start.setHours(start.getHours() + 1); + const end = new Date(start); + end.setHours(end.getHours() + 1); + return { startsAt: localInputValue(start), endsAt: localInputValue(end) }; +} + +function hour(value: string) { + return new Intl.DateTimeFormat(undefined, { + hour: "numeric", + minute: "2-digit", + }).format(new Date(value)); +} + +function errorCode(error: unknown) { + if ( + error && + typeof error === "object" && + "errorCode" in error && + typeof error.errorCode === "string" + ) + return error.errorCode; + return undefined; +} + +export default function RoomWeekRoute() { + const t = useT(); + const { roomId = "" } = useParams(); + const [searchParams, setSearchParams] = useSearchParams(); + const [formTimes] = useState(initialTimes); + const [title, setTitle] = useState(""); + const [startsAt, setStartsAt] = useState(formTimes.startsAt); + const [endsAt, setEndsAt] = useState(formTimes.endsAt); + const [pendingCancelId, setPendingCancelId] = useState(null); + const queryClient = useQueryClient(); + const week = searchParams.get("week") ?? dateKey(startOfWeek(new Date())); + const range = useMemo(() => weekRange(week), [week]); + const params = useMemo( + () => ({ roomId, from: range.from, to: range.to }), + [roomId, range.from, range.to], + ); + const queryKey = ["action", "list-bookings", params]; + const { data, isPending } = useActionQuery("list-bookings", params); + const roomsQuery = useActionQuery("list-rooms", {}); + const room = roomsQuery.data?.rooms.find( + (candidate) => candidate.id === roomId, + ); + + const book = useActionMutation("create-booking", { + onMutate: async (input) => { + await queryClient.cancelQueries({ queryKey }); + const previous = queryClient.getQueryData(queryKey); + queryClient.setQueryData( + queryKey, + (old: { bookings: Booking[] } | undefined) => + old && { + bookings: [ + ...old.bookings, + { ...input, id: "pending-" + Date.now(), status: "confirmed" }, + ], + }, + ); + return { previous }; + }, + onError: (error, _input, context) => { + queryClient.setQueryData( + queryKey, + (context as { previous?: unknown } | undefined)?.previous, + ); + toast.error( + errorCode(error) === "booking_conflict" + ? t("rooms.conflict") + : (actionErrorMessage(error) ?? t("rooms.createFailed")), + ); + }, + onSuccess: () => { + setTitle(""); + toast.success(t("rooms.bookingCreated")); + }, + }); + + const cancel = useActionMutation("cancel-booking", { + onMutate: async ({ id }) => { + await queryClient.cancelQueries({ queryKey }); + const previous = queryClient.getQueryData(queryKey); + queryClient.setQueryData( + queryKey, + (old: { bookings: Booking[] } | undefined) => + old && { + bookings: old.bookings.filter((booking) => booking.id !== id), + }, + ); + return { previous }; + }, + onError: (error, _input, context) => { + queryClient.setQueryData( + queryKey, + (context as { previous?: unknown } | undefined)?.previous, + ); + toast.error(actionErrorMessage(error) ?? t("rooms.cancelFailed")); + }, + onSuccess: () => setPendingCancelId(null), + }); + + function submit(event: React.FormEvent) { + event.preventDefault(); + const start = new Date(startsAt); + const end = new Date(endsAt); + if ( + !title.trim() || + Number.isNaN(start.getTime()) || + Number.isNaN(end.getTime()) || + end <= start + ) { + toast.error(t("rooms.invalidRange")); + return; + } + book.mutate({ + roomId, + title: title.trim(), + startsAt: start.toISOString(), + endsAt: end.toISOString(), + }); + } + + const days = Array.from({ length: 7 }, (_, index) => { + const date = new Date(range.start); + date.setDate(date.getDate() + index); + return date; + }); + const bookings = data?.bookings ?? []; + + function moveWeek(amount: number) { + const next = new Date(range.start); + next.setDate(next.getDate() + amount * 7); + setSearchParams({ week: dateKey(next) }); + } + + if (roomsQuery.isPending || isPending) { + return ( +
+ {Array.from({ length: 7 }, (_, index) => ( + + ))} +
+ ); + } + if (!room) { + return ( +
+

+ {t("rooms.roomNotFound")} +

+ + {t("rooms.backToRooms")} + +
+ ); + } + + return ( +
+
+
+ + {t("rooms.backToRooms")} + +

+ {room.name} +

+ {room.capacity ? ( +

+ + {room.capacity} {t("rooms.seats")} +

+ ) : null} +
+
+ + + {new Intl.DateTimeFormat(undefined, { + month: "short", + day: "numeric", + }).format(range.start)} + + +
+
+ +
+
+ + setTitle(event.target.value)} + maxLength={100} + required + /> +
+
+ + setStartsAt(event.target.value)} + required + /> +
+
+ + setEndsAt(event.target.value)} + required + /> +
+ +
+ +
+ {days.map((day) => { + const dayBookings = bookings.filter( + (booking) => dateKey(new Date(booking.startsAt)) === dateKey(day), + ); + return ( +
+

+ + {new Intl.DateTimeFormat(undefined, { + weekday: "short", + }).format(day)} + + +

+
+ {dayBookings.length ? ( + dayBookings.map((booking) => ( +
+
+ + + + {booking.title} + + + +
+ {!booking.id.startsWith("pending-") ? ( + + ) : null} +
+ )) + ) : ( +

+ {t("rooms.emptyDay")} +

+ )} +
+
+ ); + })} +
+ + { + if (!open) setPendingCancelId(null); + }} + > + + + {t("rooms.cancelBookingTitle")} + + {t("rooms.cancelBookingDescription")} + + + + {t("rooms.keepBooking")} + { + if (pendingCancelId) cancel.mutate({ id: pendingCancelId }); + }} + > + {cancel.isPending + ? t("rooms.cancelling") + : t("rooms.confirmCancel")} + + + + +
+ ); +} +``` + +The booking mutation reports `booking_conflict` through `fail()`; the route +shows the localized conflict toast and rolls back its optimistic row. The cancel +mutation removes the booking optimistically and the query refresh confirms the +released slot. The mutation hook refetches action queries after success. + +## Shell edits + +`app/components/layout/Sidebar.tsx`: add `IconDoor` to the existing +`@tabler/icons-react` import, then add this inside `