CLAUDE.md · git:20261111.6107e23 · 2026-11-11 · sha256 907669dbc32e2312
CLAUDE.md git:20261111.6107e23A
Immutable. This exact content never changes and is served at /api/v1/blob/907669dbc32e2312.
# agentes.chat
A Slack/Teams-style workspace where people and AI agents work together. This file is for contributors and their coding agents: the engineering rules and where things live. Start with `README.md`, `CONTRIBUTING.md` and `SELF_HOSTING.md`; architecture decisions are in `docs/adr/`.
Product name in code and docs: **agentes.chat**. Package scope `@agenteschat/*`. The product has its own design system (`docs/design`): buttons, inputs and icons are all original, so reuse its components instead of generic ones.
## Stack
Bun + Hono + Drizzle on the server, Vite + React + TanStack on the web, Bun's native WebSocket, Better Auth (ADR 0011). PostgreSQL is the only required dependency (ADR 0005).
Licensing: AGPL-3.0-only for everything public, contributions under the same license, no `ee/` directory (ADR 0002). `packages/setup` (`@agenteschat/setup`) is the one MIT package. Self-hosting is docker-compose and free (`SELF_HOSTING.md`); agentes.chat Cloud runs this same image, configured by env vars. Any external service is optional, switched on by an env var behind an interface or module (swappable adapters).
## Concepts
- Organization (multi-tenant): everything has an `org_id`. The organization's context goes into every agent's prompt.
- Agent: role, instructions, model, credential, connectors and scopes, budget, responsible person.
- Provider credentials live at the organization level, encrypted; an agent points at one (or at the platform key).
- Router: a cheap, fixed model decides who answers (0 to 2 agents). It never grants permissions.
- Connectors in two layers: the organization connects an MCP server once; each agent gets a subset of its scopes.
- Sensitive actions (merge, deploy, rollback) always become a human approval request in the chat.
- Issues, Drive (reports, org chart, tables, diffs) and routines through scheduled jobs.
## Non-negotiables
- PostgreSQL is the only required dependency (no Redis/BullMQ in core). Jobs = Postgres outbox, in-process workers (ADR 0005).
- `apps/` and `packages/` never import `ee/` or any cloud package (`bun run check:boundaries`). With no contributor license agreement, anything in the server process must be AGPL, so Cloud-only behavior is public code switched on by env vars (through `AgentesModule` and adapters) or a separate service over the network, never a private in-process module (ADR 0002).
- Every tenant-owned table has `org_id` (a test enforces it).
- Never expose keys to a client: every model and MCP call goes through the backend.
- Model calls go only through the Model Gateway (`packages/engine/src/gateway.ts`): budget checked before the call, tokens and cost recorded with `org_id` and `agent_id`. Provider keys are encrypted per org (envelope encryption) and never returned to clients (ADR 0007).
- Env vars only in `packages/config/src/schema.ts`, then `bun run docs:env` (regenerates `.env.example`).
- Committed migrations are immutable: any change goes in a new migration (`bun run db:generate <name>`).
- Every file is public, comments included: cite the ADR or state the reason itself, never an internal planning id, prototype screen or internal name (`bun run check:boundaries` fails on them).
- A new architecture decision, or a change to one, gets an ADR in `docs/adr/`.
## Tests and local development
- Unit tests are required. They run on in-memory PGlite and fakes (a fake model provider from `@agenteschat/providers/testing`): no Docker, no local Postgres, no `.env`, no network.
- Real credentials go only in `.env` (only `dev`/`start` read it). Local development uses its own `DATABASE_URL`, never a production one.
- To fix a failure, run one test file (`bun test path/to/file.test.ts`); CI runs the full suite.
## Commands
`bun run ci:local` (every CI check but the image boot) · `bun test` · `bun run typecheck` · `bun run lint` · `bun run format` · `bun run check:boundaries` · `bun run check:licenses` · `bun run db:generate <name>` · `bun run docs:env` · `bun run dev`
Run lint, typecheck, tests and boundaries before declaring work done.
## Map
- Boot: `apps/server/src/start.ts` (`startServer`: config → DB → migrations → adapters + module overrides → HTTP + WebSocket → workers). Self-host entry: `src/main.ts`.
- HTTP app: `apps/server/src/app.ts` (`createApp`, testable via `app.request`). Private web-app API: `src/routes/app/*` (`/api/app/*`, `createRoute` from `@hono/zod-openapi`, cookie session + CSRF in `routes/app/context.ts`). OpenAPI at `/api/openapi.json`. Every `/api/*` body is capped before a route reads it (`src/http/body-limit.ts`: 8 MiB, a route that takes more gets a line there).
- Operator API (ADR 0056): its own listener on `OPERATOR_API_PORT`, only with `OPERATOR_API_TOKEN` (bearer), at `/api/operator/v1`: `apps/server/src/operator/*`, reads in `packages/engine/src/operator.ts`, events feed (`operator_events`, recorded only with the token: `enableOperatorEvents`) in `operator-events.ts`, review blocks (the only content, each read recorded) in `operator-review.ts`, workspace standing (`hold` stops the agents, `suspended` the workspace and its running work; enforced in the gateway, hub, executor, routines, router, judge and permission checks), agent hold and account block (`getMembership` reads a blocked account as no member; no session in `auth.ts`) in `standing.ts`, external provisioning (`MACHINE_PROVISIONING=external`: requests, progress, the workspace's `managed` computer and its single-use code, ready on its first hello) in `machine-provisioning.ts`, and its standby (asleep while nobody uses it, woken by whatever wants it: `wantMachine`, `machine.wake_wanted`, `machineActivity`, ADR 0161) in `machine-wake.ts`. The contract is the committed `apps/server/test/operator-openapi.json` (a test compares it).
- Billing hooks (ADR 0079; the server knows no plan, price or currency): billing holds in `standing.ts` (`BILLING_HOLDS` `payment`/`unpaid`/`ended`, `setBillingHold`: a shown hold, never over a trust hold; `createOrganization`'s `org.create_unpaid` and `holdForPayment`), the signed link to the billing service in `billing-link.ts` (`BILLING_URL`, `BILLING_LINK_SECRET`; route `routes/app/billing.ts`), and four limits in `limits.ts` (members under the `org-members` lock in `joinOrganization`; storage and a day's uploads before any blob is written, in `writeBlob` and skills' `planFiles`, a workspace's own bucket skipped, and storage alone when files come back, `restoreArtifact` and `startMigration`; the platform AI cap: `platformCapJudge`, the Jev router's `platformCapReached`, `platform_ai.threshold` events). Operator routes `apps/server/src/operator/limits.ts` (`PUT /orgs/{orgId}/billing-hold`, `/limits`; `GET /orgs/{orgId}` adds `limits` and `meters`); app `GET …/limits`; web `components/Limits.tsx`, `BillingLinkButton.tsx`; client `lib/billing.ts`, `lib/limits.ts`.
- Auth: `apps/server/src/auth.ts` (Better Auth at `/api/auth/*`). Orgs, roles, invitations, sign-up policy: `packages/engine/src/organizations.ts`.
- Invitations (ADR 0068, 0072, 0090): email invitations (links derived from their id, the batch with a role per address, channels and a note, previews that know how the address signs in, dead-link states) in `organizations.ts`; the workspace link, requests to join (the password a proven ask chose, the account an approval makes, the claim that signs the asking page in), members' suggestions and the inviter's `invitation_accepted` notice in `invite-requests.ts`; routes `apps/server/src/routes/app/invites.ts`, `management.ts`, `account.ts`; web `pages/InvitePage.tsx`, `pages/MembersPage.tsx` and the invite dialog.
- Deleting a workspace or an account (ADR 0088): `packages/engine/src/workspace-deletion.ts` (`scheduleDeletion`/`closeForDeletion`: closed at once, the date 7 days out, the emails and `org.delete` at the date; `restoreWorkspace` before the date; `purgeWorkspace`: AI accounts off its computers, Composio and GitHub grants revoked, `PURGED_BY_HAND` and the cascade in one transaction; `keptFromDeletion` and the operator's `setDeletionHold`, route in `apps/server/src/operator/standing.ts`; the hourly `enqueueOverdueDeletions`, the workers' `deletions` tick; `accountDeletionPlan`), closed as one predicate in `standing.ts` (`closedRefusal`, `workRefusal`, `openOrg`: `org.deleting`), the proof in `apps/server/src/auth.ts` (`deletionProof`: the code emailed by `sendDeletionCode`, spent by `spendDeletionCode`, with every emailed code's rules in `packages/engine/src/email-codes.ts`; the password only where no email goes; adding a password needs a recent sign-in, which a session minted from another keeps, also in `desktop-sign-in.ts`), routes in `routes/app/account.ts` (`POST`/`DELETE …/organizations/{orgId}/deletion`, `POST …/deletion/code`, `GET /account/deletion`, `POST /account/deletion/code`, `DELETE /account`), and in `organizations.ts` `deleteAccount` and `removeMember` (a person's own computers leave with them: `personalMachines` in `machines.ts`).
- Roles and permissions (ADR 0085): keys and areas in `packages/engine/src/permissions.ts` (`PERMISSION_AREAS`, `maySql`, `membersWhoMaySql`); roles, hierarchy and who holds what in `roles.ts` (`org_roles`, `organization_member_roles`; `everyone` is every member's base, the owner is a flag on `organization_members`); `getMembership` resolves a person's keys and every check is `can(membership, key)` / `requirePermission`; routes `apps/server/src/routes/app/roles.ts`; the apps read `permissions` on each workspace through `can(org, key)` (`packages/client/src/lib/permissions.ts`, screen helpers in `lib/roles.ts`); web `components/roles/RolesSection.tsx`, the role's mark `RoleMark` (packages/ui).
- WebSocket: `apps/server/src/realtime/ws.ts` (`/api/ws?orgId=`; subscribe per channel; events in `packages/engine/src/events.ts`).
- Workers: `apps/server/src/workers.ts`. Job handlers: `packages/engine/src/jobs.ts`; outbox: `outbox.ts`.
- Freeze watch: `apps/server/src/freeze-watch.ts` starts a worker thread (`freeze-watch-worker.ts`, its own entry in the native bundle) that logs an error, reported, when the main thread's beat stops for 5 s, naming the jobs and tool calls in flight; the outbox's `runJob` and the gateway's `outputOf` record them in shared memory (`@agenteschat/adapters/in-flight`).
- Right hand (ADR 0137): `packages/engine/src/right-hand.ts` (creation, guards, owner, mentions, each person's own AI `right_hand_brains`, §11), `right-hand-prompt.ts`, what it sees `team-status.ts`, settings proposals in `settings-proposals.ts` and `context/proposals.ts`; apps read it through `packages/client/src/lib/right-hand.ts`.
- Agent flow: `messages.ts` (post + mentions + outbox) → `dispatch.ts` (runs; what agents start on their own is held past its stretch's limits, `stretch.ts`, ADR 0089) → `executor.ts` (context from `context.ts`, gateway, deltas, persist; a run that goes in circles stops, `stuck.ts`, ADR 0015) with states in `runs.ts`. How every turn ends (continue, wait, ask, done) and who hears a failed run: `continuation.ts` (ADR 0097). Cancel and "stop and send" (turn interrupt) in `cancel.ts`, "Continuar" in `continue-run.ts`; read receipts for messages sent mid-run: `packages/client/src/realtime/steer.ts` (ADR 0029).
- Agents asking and handing work to each other (`ask_agent`, `tell_agent`, ADR 0034, 0095): `consultations.ts` (every note a row in `agent_consultations`, `kind` `note`; results come back once per turn, `reportHandOffs`; roll-up between agents, `handBack`; no expiry while a colleague works, `expireConsultations`; "# Work you handed off here" from `handOffsFrom`, drawn in `context.ts`).
- Delivery (nothing sent to an agent is lost): run inbox `run-inbox.ts` (status-guarded queue, release on every ending, sweeper); events to an agent's conversation only through `deliverNotice` (`delivery.ts`, `meta.notice`, text in `notices.ts`); after a message lands in a run, `steering.ts` (`afterSteered`: stop-and-send → live delivery `live-steer.ts` / runner `brain.steer` → waits `waits.ts` → fast reply `talker.ts` → stop judge). A run waiting on an approval, a secret or a mission's decision takes no new messages (`run-hold.ts`): they get a run of their own. Silence and `pass`: `reply-policy.ts` (NO_REPLY never posted). Routines are background runs (`agent_runs.background`) in their own room, speaking only through `hand_off` (`hand-off.ts`). `ask_agent` is async by default; `tell_agent` in `consultations.ts`; the questions a run asked show inside its reply (`consultationsIn`, `GET …/consultations`, `agent.consultation`; `packages/client/src/lib/consult-group.ts`, web `components/ConsultGroup.tsx`, phone `features/chat/ConsultGroup.tsx`; ADR 0034 addendum 2026-10-29), each opening the two agents' conversation read only in the thread panel (`consultationConversation`, `GET …/consultations/{id}`, web `components/ConsultationPanel.tsx`, phone `features/chat/ConsultationScreen.tsx` on its own screen; addendum 2026-10-30).
- Routines and unattended work (ADR 0053): who is behind a run is one gate, `authority.ts` (person, routine or unattended; every "who asked" helper uses it); what each may do is one table, `tools/run-policy.ts`, enforced by the Tool Gateway on every brain (approvals carry a required `why` and an `origin`); computer brains get the matching profile per turn (`apps/server/src/engine.ts`, runner `brain.ts`/`brain-codex-app.ts`, `packages/adapters/src/command-policy.ts`). A routine fires a background run in its own room with a brief (`routine-brief.ts`, `routine-room.ts`); firing rules in `routine-firing.ts`, `routine-events.ts`, `routine-state.ts`, `routines.ts`; every ending goes through `closeRoutineRun` (`routine-ledger.ts`). Outside text reaches models only through `untrustedBlock` (`untrusted.ts`).
- Credentials and crypto: `packages/engine/src/credentials.ts`, `crypto.ts`. Model catalog and prices: `packages/providers/src/catalog.ts` (`PROVIDERS`; one adapter each: `createModelProviders` in `index.ts`); Anthropic adapter `anthropic.ts`, also DeepSeek, Kimi, Z.ai and MiniMax through `compat`; Gemini adapter `gemini.ts` (Interactions API, stateless); fake for tests `fake.ts` (`@agenteschat/providers/testing`).
- Provider logos (ADR 0059): the makers' marks as path data in `packages/ui/src/brand/marks.ts` (`PROVIDER_MARKS`, `markOf`), drawn by `ProviderLogo` (`packages/ui`, web and desktop; `BrainLogo` wraps it) and `apps/mobile/src/ui/ProviderLogo.tsx`.
- People's portraits (ADR 0166): a recipe drawn on a 32×32 grid by `packages/ui/src/person/engine.js` (`drawPerson`, `encodeRecipe`/`decodeRecipe`, `CATALOG` per build), shown by `PersonPortrait` and by `Avatar` when the photo's address carries one (`#px=…`, kept by `setAvatar` in `packages/engine/src/avatars.ts`); the question ("Build an avatar" or "Upload a photo") and the builder are `apps/web/src/components/AvatarBuilder.tsx`, opened by "Change photo" in the profile.
- Coding plans as key accounts (ADR 0059 §8, protocol 20): pure data in `packages/providers/src/plans.ts` (`@agenteschat/providers/plans`: base URL, key variable, model per alias, usage endpoint), read by the runner (`accounts.ts` keeps the key in `provider.json`; `brain.ts` pins the endpoint in its own `--settings`), the engine and the apps (`@agenteschat/client/lib/plans`); "Contas de IA" is `apps/web/src/components/ai/AiAccounts.tsx` (`GET …/ai-accounts`, `listAiAccounts`), connecting one `ConnectAiSteps.tsx` and `AddAccountFlow.tsx`. System mode lends folders to agents' users (`AccountManager.lendTo`, `keepLent`).
- Plan usage (ADR 0059 §7, protocol 19): read on the computer, never with a token, by `apps/server/runner/plan-usage.ts` (turns' `rate_limit_event`s, the `get_usage` and `account/rateLimits/read` probes, coding plans' endpoints) and kept by the runner's `AccountManager` (`accounts.ts`); stored per account (`machine_accounts.usage`) and for the computer's own sign-ins (`machines.executors.ownUsage`) by `packages/engine/src/machine-accounts.ts` (`refreshAiAccounts`: `POST …/ai-accounts/refresh`); drawn by `PlanMeter` (`packages/ui`).
- Live blocks and polls (ADR 0113): `show_block`, `start_poll` and the rest in `packages/engine/src/blocks.ts` (kinds `block` and `poll`, `artifacts.in_drive` false, `polls`, `poll_votes`, `POLL_CLOSE_JOB`, notice `poll_result`); a block is parts the apps draw (`spec`: checked and drawn by `packages/ui/src/blocks/spec.ts`, formulas in our own language `expr.ts`, the same on the server; web and phone `SpecBlock.tsx`, state through `useBlockValues`; the agent reads what it shows, `blockShows`), or the agent's own page behind a click (`html`): the kit inside every frame `packages/client/src/lib/block-kit.ts`, the page and what a frame may say `lib/blocks.ts`, the policy `lib/isolated-page.ts`; web `apps/web/src/components/blocks/*` (`ArtifactCard` hands them over), phone `apps/mobile/src/features/blocks/*` (`MessageFiles`, route `block/[id]`).
- Usage views (ADR 0063): plan rows record their account (`usage_records.machine_id`, `brain_account_id`); `packages/engine/src/plan-usage.ts` (`orgPlanUsage`, `agentPlanUsage`: windows with each agent's estimated part, month by account and day); routes `apps/server/src/routes/app/plan-usage.ts`; web `components/PlanUsage.tsx` (Configurações › Uso) and `pages/agent/UsageTab.tsx`; `UsageDays` in `packages/ui`. An agent on a plan shows its account's limits where the budget was (§5): the agent list's `brain.account`/`brain.usage` (`agentBrainSummaries` in `brain-settings.ts`), the rule `usageShown` (`packages/client/src/lib/plan-usage.ts`), the line `planLine` drawn by `PlanMeter compact` (and the phone's twin in `features/usage/parts.tsx`).
- Usage report (ADR 0060 §5): what it holds and the switch in `packages/engine/src/telemetry.ts` (`buildTelemetryReport`, `telemetrySends`, `isAgentesCloud`, row `instance_telemetry`: switch, due time, host samples); sender, host sampler and `agentes telemetry` (`main.ts telemetry`) in `apps/server/src/telemetry.ts`; the owner's switch `routes/app/telemetry.ts` (card in Settings → General); sizes, container limits and loads `packages/adapters/src/host-stats.ts`, from runners on protocol 22 (`hello.size`, `pong.load` → `machines.size`/`load`).
- Adapters (search, pub/sub, presence, rate limiter, key wrapper, platform credentials): `packages/adapters/src`. Module API: `packages/modules/src/index.ts`.
- DB schema: `packages/db/src/schema/*`; migrations `packages/db/migrations` (0000 is hand-edited for `messages` partitioning, ADR 0009). Import Drizzle operators from `@agenteschat/db`, never `drizzle-orm` directly.
- GitHub App (ADR 0033, 0156): tokens, bot, uninstall and reconcile in `packages/engine/src/git/github-app.ts`; binding, removal, webhook in `github-app-installs.ts`; the server's app (env or made with the manifest flow, `instance_secrets` `github_app`) in `github-app-settings.ts`; who each GitHub call goes as in `github-call.ts` (used by `connectors/mcp.ts`); the signature and `Co-authored-by` in `signature.ts`; the app alone as a connection (`auth_type = github_app`) in `connectors/connections.ts` (`syncGitHubAppConnection`); routes `apps/server/src/routes/github-app.ts`; screens: what the panel shows `packages/client/src/lib/github-app.ts`, web `GitHubAppPanel.tsx` (panel and the server's app card) and `ConnectFlow.tsx` (the app first), phone `features/connectors/GitHubApp.tsx`.
- Tools and approvals: `packages/engine/src/tools/*` (Tool Gateway, scopes, JSON Schema), `approvals.ts`; approved ahead for a routine's run (`schedule_action` in `schedule-tools.ts`, the gateway's `prepareAhead` and `aheadFor`, ADR 0015 addendum); runs are tool loops with an append-only transcript (`executor.ts`). Connectors (MCP): `src/connectors/*`; services through Composio (ADR 0107): a preset's `composio` way (`presets.ts`), sessions, Connect Links and the per-workspace count of calls in `connectors/composio.ts`, `bun run composio:check` before one ships. Router: `router.ts` (the chain and its rules, ADR 0074), `router-jev.ts`, `router-plan.ts` (the author's own plan, runner op `brain.route` in `apps/server/runner/brain-route.ts`). Jev's key: `jev-key.ts` (ADR 0073).
- Connector usage (ADR 0103): keys, per-call counts and the operator's reads in `packages/engine/src/connector-usage.ts` (`connectorKeyOf`, `countToolCall` from the Tool Gateway, `countComposio` from Composio's `onExecute` through `composioUsageHook`, and from its webhook, `countComposioConnection` when a mailbox connects), every connector tool's `connector` field, tables `connector_usage_days` and `composio_usage_days`; routes `apps/server/src/operator/analytics.ts`. Agent work analytics (ADR 0127): `packages/engine/src/work-analytics.ts`.
- Presence and status (ADR 0084): people's availability (auto, away, busy, hidden: offline to others) and line in `packages/engine/src/member-status.ts` (`PUT …/me/status`, `/people`; connect/disconnect `announcePresence` in `realtime/ws.ts`); agents' presence from their work and their line in `agent-status.ts` (`loadAgentStatuses`, checked on read: heartbeat, waits, ends; Jev picks a line among `statusCandidates`, rates its worth and the work in a request of its own beside the run (`askRunStatus`, `startRunStatus`), `followWork` from `invokeWithChip`, the `set_status` tool, `GET …/agent-status`); events `member.status`/`agent.status`; shared `packages/client/src/lib/presence.ts`, pixel badge `packages/ui/src/presence/badge.ts` (web `PresenceBadge` in Avatar, `StatusDialog.tsx`; phone `src/ui/PresenceBadge.tsx`, `src/features/status/*`).
- Task manager (ADR 0128): the read `packages/engine/src/task-manager.ts` (`taskManager`: tasks the caller sees with what each uses now from its latest `tool_call` step, ended today, `agentActivity`; `taskSteps` for "Ver passos" without usage access), routes `GET …/task-manager`, `GET …/task-manager/{id}/steps` and `POST …/runs/{id}/stop-reason` in `routes/app/management.ts`; a stop tells the agent through `run-stopped.ts` (`tellAgentStopped`, a `run_stopped` notice that wakes nothing; `cancelRun` takes `reason`, `tell: false` for stop-and-send); client `lib/task-manager.ts`, `useTaskManager`/`useStopTasks`/`useStopReason`.
- Who sees what (ADR 0151): `packages/engine/src/task-access.ts` (`taskSeenSql`, `adminChannelSql`), one `Audience` for tasks and wiki pages; administrators read every channel in `requireChannelAccess`, never a DM.
- Notifications: `packages/engine/src/notifications.ts` (inbox, grouping, counts, auto-resolve) and `notification-producers.ts` (hooks per flow; chat via the `notifications.message` job); routes `apps/server/src/routes/app/notifications.ts`; per-user realtime on `userTopic`.
- Início and what opens when the app starts (ADR 0108): `organization_members.start_page`, `setStartPage` (`organizations.ts`) at `PUT …/me/start`, sent in `GET /me`; shared rules `packages/client/src/lib/home.ts`; web `apps/web/src/pages/HomePage.tsx`, routing in `routes/org.$orgId.index.tsx` and `lib/start.ts`; phone `features/me/useStart.ts`, first steps on Conversas `features/chats/FirstSteps.tsx`.
- Sounds (ADR 0070): synthesized in `packages/ui/src/sfx/synth.ts` (`@agenteschat/ui/sfx`, `renderSound`, `wavBytes`); which event plays what in `packages/client/src/lib/sounds.ts` (`playSound`, `soundForNotification`); players `apps/web/src/lib/sounds.ts` (Web Audio; account menu) and `apps/mobile/src/lib/sounds.ts` (expo-audio, WAVs in the cache; Você › Sons).
- Phone app (ADR 0035): app sessions = no `Origin` + `X-Agentes-Client: mobile` + cookie (`requestOriginAllowed` in `routes/app/context.ts`, also the WS upgrade), Expo and Apple sign-in in `auth.ts`, a provider's sign-in through the phone's browser tied to the app by a challenge and a one-time code in `phone-browser-sign-in.ts` (app side `apps/mobile/src/lib/auth.ts` `signInWithBrowser`); push = `push_devices`, `packages/engine/src/push.ts` (`push.send` job, enqueued from `notify`) + `push-messages.ts` (pt-BR/en text), `PushSender` in `packages/adapters/src/push.ts` (`createPhonePushSender`: Android straight to FCM `push-fcm.ts` or through the push relay `push-relay.ts` per `PUSH_SENDER`, the relay's side in `packages/engine/src/push-relay.ts` and `apps/server/src/routes/push-relay.ts` with `PUSH_RELAY_SERVE`, ADR 0152; iPhones through Expo), routes `routes/app/push.ts`; account deletion `deleteAccount` (`organizations.ts`) at `DELETE /api/app/account`; glass chat header `apps/mobile/src/features/chat/HeaderPill.tsx`; connectors `src/features/connectors/*` with OAuth handed back to the app (`packages/engine/src/connectors/oauth-return.ts`, `POST …/connectors/oauth/complete`); links that open the app `apps/server/src/app-links.ts` (`/.well-known/*`), invitation/reset/first run `src/features/auth/InviteScreen.tsx`, `ResetPasswordScreen.tsx`, `src/features/onboarding/*`.
- Browser push (ADR 0071): Web Push with the server's own VAPID pair in `instance_push` (`packages/engine/src/web-push.ts`, sender + RFC 8291/8292 in `packages/adapters/src/web-push.ts`), `web` rows in `push_devices` belonging to their session (`session_id`, deleted with it; forgotten by `POST /api/app/push/devices/forget`), sent by `deliverPush` (`push.ts`, also the 45 s hold while the person is in the app; a refused signature keeps the row), the contact in `vapidSubject`, the sender wired in `apps/server/src/start.ts` (`webPushSender`: DNS errors retry, refusals logged), service worker `apps/web/public/sw.js` (served by `/sw.js` in `app.ts`), page side `apps/web/src/lib/web-push.ts` + `components/WebPush.tsx` (account menu switch, never in the desktop app), clicks `lib/push-open.ts` + `components/NotificationOpen.tsx`; clear on read via realtime and `POST /api/app/push/stale` (`stalePushNotifications`).
- Desktop app main window (ADR 0036): the window loads the site itself, no app commands (`apps/desktop/src-tauri/src/main_window.rs`, `capabilities/main.json`); web side `apps/web/src/lib/desktop.ts`, `DesktopTitleBar.tsx`, `desktop.css`; Google/Apple sign-in through the browser = Better Auth plugin `apps/server/src/desktop-sign-in.ts` (`/api/auth/desktop/handoff` + `/redeem`, verifier/challenge) and route `desktop.sign-in.tsx`. "This Mac" bridge: `this_mac` (Rust checks + relays) → popover `apps/desktop/src/control/this-mac.ts`; web `ThisMac.tsx`. Menus: menu bar + system-drawn right click `apps/desktop/src-tauri/src/menus.rs` (labels from the popover); the right-click engine `apps/web/src/lib/context-menu.ts` (our `MenuAt` or the system's), host `components/DesktopMenus.tsx`. A connector's OAuth started in the window comes back through `agenteschat://desktop/connectors/oauth` (`packages/engine/src/connectors/oauth-return.ts` `desktop:` returns; `deep_link.rs` → web route `desktop.connector.tsx`).
- Agent browser (ADR 0040) and the screen layer (ADR 0054): tools `packages/engine/src/browser/tools.ts` (`browser_do` plans, targets in words, every action answers with what changed), the browser as a surface `browser/surface.ts` (settle + look; `browser.batch`/`browser.capture` on protocol 17, one `browser.act` at a time before); surface-agnostic layer for computer use `packages/engine/src/screen/*` (`observation.ts` snapshot → elements and diffs, `targets.ts` ref → exact → site memory → judge Choice → Jev Box on an image, `checks.ts` expect/until/find/dismiss, `plan.ts` `runPlan`, `report.ts`); images and Box questions in `judge.ts` (`JEV_VISION_MODEL`); runner `apps/server/runner/browser.ts`. Live view sockets (§7.1, protocol 49): the computer's data socket per watched browser `runner/browser-views.ts` (`BrowserViews`, `browser.view.open`, root's in system mode), frame bytes `encodeBrowserFrame` in `machine-protocol.ts` (apps' copy `packages/client/src/browser/frame-bytes.ts`), the broker hands it over (`StreamBrokerDeps.claim` → `claimView` in `browser/live.ts`), each person's frame socket `/api/browser/frames` (ticket, `createViewerPacer`) in `apps/server/src/realtime/ws.ts`, opened by `RealtimeConnection` (rates per view in `browser/watches.ts`; the phone stays on base64, `browserFrameSockets: false`); runner source pacing `pacing=ack` + `browser.room` (system mode); web `components/browser/LivePicture.tsx`. Desktop computer use (ADR 0062) reuses the layer: `ScreenSurface.kind` ("screen" in plans and reports), desktop verbs (`focus` on windows only, `double_click`, `right_click`, `drag`, `type`, `open` with `app`/`path`), `capture(region)` + `regions` for the close-up Box on small targets, `dismiss: false` (a covering dialog stops the plan); the runner's desktop helper `apps/server/runner/desktop-helper.py` (AT-SPI tree, xdotool input, pastes, XDamage settle and scrot as the agent's user, JSON lines, run as `python3 -I -c <source>`; types and command in `desktop-helper.ts`, Python tests `apps/server/test/runner/test_desktop_helper.py`, recorded snapshots in `test/runner/fixtures/desktop/`); the snapshot as screen text in `desktop-tree.ts` (`desktopLook`: occlusion, the agent browser as one line, escaped and redacted names and text, refs that stay; `observation.ts` reads a ref only from the brackets after the role and name); protocol 21 (`desktop.look`/`act`/`capture`/`apps`, `hello.desktopUse`) served by `desktop.ts` (`DesktopManager`: one helper per agent, only where this process is the agent's own OS user (`ownUserRefusal`), an action checked against fresh extents and the window stack, then input, settle and a look in one op, session-ending targets refused, idle stop, restarts), routed in `handlers.ts` behind the `desktop` and `commands` switches; in system mode they are the agent's worker's ops (`OP_ROUTES`), which gets the desktop from the supervisor (`WorkerLink.desktop` → `desktop.ensure`, answered only while it serves a desktop use request, or with `use: "browser"` a browser command the server put on the desktop); `desktop-check` times it (as the agent's user through its launcher in system mode). Engine side `packages/engine/src/desktop/*`: `tools.ts` (`createDesktopToolSource`: `desktop_do` plans, `desktop_read`, `desktop_screenshot` under `desktop:use`, offered and allowed on each call only with Run code, the org's code environment on and a computer serving desktop use; screen text in `untrustedBlock`; `dismiss: false`; a person in control holds it), `status.ts` (`agentDesktopUseStatus`), `surface.ts` (the desktop as a `ScreenSurface`, apps by name `pickApp`, web addresses refused for `browser_do`). The steps go on the message as `meta.desktop.steps` (`run-tools.ts` `desktopTrail` → `executor.ts`; client `desktopTrailOf`; web `BrowserTrailCard` with `screen="desktop"`), apps and files a plan opens in the audit log (`desktop.app_opened`, `desktop.file_opened`); whether a computer serves it on its page (`components/desktop/MachineDesktopUseCard.tsx`) and the agent's Work tab; eval `bun run eval:desktop:micro` (`packages/engine/eval/desktop/`, recorded scenes in `fixtures/`).
- Databases (ADR 0039, read-only Postgres): driver `packages/adapters/src/database.ts`; `packages/engine/src/databases/*` (connections + pool, per-agent rules, `guard.ts` with libpg-query, `pg_<slug>_*` tools); routes `apps/server/src/routes/app/databases.ts`; web `DatabaseConnect.tsx`, `DatabaseRules.tsx`, agent page `DatabaseAccess.tsx`.
- Team actions (ADR 0064): every outside action (gateway `external`, approved actions, computer commands that leave the machine) is a `team_actions` row with normalized targets, searchable (kind `action`); before the next one on the same target the gateway holds the call once and tells the agent (`team_action_checks`, shown under the reply via `meta.teamChecks`); workspace switch `organization_settings.action_check`. All in `packages/engine/src/team-actions.ts`, hooked in `tools/gateway.ts`; web `components/TeamChecks.tsx`.
- Dashboards and widgets (ADR 0135): schema `packages/db/src/schema/dashboards.ts` (`dashboards` with each person's `home` board, `dashboard_widgets`, `dashboard_widget_updates`; migration 0199); the block, checked once for every package, `packages/ui/src/widgets/spec.ts` (`@agenteschat/ui/widgets/spec`: `WidgetSpec`, `validateWidgetSpec`, `chartBlockToWidgetSpec`, schedules, sizes, caps); engine `packages/engine/src/dashboards/*` (who sees and edits `access.ts`, boards and widgets `service.ts`, Pin `pin.ts`, cost `cost.ts`, suggestions `suggestions.ts`, an agent's request to publish `proposals.ts`, agent tools `tools.ts`, ids-only events `events.ts`); a widget is redone by its own routine (target `widget`, ADR 0053): `refresh.ts` (`syncWidgetRoutine`, "Update now"/"Resolve" `refreshWidgetNow`, "Ask for a change", `update_widget`), `refresh-context.ts` (the run's brief), `refresh-fire.ts` (read by `routines.ts` as it fires), `refresh-ledger.ts` (endings, failures, history, alerts); notices `widget_alert`, `widget_failed`, `dashboard_proposal` in `notification-producers.ts`; routes `apps/server/src/routes/app/dashboards.ts` + `dashboard-schemas.ts`; client `packages/client/src/dashboards/*` (`openTarget`/`homeTarget` in `lib/notifications.ts`); drawing `packages/ui/src/widgets/*` (`WidgetCard`, `WidgetBody`, `ChartPieces.tsx`: the line and dither painter the chat's `ChartBlock` shares); web `pages/DashboardsPage.tsx`, `DashboardPage.tsx`, `components/dashboards/*`, `components/widgets/*` (`HomeMural` on Home, `WidgetPanel`, `PinToDashboard`); phone: a row on the home (Chats) `src/features/chats/DashboardsEntry.tsx` pushes `app/(app)/dashboards.tsx` (the tab bar has no Dashboards tab), pushed screens `board/[id]`, `widget/[id]`, `widget-new`, `widget-pin`, `board-*`, screens in `src/features/dashboards/*`.
- Audit log: `audit_log` holds people's changes (`recordAudit`, `audit.ts`; members, invitations, agents, connectors and AI keys included) and every agent tool call that matters as `tool.call` (`agent-audit.ts`: `auditsCall` decides, `auditInput` masks; written by the Tool Gateway on every brain, plus approval decisions in `approvals.ts`), with `run_id`, `channel_id`, `on_behalf_of_user_id`, `outcome`. Admins read it at `GET …/audit` (`listAudit`, `routes/app/audit.ts`) and in Configurações › Auditoria (words in `packages/client/src/lib/audit.ts`; web `apps/web/src/components/Audit.tsx`, the thread panel for a row's detail; phone `apps/mobile/src/features/settings/AuditScreen.tsx`, a pushed screen per row). The reader hides a tool's own rows that repeat the gateway's (`TOOL_CALL_ECHOES`) and cleans changes' details as they leave. Commands Claude Code or Codex run without asking stay on the computer (runner `activity.jsonl`).
- GIFs and stickers (ADR 0091): `meta.media` and the moods/categories in `packages/engine/src/media.ts` (`mediaOf`, `mediaSettings`); GIF search is an optional adapter (`packages/adapters/src/gifs.ts`, GIPHY with `GIPHY_API_KEY`; off agentes.chat also the key the pinned owner adds in Settings, kept like Jev's: `packages/engine/src/gif-key.ts`, `createKeyedGifs`, route `routes/app/gif-key.ts`, web `GifKeyCard.tsx`; whether GIFs exist now is `GifProvider.available()`), searched and served only by the server (`apps/server/src/routes/app/gifs.ts`: `…/gifs`, `…/gifs/{id}/media`); sending with `media` in `postPersonMessage`; agents send one when asked with their tools `send_gif`/`send_sticker` (`packages/engine/src/media-tools.ts`, `createMediaToolSource`: built in like `react`, listed by the workspace's switches, the agent's `media_replies` and the place, never by `agent_media`; a message of the run, three per run, an empty reply after it posts nothing via `Transcript.mediaSent`; refused to routines), and follow a light reply on their own only through the post-reply job `agents.media` (`packages/engine/src/agent-media.ts`: code gates, skipping a run that sent one with its tools, one calibrated Jev judgment, a silent message with `meta.mediaAfter`; eval `bun run eval:media`); the picker's tabs in `packages/ui` (`EmojiPicker`), stickers drawn by `AgentSticker` from the agent engine; settings `organization_settings.gifs|gif_rating|agent_stickers|agent_media`, `agents.media_replies`.
- Voice messages (ADR 0100): speech adapters `packages/adapters/src/speech.ts` (`SpeechEngine`, `createSpeechEngine`) (a server of one's own, `local`, is told the workspace in `X-Agentes-Org`, gets `LOCAL_SPEECH_API_KEY` and, with `LOCAL_SPEECH_WARM=on`, `warm` when `/voice/allowed` says yes); chain and the owner's key `packages/engine/src/speech-settings.ts`; `packages/engine/src/voice.ts` (recording stored, job `voice.transcribe` posts it through `postPersonMessage` with `meta.voice`, fair use, `sweepExpiredVoice`); table `voice_clips`; routes `apps/server/src/routes/app/voice.ts`. The words are `messages.body`: anything that lists a message goes through `readableBody` (`message-preview.ts`).
- Routines started by a webhook (ADR 0106): `packages/engine/src/routine-hooks.ts` (address, signing secret, calls), public `POST /api/hooks/{token}` in `apps/server/src/routes/webhooks.ts`, managers' routes in `routes/app/routines.ts`; web `WebhookPanel` in `RoutinesPage.tsx`, phone `features/routines/WebhookCard.tsx`.
- Vault (ADR 0144): logins, keys and contacts, personal or the team's (audience + agents, checked at every use by `vault/access.ts`); schema `packages/db/src/schema/vault.ts`; engine `packages/engine/src/vault/*` (items, connections + `vault.sync`, CSV import, uses, agent tools `vault_list`/`vault_save`/`vault_delete` in `tools.ts`); sources behind `packages/adapters/src/vault/source.ts` (built-in in the engine, `onepassword.ts`, `bitwarden.ts`, modules via `vaultSources`), the site rule `vault/site.ts`; a login is sealed to a one-use key in the runner's memory (`vault.key`, `agentes:type_vault`, `exec.vault`, protocol 45, `apps/server/runner/vault.ts`, AAD `vaultAad` in `secret-box.ts`); passwords agents make (`browser_make_password`, `vault_make_password`, `vault.password`, protocol 47, `saveMadePassword`, ADR 0144 §8); routes `routes/app/vault.ts`; client `packages/client/src/vault/*`; web `components/vault/*`; phone `features/vault/*`; the request card's "Save to the Vault" (`POST …/secret-requests/{id}/vault`).
- Search and memory: `search.ts` + `packages/adapters/src/search.ts` (hybrid Postgres; vectors from `packages/providers/src/embeddings.ts`, env-gated `EMBEDDINGS_*`, ADR 0167); `src/context/*` (items, summaries, reflect, consolidate, feedback, proposals, outcomes, agent tools, trust backfill, scorecard). Learning on their own (ADR 0120): `context/learn.ts` (trust, turn-end trigger, `context.learn` job), `context/learned-skills.ts` (`update_skill`, promotion, sharing, skill decay). DMs: `dms.ts`.
- Mailboxes for agents (ADR 0038): `packages/engine/src/mail/*` (accounts, per-agent policies, tools, `inbound.ts`: Composio's webhook, IMAP polling); adapters `packages/adapters/src/mail.ts` (contract), `composio.ts`, `imap.ts`; routes `apps/server/src/routes/app/mail.ts`, `POST /api/webhooks/composio`; web `MailConnect.tsx`, phone `features/connectors/MailboxSheet.tsx`.
- Emails (ADR 0069): kinds and producers `email.ts`; `packages/engine/src/email/*` (one layout, words in both languages, inert text); senders `packages/adapters/src/email.ts` (MillionSend or SMTP, via outbox); art in `apps/web/public/email/` (served at `/email/*`); preview `packages/engine/scripts/email-preview.ts`.
- Connected computers (ADR 0025): rows, pairing, targets `packages/engine/src/machines.ts`; socket hub (local + cross-replica `machine_rpc`) `machine-hub.ts`; provider `machine-provider.ts`; Bun socket `apps/server/src/realtime/machines.ts`; routes `apps/server/src/routes/machines.ts`; runner `apps/server/runner/`.
- Session screening (ADR 0076, Cloud only, `SESSION_SCREENING`): `packages/engine/src/session-screening.ts` (segments in memory, read through the operator review door), runner op `desktop.text` (`apps/server/runner/desktop.ts`).
- AI accounts on computers (ADR 0041, 0059): `packages/engine/src/machine-accounts.ts` (owner bound when the sign-in starts, `signing_in`/`removing` rows, tombstones on removal and when a person leaves), routes `apps/server/src/routes/app/machine-accounts.ts` (`account-logins`), runner `apps/server/runner/accounts.ts`; account folders are secrets in `command-policy.ts` (`runnerHome` in the scope). One sign-in for all of an owner's agents (protocol 29, `machine_accounts.shared`, `sharesSignIns`, `SHARED_SIGN_INS` in `plans.ts`): in system mode root keeps it (`claude setup-token` in a PTY, its screen read by `Screen`; `AccountManager.grant` → root's `grant` on the worker's request → the agent's own folder for it, `agentAccountHome`, the token on descriptor 3, `TOKEN_FD_ENV`, never in an env; `worker.state.account` closes the worker's processes on any other account, `BrainManager.keepAccount`; turns' usage back as `usage` link frames).
- Agent desktops and terminals (ADR 0058): protocol 18 in `machine-protocol.ts` (`desktop.session.*`, `stream.open`, the data socket's `stream.hello`/`parseStreamControl`, `STREAM_LIMITS`, `STREAM_CLOSE`); machine switches `access.tools.desktop`/`terminal`; scope `desktop:use` (`tools/scopes.ts`, only with `sandbox:run`; run-policy area `desktop`); screen `desktop` in `browser/handoff.ts` (`desktop_ask_person`; the browser and the desktop share one window when its Chrome runs there: `openHandoffOn`, `browserOnDesktop`). Who may control a desktop or open a terminal: `drivesComputer`/`requireComputerDriver` in `machines.ts` (the pairer; admins and the owner in system mode, `executors.mode`, only the owner while the agent's user holds their sign-in, ADR 0059). Streams: broker `packages/engine/src/streams.ts` (viewer ⇄ data socket, caps, pings, 30 s recheck), who/where/audit/REST/control `desktop.ts` (`authorizeStream`, `recheckStream`, `desktopTarget`, `desktopStatus`, `createDesktopControl`: control changing hands closes the streams it hides, keep-alive), routes `apps/server/src/routes/app/desktop.ts`, Bun glue `apps/server/src/realtime/streams.ts` (`/api/desktop`, `/api/terminal`, `/api/machines/stream`). Runner: `apps/server/runner/desktop-session.ts` (`DesktopSessions`: Xtigervnc + XFCE per agent on a Unix socket, displays in `slots.json`, taken back after a restart, restarted when they end, stopped when idle; `desktop.session.*` in `handlers.ts`), `streams.ts` (`openDataSocket`/`DataSockets`: one data socket per stream, closed with the session), `rfb.ts` (`openDesktopStream`: VncAuth to Xvnc with the view-only or full password, security None to the viewer, bytes copied), `terminal.ts` (`Terminals`: the login shell in a `Bun.Terminal` PTY as the agent; `stream.open` in `handlers.ts`); the agent's Chrome opens in a window on its desktop, started first, when its `browser.act|batch` requests say `desktop` (`browser.ts` `desktopFor`; in system mode the worker's, as the agent's user, on the display root gives it: `desktop.ensure` with `use: "browser"`, a `browser.desktop` lease so root doesn't idle that desktop under it, `worker.state.desktopViewers`, ADR 0058 §14); neither a desktop nor a terminal ever runs as root without a launcher (`NOT_AS_ROOT`); in system mode `desktop.session.*` and `stream.open` are root's (`OP_ROUTES`), which starts both through the agent's launcher (`systemDesktopUser`, `systemTerminalUser`, `agentGid`) and says `hello.mode: "system"`; `agentes-runner desktop-check --agent <handle>` (`main.ts`) checks both on a Linux computer.
- Hot path: message insert is one SQL statement that also starts mention/DM runs (`insertMessageWithRuns`); per-process caches in `cache.ts` (on in the server, off in tests); per-run query/stage profile (`profile.ts`, `@agenteschat/db` `queryTrace`). `bun run smoke` checks a real environment; `--desktop-agent <handle>` also watches that agent's desktop and asks its terminal who it runs as, through the running server (`apps/server/scripts/smoke-desktop.ts`).
- Agent desktops in the apps (ADR 0058): `packages/client/src/desktop/` (panel states from the status and close codes, socket addresses, `useDesktopStatus`); web `components/desktop/DesktopView.tsx` (noVNC 1.7.0, types in `src/types/novnc.d.ts`, on a socket of its own: watching view-only at quality 3, control at 6; in control the keys, paste and copy go through a hidden field, `screen-keys.ts`, ADR 0058 §16), in the dialog `components/computer/ComputerDialog.tsx` (`?computer=1`; full screen shows the screen alone); a desktop's help request in `browser/BrowserHandoffCard.tsx`.
- Daily stall-and-noise report (ADR 0089 addendum): `packages/engine/src/autonomy-report.ts` (counts from stored rows, plus the `heldBack` mark on a run's first `context` step and `executed` on a computer turn's `model_call` step); job `ops.autonomy_report` emailed to `OPS_REPORT_EMAIL`; `bun run report:autonomy [--day] [--org]` (`apps/server/scripts/autonomy-report.ts`).
- Agent's screen on the phone (ADR 0098): the server's `/screen.html` (`apps/web/screen.html`, `src/screen/session.ts`: noVNC only draws, the pointer goes as an RFB message on the channel) in a WebView that holds the session and loads nothing else; `apps/mobile/src/features/computer/AgentScreen.tsx` (the WebView as large as the desktop, moved by the UI thread; trackpad, keys, watching), `screen-page.ts` (the app's side of the page, `PointerLine`), `screen-view.ts` (camera and cursor worklets), `pixel-cursor.ts` (the cursor's drawing).
- Test helpers: `packages/db/test/pglite.ts`, `packages/engine/test/fixtures.ts`, `apps/server/test/harness.ts`.
- Frontend: `apps/web` and `packages/ui`; the server serves the built SPA from `WEB_DIR`. Every UI change follows `.claude/skills/ui-polish` (the kit's numbers, the rules and the routine), with the break-ui skill on worst-case data and Impeccable's audit (report only; its shared ignores in `.impeccable/config.json`).
- Who has access to something: `AccessDialog` (`packages/ui`) on the web and desktop, `AccessList` (`apps/mobile/src/features/shared`) on the phone. They know nothing of what they guard: reuse them for any new "who can see or edit this" instead of drawing another list.