NyxID
AGENTS.md43 starsChanged 55 days agoApache-2.0View on GitHub
NyxID is an Auth/SSO platform (similar to Supabase Auth) with a Rust backend, React frontend, and CLI tools: user authentication, OAuth/OIDC, MFA, credential brokering, admin management, and MCP proxy. The nyxid CLI covers all user-facing operations (services, keys, catalog, nodes, approvals, SSH, MCP, notifications) and includes nyxid node for managing on-premise credential nodes. Tech Stack: - Backend: Rust, Axum 0.8, MongoDB 8.0 (mongodb 3.5, bson 2.15) - Frontend: React 19, TypeScript, Vite 7, TanStack Router + Query, Tailwind CSS 4,…
- Installs packages
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,266 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository18 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- aevatar-agent-profile-managementSkill
- aevatar-automationSkill
- aevatar-channels-deliverySkill
- aevatar-codex-exec-node-setupSkill
- aevatar-codex-exec-workflow-sampleSkill
- aevatar-feasibility-advisorSkill
- aevatar-platform-mapSkill
- aevatar-schedulerSkill
- aevatar-service-publisherSkill
- aevatar-team-builderSkill
- aevatar-triageSkill
- aevatar-workflow-authoringSkill
- fallback-to-calling-agentSkill
- firecrawl-via-nyxidSkill
- github-via-nyxidSkill
- nyxid-service-skill-authoringSkill
- nyxidSkill
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
14 rules. About 1 is common, 3 are distinctive, and 10 are very specific to this project.
≈1
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
10
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 20
Before changing code, read the spec that governs it: the deep-dive docs listed above, or search docs/ for the code, route or behaviour you …
- Distinctive: line 24
Keep the spec's existing structure.
- Very specific: line 25
If you find code that disagrees with the spec and your change didn't cause it, do not edit the spec to match.
- Very specific: line 33
Every push to dev requests full CI, including backend tests, all-targets Clippy, coverage, feature builds, container E2E and image checks.
- Very specific: line 34
Run scripts/cut-release.sh with your own gh login to open a PR from a fixed staging commit into main.
- Very specific: line 35
Wait for approval, full CI Pipeline and Main Merge Guard, then select Create a merge commit.
- Very specific: line 37
After a hotfix lands, merge main back into dev using Create a merge commit before cutting the next rollup.
- Distinctive: line 43
Start here (all agents)
- Very specific: line 85
NEVER use #[serde(skip_serializing)] on model fields -- prevents insert_one(&struct) from storing them
- Very specific: line 86
ALWAYS use #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")] on DateTime<Utc> fields.
- Very specific: line 88
Every new production collection, and removal of a collection's last production use, must be registered in …
- Common: line 155
No hardcoded secrets -- env vars for all sensitive data.
- Very specific: line 158
All key material in Zeroizing wrappers.
- Distinctive: line 194
Add new entries here when introducing additional vendored URN types.
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Project Overview
NyxID is an Auth/SSO platform (similar to Supabase Auth) with a Rust backend, React frontend, and CLI tools: user authentication, OAuth/OIDC, MFA, credential brokering, admin management, and MCP proxy. The nyxid CLI covers all user-facing operations (services, keys, catalog, nodes, approvals, SSH, MCP, notifications) and includes nyxid node for managing on-premise credential nodes.
Tech Stack:
- Backend: Rust, Axum 0.8, MongoDB 8.0 (
mongodb3.5,bson2.15) - Frontend: React 19, TypeScript, Vite 7, TanStack Router + Query, Tailwind CSS 4, Zod 4, Zustand
- Mobile: React Native 0.83, Expo 55, TypeScript (iOS + Android approval app)
- SDK: TypeScript OAuth 2.0 client (
@nyxids/oauth-core,@nyxids/oauth-react) - Dev tools: Docker Compose (MongoDB + Mailpit), RSA keys for JWT signing
Deep-dive docs live in docs/ -- notably chat/README.md, ENV.md, ORACLE_RELAY.md, AGENT_ISOLATION.md, CHANNEL_BOT_RELAY.md, CHANNEL_EVENT_GATEWAY.md, NODE_PROXY_ARCHITECTURE.md, OPENCLAW_INTEGRATION.md, API_DISCOVERY.md, SSH_NODE_KEY_AUTH.md. Read the relevant doc before working in that subsystem.
Start here (all agents)
This file is long (about 230 KB). Some tools load only the beginning: if yours does, open AGENTS.md and read the section for the area you are working in. The contents list below names every section.
Specs: keep them current as you work
- Before changing code, read the spec that governs it: the deep-dive docs listed above, or search
docs/for the code, route or behaviour you are changing. - The spec is the contract. If your change alters behaviour, a contract, limit, flag, env var, error code or key decision, update the governing spec in the same PR. For new features, write the spec section first or alongside the code.
- Edit in place, in present tense, describing current behaviour only: no "previously/now/this PR" notes, history or known-issue lists.
- One place per fact: change it in its governing spec and link to it elsewhere instead of copying.
- Keep the spec's existing structure; do not restructure, split or move specs unless the task asks for it.
- If you find code that disagrees with the spec and your change didn't cause it, do not edit the spec to match. Report it in the PR description; open a NyxID issue only if the person you are working for asks.
- Do not edit docs that ship at runtime (
docs/assistant/CMA_WORKER_GUIDE.md,docs/assistant/CHANNEL_SETUP_GUIDE.md,docs/AI_AGENT_PLAYBOOK.md,docs/examples/nyxbot-voice-service.template.json) unless the task asks for it. Tests readdocs/security/PERSONAL_ERASURE_INVENTORY.md,docs/security/ENCRYPTED_FIELD_INVENTORY.md,docs/AGENT_OPERATION_SCOPES.md,docs/ACCOUNT_DATA_EXPORT.mdanddocs/chat/activity-history-compat.md; run those tests when you edit them. Pages underdocs/site/are built into the frontend and must be listed infrontend/src/features/docs/manifest.ts. - In the PR description, name the spec sections you changed, or write "Spec impact: none".
Git Workflow
- Conventional commits:
feat:,fix:,refactor:,docs:,test:,chore: - Open feature and fix PRs against
devfor review and the fast, path-filtered gate. Oncedevis the default branch, merging a PR there closes issues linked withCloses #N. - Every push to
devrequests full CI, including backend tests, all-targets Clippy, coverage, feature builds, container E2E and image checks. - Run
scripts/cut-release.shwith your ownghlogin to open a PR from a fixed staging commit intomain. Itsrelease/YYYY-MM-DDbranch must stay ondev's history. Further merges intodevcan continue during review. - Wait for approval, full
CI PipelineandMain Merge Guard, then select Create a merge commit. The guard also accepts this repository'sdevbranch. - Cut urgent fixes from
mainonhotfix/<name>. Targetmainwith full CI and review. - After a hotfix lands, merge
mainback intodevusing Create a merge commit before cutting the next rollup. - GitHub runs
Main Merge Guardfrom the default branch onpull_request_target. Retargeting a PR reruns the guard against its new base.
Contents of this file
- Project Overview
- Start here (all agents)
- Specs: keep them current as you work
- Git Workflow
- Critical Rules
- MongoDB Model Conventions
- Layer Architecture
- Error Handling
- Frontend Patterns
- Security
- 5a. Vendor URN Namespace
- Node Proxy Conventions
- OpenClaw Integration
- Streamlined Services Architecture
- Agent Isolation
- Catalog Metadata and Endpoint Discovery
- 10a. Catalog Skill Curation
- Oracle Relay (browser LLM pools)
- Auth Device-Code Login
- Hosted Connect Links
- 13a. Bot Connection Links
- Connection Webhooks and Triggers
- Agent Key Login
- Agent Plugins
- File Structure
- Key API Routes
- NyxAgent assistant engine
- Channel Bot Notes
- Environment Variables
- Available Commands
- Design System
- Consensus R&D Foundational Invariants (managed by consensus-rnd)
- Aurinko email integration
- Tools Manager boundary
- Protected organization connection use
- Organization-specialist channel bindings
Critical Rules
- Server-mode SIGTERM/ctrl-c receivers are installed before startup IO; startup steps finish without cancellation, with clean exits before database writes or a drain before binding. Startup drain budgets count from signal receipt; one-shot commands install no receivers or billing/verification workers. SIGTERM/ctrl-c drains admitted work while serving both listeners; stop background claims, retain renewals, settle deadline turns as
turn_lost/shutdown, and release exact generation/claim fences./readybecomes 503;/healthstays 200; chained start/finish audits share the process generation. Seedocs/DEPLOYMENT.md#rolling-deploys-and-graceful-drain.
1. MongoDB Model Conventions
- NEVER use
#[serde(skip_serializing)]on model fields -- preventsinsert_one(&struct)from storing them - ALWAYS use
#[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]onDateTime<Utc>fields; forOption<DateTime<Utc>>use thebson_datetime::optionalhelper (models/bson_datetime.rs) - IDs are UUID v4 stored as strings in MongoDB
_id; each model has aCOLLECTION_NAMEconstant - Every new production collection, and removal of a collection's last production use, must be registered in
services/personal_data_registry.rs(owner selector, erasure and export disposition); its source-scan test enforces this. Personal collections also need local-inventory and owner-index coverage; see the registry header anddocs/security/PERSONAL_ERASURE_INVENTORY.md.
2. Layer Architecture
Strict separation: handlers/ -> services/ -> models/
- models/ -- plain serde structs,
COLLECTION_NAME, no business logic - services/ -- business logic; takes
&mongodb::Databaseand&strfor IDs - handlers/ -- HTTP layer; converts
AuthUser.user_id(Uuid) to string for services; dedicated response structs (never serialize model structs to API responses) - crypto/jwt.rs takes
&Uuid(kept for signing); token_service parses&strtoUuidinternally - unified_key_service -- orchestration layer for the streamlined services architecture; auto-provisions UserEndpoint + UserApiKey + UserService from catalog or custom input in one operation
3. Error Handling
AppError enum (errors/mod.rs, thiserror); handlers return AppResult<T> = Result<T, AppError>. Variants map to HTTP status codes and numeric error codes; backend/src/errors/mod.rs is the authoritative list. Internal/database errors never leak details to clients.
Reserved numeric code blocks (single source of truth -- do not duplicate these tables elsewhere):
- 1004
SkillPublicationretains the HTTP 409conflictresponse and adds safe skill-save diagnostics and recovery indetails. - 1011-1019 SSH node-key/auth-mode: 1011
SshNodeKeyMissing, 1012SshHostKeyMismatch, 1013SshNodeExecChannelClosed, 1014SshPrincipalAmbiguous, 1015SshAuthModeUnsupportedForOperation - 2003
MfaStepUpRequired(HTTP 403,mfa_step_up_required): verify the current session before approving sign-ins on other devices; never signs out the approver. - 8000-8005 node/proxy: 8000
NodeNotFound, 8001NodeOffline, 8002NodeProxyTimeout, 8003NodeRegistrationFailed, 8004NodeCredentialMissing, 8005WsProxyDownstream - 8006-8011 pending-credential protocol: 8006
PendingCredentialDecryptFailed, 8007PendingCredentialVersionUnsupported, 8008PendingCredentialCiphertextTooLarge, 8009PendingCredentialPubkeyAwaiting, 8010PendingCredentialNodeOffline, 8011PendingCredentialQueueFull - 8012
ClientDisconnected(HTTP 499, nginx's "Client Closed Request"): the caller hung up before the response could be written and upstream work was cancelled. Never delivered to anyone — it exists so cancelled work is not counted as a server fault in telemetry and audit. Do not map it to 5xx. - 8013
NodeHttpSignatureUnsupported(HTTP 502): target-selected HTTP requests require a node advertising HTTP signature v2 - 8014
NodeCredentialDestinationMismatch(HTTP 403): the credential node refused the downstream destination. - 9500-9599 device-code binding: 9500
DeviceCodeNotFound, 9501DeviceCodeExpired, 9502DevicePollSignatureInvalid, 9503DeviceUserCodeInvalid, 9504DeviceCodePending, 9505DeviceCodeAlreadyDelivered, 9506DeviceCodeRateLimited, 9507DeviceCodeLocked, 9508DeviceCodeSlowDown - 10000-10015 channel relay: 10000
ChannelBotNotFound, 10001ChannelBotInactive, 10002ChannelBotLimitReached, 10003ChannelWebhookVerificationFailed, 10004ChannelRelayFailed, 10005ChannelPlatformError, 10006DeviceChannelReplyNotAllowed, 10007ChannelPlatformEditUnsupported, 10008ChannelAgentInitiateNotAllowed, 10009ChannelConversationNotAddressable, 10010ChannelPlatformSendUnsupported, 10011ChannelConversationNotReachable, 10012ChannelMediaUnsupported(415), 10013ChannelMediaTooLarge(413), 10014ChannelMediaFetchFailed(502), 10015ChannelAttachmentNotFound(404) - 11000-11099 oracle relay: 11000
OraclePoolNotFound, 11001OraclePoolSlugTaken, 11002OraclePoolInactive, 11003OracleWorkerTokenInvalid, 11004OracleQueueFull, 11005OracleQuotaExceeded, 11006OracleTaskNotFound, 11007OracleSessionNotFound, 11008OracleSessionClosed, 11009OraclePayloadTooLarge, 11010OracleExtractDisabled, 11011OracleWorkerNotFound, 11012OracleWorkerCapabilityUnsupported, 11013OracleWorkerCommandNotFound, 11014OracleWorkerLabelUnavailable, 11015OracleLoginSnapshotNotFound, 11016OracleWorkerCredentialRenewalRequired, 11017OraclePoolActiveWork(HTTP 409), 11099OracleRetired(HTTP 410: the built-in oracle is permanently retired; every/api/v1/oracleroute and everynyx__oracle_*MCP tool answers with it) - 11100
AnonymousIncompatibleService(HTTP 400) - 11200-11207 auth-device login: 11200
AuthDeviceCodeNotFound, 11201AuthDeviceCodeExpired, 11202AuthDeviceCodePending, 11203AuthDeviceCodeSlowDown, 11204AuthDeviceCodeDenied, 11205AuthDeviceCodeAlreadyDelivered, 11206AuthDeviceCodeRateLimited, 11207AuthDeviceUserCodeInvalid - 11300-11305 connect links: 11300
ConnectLinkNotFound, 11301ConnectLinkExpired, 11302ConnectLinkAlreadyCompleted, 11303ConnectLinkCancelled, 11304ConnectLinkRateLimited, 11305ConnectLinkCompletionInProgress - 11300-11304, 11307 billing (numbers shared with connect links above, which is accepted (#2329); distinguish by the response
errorkey): 11300InsufficientCredits(insufficient_credits), 11301BillingNotConfigured(billing_not_configured), 11302BillingProviderUnavailable(billing_provider_unavailable), 11303PlanEntitlementRequired(plan_entitlement_required), 11307WalletSuspended(wallet_suspended), all HTTP 402; 11304AnonymousIncompatibleBilling(anonymous_incompatible_billing, HTTP 400). CMA's unbilled quote exclusion also matches the exact message (docs/CMA_BILLING.md). - 11500
GrantCascadeConfirmationRequired(HTTP 409) - 11600-11606 triggers: 11600
TriggerNotFound, 11601TriggerSecretInvalid, 11602TriggerRateLimited, 11603TriggerPayloadTooLarge, 11604TriggerDeliveryUnsupported, 11605TriggerDeliveryFailed, 11606TriggerDeliveryRecordNotFound - 11700
RequestBodyTooLarge(HTTP 413): a bounded proxy or forwarding ingress exceeded its configured byte limit - 11900-11909 Agent Key login: 11900
AgentKeyLoginNotFound, 11901AgentKeyLoginExpired, 11902AgentKeyLoginPending, 11903AgentKeyLoginSlowDown, 11904AgentKeyLoginDenied, 11905AgentKeyLoginAlreadyDelivered, 11906AgentKeyLoginRateLimited, 11907AgentKeyLoginUserCodeInvalid, 11908AgentKeyLoginKeyIneligible, 11909AgentKeyCredentialNotFound - 12000-12004 one-time login codes: 12000
LoginCodeInvalid, 12001LoginCodeExpired, 12002LoginCodeCancelled, 12003LoginCodeRedeemed, 12004LoginCodeRateLimited - 12100
AssistantTurnActive(HTTP 409,turn_active): a persisted NyxAgent conversation already has an active turn. - 12101
AssistantAttachmentExpired(HTTP 410,attachment_expired): an assistant upload is no longer available under retention policy. - 12102
AssistantTurnRequired(HTTP 409,assistant_turn_required): a conversation key attempted execution without a live turn. (12101 is already reserved by upload retention.) - 12103
AssistantModelUnavailable(HTTP 400,model_unavailable): a NyxBot model selection names a model NyxAgent's live list does not offer; turn-time upstream model rejections settle with the samemodel_unavailablecode. - 12104
AssistantModelAuthorityChanged(HTTP 403,model_authority_changed): an admitted model connection or execution authority changed; review completed actions before retrying. Action access-mode changes alone do not revoke model consent. - 12105
OrgAgentAccessAuthoringUnavailable(HTTP 403,org_agent_access_authoring_unavailable): the rollout flag or fleet readiness prevents changes to specialist access lists. - 12200
AdminUsageQueryTimeout(HTTP 503): bounded admin usage aggregation timed out; retry with a narrower window or filters. - 12300
WorkspaceDestinationsNotActivated(HTTP 503): incomplete automatic Drive/Workspace editor reconciliation; excluded from proxy-fault telemetry - 12400-12422 machine nodes: 12400
MachineCapabilityDisabled, 12401MachineNotAllowed, 12402MachinePathOutsideRoots, 12403MachineJobNotFound, 12404MachineConfirmationPending, 12405MachineConfirmationDeclined, 12406MachineComputerUnavailable, 12407MachineLimitExceeded, 12408MachineOwnerInControl, 12409MachineNotIsolated, 12410MachineLoginNotFound, 12411MachineLoginOriginMismatch, 12412MachineLoginWrongField, 12413MachineBrowserUnavailable, 12414MachineDriverRestarting, 12415MachineComputerPermissionMissing, 12416MachineComputerToolUnsupported, 12417MachineDisplayUnavailable, 12418MachineTurnStopped, 12419MachineAuthorityUnsupported, 12420MachinePermissionRevoked, 12421MachineAuthorityStale, 12422MachineAuthorityBusy. Nodes also use 12419 forseparated_context_unavailableand 12421 forcontext_quarantine_pending. - 12600 service concurrency: 12600
ServiceConcurrencyLimited(HTTP 429,Retry-After: 1); client capacity rejection, never a server fault. - 12700
ToolOperationNotPublished(HTTP 404): unpublished or unknown operation on a tool offering. - 12800-12801: 12800
ManagedExecutionPending(HTTP 409), 12801ErasurePreparing(HTTP 409,erasure_preparing). - 12900
OAuthAuthorityUnavailable(HTTP 503,oauth_authority_unavailable): a live OAuth authority read could not complete; retry the request without discarding tokens or reauthorizing.SecurityReadinessUnavailablealso uses 12900 (HTTP 503,security_readiness_unavailable); clients must distinguish these errors by the responseerrorkey. - 13300
MonitoringUnavailable(HTTP 503,monitoring_unavailable): configured chrono-probe failed or returned an unusable response. - 13301
MonitoringNotConfigured(HTTP 404,monitoring_not_configured):CHRONO_PROBE_URLis unset or invalid; monitoring UI stays hidden. - 13302
DiagnosticNotReady(HTTP 409,diagnostic_not_ready,Retry-After: 1): a diagnostic handle is not ready for redemption; retry without treating it as a server fault. - 13400-13401 crash reporting: 13400
CrashReportingUnavailable(HTTP 404,crash_reporting_unavailable); 13401CrashReportConsentRequired(HTTP 403,crash_report_consent_required). - 12500-12502 assistant voice: 12500
VoiceQueueFull(HTTP 429), 12501VoiceProviderUnavailable(HTTP 503), 12502VoiceApprovalUnsupported(HTTP 403).
4. Frontend Patterns
- Zod schemas in
schemas/(one per domain); React Hook Form +@hookform/resolvers - Forms use
useAppForm(components/ui/form.tsx), never rawuseForm(lint-enforced viano-restricted-imports): itssetValuedefaults toshouldDirty/shouldTouch/shouldValidate: trueso non-text controls wired viawatch+setValue(Radix Switch/Select/Checkbox, custom editors) correctly enable dirty-gated submit buttons; programmatic writes (prefill, normalization in effects) opt out per call with{ shouldDirty: false, shouldTouch: false } - TanStack Query hooks in
hooks/(one per domain:use-auth.ts,use-services.ts, ...); auth state in Zustand (stores/auth-store.ts) - UI components via Radix UI + shadcn/ui pattern (
components/ui/); noconsole.login production code - App copy lives in
frontend/src/i18n/locales/app/<area>/{en,zh-CN,zh-TW}.json. Add each new key to its area in all three files, in sorted position (npm run check:i18nsuggests the area for a missing key), then runnpm run sync:i18n. Branches from before the split usenpm run adopt:i18n(seedocs/MULTILINGUAL.md). - Mobile copy uses the same structure without an English file:
mobile/src/i18n/locales/<area>/{zh-CN,zh-TW}.json(English phrase keys), imported only through thezh-CN.ts/zh-TW.tsbarrels. Add keys to both files in sorted position, then runpnpm sync:i18n(regenerates the barrels); pre-split branches usepnpm adopt:i18n.
5. Security
- No hardcoded secrets -- env vars for all sensitive data; input validation on all endpoints; PKCE for OAuth flows
- AES-256 envelope encryption with pluggable async
KeyProvidertrait (crypto/aes.rs,crypto/key_provider.rs); AWS KMS (crypto/aws_kms_provider.rs, featureaws-kms) and GCP Cloud KMS (crypto/gcp_kms_provider.rs, featuregcp-kms); fallback provider for zero-downtime migration between encryption backends - Assistant Agent Keys are the deliberate exception to hash-only API-key storage:
assistant_agent_credentialsretains one raw key per conversation only under envelope encryption because NyxAgent binds session ownership to the exact key. No API, audit, log, or Debug output may expose ciphertext or raw material; revoke removes the encrypted row; rotation adopts the encrypted successor in the same transaction without returning its raw key. Both clear session bindings. - All key material in
Zeroizingwrappers; all Debug impls redact secrets and key identifiers;MAX_WRAPPED_DEK_SIZE = 1024enforced on encrypt and decrypt paths - Middleware: rate limiting (
mw/rate_limit.rs), security headers (mw/security_headers.rs), JWT auth (mw/auth.rs) - Audit logs are tamper-evident for new rows via HMAC-SHA256 hash chaining (
services/audit_chain_service.rs): newAuditLogrows must setseq,prev_hash,entry_hashthrough the audit service append path; legacy rows withoutseqcount as pre-chain, not backfilled.AUDIT_CHAIN_HMAC_KEYis an optional 64-hex override; otherwise the key is domain-derived fromENCRYPTION_KEYor the JWT private key. v1 does not detect tail truncation without external head anchoring. Broker binding/consent revocations, administrator user creation, profile/role/status changes, password resets, email verification and session revocation, role and group creation/update/deletion and membership changes, administrator invite creation/note edits/deactivation, service-account creation/update/deactivation, secret rotation, bulk token revocation and curation/key-read grant changes, owner/admin Agent Key credential binding creation/deletion, and organization creation/profile and role-scope changes, membership add/update/revoke and invitation issue/cancel/redeem commit metadata-onlysecurity_effect_intentswith the source mutation; the relay appends each stable audit UUID through the same chain once. Migrations preserve audit facts within the metadata bound; redact secret-bearing values explicitly (profile avatar query/fragment/userinfo), never replace non-secret values with field names alone. Required audit strings retain byte-for-byte values up to their UTF-8 byte cap (identifiers/IP/key name 256, User-Agent 1,024, email/display name 512, sanitized avatar URL 4,096), with a visible...[truncated]suffix when shortened. Identifier lists retain an original-order prefix within an 8 KiB BSON-array budget and carry count, truncation and SHA-256 only when shortened; request validation and stored source values are unchanged. CAE notification intents commit with revocation, and ambiguous dispatches remain uncertain without blind resend; validated destination addresses are pinned. Audit receipts delete their intents, terminal CAE records expire after 30 days, and Integrity exposes bounded queue health. Organization deletion recordsorg_deletion_requestedwith an evidence-only marker before cleanup andorg_deletedwith the exact final org delete; partial cleanup remains visible as requested without completion and is not automatically resumed. Automatic and manual chain verification discard losingOkscans, always log a localBrokenat error level and retry its publication up to three times (on conflict, keeping the stored break at an earlier or equal sequence, or returning an error on exhaustion), so a late break after repair may restore an alarm that the next scan clears by rechecking its break cursor. Optionalrevisionidentities prevent same-millisecond publication races. - Billing transactions are tamper-evident via the append-only
billing_ledgercollection (services/billing/ledger.rs): charged usage settlements (first-apply only, including the wallet-lock crash bridge), provider-confirmed top-up checkouts, paid wallet credits (deduped by Lago invoice id), grant lifecycle movements, and purchased-credit expiry append hash-chained entries with the sameseq/prev_hash/entry_hashconstruction, keyed byBILLING_LEDGER_HMAC_KEYor thebilling-ledgerdomain derivation. Wallet usage locks remain until their v2 posting is durable; provider balance changes and their postings commit transactionally. Funded HTTP event streams best-effort checkpoint only recoverable final usage, sharing relay parsing and bounding each write to one second; a failed or losing write logs metadata once and disables the observer without changing delivery or finalization, and recovery uses ordinary idempotent settlement (see docs/BILLING_EXACT_ACCOUNTING.md). Funded direct/node Realtime sessions checkpoint numeric prefixes at distinct response boundaries and use one terminal transaction before ordinary settlement; recovery applies the existing tail formula once to recorded uncovered bytes, and a session with no durable boundary settles zero bytes/tokens plus one request (see docs/BILLING_EXACT_ACCOUNTING.md). Checkout notifications remain memo-only best-effort events. Account reconciliation (billing_accounts, additive Integrityaccountsresponse field) checks wallet balance minus pending debits and grant remaining against checkpoints updated atomically with postings. Its scheduled snapshot pass also verifies wallet/grant/allowance holds with two page reads for idle resources and detailed checks only for live rows, counters, locks or observations; incomplete hold checks leave asset certification unchanged. Unchanged mismatches across two passes and at least five minutes produce per-kind Integrity counts and signed samples; unlocked wallet, grant total/rule and allowance-period excess is returned atomically with a chained audit and observation deletion (never deficits; benefit repair also requires an existing owner and complete allocation/receipt evidence). An ordinary rolling update needs no action; an old release frozen between its two writes past both observations and five minutes can resume after repair and create a reported deficit up to its own hold. Seedocs/BILLING_EXACT_ACCOUNTING.md. When billing is enabled, a leased, fenced runner checks up to 1,000 accounts per collection in each bounded snapshot, runs batches back-to-back for one pass, then idles until the chain-verification cadence.CHAIN_VERIFY_INTERVAL_SECS=0disables both automatic chain verification and account reconciliation; no account runner is spawned. Grant issuance is unspendable until journaled, grant consumption retains its settlement lock until journal confirmation, grant issuance/terminal markers retry during reconciliation, and purchased-credit expiry retains its wallet operation until every ledger entry is durable. Verify viaGET /api/v1/admin/billing-ledger/verify. Periodic billing maintenance uses the renewablebilling:reconcilecluster lease (shared defaults: 30s TTL, 10s renewal); contending ticks skip, including startup. On loss, finish the current write protocol and stop at row/component/chunk boundaries; preserve all financial row fences and request-time behavior. Old binaries do not participate during rollout. Tail truncation is detected: the reconcile sweep anchors the ledger head into the audit chain (billing_ledger_head_anchored) and the server log, and verify cross-checks the newest anchor (tail_truncatedbreak); entries newer than the last anchor (<= one reconcile interval) are the remaining window. Both chains are also re-verified automatically in rolling chunks (services/chain_verify_service.rs,CHAIN_VERIFY_INTERVAL_SECS), with status persisted tochain_verify_status, surfaced on the admin Integrity page (/admin/integrity), and escalated via error-level logs. - Catalog
inferenceis optional admin metadata (protocol/model list/realtime). Compute caller-specific binding andstatus_slug; never store them. Startup defaults respectinference_admin_modified(including explicit null clears) and include admin-createdchrono-llm/chrono-llm-publicand seeded xAI. Provider-linked status usesProviderConfig.slug; other status uses the catalog slug. Seedocs/PLATFORM_KEYS_AND_INFERENCE.mdanddocs/API_DISCOVERY.md. - Catalog
platform_keyuses the existing encrypted master credential and live public/restricted polymorphic-owner grants. Every platform-bound resolver must call the shared ACL before decryption; no anonymous grant, no node routing or user-controlled destination. Gateway-URL providers cannot enable platform keys. Restricted ACLs batch memberships/active owners; catalog, keys (including provisioning/reconciliation), MCP and LLM listings share one request membership snapshot across service/owner checks. Reuse loaded providers or batch them once;available_with_grantsmust perform no database calls. Never cache these grants across requests. Legacy absent configs preserve public internal master-key behavior.UserService.credential_bindingis optional;POST/PUT /keysand hosted/MCP flows useuse_platform_key. Switching to platform retains the user's key. Public audience auto-provisioning is personal-only; restricted audience auto-provisioning creates personal rows for allowlisted people and org rows only for allowlisted orgs reached through activecan_proxy()memberships. Startup removes legacy public-audience org auto rows with their orphan endpoints. Explicit org-owned platform bindings (source != auto_provision) retain the live public execution ACL. Scoped agent auto-connected grants include active auto rows and explicit platform bindings. Ordinary platform-key usage preserves the authenticated billing principal withPaysFrom::PersonalviaBillingOwnerResolver::resolve_for_execution, including org-owned API keys, with no owner-type read or new refusal. Only the explicit typedExecutionLane::OrgChannelGuestselects the newOrgWalletpath: a server-verified, live org-specialist channel guest with enabled binding exposure, specialist Grants guest access (or frozen legacy binding narrowing), and a provisioned org wallet with exact funding reservations bills that org for model and tool usage, including platform keys. This exception never applies to org members, ordinary org keys, shared agents, or personal channels. Members retain org BYOK → org / platform key → person billing. ServiceBilling.byok_pricing/platform_key_pricingare optional credential-class lanes: the existing fields are the primary price; optionalcomponentsadd unique metrics. Either lane present supersedes legacy platform billing; missing lane andNoAuthare free. An unsynced primary substitutes legacy billing (or free) for the entire lane; a synced primary and synced extras charge, while unsynced extras are free and never add fallback. Resale stays independent. Primary Lago codes remainplatform_svc_{slug}_{byok|pk}, components append_{metric}, with durable component cleanup/reconcile. Price removal marks the code'sbilling_rate_cacherowretired_atand never deletes it: historical usage keeps pricing from it,fresh_raterefuses it for new reservations, and a re-synced price replaces the row.GET /billing/usageprices historical rows by grant-settled derivation, then the cached rate, then exact per-row reservation rates (rate × quantity in Decimal128 credits, as exact settlement computes), else null with grant credits still known. Omitted lanes/components preserve them; null/[] clears components. Token/image capture checks every configured component independent of slug/sync; priced token classes subtract caches included in OpenAI/Gemini input, but keep Anthropic's separate cache counts; providerTokenBreakdownremains unchanged. Computed adminallowance_metricslists configured units plus legacy only without lanes or with an unsynced primary; allowances match identical metrics. Default BYOK primary, then platform primary, then legacy. NyxID 0.34.0 prices supportPRICE_FRACTIONAL_DIGITS = 12, optional pico rates plus truncated legacy micros; all money uses checked i128 picocreditCredits, Decimal128 credits in MongoDB and decimal strings in additive API fields. Derive the exact wallet share by subtraction; never ceil or truncate movements. Legacy display fields truncate after exact aggregation. Lago quantities floor cumulatively with durable per-owner/metric/rate residue committed atomically with the claim-fenced final funding split; stale workers reuse both committed outputs. Exact BSON money keys are unit-free and take precedence over legacy integer micros. Canonical Credits use direct BID conversion with BSON-parser-equivalent bytes to bound rollup serialization overhead. Before normalization, rollup reductions fetch mixed documents to distinguish missing from null; after normalization, scalar exact cost mirrors use covering indexes; startup creates each replacement before retiring its obsolete legacy definition to bound transaction cache pressure. Invalid Lago charges disable only their own metrics and surface in Integrity. Webhook/reconcile/expiry use one settled-minus-accrued balance calculation; locked refreshes are durably deferred to a one-second worker. Walletsnapshot_generationfences provider reads against publication, balance webhooks and first wallet-backed usage ACKs; stale webhook/reconcile reads queue a fresh fetch, deferred/expiry work retains its own retry, and complete ordering requires every replica to be upgraded (old binaries ignore the field; rollback needs no data change). Preserve funding precedence, charge IDs and v1 canonical bytes; v2 entries have balanced postings. First cutover of existing billing data requires draining old writers andBILLING_EXACT_CUTOVER_DRAINED=true; a background task otherwise waits for acknowledgement while billed admission returns BillingProviderUnavailable (503). The server and metering-only traffic remain available. Billing admission and money sweeps wait only forbilling_migrations/exact-v2.completed_at; derived analytics normalization has independentbilling_migrations/exact-v2-rollups.completed_atreadiness and never creates a billing outage. Before the rollup marker, admin usage uses a legacy-tolerant mixed-document reduction; after it, readers use flatquery_{money_field}Decimal128 mirrors and v6 covering indexes (v5 added metering-only audio token measures, v6 image token subsets), avoiding nested object reconstruction in MongoDB. Folds and normalization write those mirrors atomically with their nested counterparts. Rollup normalization uses bounded MongoDB update pipelines atomic per document with concurrent folds, preserves present exact/null values, converts absent legacy micros, removes legacy mirror keys, and records durable progress/Integrity diagnostics. No hot-path migration runs. Cutover conversion and delta absorption isolate malformed documents, record Integrity diagnostics and continue bounded batches. Old binaries must not be restarted against migrated data. Seedocs/BILLING_EXACT_ACCOUNTING.md. Upgrade ALL replicas before authoring component prices, new-metric allowances, operation prices, or prices beyond six decimals; old replicas cannot deserialize the new enum units and ignore operation prices (charging the base rate). Requests lanes may price operations (operations, endpoint names or declared channel operations, own_op_{key}Lago codes) that replace the primary rate when synced; seedocs/PLATFORM_KEYS_AND_INFERENCE.md#operation-prices.- Per-service platform prices are authored in NyxID at
ServiceBilling.platform_pricingand synchronized to stable Lagoplatform_svc_{slug}sum metrics and standard charges onLAGO_PLAN_CODE. Plan updates must round-trip the full existing charge array with ids because Lago replaces it. Every plan writer runs insidebilling/plan_sync::run, which holds the renewablebilling:plan:<code>lease from the plan GET through PUT, readback, cache and status; a contended request-path write stayspending. Intent and a dirty generation are committed before any provider call; the reconcile pass audits registered plans read-only and repairs published (synced) prices that drift, comparing economics only, with per-code backoff and an Integrity diagnostic. Seedocs/PLATFORM_KEYS_AND_INFERENCE.md. Rate-cache writes are ordered by one epoch document: every explicit writer advances it in the transaction that changes the cache, and the periodic plan refresh publishes only if the epoch it captured before fetching is unchanged; a periodic refresh never revives a retired row. Pending/failed syncs and charge-removal cleanup retry during reconciliation; a service continues using its legacy plan metric until the new price issynced, and services without a NyxID price retain legacy Lago-authored pricing. - Central billing configuration (
/admin/billing,/api/v1/admin/billing/{config,rates,overview,services/{id},services/{id}/resync}; reads admin/operator, writes admin-only):PlatformSettings.billing.default_overdraft_cap_creditsoverridesBILLING_DEFAULT_OVERDRAFT_CAP_CREDITSfor newly provisioned wallets only (per-field patch, transactional audit). Effective prices come frombilling::config::resolve_service_billing, which builds the charge path'sBillingRouteContextper credential class and only explains it (never decides a charge); keep them in lockstep. Service prices stay service-scoped and the central editor reusesPUT /services/{id}. Seedocs/PLATFORM_KEYS_AND_INFERENCE.md#billing-configuration. - Allowance bundles group single-metric rows through an optional
bundle_id; funding is unchanged. Credit benefits live incredit_grants,credit_schedules,credit_schedule_periods,usage_allowances, andusage_allowance_periods. Funding precedence is actual-quantity allowance units, soonest-expiring exact grant credits, then exact wallet credits. Metering-only rows never consume benefits; legacy funding-less wallet rows remain wallet-only. Only the wallet-funded quantity is emitted to Lago or included in drift comparison. Grant expiry is enforced at reservation time and swept for terminal ledgering. Recurring windows are UTC.one_timeapplies only to allowances. Both credit schedules and allowances supportdaily,weekly, andmonthly. Grant issuance journals at most 50 one-shot recipients inline. Deferred rows are unspendable until reconcile confirms their ledger entries. Admin/operator endpoints are under/api/v1/admin/credits. User reads are/api/v1/billing/{grants,allowances}and accept an authorized orgowner_id. Recipients areall_users,selected_users,org_members(target_org_ids), orgroups(target_group_ids); member targets fund personal wallets only, including org viewers and direct group members. Grants snapshot at issuance, calendar schedule periods freeze policy with signup/join cutoffs at claim, and allowances follow live membership; selected lists are mutually exclusive and capped at 500 ids. - Credit allocations add optional disjoint allocation-local service/group ceilings in exact Decimal128 credits, pending reclaim, and actor-scoped UUID retry snapshots. One
CreditGrantremains the financial identity. New admin routes are/api/v1/admin/credits/allocations[/summary|/{id}|/schedules[/{id}]]; legacy routes and the user Billing UI remain supported. New authoring requiresBILLING_ALLOCATIONS_ENABLED=trueafter ALL API replicas/workers are upgraded and old writers drained. The flag is an operational assertion, not worker-version attestation; disabling it does not make persisted policies safe for old binaries. Enforce rules/fences across ordinary/public/pool/managed and machine caller-owned admission, plus extra settlement. Effective held includes unapplied extras; raw reservations stay compatible. Seedocs/BILLING_EXACT_ACCOUNTING.mdanddocs/plans/unified-credits-experience.md. - A scheduled grant is an ordinary
CreditGrant. Its UUID v5_idis derived from{schedule_id}:{period_start_ms}:{recipient_user_id}and is the disbursement identity. Keepgrant-issued:{grant_id}as the ledger dedupe key. Treat period rows and leases as derived progress, never as money locks. Each calendar period freezes its policy and all-owner signup snapshot when claimed. Calendar catch-up mints only the current window and abandons elapsed incomplete periods. Pausing opens no new calendar period, but an in-flight calendar walk completes. Recipient schedules retain durable individual UTC anchors, enroll eligible new and existing owners, and issue only the current anchored window while active. Calendar schedules support explicit current-period missing-recipient seeding without refilling existing grants. Account creation, organization joins and group additions grant the claimed current period of matching active calendar schedules (best effort after commit, never opening a period) and enroll in matching recipient schedules. Recipient authoring requires allocation enablement and durable fleet activation and live serving support forbilling:recipient-schedules-v1. Seedocs/BILLING_EXACT_ACCOUNTING.md#recipient-credit-schedules. Schedules use the existing billing reconcile interval and add no environment variable. - Wallet-funded usage holds/debits pre-tax wallet share plus Lago-owned tax (
billing_tax_profiles, existing rate-cache TTL). Admission rounds gross upward at pico; settlement rounds proportional tax half-up at pico.wallet_fundedand Lago quantities remain pre-tax;wallet_charge_creditsis gross, withwallet_tax_creditsand an applied-rate snapshot. Usage settlement adds balancedtax:usage:<owner>postings through the existing append/dedupe/lock path. Benefits remain untaxed and need no tax profile; missing/stale wallet tax data gets one bounded inline refresh then fails closed. Inline tax refresh may recapture and retry once after an ordering loss, sharing a five-second provider deadline and six-second overall ceiling; provider failures and forced refreshes never retry, and ordering loss sets no failure backoff. Tax refreshes discard superseded reads using profile revisions; cold/changed-plan publications also fence wallet and plan counters, and invalidation completes only after its ordered counter and profile updates. Provider cent rounding remains anexternal:lagorefresh residue. Deploy all replicas before ops configure taxes; legacy rows settle pre-tax, no backfill/fence. Plan sync must omittax_codesand response-only taxes for existing objects. Seedocs/BILLING_OPERATIONS.md. - Purchased Lago credits expire independently 365 days after settlement. Lago v1.50's wallet-wide
expiration_atcannot model rolling purchases, soservices/billing/topup_expiry.rsuses FIFO transaction remainders and Lagovoided_credits.BillingWallet.active_topup_expiryis the crash bridge andpending_topup_expiry_creditsmust be subtracted by every availability expression. The existing billing reconcile interval runs this sweep; there is no separate expiry environment variable. Expiry uses a renewable 600-second MongoDB-time processing claim and a dispatch marker; definite refusals retry on later passes, while uncertain voids retain their hold, read history each pass and permit one audited retry after 24 hours without a receipt. Cold wallet provisioning uses an owner lease and stable Lago wallet code: definite refusals clear its marker, uncertain creates wait two minutes between attempts, and the checkpoint is deleted with the local wallet commit; warm wallet reads add no coordination command. Both dispatches suppress a send older than 30 seconds by either monotonic or wall-clock age captured at marker commit return, preserving the marker for normal recovery. - Anonymous catalog endpoints may be enabled only when the service has
identity_propagation_mode = "none",forward_access_token = false, andinject_delegation_token = false(disabled draft rules may be stored on any service); violating admin writes returnAppError::AnonymousIncompatibleService(400, code 11100). Public execution still force-strips identity propagation, access-token forwarding, delegation-token injection, and downstream auth defaults as defense in depth. - Exact-service approvals bind an execution-authority v2 digest (
services/execution_authority.rs) over resolved execution inputs, includingtoken_exchange_config,service_category, andrequires_user_credential, while retaining the real v1 digest for rolling compatibility. Main-era v1-only rows validate against the live v1 projection; pre-digest rows skip that one gate within their approval expiry. The additive delegated exact-view fields retain the v2 contract: rolling rows keep the pre-additive digest for old replicas and separately bind the full projection for new replicas. DurableServiceEndpointoperations also bind the server-resolved positive generation; instance-spec and legacy unbound rows skip only the generation comparison while every other fence remains. Observe and redeem share one ordered live evaluator (catalog/exact generation -> policy -> read-only execution authority); observe reports transient drift without writes, while redeem claims first and durably records terminal revalidation failures before credential materialization. After those gates, redeem materializes credentials and compares execution authority again before any provider effect.UserApiKey.credential_epochversions credential material: bump it on user-initiated credential replacement only, never on background/lazy OAuth refresh, and always via a pipeline update (vec![doc! { "$set": ... }]) -- the bump is an aggregation expression and a classic update document silently stores it as a literal sub-document. Seedocs/GRANULAR_APPROVALS_DESIGN.md. - Delegated management parity requires the exact
account:readscope,GET, a non-WebSocket request, and a route outside the deny classes inmw/auth.rs; the verifiedAuthUserextractor is authoritative. New secret-delivering, execution-shaped, streaming, upgrade, or authentication/provisioning protocol GET routes MUST be added todelegated_read_denied_pathbefore mounting. Approval-status result readback is excluded from delegatedaccount:read; v2 requires the exact original key, child and actor. Channel media downloads (GET /api/v1/channel-relay/messages/{message_id}/attachments/{index}) are denied; the metadata-onlyGET /api/v1/channel-platformsremains allowed for delegatedaccount:read. - Execution permissions (
docs/EXECUTION_PERMISSIONS.md) are default-off and support person/org/global rollout cohorts. Global/org activation and clear-that-enables also requirepermissions:execution-enrollment-v1readiness; auth uses zero-read snapshot/person hints and admission resolves the live flag before marking work. Enablingpermissions:execution-v1requires reader,permissions:execution-dispatch-v1,permissions:execution-authoring-v1andpermissions:execution-authoring-v2readiness; the override and person hint commit together. Unmarked contexts add no database commands. Phase A covers bounded ordinary HTTP proxy/MCP/LLM and assistant owner/shared connection admission; Covered suppresses only mode-risk, personal-service approval and exact-actor connection-consent prompts. Eligible assistant MCP/proxy gaps create one privateApprovalRequest.execution_proposal; B1 adds v2 proposals for personal external keys, standalone LLM, native permission keys, watches and human-origin voice tasks. External proxy/MCP/LLM/native calls keep the owner-configured connected approval wait and real response; only validX-NyxID-Approval-Mode: async(only then mayIdempotency-Keydeduplicate; downstreamPrefer/idempotency headers alone never opt in) opts into background execution/readback. A caller can sendX-NyxID-Approval-Wait-Seconds(one decimal integer, 10–300) to cap both the connected wait and card expiry from request receipt at the shorter of the budget and configured timeout. Omitting it uses the existing wait. Invalid or repeated values return 400 before approval creation. Eligible v2 async proposals use their async deadline when both controls are present.nyxid proxy requestsends both controls with an 80-second budget by default (--approval-wait <secs>to change,--no-approval-waitto omit). Timeout/disconnect expires undispatched connected occurrences as permanently not sent. Login-child credentials remain Operation-only; external requests have no Task choice. Non-retainable effects retain legacy prompts. All independent floors/ceilings remain. Egress rechecks live authority/task/enrollment and CAS-claims onlyValidity::OperationthroughApprovalGrant.execution_use; reusable permissions are not consumed. First-party human decisions atomically write permission plus exact-effect resume intent; Operation is default, reusable scope must be enforced on every use, and the per-effect send CAS is independent of validity. Retained encrypted effects are capped at 256 KiB; uncertain sends never retry. Legacy handlers refuse proposals, notifications/mobile are link-only, and the existing TTL stays unchanged. No legacy migration ships here. Phase B additionally covers verified personal Google/Drive native-key plans, signed assistant-job service HTTP, independently admitted watch lifecycle calls, and bounded voice-task service calls. Machine HTTP gaps retain legacy prompts until B2/node negotiation; eligible B1 sources use v2 proposals through the same person/org/global enrollment resolver. Native verification reads never consume the primary claim, pre-send refusals are not uncertain, and persisted child/task/actor fences prevent consent transfer. Live voice/WS/media and external Machine principals remain outside coverage. Execution-result delivery v5 keeps only a confirmed-prefix plan and exact MongoDB-time preparation/send fences; old workers ignore v5 and uncertain sends never retry. - Platform-model tariffs require
billing:model-prices-v1fleet readiness before authoring new enum units.model_priceslane bindings select immutable completeplatform_model_tariffsrevisions; never use base/legacy fallback. Revision-qualifiedt<revision>Lago codes, exact per-code usage evidence and frozen reservation rates use the existing funding, tax, ledger, residue and reconcile paths. Retain old prices for accepted work; never reclaim forwarded holds without final evidence. Seedocs/PLATFORM_MODELS.md#pr-2-immutable-tariffs-and-exact-units. - Security readiness needs no roster/drain configuration: heartbeats record observed support after 90 seconds without hard blockers, or immediately on a legacy clean assessment. Serving, publication and flag enables (
require_flag_enable) require durable activation and support on every live generation; unknown ordinary flags stay ungated.readyis diagnostic only; roster/drain conditions are advisory. Declared mismatches emit one asynchronous warn+audit per condition per day; undeclared fleets emit none. Enabled flags that cannot serve retain the per-flag minute diagnostic. Old non-observing binaries remain invisible; seedocs/SECURITY_ROLLOUT_READINESS.md. - OAuth W1–W4 authority: equal consent is a no-op; ordinary review unions the live grant, while codes keep only the request's authority. Pure broadening retains the authority revision; narrowing/regrant rotates it. Independent
write_versionCAS, transactional revocation fences and Machine/binding checks prevent stale replay. Never widen/rebind an existing token. Seedocs/security/OAUTH_AUTHORITY_ROLLOUT.md. - OAuth redirect execution and registration share one parsed-URL policy (exact raw matching, no browser/content/local-file or opaque schemes, including legacy rows). Native/loopback handoff and browser consent POSTs share a branded script-free renderer. Keep the SPA
form-action 'self'policy. - Native NyxBot gateway sources are explicit, serde-defaulted
gateway_sourceidentities. Keep legacy relay payloads/streams unchanged. Native enrollment requiresnyxbot:native-gateway-v1readiness and the existing per-platform flag.preparingpermits bindings only; turns require committed gateway transport andready.nyxbot_gateway_sourceowns source eligibility, capabilities, credential bundles and closed identity validation; extend it for new platforms. Native responses use encrypted bounded 24-hour snapshot/SSE replay, current key/binding authorization anddelivery.state:replay(never claim these with legacy delayed senders). Bind recovery rows to assistant conversations in the turn transaction and purge with conversations/owner erasure. Native message admission shares the relay dedup namespace. Native Discord release retains an old-reader-compatible drain guard: no new IDENTIFY until confirmed remote deletion/absence plus 90 seconds; uncertain deletion still blocks a new IDENTIFY, while parked Discord releases are re-observed automatically and audited withnyxbot_gateway_release_failed. Native async updates retainChannelOrigin.native_event_idand never substitute a newer reference; omit this optional field on legacy origins. Never reuse relay image anchors on native sources. Seedocs/CHANNEL_EVENT_GATEWAY.md. Discordselectedis not connected evidence: health uses optional binding-scopedgateway_intakeand live relay lease/fence observations, never an olddelivery_status:ok. Stale direct setup repair must retain remote uncertainty and the 90-second drain; no automatic rollback of adopted native bots. See #2328/#2323 anddocs/CHANNEL_BOT_RELAY.md. - Supplemental NyxBot text on relay-source gateway channels (notices, team results, permission results) uses the local route-key relay adapter. Native sources use side messages when the original event advertises the capability. Otherwise, results use event replies and progress is skipped. See #2310, #2461 and
docs/CHANNEL_EVENT_GATEWAY.md.
Crash diagnostics are default-off behind diagnostics:crash-reports and fleet readiness. Require policy-2 account and device acknowledgement; keep the policy-agnostic analytics gate unchanged. Build closed records with no messages, raw stacks, URLs, function names or request context. Only the owner-free sanitized projection may reach the fenced exporter. See docs/CRASH_REPORTING.md.
5a. Vendor URN Namespace
NyxID-vendored URN types live under urn:nyxid:params:oauth:<category>:<name> (the params:oauth infix mirrors urn:ietf:params:oauth:* so generic vendor-extension parsers recognize the shape). Registered:
urn:nyxid:params:oauth:token-type:binding-id-- RFC 8693 subject_token_type identifying anOauthBrokerBindinghandle; used at/oauth/tokenwithgrant_type=urn:ietf:params:oauth:grant-type:token-exchange.
Add new entries here when introducing additional vendored URN types.
6. Node Proxy Conventions
- Ordinary node credential updates/removals use durable delivery generations independent of approval epochs; commit intent with material, retry through owner routing, and persist/compare node high-water marks before acknowledging (see
docs/NODE_PROXY_ARCHITECTURE.md). NodeWsManager: in-memory connection pool shared viaArcinAppState;DashMapfor lock-free concurrent accessNode.user_idis the polymorphic owner field (person or org user, matchingUserService/UserApiKey). Do not add a separateorg_idto node-related models; ACL viaorg_service::resolve_owner_access(actor, node.user_id).- Registration tokens carry the chosen owner and authenticated person issuer separately. Admin role is verified at issuance, not redemption. Mint and redemption transactionally fence the live owner/issuer/org lifecycle; redemption consumes the still-live exact capability. Demotion/removal/personal departure retires the issuer's pending registrations; legacy unattributed org tokens require reissuance and are conservatively cleared on admin departure. Preserve established org-owned nodes and other admins' attributed tokens. TTL defaults to 1h (
NODE_REGISTRATION_TOKEN_TTL_SECS). - Node auth tokens (
nyx_nauth_...) and registration tokens (nyx_nreg_...) are 32 random bytes; only SHA-256 hashes stored. HMAC signing secrets are generated at registration: SHA-256 hash on server, encrypted locally on the node agent. - WebSocket handler (
handlers/node_ws.rs) authenticates in the first message, not via HTTP middleware - Catalog master credentials (including legacy internal rows) always use server transport; HTTP/WS and MCP ignore owner-node bindings for these rows. This intentionally hardens legacy behavior: nodes inject only node-owned credentials. Explicit platform connections reject node selection.
node_routing_service::resolve_node_routeruns before credential resolution inexecute_proxy(); returnsNodeRoutewithfallback_node_idsfor multi-node failover- Streaming proxy:
proxy_response_start/ chunk frames /proxy_response_end; preferred chunk transport is a WS binary frame with a 36-byte request_id prefix, with legacyproxy_response_chunkJSON fallback for older servers - Node metrics (
node_metrics_service) recorded fire-and-forget after each proxy request; stored as embeddedNodeMetricsdocument on the Node model. Node-routed audit events include"routed_via": "node"and"node_id". NodeStatusis an enum (Online/Offline/Draining) -- not a bare string. WS writer channels are bounded (capacity 256);try_sendtreats full buffers as node offline (H4).- WS auth-frame injection rules live on
DownstreamService.ws_frame_injectionsandUserService.ws_frame_injections; additive, separate from HTTPauth_methodinjection.WsFrameDirectionis the trigger direction: adownstreamrule matches frames from the service and injects the configured response back toward it. Credential placeholders apply only to frames sent to the downstream service. The direct bridge skips stored caller-facing replies with a placeholder and forwards the triggering frame. Both bridges emit metadata-onlyws_frame_auth_injectedaudit events, withoutcome: "skipped"for a skipped reply. - SSH services use
ssh_auth_mode(cert|node_key|proxy_only); legacycertificate_auth_enabledtrue/false maps tocert/proxy_only. Node-key credentials live only in the node-local encrypted store, keyed by(service_slug, principal), with configuredhost_key_sha256enforced by the russh client. Cert-modessh execand browser terminal also run through russh on the node agent (backend-issued ephemeral private key + OpenSSH user certificate) and verify target host keys against a node-local TOFU storessh_cert_host_keys.tomlin the node config dir; pins are enforced on every session, and a changed key returnsSshHostKeyMismatch(1012) +ssh_host_key_mismatchaudit. Manage pins withnyxid node ssh cert-host-key list|pin|forget(pinpre-seeds/replaces a SHA256 fingerprint;forgetis the legitimate rotation recovery path; the store is live-reloaded, so no daemon restart).ssh proxyis unsupported fornode_key-- usessh execor the browser terminal. - Admin node endpoints (
handlers/admin_nodes.rs) require admin role and have no ownership check nyxid node daemonmanages background service lifecycle (cli/src/node/daemon.rs): launchd LaunchAgent on macOS / systemd user unit on Linux. All node commands support--profilefor multi-instance: service labelsdev.nyxid.node.{profile}(macOS) /nyxid-node-{profile}.service(Linux), config at~/.nyxid-node/profiles/{name}/.- Machine nodes add locally-authoritative
shell/files/computercapabilities (all off by default), mandatory signed requests, bounded jobs/files, cua MCP stdio, job-bound service gateway and human-only live desktops. Only owner-turn assistant chat keys can use them; guests never. Specialists storemachine_node_idsandsaved_login_idsbesidegrants. Owner settings (machine_confirm, single-user saved-login opt-in) are human-only. Browser policies/extension/native host belong to the supervisor;--separate-userssetups use distinct browser and command identities. Saved logins are encrypted, write-only, exact-origin fills, with no secret-bearing Debug, logs, audit or tool results. Setup/control watches queue their event transactionally. No extra machine DB reads on unrelated proxy/MCP/turn paths. Seedocs/MACHINE_NODES.mdfor the binding contract anddocs/NYXID_NODE.mdfor setup and warnings.separatedmode is opt-in behindassistant:machine-contexts, changed only through an owner action card, and never called isolated; seedocs/MACHINE_AGENT_ISOLATION.mdfor residuals. Existing assignments remainshared_legacy; full isolation requires a separate machine container/VM per agent. - Machine exec
servicesis an explicit per-job least-privilege declaration (default none), bound as ID+slug on MachineJob, shown on cards/audit and rechecked at gateway execution. Server cataloginference.wire_protocolandgit_httpmetadata generate the signed SDK/git environment; no node slug mappings. Reuse the shared service visibility resolver and middleware API-key identity constructor. Preserve Content-Encoding with Content-Length through both streaming hops. Non-isolated shell warnings must explicitly mention access to node tokens/signing secrets/stored credentials; recommend the container or--separate-users, never refuse solely for owner-machine risk. Container Chromium uses user-namespace/seccomp sandboxing via the shipped profile; every Linux agent/file child sets NoNewPrivs and denies namespace syscalls through a per-process filter; browser/cua retain sandbox namespace access. Human live view uses X11/XTest or ScreenCaptureKit/separate human cua input, at 30 Hz with JPEG dirty rectangles and zero idle payload; agent actions/observations stay on cua. Controller revisions cancel in-flight agent work without locks across I/O. Run extension freshness/unit tests and machine container e2e in PR CI. Performance measurements and repeatable commands:docs/MACHINE_NODES.md#validation-and-measurements. - Machine automation turns retain live machine/login grants and owner-control fences. In Auto and Ask every time, webhook confirmation is additive to
machine_confirm; one exact, one-use owner card satisfies both. Full access bypasses ordinary machine confirmations with an automatic receipt; covered org declarations still need trusted instruction or an exact command card. Exec, file writes/saves, job cancellation and mutating computer input are destructive; checked login fills and owner-control requests are changing only. Apply the gate in the machine adapter after normalization so direct and universal tool calls agree. Machine gateway streamed uploads bind exact services and never retry another node or pool member; declared pools support buffered SDK/JSON requests with normal failover and live member ACLs. Catalog discovery projects one ID-bounded batch. All human machine routes reuselogin_client_context::require_first_party_human; desktop upgrades also retain the/assistant/nyxagent/*OAuth-client rejection layer.
7. OpenClaw Integration
OpenClaw is a self-hosted AI gateway integrated at three levels (details: docs/OPENCLAW_INTEGRATION.md):
- Provider: seeded as an
api_keyprovider withrequires_gateway_url: true; users supply gateway URL + bearer token.UserProviderToken.gateway_urlstores the per-user instance URL;proxy_service::resolve_gateway_url_override()overrides the service's defaultbase_urlat proxy time. - Node proxy:
nyxid node openclawstores credentials locally, registers the provider connection, and creates the node service binding in one step. Flow: NyxID -> node agent (WS) -> local OpenClaw; the node agent injects the bearer token from its credential store. - Channels:
openclaw_channel_servicehandles inbound webhooks from OpenClaw channels (WhatsApp, Telegram, Discord, ...);openclaw_channel_mappingsmaps channel users to NyxID users, each with its own per-user webhook secret (SHA-256 hash stored, raw secret returned once). No server-level env var needed.
Key files: services/openclaw_channel_service.rs, handlers/openclaw_channel.rs, models/user_provider_token.rs (gateway_url), models/provider_config.rs (requires_gateway_url).
8. Streamlined Services Architecture
MCP and proxy connection selection applies live service authority before
same-slug resolution and preserves the selected UserService.id through
discovery and dispatch; see docs/API_DISCOVERY.md
for the connection-selection invariant.
- Tools are internal catalog offerings with publication enforced across MCP, HTTP and WS execution; preserve legacy defaults and MCP names. See
docs/TOOLS.mdfor runtime creation, publication and listing rules. service_preferencesis per acting identity: NyxBot enforces eligible personal-first, per-catalog connection order at concrete execution; ordinary external clients retain advisory discovery ordering (nyx__search_tools/nyx__list_connected_services,/keysgroup-relativepreference_rankand disabled-inclusivepreference_position). Exact owner selection and bounded verified fallback are described indocs/NYXBOT_SERVICE_EXECUTION.md;tools/list//mcp/configstay unchanged. Exposed ranks are dense after authorization; scoped group PUT and explicit hidden DELETE require verified first-party human auth. Scoped saves preserve unrelated/hidden/stale IDs; only hidden DELETE releases IDs outside the full authorized inventory.
Services/connections/providers were unified into 3 user-managed collections plus one orchestration layer; old collections are kept for backward compatibility during migration.
- Collections:
user_endpoints(target URLs, custom or from catalog),user_api_keys(external credentials: API keys, OAuth tokens, bearer tokens),user_services(proxy routing config: endpoint + key + auth method + optional node + identity propagation + custom User-Agent override) unified_key_serviceauto-provisions all 3 records from a singlePOST /api/v1/keysrequest, using catalog defaults or user-provided values- Proxy resolution checks
UserServicefirst (by slug + user_id), then falls back to the legacyDownstreamService+UserProviderTokenpath for unmigrated users - OAuth SDK (
@nyxids/oauth-core/@nyxids/oauth-react): use expiry-awaregetAccessToken()and atomic rotated refresh persistence; retain credentials on retryable failures. Web Locks serialize shared browser storage. - OAuth resource indicators: RFC 8707 resource URIs for user services are deterministic and not stored. The canonical URI is
{BASE_URL}/api/v1/proxy/s/{slug}where{slug}isUserService.slug; catalog and user-services responses expose this asresource_uri. OAuthresourceparameters resolve activeUserServicerows through the same personal/org ACL model used by proxy resolution. Issued JWTs keep the fixed NyxID audience while carrying granted resource URIs in aresourcesclaim plusallowed_service_idsfor enforcement. - Proxy User-Agent: client UA is forwarded as-is by default;
UserService.custom_user_agent/DownstreamService.custom_user_agentoverrides it in all four proxy paths (direct HTTP, node HTTP, direct WS, node WS). Use for downstreams whose WAFs block SDK UA strings (e.g.OpenAI/Python). ApiKeyscope fields (absorbed from the deletedAgentGroupmodel):allowed_service_ids,allowed_node_ids,allow_all_services,allow_auto_connected_services,allow_all_nodes; enforced at proxy time viakey_service- Frontend: unified "AI Services" page at
/keyswith 2 tabs (External Services; NyxID API Keys with scope). Services/Connections/Providers removed from the normal user sidebar (admin-only); old/api-keyspage deleted. - Legacy models kept for migration: DownstreamService (now the read-only catalog), UserServiceConnection, UserProviderToken, UserProviderCredentials, NodeServiceBinding (node routing absorbed into
UserService.node_id) - Lifecycle is exactly two actions, named Disable/Enable (reversible, sets
UserService.is_active) and Delete (hard-deletes credential + endpoint, leaves anis_active: falsetombstone). Do not introduce further synonyms;revokedis a credential status, not a button verb.GET /keysis the one listing that returns disabled services — consumers MUST readis_activerather than assume every row is usable, and MUST NOT renderstatus(the credential's) as the service's state. Every credential-resolving or catalog path keeps the active-onlylist_user_services_with_sources; onlylist_keysuses the_including_disabledvariant, with effective service-allowlist filtering on top for restricted API keys./keys/{id_or_slug}resolves a disabled row by UUID but deliberately not by slug — full rationale and the two known gaps indocs/AI_SERVICES_ARCHITECTURE.md. - AI-service inventory GETs under
/api/v1(/keys,/keys/{id_or_slug},/keys/{id_or_slug}/authorization,/user-services,/endpoints,/endpoints/{id}/authorization,/endpoints/{id}/openapi-endpoints,/api-keys/external,/api-keys/external/{id}/authorization,/mcp/config,/catalog,/catalog/{slug},/catalog/{slug}/endpoints) accept general API keys without provisioning or lazy pending-OAuth reconciliation./mcp/configrequiresproxyorproxy:*scope and matches stateless MCP discovery, including chat acknowledgement semantics. Restricted keys use their effective service allowlist and backing endpoint/credential references; org-owned keys act as the org (credential_source.type: "personal"), personal keys use active Member/Admin memberships and effective role scopes. Inventory writes and NyxID/api-keysmanagement stay human-only for API keys; delegatedaccount:readparity is unchanged.
Platform-admin service account create/update with explicit catalog:skills:read/write scopes atomically sets server-only catalog_scope_authorized=true, sticky purpose=catalog_editor, and protection. These accounts use matching token/live catalog scopes across all existing and future catalog services without catalog roles, activation, or per-resource grants. /keys and /keys/{uuid} need only catalog read scope and return projected catalog metadata with catalog UUIDs and resource_type: "catalog_service"; no private connections. Legacy editors (marker absent/false) retain live global nyxid:catalog:skills:read/write role checks and additional user-services:read for key GETs until explicit admin scope save. Stored General/Curation scope strings never auto-elevate. Skill writes transactionally fence account/token authority and legacy authorizing roles. General and legacy Curation SAs retain their separate connection metadata grant behavior. CatalogEditor Ornn proxy resolves the exact catalog UUID or slug; operation policy is optional only for scope-authorized editors and configured policies remain enforced. Scope-authorized editors may use the guarded internal catalog credential (JWT/Both identity, no provider configuration, platform key, or destination targets); forwarding requires a signed SA identity. Legacy editors and Curation retain mandatory policy and dedicated credentials. See docs/SERVICE_ACCOUNTS.md.
Key files: services/unified_key_service.rs, services/catalog_service.rs (list_catalog_all), handlers/keys.rs, handlers/catalog.rs, models/user_{endpoint,api_key,service}.rs.
Catalog Manager (catalog_manager, nyxid:catalog:services:write) lets an Operator create providers and public HTTP catalog services, edit rows they created, and complete shared rows (including seeded ones) through the CLI: on any provider, scopes/supports_oauth_scopes/name/description/docs/API key instructions and link/icon (display links must be absolute http(s)) and the first OAuth client; its URLs, credential mode and token settings only before anyone has connected through it (no user tokens/connections/own clients reference it), and once a platform client exists only with that client re-entered in the same request (constant-time proof of possession; secretless clients stay Admin-only). Manager provider writes are version-guarded on updated_at. On shared catalog rows (public, unowned, HTTP, non-internal, non-Tool) they edit descriptive fields and the spec URL and add/update/delete/discover/pause/publish operations. Replacing or clearing others' clients, provider deactivation, deactivating or deleting rows they did not create, private/owned/Tool rows, and credential/identity/billing/policy fields stay Admin-only. Rows a Catalog Manager creates are marked catalog_manager_created; on those rows a non-admin may change the row or its endpoints only while holding the role, anonymous rules stay Admin-only, and destination changes are refused once an Admin attaches a credential or foreign provider. Unmarked rows keep the plain creator rule. Classify every new provider/service request field in handlers/catalog_authority.rs (exhaustive destructuring). CLI: nyxid admin provider ..., nyxid admin catalog add|apply|validate with secret-free manifests (cli/templates/catalog/). See docs/CATALOG_MANAGER.md. Identity resync (POST /services/{id}/resync-identity, nyxid catalog resync-identity, the service page's can_resync_identity) is human-only and authorized by catalog_authority::require_service_update_authority with a body setting every identity field (Admin or plain creator); it rewrites only connections whose identity differs.
CatalogEditor PUT /keys/{catalog_uuid} accepts only recommended_skill_refs with live/token catalog write authority (plus the existing role for legacy editors). It uses the shared skill transaction against one server-observed revision, returns safe metadata without requiring read scope, and never rebases conflicts. Explicit revision/replay clients use /catalog-curation/services/{id}/skills. Human key writes keep their original handler; other SA purposes, API-key, delegated, and relay writes remain denied.
9. Agent Isolation
Per-agent credential binding, rate limiting, and audit attribution: each agent (Claude Code, Codex, OpenClaw, ...) uses its own scoped API key (nyxid_ag_ prefix). Details: docs/AGENT_ISOLATION.md.
- General agent keys can GET
/orgs,/orgs/{key},/orgs/{key}/authorization,/orgs/{org_id}/members,/orgs/{org_id}/members/{member_id}/authorization, and/orgs/{org_id}/role-scopesunder/api/v1, with membership/admin ACLs and no extra scope. Org-owned keys list their own org with Direct read access projected asyour_role: "admin"; all writes, invites (including GET), and primary-org changes remain human-only for API keys. Scheduled-invocation keys remain denied; delegatedaccount:readparity is unchanged. ApiKey.allow_auto_connected_servicesadds active, same-owner auto-provisioned and explicit platform-bound service IDs to restricted keys at auth-context construction; defaults to false. Human/delegated key listing, Agent Key login delivery (login options), and device-code approval/onboarding for the acting person's own account invoke shared provisioning. Public platform services create personal auto rows only; restricted platform services may create org rows only for allowlisted orgs reached through active Member/Admin memberships withcan_proxy()and explicit grants. The 0.19.0 guarantee remains: org-targeted device approval/onboarding resolves existing org services and never provisions rows for the target org as a side effect of targeting. Grant removal or a switch to public reconciles those org auto rows away; startup also removes legacy public org auto rows. Legacy no-auth provisioning remains personal-only during membership traversal. JWT/API-key authentication itself never provisions rows.- Global approval has three states: absent
NotificationChannel.approval_requiredmeans Writes only (default); explicit true means All requests, false means Off. Lazy settings/tool-approval creation must preserve absence. Unknown operations are writes; stateless inference uses the existing closed catalog contract, never a service-name heuristic. Personal approval requirements (explicit per-service or global) never gate a live assistant turn’s own closed stateless catalog model call. Deny and org policy still apply; Session bypass, guests, auto-connected and durable fences otherwise retain precedence. Unmarked unreleased W9.3 true rows keep true; only an owner action clears them. Upgrade and drain every old replica before relying on new-user write protection; seedocs/SECURITY_ROLLOUT_READINESS.md. AuthUsercarriesapi_key_id,api_key_name,rate_limit_per_second,rate_limit_burstwhen auth is via API key;ApiKeyhasrate_limit_per_second,rate_limit_burst,platform;AuditLoghasapi_key_id,api_key_namefor attributionnyxid-assistantkeys belong to one chat, cannot be channel route agents, and cannot be widened by native chat tools. InternalASSISTANT_ACCOUNT_SCOPE(assistant:account) is held by NyxBot thread keys and by specialist thread keys with anaccount_readgrant (read-only tools); it is excluded from public scope assignment and grants no REST management authority.AgentServiceBindingmaps(api_key_id, user_service_id)to an overrideuser_api_key_id; the proxy handler checks bindings before credential injection and falls back to the service default- Operation scopes (
docs/AGENT_OPERATION_SCOPES.md) narrow specialists and ordinary general-purpose Agent Keys to selected operations per service, optionally with closed path/query/body input limits evaluated by the sharedpermissions/src/values.rsevaluator. Key scopes live inApiKey.assistant_operation_scopes(/api-keys/{id}/operations, human-only, revision-fenced; rotation copies them). Every transport callsauthorizethencheck_inputson the final request. Guest/webhook checks are turn authority and run whether or not a service is scoped; ordinary keys incur no extra reads. Scoped and permission-bound requests never follow redirects; scoped keys cannot use Oracle, SSH meta-tools or delegation-token services. Widening cards bind the compiledcontract_digest; retries must sendretry_arguments.JsonShape::Numberaccepts finite JSON numbers bounded byminimumandmaximum, withmax_fraction_digitslimiting decimal places; old enum readers fail closed. Upgrade all replicas before saving a scope that uses Number; remove all such scopes, including compiled key copies, before rolling back. PerAgentRateLimiter(mw/rate_limit.rs): per-API-key buckets, 1-second sliding window. Proxy responses includeX-NyxID-Agent-Idwhen the request used an API key.- CLI:
--profileflag onAuthArgs,LoginArgs,BaseUrlArgs, and all node commands (envNYXID_PROFILE); token storage~/.nyxid/profiles/{name}/(default profile uses~/.nyxid/); profile names 1-64 chars, alphanumeric + hyphens + underscores nyxid api-key create --platformandnyxid api-key bindmanage agent identities (consolidated from formerai-setup agentsubcommands)--orgflags accept UUID, slug, or display name, resolved in that order: UUID locally, slug viaGET /orgs/{slug}, display name via oneGET /orgsfetch (errors with candidate rows when ambiguous). Org users have an auto-generatedslug(visible innyxid org list).nyxid service add-sshalso accepts--orgfor org-owned SSH services.- Frontend: API key detail page has platform selector, rate limit editor, and bindings CRUD; the key table shows platform and bindings count
Key files: models/agent_service_binding.rs, services/agent_binding_service.rs, handlers/agent_bindings.rs, services/proxy_service.rs (resolve_agent_credential_override), cli/src/commands/api_key.rs, frontend/src/hooks/use-agent-bindings.ts, frontend/src/schemas/agent-bindings.ts.
10. Catalog Metadata and Endpoint Discovery
Rich metadata on DownstreamService so agents can discover service docs, repos, capabilities, and API endpoints without guessing (issue #148; details: docs/API_DISCOVERY.md).
- Fields:
homepage_url/repository_url/issues_url(validated URLs);capabilities(ServiceCapabilitiesboolean flags:supports_proxy_read,supports_proxy_write,supports_proxy_binary_upload,supports_direct_downstream_auth,supports_authoring_via_nyx,supports_websocket,supports_streaming);auth_notes/known_limitations(max 4096 chars);required_permissions(max 100 entries, 256 chars each) - API: catalog GETs require authentication and accept general API keys without proxy scope; service accounts remain rejected because catalog detail requires a User actor for restricted platform-grant membership lookup; delegated
account:readparity is unchanged. Template metadata/live grants never include instance overrides; instance-backed private access and mounted-spec fallback use effective API-key inventory scope.GET /api/v1/catalog?include_all=trueincludes system services that require no downstream credentials (default filters to connectable);GET /api/v1/catalog/{slug}/endpointsfetches + parses the OpenAPI spec (JSON, or YAML with bounded alias expansion) via hardenedapi_docs_service::fetch_spec_json(DNS pinning, 5MB limit, 60s cache); adminPOST/PUT /servicesaccepts all metadata fields with URL validation and length limits - CLI:
nyxid catalog list --all,nyxid catalog show <slug>,nyxid catalog endpoints <slug>. Frontend: "Service Metadata" sections on the service edit and detail pages. - Legacy:
migrate_legacy_api_spec_url()runs at startup to renameapi_spec_url->openapi_spec_urland remove duplicates; the update handler also includes$unset: { api_spec_url: "" }. - Hosted overlay specs: hand-curated OpenAPI 3.1 overlays with
x-aevatar-toolannotations live inbackend/specs/catalog/and are served publicly at/api/v1/catalog-specs/{spec_key}/openapi.json(services/catalog_spec_registry.rs; several slugs may share one overlay, e.g. github / lark-feishu pairs). Seeded rows getopenapi_spec_urlfrom the registry (insert-time + null-guarded backfill; admin-set URLs never overwritten).services/catalog_spec_sync.rsruns at startup and additively upsertsServiceEndpointrows from the overlays (matched by name; admin-added endpoints never soft-deleted) so/api/v1/mcp/configpublishes concreteservice_id+endpoint_idoperations for catalog-backed user services (issue #1290 / Aevatar v4 workflow admission). - MCP catalog precedence: a valid instance-mounted
openapi_spec_urlon a catalog-backed UserService overrides the template'sServiceEndpointrows (per-instance override wins); a broken/empty instance spec falls back to template rows when they exist, else degrades to the generic proxy tool. No instance spec -> template rows; empty + no spec still drops the service from the operation catalog. - Spec-URL auto-discovery: active HTTP catalog services with an
openapi_spec_urland zeroServiceEndpointrows get discovery run automatically (startup background sweep + on admin create/update with a spec URL) via the hardened fetch path; private/internal spec URLs still need the manualdiscover-endpointsroute, and services with existing rows are never auto-touched. - Overlay drift guard:
.github/workflows/catalog-spec-drift.yml(weekly + manual) runsscripts/check-catalog-spec-drift.pyto verify every overlay operation still exists in the official upstream spec for providers that publish one (OpenAI, X, Discord, ElevenLabs, Twilio); red = update the overlay by hand, never auto-updated.
10a. Catalog Skill Curation
- Dedicated Curation service accounts carry one live embedded grant with exact
DownstreamServiceIDs, persisted write budget, optional Ornn proxy target, and sticky platform protection. Curation Ornn targets require an explicit existingproxy_operation_policyat grant issuance and live resolution; use a dedicated endpoint with exact skill CRU/read rules, since Ornn also has auth-only execution routes. Only platform admins issue/revoke grants or manage protected credentials/roles; ordinary SA request DTOs must reject grant/purpose/protection fields. - The verified SA extractor confines Curation to grant-scoped
/catalog-curationand ordinary HTTP/proxy/{exact_ornn_catalog_id}. No slug routing,_nyxid_via, WS, MCP, LLM, owner connection/node/endpoint inheritance, or self-management. General SA routing stays unchanged. Validate every SA JWT against its persisted token identity/scope/expiry/revocation and current credential generation, including MCP/introspection; generation changes atomically with secret rotation. - Human and machine recommendation writes share
catalog_skill_service: service metadata/skills, revision/history, durable actor/request receipt, and machine budget/fences commit in one MongoDB transaction. Pure no-op has no mutation/receipt/effects; metadata-only mixed changes need a receipt without phantom skill history. Keep external identity/billing/OIDC/discovery effects after commit and repair retries from current committed state. - Preserve the existing names-based catalog digest; refs use a separate versioned skills digest. An instance name override suppresses catalog refs. NyxID owns recommendations, Ornn owns package bytes. Upgrade all auth/proxy/MCP replicas before enabling Curation credentials; disable/revoke before rollback. See
docs/SERVICE_ACCOUNTS.md#catalog-skill-curation.
11. Oracle Relay (browser LLM pools)
Retired 2026-10-22. NyxID's built-in oracle is permanently deprecated and blocked: a router layer (retire_builtin_oracle in routes.rs) answers every consumer and worker route under /api/v1/oracle with 410 oracle_retired (11099) before any handler runs, the nyx__oracle_* MCP tools are no longer listed and any call to one returns the same message as an error tool result, and the CLI nyxid oracle help says so. The handlers, services, models and CLI commands below stay in the tree but are unreachable; do not extend them. The error message must keep saying the feature is permanently deprecated and must not point callers at a replacement.
Generic async task relay: any NyxID user or agent calls a browser-driven LLM through /api/v1/oracle. A pool owns the shared worker token and quotas. A worker is the supervised CDP daemon or the unchanged userscript. Browser details stay in worker clients. Full design: docs/ORACLE_RELAY.md.
- Models: all documents use UUID-string
_idvalues andCOLLECTION_NAME.OraclePooluses the polymorphicuser_idowner.OracleTaskstores prompt and response bodies, task status, lease, serde-defaultedretry_count/max_retries/attempt_count, optionaldispatch_attempt_id, and terminal TTL.OracleSessionstores multi-turnconv_...metadata.OracleWorkeruses{pool_id}:{label}and has defaulted presence, capability, health, installation, and desired-state fields.OracleWorkerCommandstores leased, bounded command delivery.OracleLoginSnapshotstores only an outer-encrypted copy of an already end-to-end-sealed envelope with a one-hour TTL. - Queue and recovery (
oracle_task_service): MongoDB FIFO claim sorted bycreated_at; no in-memory state.task_timeout_secsdefaults to four hours andackrefreshes the lease. Lease expiry and worker-reported pre-sendbrowser_recovery_exhaustedconsume the same infrastructure retry budget and requeue to the FIFO front while retries remain. Exhaustion fails withinfrastructure_retry_exhausted. Fresh claims increment attempts; idempotent reclaims do not. Capable clients echodispatch_attempt_idon ack/result/pin/transcript so stale attempts cannot settle replacement work.client_refremains submitter-scoped submit idempotency. - Worker identity and commands:
POST /pools/{pool}/workers/allocatereserves a unique label: server-generated by default, or an operator-chosenlabel(validated; an existing unbound legacy row is adopted, a label bound to another installation is refused with 11014). New CDP workers persist a stable installation ID, so two installations cannot share one label. Managers can queuedrain,resume,restart,relaunch_browser,relogin, andupgrade;session_importis internal.DELETE /pools/{pool}/workers/{label}/commands/{id}(worker cancel-command) withdraws a queued or delivered-but-unexecuted command; delivered ones are dropped by the worker on its next heartbeat viacancelled_command_ids.DELETE /pools/{pool}/workers/{label}(worker forget) removes a stale presence row and its commands and releases the label's session affinity; it refuses online or busy workers unlessforce=true. Commands arrive only through capability-gated heartbeats, use delivery leases and bounded redelivery, and carry metadata-only audit records. Legacy userscripts advertise no capabilities and never receive commands or new protocol shapes. - CDP resilience: transient HTTP failures retry forever with capped jittered exponential backoff. CDP disconnects reconnect, repeated CDP and task-level failures relaunch configured Chrome, and tab failures reopen ChatGPT and restore the project URL. Task recovery has a bounded failure count. The mode
0600state file stores task ID, attempt ID, conversation URL, phase, transcript baseline, and failure counters only. Persistsend_attemptedbefore Send. After recovery, extract a completed matching turn, wait for an existing pending turn, or send only from a known pre-send phase. An uncertain post-send transcript must fail withprompt_delivery_uncertain; NEVER resend that prompt. Reasoning-level selection (selectModel) runs under a cooperative deadline with an abort signal, opens the structural composer pill regardless of locale, only treats menus that appeared after the pill click as the picker, never clicks an unrecognized entry, and is followed by a bounded composer-unobstructed guard before typing and before Send; the model family/tier is verified before the effort pill and again before Send.require_model_matchdefaults true on pools/tasks; switcher mismatch or recognized effort evidence that cannot verify fails pre-send asmodel_unavailable(unrecognized Tools/attach controls do not). Families parse generic major/minor versions; compare minors only when both exist. Exact tier-only entries require matching family context; at most one exact-family submenu is opened with a new menu identity baseline. Plain-proandextended/扩展prefer Pro Extended;standard/标准explicitly chooses Standard. Acks runpage_ready->selecting_model(second ack carries metadata-onlyphase_detail) ->ready_to_send->sent. Raw picker labels are logged only withNYXID_ORACLE_LOG_PICKER_LABELS=1. Model family/tier verification (selectModelSwitcher) prefers the header switcher and otherwise accepts a unique compact<version>\n<tier>menu button inside the composer form (also recognized as picker items); the marked switcher trigger is never an effort-pill candidate. - Failure attribution and capacity: bounded
failure_detailisstable_code@phase, never error text; preserve the last underlying cause through infrastructure exhaustion and delivery uncertainty. One metadata-only structural probe accompanies settlement.page_crashedreplaces the tab. After Send, empty output and scoped ChatGPT error UI reload once, recheck the send fence, then wait even without a generation indicator or fail as task errors; persistent pre-send error banners use one reload and one DOM-shape relaunch cycle.usage_limit_reached/model_unavailableuseexcluded_worker_idsand at most 20 capacity reroutes, independent of infrastructure retries; capacity failures settle with the original code when no eligible alternate has recentlast_seen_atfrom heartbeat/ack/claim (busy workers count), or the task is account-pinned. Usage cooldown defaults to 900 seconds (NYXID_ORACLE_USAGE_COOLDOWN_SECS); heartbeats continue without claims. Pool status exposes embedded bundle version and outdated online count; results and capacity reroutes retain canonical switcher/effort observations, with a diagnosticselecting_modelack before strict failure. Presence ignores and unsets legacypage_url. Old workers remain additive-compatible. - Pool-wide login:
nyxid oracle login <pool>performs password, OTP, SSO, and Cloudflare work in local Chrome, captures allowlisted ChatGPT/OpenAI cookies and storage through CDP, and encrypts locally with AES-256-GCM using HKDF-SHA256 from the raw pool worker token. The manager uploads only a 512 KiB-capped sealed envelope and token hash verifier, then stops Chrome and deletes the temporary capture profile. The server validates the verifier, wraps the sealed envelope withEncryptionKeys, TTLs it for one hour, and queuessession_importto capable workers. Workers defer import until task settlement unless a logged-out task cannot continue, decrypt locally, import through CDP, verify the logged-in DOM, and report per-worker results. A device-bound rejection is a clear verification failure. The persisted server state cannot derive the HKDF key, but the live backend sees bearer tokens while authenticating worker requests. - Worker token and bundle:
nyx_owk_...is 32 random bytes; only SHA-256 is stored, and create/rotate shows it once. Install and login use a local token file, environment variable, or hidden prompt and NEVER rotate implicitly. The backend embedsworker.mjs; manager and worker-token endpoints return source, version, SHA-256, and the exactplaywright-coreversion. CLI install and worker upgrade verify SHA-256. Worker upgrade runs npm only when the installedplaywright-corediffers from the manifest pin (bundle-only upgrades need no npm or network), using the install-time absolute npm path (NYXID_NPM_EXECUTABLE) with node's directory on the daemonPATH, and restorespackage.jsonon failure. launchd or systemd restarts the worker after upgrade. - Org worker enrollment:
worker install --pool <pool>automatically enrolls active Member/Admin contributors in org-visible pools using NyxID authentication; owners/admins can also enroll in pools they manage. No shared token is requested. CLI generates and privately persists anyx_owi_installation credential beforePOST /pools/{pool}/workers/enroll; the server stores only its hash. Every worker route checks actor/org activity, membership ID + join timestamp, pool token epoch, label, and installation. Members manage their own contributed workers; admins manage all. Enrollment inventory is capped at 256 separately frommax_workersdispatch concurrency. Rejoining after revocation/rotation requires authenticatedinstall --forceand a fresh credential (11016). New installs use their own browser accounts; shared-login capabilities and envelope access are excluded. Existing/explicit pool-token installs retain saved-login support. - ACL and compatibility:
ensure_can_submituses visibility andorg_service::resolve_owner_access;ensure_can_managegates pool mutation, legacy worker allocation, and login fanout. Worker management also permits eligible contributing owners throughoracle_worker_enrollment_service. Worker commands bind an immutable generation to prevent label-reuse races; enqueue/cancel/forget fence the authorized worker in Mongo transactions. Bundle download requires ordinary authentication; installation proves enrollment or manager access and verifies the worker endpoint's pool ID. Unauthorized task/session reads are not-found-shaped. Startup rewrites exactly the retired pool defaultchatgpt-5.5-protochatgpt-6-proidempotently. All new fields are optional or serde-defaulted. Existing rows, deployed userscripts, and old CDP workers remain valid. - Privacy: prompt, response, transcript, attachment, attachment filename, generated files, generated filenames, session, cookie, storage, raw-token, conversation-URL, and signed-image material must NEVER appear in logs or audit. Prompt, response, and generated artifact bodies live only on the task document and expire after
ORACLE_TASK_RETENTION_DAYS. Worker state contains metadata only. Login snapshot logs and audit contain IDs, sizes, target counts, status, and stable error codes only. Secret-bearing structs need redacted customDebug. - CLI: consumer and pool commands remain. Worker operations add
worker list/show/install/start/stop/status/logs/uninstall, control verbs, andworker upgrade.worker listreports only online workers by default and--alladds offline rows with their last-seen age.worker upgrade --pool <pool>waits for and verifies the installed local worker. Adding--labelqueues an asynchronous remote upgrade.oracle login <pool>performs local capture and pool fanout. Installs live under~/.nyxid-oracle/<pool>/, with named profiles underprofiles/<name>/, and reuse the node daemon's launchd or systemd pattern.
Key files: models/oracle_{pool,task,session,worker,worker_command,login_snapshot}.rs, services/oracle_{pool,task,session,worker,login_snapshot,worker_bundle}_service.rs, handlers/oracle_{pools,tasks,worker,workers,worker_bundle}.rs, cli/src/commands/oracle.rs, cli/src/commands/oracle_worker_daemon.rs, integrations/oracle/cdp-worker/worker.mjs, integrations/oracle/nyxid_oracle.user.js.
12. Auth Device-Code Login
First-party RFC 8628-style login: plain nyxid login and --device display a short user_code; a human chooses account access or a restricted Agent Key in the web UI or mobile app. Explicit --agent-key remains restricted-only.
- Storage and rollout: legacy
auth_device_codesremains account-only./auth/device/v2/{request,poll,poll-web}uses isolatedauth_device_codes_v2andnyx_adc2_poll secrets. Both protocols default to eight-characterXXXX-XXXXhuman codes;AUTH_DEVICE_EIGHT_CHAR_CODES=falserestores2-XXXX-XXXXv2 issuance, and both formats remain readable. Shared preview/decisions search both collections, reject ambiguous matches and use shared code reservations. Capability comes fromsupports_grant_choice, not spelling. Never retry v2 through legacy polling. Both collections store HMACs of codes, sanitized context and encrypted deliveries; raw codes and token plaintext never persist. Terminal TTL usespurge_atonly after cleanup; an indexed expiry sweep retains unfinished revocations. When upgrading replicas without shared readers/reservations, explicitly keep the flag false until they are drained; followdocs/ADR-015-auth-device-login.mdfor rollout and rollback. - Routes:
POST /auth/device/request,/poll, and/previeware public (no auth)./poll-webis also public but is a first-party browser-only delivery surface: it shares the/polllimiter, atomically claims the same delivery, revokes the approve-minted JWT session, and creates a freshnyx_sessioncookie session without returning tokens. Preview is non-mutating and returns untrustedclient_label/client_user_agentplus server-observedclient_ip, Z-suffix timestamps, and status.POST /auth/device/approveand/denyare human-only: JWT session user; API keys, service accounts, delegated tokens, and relay tokens are rejected before handler execution. Approve and deny race atomically onstatus = pending; deny mints no tokens and the next poll returns 11204. All routes are rate-limited per IP; decisions also share a per-user limit. - Grant decisions and delivery: only first-party human sessions/access JWTs without an OAuth client ID can decide grants. Restricted selection uses
/auth/device/approve-agent-key, so an old replica cannot silently issue account access. Issuance and approval commit together. Decrypt before atomically claimingapproved->delivered, retaining retryability on KMS failures. Account browser delivery atomically revokes approval bearer credentials and creates the cookie session. Restricted browser delivery returns a one-time CLI handoff without cookies; handoff redemption and direct polling have one winner. Abandonment revokes only its session/child, preserving reused parent configuration and other consumers. - Rate limiters:
auth_device_{request,poll,approve,approve_per_user,preview}_limiter(/poll-websharespoll) - CLI output: JSON includes
user_code, bareverification_uriandverification_uri_complete; text output and browser opening use the code-free completed link, which carries only validated preference hints. Displayuser_codeseparately for manual entry; never appenduser_codeordevice_codeto CLI login links. Poll secrets never appear in output.-c/--clipboardbest-effort copies only the user code before browser opening; failure prints one stderr line and continues. Clipboard conflicts with--passwordand--code, but is allowed with--callbackfor the device-code fallback.--no-wait --output jsonreturns a local request handle and completed login link without copying, opening a browser or polling. Explicit device/Agent Key login on stdin+stderr TTYs promptsOpen in your browser? [Y/n]and opens viacrate::browser::open_browser; failure leaves manual URL entry available. Without a TTY, explicit modes skip the prompt and poll. - CLI dispatch: plain blocking login deliberately defaults to selectable device v2, including desktop: it is the only terminal-originated flow with requester attribution (IP, timezone, origin, screen) and the human's account/restricted Agent Key choice (#1535). This motivated 0.16.0 (
78cb26b), whose commit message omitted the rationale.--callbackselects the legacy local browser callback (full account session, no code entry or requester review), with CannotOpenBrowser -> device-code fallback.NYXID_LOGIN_NO_DEVICE_FALLBACK=1is its legacy alias through the same dispatch path.--callbackconflicts with password/device/Agent Key/code/no-wait flags and rejects--output jsonorlogin resumeat the top of CLI dispatch (no callback JSON/resume contract). Without--callback, explicit device/Agent Key/code/resume/JSON/no-wait modes keep the exchange.--no-wait --output jsonnever waits or opens a browser;login resume <REQUEST_ID> [--once]uses a mode-0600 local handle bound to profile/destination, persists backoff/deadlines and returns distinct stable JSON errors. Poll secrets never appear in output. - Verification page (
/login/device): validates?user_code=and bounded preference hints, retains them in the URL and performs a non-mutating public preview on mount for a valid code. Manual code entry previews only after Continue. Invalid input fails visibly. Preview, scanning and verification never approve the requester. Review echoes the formatted code through final confirmation and asks the approver to match it against the requesting device/terminal and reject a mismatch (RFC 8628 §§3.3.1, 5.4). Account approval and key permission confirmation require first-party human authentication and explicit decisions with >=750 ms throttling. Legacy rows only offer account access./login/codeis a mint page without a code input. Anonymous phone preview leaves browser account cookies/storage untouched. Login-grant routes suppress telemetry even after SPA navigation from an opted-in page. Seedocs/DEVICE_LOGIN_PROTOCOL.mdfor the URL contract. - Approval identity:
/auth/approvalowns request-bound browser verification: begin, status/cancel, password/MFA, inventory and final approval/denial, plusPOST /{id}/appand/app/poll.LoginMethodsshares configured social providers, the NyxID app and enabled email/password between normal and approval login. Only for this request creates no general session; Keep me signed in creates one at verification. Password and social first factors both require NyxID TOTP/recovery when MFA is enabled; app verification derives authority from an existing authenticated human session under the saved QR MFA policy. Completed sessions explicitly carrymfa_assured; absent/null legacy rows and persistedmfa_exemption: mobile_rolloutsessions remain usable until normal expiry/revocation. Explicit false without an exemption still rejects/revokes once for MFA accounts. Only verified approvers may derive sign-ins (otherwise 2003), except QR/manual-code app approvals allowed byPUT /users/me/security(profile_config.security.skip_mfa_for_approved_sign_ins, default true, including absent preferences). Turning it back on for an MFA-enabled account requires a live verified human session; without MFA either choice may be saved. A no-op needs no step-up. Disabling needs no step-up and MFA disable preserves the choice but rotates its revision. The exception requires a live sid-bound human or request-bound app proof, retainsmfa_assured: falseandmfa_exemption: approved_sign_in_policy, and fences every exempt approval/delivery transaction on its exact live policy revision. Off/on never revives outstanding grants; completed sessions retain normal expiry/revocation. Ordinary login-code creation/redemption and unrelated derivation remain strict. Use a coordinated traffic cutover to a fully upgraded backend fleet before publishing the frontend: default-on approvals immediately write the new exemption and old replicas cannot deserialize it (mixed-fleet requests may 500). Before a backend rollback revoke allapproved_sign_in_policysessions and drain exempt grants/proofs./auth/mfa/step-upupgrades the current identified first-party human session using the login verifier. Sid-less first-party refresh acquires a transactionally bound fixed 30-daylegacy_migrationsession on first refresh, reused by every successor. In-flight legacy device/login-code/approval records without assurance fail closed. Default-offauth:mobile-mfaresolves personal features (including live org overrides) only at mobile social sign-in (typed mobile redirect or social id_token exchange); off exempts that device, on challenges. Password mobile login always requires MFA. Off permits anyone holding the social first factor to sign in through mobile without MFA and, by default, approve web QR login without TOTP; turning off the QR skip setting closes that derivation path. Flipping on preserves existing exemptions; enrollment assures the current identified session and transactionally revokes other sessions and refresh/MCP authority. App rows carry a server-onlylogin_approval_id; ordinary poll routes cannot redeem them. Publish this frontend only after all backend replicas support it. Roll back the frontend and drain outstanding app identity requests before a backend rollback. - Mobile approval:
CameraViewaccepts login QR links from trusted embedded frontend/API origins and the configured custom scheme (nyxid://login/device?user_code=...). The app extracts and normalizes onlyuser_code; every request uses its configured API base URL. Opening a trusted device-login app link or custom-scheme link automatically loads the non-mutating public preview. Manual code entry previews after Continue; scanning also previews. Approve/reject remain separate explicit authenticated actions under the existing human/MFA policy and >= 750 ms action throttle; opening, previewing and signing in never auto-approve. - Web login: only
/login(including its MFA app option) opts into native app QR payloads. On coarse-pointer devices with a ready, live native QR, tapping that QR opens “Open NyxID app?” confirmation. Only its affirmative link can open a new tab with no referrer, preserving the original polling tab. Other consumers use plainverification_uri_completeQR payloads and no handoff. No app opening on Continue, generation, mount, polling or resume; no installation/association success claim. Confirmation binds the exact request/URL, rechecks the original expiry on tap/confirm and retires on close, expiry, replacement or eligibility loss. Opening never approves; the user reviews, approves and returns to the original tab. - One-time codes: web/mobile settings mint through
/auth/login-code; public/redeematomically claims and issues either grant. Issuer-only status, cancellation and revocation expose no secrets. Five-minute codes are limited by source and owner and stored only as HMACs. Browser handoff extends the initial 60-second delivery window to approval + 300 seconds; repeated handoffs never extend that fixed deadline. First-party JWTsidchecks live session state during protected access and refresh; issuer revocation cascades to MCP and invalidates refreshed access too. - Local identity lifecycle: login replacement, refresh snapshots and logout use a profile generation under the refresh lock. An in-flight request cannot retry another login's token, including a replacement at the same destination. Bounded logout clears only the matching generation. Explicit credentials do not require profile storage or fall back to another identity.
13. Hosted Connect Links
Single-use hosted credential setup for agents and CLI callers. An authenticated creator requests a catalog service link and gives the returned URL to the same account's human user. App callers can receive lifecycle webhooks; polling remains available. See Third-party Connector Integration for the API and webhook contracts.
connect_linksstores UUID-string IDs and only SHA-256 hashes ofnyx_clk_tokens. Raw tokens appear once in the hosted URL and must never be logged, audited, or persisted in OAuth state.- Links default to 15 minutes, are clamped to 60-3600 seconds, and retain an observable
expiredterminal state through atomic query-time expiry claims. An OAuth or device flow pinned before expiry gets 30 minutes of finalization grace, then expires if it remains pending. - App-bound abandoned links are also claimed by the
CONNECT_LINK_EXPIRY_SWEEP_INTERVAL_SECSbackground sweep soconnect_link.expiredwebhooks do not depend on polling.0disables the sweep. - Preview is public and rate-limited but non-mutating. Completion is human-session-only; API keys, service accounts, delegated tokens, and relay tokens are rejected before the handler. Personal completion requires the exact creating account; org-owned completion uses
org_service::resolve_owner_accesswrite access. Unauthorized access is not-found-shaped. - Normal authorization-code access tokens issued to registered developer apps may create, read, and creator-cancel connect links; their JWT
client_idbinds the link to the active app record. Delegated, relay, and service-account tokens remain rejected on that route group, and no other rejection layer is weakened. App callbacks useoauth_service::validate_clientagainst registered redirect policy, while sessions and agent API keys retain shape-only HTTP(S) validation. The authenticated app ID/name overrides untrusted request-body attribution. - Hosted human decline uses the same raw-token and owner checks as completion but only transitions the link to
cancelled. Every terminal callback is built from the stored URI withstatusandconnect_link_id; existing query parameters are preserved, reserved parameters are replaced, and raw tokens are never added. Provider callback errors store only a normalizedlast_errorcode and timestamp while the link remains retryable. - API-key and OAuth provisioning must reuse
unified_key_service; completion is atomically serialized and single-use. OAuth state carries onlyconnect_link_id, while the browser keeps the raw token in session storage across the redirect. - MCP callers use
nyx__connect_servicefollowed bynyx__wait_for_connection. A pending link must not activate service tools or emittools/list_changed; activation happens only after completed status is observed. - After readiness activation of
assistant:hosted-connect-intent-v1, assistant personal-credential links (MCP, and Plugins/card "Connect your own" withassistant_personal: true, first-party human only) storeassistant_intent_lockedwithuse_platform_key=false. Plain Plugins Connect creates an ordinary link; assistant platform-key and credential-free connects stay one-step. Preview exposes the lock; completion and resume reject intent overrides. Legacy/non-assistant links keep their existing override contract. Connect links never auto-grant a specialist. - Assistant connection setup uses
nyx__connect_servicewith a visible catalog UUID or slug. Both named and unnamedsettings_link add_servicereturn structured connect guidance (identify the catalog first if unnamed); neither returns a page link. Give hosted links immediately with one short line of bounded existing-connection facts; never ask whether to proceed or suggest reuse instead. Explicit chat platform-key adds use unified connections; other non-hosted adds retain the legacy one-step connector, whose active duplicate returns successfulalready_connected(no separate account to add). Unavailable hosted flows return facts and an accurate non-link reason; provider-requirement-only refusal applies only to required providers without a catalog-owned credential form. Unified inventory reuses shared service visibility, excluding Viewer/scope-denied rows and both deleted tombstone shapes while retaining disabled rows. Unscoped NyxBot inventory also includes the actor's own active legacy connection for the catalog via a metadata-only projection (source: "legacy_connection"), sharing the ten-row bound and ownership wording. A retained unifiedmigration_connectionrow with matching legacysource_idsuppresses the duplicate legacy fact. Specialists never mint links and see only unified facts within their grants. External MCP contracts remain unchanged. Studio/keysremains Advanced setup for SSH/node/custom connections. Truthfulconnectionfacts distinguish self/shared person/organization and report unknown provider account identity.
13a. Bot Connection Links
- Tracked bot setup uses separate
channel_connect_linksstorage,/api/v1/channel-connect-linksendpoints, and/connect/bot/{token}. Preserve the existing service Connector link contracts and reusable channel setup URLs. See API reference and implementation and lifecycle. - Owner, platform, and label are fixed at creation. Agent Keys can create/read/cancel; setup routes require a human account with owner write access. Telegram consent remains bound to the account that started it, including for org-owned bots.
- Renewable claims fence setup. Bot insertion and link association are transactional, as are Telegram request insertion and association. Completion reserves one stable terminal event snapshot atomically. Manual
pending_webhookcan count as saved; managed setup must satisfy its readiness checks. Never discard a successful secret-bearing response because terminal recording failed. - Events are
channel_connect.completed,.cancelled, and.expired. App callers use their registered connection webhook; direct callers receive one encrypted-at-rest signing secret once. Bot delivery opts into public HTTPS validation, DNS pinning, redirects disabled, and a separate app quota. Preserve the existing Connector delivery path. The independent bot sweep sharesCONNECT_LINK_EXPIRY_SWEEP_INTERVAL_SECS;0disables both sweeps. - CLI direct webhooks require
--webhook-signing-secret-filewith--webhook-url. Create a new file with mode0600on Unix; reject existing paths and symlinks before creating the link. JSON and terminal output contain the file path and key ID only. Keep the raw secret out of output and logs; the direct HTTP API still returns it once.
14. Connection Webhooks and Triggers
- Developer-app connection webhooks use a server-generated secret encrypted with
EncryptionKeys. Secrets are returned only by configure/rotate responses, alongside a non-secret key ID. Delivery signsX-NyxID-Timestamp + "." + raw_bodywith HMAC-SHA256 and sends the signature, timestamp, event type, delivery ID, and key ID headers. Connect-link terminal events use the link as a durable bounded outbox; connection-expiry events remain best effort. Transition paths never depend on delivery success. - Outbound webhook configuration requires HTTPS and public DNS/IP targets. Apply
webhook_delivery_service::validate_webhook_urlto every new server-fetched webhook URL. - Trigger inbound secrets use the
nyx_trg_prefix and are SHA-256 hashed. HMAC verification additionally retains an encrypted copy because verification requires the raw key. Trigger and delivery types are serde-tagged enums; all secret-bearing structs use redactedDebugimplementations. - Trigger ingress is public; unknown and disabled triggers are not-found-shaped, then per-trigger rate limiting runs before body reads, HMAC decryption, or verification. Webhook-target envelopes are persisted only in
trigger_deliveries, encrypted withEncryptionKeys, and TTL-expired for durable dedup and authenticated replay;TRIGGER_DELIVERY_RETENTION_HOURS=0stores metadata only. Agent and notification payloads are never persisted; their event IDs use fenced, TTL-expiring dedup claims in MongoDB. Agent targets enter through the trusted channel-event service path without broadening the public channel-event auth contract. - Automations extend
Triggerwith defaultedwebhook/schedulesource andassistantdelivery. Schedule verification has no inbound secret or URL and ingress refuses it. Upgrade all replicas before creating automations: old readers fail on new enum variants, including owner lists and ingress; existing retries/replay and delivery TTL never sweep or delete automation rows. - Use covered, leased
trigger_workand UUID-v5 occurrence identities; advance schedules atomically with occurrence insertion and admit assistant runs in the turn transaction. Fence stale workers and never replay started turns. Missed history is one count/bounds summary plus one audit; history is metadata only and bounded, with counter-gated trimming. - Trigger turns preserve normal owner/agent authority and the existing turn pool without changing event streaks. Enforce separate owner budgets and per-trigger overlap. Card decisions wake the same run transactionally; expiry is the fallback. Initial admissions alone debit the owner occurrence budgets (30/hour and 300/day by default); coordinator and confirmation continuations never debit or defer on these budgets. Busy work uses bounded backoff; exhausted budgets wait for their next window with one notice. Avoid duplicate browser/channel continuations; result delivery uses live ACLs and fenced outbound attempts. Push-only notification results retain separate execution/delivery status and an owner-thread failure notice; retry only confirmed 429/503 refusals with no accepted or uncertain send, never the task itself. See
docs/NYXBOT_SCHEDULES.md. - Coordinator completion v2 is enrollment-only and default off (
AUTOMATION_CONTINUATION_V2_ENABLED). Per-run enrollment usesautomation:coordinator-completion-v2serving readiness; recorded active support tolerates roster warnings, while hard-unready admission stays legacy. Disabling affects new runs only: persisted v2 work drains without the flag. No trigger stamps or migration. A delivery's selected thread coordinates: NyxBot home, dedicated NyxBot/specialist webhook, or per-run; Run now follows the same policy. Track direct assignments, group requests and member @mention descendants with server-derived run/work lineage, never inherited execution authority. V2 children retain the webhook confirmation floor; schedules keep normal confirmations. Bound each run to 32 dispatches, 32 coordinator continuations andCOORDINATOR_DEADLINE_SECONDS(one hour); results wake it with a 60–300 second recovery backstop. History shows its deadline andcoordinator_timeout. Idle Stop never selects waiting runs; use the human-only run Cancel action. Disable and drain all bound runs/events/children/receipts/followers/cards/watches before downgrading; the admin/operator metadata diagnostic reports blockers. - Automation management, run history and timezone/budget settings require the shared first-party human guard; legacy trigger API-key rules stay unchanged. Only NyxBot exposes schedule tools. Store webhook prefill on an owner-bound watch, fetch it through authentication and consume it in the insert transaction. URLs contain only the watch ID; secrets stay on the page. Audit never includes instructions or payloads. Reuse trigger errors 11600–11606. See
docs/NYXBOT_SCHEDULES.mdfor limits, APIs and rollout details. - Webhooks default to dedicated threads for every agent and
confirmation_policy = changes. Dedicated/per-run automation threads must never be adopted as home, including after home deletion. Explicithomeordestructivechoices require UI/tool/setup warnings: home retains untrusted text for later full-authority owner/private-channel turns, outside the webhook policy. Classify changing calls through shared HTTP/catalog and native-tool contracts, snapshot policy per run, and enforce it in Auto and Ask every time. Full access bypasses it with an auto-allowed receipt. Schedules retain NyxBot-home/specialist-dedicated defaults and normal owner confirmations. - Cron gaps collapse at the first valid instant, deduplicated against real matches; folds use the earlier instant. Persist instants as UTC BSON dates; parse/format RFC3339 only in DTOs. Every NyxAgent route rejects OAuth-client tokens; first-party web/mobile/CLI tokens have no client ID. Ordinary denials bind the initiating user turn; trigger denials bind their active turn.
15. Agent Key Login
nyxid login --agent-key authorizes a CLI profile with a child login credential bound to an existing or newly created Agent Key. It never creates an account session or falls back to account login. Follow Rule 12's client-context sanitization, request attribution, explicit review, and throttling posture.
- Routes:
POST /auth/agent-key/{request,poll,preview}are public with shared per-IP limits.POST /auth/agent-key/{options,approve,deny}live inapi_v1_human_only; session/access JWTs for people are required, and API-key, service-account, delegated, and relay tokens are rejected. Approver actions have per-IP and per-user limits.GET/DELETE /auth/agent-key/selflive outside the human-only group and require the calling child credential; DELETE can revoke itself even without a write scope.GET /api-keys/{id}/credentialsandDELETE /api-keys/{id}/credentials/{credential_id}inherit key-management auth and personal/org ACLs; API-key callers are rejected by that router, and mutation requires write authority. - Credential model:
api_key_credentialsstores only a SHA-256 hash of eachnyxid_ag_secret, its parent ID, copied owner, sanitized label, request ID, lifecycle metadata, and bounded expiry.validate_api_keyreturns the live parent plusapi_key_credential_id; scopes, restrictions, bindings, rate limits, and audit attribution stay on the parent. Existing-key selection never edits or rotates that key. New-key creation uses the existing scope-authorized validation path, defaults both allow-all flags to false, and discards the primary secret; delivery always uses a child. - Exchange:
agent_key_login_requestsstores domain-separated HMACs of the opaquenyx_akl_device code and user code. Approval atomically commits the pending claim, optional key insertion, child issuance, and encrypted delivery in a MongoDB transaction. Pending requests last 10 minutes; approval opens a 60-second delivery window. Poll atomically claims approved -> delivered once and unsets ciphertext. Deny races only on pending. Failed approval transactions commit no orphaned key or credential. Poll/preview expiry and theAGENT_KEY_LOGIN_SWEEP_INTERVAL_SECSsweep (default 60; 0 disables) revoke undelivered children; terminal TTL never removes an unfinished cleanup marker. New rows set legacykey_was_created=falsewith separatekey_created_by_approvalattribution, so old sweepers cannot delete reused parents. Legacy pending-created parents remain ineligible for new consumers until delivered. - Revocation: logout revokes only the calling child (
logout); the key detail page revokes a child (web_revoke). Parent revoke/rotation deactivates children (parent_revoked/parent_rotated), and parent/child expiry is checked live. Metadata-only approval, denial, delivery, and revocation audits never contain codes or secrets. - Anti-phishing and privacy: share the CLI's code-free
verification_uri_completeanduser_codeseparately; the human must enter the code manually. CLI links contain only validated preferences. Browser-owned QR links retain their existing code-prefill contract. The public/login/agent-keypage follows Rule 12's URL contract: validate and retain the code/hints, perform a non-mutating preview for a valid URL code, and require Continue for manually entered codes. Malformed input fails visibly. Phone QR contains a user code, never a credential; scanning/deep linking prefills both web and mobile. Preview, scanning and verification never approve. Review echoes the code through final confirmation and instructs the approver to match the requesting device/terminal and reject a mismatch (RFC 8628 §§3.3.1, 5.4). Approval always requires review, key selection, permission confirmation, and an explicit decision with >=750 ms throttling./login/codeminting is unaffected. The computer's QR path uses anonymous preview polling at >=5 seconds, component state only, and clears temporary state at terminal/unmount without storing account credentials or cookies. - CLI profiles: atomic mode-0600
token,auth_kind=agent_key, safeagent_key.json, and existingbase_urlhandling. Stale account access/refresh/user files are removed. Saved Agent Key credentials never refresh, parse JWT expiry, or prompt for account login.whoami/statususe live self metadata; explicit/env credential precedence stays unchanged.session refreshexits 3; bounded logout clears the matching local login after best-effort server revocation, preserving a newer concurrent login.
16. Agent Plugins
The Claude (integrations/claude-plugin/) and Codex (integrations/codex-plugin/) packages and both repository marketplaces (.claude-plugin/marketplace.json, .agents/plugins/marketplace.json) are generated from integrations/plugin-source/ by scripts/sync-plugins.py; edit the source, regenerate, and bump its shared version. CI fails on drift, and a backend test fails when the skill names an MCP tool that does not exist or lacks annotations. The marketplace's nyxid plugin is the hosted-MCP package (plugin:nyxid:nyxid); nyxid-cli is the root CLI skill bundle that nyxid ai-setup installs (it uninstalls a pre-0.9.0 nyxid@nyxid, the old CLI bundle). Every tool listed to MCP clients needs a title plus annotations (tool_title / tool_annotations). MCP session fallback (Mcp-Session-Id without a bearer becomes allow-all, approval-bypassing AuthMethod::Session) is allowed only for sessions with session_fallback_allowed, which only unrestricted first-party access tokens set; app-issued (client_id) and service/node-restricted tokens, service accounts and legacy rows must re-present a live bearer. Never widen this. See docs/PLUGINS.md.
File Structure
cli/src/
|-- main.rs # CLI entry point
|-- cli.rs # Clap subcommand definitions
|-- commands/ # Command implementations (one file per command group)
|-- api_client.rs # HTTP client for NyxID API calls
|-- auth.rs # Token storage and retrieval (file-based session)
|-- output.rs # Table/JSON output formatting
backend/src/
|-- config.rs # AppConfig from env vars
|-- db.rs # MongoDB connection + ensure_indexes()
|-- routes.rs # All route definitions
|-- main.rs # Server startup
|-- models/ # MongoDB document structs, one per collection
|-- services/ # Business logic (incl. channel_adapters/{telegram,discord,lark,openclaw})
|-- handlers/ # HTTP handlers
|-- crypto/ # JWT, AES, password hashing, token generation, device-code Ed25519 verification, KeyProvider trait, KMS providers, JWKS
|-- errors/ # AppError enum, ErrorResponse, AppResult
|-- mw/ # Middleware: auth, rate_limit, security_headers
frontend/src/
|-- pages/ # Route pages
|-- components/ # UI components (auth/, dashboard/, layout/, shared/, ui/)
|-- hooks/ # TanStack Query hooks (one per domain)
|-- schemas/ # Zod validation schemas with vitest specs
|-- stores/ # Zustand stores (auth-store)
|-- lib/ # API client, constants, utils
|-- types/ # TypeScript type definitions
|-- router.tsx # TanStack Router config
mobile/src/ # React Native + Expo app (Expo 55, RN 0.83): app/ (shell, navigator,
# deep linking nyxid://challenge/{id}), features/ (auth, challenges,
# approvals, account, legal), components/, lib/ (API client, SecureStore
# session, push registration), theme/
sdk/ # OAuth SDK monorepo (@nyxids/* npm namespace): oauth-core (PKCE OAuth 2.0
# client, NyxIDClient), oauth-react (React context + useNyxID() hook),
# demo-react (private demo app)Key API Routes
NyxBot Notifications is default off (assistant:notifications) and requires the
NyxAgent engine flag. Upgrade all API replicas and scheduler workers before
enabling it. The acting person's feed stores identifiers and state only;
previews are joined after live visibility checks. Push preferences default off,
and NyxBot's read-only nyxid__list_notifications tool never marks entries seen.
See docs/chat/12-notifications.md for the normative contract.
| Notifications route | Purpose |
GET /api/v1/assistant/nyxagent/notifications | Cursor-paged feed with bounded previews and canonical source links |
GET /api/v1/assistant/nyxagent/notifications/summary | Bell counts and per-source unread markers |
POST /api/v1/assistant/nyxagent/notifications/read | Ids, source, or mark-all with server before fence |
GET/PUT /api/v1/assistant/nyxagent/settings | Additive notifications.push preferences, all false by default |
All API routes under /api/v1:
/auth-- register, login, logout, refresh, verify-email, forgot/reset-password/auth/device/v2/{request,poll,poll-web}and shared/auth/device/{preview,options,approve,approve-agent-key,deny}-- selectable login; legacy request/poll/poll-web remain account-only (Rule 12)/auth/login-code,/options,/redeem,/{id},/{id}/revoke-- human-issued single-use grants (Rule 12)/auth/agent-key/{request,poll,preview,options,approve,deny,self}-- Agent Key login and calling-credential identity/revocation (Critical Rule 15)/connect-links-- create, poll, creator cancel, public preview, human decline, and human-only completion for hosted service connections (see Critical Rule 13)/channel-connect-links-- tracked bot setup, signed terminal notifications, status and cancellation; human-only manual/managed/Telegram setup (see Critical Rule 13a)/developer/oauth-clients/{client_id}/connection-webhook-- human-only developer-app lifecycle webhook configure/disable;/connection-webhook/rotate-secretreturns a new signing secret and key ID once/triggers-- trigger CRUD plus human-onlyPOST /preview,GET /setup/{id}(webhook prefill),GET /{id}/runs(cursor-paged metadata),POST /{id}/runandPOST /{id}/runs/{run_id}/cancelfor Automations (admin/operator diagnostic:GET /admin/automation-continuations/readiness);/{id}/rotate-secret,/{id}/rotate-delivery-secret,/{id}/deliveries, and/{id}/deliveries/{event_id}/redelivercover inbound/outbound secret rotation, delivery history, and retained-envelope replay. Delegated, relay and service-account tokens are always rejected; agent API keys may manage only webhook-source triggers withoutassistantdelivery, while schedule-source andassistant-delivery triggers (automations) are first-party human only and omitted from API-key listings (seedocs/API.md"Inbound Triggers")/webhooks/triggers/{trigger_id}-- unauthenticated trigger ingress verified by token or raw-body HMAC (see Critical Rule 14)/auth/mfa-- setup, confirm, verify (login), step-up (current session), disable (nested under/authinroutes.rs;setupis idempotent against unverified factors per NyxID#506)/users-- get/update current user;POST /users/me/exportdownloads the bounded account data export/api-keys-- CRUD + rotate;ApiKeyscope + agent isolation fields per Critical Rules 8-9/api-keys/{id}/bindings-- agent credential binding CRUD (AgentServiceBinding)/api-keys/{id}/credentialsand/{credential_id}-- list and revoke login credentials bound to a key/services-- CRUD + OIDC credentials + endpoints + requirements/sessions-- list sessions/connections-- connect/disconnect services/providers-- CRUD + OAuth/device-code/API-key flows + token management + per-user credentials;/codex-connectionstatus/import and/codex-connection/verifyrequire first-party human auth and exact reviewed connection versions (seedocs/CODEX_CONNECTION.md)/admin-- user management, audit log, OAuth clients, service accounts/admin/usage-- admin/operator (ornyxid:admin:usage:readrole holders, e.g. seeded Usage Viewer; read-only) platform-wide usage, default 24 hours and maximum 31 days; actor/owner and service filters, primary-request deduplication, MongoDB ranking and exact/legacy funding costs. Metering requiresBILLING_ENABLED./admin/audit-log-- unchanged substring filters; count and page queries run concurrently. Unfiltered totals are metadata-based viaestimated_document_count(exact except briefly after an unclean shutdown), avoiding a collection-sized count scan. Every non-empty filter keeps an exact count; global-search-only counts use one collection pass instead of seven full index scans, and their pages use the existing sort index. Narrowing predicates retain normal index selection. Event-type filter options are derived display data cached per process/AppState for 30 seconds; audit rows and counts are never cached./assistant/nyxagent/*-- human-only, default-on NyxAgent conversations/history/rename/delete, model list (GET /models, per-owner live list withavailable) and per-thread model selection (PATCH /conversations/{id}/model, live-list validated, refused during a turn, auditedassistant_model_changed; agent models viaPATCH /agents/{id}model), turn SSE, Stop, acknowledgement decisions (POST /conversations/{id}/acknowledgements/{ack_id}), owner-only tool images (GET /conversations/{id}/attachments/{attachment_id}), working context (GET /conversations/{id}/context,POST /conversations/{id}/context/reset; durable checkpoint, seedocs/chat/08-nyxagent-engine.md), idempotent reply feedback (PUT/DELETE /conversations/{id}/messages/{message_id}/feedbackand the group equivalent), owner-only retry recovery (GET /conversations/{id}/messages/{message_id}/recovery; server evidence and one-use source claims, seedocs/chat/08-nyxagent-engine.md), agents (GET/POST /agents,GET/PATCH/DELETE /agents/{id},PUT /agents/{id}/grants,POST /agents/{id}/destroy,DELETE /agents/{id}/memory/{note_id}), settings (GET/PUT /settings), first-run onboarding (GET/PUT /onboarding,POST /onboarding/suggestions/hide,POST /onboarding/suggestions/show; interests, a fixed-ID NyxBot memory note and curated next steps, seedocs/NYXBOT_FIRST_RUN.md), channel links (GET/POST /channels,PATCH/DELETE /channels/{id}incl.private_chats) and their chats (GET /channels/{id}/chats,PATCH /channels/{id}/chats/{chat_id}), the owner's live change stream (GET /live, SSE, identifiers only), and cached profile discovery;PATCH /conversations/{id}/access-modeanswers 410. All routes enforce the engine flag and acting-person ownership/nyxbot/*-- NyxBot as the Agent Event Gateway'snyxbotprovider (agent-card,bindings/{binding_id},…/conversations/{conversation_id},…/events/{event_id},responses) authenticated inside each handler by the channel's gateway agent key, plusrelay/{channel_id}for NyxID's signed relay callbacks (direct platforms); outside JWT middleware/admin/assistant/profile-routes-- admin GET/PUT of NyxBot role-to-profile routes (stored and validated; inactive)/admin/assistant/feedback-- admin/operator/usage-read (nyxid:admin:usage:read) feedback aggregate and cursor-paged recent rows with reply context (from,to,vote,model,agent_kind,has_error,cursor)/assistant/actions-- public static assistant action manifest for Aevatar startup discovery/proxy/{service_id}/{path}and/proxy/s/{slug}/{path}-- authenticated proxy (UUID- and slug-based); HTTP + WebSocket passthrough/proxy/services-- service discovery (paginated list of proxyable services)/llm-- LLM gateway (provider proxy, OpenAI-compatible gateway, status)/delegation/refresh-- refresh delegated access tokens/notifications-- notification settings CRUD, Telegram link/disconnect, device token management/approvals-- approval history, grants, decide, status polling, per-service approval configs (approval_mode:per_requestdefault orgrantopt-in)/webhooks/telegram-- Telegram webhook (unauthenticated, secret-verified)/devices/code/request-- unauthenticated device-code binding start for headless devices; returnsdevice_code,user_code, verification URLs/devices/code/poll-- unauthenticated but Ed25519-signed device poll; returns pending user-code rotations or one-time credentials after approval/devices/code/approve-- authenticated approval (web + CLI); creates the scoped API key, node row, and refresh token.DeviceCodeApprove.default_servicesis an opt-in list of user-service UUIDs/slugs granted proxy access at approval; omit for an empty allowlist./devices/onboard-- authenticated server-side QR provisioning for no-WiFi headless devices; creates the scoped API key + device node stub, embeds WiFi + raw one-time credentials in anyxprov://QR payload, stores only the refresh-token hash, never persists the WiFi password/nodes-- node management (register-token, list, get, delete, rotate-token, bindings CRUD + priority update)/nodes/ws-- WebSocket upgrade for node agents (auth via WS protocol, not middleware)/admin/nodes-- admin node management (list all, get, disconnect, delete -- no ownership check)/integrations/openclaw/channel-- OpenClaw channel webhook (unauthenticated, HMAC-verified);/integrations/openclaw/mappings-- mapping creation (POST, authenticated)/keys-- unified key management: auto-provisions UserEndpoint + UserApiKey + UserService from catalog or custom input (CRUD + OAuth flows)/endpoints,/api-keys/external,/user-services-- list/update/delete for the three user collections/catalog-- read-only service catalog (?include_all=truefor full discovery;/{slug}/endpointsfor OpenAPI endpoint discovery via hardened spec fetch)/oracle-- browser LLM relay (Critical Rule 11). Consumer routes cover pools, tasks, attach, status, and sessions. Manager routes add worker allocation/list/show/commands, login-snapshot fanout, and the embedded worker bundle./oracle/worker/{task,heartbeat,ack,result,pin-conv-url,transcript,bundle,login-snapshots/*}authenticates with the pool worker token inside each handler and outside JWT middleware. The Oracle route groups have a 16 MiB body cap and normal global rate limiting. The manager login-snapshot route has a smaller request cap based on its 512 KiB decoded envelope limit./channel-platforms-- authoritative adapter metadata, registration fields, managed onboarding, non-secret credential-configured flags and media capabilities; JWT/session, agent key, service account and delegatedaccount:readaccepted./channel-relay/messages/{message_id}/attachments/{index}-- bounded inbound media download using the assigned live agent key or exact-message reply token without consuming its JTI. Explicitly denied to delegated/service-account/relay tokens. Stores inbound routing metadata only; never media bytes, outbound filenames or captions (ADR-013)./channel-bots-- channel bot registration CRUD + PATCH for platform verification material;GET /{id}/health(read access, metadata-only diagnostics + stablerecommended_action,can_write) andPOST /{id}/resubscribe(write access, X only, audited); adminGET /admin/channel-bots[?platform&status&limit&offset],/admin/channel-bots/{id}/health,/admin/channel-bots/webhook-rejections/admin/platform-credentials[/{provider}]-- admin-only descriptor listing (GET), field updates (PUT/PATCH, null clears), DELETE; generated Verify Token is admin-readable, app secrets never returned/channel-bots/managed-onboarding/{platform}(GET),/channel-bots/managed-onboarding/{platform}/complete(POST),/channel-bots/{id}/reregisterand/channel-bots/{id}/managed-setup/repair(POST) -- human-only router; writes share a per-user rate limit/webhooks/channel/{platform}/platform-- adapter-opted-in public GET handshake / POST signature-verified dispatcher/channel-conversations-- conversation-to-agent routing CRUD (platform conversations -> agent API keys)/channel-relay/reply-- agent async reply to a platform conversation. Only async replies are supported (sync 200+body callback replies removed per ADR-013 / NyxID#221): agents return 202 to the callback and post here. Dual auth: (a) agent API key (Bearer nyxid_ag_..., scoped byconversation.agent_api_key_id); (b) per-callbackreply_tokenfrom the inbound payload -- a single-use RS256 JWT,aud="channel-relay/reply", bound to oneinbound_message_id+conversation_id+api_key_id+platform, TTLJWT_RELAY_REPLY_TTL_SECS, use tracked in MongoDBreply_token_uses. Lets downstream runtimes (e.g. Aevatar) reply without persisting agent keys. Details:docs/CHANNEL_BOT_RELAY.md./channel-relay/send-- target-addressed proactive send, default-off human opt-in (allow_agent_initiated); assigned live API key or human owner session (including first-party CLI access JWT), shared per-conversation rate limit before auth, payload-bound 24h idempotency claims, metadata-only storage. Adapters declare outbound capabilities and classify permanent target refusals; unsupported adapters explicitly refuse dispatch./channel-relay/conversations-- API-key-only discovery of active assigned conversations, addressability, opt-in, capabilities, and last-message timestamp; paginated, metadata only./channel-relay/reply/update-- edit a previously-sent reply by the upstreamplatform_message_id; same dual auth. Lookup is caller-scoped (API key: rows it sent; reply token: its key + conversation + inbound anchor), never by platform ID alone, because Telegram IDs repeat per chat.outbound_message_id(the NyxIDmessage_idfrom/reply//send) pins the row; it is required for API-key edits on adapters withmessage_ids_are_chat_scoped()(Telegram, telegram-new), and ambiguous unpinned matches elsewhere return 409. The per-message edit limiter runs after resolution, keyed on the outbound row. A reply token may edit only if its JTI already exists inreply_token_uses(proves it was used to send first). Native edits: Telegram (including telegram-new), Discord, Slack, Lark, and Feishu. WhatsApp, X, and OpenClaw returnedit_unsupported. API keys can also edit agent-initiated messages; reply tokens remain bound to anchored replies./channel-relay/messages/{conversation_id}-- message history for agents;/channel-relay/resolve-sender-- resolve platform sender to NyxID user/channel-events/{conversation_id}-- HTTP Event Gateway ingress (NyxID#221, ADR-013). Accepts device event envelopes{event_id, source, type, timestamp, payload, metadata}, converts toCallbackPayloadwithplatform="device", forwards through the channel relay pipeline. Per-channel rate limited (default 100/s), idempotent via a shared MongoDB dedup claim (CHANNEL_EVENT_DEDUP_TTL_SECS, default 300 s), metadata-only logging tochannel_event_logs(no payload persistence)./webhooks/channel/{telegram,discord,lark,feishu,slack,whatsapp}/{bot_id}-- adapter-driven public POST receivers; WhatsApp also uses GET for Meta subscription verification/ssh/{service_id}/certificate(POST, issue short-lived SSH user cert),/ssh/{service_id}(WS tunnel),/ssh/{service_id}/terminal(WS web terminal),/ssh/{service_id}/exec(POST, remote command execution)/admin/service-accounts-- service account CRUD, secret rotation, token revocation, provider management on behalf of SAs/oauth/token-- also supportsgrant_type=client_credentials(service accounts) and RFC 8693 token exchange (grant_type=urn:ietf:params:oauth:grant-type:token-exchange) for delegated access and social token exchange (subject_token_type=id_tokenfor native mobile Google/GitHub login)
Top-level: /health, /.well-known/openid-configuration, /oauth/*, /mcp, /llms.txt, /llms-full.txt
NyxAgent assistant engine
Admin-selected public built-in skills use assistant:system-skills (default off), acting-person NyxBot default/override settings and per-agent tri-state choices. Reuse the bound Ornn reader and shared effective set; owner pins take precedence, guests never receive built-ins. Upgrade every replica before enabling; disable the flag before binary rollback. See docs/chat/09-nyxbot-orchestrator.md#built-in-system-skills.
New browser chats default to assistant:nyxagent-engine (on), then the experimental Direct flag, then Aevatar. NyxID owns nyxa-* transcripts and detached turns; the llm-nyx catalog row owns the target and NyxAgent owns disposable live context. A stable per-conversation assistant key authenticates upstream; failed/Stopped turns clear the context binding, and later turns send a bounded recap. Active fences expire after 2100 seconds and the next send transactionally records turn_lost before reclaiming; settlement retries stop after five minutes. Turns enrolled in assistant:turn-handoff (with its readiness capabilities; see docs/DEPLOYMENT.md) can instead be reattached by a surviving replica to the same upstream execution; a request is re-sent only when NyxAgent proves it never started, so nothing already started is replayed (see docs/chat/08-nyxagent-engine.md "Turn survival"). The browser polls selected history while active or awaiting acknowledgement and renders one inline note at the latest context reset. Each chat owns a restricted key, encrypted credential row, and assistant_acknowledgements transcript records. Native nyxid__* account tools dispatch directly through services with owner checks, metadata audit and non-blocking human acknowledgement; refusals are MCP isError results. Ask/Full is retired. Every owner has one persistent NyxBot agent (assistant_agents, kind: nyxbot, Muse/Grok-Bot-style personal chief of staff) with full account authority, plus persistent specialist agents created by the owner or NyxBot; conversations are threads of an agent (agent_id; legacy rows are NyxBot threads, upgraded to Full inside begin_turn with stale consent cards expired; access_mode reads full). Each agent has memory notes (nyxid__remember/forget, supplied in fresh turn input and excluded from stable instructions) and, for specialists, durable grants mirrored onto every thread key (no auto-connected services; NyxID's proxy still lets a live assistant conversation key reach catalog inference model services, because NyxAgent calls its model there with the thread key; allowlists and MCP tools stay the grants). Account-changing tools are NyxBot-only. The owner's access mode (AssistantSettings.access_mode: autopilot, nyxmode default, ask_every_time; optional per-agent access_mode_override, set only by maintainers through the human-only agent PATCH, never by NyxBot) decides which actions need a single-use owner action card: one closed classifier (assistant_acknowledgement_service::known_action_class) rates every native, meta and machine tool and every service operation (from catalog/HTTP effects) as read, change, sensitive or destructive; Auto asks for sensitive/destructive, Ask every time for every non-read, Full access for none of those risk classes. With assistant:org-instruction-v1 active, NyxBot and personal specialists additionally require this turn’s trusted owner instruction or an exact single-use card before using an org-owned user connection, including reads in Full access. Actual agent-owner UserType excludes org-owned specialists; platform/auto-connected services and the model transport contract are unchanged. Machine operations rate as changes (each machine's machine_confirm applies in Auto and Ask every time; Full access bypasses it with a receipt). One gate (confirmation_needed + confirm_action) adds the webhook floor and machine/login floors, consumes one card once, and records confirmation {risk, access_mode, reason} on the card; Full access bypasses ordinary risk, webhook, machine/saved-login and service policies, machine updates and skill publication; org-instruction and shared delegation cards remain explicit, and records non-consumable decided_by: access_mode receipts after success. Resource confirmations apply in Auto and Ask every time; org-instruction cards also apply in Full access. Guests never widen. Browser decision continuations store continuation_of and render as system lines. The legacy skip_destructive_confirmation switch is a view of the mode (true = Full access) and legacy rows migrate on their next write. Mode changes audit assistant_access_mode_changed. NyxBot grants a specialist services with nyxid__grant_subagent, which grants what resolves and reports the rest in not_granted with reasons (NyxAgent's own llm-nyx is never a grant). NyxBot is involved in a specialist turn only per the turn's admission snapshot (ActiveTurn.report_to = the exact assigning NyxBot thread, kept only when every drained event is bound to it; or with_nyxbot for a personal group NyxBot is a current member of); user/channel/trigger turns and any unbound, legacy or mixed event are never involved, conversation.report_to is written for old readers but never read, and cards store the turn's routing (assigned/group_with_nyxbot/not_involved; absent = legacy, decidable by the owner only). Non-involved specialist work (a direct chat with a specialist) gets a neutral human-addressed missing_access result (scope, target, "no request was created", AssistantPage::AgentDetails { agent, tab } link, tab = grants/skills) and continues: no NyxBot card, event, message or outbox, and no prompt, tool result, UI or doc copy may say NyxBot takes over a direct specialist chat (NyxBot takes over only when you talk to NyxBot or in a group with NyxBot). For involved work, specialist access defaults to denied: granted account reads continue to work, while new service/account/operation/skill/machine requests and connect-link creation return access_request_denied with audit metadata and a notice to the exact report_to thread (team and channel-bot tools refuse specialists with orchestrator_only, pointing a direct chat at the NyxID page instead, e.g. AssistantPage::Automations { setup, agent }); allowed requests audit assistant_access_requested, decisions and grants record the resolved approver (nyxbot, owner or api_key). Assistant management REST routes refuse conversation keys regardless of the live-turn flag, and channel/group management handlers require a first-party human. Owners may opt into routed_to_nyxbot; involved requests then route to NyxBot (decider: orchestrator, delivered to the card's assigned thread or, for group_with_nyxbot, NyxBot's home after a live membership recheck) and resume the specialist with an event turn; legacy allowed-skill notifications without routing stay eligible only when created before the assistant_migrations/issue-1883 cutover marker. Hosted connect links remain denied from specialist chat keys even in routed mode. For org-owned specialists, the acting member's setting applies. NyxID starts specialist, event and channel turns itself (owner identity/billing) from an owner pool sized by settings (defaults 8 live / 3 concurrent); browser turns beyond four running per person wait inside their claimed turn (at most eight, ten minutes, then queue_timeout) instead of a 429; events coalesce on pending_events; loop guards are 20 event turns per owner per hour and 3 consecutive event turns per NyxBot thread without a user message. Direct user chats with a specialist never wake NyxBot. Agents may carry an owner-chosen display_name and persona (style only, credential shapes refused). Group chats (assistant_groups/assistant_group_messages) put the owner and 1-8 agents in one transcript: messages go to the composer's recipient pills, else @mentioned members, else the sender's sticky last recipients, else the lead (NyxBot when a member); confirmations and NyxBot posts never change the sticky set, members hand off with @name (bounded by the owner's max_group_handoffs per request, default 6, and max_group_handoffs_per_hour, default 60), each speaking through a hidden member thread (group_id) with its own key; NyxBot threads that post work into a group are woken with the members' replies (group_settled) once it is quiet. The owner never replies "done": connect links and channel-bot setup links a chat hands out are watched (nyxbot_watches, TTL), and they and channel owner verification resume the waiting thread (proxy approvals need nothing: the tool call waits for the decision); each replica's MongoDB change stream (services/assistant_live.rs, identifiers/owner/status projection only) resolves watches the moment a link finishes or a bot becomes active and pushes identifier-only thread/group changes to browsers over GET /assistant/nyxagent/live, with the 15-second sweep as backstop for watches and wake-ups. NyxBot hands out setup/settings pages (nyxid__channel_bot_setup_link, nyxid__settings_link) instead of taking secrets or pointing at Studio; in channel threads and groups links are plain URLs and a reply decides an action card only when it quotes the card's 4-digit code ("yes 4821") or is a plain yes/no with exactly one card raised since the owner's previous message. New requests (owner messages or NyxBot posts from outside) refill the hand-off budget, NyxBot cannot post into a group from inside it, transcript continuations are indented, and names like user/nyxbot are reserved. Agents persist until destroyed (read-only threads, channels disconnected); destroyed specialists can be purged. Role-to-profile routing is admin-settable but inactive. The owner's private chats with an agent on every attached bot continue that agent's own home thread (one transcript and live context with the app; reply_channel sends asynchronous replies to the chat they last wrote from, cleared by app messages; messages record via); a question already being answered or queued is not worked on again (question digest on the active turn; a repeat from another chat gets the answer too via also_deliver), and turns are told what the agent's other threads are working on. Each other person's private chat of a channel bot is its own thread and each group, channel or topic one shared thread (senders named; guests whose platform sends no name read "{Platform} user …1234", and on NyxID's relay Lark/Feishu @_user_N mention keys are replaced by the mentioned names); relay callbacks carry each message's own chat type (not the catching route's), so groups are recognised automatically; per chat the owner sets reply_mode (groups: mention default, or all; the gateway admits every group message only while a chat needs it), members (everyone once the owner has talked to the bot there, else owner), allow_posts (for nyxid__post_to_chat) and an agent override, and per bot private_chats (owner by default for personal bots, everyone for new org bindings) plus private_chat_posts (absent/false: off), the initial posting permission for new private chats only. nyxid__update_channel_access and the human channel PATCH optionally apply it to at most 1,000 changed existing private chats transactionally (apply_to_existing); per-chat allow_posts remains the only posting authority, and groups/topics require separate opt-in. Non-owners talk as guests (guest_turn): NyxBot calls no tools for them (it holds every owner service); a specialist's guest turns use its granted services as far as the owner sets per specialist and service (AssistantAgent::guest_access, on the agent's Grants or via NyxBot's nyxid__set_guest_access): stored beside grants: read (GET/HEAD/OPTIONS, or a POST a catalog contract marks readOnly: stored row or hosted overlay, never a remote spec), use (default: no change or removal of what exists: PUT/PATCH/DELETE by method unless NyxID's per-operation x-nyxid-changes-existing says otherwise (true from any spec wins; false only from a catalog contract), never DELETE; Aevatar-destructive operations remain blocked except a compiled NyxID x-nyxid-append-only POST whose x-nyxid-append-only-query requirements match (Sheets append requires insertDataOption=INSERT_ROWS; remote specs cannot widen); overlay marks come from the compiled overlay so endpoint rows and generations are untouched, a mounted spec's own marks only narrow; Aevatar's markers are not changed) or all (NyxBot must name the services). Additive guest_operation_scopes and revisions intersect the level and ordinary scopes for guests only: an empty selection withholds the service (none in NyxBot's tool); owner turns retain it. New guest scope configuration requires assistant:guest-operation-scopes and replica readiness; saved restrictions are always enforced. Never extend the persisted GuestAccess enum incompatibly. Guest calls never carry method overrides; no name or word matching. Guests never use SSH, nyxid__, connection or Oracle tools, ask for more access, raise approvals or run on the owner's approval grants (audit rows record guest); guests' messages never queue as owner work; the owner's messages are marked (owner) in shared threads; guest turns see none of the owner's memory, roster or app-only messages (messages record their turn origin), start fresh after an owner turn, and cannot confirm cards. Channel bots link to NyxBot or any personal specialist: Telegram bots, and personal or org bots on platforms whose nyxbot:gateway-{platform} feature flag (lark, feishu, discord, slack, whatsapp, x, aurinko; default off, resolved for the linking person including live org membership overrides, admin-toggled without a restart) is on, through the Agent Event Gateway (NyxID is its nyxbot provider; the gateway operator must allowlist it; verified bots move there automatically once the gateway takes the platform, built beside the working bot and swapped in place, and stay unchanged on NyxID's relay if refused), other platforms through NyxID's relay directly; only owner-verified senders act as the owner (verified by link code, the owner's Telegram notification link, or as the Telegram account that created the bot through NyxID's in-Telegram creation). Bots of organizations the owner administers can be linked too (by id or label; NyxBot's bot/route tools list and manage them with their org): their route and route key are org-owned (no service grants), their gateway creator bearer and provider key belong to the linking admin (provider authentication binds row.user_id), and every provider event, relay inbound and asynchronous reply re-checks live org-admin authority (else org_access_lost, gateway release and key cleanup). Flag-off gateway bots return to the relay using the same build-beside-then-swap protocol, one move per sweep per replica, deferred while answering; Telegram always stays on the gateway. WhatsApp differs: only dedicated-app BYO bots use the native gateway (after credential and callback verification), managed Embedded Signup bots stay on the relay, and returning to the relay requires restoring and verifying the Meta relay callback. This symmetric flag-off behaviour also applies to personal bots. Lark/Feishu gateway input remains text-only; NyxID sends outbound tool images through its own adapters. Group-thread follow reuses relay policy only after explicit CMA thread contract 1 negotiation; older gateways retain legacy behavior. Admission projections add no follow reads for dormant/private/non-follow events, and native immediate/delayed replies bind to the original source rather than a caller-supplied thread ID. See docs/CHANNEL_THREAD_FOLLOW_GATEWAY_CONTRACT.md. Ordinary conversation keys allow nodes because service consent covers its node route; restricted model-setup and org-channel guest keys never receive node access. Platform-source services are granted on a key's allowed_platform_service_ids (chat keys only), and nyx__connect_service mints hosted links only for eligible owner/NyxBot chat keys; specialist chat keys are denied, including in routed mode. Execution/mutation requests add assistant MCP audits; read-only discovery does not. An allowed action card resumes the orchestrator with a visible continuation turn, queued until a running turn settles (not after Stop); each turn's instructions also list card decisions made since the previous user message, identifiers only. Chat-key tools/call requests during a live turn are recorded as metadata-only active_turn.activities (bounded) and copied onto the settled reply so the browser can show what the assistant is doing. Verified PNG/JPEG/GIF/WebP tool responses (2xx, <=5 MiB, type and magic bytes agree) become a leading text note plus, for non-chat callers, MCP image content (<=1 MiB inline, NyxAgent caps responses at 2 MiB); chat keys get the note in tool results because NyxAgent stringifies and truncates them at 10,000 characters; capable agents receive unseen tool images only after a successful response, through at most two live-turn image-input continuations (Stop/retention/key fenced, positive continuation counter, normal model-call billing, failures preserve completed text); budget/time continuations remain text-only, and tool-image delivery metadata stays unset without an attempted image round; for chat keys with a live turn they are also envelope-encrypted into assistant_attachments (<=8 per turn, deleted with the conversation and in user purge), listed as attachments on the turn and reply, sent before chat reply text through NyxID adapters with durable per-(source image, audience) nyxbot_image_deliveries_v2 claims (_id = sha256("v2\0{owner}\0{attachment_id}\0{audience_key}"), audience = real ChannelBot.id + platform chat id + native topic/root thread; no TTL, deleted with the source attachment plus an orphan sweep; CAS pending -> sending -> sent|failed|skipped|unknown, uncertain or in-progress sends never resent nor reported delivered; nyxid__post_to_chat include_images and automation TriggerRun.image_refs (16, oldest terminal evicted) share them; initiated posts keep the thread's native topic; notes never claim delivery; computer-use screenshots stay in the app via chat_delivery: false, explicit machine shares remain deliverable), copied into web-group transcripts with human group-read authorization, and served owner-only at GET /assistant/nyxagent/conversations/{id}/attachments/{attachment_id} with nosniff and a sandbox CSP. ToolResponse.text stays byte-identical for existing consumers and receipt digests. Existing actor history and action routes remain available; the NyxAgent sidebar no longer lists legacy Aevatar/Direct chats. Failed replies carry metadata-only error_detail with a named stage; NyxID-classified failures never fill upstream_error_code. Every settled owner turn writes a durable checkpoint (assistant_checkpoints, purged with the conversation, group thread and user) that leads the reset recap and backs the Working context sheet; an owner reset is fenced (turn_active) and drops it. Owner Retry sends retry_of: the server re-attaches the failed turn's bound uploads and refuses repeats of its completed calls (tool + canonical argument digest) with retry_duplicate_action, recorded on the live turn and audited metadata-only. Automation completion uses the default-off AUTOMATION_CONTINUATION_V2_ENABLED setting; the NyxAgent deployment must set NYXAGENT_SERVICE_SLUG=llm-nyx for recursion protection. See docs/chat/08-nyxagent-engine.md for the normative contract and docs/chat/09-nyxbot-orchestrator.md for the NyxBot team and channel design, including the gateway provider registration.
All NyxID replicas must be upgraded before any agent skill pin is disabled because SkillReference uses deny_unknown_fields.
Automation turns share the engine and team pool, with admission fenced inside begin_turn and no trigger lookup on ordinary turns. Schedule tools are NyxBot-only; webhook thread isolation and confirmation rules are in Rule 14 and docs/NYXBOT_SCHEDULES.md.
Shared agents (Phase 1; backend core validated): assistant:shared-agents defaults off. Only personal specialists may be published to people or an organization's live can_proxy() members; personal NyxBot and org-owned specialists cannot be shared. Managers may edit profile/persona and explicitly published team memory only; grants, credentials and all other management remain owner-only. Sharing writes use a CAS version that advances on every non-no-op save, while authority revision advances only for enable/narrowing changes and remains bound to keys and consents. Widening an agent's sharing (including adding/raising owner service delegation) always asks the owner with a one-use card, even in Full access; narrowing follows the normal access mode. Shared turns use the acting person's private thread, key, cards, approvals and notes. Owners/managers cannot read recipients' private chats or notes, and recipients never receive owner memory or roster. org_agent_service::RequestAccess composes a batched, request-local shared snapshot bound to the actor and exact agent/key; execution revalidates live authority, and unrelated owner paths acquire no sharing reads. Stored thread markers are history metadata, never execution authority.
Only the shared lane is caller-paid for model and metered-service usage. org_member retains BillingOwnerResolver::resolve_for_execution (org BYOK bills the org; platform keys bill the person); owner and guest billing stay unchanged. Owner credentials require an explicit per-service shared policy through the thin GuestAccess adapter; absence means withheld. Actor-owned connections for the same catalog service require private consent even in Full access: Once binds one exact operation or a bounded stateless-model turn, Always lasts until revoked or invalidated, and Skip applies to the current turn. The stateless model bootstrap may use the recipient's exact platform-bound connection without account-delegation consent because it uses NyxID's credential; live platform ACL, Deny, org approval policy and caller billing still apply. Personal approval requirements never gate the live turn’s own stateless model call. BYOK model credentials and stateful calls retain consent. Never silently switch accounts. Shared authority never includes owner machine nodes, saved logins, SSH, Oracle, owner-account nyxid__ tools or owner approval grants; audits distinguish actor, owner and execution mode.
Phase 1 supports private shared chats, shared members of the recipient's own single-person personal crews, HTTP/MCP model and service calls, exact pinned pool members, managed exchanges, async watches, private voice sessions, WebSocket/CONNECT and explicitly allowed recipient-owned channel posts. Crew members retain the recipient's hidden thread/key/cards/consents/billing, pinned skills and private notes; NyxBot involvement never transfers account or decision authority. Revoked/destroyed shares remain unavailable in the roster and addressed attempts post the fixed share-request notice without a model turn. Recipient UUIDs and @UUID route exactly; ambiguous bare handles never select a namesake. Transport extensions require assistant:shared-agent-transports-v1 readiness under the existing sharing flag. Durable bindings retain the recipient payer, exact consent claim and authority/behavior digests; re-read live rights before every effect and on resumed work. Never reuse a stored ACL snapshot or grant idle bearer execution. Once cannot open a second job/stream/session; pool retries cannot switch accounts. Machines, saved logins, SSH, Oracle, account tools, owner approvals, channel links and automation authority remain excluded; organization-group/platform publication refuses shared agents. Multi-person groups use the separate Phase 2 classifier and readiness gate. The v0.75.0 #1996 guest-access helpers are integrated through the shared-access adapter. New fields use safe serde defaults, and new enum values must never enter legacy fields. Observed support and durable activation gate new work automatically; flag-off preserves private-history access and revocation and is not sufficient for binary rollback. See the shared-agent design for contracts and rollout.
Assistant wake references require assistant:durable-wakes-v1 readiness: commit watch claims, follower removal and health throttles with their metadata-only pending events, consume legacy member queues with turn admission, and publish marked legacy group replies and their handoffs plus collaboration handoffs in reply settlement; preserve event budgets and never replay admitted turns (docs/chat/09-nyxbot-orchestrator.md).
Phase 2 collaboration groups are explicit new groups, never lazy conversions of legacy crews/org groups. collaboration_group_service and handlers/collaboration_group.rs enforce assistant:shared-agents plus full-fleet assistant:collaboration-groups-v1 readiness for new work. Groups contain 1–16 people and 1–8 specialists; no personal NyxBot. First-party human REST and native/MCP tools share transactional membership, SHA-256 single-use seven-day invitations, accepted creator transfer, proposals and owner guest opt-in. Invite consumption and revision-fenced membership writes must each match one row. Everyone joining/quick-added sees the full retained history disclosure. Guest enablement always requires the exact owner's delegation card, including in Full access; owners outside a group can manage only their own policy, never see its transcript. Hidden slots bind agent, original requester, lane, request and membership revision; handoffs/queued work cannot change principal. Authenticated work uses the requester pool/key/cards and the lane's existing billing; guests use owner identity/billing/channel pool with no cards. Group prompts contain only public transcript and published team memory, never private notes/roster. Decisions are requester-only and resume the exact chain. Only successful final replies and explicit deliverable images enter the group transcript; failed turns publish a deduplicated public agent-name/error-code notice, while drafts and exact account/card details stay private. Internal stop/history checks use the live collaboration execution binding; the ordinary private-thread reader still refuses hidden collaboration rows. Live notifications carry group IDs only and recheck participation. Removal/cancellation expires cards, consents and approvals and revokes keys; cleanup waits for settlement and preserves retained public history on departure. Flag-off retains history/revocation/deletion on upgraded readers; it is not safe binary rollback. See docs/chat/12-shared-agents-and-groups.md for routes, tools and rollout.
Private transport shared_execution receipts do not bind a collaboration request or audience and must refuse collaboration threads before effects. Collaboration queues and continuations use their own original-requester binding; foreground HTTP/MCP and exact pool calls retain live turn authority. Channel discovery/posting and private voice entrances remain unavailable from these hidden threads.
Channel Bot Notes
Chat reply-length advice belongs in turn-only context and must use channel_text::TextLimit budgets. Route it by the actual primary/additional/manager/automation destination; app-only turns receive none. Prefer one message unless long/complete output is requested. Longer text is split, never truncated within the 64-part limit (docs/TELEGRAM_NEW.md#full-saved-reply-delivery). Chat-list tool results carry the same guidance for post_to_chat.
Telegram forwarding carries provider-authenticated original-message eligibility separately from reference content. Only an original message may decide action cards or consume pairing/control proofs; absent gateway or legacy metadata fails closed. Raw relay text and the callback attachment list must match Telegram’s own top-level fields for CMA verification. Stored inbound attachments preserve that exact own-file prefix, then append unique external-reply handles for NyxBot; never shift callback download indexes. NyxID creates Telegram gateway channels with nyxid_relay sources. Native-source gateway events without sealed telegram_input stay plain text and cannot decide cards, pairing or controls; richer native forwarding is an optional CMA follow-up. Direct NyxID delivery extracts rich text, quotations and hidden links. Current nyxid_relay gateway channels supply gateway plain text plus original-message eligibility and own/quoted file handles only; forward-origin names, quote/external_reply text and hidden link URLs are unavailable (owner-accepted demo limitation; see the CMA follow-up doc). inbound files bind encrypted into the exact owner turn. Manager proof/setup material stays outside model input. Additional managers resolve encrypted credentials by identity through telegram_manager_registry, with distinct webhook routes/secrets and the legacy default preserved. Shared BotFather help uses immutable publications, version-fenced drafts/assignments and a revision pinned per turn; publishing grants no execution authority. The older onboarding flow requires fresh browser-only return proof. Upgrade all writers/readers before using additional managers or fresh onboarding proofs; see docs/TELEGRAM_NEW.md and docs/PLATFORM_BOTFATHER.md.
Channel health (services/channel_bot_health.rs): one recommendation function keyed on stable failure codes serves Health, the channel_bot_failed audit and the best-effort failure notice (owner, or every admin of an org bot; once per transition via notify_failure). Only authenticated deliveries write bot diagnostics; unauthenticated signature/target rejections are throttled per-platform counters in channel_webhook_rejections. Every send path records last_outbound_* through record_outbound_outcome. See docs/CHANNEL_BOT_RELAY.md#x-channel-workflow-health-and-recovery.
Platform Credentials is an adapter-described provider inventory: Stored backing keeps encrypted fields in platform_credentials (Meta); ProviderOAuth { provider_slug } reads/writes the provider config's encrypted client credentials (X shares twitter). Admin API, CLI and forms consume those descriptors. Managed UI components are selected through the meta_embedded_signup / oauth_connection flow registry.
X DMs use managed OAuth user connections (credential_source = "connection", connection_id is an owner-bound UserApiKey), with live refresh through the existing OAuth machinery. The X adapter owns protocol, scopes, rate handling and newest-first pagination; generic ingestion/credential hooks drive a MongoDB-leased poll sweep and the shared inbound pipeline. CHANNEL_POLL_INTERVAL_SECS=30 schedules sweeps; 0 disables them. X polls no faster than 60 seconds, starts at the newest event without replaying history, and fails after five consecutive errors. A backlog exceeding ten pages is truncated with a persistent last_poll_notice, without failing the bot. Reconnect validates the same account and preserves an existing cursor so the next sweep processes the backlog; deletion retains the OAuth connection. Current X pricing uses paid usage credits, shared across NyxID's app. Paid channels require a synced Requests price on the Your own key (BYOK) lane (or selected legacy Requests billing), plus a provisioned Lago wallet/subscription even with grants or allowances. See docs/CHANNEL_BOT_RELAY.md for limits and recovery.
Managed WhatsApp Embedded Signup v4 uses adapter-owned credential/onboarding/dispatcher hooks and SDK launch descriptors, with encrypted platform_credentials configured at Admin > Platform Credentials. Legacy bots default to credential_source = "user"; managed bots use "platform", resolve app-secret fallback on demand, and store their PIN and Verify Token encrypted for setup repair. Coexistence skips number registration and requests contact/history sync without historical chat import; repair preserves successful one-shot requests. Platform and WABA-override callbacks fan out through managed-only lookup and existing per-bot verification/dedup. Deletion best-effort clears unshared WABA overrides while leaving the Meta subscription. No new environment variables. See docs/CHANNEL_BOT_RELAY.md for prerequisites and recovery. The manual setup below describes BYO credentials.
Personal channel guest media requires both assistant:channel-media and default-off assistant:channel-guest-media, plus assistant:channel-media-v2 and guest-capable observed fleet support and durable activation. Guest uploads bind only to their private channel or shared topic conversation, never the owner home. Optional server-authored source.guest pins event/channel/sender, while exact turn/message/receipt bind model input. Human-owner reads retain ordinary retention; model reads require the current guest turn/key, live source/audience/flag and before/after-decryption checks. Keep ordinary guest attachment tools denied; bounded current-message document text and images are untrusted data, never authority. Flag-off stops guest fetch/model reads but preserves retained human-owner reads. Org-specialist guests and native Discord/WhatsApp media remain deferred. Do not revive old binaries after guest rollout without draining work. See docs/chat/10-uploads.md#personal-channel-guest-media.
Generated Sandbox files in private owner Web chat use default-off assistant:generated-artifacts (normal user/org/global rollout) and the matching all-replica readiness capability at acquisition. Retained files use contextual-envelope encryption only when CONTEXTUAL_RECORD_WRITES=true (which requires CONTEXTUAL_RECORD_WRITERS_DRAINED=true); otherwise new writes use legacy envelope encryption, and reads follow each row's version marker; summaries contain only success/exit code/verified count, never stdout/stderr or filenames. Generated rasters follow image retention, video/other files document retention, with live shortening bounded by the stored cap. Both recovery transports require the flag; admitted watches and retained owner GETs drain while off, and history hides generated fields. Ship tolerant frontend readers before enabling. See docs/chat/10-uploads.md#generated-sandbox-files and the encrypted-field inventory.
Owner Lark/Feishu inbound media uses the default-off, per-person assistant:channel-media flag. Discord/Slack/WhatsApp/X relay owner media shares late binding only with assistant:channel-media-v2 all-replica readiness; fetch from authenticated stored selectors, recheck authority after downloads and before binding, and preserve unsupported originals as download-only uploads with an explicit model limitation. Native CMA Discord/WhatsApp ingestion remains deferred to CMA#1402. Do not turn remote Markdown images into browser fetches. Admission stores source selectors; the consuming turn's run fetches and late-binds uploads after the conversation and user message exist. Binding reads the immutable receipt first, and media_finalize runs outside the cancellable execution future for Stop, failure, timeout, and orphan cleanup. Native media dedup uses NyxbotEvent.media.key, with a 7-day media-event TTL versus 24 hours for text. The maintenance sweep converts queued media to durable owner transcript notices after six days; a first-party human platform admin can convert it earlier with POST /api/v1/admin/assistant/channel-media/drain (repeat until converted: 0). Without the separate personal guest-media opt-in, admitted guest turns never download media or create uploads and receive attachments from guests are not shared with the assistant. Browser uploads, channel fetches, and attachment egress share one process-wide 192 MiB byte budget. Inbound downloads require any one of im:message, im:message:readonly, or im:message.history:readonly on the channel bot app in the developer console, as listed by the official "Obtain resource files in messages" API (/reference/im-v1/message-resource/get). Upgrade all replicas before enabling assistant:channel-media. The Discord/Slack/WhatsApp/X path additionally requires assistant:channel-media-v2 readiness, which converges from observed support without roster/drain declarations. Rollback turns both assistant:channel-media and assistant:attachment-writes off and keeps the new binaries and sweeps running. The media completion queries db.assistant_conversations.countDocuments({pending_events: {$elemMatch: {"media_event_ids.0": {$exists: true}}}}) and db.assistant_messages.countDocuments({media_pending: {$ne: null}}) must both return zero. See docs/chat/10-uploads.md for the normative contract, limits, and full rollback procedure.
Managed Lark IM operations use compiled catalog-only input adapters for all four Lark/Feishu slugs. im_message_create/im_message_reply accept plain text with msg_type=text, mutually exclusive with raw content (object or JSON-encoded object string); valid legacy strings are unchanged. im_image_create fetches a public HTTPS URL without credentials/redirects or decodes base64 (10 MiB), verifies MIME/magic/raster and uploads multipart image_type=message under ordinary service/operation/guest/confirmation authority. It returns only image_key; provider errors expose metadata only. /mcp/config retains raw message schemas and omits image materialization; image exact/background execution is unsupported. See docs/API_DISCOVERY.md#larkfeishu-message-text-and-image-uploads.
Binary tool files stay encrypted as origin: tool turn attachments; live non-guest owner chat keys can use exactly one of base64 body (model-authored content) or server-resolved attachment_id (existing files) for published catalog Binary uploads without a flag, binding handle uploads to owner confirmation and final HTTP egress while preserving stored contracts/config/exact views (old replicas refuse handle calls until upgraded; Lark writes retain their separate flag).
Managed Lark Base writes provide bitable_fields_list, standalone bitable_media_upload (file token only), and bitable_record_create_with_attachments. Attachment writes require a live, non-guest owner-chat key and default-off, per-person assistant:attachment-writes. The composite binds one action decision and revalidates turn/key/scopes/contracts/destination/credential authority before every child send. It validates existing fields/options, finite JSON numbers and complete source photo sets (N of M photos from that message could not be read; ask the owner to resend); managed permission errors identify the outbound service slug and connection label. Success returns {record_id, already_created:false}; authorized identical replay returns {record_id, already_created:true} even after credential rotation. Active writes report in progress; try again shortly; uncertain reports outcome unknown; check the Base; NyxID will not create it again, with no automatic create resend after the dispatch barrier. Succeeded-photo conflicts name the existing record and direct field changes to bitable_record_update. failed_pre_dispatch and failed_definite release reservations; failed_definite / not_sent proves the create request never left NyxID, permitting one create on a corrected new call. Uploaded tokens remain bound to credential/contract generations. The lark_base_writes ledger and lark_base_write_photos reservations protect identical content per owner/app/table for 400 days after terminal settlement; active rows are never retention-deleted, and owner purge removes both collections. Field listing is discovered normally; attachment operations require eligible chat keys with the flag on, are excluded from /mcp/config and exact descriptors, and refuse non-chat, feature-off, exact, durable and async execution before effects. Plain record create remains unchanged. Upgrade all replicas before enabling either media/write flag. Rollback disables both flags and keeps new binaries/sweeps running until all active-write/media queries reach zero, deletes both attachment operation rows for all four Lark/Feishu catalog slugs via DELETE /api/v1/services/{service_id}/endpoints/{endpoint_id} (list IDs with nyxid catalog endpoint list <catalog-slug> --output json), removes Number scopes including compiled key copies, then deploys the old binary; prevent new-release startup/spec sync from recreating the deleted rows during cutover. See docs/chat/10-uploads.md#channel-rollout-and-rollback for the deletion sequence, docs/site/cli/guides/connect-a-service.md#lark-base, docs/AGENT_OPERATION_SCOPES.md#receipt-bot-recipe, and docs/API_DISCOVERY.md for permissions, recipe, trusted projection, and rollout.
Lark / Feishu developer-console fields serve different purposes -- do not conflate:
- App ID + App Secret: authenticate outbound NyxID calls to Lark/Feishu APIs (tenant access tokens, sending replies)
- Verification Token: required for inbound webhook verification; compared against
header.tokenon v2 events or top-leveltokenon v1 /url_verificationpayloads - Encrypt Key: optional; when configured, NyxID verifies
X-Lark-Signature, decrypts theencryptpayload, then validates the Verification Token on the decrypted JSON
A bot stuck in pending_webhook: patch it with its Verification Token (and optional Encrypt Key) via PATCH /api/v1/channel-bots/{id} or nyxid channel-bot update <ID> --verification-token ... [--encrypt-key ...] [--app-id ...] [--app-secret ...]; the next verified inbound auto-promotes it to active.
WhatsApp uses the Business Platform / Meta Cloud API, not the consumer WhatsApp Business App or Twilio. Access Token authenticates Graph calls; Phone Number ID is platform_bot_id; Meta App Secret verifies raw POST HMACs; optional WABA ID uses the generalized app_id storage column but is exposed as waba_id. The generated one-time Verify Token configures the Meta dashboard GET handshake; token/secret rotation and Verify Bot must preserve its hash. Subscribe the callback to messages and manually subscribe the app to the WABA. Filter app-wide events by Phone Number ID. Registration fields, verification secrets, acknowledgment policy, reply context, and retry deduplication belong to adapter hooks; services/channel_adapters/mod.rs::resolve_adapter is the single registry. WhatsApp, X, Messenger and Instagram opt into atomic inbound admission (atomic_inbound_admission): an existing coordination-store claim is committed with metadata in a MongoDB transaction, scoped to bot/owner and the platform message ID (WhatsApp wamid), with an in-transaction legacy-row check and expiry/replacement fencing. Telegram edits retain their behavior. Provider ACK remains immediate; callback failure, timeout or crash after admission is not automatically retried. Claims are released only before admission; committed markers last 30 days.
WhatsApp send outcome hooks preserve every accepted component ID (split text, media, audio captions; max 64), final-ID API compatibility, expected count and certainty. Default hooks preserve other adapters’ send_bound_reply overrides. A confirmed Graph refusal before any accepted component releases an initiated claim; ambiguous or partial sends retain it for the existing finite 24h retention and persist known IDs without marking the send complete. Signed, phone/WABA-filtered individual receipts store bounded IDs, per-status provider times and numeric codes only, with UUID v4 _id, unique identity key and 30d TTL. Group/participant receipts are rejected. Authorized message pages batch-join exact owner/bot/phone/WABA/recipient/wamid receipts; read implies delivered. Whole-reply status requires all components. Partial/unknown and legacy final-only rows cannot claim whole-reply delivery; group routes never imply all-participant delivery. No raw webhook, error prose, content queue or unmatched receipt API. Conversation IDs are wa_id digits. See docs/CHANNEL_BOT_RELAY.md for setup and delivery limits.
Environment Variables
Full semantics for the long-form entries: docs/ENV.md.
# Required
DATABASE_URL=mongodb://... # MongoDB connection string
ENCRYPTION_KEY= # 64 hex chars (AES-256); required for local, optional for KMS (enables fallback)
ENCRYPTION_KEY_PREVIOUS= # Optional previous key for zero-downtime rotation
KEY_PROVIDER=local # "local" (default), "aws-kms", "gcp-kms" (feature-gated)
# KMS (optional; --features aws-kms / gcp-kms; *_PREVIOUS for rotation)
AWS_KMS_KEY_ARN= / AWS_KMS_KEY_ARN_PREVIOUS=
GCP_KMS_KEY_NAME= / GCP_KMS_KEY_NAME_PREVIOUS=
# Defaults provided
PORT=3001
SHUTDOWN_DRAIN_TIMEOUT_SECS=25 # Fits Kubernetes default 30s grace; includes 2.5s cleanup; extended grace >= budget + 30s; 0 = legacy immediate exit
BASE_URL=http://localhost:3001
FRONTEND_URL=http://localhost:3000
JWT_PRIVATE_KEY_PATH=keys/private.pem
JWT_PUBLIC_KEY_PATH=keys/public.pem
JWT_ISSUER=http://localhost:3001 # Defaults to BASE_URL, not "nyxid"; pin during migration
JWT_AUDIENCE= # Optional; defaults to BASE_URL (dedicated/client audiences unchanged)
BASE_URL_ALIASES= # Optional comma-separated HTTPS API origins, no paths
FRONTEND_URL_ALIASES= # Optional comma-separated HTTPS browser origins
COOKIE_DOMAIN_ALIASES= # Optional configured cookie domains selected by trusted request host
# No aliases means existing behavior; see docs/DOMAIN_MIGRATION.md
JWT_ACCESS_TTL_SECS=900 # 15 min
JWT_REFRESH_TTL_SECS=604800 # 7 days, ROLLING: every refresh rotates the token and restarts the TTL,
# so an active CLI never needs a browser re-login. Reuse of a rotated
# token more than 120s after rotation (a stale copy in another tool
# or profile) revokes the whole session; the CLI locks + re-reads the
# profile's token files across processes to avoid that.
JWT_RELAY_REPLY_TTL_SECS=1800 # Per-callback reply token TTL
JWT_RELAY_CALLBACK_TTL_SECS=300 # Callback authentication JWT TTL
JWT_RELAY_ACCESS_TTL_SECS=300 # X-NyxID-User-Token relay access token TTL. Relay tokens are
# proxy/LLM-only (rejected elsewhere by reject_relay_tokens),
# inherit the agent key's service/node allowlist, and are
# invalidated when that key is revoked (ensure_relay_agent_key_active).
JWT_ASSISTANT_FORWARD_TTL_SECS=300 # Legacy tombstone for the retired assistant_forward token.
# Live assistant delegation uses the compile-time 300s
# MCP_DELEGATION_TOKEN_TTL_SECS constant; this env has no effect.
SA_TOKEN_TTL_SECS=3600 # Service account tokens
ENVIRONMENT=development
RATE_LIMIT_PER_SECOND=10
RATE_LIMIT_BURST=30
PLATFORM_SERVICE_RATE_LIMIT_PER_SECOND=0 # Sustained per-user rate for platform-credentialed services; 0 (default) disables
PLATFORM_SERVICE_RATE_LIMIT_BURST=10 # Per-user burst capacity for platform-credentialed services
TRUSTED_PROXY_IPS= # Reverse-proxy IPs whose X-Forwarded-For/X-Real-IP are trusted for
# per-IP rate-limit keying. Empty = trust only the TCP peer. Only list
# proxies configured to overwrite client-supplied forwarded headers.
MTLS_CLIENT_CERT_HEADER= # Header carrying a URL-encoded PEM client cert from a trusted
# mTLS-terminating proxy (RFC 8705 cert-bound broker tokens).
# Unset = disabled. The proxy must strip this header from external requests.
BROKER_REQUIRE_SENDER_CONSTRAINT=false # Default-off broker hardening: require DPoP/mTLS-pinned
# broker bindings at create and exchange time. Runtime-overridable
# by platform admins via Admin -> OAuth Clients -> Broker Rollout Policy;
# DB override wins over this env default; other replicas refresh
# from MongoDB on a short background interval. See docs/ENV.md.
BROKER_REQUIRE_ADMIN_CAPABILITY=false # Default-off broker hardening: require platform-admin
# broker_capability_enabled provisioning; DCR scope and
# non-admin developer-app self-grant no longer confer broker mode.
# Runtime-overridable by platform admins; DB override wins over env.
CLI_PAIRING_HMAC_KEY= # Optional 64 hex; keys CliPairing.code_hash against DB-snapshot
# brute force. Unset = derived from ENCRYPTION_KEY or the JWT key
# (stable per-worker, multi-instance safe).
AUDIT_CHAIN_HMAC_KEY= # Optional 64 hex; keys audit-log HMAC chaining; same derivation fallback
BILLING_LEDGER_HMAC_KEY= # Optional 64 hex; keys billing-ledger HMAC chaining; same derivation fallback
CHAIN_VERIFY_INTERVAL_SECS=3600 # Automatic chain verification and billing account reconciliation; 0 disables both
CHANNEL_RELAY_CALLBACK_TIMEOUT_SECS=30
CHANNEL_RELAY_MAX_BOTS_PER_USER=5
CHANNEL_RELAY_MESSAGE_TTL_DAYS=30
CHANNEL_MEDIA_MAX_BYTES=20971520 # Per attachment; raises the JSON body caps of /reply, /thread-reply and /send (/reply and /thread-reply accept at least 2 MiB)
CHANNEL_POLL_INTERVAL_SECS=30 # Adapter-driven poll sweep; 0 disables (X minimum interval: 60s)
CHANNEL_RELAY_EDIT_RATE_LIMIT_PER_SECOND=10 # Per-outbound-message edit rate limit
CHANNEL_RELAY_EDIT_RATE_LIMIT_BURST=20
CHANNEL_RELAY_INITIATE_RATE_LIMIT_PER_SECOND=1 # Per-conversation unsolicited message limit
CHANNEL_RELAY_INITIATE_RATE_LIMIT_BURST=5
# Telegram / Approval System (optional)
TELEGRAM_BOT_TOKEN= # From @BotFather
TELEGRAM_WEBHOOK_SECRET= # Random string for webhook verification
TELEGRAM_WEBHOOK_URL= # e.g. https://auth.nyxid.dev/api/v1/webhooks/telegram
TELEGRAM_BOT_USERNAME= # Without @
APPROVAL_EXPIRY_INTERVAL_SECS=5 # Interval between expiry sweeps
CONNECT_LINK_EXPIRY_SWEEP_INTERVAL_SECS=60 # Service-link expiry and bot-link recovery sweeps; 0 disables both
AGENT_KEY_LOGIN_SWEEP_INTERVAL_SECS=60 # Revoke expired undelivered Agent Key credentials; 0 disables
# Service monitoring (optional; requires services:monitoring for the acting person)
CHRONO_PROBE_URL= # Trusted internal HTTP(S) origin; unset/invalid hides Monitoring
# OAuth token refresh (optional)
OAUTH_REFRESH_SWEEP_INTERVAL_SECS=600 # Proactive refresh sweep for expiring multi-connection OAuth
# tokens; 0 disables (lazy proxy-time refresh still applies).
# Does NOT extend refresh-token lifetime (a Google app in
# "Testing" still expires refresh tokens after 7 days).
OAUTH_REFRESH_SWEEP_WINDOW_SECS=900 # Look-ahead window; keep larger than the proxy-time 5-min buffer
CONNECTION_EXPIRY_NOTIFICATIONS=true # Notify once when OAuth dies; transition audits remain enabled
# Mobile Push (optional)
FCM_SERVICE_ACCOUNT_PATH= # Firebase service account JSON
APNS_KEY_PATH= / APNS_KEY_ID= / APNS_TEAM_ID=
APNS_TOPIC= # iOS bundle ID (e.g. dev.nyxid.app)
APNS_SANDBOX=true # Default true in dev
ANDROID_APP_PACKAGE= # Public Android application id for assetlinks.json
ANDROID_APP_SHA256_CERT_FINGERPRINTS= # Comma-separated 32-byte AA:BB:… signing fingerprints
MOBILE_APP_RETURN_SCHEMES= # Optional lowercase custom mobile OAuth schemes; malformed values fail startup
# Credential Nodes (optional, defaults shown)
NODE_HEARTBEAT_INTERVAL_SECS=30
NODE_HEARTBEAT_TIMEOUT_SECS=90 # Mark offline after N secs without heartbeat
NODE_PROXY_TIMEOUT_SECS=30
NODE_REGISTRATION_TOKEN_TTL_SECS=3600
NODE_MAX_PER_USER=10
NODE_MAX_WS_CONNECTIONS=100
NODE_MAX_STREAM_DURATION_SECS=300
NODE_HMAC_SIGNING_ENABLED=true
PROXY_MAX_BODY_SIZE=104857600 # Authenticated proxy + MCP raw bodies; direct and node-routed
LLM_MAX_BODY_SIZE=10485760 # /api/v1/llm provider + gateway bodies
PUBLIC_PROXY_MAX_BODY_SIZE=1048576 # Anonymous public proxy + public MCP bodies
WS_PASSTHROUGH_MAX_CONNECTIONS=200
# HTTP Event Gateway (NyxID#221, ADR-013)
CHANNEL_EVENT_RATE_LIMIT_PER_SECOND=100
CHANNEL_EVENT_RATE_LIMIT_BURST=200
CHANNEL_EVENT_DEDUP_TTL_SECS=300
TRIGGER_RATE_LIMIT_PER_SECOND=10
TRIGGER_RATE_LIMIT_BURST=20
TRIGGER_PAYLOAD_MAX_BYTES=262144
TRIGGER_DELIVERY_RETENTION_HOURS=72 # 0 keeps metadata only and disables replay
AUTOMATION_CONTINUATION_V2_ENABLED=false # per-run enrollment requires serving readiness
# Registration is gated by the default-on auth:invitation-code feature flag.
AUTO_VERIFY_EMAIL=false # Dev only: skip email verification on registration
# Optional
GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET
GITHUB_CLIENT_ID / GITHUB_CLIENT_SECRET
SMTP_HOST / SMTP_PORT / SMTP_USERNAME / SMTP_PASSWORD / SMTP_FROM_ADDRESSAvailable Commands
# CLI (from project root; end users install prebuilt release binaries, cargo install is for dev)
source "$HOME/.cargo/env" 2>/dev/null # Ensure cargo is available
cargo build -p nyxid-cli # Build CLI binary (includes node subcommand)
cargo test -p nyxid-cli # CLI tests (includes node agent tests)
cargo install --path cli # Install as `nyxid`
nyxid session refresh # Renew the saved session now (rotates the refresh token); exit 3 = must `nyxid login`, 4 = retry later
nyxid login --agent-key --profile agent # Web key selection/creation or phone QR approval; stores no account session
nyxid login --device # Explicit selectable device-code login (also the plain-login default)
nyxid login --callback # Full account session via local callback; legacy env alias: NYXID_LOGIN_NO_DEVICE_FALLBACK=1
nyxid login -c # --clipboard copies only the user code; JSON/no-wait modes skip clipboard/browser
# Backend (from project root)
cargo build [--features aws-kms,gcp-kms] # Feature-gated KMS providers
cargo test [--all-features]
cargo run # Start backend (port 3001)
# Node agent
nyxid node register --token nyx_nreg_... --url ws://localhost:3001/api/v1/nodes/ws
nyxid node start | agent-status | credentials list
nyxid node openclaw connect --url http://localhost:18789 # --credential-env for non-interactive
nyxid node openclaw status | disconnect
nyxid node daemon install|start|stop|restart|status|logs --follow|uninstall # launchd/systemd; supports --profile
nyxid node setup --machine [--computer] [--profile NAME] # pairing or page-issued --token; Linux isolation: sudo + --separate-users
nyxid node machine enable|disable|status # independent shell/files/computer; local authority
nyxid node docker start --machine # desktop image, persistent identity/workspace
nyxid node docker build|start|stop|status|logs [--profile <name>] # Docker alternative to native daemon
# Oracle relay
nyxid oracle ask <pool> <prompt> | result <task_id> | status <pool>
nyxid oracle pool create|list|show|update|rotate-token
nyxid oracle worker install --pool <pool> [--label <label>] [--worker-token-file <path>] [--profile <name>]
nyxid oracle worker list <pool> [--all] | show <pool> <label> # online only unless --all
nyxid oracle worker start|stop|status|logs|uninstall --pool <pool> [--profile <name>]
nyxid oracle worker drain|resume|restart|relaunch-browser|relogin <pool> <label>
nyxid oracle worker forget <pool> <label> [--force] # remove a stale worker row + its commands; releases its session affinity
nyxid oracle worker cancel-command <pool> <label> <command-id> # withdraw a queued/delivered-but-unexecuted command (e.g. a bad upgrade)
nyxid oracle worker upgrade --pool <pool> [--label <label>]
nyxid oracle login <pool> [--worker-token-file <path>]
# Catalog administration (Admin or Catalog Manager)
nyxid admin user grant-role <EMAIL|ID> catalog_manager
nyxid admin catalog add --template zoho-mail # wizard: provider + service + OAuth client + validate
nyxid admin catalog apply --file m.yaml [--dry-run] | validate --file m.yaml
nyxid admin provider create | update <SLUG> # wizard without --file; then offers the OAuth client
nyxid admin provider list | show | set-credentials <SLUG>
# Billing administration (human sessions; reads admin/operator, writes admin)
nyxid admin billing config show|set | overview | rates [--service <SLUG|UUID>]
nyxid admin billing service show|update|set-managed|resync|verify <SLUG|UUID>
nyxid admin billing ledger verify [--all]
nyxid admin usage [--period 24h|7d|30d | --from RFC3339 --to RFC3339]
nyxid admin credits grant issue|list|revoke
nyxid billing wallet [--provision] [--owner-id <UUID>] | executions list|show
# --owner-id always uses the owner-aware POST, provisioning if missing; personal reads use GET.
nyxid mcp tools [--service <SLUG>] | call <TOOL> --args @file [--envelope]
# Agent isolation
nyxid api-key create --name "coding-agent" --platform claude-code
nyxid api-key list | show <ID_OR_NAME> | rotate <ID_OR_NAME> | delete <ID_OR_NAME>
nyxid api-key bind <ID_OR_NAME> --service <SLUG> --credential <LABEL> # Credential override
# Device-code binding
nyxid device approve XXXX-XXXX-XXXX [--org <ID|SLUG|NAME>] [--label <LABEL>] [--service <SLUG_OR_UUID>]...
nyxid device onboard --label "Kitchen Camera" --ssid "MyNetwork" --password-env WIFI_PASSWORD [--org ...] [--service ...]...
nyxid device factory-key [--count N] [--out FILE] [--ndjson]
# Channel bots
nyxid channel-bot register --platform telegram --label support --token-env TELEGRAM_BOT_TOKEN
nyxid channel-bot register --platform lark --label support --token-env LARK_BOT_TOKEN \
--app-id cli_xxx --app-secret-env LARK_APP_SECRET --verification-token vtoken_xxx
nyxid channel-bot update <BOT_ID> --verification-token ... [--encrypt-key ...]
# env alternatives: NYXID_LARK_VERIFICATION_TOKEN / NYXID_LARK_ENCRYPT_KEY
# Frontend (from frontend/)
npm run dev | build | test | test:watch | lint # dev = port 3000; build = type-check + prod build
# Mobile (from mobile/): npm run start | ios | android
# SDK (from sdk/): npm run build | clean
# Docker (from project root):
docker compose up -d # MongoDB (27018) + Mailpit (8025)Design System
Always read DESIGN.md before making any visual or UI decisions. All font choices, colors, spacing, and aesthetic direction are defined there. Do not deviate without explicit user approval. In QA mode, flag any code that doesn't match DESIGN.md.
<!-- consensus-rnd:foundational-invariants:start version=1 sha256=180aef50d385eb24f73e772f75753fa61a2adde8407539bbacd586878d7e2166 -->Consensus R&D Foundational Invariants (managed by consensus-rnd)
- FI-001 AI outputs are untrusted by default; before entering the mainline they must pass independent checks, including the applicable mix of consensus, review, or automated verification.
- FI-002 Host facts must be injected by host configuration or host rules; generic skills / engines must not hardcode project, organization, path, branch, or personnel facts. Skill-private runtime directories such as
.refactor-loop/must not become host production configuration or ledger SSOT. - FI-003 Keep the stable core small and auditable; frequently changing behavior belongs in host rules, prompts, scripts, or extension layers, not in core invariants.
- FI-004 Facts that cross processes, turns, or nodes must have an authoritative record; in-process memory, caches, and temporary variables cannot pretend to be sources of truth.
- FI-005 Boundaries take priority over convenience; responsibility, layering, protocols, and state ownership must be clear, and shortcuts through intermediate layers must not bypass the main path.
- FI-006 Changes must be verifiable and evidence-based; failures, gaps, and out-of-bounds commitments must be surfaced explicitly, not hidden behind silent assumptions or disabled tests.
- FI-007 Prefer deletion; remove deprecated paths directly unless host rules explicitly require migration-period compatibility.
<!-- consensus-rnd:foundational-invariants:end -->NyxAgent failed replies use normalized error classes with a separate sanitized
upstream code and metadata-only diagnostics. Reclaimed turns retain activity
and attachment checkpoints, and post-reset prompts use the bounded
“Previous context (after reset)” recap described in
docs/chat/08-nyxagent-engine.md.
Aurinko email integration
api-aurinkois an owner-scoped account-token AI Service; its curated overlay supplies fifteen MCP operations. No managed OAuth until Aurinko documents compatible PKCE. Do not use application credentials as a shared mailbox token.- The
aurinkochannel adapter has independent encrypted account-token/signing-secret storage, signed raw-byte POST validation, bound subscriptions, and bounded inline producer retries. Never return 422 to Aurinko. - ADR-013 still applies: persist only email subscription bindings, batch digest/cursor, stable UUID-v4 receipts, and send-attempt barriers. Receipts/sends have no TTL while their bot exists; owner/bot deletion must fence in-flight effects before cleanup. Do not consume a retryable Aurinko reply token before preflight or resend an uncertain POST. Legacy adapter behavior remains unchanged.
- See
docs/AURINKO_INTEGRATION.mdfor lifecycle, callback routing, filtering, reply authority, scopes, and validation limits. Aurinko is included in the catalog overlay drift map.
Assistant workspace navigation places Automations (/assistant/automations) and
Machines (/assistant/machines, Saved logins at ?tab=logins) beside Plugins and
Approvals for both engines. Setup/pairing stay in AssistantShell; the desktop is
standalone under /assistant/machines/{id}/desktop. Studio Nodes shows only a
read-only machine summary linking to assistant settings; Developer → Triggers
retains secrets/replay. /automations redirects with setup and agent intact.
Account data (Settings with all seven tabs, Billing & Usage when available, and
NyxBot settings for the NyxAgent engine) opens as URL-driven modals over the
current assistant view using ?panel= and namespaced panelTab/filter keys,
never as in-shell pages. The assistant has no desktop top bar: the sidebar column
carries the logo, search (⌘K: recent chats, agents/groups, pages, settings tabs,
theme) and the account menu, and both open the same panel URLs as NyxBot's
settings links.
Opening pushes history; Settings tab changes replace, Billing user changes push
and automatic cleanup replaces. Back immediately after opening closes the panel;
Back after an explicit close reopens it with any pending top-up already consumed.
The assistant header bell beside Search opens the activity feed and shows its unread count. Notification preferences are a tab in Account Settings. The assistant account menu shows the linked email, Settings, Billing and Usage when available, Open Studio, and Log out. Profile also contains Log out. The agent details sheet and in-chat
connection/setup flows keep their existing presentation. Studio /settings and
/billing remain available. Lago checkout returns to /billing (as configured in
docs/LAGO_SETUP.md), even when started in the assistant.
Server-generated browser URLs use services::assistant_links::AssistantPage.
Machine web tasks use nyx__machine_browser; secure browser DevTools and arbitrary script evaluation are disabled. The separate dev browser is for debugging and has no saved-login access. Explicit NyxAgent budget/time errors continue the same session under max_auto_continuations; Stop must fence the turn and cancel node jobs/gateway work. Machine error codes 12413–12418 distinguish browser/driver/display/restart/stop states.
Machine updates: machine_update_service owns durable policy/attempt/watch state;
handlers/machine_update exposes human-only UI and tools that require owner cards in Auto and Ask every time; Full access runs them with automatic receipts.
Granted specialists may request, never approve, updates. Keep reconnect watches
bound to their attempt, and exclude jobs/turns/desktops/owner control from idle
updates. Only signed supervisor commands write version-only private update
mailboxes. The companion's Docker socket is host-root authority: fixed official
repositories, digest-bound Publish Images attestations, inspected configuration
preservation and rollback are mandatory. Never log Docker inspect environments
or expose update-volume access to agent/browser users. Test-only local-image
injection must remain behind cfg(test); production has no trust bypass.
Companion self-update uses companion-journal.json, a fenced heartbeat and separate
controller/handoff locks. Keep the predecessor alive until commit; recover
post-commit by finishing cleanup, never rolling back. Successors check the exact
attested image and release. Report companion outcomes separately from machine
progress, and never downgrade the companion.
Machine performance budgets belong in ignored benchmarks or explicit
NYXID_MACHINE_STRICT_BENCHMARK=1 runs on a quiet host. Shared-runner container
CI prints the same measurements but uses sanity ceilings (8 fps minimum,
500 ms input p95) so runner jitter cannot block image publication.
Machine browser compatibility/security: secure and dev Linux browsers use separate Xvfb/Openbox displays and Xauthority cookies; cua remains secure-only. The owner's display switcher routes capture/input and control by display (macOS shares its physical desktop and locks both). Browser refs carry frame IDs; snapshots accept query/offset/scope and return bounded pagination markers. Trusted native input follows extension hit testing; explicit DOM fallback is labelled. Command isolation is an actual uid/filesystem access probe, separate from saved-login browser isolation; missing fields mean unknown. Continuation progress stores rolling MCP argument/result hashes only, never raw values or bounded activity labels. Docker migration/setup commands require the server's cached, attestation-verified updater digest, with no mutable-tag fallback.
Machine 0.41.1 recovery: MV3 startup/install listeners and reconnecting native ports
are required on persisted profiles. A missing/changed managed package must clear
its own Preferences/Secure Preferences install registration before signed policy
reinstallation; deleting Extensions files alone does not repair Chromium. Never
start browsers/cua or bind sockets from machine status: read daemon snapshots.
12416 includes advertised tool names and browser snapshot/screenshot guidance;
machine discovery uses the shared ToolSearch ranker. Container updater TUF
stores live inside its private locked update volume; keep tmpfs flags in both
rendered commands for 0.41.0 compatibility. Failures expose fixed stage/reason
codes and guidance only. Production-image verification tests must exercise real
TUF and attestation code under read-only/cap-drop/no-new-privileges restrictions.
NyxBot's actor-scoped creator grant is restricted to the registered confidential
gateway caller; its server-only creator bearer is separate from provider credentials.
Preserve the contract in docs/CHANNEL_EVENT_GATEWAY.md. Gateway retirements
retain exact cleanup authority before local references change; activation commits
continuity and provisional adoption atomically. This is lifecycle cleanup only,
with no delivery retry.
NyxBot owner settings include an enforced access_mode (nyxmode, autopilot,
or ask_every_time) and optional specialist override. The backend acknowledgement
service owns classification and approval; clients cannot bypass policy floors.
NyxAgent model selection is owner-authenticated, validated against live models,
and changing an existing thread resets its upstream context.
Delegated specialist tool images use server-authored assignment edges and a
separate, bounded delegated_images.references projection on the receiving
turn/reply. Preserve source identity and retention; recheck live source use,
recipient and destination authority at adoption and before sending. Wait and
event drain adopt before consuming exact result event IDs. Never treat foreign
IDs in model text or a mutable report_to as image authority. Delegated sends
reuse source v1/v2 image claims; see docs/CHANNEL_BOT_RELAY.md (#1897).
Delegated publication business refusals must not abort source settlement: save
the refusal code and attempt the legacy text-only notice after settlement.
Database/transport errors remain fatal; delegated results follow ordinary FIFO
eviction, preserving source-question/invocation fences.
NyxBot image upgrades from release 0.71.0 must read legacy
nyxbot_image_deliveries before every v2 claim, matching owner, conversation,
turn and NyxBot channel across all destination aliases. Sent items suppress
resend as previously delivered; sending/unknown and pending-in-sending items
remain uncertain. Only a pending batch or a proven pre-dispatch skip can retry;
unknown failure/skip codes retain their old outcome. V2 uses the separate
nyxbot_image_deliveries_v2 collection; never rewrite v1 rows or drop their
seven-day TTL during this release. This may suppress a second audience of the
same bot. Concurrent old/new sends remain a rollout risk; rollback to 0.71.0
ignores v2 and restores old behavior. Remove the v1 read path and collection/index
one release later, at least seven days after deploy, and track that sunset in
the PR. See docs/CHANNEL_BOT_RELAY.md.
Assistant reply feedback is a human-only NyxAgent conversation and group feature: PUT/DELETE feedback routes require the engine flag and participant ownership, while /admin/assistant/feedback is read-only for admins, operators and nyxid:admin:usage:read holders (filters model, agent_kind, has_error; pre-snapshot rows show no context). Controls are hidden for replay, legacy Aevatar, stopped, and failed replies; comments are optional and bounded. Writes are scoped to the parent conversation or group, purged with it, and atomic per person and reply. Each change stores a metadata-only reply context snapshot and emits one nyxid::assistant_feedback log line (submitted/changed/comment_updated/withdrawn); comment, prompt and reply text are never logged. See docs/chat/08-nyxagent-engine.md#reply-feedback.
Tools Manager boundary
Tools Manager is Operator-only (nyxid:catalog:tools:write) and binds every
mutation to own server-marked Tool rows and live first-party human authority.
Admin alone publishes and configures audience/prices. Manager creation uses a
restricted empty audience; twin inheritance is sanitized. First credential and
destination version commit atomically, with a durable freeze after first set.
Contract edits demote live operations and advance generation transactionally;
no-op discovery/planning must not mutate state. Tool icons reuse static-SVG
validation and recheck authority on attachment. Keep manifest/wizard credentials
in zeroizing memory, env names only in saved manifests, no credential reads in
dry-run/validate, no redirects on shared-credential transport. See docs/TOOLS.md.
NyxBot saved manager replies and proactive text posts use the shared
channel_reply_plan/channel_text planner (64 parts) and metadata-only
channel_text_deliveries per-part receipts. Never replace long content with an app
link: only the overflow notice defined in docs/TELEGRAM_NEW.md#full-saved-reply-delivery stands in for text beyond the limit. Never replay a sending/uncertain part. Revalidate live authority between effects;
retain confirmed prefix IDs on partial outcomes. Pin action-card identities and
numeric media notice inputs so retries reproduce the plan without storing bodies.
Discord/WhatsApp assistant text plans pin renderer v2, and Slack pins v3. Absent versions replay v1 only. See the renderer and journal contract.
Saved manager and scheduled chat text uses exact MongoDB-time preparation leases and a parent/part transaction at the provider boundary; reclaim only pending parts, never a receipt-less sending part, and revalidate live authority between effects.
Manager attachments use v2 image claims with the existing legacy read gate.
Versioned attachment preparations retain original routing identifiers and MongoDB-time leases; reclaim only proven-unsent work, fence the exact attempt before every upload, and never retry a possible provider effect (see docs/CHANNEL_BOT_RELAY.md). Drain
these writers for upgrade/rollback; old workers must not resume multipart rows.
See docs/TELEGRAM_NEW.md#full-saved-reply-delivery. Late direct/gateway NyxBot text uses a MongoDB-time preparation lease and exact provider-boundary fence on its event; recover only unsent parts or the bounded gateway reply-target operation described below, keep other uncertain sends terminal, and append their fixed notice only to an existing owner-visible thread.
Protected organization connection use
assistant_service_execution::instruction::owner_instruction accepts only positive server-issued provenance from first-party owner UI turns or verified owner-private channel ingress. It binds exact connection, actor, key, conversation, live turn and expiry. Legacy selection rows, approved-card selections, model _nyxid_via, API/delegated input, automations, groups and guests never become instruction. Trusted selection satisfies the org requirement for that turn; independent sensitive/destructive policies still apply. ConfirmationNeed.org_instruction is typed separately from other floors and persists org_connection ahead of webhook/mode reasons. Org cards survive Full retirement/UI bypass and use a v2 exact binding that omits only mode preference. Before OAuth refresh/token exchange, resolve metadata, authorize selection or atomically consume the exact card, carry one Admission through materialization, and revalidate it before HTTP/WS/node egress. New machine jobs/async watches retain server-owned receipts only for their exact bounded lifecycle. Legacy org jobs refuse and require a newly reviewed bounded command; legacy watches pause for a card covering their existing operation's status/result/cancel lifecycle. Deploy compatible readers/UI first; the two readiness-gated flags can be enabled once all observed admission/execution/link-completion writers support them and activation is recorded, without roster/drain declarations. Old binaries must not rejoin after activation. See docs/SECURITY_ROLLOUT_READINESS.md and docs/NYXBOT_SERVICE_EXECUTION.md.
Organization-specialist channel bindings
Organization specialist use and maintenance follow independent per-person lists within live Admin/Member membership. First-party human org Admins govern both lists through a revision-checked, audited PUT gated by assistant:org-agent-access-lists-v1 and fleet readiness. Always enforce saved lists and narrowing revisions, including while authoring is disabled. See docs/ORG_AGENTS.md.
nyxbot:org-specialist-channels is default-off and requires recorded activation and observed support from every live executing API/worker; no roster/drain declaration is required. A live same-org admin links an org bot to an org specialist; there is no org NyxBot and no personal-agent fallback. NyxbotChannel.user_id remains the transport/provider admin; optional versioned org_specialist and ChannelOrigin.org_execution bind separate execution authority. Members confirm their own authenticated private sender in a first-party session; active Admin/Member (can_proxy) uses org_member, never the admin's lane. Revoked links remain tombstones and cannot silently become paid guests. Only verified admins set owner-presence. Groups/topics keep one public transcript and isolated hidden execution per actor; member DMs use their existing private org-agent home. Cards bind the acting member. Guests have no account, approvals, nodes, machines, saved logins or private memory. Guest exposure is admin-managed and defaults on for new org bindings, including private chats; GuestPolicy::default() remains closed for absent/legacy data. Admin/Member (can_proxy()) reads are available with private-chat/history identifiers omitted; existing amount and bot-detail contracts remain compatible; existing Viewer bot detail/health reads remain unchanged. Connect preview is first-party-human/admin-only, metadata-only and never an authorization. Missing billing preserves the desired On choice, refuses guest execution and reports the existing enable_billing health recommendation. The versioned background step enables active historical Off when a bounded same-bot/org binding history has no save audit or revision evidence of a choice, including untouched predecessors/restorations. Missing history and malformed facts stay unchanged; query errors and recoverable authority failures retry. Existing hinted event indexes serve audit reads. Restoration audits now record the generated guest revision; older audits cannot distinguish a later revision from restoration, so their accepted evidence limit remains. Bot health status does not exclude otherwise live authority. It opens unchosen private audience, retains frozen service limits, and sends a typed admin notice. Explicit Off saves now record a revision and a transactional save audit. After nyxbot:org-guest-grants-v1 readiness there is no daily cap; new bindings follow specialist Grants guest levels/scopes immediately on enable (default use). Existing bindings retain frozen service lists/digests, empty = model-only, until an explicit human/admin reviewed whole-policy handoff in Grants. Additive follows_agent_grants defaults false; retain legacy API fields, lists, budgets and holds. Six requests/minute/sender, wallet/funding checks and existing guest evaluators remain. Old replicas enforce the retained cap/list; disable, drain and settle before rollback. Guest model setup remains hidden/fenced, with the verified org guest payer and exact funding; the linking admin only receives setup diagnostics. Thread-bound org setup resolves the exact originating guest lane with the same admitted-turn validation, retaining its own hidden key/settlement and live source fences. Org thread answers use the committed event conversation and validated execution actor, including pre-upgrade events; never retarget to a newer conversation. Initial target rejection preserves reply tokens; unknown dispatch effects never release them. Closed thread target/authority rejections and send failures update existing bot Health with metadata only; failed sends preserve the existing provider reason with additive thread detail. Used-token replay and transient preflight errors do not. Shared inbound thread lookup retains its existing fallback. Every admission, key authentication, proxy effect and delivery revalidates live authority. Changing the specialist resets sender verification and guest service authority, preserving the saved exposure choice. Rebuilding the same org/bot/specialist preserves guest configuration with fresh policy identity, live admin/service checks and the original daily budget ledger, including On while billing is unavailable; upgrade all executing replicas before using preserved exposure. The bounded #2458 worker may rebuild only a pre-cutover org_access_lost predecessor with an old audit proof, fresh authority and no competing live route, using the same creator-bearer path as an admin reconnect; it sends one health transition notice and tells members to verify again. See the guest settings and binding recovery section in docs/chat/09-nyxbot-orchestrator.md. Flag-off, unavailable security readiness and dependency errors suspend work without retiring the binding; recovery resumes it. Only confirmed transport-admin or org/bot/agent authority loss retires it through org_access_lost, never retargets it. Retain financial settlement records. Person erasure removes personal linkage and transcript/lane content, retaining only a sender revocation tombstone so the identity cannot become an org-paid guest; channel/org erasure removes those tombstones.
Gateway reply-target retries (#2566) accept exact 409 routed_reply_in_progress, any 5xx, no HTTP response, and unreadable/unparseable 2xx; only the exact 409 proves admission. A 2xx with valid JSON and an explicit unconfirmed, missing or unknown outcome is terminal. Reuse the event preparation claim, frozen request/target/key and bounded deadline, with outer unknown plus a pending receipt marker. Write receipt marker v2, upgrade v1 on acquire, and recover stale sending only with the committed target and frozen request hash v1, anchored on original checked_at. Every pending receipt lookup is started; terminal uncertainty is unconfirmed. Legacy unkeyed operations and other transports never re-ask uncertain outcomes. Provider POST admission records at most 32 dispatch_identity.keys aliases; lookup is observational, including auth (no key touch or org cleanup), and is the only reader of automatic nyxbot:gateway-reply-arbitration-v1 readiness. Replay and the effect barrier contend atomically, including preparing_text; local ownership returns empty completed recovery. See docs/CHANNEL_EVENT_GATEWAY.md#reply-target-receipts-and-dispatch-lookup.
Relay admissions without stored turn output (including followed threads) retain a 24-hour, versioned event response_read mapping and the resolved thread_reply choice. GET/events/repeated POST observe turn settlement with empty completed output; never set gateway_response_id, claim replay/stream ownership or change turn delivery through these reads. Valid four-key metadata plus a binding and existing gateway recovery advertisement enable the queued id/sequence-0 acceptance prefix and X-CMA-Response-ID; preserve thread_reply on original and replayed created frames. No-turn replies under that prefix retain the existing encrypted Payload separately on the event: only the original command exposes that output and only the gateway parent delivers it; NyxID's sender never sends it. Aliases remain empty. For fixed refusals on prepared org threads, bind the exact text and source to the terminal no-turn event. Both gateway consumers must claim the same notice receipt and recheck live sender, binding, route and thread access. Guest wallet, credit and service grants do not gate a fixed notice. No new readiness capability or backfill. See docs/CHANNEL_EVENT_GATEWAY.md#locally-delivered-response-lifecycle-2588.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

