forked from retoor/devplacepy
Compare commits
21
Commits
messenger-chat
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ea7701c1a | ||
|
|
3774f1dd23 | ||
|
|
c50f5e81a5 | ||
|
|
3366e0372c | ||
|
|
fc9e09c47a | ||
|
|
6a5ed75072 | ||
|
|
585fab74a6 | ||
|
|
2452f9e85b | ||
|
|
d815fbe9f8 | ||
|
|
376c6ba99d | ||
|
|
8b45a515f2 | ||
|
|
695be8ba9a | ||
|
|
1a9201cb91 | ||
|
|
8d4d06de61 | ||
|
|
8e36807926 | ||
|
|
151476125f | ||
|
|
3f6e83c753 | ||
|
|
8a48e3ef85 | ||
|
|
dbdd0d29dd | ||
|
|
33eb090e27 | ||
|
|
078d0657ff |
@@ -1,3 +1,5 @@
|
||||
aura*
|
||||
.*
|
||||
.docs
|
||||
.dpc
|
||||
.devplace
|
||||
|
||||
@@ -2,19 +2,22 @@
|
||||
|
||||
This file provides guidance to Claude Code when working with code in this repository. It holds only what applies regardless of which part of the codebase is being touched. Deep, subsystem-specific detail lives in nested `CLAUDE.md` files placed inside the relevant directory - Claude Code auto-loads a nested file only when a file under that directory is read or edited, so the always-loaded cost of this repository stays proportional to this file alone. See "Subsystem map" below for the full list.
|
||||
|
||||
It is a big project, whatever you are implementing, it is probably done before. You should look it up and match the implementation structurely and visually. For inconsistency there is zero tolerance policy. Develop dry, kiss, re-usable code, consistent with existing implementation. Literally always try to find relatable examples before making a modification. If no-example exists, explain to user what is the case and let user decide what to do and how to continue.
|
||||
It is a big project, whatever you are implementing, it is probably done before. You should look it up and match the implementation structurely and visually. For inconsistency there is zero tolerance policy. Develop dry, kiss, re-usable code, consistent with existing implementation. Literally always try to find relatable examples before making a modification. If no-example exists, explain to user what is the case and let user decide what to do and how to continue.
|
||||
|
||||
The completion contract for every change is [DEFINITION_OF_DONE.md](./DEFINITION_OF_DONE.md): universal gates, test obligations, the four-layer rigor procedure for spendable resources and races, per-subsystem rules, and the final checklist. A change is done only when every applicable gate in it passes.
|
||||
|
||||
|
||||
## Project
|
||||
|
||||
DevPlace is a server-rendered social network for developers. FastAPI backend serves Jinja2 templates with pure ES6 module JavaScript on the frontend. SQLite via the `dataset` library (auto-syncs schema). No JS framework, no NPM, no JWT.
|
||||
|
||||
- **Database:** `dataset` (auto-syncs schema, uses `uid` for PKs). SQLite.
|
||||
- **Auth:** `session` cookie, plus `X-API-KEY` / `Authorization: Bearer <api_key>` / HTTP Basic (username-or-email:password) - all resolved in `get_current_user`. PBKDF2-SHA256 via passlib. No JWT. Every user has an `api_key` (uuid7), set at signup and backfilled in `init_db`/`devplace apikey backfill`. Docs site at `/docs` (`routers/docs/` package, `DOCS_PAGES` registry; FastAPI's Swagger is moved to `/swagger` so `/docs` is free).
|
||||
- **Auth:** three account credentials: username+password, email+password, personal `api_key`. All password exchanges (`POST /auth/login` form+JSON, `POST /auth/token`, HTTP Basic, devRant `POST /api/users/auth-token`) take username-or-email as identifier (username case-sensitive, email lowered); the `api_key` rides `X-API-KEY` / `Authorization: Bearer` (client-side `DEVPLACE_API_KEY` env var holds its value, injected into containers) plus `session` cookie - all resolved in `get_current_user` (order: session, X-API-KEY, Bearer, Basic; headers also try DevRant/access tokens). Every JSON return of the personal key also returns `username`+`email` (login/signup `data`, gated `ProfileOut.email` beside `api_key`, regenerate), so `GET /profile` with an API key is the whoami/account fetch; never add `email` to public `UserOut`. PBKDF2-SHA256 via passlib. No JWT. Every user has an `api_key` (uuid7), set at signup and backfilled in `init_db`/`devplace apikey backfill`. Docs site at `/docs` (`routers/docs/` package, `DOCS_PAGES` registry; FastAPI's Swagger is moved to `/swagger` so `/docs` is free).
|
||||
- **Static:** `devplacepy/static/` mounted at `/static`; URLs are boot-versioned (`/static/v<ts>/...`) via `static_url`/`assetUrl` and served immutable for a year.
|
||||
- **Templates:** `devplacepy/templates/`. Shared `templates` instance from `devplacepy.templating` - all routers import from there, never instantiate their own.
|
||||
- **Ports:** 10500 (dev), 10501 (tests; the serial suite uses a single uvicorn subprocess).
|
||||
- **Username:** letters, numbers, hyphens, underscores only, 3-32 chars. **Password:** minimum 6 chars.
|
||||
- **Avatars:** Multiavatar SVG generated locally from a seed in <5ms, in-memory cache cleared on restart, fallback to initial-based SVG on error. URL `/avatar/multiavatar/{seed}?size={size}`. The seed is per-user: the nullable `users.avatar_seed` column overrides the username. Always resolve it through the single null-safe choke point `avatar.avatar_seed(user)` (a Jinja global) - `user.get("avatar_seed") or user.get("username")` - never read `avatar_seed` or pass `username` to `avatar_url(...)` directly; every render site (the `_avatar_link.html` partial, `og_image`, the devRant avatar payload, etc.) goes through it. Regenerate is owner-or-admin at `POST /profile/{username}/regenerate-avatar` (writes a fresh `generate_uid()`, invalidates the user cache, audits `profile.avatar.regenerate`); the old seed is never stored, so the old avatar cannot return. Devii tool `regenerate_avatar` (`CONFIRM_REQUIRED`).
|
||||
- **Avatars:** Multiavatar SVG generated locally at `/avatar/multiavatar/{seed}?size={size}`. Seed resolution, regenerate flow, and the owner-or-admin rule live in `devplacepy/templates/CLAUDE.md` ("Avatar seed choke point").
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -55,60 +58,12 @@ devplace token list <username> # list a user's active access tokens
|
||||
devplace token revoke <token_uid> # revoke a single access token by uid
|
||||
devplace token revoke-all <username> # revoke all access tokens for a user
|
||||
devplace token prune # soft-delete all expired access tokens
|
||||
devplace news clear # delete all news rows
|
||||
devplace news sanitize # strip HTML from news descriptions/content
|
||||
devplace attachments prune # remove orphan attachment records/files
|
||||
devplace system prune [--dry-run] # safe but aggressive: purges soft-deleted attachment/project-file blobs, sweeps blob files with zero DB reference at all (e.g. left by an interrupted/racing sync), and GCs orphaned container workspace dirs
|
||||
devplace devii reset-quota <username> # reset one user's rolling 24h AI quota
|
||||
devplace devii reset-quota --guests # reset every guest quota
|
||||
devplace devii reset-quota --all # reset every quota (users and guests)
|
||||
devplace devii tasks list [--all] # list scheduled Devii tasks and their owners
|
||||
devplace devii tasks disable <uid> # disable one scheduled task
|
||||
devplace devii tasks prune # disable every task whose owner may not schedule
|
||||
devplace gateway quota list # list AI gateway quota rules and current 24h spend
|
||||
devplace gateway quota set --limit-usd N [--owner-kind K] [--owner-id ID] [--app-reference APP] [--label L] [--uid UID]
|
||||
devplace gateway quota delete <uid> # delete a quota rule
|
||||
devplace gateway quota reset [--owner-kind K] [--owner-id ID] [--app-reference APP] # clear the counted 24h spend (keeps the usage history)
|
||||
devplace zips prune # delete expired zip archives + job rows
|
||||
devplace zips clear # delete every zip archive + job row
|
||||
devplace forks prune # delete expired completed fork job rows (forked projects persist)
|
||||
devplace forks clear # delete every fork job row (forked projects persist)
|
||||
devplace community discover <query> [--run] [--relearn] [--dry-run] # discover, learn and generate collectors for an external community
|
||||
devplace community run <slug> [--dry-run] # run a community's collectors through the sync API
|
||||
devplace community login <slug> [--login-user U] [--login-email E] [--login-password P | --clear] # store or remove the account used to log in
|
||||
devplace community list # list communities
|
||||
devplace messaging prune-tickets # delete expired WebSocket auth tickets (ws_tickets)
|
||||
devplace seo prune # delete expired SEO audit reports + job rows
|
||||
devplace seo clear # delete every SEO audit report + job row
|
||||
devplace seo-meta prune # delete expired SEO metadata job rows (generated metadata persists)
|
||||
devplace seo-meta clear # delete every SEO metadata job row (generated metadata persists)
|
||||
devplace deepsearch prune # delete expired DeepSearch sessions + job rows + collections
|
||||
devplace deepsearch clear # delete every DeepSearch session + job row + collection
|
||||
devplace isslop analyze <url> # run a AI usage analysis from the terminal (report persists)
|
||||
devplace isslop prune # delete expired AI usage analysis job rows (analyses + reports persist)
|
||||
devplace isslop clear # delete every AI usage analysis, its report and job rows
|
||||
devplace quiz prune # delete abandoned/expired quiz attempts older than the retention window
|
||||
devplace game market prune # delete Code Farm market tick buckets older than the tracking window
|
||||
devplace game steals prune # delete Code Farm raid records older than the raid-efficiency window
|
||||
devplace game era status # show the current Code Farm Era
|
||||
devplace game era start <name> [--days N] # start a Code Farm Era (default 28 days)
|
||||
devplace game era end # end the running Code Farm Era (ranks, awards Stars, records results)
|
||||
devplace accounts pending # list deleted accounts awaiting their purge
|
||||
devplace accounts prune # permanently purge accounts past the deletion grace window (--dry-run to preview)
|
||||
devplace backups list # list recorded backups
|
||||
devplace backups run <database|uploads|keys|full> # enqueue a backup (processed by the running server)
|
||||
devplace backups prune # remove backup records whose archive file is missing
|
||||
devplace backups clear # delete every backup archive + record
|
||||
devplace containers list # list container instances
|
||||
devplace containers reconcile # run one reconcile pass (desired vs docker ps)
|
||||
devplace containers prune # reap orphan containers + dangling images
|
||||
devplace containers prune-builds # remove legacy per-project images + clear dockerfiles/builds tables (one-time)
|
||||
devplace containers gc-workspaces # remove workspace dirs with no instances
|
||||
devplace emoji-sync # regenerate static/js/emoji-shortcodes.js from the emoji library (run after an emoji dep bump)
|
||||
devplace embeds-sync # regenerate static/js/embed-spec.js from devplacepy/embeds.py (run after editing the embed table)
|
||||
devplace migrate-data # relocate legacy runtime files into data/ (idempotent; --dry-run to preview)
|
||||
```
|
||||
|
||||
Per-subsystem commands live in the nested file: `devplace devii ...` (Devii), `devplace gateway quota ...` (AI gateway), `devplace backups ...` (backup service), `devplace containers ...` (container manager), `devplace news ...` (news service), `devplace community ...` (community discovery), `devplace messaging prune-tickets` (messaging), `devplace {zips|forks|seo|seo-meta|deepsearch|isslop} ...` (async jobs), `devplace quiz prune` (quizzes), `devplace game ...` (Code Farm), `devplace accounts ...` (moderation), `devplace apikey backfill`, `devplace attachments prune`, `devplace system prune` (database), `devplace emoji-sync` (frontend JS), `devplace embeds-sync` (templates).devplace migrate-data # relocate legacy runtime files into data/ (idempotent; --dry-run to preview)
|
||||
```
|
||||
|
||||
### Runtime data layout (single source of truth)
|
||||
|
||||
Every runtime/user-generated artifact lives under one root, `config.DATA_DIR` (`DEVPLACE_DATA_DIR`, default `<repo>/data`). `config.py` derives every runtime path from it and lists them in the `DATA_PATHS` registry; `ensure_data_dirs()` creates the whole tree before anything is written. **No module computes a runtime path from scratch** - import the constants (`UPLOADS_DIR`, `ATTACHMENTS_DIR`, `PROJECT_FILES_DIR`, `ZIPS_DIR`, `ZIP_STAGING_DIR`, `FORK_STAGING_DIR`, `KEYS_DIR`, `BOT_DIR`, `LOCKS_DIR`, `CONTAINER_WORKSPACES_DIR`, `DEVII_TASKS_DB`, `DEVII_LESSONS_DB`, `VAPID_*_FILE`, `SERVICE_LOCK_FILE`, `INIT_LOCK_FILE`). Uploads are physically under `data/uploads/` but still served at the unchanged `/static/uploads/` URL. Stored DB values for attachments/project files are relative (`directory` + `stored_name`), so no DB rewrite is ever needed for a layout change.
|
||||
@@ -142,6 +97,7 @@ Nested `CLAUDE.md` files (loaded automatically by Claude Code only when a file i
|
||||
| Path | Covers |
|
||||
|------|--------|
|
||||
| `devplacepy/routers/CLAUDE.md` | Full URL prefix map, route aggregation rules, HTML/JSON negotiation, FastAPI patterns, gists, feed/listing features, engagement (reactions/bookmarks/polls/heatmap/follow/block-mute), SEO implementation, polymorphic comments/votes |
|
||||
| `devplacepy/routers/admin/CLAUDE.md` | The admin page specification (A1-A11): rendering, response contract, page anatomy, class vocabulary, time, caps, remote work, live refresh, assets, the nav registry, responsiveness |
|
||||
| `devplacepy/routers/projects/CLAUDE.md` | Project detail page, virtual filesystem routes, visibility/read-only UI, deletion confirmation |
|
||||
| `devplacepy/routers/docs/CLAUDE.md` | The `/docs` documentation site: `DOCS_PAGES`, audience tiers, prose rendering, API tester |
|
||||
| `devplacepy/routers/devrant/CLAUDE.md` | devRant-compatible REST API (`/api`) |
|
||||
@@ -191,75 +147,23 @@ The AI usage analyzer (`devplace isslop analyze`, the `/tools/isslop` job servic
|
||||
|
||||
### Routing layout
|
||||
|
||||
Routers in `devplacepy/routers/` are organised as a **directory tree that mirrors the endpoint (URL) path**, exactly like `tests/`. A domain with a single resource stays one flat file (`feed.py`, `posts.py`, ...); a domain with several sub-resources is a **package directory** split one file per sub-resource. Each leaf declares its own `router = APIRouter()`; the package `__init__.py` aggregates with `router.include_router(...)`. A leaf owning the domain's collection-root (`""`) route must be the package's base router (FastAPI rejects an empty path under an empty prefix). Full elaboration, per-domain detail, and the complete deep-dive live in `devplacepy/routers/CLAUDE.md` - read it before touching routing. Compact map:
|
||||
|
||||
| Prefix | Router |
|
||||
|--------|--------|
|
||||
| `/auth` | auth/ package |
|
||||
| `/feed`, `/posts`, `/comments` | flat files |
|
||||
| `/topics` | topics.py - crawlable per-topic category index pages (`/topics` hub, `/topics/{topic}` listing) |
|
||||
| `/projects`, `/projects/{slug}/files`, `/projects/{slug}/containers` | projects/ package - see `routers/projects/CLAUDE.md` |
|
||||
| `/profile` | profile/ package (customization, notifications, ai-correction, ai-modifier, interactions, telegram, usage) |
|
||||
| `/messages` | messages.py - see `services/messaging/CLAUDE.md` |
|
||||
| `/notifications`, `/votes`, `/reactions`, `/bookmarks`, `/polls`, `/avatar`, `/follow`, `/leaderboard` | flat files |
|
||||
| (none) | relations.py - block/mute |
|
||||
| `/` | landing.py - home route (guests get the splash, users the dashboard) |
|
||||
| `/admin`, `/admin/services`, `/admin/containers` | admin/ package |
|
||||
| `/issues` | issues/ package - see `services/gitea/CLAUDE.md` |
|
||||
| `/gists`, `/news`, `/uploads`, `/media` | flat files |
|
||||
| `/giphy` | giphy.py - GIF picker backend (search, trending, attach), see `services/giphy/CLAUDE.md` |
|
||||
| `/openai` | openai_gateway.py - see `services/openai_gateway/CLAUDE.md` |
|
||||
| `/devii` | devii.py - see `services/devii/CLAUDE.md` |
|
||||
| `/zips`, `/forks` | see `services/jobs/CLAUDE.md` |
|
||||
| `/tools` | tools/ package (SEO diagnostics, DeepSearch, AI Usage Analyzer) - see `services/jobs/CLAUDE.md` |
|
||||
| `/p/{slug}` | proxy.py - container ingress reverse proxy |
|
||||
| `/xmlrpc` | xmlrpc.py - see `services/xmlrpc/CLAUDE.md` |
|
||||
| `/api` | devrant/ package - see `routers/devrant/CLAUDE.md` |
|
||||
| `/dbapi` | dbapi/ package, **primary-administrator-only, strictly READ-ONLY** - see `services/dbapi/CLAUDE.md` |
|
||||
| `/sync` | sync/ package, **administrator only**, off by default - see `services/sync/CLAUDE.md` |
|
||||
| `/game` | game/ package - see `services/game/CLAUDE.md` |
|
||||
| `/reports`, `/admin/moderation`, `/workspaces` | reports.py, admin/moderation.py, workspaces.py - see `services/moderation/CLAUDE.md` |
|
||||
| `/quizzes` | quizzes/ package - see `services/quiz/CLAUDE.md` |
|
||||
| `/battles` | battles.py - see `services/opinionwar/CLAUDE.md` |
|
||||
| (none) | push.py (web push/PWA), docs.py (see `routers/docs/CLAUDE.md`) |
|
||||
| `/pubsub` | pubsub.py - see `services/pubsub/CLAUDE.md` |
|
||||
| (none) | seo.py - `/robots.txt`, `/sitemap.xml` |
|
||||
Routers in `devplacepy/routers/` are organised as a **directory tree that mirrors the endpoint (URL) path**, exactly like `tests/` (one segment per directory, last segment is the file; packages aggregate with `include_router`). A leaf owning the domain's collection-root (`""`) route must be the package's base router. Full URL prefix map, aggregation rules, HTML/JSON negotiation, FastAPI patterns, and per-domain detail live in `devplacepy/routers/CLAUDE.md` - read it before touching routing. Sub-domain pages: `routers/projects/`, `routers/docs/`, `routers/devrant/` (each with its own nested file, see Subsystem map).
|
||||
|
||||
### Templates and frontend
|
||||
|
||||
- All routers MUST import the shared `templates` from `devplacepy.templating`. Do NOT instantiate `Jinja2Templates` per router.
|
||||
- Templates extend `base.html`; page CSS via `{% block extra_head %}`, page JS via `{% block extra_js %}`.
|
||||
- **Nav active state is the `nav_active` Jinja global**, never an inline path check.
|
||||
- **Static asset URLs are boot-versioned:** never hardcode a bare `/static/...` href/src - use `static_url(path)` (Jinja) / `assetUrl(path)` (JS).
|
||||
- All JS is ES6 modules, one class per file, instantiated as `app`. Custom web components (`dp-*` prefix) and shared frontend utilities (`Http`, `Poller`, `JobPoller`, `OptimisticAction`, `FloatingWindow`, `ScrollMemory`) are documented in `devplacepy/static/js/CLAUDE.md` - reuse them, never re-implement.
|
||||
- CDN scripts in `base.html` MUST use `defer` or `type="module"`.
|
||||
- Modal system, shared template partials (`_avatar_link.html`, `_user_link.html`, `_sidebar_search.html`) are documented in `devplacepy/templates/CLAUDE.md`.
|
||||
All routers import the shared `templates` from `devplacepy.templating` (never instantiate per router); templates extend `base.html` (`extra_head`/`extra_js` blocks, `nav_active` global, boot-versioned `static_url`/`assetUrl`, deferred CDN scripts). JS is ES6 modules, one class per file, `dp-*` web components plus shared utilities (see `devplacepy/static/js/CLAUDE.md`). Modal system and shared partials: see `devplacepy/templates/CLAUDE.md`.
|
||||
|
||||
### Content rendering pipeline
|
||||
|
||||
**Server-rendered content and titles are rendered on the BACKEND for SEO** (`devplacepy/rendering.py`, Jinja globals `render_content(text)`/`render_title(text)`). This is the default for all content that exists at request time (post bodies, comments, news, project/gist descriptions, DM history, every content title). It mirrors the client pipeline using **mistune**: em-dash normalization, emoji shortcodes, GFM markdown (`escape=True` - the server XSS control), then a media pass turning bare URLs into embeds and `@mentions` into links. Both are `@lru_cache`d. Server-rendered code blocks get syntax highlighting + Copy button client-side via `ContentEnhancer`.
|
||||
|
||||
The CLIENT pipeline (`ContentRenderer.js`, `dp-content`/`dp-title`) is retained ONLY for genuinely live/dynamic content that does not exist at request time (live comments, DM bubbles, Devii/DeepSearch/Docs chat, planning report). Runs `marked` -> **`DOMPurify.sanitize`** (the client XSS control, fail-closed) -> highlight.js -> media/autolink. **Do NOT add `data-render` to server-rendered content - call `render_content`/`render_title` instead.**
|
||||
|
||||
**Emoji shortcodes are the full GitHub/Discord `:name:` set** (~4869 names), generated once from the `emoji` library by `rendering.py` `build_emoji_shortcodes()`; the frontend gets the identical map via the generated `static/js/emoji-shortcodes.js` (regenerate with `devplace emoji-sync` after bumping the dependency, never hand-edit).
|
||||
|
||||
**YouTube and YouTube Music embeds** have ONE specification, `devplacepy/embeds.py` (`EmbedParser.parse(url)` -> `Embed(kind, video_id, list_id, start, music)`, `EmbedParser.src(embed)`): exact host allowlists (never substring matching), query-order independent parsing, validated ids only (`[A-Za-z0-9_-]{11}` video, `{13,64}` list) so nothing but validated characters can reach an iframe `src`. YouTube Music has no player of its own and `music.youtube.com` sends `X-Frame-Options: SAMEORIGIN`, so a music link is YouTube's player (`www.youtube.com/embed/...`) wrapped in `<div class="embed-music">` with an "Open in YouTube Music" caption link; playlists/albums use `embed/videoseries?list=`. `/browse`, `/channel`, `/search`, `/library` carry no embeddable id and stay plain links. At most `MAX_MUSIC_EMBEDS` (3) music embeds render per content item, the overflow stays a plain link; plain YouTube is uncapped. `rendering.py` (`_youtube_embed`, per-`_MediaProcessor` `_EmbedBudget`) and `ContentRenderer.js` (`youtubeEmbed`, via `static/js/EmbedParser.js`) both follow it; the JS constants come from the generated `static/js/embed-spec.js` (`devplace embeds-sync`, never hand-edit). Never add another YouTube regex.
|
||||
|
||||
**Email anonymization:** both `_render_content` and `_render_title` mask email addresses to prevent doxing. `_mask_emails` in `rendering.py` runs on rendered text nodes only (inside `_transform_text`, `_MediaProcessor`, and `_InlineFilter` - never before mistune, or the `*` mask characters would be parsed as emphasis) and stars ~80% of the local part (keeps a leading 20%, minimum one visible char). Addresses on `molodetz.nl` (and its subdomains) are exempt and render verbatim.
|
||||
|
||||
**Em-dash normalization:** `_normalize_dashes` in `rendering.py` replaces all forms (em dash `\u2014`, en dash `\u2013`, and their HTML entities) with a hyphen BEFORE mistune processes the text. Runs inside `_render_content`/`_render_title` which are `@lru_cache`d, so each unique text is normalized once. No per-template overhead.
|
||||
Server content renders on the backend for SEO (`render_content`/`render_title` in `devplacepy/rendering.py`); the client pipeline is only for live content (`DOMPurify` fail-closed). Full pipeline rules (emoji map, YouTube spec, email masking, dash normalization) live in `devplacepy/templates/CLAUDE.md` ("Content rendering pipeline").
|
||||
|
||||
### Auth
|
||||
|
||||
Session cookies named `session`, value a 64-char hex token. Passwords hashed with `pbkdf2_sha256` via passlib. `get_current_user(request)` returns user dict or `None`, per-process TTL cache (300s) keyed by token. `require_user(request)` raises a 303 redirect to `/` for guests; `require_admin(request)` redirects to `/feed` for non-admins. Public pages use `get_current_user` so guests can browse - POSTs are all guarded by `require_user`.
|
||||
Session cookies named `session`, value a 64-char hex token. Passwords hashed with `pbkdf2_sha256` via passlib. `get_current_user(request)` returns user dict or `None`, per-process TTL cache (300s) keyed by token. `require_user(request)` raises a 303 redirect to `/` for guests; `require_admin(request)` redirects to `/feed` for non-admins. Public pages use `get_current_user` so guests can browse - POSTs are all guarded by `require_user`. Password exchanges (`routers/auth/login.py`, `routers/auth/token.py`) reuse the `LoginForm.email` field as username-or-email: look up `email=identifier.lower()` first, then `username=identifier` un-lowered (mirroring `_user_from_basic` semantics); never lower the identifier before the username lookup.
|
||||
|
||||
### Database
|
||||
|
||||
SQLite via `dataset.connect` with WAL + 30s busy timeout + 256MB mmap. **SQLite is synchronous by design and will never be made async (hard rule).** The `dataset`/SQLite layer is called directly inside async route handlers - the database is a local file tuned with WAL/`synchronous=NORMAL`/8MB page cache/256MB mmap, so queries are sub-millisecond and never meaningfully stall the event loop. Do NOT convert the database layer to async, wrap calls in a threadpool/`run_in_executor`/`to_thread`, or raise synchronous DB access as a blocking-I/O concern - this is a settled design decision, not open for revisiting.
|
||||
|
||||
`init_db()` is idempotent and **ensures the full column set of any table code filters on** before creating indexes - `dataset` gives a lazily-created table only the columns of its first insert, so a partial insert elsewhere would leave a reduced schema that later 500s with `no such column`. Full dataset rules, indexing conventions (the soft-delete planner trap), site settings, and the complete table list live in `devplacepy/database/CLAUDE.md`.
|
||||
|
||||
Runtime config lives in `site_settings`, read via `get_setting(key, default)`/`get_int_setting(key, default)` (60s TTL cache, cross-worker invalidated via `cache_state`). Batch helpers (`get_users_by_uids`, `get_comment_counts_by_post_uids`, `get_vote_counts`, `load_comments`) exist specifically to avoid N+1 - use them instead of per-row lookups.
|
||||
**SQLite is synchronous by design and will never be made async (hard rule).** The `dataset`/SQLite layer is called directly inside async route handlers; never wrap it in a threadpool/`run_in_executor`/`to_thread` or raise sync DB access as a blocking-I/O concern. Dataset rules, indexing, soft delete, visibility spec, `site_settings`, batch helpers (use instead of N+1), and the table list live in `devplacepy/database/CLAUDE.md`.
|
||||
|
||||
### Per-user site customization (CSS/JS)
|
||||
|
||||
@@ -274,19 +178,19 @@ Users and guests inject their own CSS and JS, scoped to a page type or globally,
|
||||
|
||||
### Background task queue, AI correction/modifier, background services
|
||||
|
||||
`services/background.py` `background.submit(fn, *args)` is a generic fire-and-forget offload onto one per-worker `asyncio.Queue`; when the consumer isn't running (tests, full queue) it runs the callable **inline**, so audit/notification/XP writes stay deterministic for the suite while production defers them. It is the choke point for every audit-log write, every XP award, and every notification - handlers call `award_rewards`/`create_notification` directly (never wrap them in `background.submit`, that double-queues). AI content correction (opt-in, off by default) and the AI modifier (`@ai <instruction>` inline directive, on by default) rewrite user prose via the internal gateway; sync apply mode never blocks the event loop (`run_in_executor` + the `await_pending_corrections` middleware). `BaseService`/`ServiceManager` provide the async run loop and singleton registry for background services (`NewsService`, `GatewayService`, `DeviiService`, `BotsService`, container/audit/telegram reconcilers). Full detail on all of this, plus presence and the live view relay, is in `devplacepy/services/CLAUDE.md`.
|
||||
`background.submit` offload, AI correction/modifier via the internal gateway, `BaseService`/`ServiceManager`, presence, and the live view relay: see `devplacepy/services/CLAUDE.md`.
|
||||
|
||||
### Container manager, Devii assistant, AI gateway, async jobs, audit log
|
||||
|
||||
DevPlace ships a Docker-backed **Container manager** (admin-only, one shared `ppy:latest` image, security-hardened rootless workflow via a `sudo` superclone and `aptroot`), the **Devii** in-platform agentic assistant (WebSocket terminal, per-owner-channel sessions, scheduler/reminders, self-learning lessons, user-defined virtual tools, self-configured behavior, browser-automation client tools), the **AI gateway** (`/openai/v1/*`, single point of truth for every AI call, per-user cost attribution, provider/model routing overlay), **async job services** (`JobService` base pattern: zip, fork, SEO diagnostics, SEO metadata generation, DeepSearch, AI Usage Analyzer), and an admin-only append-only **audit log** (`record`/`record_system` entrypoints, `events.md` catalogue of every recorded event key, never raises into the caller). These are among the largest subsystems in the codebase - read their dedicated nested `CLAUDE.md` files (see Subsystem map) before working in any of them; do not assume prior knowledge from this summary.
|
||||
Container manager, Devii, AI gateway, async jobs, audit log: see their nested `CLAUDE.md` files (Subsystem map). Read the dedicated file before working in any of them.
|
||||
|
||||
### Telegram bot, email, devRant compatibility API, issue tracker
|
||||
|
||||
Devii is also reachable over **Telegram** (one supervised long-poller subprocess, `channel="telegram"` isolated conversation thread), can drive a user's own **external mailbox** over IMAP/SMTP (stdlib only, credentials in a soft-deletable table, SSRF-guarded), and DevPlace exposes a **devRant-compatible REST API** at `/api` (translates devRant requests onto native posts/comments/votes via reused audited cores, ID mapping is `posts.id`/`comments.id` directly). The **issue tracker** at `/issues` has no local store - it reads/writes Gitea live via one shared bot token, filing is an async AI-enhanced job. Full detail in the respective nested `CLAUDE.md` files.
|
||||
Telegram bridge, email tools, devRant API, Gitea issue tracker: see their nested `CLAUDE.md` files (Subsystem map).
|
||||
|
||||
### SEO
|
||||
|
||||
`devplacepy/seo.py` generates JSON-LD schemas (WebSite, BreadcrumbList, DiscussionForumPosting, ProfilePage, SoftwareApplication). Every router builds context via `base_seo_context(request, ...)`. Auth/messages/notifications are `noindex,nofollow`; profiles with fewer than 2 posts are `noindex,follow`. `/robots.txt` and `/sitemap.xml` are served by `routers/seo.py`. Full implementation map (template layer, heading hierarchy, slugs, related posts, performance, default OG image, SEO tests) is in `devplacepy/routers/CLAUDE.md`.
|
||||
JSON-LD schemas via `devplacepy/seo.py` and `base_seo_context`; index/follow rules per surface. Full implementation map in `devplacepy/routers/CLAUDE.md`.
|
||||
|
||||
## The production database is never touched without explicit confirmation (hard rule)
|
||||
|
||||
@@ -311,79 +215,41 @@ The escape hatch is deliberately two-factor and must never be self-served: after
|
||||
- **Roles are stored capitalized:** `users.role` is exactly `"Admin"` or `"Member"`. Always test admin-ness through the `is_admin(user)` global (case-sensitive `== "Admin"`) - never hand-roll a lowercase compare. **Any write to `users.role` MUST call `database.invalidate_admins_cache()`.**
|
||||
- **Admin seniority: a junior admin cannot manage a more senior admin.** Every per-user mutation in `routers/admin/users.py` and `routers/admin/moderation.py` is gated by `is_senior_admin(actor, target)` (`routers/admin/_shared.py`) - blocks (audits `result="denied"`) when the target is an Admin who registered earlier. Server-side, so it also covers Devii's admin tools.
|
||||
- **Never pass a `respond()` context key that collides with a Jinja global.** `respond(request, template, ctx, model=XOut)` feeds the same `ctx` to both the Pydantic model (JSON) and the template. A key like `is_admin`/`avatar_url`/`is_self` holding a non-callable value shadows the global across the whole inheritance chain, turning `{% if is_admin(user) %}` into `False(user)` -> `TypeError`, a 500 that fires only for the branch that calls the global. Name viewer/permission flags distinctly (`viewer_is_admin`, not `is_admin`) in both schema and context.
|
||||
- **Project visibility (`is_private`) and read-only (`read_only`)** are owner-controlled flags on `projects`. Read access is gated by the single `content.can_view_project(project, user)` predicate at EVERY read surface - never re-implement the check inline. Predicate: `not is_private OR is_owner OR (is_admin AND owner is not an admin)` - a project hidden by a member stays visible to any admin, but one hidden by an admin is visible only to that owner admin. **Containers have their own, stricter isolation predicates** (`owns_instance`, `can_view_project_containers`, `can_view_instance`, `can_manage_instance`) - the primary administrator sees/manages every container; any other admin can VIEW others' containers only on public projects and can MANAGE only instances they own. Read-only is enforced as a single data-layer guard `project_files._guard_writable(project_uid)` at the top of every mutation entrypoint - add it to any NEW file-mutating function. Devii may flip read-only/visibility only after explicit confirmation (`CONFIRM_REQUIRED`). Full UI-level detail in `devplacepy/routers/projects/CLAUDE.md`.
|
||||
- **Content visibility (`published`/`hidden`/`draft`/`offline`) on posts, gists, projects and news is one specification, `devplacepy/database/visibility.py`.** Any new read of those tables applies `listed_clause`/`listed_sql` (or goes through `paginate`, which does it), and any single-item or target access uses `content.can_view_item`/`can_view_target`. NULL reads as published. Full detail in `devplacepy/database/CLAUDE.md`.
|
||||
- **Project visibility and read-only** are owner-controlled flags gated by single predicates (`can_view_project`, container isolation predicates, `_guard_writable`): see `devplacepy/routers/projects/CLAUDE.md`.
|
||||
- **Content visibility on posts, gists, projects and news is one specification** (`database/visibility.py`, choke points `listed_clause`/`listed_sql`, `can_view_item`/`can_view_target`): see `devplacepy/database/CLAUDE.md`.
|
||||
- **Deletions ALWAYS require confirmation:** `confirmation_error` gates EVERY content delete tool via `CONFIRM_REQUIRED` (`delete_post`, `delete_comment`, `delete_gist`, `delete_project`, `project_delete_file`, `delete_media`, `delete_attachment`, `admin_delete_news`, container delete, and any `container_exec` matching `dispatcher.DESTRUCTIVE_COMMAND`). The first call is refused; the agent must show the exact target then pass `confirm=true`. **Load-bearing: every confirmation-gated tool MUST also declare a `confirm` boolean param in its catalog spec** - schemas set `additionalProperties: false`, so a gated tool without a declared `confirm` param can never receive it and loops forever.
|
||||
|
||||
## Every user-generated surface is reportable by construction (hard rule)
|
||||
|
||||
A new content table added to `SOFT_DELETE_TABLES` that is visible to anyone other than its author MUST be registered in `database/moderation.py` `REPORTABLE_TARGETS`, MUST resolve in `resolve_object_url`, and MUST include `_report_button.html` in its action bar. A table that is genuinely private to its owner goes in `UNREPORTABLE_TABLES` **with its reason** instead. `tests/unit/database/moderation.py` computes the difference and fails the suite on anything unclassified, so report coverage is closed under future additions rather than remembered; the e2e coverage test enforces the third requirement.
|
||||
New user-generated tables are classified in `REPORTABLE_TARGETS` (with `resolve_object_url` and `_report_button.html`) or in `UNREPORTABLE_TABLES` with a reason; the suite enforces it. No social login, payment, purchasable randomness, advertising, or cross-app tracking without their app-store obligations. Full detail in `devplacepy/services/moderation/CLAUDE.md`.
|
||||
|
||||
The same rule keeps the untriggered app-store conditionals untriggered: **no social login, no payment path, no purchasable randomness, no advertising, and no cross-app tracking** may be introduced without also implementing the obligations each of them creates (Sign in with Apple, in-app purchase, odds disclosure, ad reporting, App Tracking Transparency). Full detail in `devplacepy/services/moderation/CLAUDE.md`.
|
||||
## Admin pages follow one specification (hard rule)
|
||||
|
||||
Every `/admin` page is built to `devplacepy/routers/admin/CLAUDE.md`: backend-rendered first paint with no "Loading..." placeholder, one builder shared by the HTML route and the `/data` refresh endpoint, `respond()` with an `*Out` model, `admin-*` classes only, `local_dt` for every instant, every list paginated or capped, no remote call in a GET, `Poller` only, one Chart.js path, and the section list declared once in `devplacepy/admin_sections.py`. `tests/unit/admin_spec.py` enforces the mechanical rules. A new admin page that breaks the spec does not ship.
|
||||
|
||||
## Modal pattern
|
||||
|
||||
`Application.js` `initModals()` toggles a `.visible` CSS class on `.modal-overlay`; the CSS rule `.modal-overlay.visible { display: flex; }` handles visibility. Triggers usually have `href="#"`, so call `e.preventDefault()`. `.modal-close` is wired generically - no inline JS needed. Full modal/partial/CDN detail in `devplacepy/templates/CLAUDE.md`.
|
||||
See `devplacepy/templates/CLAUDE.md` (modal system, partials, CDN).
|
||||
|
||||
## Polymorphic comments and votes
|
||||
|
||||
The `comments` table uses `(target_type, target_uid)` so `_comment_section.html` works for `post`, `project`, `gist`, and `news`. Votes follow the same shape via `/votes/{target_type}/{uid}`. `resolve_target_redirect()` in `comments.py` maps target_type back to the correct detail URL. Full detail (reactions/bookmarks/polls/heatmap/follow/block-mute reuse the same target-type pattern) in `devplacepy/routers/CLAUDE.md`.
|
||||
`(target_type, target_uid)` shapes comments, votes, and the engagement reuse family: see `devplacepy/routers/CLAUDE.md`.
|
||||
|
||||
## Project-wide soft delete (hard rule)
|
||||
|
||||
**Every removal is a soft delete; only garbage collection is a hard delete.** Removable rows carry `deleted_at` (ISO timestamp) + `deleted_by` (actor uid or `system`); a live row has `deleted_at = NULL` and every list/count read filters `deleted_at IS NULL`. The table set is `database.SOFT_DELETE_TABLES`; `init_db` ensures both columns + a partial index per table. Core primitives in `database/`: `soft_delete`, `soft_delete_in`, `restore`, `purge`, `list_deleted`/`count_deleted`, `restore_event`/`purge_event`.
|
||||
|
||||
- **Every INSERT into a soft-deletable table MUST write `deleted_at: None, deleted_by: None`** - `dataset.find(deleted_at=None)` on a table missing the column matches NOTHING, silently hiding all rows on a fresh DB.
|
||||
- **Any new read of a soft-deletable table MUST filter `deleted_at IS NULL`.**
|
||||
- **Toggles revive, never duplicate:** look up the physical row ignoring `deleted_at`, stamp on toggle-off, clear on re-toggle.
|
||||
- **Cascades share one `stamp`** so the event restores/purges atomically.
|
||||
- **Delete authz is owner-OR-admin on the endpoint** - one check covers the UI and Devii.
|
||||
- **GC stays HARD** (job sweep, metrics ring, usage-ledger prune/reset, expired-session cleanup, fork rollback). Logout is soft (auditable); only expiry GC is hard.
|
||||
|
||||
Admin **Trash** at `/admin/trash` restores/purges by event. Full table list, dataset rules, indexing conventions (the soft-delete planner trap), and site settings are in `devplacepy/database/CLAUDE.md`.
|
||||
**Every removal is a soft delete; only garbage collection is a hard delete.** Inserts write `deleted_at: None, deleted_by: None`; reads filter `deleted_at IS NULL`; toggles revive; cascades share one stamp; delete authz is owner-OR-admin. Full table list, primitives, and indexing rules in `devplacepy/database/CLAUDE.md`.
|
||||
|
||||
## Testing
|
||||
|
||||
Playwright (NOT pytest-playwright). Around 2882 tests in `tests/`, split into three category directories by *what they exercise*: `tests/api/` (HTTP integration, no browser), `tests/e2e/` (Playwright browser), `tests/unit/` (pure in-process). **The directory tree mirrors the path** - one segment per directory, last segment is the file. `api`/`e2e` mirror the URL path (`GET /admin/ai-usage` -> `tests/e2e/admin/aiusage.py`); `unit` mirrors the source module path (`devplacepy/utils.py` -> `tests/unit/utils.py`). A test's tier is decided by its fixtures: `page`/`alice`/`bob` = e2e; `app_server`/`seeded_db` or any HTTP call = api; `local_db`-only or no fixture = unit. Run a tier with `make test-unit`/`make test-api`/`make test-e2e`; `make test` runs all three.
|
||||
|
||||
Fixture stack: `app_server` (session-scoped uvicorn subprocess on port 10501), `browser_context` (session-scoped Playwright context), `page` (function-scoped, fresh cookies), `alice`/`bob` (seeded logged-in users, `bob` gets its own context for multi-user tests).
|
||||
|
||||
Required patterns: every `page.goto(...)`/`page.wait_for_url(...)` MUST pass `wait_until="domcontentloaded"`; prefer `page.locator(...).wait_for(state="visible")` over `wait_for_selector`; scope ambiguous selectors (e.g. comment Delete is `.comment-action-btn:has-text('Delete')`). A test that flips a global `site_settings` value MUST restore it in `try/finally`. Full pitfalls/patterns catalogue is in `tests/CLAUDE.md`.
|
||||
|
||||
**Always run the full test suite (`make test` - unit, api, and e2e, every test) as the final validation of every change.** No tier may be skipped and no subset substituted for the whole. The clean import (`python -c "from devplacepy.main import app"`) and per-language manual checks are preliminary gates before the suite, not replacements for it. Any failure is a real signal and blocks completion until fixed.
|
||||
Tiers, fixtures, required patterns (domcontentloaded, try/finally restores), and the triage loop live in `tests/CLAUDE.md`. The mandate: **full `make test` green as the final validation of every change, no tier skipped, no subset substituted.** Import gate and per-language manual checks are preliminary gates, never replacements.
|
||||
|
||||
## Rigorous correctness verification (money, state machines, concurrency)
|
||||
|
||||
The persisted test suite (`tests/unit`/`api`/`e2e`) is example-based: it proves the specific inputs someone wrote down behave correctly. It is structurally blind to three classes of bug - a formula wrong at an input nobody tried, an invariant violated only after a long sequence of actions, and a race that only two nearly-simultaneous requests trigger. **Any feature that touches a spendable resource (coins, credits, quotas), a bounded state machine (levels, tiers, counters with a floor/ceiling), or a read-then-write mutation reachable from more than one request path applies this procedure in addition to, not instead of, the normal persisted tests.** A simple CRUD toggle doesn't need it; an economy, inventory, ledger, or scoring feature does. This was built out fully for the Code Farm economy rebalance (see `devplacepy/services/game/CLAUDE.md`, "Every purchase/upgrade is atomic..." - the worked example, including every bug it actually caught) and is the standing procedure for anything shaped like it going forward.
|
||||
|
||||
Four escalating layers, run in order, as disposable Python scripts that call the real functions directly against a temp DB (`DEVPLACE_DATABASE_URL`/`DEVPLACE_DATA_DIR` pointed at a scratch file) - not pytest files, unless the user separately asks for persisted tests too:
|
||||
|
||||
1. **Property/invariant checks on every pure function, across the full input domain.** For each formula (a reward, a cost curve, a score, a discount), assert the mathematical property it must have - monotonicity, bounds, non-negativity, idempotency, additivity over a partition of its domain - by iterating the real range (hundreds to thousands of values), not a handful of hand-picked spot checks. A monotonicity bug at input 347 is invisible if only 0, 1, and 10 are tried.
|
||||
2. **Stateful fuzzing.** Build N independent entities, fire a long randomized sequence of every mutating action across all of them against a live temp DB, and re-check invariants after every single action: balances never negative, counters that should only increase never decrease, levels/tiers never exceed their declared bounds. Catch the domain's expected exception type and continue - the goal is catching invariant violations and *unexpected* exceptions, not asserting every action succeeds. This proves safety (nothing bad happens) but not liveness (legitimate actions actually succeed) - a bug that wrongly blocks a valid action just raises a well-formed expected exception and sails through a pure fuzz test undetected. Layer 3 exists because of exactly this gap.
|
||||
3. **Concurrency: prove races are closed, never infer it from luck.** Any read-then-write mutation reachable from more than one worker process (`uvicorn --workers N`) is a TOCTOU race until proven otherwise. Test with **real separate OS processes**, not threads in one process - `dataset` gives each thread its own pooled connection, and enough threads exhausts that pool and produces `database is locked` noise that is a test-harness artifact, not a finding about the application. Set up genuinely fresh, production-representative state before racing - **never pre-seed or zero a column that the real code path leaves unset/NULL.** This was the single most expensive mistake made building this procedure: a first race-safety pass "passed" only because its own setup script had artificially pre-zeroed columns that a real fresh row leaves as SQL `NULL` - silently hiding the exact bug the fix was supposed to prevent (`NULL = 0` evaluates to `NULL`, not true, in a SQL `WHERE` clause; any column not written in the row's original `INSERT` needs `COALESCE(column, 0)` in every later precondition and every arithmetic `SET`, not a bare comparison). Fire many concurrent attempts at the same resource, assert the exact right number succeed, and verify the final state matches the hand-computed expected total exactly (currency spent, levels advanced) - not just "the others were blocked." Fix a real race with a single atomic conditional SQL statement at the exact chokepoint (`UPDATE ... SET ... WHERE <precondition>`, checked via the driver's real `rowcount` - `dataset`'s wrapped `db.query()` does not expose it, use `db.executable.execute(sqlalchemy.text(...), params).rowcount` inside `with db:`), not a client-side lock or an optimistic-locking library this codebase doesn't otherwise use.
|
||||
4. **Static analysis beyond `py_compile`.** A clean `python -m py_compile` and a clean `from devplacepy.main import app` only prove syntax and module-load order - neither catches a missing import inside a function body, which is a runtime `NameError` invisible until that exact line executes. Run `pyflakes`/`ruff check` on every touched file before calling a change done; it is nearly free and catches an entire class of bug that layers 1-3 can each individually miss if they don't happen to exercise the broken line.
|
||||
Spendable resources, bounded state machines, and multi-worker read-then-write mutations additionally require the four-layer procedure (property checks, stateful fuzzing, real-process races, `pyflakes`/`ruff`): see `tests/CLAUDE.md` ("Rigorous correctness verification").
|
||||
|
||||
## Feature workflow
|
||||
|
||||
Every feature in DevPlace is **one data source fanning out into several consumers**. DevPlace has no isolated change - internalize this before editing. A single handler in `routers/{area}.py` is simultaneously the **four faces of one route**:
|
||||
|
||||
1. **HTML** - `respond()` returns a rendered template for browsers.
|
||||
2. **JSON** - the SAME `respond(..., model=XOut)` returns JSON when `Accept: application/json`. The `*Out` schema is the gate: a context key not declared on `*Out` is silently dropped from JSON even though the template still sees it.
|
||||
3. **Agent tool** - `services/devii/actions/catalog/` (the relevant module inside the package, e.g. `posts.py`, `admin.py`) exposes the route as an `Action` so Devii can call it on the user's behalf. `requires_auth` mirrors the route guard.
|
||||
4. **Documented endpoint** - `docs_api.py` `endpoint()` describes it (params, auth, `sample_response`) in the right group, rendered at `/docs/{group}.html`.
|
||||
|
||||
A new public read almost always needs all four. The cardinal failure mode is changing one face and forgetting a connected one - a real worked example (followers/following listing) touched nine files across data helpers, output schema, route, view, agent tool, API docs, and the docs trio below for one conceptual feature; that count is the norm, not the exception. If a change touches only one file, confirm none of the four faces were missed. Checklist, ordered by data flow:
|
||||
|
||||
1. **Understand.** Read the router, template, matching tests (per the tier naming rule above), and the matching nested `CLAUDE.md`. Trace input model -> router -> data helper -> response (HTML and JSON).
|
||||
2. **Data layer.** `database/` for query/batch helpers (never inline N+1 loops - use `get_users_by_uids`, `build_pagination`, `_in_clause`; guard raw SQL with `if "table" in db.tables`). `models/` for the Pydantic `Form` input model (add the class to the matching domain module and to the re-export list plus `__all__` in `models/__init__.py`). `schemas/` for the `*Out` JSON response model - every context key a JSON route exposes via `respond(..., model=XOut)` MUST exist on `XOut` or it is silently dropped. Schema auto-syncs via `dataset`; add indexes in `init_db()` with `CREATE INDEX IF NOT EXISTS`.
|
||||
3. **Server layer.** Handler with the right auth guard (`get_current_user` public read, `require_user` member POST, `require_admin` admin). Specific paths (`/{username}/followers`) declared before catch-alls (`/{username}`). Return HTML+JSON via `respond(request, template, ctx, model=XOut)` or pure JSON via `JSONResponse`. Register any NEW router in `main.py`.
|
||||
4. **View layer.** Extend `base.html`; page CSS in `{% block extra_head %}`, page JS in `{% block extra_js %}`. Reuse partials and template globals. JS is ES6 modules, one class per file, instantiated on `app`.
|
||||
5. **Safety layer (skip only when the feature stores nothing and shows nothing).** If the feature adds a surface that carries user-generated content, register it in `database/moderation.py` `REPORTABLE_TARGETS` (or in `UNREPORTABLE_TABLES` with a reason), resolve it in `resolve_object_url`, and include `_report_button.html` in its action bar - the registry test and the e2e coverage test both fail otherwise. If it collects or transmits a new *category* of personal data, or sends anything new to a third party, update `/docs/privacy.html` and the app-store privacy declarations in the same change; that disclosure is part of the feature, not a follow-up.
|
||||
6. **Agent + docs layer (the most-forgotten step - do not skip).** `services/devii/actions/catalog/` (the relevant module inside the package) - add an `Action` tool if a user could ask Devii to do this (`requires_auth=False` for public reads). `docs_api.py` - every public/auth endpoint gets an `endpoint()` entry with params and a `sample_response`. `routers/docs/pages.py` `DOCS_PAGES` for prose pages. SEO (`seo.py`) - `base_seo_context` and any JSON-LD for a new public page; add to `routers/seo.py` sitemap if indexable.
|
||||
7. **Document.** `README.md` (product-facing, routes/config/dependencies/user-visible features), the relevant nested `CLAUDE.md` (any new mechanic, helper, pitfall, or cross-layer wiring), this root `CLAUDE.md` only when a NEW architectural rule or workflow step is introduced (not per feature).
|
||||
8. **Validate.** Confirm a clean import (`python -c "from devplacepy.main import app"`), check each touched language manually, grep for em-dash in touched files (neither the character nor its HTML entity - use a hyphen), and run `pyflakes`/`ruff check` on every touched file. **If the feature touches a spendable resource, a bounded state machine, or a read-then-write mutation reachable from more than one request path, also run the four-layer procedure in "Rigorous correctness verification" above** - it is the default for that shape of feature, not an optional extra. **Finish by running the full persisted test suite (`make test` - every tier, every test) and fixing any failure before the change is done.** Write new tests in the matching tier/path, following the required patterns above.
|
||||
|
||||
Failures at any implementation step block the workflow - never skip a failed step.
|
||||
Every feature is one data source fanning out into HTML, JSON, a Devii action, and a documented endpoint. The ordered checklist (understand, data, server, view, safety, agent+docs, document, validate) lives in `devplacepy/routers/CLAUDE.md` ("Feature checklist"). Failures at any step block the workflow.
|
||||
|
||||
## CI/CD
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# Definition of Done
|
||||
|
||||
This is the completion contract for every change in this repository. A change is done only when every applicable gate below passes. It is linked from the root `CLAUDE.md` and draws on all nested `CLAUDE.md` files; where a nested file states a stricter rule for its subsystem, the stricter rule wins.
|
||||
|
||||
## 1. Universal gates (every change)
|
||||
|
||||
1. **Exact, minimal diffs.** Edit existing files; create a new file only when the change genuinely needs a home. No unrelated edits, no drive-by refactors.
|
||||
2. **DRY, one choke point.** If the behaviour already exists somewhere, reuse it through the existing choke point; never add a second implementation, second focus system, second removal path, second suspension check, second consent gate, second terms check, second proxy, second bulk mechanism, or second query on a different basis. A per-type copy of shared logic is a defect.
|
||||
3. **A specification exists somewhere.** Literally everything has a declared spec: a `spec.py` single source of truth, a registry (`REPORTABLE_TARGETS`, `DOCS_PAGES`, `NOTIFICATION_TYPES`, `GATEWAY_APPS`, `CUSTOMIZATION_PREF_COLUMNS`), a table in a `CLAUDE.md`, or an explicit decision section. The new behaviour is declared in it, not just implemented.
|
||||
4. **Zero tolerance for inconsistency.** New code matches existing implementation structurally and visually. Before modifying, find the relatable example; if none exists, explain and let the user decide how to continue.
|
||||
5. **The four faces.** Every feature is one data source fanning out into HTML, JSON (`respond(..., model=XOut)`, and a context key not on the `*Out` schema is silently dropped from JSON), a Devii agent action, and documentation. State each face explicitly, including "no change" where that is the decision.
|
||||
6. **Import gate and static checks.** `python -c "from devplacepy.main import app"` imports clean; `pyflakes`/`ruff` on every touched file is clean (module-level load order and missing function-level imports are invisible to the other checks). Check each touched language manually (Python compiles/imports, JS parses, CSS braces and HTML tags balance).
|
||||
7. **Full suite green.** `make test` (unit + api + e2e, serial, one pass) passes with no tier skipped and no subset substituted. Triage cheapest-first: `make test-fast`, then `make test-failed` until empty. A failing existing test is a contract to satisfy, never to skip, narrow (`-k`, `--deselect`), or rewrite to fit the change.
|
||||
8. **Verification through the real path.** Real filesystem, real concurrency, real failure injection: bursts, races, and full disks are test cases, not weather. Re-running your own probe is not verification; the oracle must be independent (the repo's own tests, a golden file, a second method).
|
||||
9. **Commit, deploy, verify, in that order, same session.** A change that is not running is not done. After deploy, verify live; green locally means nothing until prod confirms it.
|
||||
10. **Production database untouched without explicit confirmation.** `data/devplace.db` and everything under `data/` is never read or written by an agent-initiated command without the user's own written confirmation plus the `I-HAVE-CONFIRMED-PRODUCTION-DB-ACCESS` token. Disposable verification scripts use `DEVPLACE_DATABASE_URL`/`DEVPLACE_DATA_DIR` on scratch files.
|
||||
11. **No comments, no docstrings.** Code is self-documenting. No em dashes anywhere.
|
||||
12. **Forbidden patterns respected.** No `_new`/`_old`/`_temp`/`_v2`/`better_`/`my_`/`the_` names; `RedirectResponse(url=..., status_code=302)` with an integer literal; no `is_admin`-style context key colliding with a Jinja global (use `viewer_is_admin`-style names); dates shown DD/MM/YYYY via `local_dt`/`dt_ago`.
|
||||
|
||||
## 2. Tests (committed, reusable, in the mirrored tree)
|
||||
|
||||
- HTTP tests under `tests/api/<url path>/`, browser tests under `tests/e2e/<url path>/`, pure-function tests under `tests/unit/<module path>/`. Reuse `alice`/`bob`, `app_server`, `seeded_db`, `local_db`.
|
||||
- Browser rules: every `page.goto`/`wait_for_url` passes `wait_until="domcontentloaded"`; prefer `locator().wait_for(state="visible")`; scope ambiguous selectors; restore global `site_settings` flips in `try/finally`.
|
||||
- A behavior change keeps one focused failing-first test with the change, in the existing layout, using the existing fixtures. No new test framework. Throwaway probes stay out of the repo (and a `/tmp` probe never substitutes for the committed test).
|
||||
- Never weaken a failing test to obtain green; fix the product or justify the expectation change. Observe the authentic failure before the fix when safe and runnable; run the focused test after the final edit; run the broad suite once, at the end.
|
||||
|
||||
## 3. Concurrency and state-machine rigor (the four layers)
|
||||
|
||||
For any spendable resource (coins, credits, quotas), bounded state machine (levels, tiers, counters with a floor/ceiling), or read-then-write mutation reachable from more than one worker, the persisted suite is not enough. Run, in order, as disposable scripts against a temp DB (never pytest files unless also requested):
|
||||
|
||||
1. **Property checks** on every pure function over the full input domain (monotonicity, bounds, non-negativity, idempotency), iterating the real range, not spot checks.
|
||||
2. **Stateful fuzzing**: many entities, long randomized action sequences, invariants re-checked after every action (balances never negative, monotonic counters never decrease, bounds never exceeded).
|
||||
3. **Real multi-process races**: separate OS processes, never threads; production-representative state, never pre-seeded columns (NULL is not 0 in SQL, use `COALESCE`). Prove exact right-wins counts and hand-computed final totals. Fix with one atomic conditional SQL statement (`UPDATE ... WHERE <precondition>`, real driver `rowcount`), never a client-side lock.
|
||||
4. **Static analysis** beyond `py_compile`: `pyflakes`/`ruff` on every touched file.
|
||||
|
||||
Single-process races do not count. Threads do not count. Luck does not count.
|
||||
|
||||
## 4. Data layer
|
||||
|
||||
- Every insert into a soft-deletable table writes `deleted_at: None, deleted_by: None`; every read filters `deleted_at IS NULL`. Toggles revive, never duplicate; cascades share one stamp; delete authz is owner-or-admin on the endpoint; GC stays hard. New user-generated tables are classified in `REPORTABLE_TARGETS` with `resolve_object_url` and `_report_button.html`, or in `UNREPORTABLE_TABLES` with a reason (the suite enforces this).
|
||||
- `init_db` ensures the full column set of any table code filters on before creating indexes; new columns go through the ensure idiom plus the born-live pair, never bare DDL that misses pre-existing tables.
|
||||
- Bounded, indexed reads: window functions over full-table loads, batch helpers over N+1, live-partial indexes built to plan without table scans. Nullable legacy columns need `COALESCE` in every precondition.
|
||||
- Migrations: `init_db` is idempotent, guarded by locks, skipped seeds stay skipped (consumers pass defaults to `get_setting`, never assume the seed ran). Consent backfills are forbidden (never fabricate consent); `terms_version` stays NULL for legacy accounts.
|
||||
- Runtime paths come only from `config.DATA_DIR` constants, never computed from scratch; blobs shard on uuid tail or hash, never the head.
|
||||
|
||||
## 5. Routing, templates, frontend
|
||||
|
||||
- Routers mirror the URL path (`routers/<path>.py`, packages aggregate with `include_router`); route guards mirror auth needs (`require_user`, `require_admin`, `require_user_api`); public pages use `get_current_user`. Mutations are POST with `data-confirm`; deletes additionally allow any admin; seniority gates (`is_senior_admin`) bind Devii too.
|
||||
- One shared `templates` instance; `nav_active` for nav state; `static_url`/`assetUrl` for every asset, never a bare `/static/` href; `dp-*` web components (no duplicates, real-button triggers inside popovers so no-JS stays correct, Escape closes); new JS reuses `Http`/`Poller`/`JobPoller`/`OptimisticAction`/`FloatingWindow`/`ScrollMemory`.
|
||||
- Server pipeline renders content for SEO (`render_content`/`render_title`, with `local_dt`/`dt_ago` for timestamps); the client pipeline is only for live content (`DOMPurify` fail-closed). Notifications use `render_title`. Emoji shortcodes come from the one map; YouTube embeds follow `embeds.py` only; emails are masked; em dashes become hyphens.
|
||||
- CSS: tokens from `variables.css` only (file-scoped `--x-*` palette block per new file, then `--color-*`/`--space-*`); `--z-*` bands; closed breakpoints; `prefers-reduced-motion` disables animation; no literals, no `var()` fallbacks, one radius per element, matching dark theme on first paint.
|
||||
- Admin pages conform to `devplacepy/routers/admin/CLAUDE.md` (A1-A11): server-rendered first paint, one builder for HTML and `/data`, `respond()` with an `*Out` model, `admin-*` classes, `local_dt`, capped lists, `Poller`, the `ADMIN_SECTIONS` registry; `tests/unit/admin_spec.py` passes.
|
||||
|
||||
## 6. Services and jobs
|
||||
|
||||
- Background services run only in the lock owner, supervised with health checks and lock files; a new `JobService` needs a server restart and registers its kind. The DB row is the queue; retention is built in; cleanup decisions are per-kind and deliberate (disposable archive vs permanent artifact).
|
||||
- Services report state through the one live-view relay row, audit through `record`/`record_system` with catalogued `events.md` keys (never raising into the caller), and telegram/push delivery never invents new channels. New websockets get their own nginx upgrade `location` above `location /`.
|
||||
- New dependencies are unpinned only by deliberate exception; outbound HTTP goes through stealth with `net_guard` where untrusted; feature code never blocks the event loop (gateway-adjacent sync calls run in `to_thread`).
|
||||
|
||||
## 7. AI, Devii, and money
|
||||
|
||||
- The gateway is the single point of truth for AI: every consumer points at it, keys fall back to the internal key, spend is attributed and metered, financial figures are admin-only everywhere. Consent (`ai_third_party`) gates user-content calls at exactly one place; structured internal callers may bypass the operator preamble, conversational ones never do.
|
||||
- Devii: every gated tool declares a `confirm` boolean (`additionalProperties: false` makes a gateless confirm fatal); classifier recall beats precision; budget-bounded tools with fail-closed redaction; lessons carry provenance and are never auto-applied from third-party content; channels stay isolated; self-dial uses the real origin URL.
|
||||
- Economy and scoring invariants hold exactly: one pure function per number, atomic transitions only, recomputation beats counters, races proven with real processes (see section 3).
|
||||
|
||||
## 8. Done means
|
||||
|
||||
- [ ] Minimal diff, no unrelated edits; new files only with a home.
|
||||
- [ ] One choke point reused; spec/registry updated; four faces stated.
|
||||
- [ ] Import gate + `pyflakes`/`ruff` clean; per-language manual checks done.
|
||||
- [ ] Committed reusable tests added/updated in the mirrored tree; focused failure observed before, passing after.
|
||||
- [ ] Section 3 layers run where applicable (spendable resource, bounded state machine, multi-worker mutation).
|
||||
- [ ] `make test` fully green; no tier skipped, no test narrowed or rewritten to fit.
|
||||
- [ ] No production data touched; scratch DBs only.
|
||||
- [ ] Docs touched where the behaviour is user-visible (`/docs` prose + `DOCS_PAGES`, `docs_api` groups, `events.md`, nested `CLAUDE.md` notes).
|
||||
- [ ] Committed, deployed, verified live, same session.
|
||||
@@ -351,13 +351,20 @@ accepts three header-based methods, resolved centrally in `get_current_user`
|
||||
Every user has an `api_key` (a uuid7), set at signup and backfilled for existing
|
||||
users on startup (and via `devplace apikey backfill`). The key is shown on the
|
||||
profile page to its owner (and to admins for any user) with a live **Regenerate**
|
||||
button; regenerating invalidates the old key immediately. A successful JSON
|
||||
`POST /auth/login` or `POST /auth/signup` also returns the account's `email`,
|
||||
`api_key`, and `is_admin` flag, and `GET /profile/{username}` as JSON reports
|
||||
`profile_is_admin` plus the key (null unless the viewer owns the profile or is
|
||||
an admin). Invalid credentials return `401`; requests with no credentials behave
|
||||
as anonymous (browser redirect to login). Full details and copy-paste `curl`
|
||||
examples live at `/docs/authentication.html`.
|
||||
button; regenerating invalidates the old key immediately. The three account
|
||||
credentials are username+password, email+password, and the personal API key: the
|
||||
login form, JSON `POST /auth/login`, `POST /auth/token`, and HTTP Basic all accept
|
||||
the username or the email address as the password identifier (usernames are
|
||||
case-sensitive, email addresses are not), and clients conventionally carry the API
|
||||
key in the `DEVPLACE_API_KEY` environment variable. Every JSON response that returns
|
||||
the personal API key returns the account's `username` and `email` alongside it:
|
||||
login/signup (`data`), `POST /profile/regenerate-api-key`, and the profile JSON
|
||||
(`profile_user.username`, `email`, `api_key`; key and email null unless the viewer
|
||||
owns the profile or is an admin). So a client holding only an API key fetches its
|
||||
account in one call: `GET /profile` with `X-API-KEY` and `Accept: application/json`.
|
||||
Invalid credentials return `401`; requests with no credentials behave as anonymous
|
||||
(browser redirect to login). Full details and copy-paste `curl` examples live at
|
||||
`/docs/authentication.html`.
|
||||
|
||||
```bash
|
||||
curl -H "X-API-KEY: <your-key>" https://your-host/notifications
|
||||
@@ -526,7 +533,7 @@ and its full configuration are documented automatically - including future servi
|
||||
- **`ServiceManager`** - singleton: `register`, `describe_all`, `set_enabled`, `send_command`, `save_config`, `supervise`, `shutdown_all`
|
||||
- **`NewsService`** - a fully automatic, zero-maintenance news pipeline: fetches news from `news.app.molodetz.nl/api`, cleans each article, fetches and perceptually compares the images to reject placeholders and detect uniqueness, grades each one against a free, local, deterministic quality model (aquality - no billed LLM call, no API key), optionally reformats articles that clear the publish grade threshold into clean Markdown with a generative AI model (off by default, since the default grading model cannot generate text), and auto-rotates the best articles to Featured and the landing page. Any AI spend it does incur is metered from the gateway response headers and reported on the admin Services page (calls, tokens, total cost, and per-call averages)
|
||||
- **`BotsService`** - Playwright fleet of AI personas that browse and interact with a DevPlace instance, with live cost/usage metrics and a live screenshot monitor at `/admin/bots` (opt-in; install the `bots` extra)
|
||||
- **`GatewayService`** - OpenAI-compatible LLM gateway at `/openai/v1/*`, forwarding to DeepSeek (default) with optional vision augmentation; the single point of truth for AI that every other service routes through (enabled by default). Every chat request is made date-aware by injecting the current date in EU `DD/MM/YYYY` format into the system message when it contains no date already (date only, never time, to keep upstream prompt caching effective), and an admin-configurable system preamble (`gateway_system_preamble`) can be prepended ahead of the client's system message on every call. **Thinking is disabled by default** on every chat and vision call (`thinking.type=disabled` on DeepSeek, `reasoning.effort=none` on OpenRouter, `think=false` on Ollama) so the fast path is the default; a client may re-enable it per request, and an administrator may flip `gateway_thinking` on. **Provider and model routing** (admin **Gateway** page, `/admin/gateway`) maps any number of requested model names onto named upstream providers and target models, each with its own pricing economy (input, output and cache-hit/cache-miss rates per million tokens) and an optional vision model that describes image content before forwarding, so text and vision models are merged transparently. Unmapped requests fall through to the default upstream unchanged, so existing clients are unaffected. Each route may also name a **fallback model** - another already-configured model of the same kind, picked from a select box of the public model names (never a free-text provider model id) - that the gateway retries once, automatically, whenever the primary model fails after its own retries are exhausted, so a struggling model degrades to a working one instead of failing the caller
|
||||
- **`GatewayService`** - OpenAI-compatible LLM gateway at `/openai/v1/*`, forwarding to DeepSeek (default) with optional vision augmentation; the single point of truth for AI that every other service routes through (enabled by default). Every chat request is made date-aware by injecting the current date in EU `DD/MM/YYYY` format into the system message when it contains no date already (date only, never time, to keep upstream prompt caching effective), and an admin-configurable system preamble (`gateway_system_preamble`) can be prepended ahead of the client's system message on every call. **Thinking is disabled by default** on every chat and vision call (`thinking.type=disabled` on DeepSeek, `reasoning.effort=none` on OpenRouter, `think=false` on Ollama) so the fast path is the default; a client may re-enable it per request, and an administrator may flip `gateway_thinking` on. **Provider and model routing** (admin **Gateway** page, `/admin/gateway`) maps any number of requested model names onto named upstream providers and target models, each with its own pricing economy (input, output and cache-hit/cache-miss rates per million tokens) and an optional vision model that describes image content before forwarding, so text and vision models are merged transparently. Unmapped requests fall through to the default upstream unchanged, so existing clients are unaffected. Each route may also name a **fallback model** - another already-configured model of the same kind, picked from a select box of the public model names (never a free-text provider model id) - that the gateway retries once, automatically, whenever the primary model fails after its own retries are exhausted, so a struggling model degrades to a working one instead of failing the caller. When an upstream rejects a request key with a parsable unrecognized-key 400 (for example a strict-schema provider refusing the `thinking` field), the gateway automatically tries other request shapes, remembers the one that works per provider and target model, and applies it from then on; administrators see it as a `shape:` badge on the model grid with a Reset learned action
|
||||
- **`JobService` / `ZipService` / `ForkService`** - generic async job framework (`services/jobs/`) for heavy, blocking work run off the request path; `ZipService` builds project zip archives in a subprocess, `ForkService` copies a project into a new project owned by the forking user
|
||||
- **`ContainerService`** - the admin container manager (`services/containers/`): a reconciling supervisor for container instances, all running one shared prebuilt image
|
||||
- **`AcceptanceService`** - grants every policy agreement (Terms of Service, Privacy Policy, third-party AI processing, activity recording, container credentials) to every account that has not declined it, so an instance kept production-identical for extended manual testing never interrupts with an acceptance dialog. Administrator-only, **off by default**, with a separate switch per agreement type and a dry run that reports what it would do without writing. An account that withdrew a consent is never granted it again, with no further action: the consent ledger itself is the decline register. It is not appropriate on a real production host
|
||||
@@ -767,6 +774,7 @@ Configuration on the Services tab:
|
||||
| `gateway_rsearch_cost_per_call` | 0.0 | Flat cost attributed to each external `rsearch` call (web search / AI answer / chat / image describe), recorded under backend `rsearch` so external AI spend appears in AI usage |
|
||||
| `gateway_max_retries` / `gateway_retry_backoff_ms` | 2 / 250 | Retry attempts and linear backoff on timeout, connection error, or upstream 5xx |
|
||||
| `gateway_circuit_threshold` / `gateway_circuit_cooldown_seconds` | 5 / 30 | Consecutive failures before the circuit breaker opens, and its cooldown |
|
||||
| `gateway_target_circuit_enabled` | on | Per-model circuit breaker: one upstream error opens it for the cooldown and notifies every admin with the error details |
|
||||
| `gateway_usage_retention_hours` | 720 | How long per-call usage rows are kept before pruning (30 days) |
|
||||
| `gateway_model_context_map` | JSON map | Model to max-context-tokens map for context-window utilization tracking |
|
||||
|
||||
@@ -791,7 +799,7 @@ token usage with averages and percentiles (p50/p90/p95/p99), latency (upstream r
|
||||
gateway overhead, semaphore queue wait, connection establishment), error rates by category,
|
||||
cost (per model, per caller, input vs output, projected monthly burn, caching savings),
|
||||
caller behavior, and an hourly breakdown - divided and combined. The gateway also retries
|
||||
transient upstream failures and opens a circuit breaker after repeated failures. Time to
|
||||
transient upstream failures, opens a circuit breaker after repeated failures, and opens a per-model breaker on the first error of a model and notifies every admin. Time to
|
||||
first token and inter-token latency are not reported because the gateway forwards
|
||||
non-streaming to the upstream.
|
||||
|
||||
@@ -1067,7 +1075,9 @@ in real time, bridged onto the in-process pub/sub bus by a lock-owner relay:
|
||||
| Issue-tracker update | reporter / admins |
|
||||
|
||||
`create_notification` schedules delivery as a fire-and-forget async task, so a dead
|
||||
subscription or push-service error never blocks the triggering request. Delivery
|
||||
subscription or push-service error never blocks the triggering request. The payload carries the recipient's unread count (`unread`, the same number as
|
||||
`/notifications/counts`), which APNs presents as `aps.badge` so the app icon updates even
|
||||
while the app is closed. Delivery
|
||||
(`push.notify_user`) reads a user's subscriptions once, groups them by provider, builds
|
||||
each provider's payload once, and sends over that provider's own HTTP client (stealth for
|
||||
Web Push, a dedicated HTTP/2 client for APNs). A subscription the push service reports as
|
||||
@@ -1126,8 +1136,8 @@ every page load. `PushManager.js` owns registration, subscription, and the opt-i
|
||||
|
||||
`manifest.json` (192/512 and maskable icons) and `service-worker.js` make the app
|
||||
installable via the browser's native install affordance. The service worker uses a
|
||||
network-first strategy for navigations and falls back to `static/offline.html` when
|
||||
offline. Installation requires a secure origin (HTTPS, or `localhost` for development).
|
||||
network-first strategy for navigations, retries a failed navigation once, and falls
|
||||
back to `static/offline.html` when both attempts fail. Installation requires a secure origin (HTTPS, or `localhost` for development).
|
||||
|
||||
| File | Role |
|
||||
|------|------|
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AdminSection:
|
||||
key: str
|
||||
label: str
|
||||
href: str
|
||||
icon: str
|
||||
|
||||
|
||||
ADMIN_SECTIONS: tuple[AdminSection, ...] = (
|
||||
AdminSection("users", "Users", "/admin/users", "\U0001f465"),
|
||||
AdminSection("news", "News", "/admin/news", "\U0001f4f0"),
|
||||
AdminSection("media", "Media", "/admin/media", "\U0001f5bc️"),
|
||||
AdminSection("moderation", "Moderation", "/admin/moderation", "\U0001f6a9"),
|
||||
AdminSection("trash", "Trash", "/admin/trash", "\U0001f5d1️"),
|
||||
AdminSection("services", "Services", "/admin/services", "⚙️"),
|
||||
AdminSection("gateway", "Gateway", "/admin/gateway", "\U0001f500"),
|
||||
AdminSection("containers", "Containers", "/admin/containers", "\U0001f4e6"),
|
||||
AdminSection("workspaces", "Workspaces", "/admin/workspaces", "\U0001f4bb"),
|
||||
AdminSection("devii-tasks", "Devii tasks", "/admin/devii-tasks", "⏰"),
|
||||
AdminSection("communities", "Communities", "/admin/communities", "\U0001f310"),
|
||||
AdminSection("nodes", "Community nodes", "/admin/nodes", "\U0001f4e1"),
|
||||
AdminSection("bots", "Bot Monitor", "/admin/bots", "\U0001f916"),
|
||||
AdminSection("game", "Code Farm", "/admin/game", "\U0001f69c"),
|
||||
AdminSection("ai-usage", "AI usage", "/admin/ai-usage", "\U0001f4ca"),
|
||||
AdminSection("statistics", "Statistics", "/admin/statistics", "\U0001f4c8"),
|
||||
AdminSection("audit-log", "Audit Log", "/admin/audit-log", "\U0001f4cb"),
|
||||
AdminSection("backups", "Backups", "/admin/backups", "\U0001f4be"),
|
||||
AdminSection("issues", "Ticket Planning", "/admin/issues/planning", "\U0001f5c2️"),
|
||||
AdminSection("notifications", "Notifications", "/admin/notifications", "\U0001f514"),
|
||||
AdminSection("settings", "Settings", "/admin/settings", "\U0001f527"),
|
||||
)
|
||||
|
||||
ADMIN_SECTION_KEYS: frozenset[str] = frozenset(section.key for section in ADMIN_SECTIONS)
|
||||
@@ -129,6 +129,35 @@ def can_view_target(target_type: str, target_uid: str, user: dict | None) -> boo
|
||||
return can_view_item(table_name, item, user)
|
||||
|
||||
|
||||
def can_discover_target(target_type: str, target_uid: str, user: dict | None) -> bool:
|
||||
table_name = TARGET_TABLES.get(target_type)
|
||||
if not table_name:
|
||||
return True
|
||||
item = resolve_by_slug(get_table(table_name), target_uid)
|
||||
if not item:
|
||||
return True
|
||||
if is_listed(table_name, item):
|
||||
return True
|
||||
return bool(user and (item.get("user_uid") == user.get("uid") or is_admin(user)))
|
||||
|
||||
|
||||
def discoverable_target_rows(rows: list, user: dict | None) -> list:
|
||||
memo: dict[tuple[str, str], bool] = {}
|
||||
kept = []
|
||||
for row in rows:
|
||||
if user and row.get("user_uid") == user.get("uid"):
|
||||
kept.append(row)
|
||||
continue
|
||||
target_type = row.get("target_type") or "post"
|
||||
target_uid = row.get("target_uid") or row.get("post_uid") or ""
|
||||
key = (target_type, target_uid)
|
||||
if key not in memo:
|
||||
memo[key] = can_discover_target(target_type, target_uid, user)
|
||||
if memo[key]:
|
||||
kept.append(row)
|
||||
return kept
|
||||
|
||||
|
||||
def mature_hidden_by_default() -> bool:
|
||||
return get_int_setting("moderation_mature_default_hidden", 1) != 0
|
||||
|
||||
|
||||
@@ -260,8 +260,17 @@ Posts, gists, projects and news carry one status from `VISIBILITY_VALUES`: `publ
|
||||
|
||||
- **Column.** `VISIBILITY_COLUMNS = {posts, gists, projects: "visibility", news: "status"}`. News reuses its existing `status` column (it already held `published`/`draft`), so no news migration exists. `ensure_visibility_columns()` (called from `init_db`) adds the text column and `idx_<table>_visibility` ONLY to tables that already exist; it must never create the table (an empty `posts` table breaks every `"posts" in db.tables` guard and the first-signup schema). A NULL or unknown value reads as `published` everywhere (`normalize_visibility`, `item_visibility`), so legacy rows needed no backfill and `init_db` does no per-row work.
|
||||
- **Every read goes through one of three choke points, never an inline compare.** `paginate`/`paginate_diverse` auto-append `listed_clause(table)` for any table in `VISIBILITY_COLUMNS` (`include_unlisted_of=<uid>` ORs in that owner's own rows, used for an owner's own profile/listing); `listed_clause(table, own_uid)` for `count()`/`find()` call sites; `listed_sql(table, alias)` for raw SQL (it returns `1 = 1` when the table or column does not exist yet, so a fresh database never errors). The predicates `is_listed`/`is_open` work on a row dict. Single-item access is `content.can_view_item(table, item, user)` (open, or owner, or admin) and `content.can_view_target(target_type, uid, user)` for polymorphic targets; `load_detail` applies the first, so every detail page 404s without per-route code. `can_view_project` composes visibility first, then the `is_private` rule.
|
||||
- **Discoverability vs openness (hard rule).** A `hidden` link is the secret, so any surface that lists a user's activity must not expose it. `content.can_discover_target` / `discoverable_target_rows(rows, viewer)` keep a row only when its target is listed, or the viewer owns the target, is an administrator, or authored the row; the profile Activity tab and the devRant profile comments use it. Opinion Wars follow their post: `store._list_clauses` restricts `/battles` to wars whose post is listed (own posts and admins excepted), and every `/battles/{uid}` route 404s through `can_view_target` (`routers/battles._viewable_war`). Tests: `tests/api/content/visibility.py`.
|
||||
- **Writes.** `content.apply_visibility` is the one writer (column update, cache invalidation, `<kind>.visibility.set` audit with old/new value). `edit_content_item` pops the optional `visibility` form field and calls `apply_visibility` when it changed; `content.set_visibility_item` exists only for the administrator news route (news has no edit form). `create_content_item` stamps the column (`_with_visibility`) and skips mention notifications for non-open items.
|
||||
- **Public counters** (`get_user_post_count`, `get_site_stats`, `get_post_counts_by_user_uids`, trending topics, topic hub counts, sitemap author counts, happy-404 pool) count listed rows only, so the owner's own profile count excludes their hidden and offline posts.
|
||||
- **Backwards compatibility (hard rule).** `visibility` is optional on every API: `VisibilityCreateMixin` defaults to `published`, `VisibilityEditMixin` defaults to `None` meaning keep the current value (never reset to published), NULL rows read as published, and the docs/Devii parameter descriptions say so (`tests/unit/docs_api/visibility.py`, `tests/api/content/visibility.py` legacy-client tests). Never make the field required.
|
||||
- **Outputs.** `VisibleOut` (`schemas/content.py`) gives `PostOut`/`GistOut`/`ProjectOut` a `visibility` that reads NULL as `published`. Forms use `VisibilityCreateMixin` (default `published`) and `VisibilityEditMixin` (`None` keeps the current value); `VisibilityForm{value}` backs the admin news route.
|
||||
- **Adding a table.** Put it in `VISIBILITY_COLUMNS` and `TARGET_TABLES`, add its form mixin and Out base, apply `listed_clause`/`listed_sql` to each new read, and extend `tests/api/content/visibility.py`. `tests/unit/database/visibility.py` asserts the spec is self-consistent.
|
||||
|
||||
## Notification grouping, throttling and keyboard settings
|
||||
|
||||
`users` carries `enter_to_submit`, `notif_grouping_enabled` and `notif_throttle_enabled` (all default 1, ensured in `schema.py`, owner-or-admin toggles on the profile page).
|
||||
|
||||
## Data CLI
|
||||
|
||||
`devplace apikey backfill` assigns keys to users that lack one. `devplace attachments prune` removes orphan attachment records/files. `devplace system prune` (with `--dry-run`) purges soft-deleted attachment/project-file blobs, sweeps blob files with zero DB reference, and GCs orphaned container workspace dirs. `database/notifications.py` owns the single grouping specification: `NOTIFICATION_GROUP_KEYS` (actor / target / single per type, unlisted types are single), `notification_group_key(row)`, and `count_unread_groups(user_uid)` (groups when enabled, rows when off). Every badge producer calls `count_unread_groups`; none counts rows itself. The push payload (`unread`, presented as `aps.badge`) is one of them. The `notifications` column set is ensured in `init_db` like `messages` (listed in `tests/unit/database/schema.py` `FILTERED_COLUMNS`), and the unread read `find(user_uid=..., read=False)` is served by `idx_notifications_user_read (user_uid, read)`. Delivery throttling (item 5) reuses the same key.
|
||||
|
||||
@@ -32,7 +32,8 @@ from .seo_meta import SEO_META_TYPES, get_seo_metadata, get_seo_metadata_batch,
|
||||
from .activity import record_activity, record_unique_activity, get_user_activity, _activity_cache, _ACTIVITY_TABLES, get_activity_calendar, _activity_level, get_first_activity_date, HEATMAP_WEEKS, get_activity_heatmap, get_activity_months, get_streaks
|
||||
from .customization import CUSTOMIZATION_GLOBAL_SCOPE, CUSTOMIZATION_LANGS, _customizations_cache, _customization_key, CUSTOMIZATION_PREF_COLUMNS, get_customization_prefs, set_customization_pref, get_custom_overrides, get_custom_override, list_custom_overrides, set_custom_override, delete_custom_override
|
||||
from .email import EMAIL_ACCOUNT_DEFAULTS, list_email_accounts, get_email_account, set_email_account, delete_email_account
|
||||
from .notifications import NOTIFICATION_TYPES, NOTIFICATION_CHANNELS, _NOTIFICATION_CHANNEL_COLUMNS, _NOTIFICATION_CHANNEL_DEFAULTS, _NOTIFICATION_TYPE_KEYS, _notification_prefs_cache, _notification_default, get_notification_default, set_notification_default, _notification_overrides, notification_enabled, get_notification_prefs, set_notification_pref, reset_notification_prefs, mark_notifications_read_by_target
|
||||
from .notifications import NOTIFICATION_TYPES, NOTIFICATION_CHANNELS, _NOTIFICATION_CHANNEL_COLUMNS, _NOTIFICATION_CHANNEL_DEFAULTS, _NOTIFICATION_TYPE_KEYS, _notification_prefs_cache, _notification_default, get_notification_default, set_notification_default, _notification_overrides, notification_enabled, get_notification_prefs, set_notification_pref, reset_notification_prefs, mark_notifications_read_by_target, NOTIFICATION_GROUP_KEYS, notification_group_key, notification_throttle_key, get_notification_grouping_enabled, set_notification_grouping_enabled, get_notification_throttle_enabled, set_notification_throttle_enabled, count_unread_groups
|
||||
from .enter_submit import get_enter_to_submit, set_enter_to_submit
|
||||
from .forks import record_fork, get_fork_parent, count_forks, soft_delete_fork_relations, delete_fork_relations
|
||||
from .follows import get_follow_counts, get_follow_list, get_following_among
|
||||
from .deepsearch import _ds_now, create_deepsearch_session, update_deepsearch_session, get_deepsearch_session, list_deepsearch_sessions, add_deepsearch_message, get_deepsearch_messages, get_cached_deepsearch_url, upsert_deepsearch_url_cache
|
||||
@@ -251,6 +252,16 @@ __all__ = [
|
||||
"set_notification_pref",
|
||||
"reset_notification_prefs",
|
||||
"mark_notifications_read_by_target",
|
||||
"NOTIFICATION_GROUP_KEYS",
|
||||
"notification_group_key",
|
||||
"notification_throttle_key",
|
||||
"get_notification_grouping_enabled",
|
||||
"set_notification_grouping_enabled",
|
||||
"get_notification_throttle_enabled",
|
||||
"set_notification_throttle_enabled",
|
||||
"count_unread_groups",
|
||||
"get_enter_to_submit",
|
||||
"set_enter_to_submit",
|
||||
"record_fork",
|
||||
"get_fork_parent",
|
||||
"count_forks",
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from .core import db, get_table
|
||||
|
||||
|
||||
def get_enter_to_submit(owner_id: str) -> bool:
|
||||
if "users" not in db.tables:
|
||||
return True
|
||||
user = db["users"].find_one(uid=owner_id)
|
||||
if user is None:
|
||||
return True
|
||||
value = user.get("enter_to_submit")
|
||||
return True if value is None else bool(value)
|
||||
|
||||
|
||||
def set_enter_to_submit(owner_id: str, enabled: bool) -> None:
|
||||
from devplacepy.utils import clear_user_cache
|
||||
|
||||
get_table("users").update(
|
||||
{"uid": owner_id, "enter_to_submit": 1 if enabled else 0}, ["uid"]
|
||||
)
|
||||
clear_user_cache(owner_id)
|
||||
@@ -64,6 +64,7 @@ UNREPORTABLE_TABLES: dict[str, str] = {
|
||||
"quiz_answers": "private to the participant",
|
||||
"sessions": "authentication state",
|
||||
"access_tokens": "authentication state",
|
||||
"mcp_tokens": "authentication state",
|
||||
"devrant_tokens": "authentication state",
|
||||
"user_relations": "private block and mute lists",
|
||||
"notification_preferences": "private to the owner",
|
||||
|
||||
@@ -592,14 +592,23 @@ def raise_flag(kind: str, *, device_uid: str = "", user_uid: str = "", detail: s
|
||||
return table.find_one(uid=uid)
|
||||
|
||||
|
||||
def list_flags(status: str = FLAG_OPEN) -> list[dict]:
|
||||
def list_flags(status: str = FLAG_OPEN, limit: int | None = None) -> list[dict]:
|
||||
window = {} if limit is None else {"_limit": limit}
|
||||
return list(
|
||||
get_table("node_flags").find(
|
||||
status=status, deleted_at=None, order_by=["-created_at"]
|
||||
status=status, deleted_at=None, order_by=["-created_at"], **window
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def count_flags(status: str = FLAG_OPEN) -> int:
|
||||
return get_table("node_flags").count(status=status, deleted_at=None)
|
||||
|
||||
|
||||
def count_all_devices() -> int:
|
||||
return get_table("node_devices").count(deleted_at=None)
|
||||
|
||||
|
||||
def resolve_flag(flag_uid: str, actor_uid: str) -> bool:
|
||||
return (
|
||||
_execute(
|
||||
|
||||
@@ -204,3 +204,87 @@ def mark_notifications_read_by_target(user_uid: str, target_url: str) -> int:
|
||||
|
||||
clear_unread_cache(user_uid)
|
||||
return len(ids)
|
||||
|
||||
|
||||
NOTIFICATION_GROUP_KEYS = {
|
||||
"comment": "actor",
|
||||
"reply": "actor",
|
||||
"thread": "actor",
|
||||
"mention": "actor",
|
||||
"message": "actor",
|
||||
"harvest_stolen": "actor",
|
||||
"award": "actor",
|
||||
"quiz_attempt": "actor",
|
||||
"vote": "target",
|
||||
"follow": "target",
|
||||
"badge": "single",
|
||||
"level": "single",
|
||||
"issue": "single",
|
||||
"reminder": "single",
|
||||
"battle": "single",
|
||||
"workspace": "single",
|
||||
"moderation": "single",
|
||||
"system": "single",
|
||||
"ai_quota_warning": "single",
|
||||
"game_upkeep": "single",
|
||||
}
|
||||
|
||||
|
||||
def notification_group_key(row) -> tuple:
|
||||
ntype = (row.get("type") or "")
|
||||
shape = NOTIFICATION_GROUP_KEYS.get(ntype, "single")
|
||||
if shape == "actor":
|
||||
return (ntype, row.get("related_uid") or "", row.get("target_url") or "")
|
||||
if shape == "target":
|
||||
if ntype == "follow":
|
||||
return (ntype,)
|
||||
return (ntype, row.get("target_url") or "")
|
||||
return (ntype, row.get("uid") or "")
|
||||
|
||||
|
||||
def notification_throttle_key(user_uid: str, notification_type: str, related_uid: str, target_url) -> tuple:
|
||||
row = {"type": notification_type, "related_uid": related_uid or "", "target_url": target_url or "", "uid": ""}
|
||||
return (user_uid,) + notification_group_key(row)
|
||||
|
||||
|
||||
def _user_bool_pref(user_uid: str, column: str) -> bool:
|
||||
if "users" not in db.tables:
|
||||
return True
|
||||
user = db["users"].find_one(uid=user_uid)
|
||||
if user is None:
|
||||
return True
|
||||
value = user.get(column)
|
||||
return True if value is None else bool(value)
|
||||
|
||||
|
||||
def get_notification_grouping_enabled(user_uid: str) -> bool:
|
||||
return _user_bool_pref(user_uid, "notif_grouping_enabled")
|
||||
|
||||
|
||||
def get_notification_throttle_enabled(user_uid: str) -> bool:
|
||||
return _user_bool_pref(user_uid, "notif_throttle_enabled")
|
||||
|
||||
|
||||
def _set_user_bool_pref(user_uid: str, column: str, enabled: bool) -> None:
|
||||
from devplacepy.utils import clear_user_cache
|
||||
|
||||
get_table("users").update({"uid": user_uid, column: 1 if enabled else 0}, ["uid"])
|
||||
clear_user_cache(user_uid)
|
||||
bump_cache_version("notif_prefs")
|
||||
|
||||
|
||||
def set_notification_grouping_enabled(user_uid: str, enabled: bool) -> None:
|
||||
_set_user_bool_pref(user_uid, "notif_grouping_enabled", enabled)
|
||||
|
||||
|
||||
def set_notification_throttle_enabled(user_uid: str, enabled: bool) -> None:
|
||||
_set_user_bool_pref(user_uid, "notif_throttle_enabled", enabled)
|
||||
|
||||
|
||||
def count_unread_groups(user_uid: str) -> int:
|
||||
if "notifications" not in db.tables:
|
||||
return 0
|
||||
rows = list(get_table("notifications").find(user_uid=user_uid, read=False))
|
||||
if not get_notification_grouping_enabled(user_uid):
|
||||
return len(rows)
|
||||
return len({notification_group_key(row) for row in rows})
|
||||
|
||||
@@ -126,6 +126,19 @@ def init_db():
|
||||
access_tokens.create_column_by_example(column, example)
|
||||
_index(db, "access_tokens", "idx_access_tokens_token", ["token"])
|
||||
_index(db, "access_tokens", "idx_access_tokens_user", ["user_uid"])
|
||||
if "mcp_tokens" in tables:
|
||||
mcp_tokens = get_table("mcp_tokens")
|
||||
for column, example in (
|
||||
("uid", ""),
|
||||
("token", ""),
|
||||
("user_uid", ""),
|
||||
("label", ""),
|
||||
("created_at", ""),
|
||||
):
|
||||
if not mcp_tokens.has_column(column):
|
||||
mcp_tokens.create_column_by_example(column, example)
|
||||
_index(db, "mcp_tokens", "idx_mcp_tokens_token", ["token"], unique=True)
|
||||
_index(db, "mcp_tokens", "idx_mcp_tokens_user", ["user_uid"])
|
||||
if "telegram_pairings" in tables:
|
||||
telegram_pairings = get_table("telegram_pairings")
|
||||
for column, example in (
|
||||
@@ -200,6 +213,19 @@ def init_db():
|
||||
)
|
||||
_index(db, "messages", "idx_messages_updated_at", ["updated_at"])
|
||||
_index(db, "messages", "idx_messages_dedupe", ["sender_uid", "client_id"])
|
||||
notifications = get_table("notifications")
|
||||
for column, example in (
|
||||
("uid", ""),
|
||||
("user_uid", ""),
|
||||
("type", ""),
|
||||
("message", ""),
|
||||
("related_uid", ""),
|
||||
("target_url", ""),
|
||||
("read", False),
|
||||
("created_at", ""),
|
||||
):
|
||||
if not notifications.has_column(column):
|
||||
notifications.create_column_by_example(column, example)
|
||||
_index(db, "notifications", "idx_notifications_user", ["user_uid"])
|
||||
_index(db, "notifications", "idx_notifications_user_read", ["user_uid", "read"])
|
||||
push_registration = get_table("push_registration")
|
||||
@@ -685,6 +711,7 @@ def init_db():
|
||||
("inter_token_ms", 0.0),
|
||||
("provider", ""),
|
||||
("fallback_used_route", ""),
|
||||
("resolved_method", ""),
|
||||
):
|
||||
if not gateway_usage_ledger.has_column(column):
|
||||
gateway_usage_ledger.create_column_by_example(column, example)
|
||||
@@ -950,6 +977,10 @@ def init_db():
|
||||
|
||||
gateway_routing.ensure_tables()
|
||||
|
||||
from devplacepy.services.openai_gateway import learned as gateway_learned
|
||||
|
||||
gateway_learned.ensure_table()
|
||||
|
||||
from devplacepy.services.openai_gateway import quota as gateway_quota
|
||||
|
||||
gateway_quota.ensure_tables()
|
||||
@@ -2758,6 +2789,12 @@ def backfill_api_keys() -> int:
|
||||
users.create_column_by_example("cust_disable_global", 0)
|
||||
if not users.has_column("cust_disable_pagetype"):
|
||||
users.create_column_by_example("cust_disable_pagetype", 0)
|
||||
if not users.has_column("enter_to_submit"):
|
||||
users.create_column_by_example("enter_to_submit", 1)
|
||||
if not users.has_column("notif_grouping_enabled"):
|
||||
users.create_column_by_example("notif_grouping_enabled", 1)
|
||||
if not users.has_column("notif_throttle_enabled"):
|
||||
users.create_column_by_example("notif_throttle_enabled", 1)
|
||||
if not users.has_column("ai_correction_enabled"):
|
||||
users.create_column_by_example("ai_correction_enabled", 0)
|
||||
if not users.has_column("ai_correction_prompt"):
|
||||
|
||||
@@ -52,6 +52,7 @@ SOFT_DELETE_TABLES = [
|
||||
"isslop_analyses",
|
||||
"devrant_tokens",
|
||||
"access_tokens",
|
||||
"mcp_tokens",
|
||||
"email_accounts",
|
||||
"user_relations",
|
||||
"seo_metadata",
|
||||
|
||||
@@ -796,6 +796,49 @@ four ways to sign requests.
|
||||
field("app_reference", "json", "string", False, "typosaurus", "App label (the X-App-Reference header). Blank = every app."),
|
||||
],
|
||||
),
|
||||
endpoint(
|
||||
id="admin-gateway-learned",
|
||||
method="GET",
|
||||
path="/admin/gateway/learned",
|
||||
title="List learned gateway request shapes",
|
||||
summary=(
|
||||
"Every request shape the gateway learned automatically after an upstream rejected the "
|
||||
"default one with an unrecognized-key 400, per provider and target model, plus the "
|
||||
"resolved/exhausted/healed counters."
|
||||
),
|
||||
auth="admin",
|
||||
sample_response={
|
||||
"learned": [
|
||||
{
|
||||
"provider": "vaids",
|
||||
"target_model": "deepseek-v4-1-flash-1017-uncensored",
|
||||
"method": "none",
|
||||
"thinking_dialect": "none",
|
||||
"drop_keys": [],
|
||||
"learned_at": "2026-11-13T00:55:00+00:00",
|
||||
}
|
||||
],
|
||||
"count": 1,
|
||||
"stats": {"resolved": 1, "exhausted": 0, "healed": 0},
|
||||
},
|
||||
),
|
||||
endpoint(
|
||||
id="admin-gateway-learned-reset",
|
||||
method="POST",
|
||||
path="/admin/gateway/learned/reset",
|
||||
title="Reset a learned gateway request shape",
|
||||
summary=(
|
||||
"Forget the learned method for one provider and target model so the gateway starts from "
|
||||
"the default shape again. Use provider 'default' for the base upstream."
|
||||
),
|
||||
auth="admin",
|
||||
destructive=True,
|
||||
params=[
|
||||
field("provider", "json", "string", False, "vaids", "Provider name, or default."),
|
||||
field("target_model", "json", "string", True, "deepseek-v4-1-flash-1017-uncensored", "Upstream target model."),
|
||||
],
|
||||
sample_response={"ok": True},
|
||||
),
|
||||
endpoint(
|
||||
id="admin-gateway-quota-rule-delete",
|
||||
method="DELETE",
|
||||
|
||||
@@ -23,8 +23,10 @@ The POST endpoints are **actions**: they accept form fields, set or clear the `s
|
||||
and return a `302` redirect (or the JSON envelope for JSON callers).
|
||||
|
||||
**Sign-up requires a unique `username` and `email`** plus a `confirm_password` that matches the
|
||||
password; **you log in with your `email` and password**. JSON callers receive validation errors
|
||||
as a `422` with the shape `{ "fields": {...}, "messages": [...] }`.
|
||||
password; **you log in with your `username` or your `email`, plus your password** (the `email`
|
||||
field accepts either identifier; usernames are case-sensitive, email addresses are not). The
|
||||
same identifier rule applies to `POST /auth/token` and HTTP Basic. JSON callers receive
|
||||
validation errors as a `422` with the shape `{ "fields": {...}, "messages": [...] }`.
|
||||
""",
|
||||
"endpoints": [
|
||||
endpoint(
|
||||
@@ -89,20 +91,20 @@ as a `422` with the shape `{ "fields": {...}, "messages": [...] }`.
|
||||
method="POST",
|
||||
path="/auth/login",
|
||||
title="Log in",
|
||||
summary="Authenticate with email and password. Sets the session cookie.",
|
||||
summary="Authenticate with username (or email) and password. Sets the session cookie.",
|
||||
auth="public",
|
||||
encoding="form",
|
||||
params=[
|
||||
field("email", "form", "string", True, "alice@example.com", "Your registered email."),
|
||||
field("email", "form", "string", True, "alice@example.com", "Your username or your registered email."),
|
||||
field("password", "form", "string", True, "mysecret", "Your password."),
|
||||
field("remember_me", "form", "string", False, "on", "Send 'on' to extend the session to the remember-me lifetime."),
|
||||
field("next", "form", "string", False, "", "Redirect target after login."),
|
||||
],
|
||||
notes=[
|
||||
"JSON callers receive the account's `email`, `api_key`, and "
|
||||
"`is_admin` flag in `data`, so a script can trade one email/password "
|
||||
"login for a reusable key. Failed logins return 401 and never "
|
||||
"include the key.",
|
||||
"JSON callers receive the account's `username`, `email`, `api_key`, "
|
||||
"and `is_admin` flag in `data`, so a script can trade one "
|
||||
"username/password or email/password login for a reusable key. "
|
||||
"Failed logins return 401 and never include the key.",
|
||||
],
|
||||
sample_response={
|
||||
"ok": True,
|
||||
@@ -115,6 +117,31 @@ as a `422` with the shape `{ "fields": {...}, "messages": [...] }`.
|
||||
},
|
||||
},
|
||||
),
|
||||
endpoint(
|
||||
id="auth-token",
|
||||
method="POST",
|
||||
path="/auth/token",
|
||||
title="Issue access token",
|
||||
summary="Exchange username (or email) and password for a short-lived access token. No session cookie is set.",
|
||||
auth="public",
|
||||
encoding="form",
|
||||
params=[
|
||||
field("email", "form", "string", True, "alice@example.com", "Your username or your registered email."),
|
||||
field("password", "form", "string", True, "mysecret", "Your password."),
|
||||
],
|
||||
notes=[
|
||||
"Accepts a JSON body with the same fields. The returned token "
|
||||
"works as an `Authorization: Bearer` or `X-API-KEY` credential "
|
||||
"until it expires (default 7 days). Missing fields return 400, "
|
||||
"wrong credentials 401, a deactivated account 403; failures "
|
||||
"never include a token.",
|
||||
],
|
||||
sample_response={
|
||||
"access_token": "ACCESS_TOKEN",
|
||||
"token_type": "bearer",
|
||||
"expires_in": 604800,
|
||||
},
|
||||
),
|
||||
endpoint(
|
||||
id="auth-forgot-password",
|
||||
method="GET",
|
||||
|
||||
@@ -19,10 +19,11 @@ Every example uses your current host:
|
||||
## Authentication
|
||||
|
||||
Each endpoint is tagged **public**, **user**, or **admin**. Authenticate user and admin
|
||||
endpoints with any of the four methods in [Authentication](/docs/authentication.html): the
|
||||
`session` cookie, an `X-API-KEY` header, a `Bearer` token, or HTTP Basic credentials. The
|
||||
interactive panels on this site pre-fill your own API key, so you can run user-level calls
|
||||
immediately.
|
||||
endpoints with any of the methods in [Authentication](/docs/authentication.html): the
|
||||
`session` cookie, an `X-API-KEY` header, a `Bearer` token, or HTTP Basic credentials
|
||||
(username or email, plus password; the headers also accept native access tokens and
|
||||
DevRant auth tokens). The interactive panels on this site pre-fill your own API key, so
|
||||
you can run user-level calls immediately.
|
||||
|
||||
## Request bodies
|
||||
|
||||
|
||||
@@ -8,8 +8,7 @@ GROUP = {
|
||||
"intro": """
|
||||
# Notifications
|
||||
|
||||
Read your notification feed and mark items read. The unread counts endpoint backs the badges
|
||||
in the navigation bar. Deliver these to the browser with [Web Push](/docs/push.html).
|
||||
Read your notification feed and mark items read. With grouping on (the default, a profile setting), similar events share one entry in `event_entries` and the unread counts count groups; with it off, entries stay one per event. Repeat external alerts are throttled to one per similar event group per 5 minutes unless the user turned throttling off; in-app rows are never throttled. The unread counts endpoint backs the badges in the navigation bar. Deliver these to the browser with [Web Push](/docs/push.html).
|
||||
|
||||
Every endpoint follows the shared [Conventions & Errors](/docs/conventions.html) (auth, content
|
||||
negotiation, pagination, status codes); see [Authentication](/docs/authentication.html) for the
|
||||
|
||||
@@ -379,7 +379,11 @@ four ways to sign requests.
|
||||
"> Running this invalidates the key these documentation panels use. Do it from your "
|
||||
"[profile page](/profile/{{ username }}) instead, then reload these docs.",
|
||||
],
|
||||
sample_response={"api_key": "NEW_UUID"},
|
||||
sample_response={
|
||||
"api_key": "NEW_UUID",
|
||||
"username": "alice",
|
||||
"email": "alice@example.com",
|
||||
},
|
||||
),
|
||||
endpoint(
|
||||
id="profile-give-award",
|
||||
@@ -500,6 +504,48 @@ four ways to sign requests.
|
||||
),
|
||||
],
|
||||
),
|
||||
endpoint(
|
||||
id="profile-enter-to-submit",
|
||||
method="POST",
|
||||
path="/profile/{username}/enter-to-submit",
|
||||
title="Toggle Enter to send",
|
||||
summary="Enter posts comments and sends messages; Shift+Enter adds a new line. Admins may target any user.",
|
||||
auth="user",
|
||||
encoding="form",
|
||||
destructive=True,
|
||||
params=[
|
||||
field("username", "path", "string", True, "bob_test", "Profile owner. Must be yourself unless you are an admin."),
|
||||
field("value", "form", "boolean", False, "1", "1 for Enter to send, 0 for Enter adds a new line."),
|
||||
],
|
||||
),
|
||||
endpoint(
|
||||
id="profile-notification-grouping",
|
||||
method="POST",
|
||||
path="/profile/{username}/notifications/grouping",
|
||||
title="Toggle grouped notifications",
|
||||
summary="Group similar notifications into one card; the badge counts groups. Admins may target any user.",
|
||||
auth="user",
|
||||
encoding="form",
|
||||
destructive=True,
|
||||
params=[
|
||||
field("username", "path", "string", True, "bob_test", "Profile owner. Must be yourself unless you are an admin."),
|
||||
field("value", "form", "boolean", False, "1", "1 to group, 0 to show every event."),
|
||||
],
|
||||
),
|
||||
endpoint(
|
||||
id="profile-notification-throttling",
|
||||
method="POST",
|
||||
path="/profile/{username}/notifications/throttling",
|
||||
title="Toggle throttled repeat alerts",
|
||||
summary="At most one push, Telegram message and toast per similar event group per 5 minutes. In-app is never throttled. Admins may target any user.",
|
||||
auth="user",
|
||||
encoding="form",
|
||||
destructive=True,
|
||||
params=[
|
||||
field("username", "path", "string", True, "bob_test", "Profile owner. Must be yourself unless you are an admin."),
|
||||
field("value", "form", "boolean", False, "1", "1 to throttle repeat alerts, 0 to alert on every event."),
|
||||
],
|
||||
),
|
||||
endpoint(
|
||||
id="profile-notification-toggle",
|
||||
method="POST",
|
||||
|
||||
@@ -20,6 +20,11 @@ its build. A registration body without a `provider` field is a `webpush` registr
|
||||
existing clients need no change. An APNs body may include a stable `client_id` so a later
|
||||
token rotation updates the same device instead of inserting another row.
|
||||
|
||||
Every delivered notification carries the recipient's unread count, the same number as
|
||||
`notifications` in `GET /notifications/counts` ([Notifications](/docs/notifications.html)). `apns` presents it as `aps.badge`,
|
||||
so a native app icon updates while the app is in the background; `webpush` forwards it as the
|
||||
`unread` field of the payload.
|
||||
|
||||
`DELETE /push.json` removes a single registration by the same identity used to create it
|
||||
(`endpoint` for webpush, `token` or `client_id` for apns). The server also stops delivering to a
|
||||
subscription once its push endpoint reports it as gone. These mirror the in-app
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from devplacepy.database import (
|
||||
count_unread_groups,
|
||||
db,
|
||||
get_table,
|
||||
get_setting,
|
||||
@@ -71,7 +72,7 @@ def _user_facts(user: dict) -> dict:
|
||||
"followers": _count("follows", following_uid=uid),
|
||||
"following": _count("follows", follower_uid=uid),
|
||||
"bookmarks": _count("bookmarks", user_uid=uid),
|
||||
"unread_notifications": _count("notifications", user_uid=uid, read=False),
|
||||
"unread_notifications": count_unread_groups(uid),
|
||||
"unread_messages": _count("messages", receiver_uid=uid, read=False, deleted_at=None),
|
||||
},
|
||||
"recent_posts": [
|
||||
|
||||
@@ -44,6 +44,7 @@ from devplacepy.services.notification_relay import NotificationRelayService
|
||||
from devplacepy.services.openai_gateway import GatewayService
|
||||
from devplacepy.services.opinionwar.service import OpinionWarService
|
||||
from devplacepy.services.presence_relay import PresenceRelayService
|
||||
from devplacepy.services.project_blob_sweep import ProjectBlobSweepService
|
||||
from devplacepy.services.pubsub import PubSubService
|
||||
from devplacepy.services.push import PushService
|
||||
from devplacepy.services.telegram import TelegramService
|
||||
@@ -81,6 +82,7 @@ SERVICE_CLASSES = [
|
||||
AuditService,
|
||||
ModerationService,
|
||||
AcceptanceService,
|
||||
ProjectBlobSweepService,
|
||||
CommunityService,
|
||||
NodesService,
|
||||
PushService,
|
||||
|
||||
@@ -51,6 +51,7 @@ from devplacepy.routers import (
|
||||
docs,
|
||||
openai_gateway,
|
||||
devii,
|
||||
mcp,
|
||||
zips,
|
||||
forks,
|
||||
proxy,
|
||||
@@ -77,6 +78,15 @@ logging.getLogger("alembic.runtime.migration").setLevel(logging.WARNING)
|
||||
|
||||
app = FastAPI(
|
||||
title="DevPlace",
|
||||
description=(
|
||||
"Authentication: username+password, email+password (login form, JSON "
|
||||
"POST /auth/login, POST /auth/token, and HTTP Basic all accept the "
|
||||
"username or the email address), or the personal API key from the "
|
||||
"profile page sent as X-API-KEY or Authorization: Bearer "
|
||||
"(conventionally carried in the DEVPLACE_API_KEY environment variable). "
|
||||
"GET /profile with an API key returns the account username, email, and "
|
||||
"API key. Full reference: /docs/authentication.html"
|
||||
),
|
||||
docs_url="/swagger",
|
||||
redoc_url=None,
|
||||
openapi_url="/openapi.json",
|
||||
@@ -123,6 +133,7 @@ app.include_router(push.router)
|
||||
app.include_router(docs.router)
|
||||
app.include_router(openai_gateway.router, prefix="/openai")
|
||||
app.include_router(devii.router, prefix="/devii")
|
||||
app.include_router(mcp.router)
|
||||
app.include_router(issues.router, prefix="/issues")
|
||||
app.include_router(gists.router, prefix="/gists")
|
||||
app.include_router(news.router, prefix="/news")
|
||||
|
||||
@@ -14,6 +14,9 @@ from devplacepy.templating import templates
|
||||
from devplacepy.utils import client_ip, get_current_user
|
||||
|
||||
|
||||
RATE_LIMIT_EXEMPT_PREFIXES = ("/openai", "/xmlrpc", "/mcp")
|
||||
|
||||
|
||||
async def rate_limit_middleware(request: Request, call_next):
|
||||
if state.RATE_LIMIT_DISABLED:
|
||||
return await call_next(request)
|
||||
@@ -22,7 +25,7 @@ async def rate_limit_middleware(request: Request, call_next):
|
||||
"PUT",
|
||||
"DELETE",
|
||||
"PATCH",
|
||||
) and not request.url.path.startswith(("/openai", "/xmlrpc")):
|
||||
) and not request.url.path.startswith(RATE_LIMIT_EXEMPT_PREFIXES):
|
||||
settings = state._hot_settings()
|
||||
limit = state._worker_rate_limit(settings["rate_limit_per_minute"])
|
||||
window = settings["rate_limit_window_seconds"]
|
||||
@@ -57,7 +60,16 @@ async def rate_limit_middleware(request: Request, call_next):
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
_MAINTENANCE_ALLOWED_PREFIXES = ("/static", "/avatar", "/auth", "/admin", "/openai")
|
||||
# /mcp stays up in maintenance mode, consistent with /openai: token holders
|
||||
# keep their harness access while page POSTs are gated for non-admins.
|
||||
_MAINTENANCE_ALLOWED_PREFIXES = (
|
||||
"/static",
|
||||
"/avatar",
|
||||
"/auth",
|
||||
"/admin",
|
||||
"/openai",
|
||||
"/mcp",
|
||||
)
|
||||
|
||||
|
||||
async def maintenance_middleware(request: Request, call_next):
|
||||
|
||||
@@ -44,6 +44,7 @@ from devplacepy.models.projects import (
|
||||
)
|
||||
from devplacepy.models.profile import (
|
||||
CustomizationToggleForm,
|
||||
EnterToSubmitForm,
|
||||
AwardGiveForm,
|
||||
NotificationPrefForm,
|
||||
AiCorrectionForm,
|
||||
@@ -195,6 +196,7 @@ __all__ = [
|
||||
"ProjectFileDeleteLinesForm",
|
||||
"ProjectFileAppendForm",
|
||||
"CustomizationToggleForm",
|
||||
"EnterToSubmitForm",
|
||||
"AwardGiveForm",
|
||||
"NotificationPrefForm",
|
||||
"AiCorrectionForm",
|
||||
|
||||
@@ -12,6 +12,10 @@ class CustomizationToggleForm(BaseModel):
|
||||
value: bool = False
|
||||
|
||||
|
||||
class EnterToSubmitForm(BaseModel):
|
||||
value: bool = True
|
||||
|
||||
|
||||
class AwardGiveForm(BaseModel):
|
||||
description: str = Field(min_length=1, max_length=125)
|
||||
|
||||
|
||||
+109
-46
@@ -21,6 +21,9 @@ MAX_SEGMENT_LENGTH = 255
|
||||
MAX_DEPTH = 32
|
||||
_MISSING_BLOB_LOG_SECONDS = 60
|
||||
_missing_blob_logged: dict[str, tuple[int, float]] = {}
|
||||
MISSING_BLOB_RETRY_SECONDS = 600
|
||||
MISSING_BLOB_MAX_TRACKED = 10000
|
||||
_missing_blob_until: dict[tuple[str, str], float] = {}
|
||||
|
||||
TEXT_EXTENSIONS = {
|
||||
".txt",
|
||||
@@ -341,6 +344,18 @@ def _unlink_blob(node: dict) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _blob_matches(node: dict, data: bytes) -> bool:
|
||||
if not (node.get("is_binary") and node.get("stored_name") and node.get("directory")):
|
||||
return False
|
||||
if node.get("size") != len(data):
|
||||
return False
|
||||
try:
|
||||
blob = PROJECT_FILES_DIR / node["directory"] / node["stored_name"]
|
||||
return blob.read_bytes() == data
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def store_upload(
|
||||
project_uid: str, user: dict, dir_path: str, filename: str, data: bytes
|
||||
) -> dict:
|
||||
@@ -365,46 +380,53 @@ def store_upload(
|
||||
existing = get_node(project_uid, path)
|
||||
if existing is not None and existing["type"] == "dir":
|
||||
raise ProjectFileError(f"'{path}' is a directory")
|
||||
if existing is not None and _blob_matches(existing, data):
|
||||
return existing
|
||||
if existing is None:
|
||||
_guard_capacity(project_uid)
|
||||
stored_name, directory, mime = _store_blob(data, base)
|
||||
if existing is not None:
|
||||
if existing.get("is_binary"):
|
||||
_unlink_blob(existing)
|
||||
_table().update(
|
||||
{
|
||||
"uid": existing["uid"],
|
||||
"content": None,
|
||||
"is_binary": 1,
|
||||
"stored_name": stored_name,
|
||||
"directory": directory,
|
||||
"mime_type": mime,
|
||||
"size": len(data),
|
||||
"updated_at": _now(),
|
||||
},
|
||||
["uid"],
|
||||
)
|
||||
return get_node(project_uid, path)
|
||||
_guard_capacity(project_uid)
|
||||
_table().insert(
|
||||
{
|
||||
"uid": generate_uid(),
|
||||
"project_uid": project_uid,
|
||||
"deleted_at": None,
|
||||
"deleted_by": None,
|
||||
"user_uid": user["uid"],
|
||||
"path": path,
|
||||
"name": base,
|
||||
"parent_path": _parent_of(path),
|
||||
"type": "file",
|
||||
"content": None,
|
||||
"is_binary": 1,
|
||||
"stored_name": stored_name,
|
||||
"directory": directory,
|
||||
"mime_type": mime,
|
||||
"size": len(data),
|
||||
"created_at": _now(),
|
||||
"updated_at": _now(),
|
||||
}
|
||||
)
|
||||
try:
|
||||
if existing is not None:
|
||||
_table().update(
|
||||
{
|
||||
"uid": existing["uid"],
|
||||
"content": None,
|
||||
"is_binary": 1,
|
||||
"stored_name": stored_name,
|
||||
"directory": directory,
|
||||
"mime_type": mime,
|
||||
"size": len(data),
|
||||
"updated_at": _now(),
|
||||
},
|
||||
["uid"],
|
||||
)
|
||||
else:
|
||||
_table().insert(
|
||||
{
|
||||
"uid": generate_uid(),
|
||||
"project_uid": project_uid,
|
||||
"deleted_at": None,
|
||||
"deleted_by": None,
|
||||
"user_uid": user["uid"],
|
||||
"path": path,
|
||||
"name": base,
|
||||
"parent_path": _parent_of(path),
|
||||
"type": "file",
|
||||
"content": None,
|
||||
"is_binary": 1,
|
||||
"stored_name": stored_name,
|
||||
"directory": directory,
|
||||
"mime_type": mime,
|
||||
"size": len(data),
|
||||
"created_at": _now(),
|
||||
"updated_at": _now(),
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
_unlink_blob({"stored_name": stored_name, "directory": directory})
|
||||
raise
|
||||
if existing is not None and existing.get("is_binary"):
|
||||
_unlink_blob(existing)
|
||||
return get_node(project_uid, path)
|
||||
|
||||
|
||||
@@ -621,7 +643,7 @@ def sync_dir_bidirectional(project_uid: str, workspace, user: dict) -> dict:
|
||||
new_manifest[path] = entry
|
||||
continue
|
||||
if db_epoch >= fs_epoch - _SYNC_CLOCK_SKEW_SECONDS or readonly:
|
||||
recorded = _record_export(row, dest)
|
||||
recorded = _export_with_backoff(project_uid, row, dest)
|
||||
if recorded:
|
||||
counts["exported"] += 1
|
||||
new_manifest[path] = recorded
|
||||
@@ -641,7 +663,7 @@ def sync_dir_bidirectional(project_uid: str, workspace, user: dict) -> dict:
|
||||
or readonly
|
||||
or db_epoch > entry["db_epoch"] + _SYNC_CLOCK_SKEW_SECONDS
|
||||
):
|
||||
recorded = _record_export(row, dest)
|
||||
recorded = _export_with_backoff(project_uid, row, dest)
|
||||
if recorded:
|
||||
counts["exported"] += 1
|
||||
new_manifest[path] = recorded
|
||||
@@ -682,6 +704,21 @@ def sync_dir_bidirectional(project_uid: str, workspace, user: dict) -> dict:
|
||||
return counts
|
||||
|
||||
|
||||
def _export_with_backoff(project_uid: str, row: dict, dest: Path):
|
||||
key = (project_uid, row["path"])
|
||||
until = _missing_blob_until.get(key)
|
||||
if until is not None and time.monotonic() < until:
|
||||
return None
|
||||
recorded = _record_export(row, dest)
|
||||
if recorded is not None or not row.get("is_binary"):
|
||||
_missing_blob_until.pop(key, None)
|
||||
return recorded
|
||||
if len(_missing_blob_until) >= MISSING_BLOB_MAX_TRACKED:
|
||||
_missing_blob_until.clear()
|
||||
_missing_blob_until[key] = time.monotonic() + MISSING_BLOB_RETRY_SECONDS
|
||||
return None
|
||||
|
||||
|
||||
def _record_export(row: dict, dest: Path):
|
||||
target = _export_node(row, dest)
|
||||
if target is None:
|
||||
@@ -1090,9 +1127,7 @@ def purge_soft_deleted_project_files(*, dry_run: bool = False) -> tuple[int, int
|
||||
return removed, freed
|
||||
|
||||
|
||||
def sweep_orphan_project_file_blobs(*, dry_run: bool = False) -> tuple[int, int]:
|
||||
if not PROJECT_FILES_DIR.exists():
|
||||
return 0, 0
|
||||
def referenced_project_blobs() -> set:
|
||||
referenced = set()
|
||||
if "project_files" in db.tables:
|
||||
for row in _table().find(is_binary=1):
|
||||
@@ -1100,8 +1135,21 @@ def sweep_orphan_project_file_blobs(*, dry_run: bool = False) -> tuple[int, int]
|
||||
stored_name = row.get("stored_name")
|
||||
if directory and stored_name:
|
||||
referenced.add((directory, stored_name))
|
||||
return referenced
|
||||
|
||||
|
||||
def sweep_project_blob_tree(
|
||||
referenced: set,
|
||||
*,
|
||||
dry_run: bool = False,
|
||||
min_age_seconds: float = 0,
|
||||
limit: int | None = None,
|
||||
) -> tuple[int, int]:
|
||||
if not PROJECT_FILES_DIR.exists():
|
||||
return 0, 0
|
||||
removed = 0
|
||||
freed = 0
|
||||
cutoff = time.time() - min_age_seconds
|
||||
base = str(PROJECT_FILES_DIR)
|
||||
for root, _dirs, files in os.walk(base):
|
||||
directory = os.path.relpath(root, base)
|
||||
@@ -1110,14 +1158,29 @@ def sweep_orphan_project_file_blobs(*, dry_run: bool = False) -> tuple[int, int]
|
||||
continue
|
||||
file_path = os.path.join(root, name)
|
||||
try:
|
||||
size = os.path.getsize(file_path)
|
||||
stat = os.stat(file_path)
|
||||
except OSError:
|
||||
continue
|
||||
if stat.st_mtime > cutoff:
|
||||
continue
|
||||
if not dry_run:
|
||||
try:
|
||||
os.unlink(file_path)
|
||||
except OSError:
|
||||
continue
|
||||
removed += 1
|
||||
freed += size
|
||||
freed += stat.st_size
|
||||
if limit is not None and removed >= limit:
|
||||
return removed, freed
|
||||
return removed, freed
|
||||
|
||||
|
||||
def sweep_orphan_project_file_blobs(
|
||||
*, dry_run: bool = False, min_age_seconds: float = 0, limit: int | None = None
|
||||
) -> tuple[int, int]:
|
||||
return sweep_project_blob_tree(
|
||||
referenced_project_blobs(),
|
||||
dry_run=dry_run,
|
||||
min_age_seconds=min_age_seconds,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
@@ -76,5 +76,6 @@ A match **updates** the row (token, client_id, environment) and clears `deleted_
|
||||
- A `.p8` that does not parse is cached as a failure for the same window, so a misconfiguration costs one error log per window rather than one parse per notification.
|
||||
- **`DEAD_REASONS` is deliberately narrow: only `BadDeviceToken` (400), `Unregistered` (410) and `ExpiredToken` (410).** These are the only reasons in Apple's documented table that describe the TOKEN itself as permanently invalid. `DeviceTokenNotForTopic` and `TopicDisallowed` are 400 errors about the **topic/provisioning matching the connection**, not the token - they fire identically for every token when `push_apns_topic` is misconfigured or the certificate/entitlements don't match, so treating them as dead would soft-delete the entire APNs subscriber base (a table deliberately kept OUT of `SOFT_DELETE_TABLES`, hence unrestorable) on the first delivery after a one-field admin typo. Never add a topic/provisioning-shaped reason to `DEAD_REASONS`.
|
||||
- **A 410's `timestamp` is honored before deleting.** Apple's 410 body carries `{"reason": "Unregistered", "timestamp": <ms epoch>}` - the instant Apple last confirmed the token dead, which can trail real device state by "several days" per Apple engineering guidance (410 delivery is intentionally non-deterministic; do not use it to infer app-uninstall timing). `apns._dead_before` converts it to ISO and it rides on `Delivery.dead_before`; `store.mark_dead(id, dead_before)` compares it against the row's `registered_at` and **skips the delete** (logs at INFO instead) if the registration was re-registered/revived after that instant - closing the race where an in-flight delivery against a stale row state would otherwise undo a concurrent revival. `dead_before` is only ever set for a 410; the `BadDeviceToken`/`ExpiredToken` paths pass `None` (unconditional delete, as before), since those reasons carry no `timestamp`.
|
||||
- The shared payload dict (`title`, `message`, `icon`, `url`) is translated once per batch into `aps.alert` plus the custom `url`/`icon` keys, mirroring what `service-worker.js` does for Web Push. `thread-id` mirrors the service worker's notification `tag`.
|
||||
- The shared payload dict (`title`, `message`, `icon`, `url`, `unread`) is translated once per batch into `aps.alert` plus the custom `url`/`icon` keys, mirroring what `service-worker.js` does for Web Push. `thread-id` mirrors the service worker's notification `tag`.
|
||||
- **`unread` becomes `aps.badge`.** `unread` is the recipient's unread notification count, `count_unread_groups(user_uid)` (groups when grouping is on, rows when off: the same number as `/notifications/counts`), computed by `utils/notifications.py` `_deliver_notification` right after the in-app insert and only when a push is actually sent. `apns._badge` accepts a non-negative integer (a `bool` is refused) and otherwise omits `aps.badge`, which leaves the app icon untouched; the welcome probe carries no `unread`. iOS applies `aps.badge` itself, so the icon updates while the app is backgrounded or terminated. The key is named `unread`, never `badge`, because `badge` already means the monochrome icon URL in the Notifications API. Web Push forwards the payload unchanged and the service worker ignores the extra key. A throttled push is not sent, so the badge shows the count at the last delivered push until the app is opened.
|
||||
- `POST /push.json` probes a created or revived row immediately via `notify_registration`. The JSON is `{registered: true, delivered: bool, error?: string}`. `registered` stays true so existing clients keep working; `delivered`/`error` surface Apple's reason instead of killing the row silently from the client's point of view. The row is still marked dead on a `DEAD` outcome (subject to the `dead_before` guard above) so later `notify_user` calls do not keep hitting a known-bad token.
|
||||
|
||||
@@ -230,6 +230,13 @@ def _dead_before(response: httpx.Response) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _badge(payload: dict[str, Any]) -> int | None:
|
||||
unread = payload.get("unread")
|
||||
if isinstance(unread, bool) or not isinstance(unread, int) or unread < 0:
|
||||
return None
|
||||
return unread
|
||||
|
||||
|
||||
class ApnsProvider(PushProvider):
|
||||
name = "apns"
|
||||
label = PROVIDER_LABEL
|
||||
@@ -323,16 +330,20 @@ class ApnsProvider(PushProvider):
|
||||
return fields
|
||||
|
||||
def prepare(self, payload: dict[str, Any]) -> str:
|
||||
aps: dict[str, Any] = {
|
||||
"alert": {
|
||||
"title": payload.get("title") or "DevPlace",
|
||||
"body": payload.get("message") or "",
|
||||
},
|
||||
"sound": "default",
|
||||
"thread-id": THREAD_ID,
|
||||
}
|
||||
badge = _badge(payload)
|
||||
if badge is not None:
|
||||
aps["badge"] = badge
|
||||
return json.dumps(
|
||||
{
|
||||
"aps": {
|
||||
"alert": {
|
||||
"title": payload.get("title") or "DevPlace",
|
||||
"body": payload.get("message") or "",
|
||||
},
|
||||
"sound": "default",
|
||||
"thread-id": THREAD_ID,
|
||||
},
|
||||
"aps": aps,
|
||||
"url": payload.get("url") or DEFAULT_PUSH_URL,
|
||||
"icon": payload.get("icon") or PUSH_ICON,
|
||||
}
|
||||
|
||||
@@ -100,6 +100,7 @@ def ensure_certificates() -> None:
|
||||
):
|
||||
return
|
||||
lock_path = VAPID_PRIVATE_KEY_FILE.parent / ".vapid.lock"
|
||||
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(lock_path, "w") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
try:
|
||||
|
||||
+11
-2
@@ -19,7 +19,14 @@ def wants_json(request: Request) -> bool:
|
||||
return "application/json" in accept and "text/html" not in accept
|
||||
|
||||
|
||||
def respond(request: Request, template: str, context: dict, *, model: type[BaseModel]):
|
||||
def respond(
|
||||
request: Request,
|
||||
template: str,
|
||||
context: dict,
|
||||
*,
|
||||
model: type[BaseModel],
|
||||
status_code: int = 200,
|
||||
):
|
||||
if wants_json(request):
|
||||
try:
|
||||
payload = model.model_validate(context).model_dump(mode="json")
|
||||
@@ -29,7 +36,9 @@ def respond(request: Request, template: str, context: dict, *, model: type[BaseM
|
||||
return JSONResponse(payload)
|
||||
from devplacepy.templating import templates
|
||||
|
||||
return templates.TemplateResponse(request, template, context)
|
||||
return templates.TemplateResponse(
|
||||
request, template, context, status_code=status_code
|
||||
)
|
||||
|
||||
|
||||
def action_result(
|
||||
|
||||
@@ -179,6 +179,10 @@ All dates displayed to users use European DD/MM/YYYY format. Implemented via:
|
||||
- **`time_ago()`** returns `DD/MM/YYYY` for items older than 30 days (instead of `"Xmo ago"`)
|
||||
- Services page has a JS `formatDate()` function for live polling updates
|
||||
|
||||
### Admin page specification
|
||||
|
||||
Every admin route and template conforms to `devplacepy/routers/admin/CLAUDE.md` (A1-A11). Read it before adding or changing anything under `/admin`; it is enforced by `tests/unit/admin_spec.py`.
|
||||
|
||||
### Admin pagination
|
||||
|
||||
Both `/admin/users` and `/admin/news` use offset-based pagination via a reusable component:
|
||||
@@ -294,10 +298,10 @@ All SEO features are implemented across the following locations:
|
||||
|
||||
### Post page layout (three columns, mirrors `/feed`)
|
||||
|
||||
`post.html` reuses `/feed`'s exact layout building blocks rather than inventing new ones, wrapped in `.post-page-layout` (`static/css/post.css`, `grid-template-columns: var(--sidebar-width) minmax(0, 1fr) 280px`, collapsing to one column at 1024px):
|
||||
`post.html` reuses `/feed`'s exact layout building blocks rather than inventing new ones, wrapped in `.post-page-layout` (`static/css/post.css`). The grid is `var(--sidebar-width) minmax(0, 1fr) 280px` only when both asides are present. Each column is placed explicitly (sidebar column 1, `.post-page` column 2, `.feed-right` column 3), and a missing aside drops its track instead of shifting the article into the 240px sidebar column. It collapses to one column at 1024px:
|
||||
|
||||
- **Left column** - `<aside class="post-page-sidebar">`, sticky, holding up to three separate `.sidebar-card` blocks (never merged into one card - each is its own bordered panel): "Gists from {author}" and "Projects from {author}" (`content.get_user_sidebar_gists`/`get_user_sidebar_projects`, up to 5 each, most-recently-modified first, private projects filtered via `can_view_project`), and "Related Discussions" (same-topic posts). Every card title is a `.sidebar-heading` div (the same class `feed.html`'s left sidebar uses for "Topics"/"Resources"/"Online now" - `.sidebar-card .sidebar-heading` in `sidebar.css`, so it only styles correctly nested inside a `.sidebar-card`, never bare). Each list item reuses the plain `.related-list`/`.related-link`/`.related-title`/`.related-meta` classes (`base.css`) with `content_preview()` for the ellipsis-truncated description.
|
||||
- **Middle column** - `.post-page` (`max-width: 720px`): the post article, comments.
|
||||
- **Middle column** - `.post-page` (`width: 100%`, `max-width: 720px`, centered in its column): the post article, comments. Below 1024px it fills the single column instead of shrink-wrapping to the post text.
|
||||
- **Right column** - `<aside class="feed-right">`, the exact same class `feed.html` uses for its Daily Topic widget (sticky, hidden below 1024px via `feed.css`'s own media query - no post-page-specific override needed). Holds the "Featured" cards (`database.get_featured_topics`, up to 3, cached pool + per-request random sample): each is a `.daily-topic-card` with its own `.daily-topic-label` ("Featured") - matching the single Daily Topic card's internal label, since there is no section-level heading here (a `.sidebar-heading` div placed directly in `.feed-right` would NOT be styled, as noted above - the fix used is a per-card label instead of a bare heading).
|
||||
|
||||
All three columns are populated by `routers/posts.py` `post_page_context()`, the single context builder shared by the real `/posts/{slug}` route and `happy404.render()` (see the root `CLAUDE.md`), so a decoy happy-404 post page renders with the identical sidebar/featured layout as a real one.
|
||||
@@ -382,3 +386,21 @@ The profile **Activity** tab (`/profile/{username}?tab=activity`, public) interl
|
||||
## Content visibility routes
|
||||
|
||||
Posts, gists, projects and news share one four-value status (published, hidden, draft, offline); the specification, truth table and choke points are in `devplacepy/database/CLAUDE.md` ("Content visibility"). It is an ordinary field of the create and edit forms of posts, gists and projects (`visibility`, via the `_visibility_field.html` partial), handled by `create_content_item` and `edit_content_item` like every other field; there are no dedicated toggle routes. The only dedicated route is the administrator's `POST /admin/news/{uid}/visibility` (`VisibilityForm{value}`), because news has no edit form. Hidden items are `noindex,nofollow`. Comments, votes, reactions, bookmarks and notes refuse (404) a target the viewer cannot open (`content.can_view_target`), and the saved/notes lists skip such targets. The devRant API resolves rants through `post_by_id(rant_id, viewer)` and lists listed rants only. Audit key: `<kind>.visibility.set`. Devii: the `visibility` parameter on the create and edit tools, plus `admin_set_news_visibility`.
|
||||
|
||||
## Notifications grouping and profile settings (requested_changes items 1, 4, 5)
|
||||
|
||||
- `POST /profile/{username}/enter-to-submit`, `POST /profile/{username}/notifications/grouping` and `POST /profile/{username}/notifications/throttling` are owner-or-admin toggles through `routers/profile/_shared.resolve_customization_target`, audited as `profile.enter_to_submit.toggle`, `profile.notification.grouping.toggle` and `profile.notification.throttle.toggle`.
|
||||
- `GET /notifications` groups events with `notification_group_key` when the recipient has grouping on (250 row fetch cap, 25 groups per page, date groups outside event groups). Opening or dismissing a grouped card marks every member read. With grouping off the page and badge keep the old one-row behaviour.
|
||||
|
||||
## Feature checklist (one data source, four faces)
|
||||
|
||||
Every feature is one data source fanning out into HTML, JSON (`respond(..., model=XOut)`; a context key not on `XOut` is silently dropped from JSON), a Devii agent action, and a documented endpoint. A change touching one file must confirm none of the four faces were missed. Checklist, ordered by data flow:
|
||||
|
||||
1. **Understand.** Read the router, template, matching tests, and the nested `CLAUDE.md`. Trace input model, router, data helper, response (HTML and JSON).
|
||||
2. **Data layer.** `database/` for query/batch helpers (never inline N+1; guard raw SQL with `if "table" in db.tables`). `models/` for the Pydantic `Form` (add to the domain module, re-export list, and `__all__`). `schemas/` for the `*Out` JSON model; every context key a JSON route exposes must exist on it. Indexes via `CREATE INDEX IF NOT EXISTS` in `init_db()`.
|
||||
3. **Server layer.** Guard matches the read (public), write (member), or admin surface. Specific paths before catch-alls. HTML+JSON via `respond(...)` or pure JSON via `JSONResponse`. Register any new router in `main.py`.
|
||||
4. **View layer.** Extend `base.html`; page CSS/JS via `extra_head`/`extra_js`. Reuse partials and template globals. ES6 modules, one class per file, instantiated on `app`.
|
||||
5. **Safety layer (skip only when the feature stores and shows nothing).** New user-generated surface: register in `REPORTABLE_TARGETS` (or `UNREPORTABLE_TABLES` with reason), resolve in `resolve_object_url`, include `_report_button.html`. New personal-data category or third-party transmission: update `/docs/privacy.html` and the app-store declarations in the same change.
|
||||
6. **Agent + docs layer.** Devii `Action` where a user could ask for this (`requires_auth` mirrors the guard). `docs_api.py` `endpoint()` with params and `sample_response`. `DOCS_PAGES` prose. `seo.py` context and sitemap entry for new public pages.
|
||||
7. **Document.** `README.md` for product-facing surface; the nested `CLAUDE.md` for any new mechanic or cross-layer wiring; root `CLAUDE.md` only for a new architectural rule or workflow step.
|
||||
8. **Validate.** Import gate, per-language manual checks, no em dashes, `pyflakes`/`ruff check` on every touched file, the four-layer rigor procedure for spendable/state-machine/race shapes, then full `make test` green before done. Failures at any step block the workflow.
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# CLAUDE.md
|
||||
|
||||
The specification every `/admin` page follows. Claude Code loads it whenever a file under `routers/admin/` is touched; the root, `routers/`, `templates/`, `static/js/` and `static/css/` `CLAUDE.md` files point here. A page that breaks a rule below is a defect, not a style choice. `tests/unit/admin_spec.py` enforces the mechanical rules (A1, A2, A5, A6, A7, A9, A10) against the real templates and routers, so a violation fails the suite.
|
||||
|
||||
Code references: the section registry is `devplacepy/admin_sections.py`; the caps and floors are `ADMIN_LIST_CAP` and `ADMIN_POLL_FLOOR_SECONDS` in `routers/admin/_shared.py`; the cap note is `templates/_admin_cap_note.html`.
|
||||
|
||||
## A1. Backend rendered, always
|
||||
|
||||
A GET of an admin page returns the complete content in the HTML: every table, card, key figure, tab label and empty state is rendered by Jinja from data the handler computed. A placeholder such as "Loading..." in a template is forbidden. The page must be readable and correct with JavaScript off.
|
||||
|
||||
JavaScript only enhances: live refresh, charts drawn on a `<canvas>`, sorting, modals. The numbers and tables around a chart are server rendered; the chart is drawn from JSON embedded in the page.
|
||||
|
||||
The only permitted live-first surface is a page whose whole purpose is a live channel (WebSocket) such as the Bot Monitor and the container terminal, and even those render their initial frame on the server.
|
||||
|
||||
## A2. One handler, one builder, one model
|
||||
|
||||
- The HTML route calls `respond(request, "<template>.html", ctx, model=XOut)` with `base_seo_context(..., robots="noindex,nofollow")` and a breadcrumb trail `Home > Admin > <Page>`. Never `templates.TemplateResponse` directly: that drops the JSON face and the `*Out` schema.
|
||||
- The data the page shows is produced by ONE builder function. The HTML route and the refresh endpoint (`GET /admin/<page>/data`, `require_admin`, `JSONResponse`) both call it. The two must never compute the same figures twice with different code.
|
||||
- Context keys never collide with a Jinja global (root rule: `viewer_is_admin`, not `is_admin`).
|
||||
- Every admin page sets `"admin_section": "<key>"` where the key exists in `ADMIN_SECTIONS`.
|
||||
|
||||
## A3. Page anatomy
|
||||
|
||||
Every page extends `admin_base.html` and, in this order, renders:
|
||||
|
||||
1. `<div class="admin-toolbar">` holding the page title as `<h2>` (never `<h1>`; the layout owns the document heading), then `admin-count` spans, filters and the primary action.
|
||||
2. Optional `<nav class="admin-tabs" data-overflow-tabs>` for page tabs. A tab is a real link (`?tab=`), rendered on the server.
|
||||
3. The content: `admin-table-wrap > table.admin-table`, or cards, or a form `admin-settings-form`.
|
||||
4. The empty state: `<p class="admin-empty">`, never `empty-state`, never an empty table.
|
||||
5. Pagination via `_pagination.html` when the list is paged (A6).
|
||||
|
||||
Tables carry `<caption class="sr-only">`, every `<th>` has `scope="col"`, every icon-only or repeated row button has an `aria-label`. Page CSS goes in `{% block extra_head %}` after `{{ super() }}` (never re-link `admin.css` or `sidebar.css`; `admin_base.html` already loads them). No inline `<style>`, no `style=` attributes, no inline event handlers.
|
||||
|
||||
## A4. Class vocabulary
|
||||
|
||||
Buttons are `admin-btn` with `admin-btn-primary`, `admin-btn-danger`, `admin-btn-sm`. Fields are `admin-field`, selects `admin-select`, forms `admin-settings-form` or `admin-inline-form`, hints `admin-hint`. Status chips reuse the page family badge (`service-status`, `cm-badge`, `workspace-badge`). The public-site classes `btn`, `btn-primary`, `btn-danger`, `hint-text`, `empty-state`, `admin-header` are forbidden in admin templates. A missing admin class is added to `admin.css`, never worked around with a public class. Destructive buttons carry `data-confirm` (and `data-confirm-danger` for role/quota style changes).
|
||||
|
||||
## A5. Time
|
||||
|
||||
Every instant shown to a viewer is `local_dt(iso, mode)` or `dt_ago(iso)`; never `format_date`/`time_ago` for an instant (those stay for JSON and non-timestamp date fields). When client JS re-renders a row it emits the same `<time data-dt="...">` markup, and `LocalTime` localizes it through its MutationObserver; JS never formats an instant itself with `toLocaleString`/`toLocaleTimeString`.
|
||||
|
||||
## A6. Everything is capped
|
||||
|
||||
No list is unbounded.
|
||||
|
||||
- A list that can grow with users or content is paginated: `build_pagination(page, total)` plus `_limit/_offset` in the query and `_pagination.html`. Sorting is in SQL (`order_by`), never `rows.sort()` over the whole table.
|
||||
- A list that is naturally small (services, gateway providers) still reads with `_limit=ADMIN_LIST_CAP` and renders `_admin_cap_note.html` (`_shown`, `_total`) so truncation is visible, never silent.
|
||||
- Per-row work (queries, `await`s, service calls) is done for the visible page only, in batch (`get_users_by_uids` and friends), never per row of the whole table.
|
||||
- Query parameters that size a computation (`hours`, `top_n`, `limit`) are clamped on the server to a declared constant.
|
||||
|
||||
## A7. Heavy and remote work
|
||||
|
||||
A GET handler must not wait on a remote service. Gitea, providers and any network call go through a cache with a fixed TTL and a hard item cap; the handler renders the cached value at once and keeps the page's explicit error state (`*_error`) when the source is down. A computation costing more than one page of plain queries (statistics, usage analytics) is computed once per request: the HTML route embeds its result, and a tab or window change either navigates (server render) or fetches `/data`, never both.
|
||||
|
||||
## A8. Live refresh
|
||||
|
||||
- The shared `Poller` only: `new Poller(fn, ms, { pauseHidden: true, immediate: false })`. `immediate: false` because the first paint is already on the page (A1). Raw `setInterval` is forbidden.
|
||||
- Interval floor is `ADMIN_POLL_FLOOR_SECONDS` (15 s); a page that needs faster is a live channel.
|
||||
- Fetch through `Http.getJson`; never a bare `fetch`.
|
||||
- The refresh response is the `/data` JSON of A2, or, for a page made of server-rendered sections, HTML fetched with `Http.getHtml` (the page itself, or a `/fragment` route returning the same partial) and swapped into the `[data-live]` regions (Backups, Community pages, AI usage, Gateway stats). The markup then lives only in Jinja and the one builder feeds the page, the fragment and `/data`. The client re-renders only the regions that changed and preserves open modals, focus, scroll position and input values.
|
||||
- Initial data for charts is embedded as `<script type="application/json" id="<root>-initial">{{ initial | tojson }}</script>` and read synchronously; the client does not issue a second request to learn what the server already knew.
|
||||
|
||||
## A9. Assets
|
||||
|
||||
- One copy of each vendored library. Chart.js is `/static/vendor/chartjs/chart.umd.min.js`, loaded with `defer` through `static_url(...)` from `{% block extra_js %}` only on pages that draw charts.
|
||||
- Page JS is one ES6 module per class in `static/js/`, started from a three-line module block in `extra_js`. No page logic inline.
|
||||
|
||||
## A10. Navigation is one registry
|
||||
|
||||
The admin sections are declared once in `devplacepy/admin_sections.py` (`ADMIN_SECTIONS`, exposed as the `admin_sections` Jinja global). `admin_base.html` (desktop sidebar) and the admin block of `base.html` (the phone menu, because the sidebar is hidden at 1024 px and below) both loop over it. A new admin page adds one registry entry and nothing else; hand-writing a nav link in either template is forbidden. Every `admin_section` value passed by a route must exist in the registry.
|
||||
|
||||
## A11. Responsive
|
||||
|
||||
Everything works at 360 px. Tables sit in `admin-table-wrap` (horizontal scroll inside the wrap, never the page). A toolbar with more than three controls wraps; a button group of more than three becomes a `<select>` or a `dp-action-menu`. Touch targets are at least 44 px (`admin.css` already enforces it for `admin-btn`/`admin-select`).
|
||||
|
||||
## Checklist for a new or changed admin page
|
||||
|
||||
1. Registry entry in `ADMIN_SECTIONS`, `admin_section` matches.
|
||||
2. Builder function, `respond(... model=XOut)`, `/data` endpoint if it refreshes, audit event for every mutation.
|
||||
3. Template follows A3, A4, A5; no placeholder text; caps and pagination per A6.
|
||||
4. JS (only if needed) per A8 and A9.
|
||||
5. `tests/api/admin/...` asserts the first response already contains the data (not "Loading"), and `tests/unit/admin_spec.py` still passes.
|
||||
@@ -8,6 +8,10 @@ from devplacepy.responses import action_result
|
||||
from devplacepy.services.audit import record as audit
|
||||
|
||||
|
||||
ADMIN_LIST_CAP = 200
|
||||
ADMIN_POLL_FLOOR_SECONDS = 15
|
||||
|
||||
|
||||
def seniority_key(user: dict) -> tuple[str, int]:
|
||||
return (user.get("created_at") or "", user.get("id") or 0)
|
||||
|
||||
|
||||
@@ -8,16 +8,46 @@ from devplacepy.seo import base_seo_context, site_url, website_schema
|
||||
from devplacepy.responses import respond
|
||||
from devplacepy.schemas import GatewayUsageOut
|
||||
from devplacepy.services.manager import service_manager
|
||||
from devplacepy.services.openai_gateway.analytics import build_analytics
|
||||
from devplacepy.services.openai_gateway.analytics import MAX_WINDOW_HOURS, build_analytics
|
||||
from devplacepy.services.openai_gateway.usage import pricing_from_cfg
|
||||
from devplacepy.templating import templates
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
DEFAULT_WINDOW_HOURS = 48
|
||||
MAX_TOP_N = 50
|
||||
WINDOW_CHOICES = (
|
||||
(1, "1 hour"),
|
||||
(24, "24 hours"),
|
||||
(48, "48 hours"),
|
||||
(168, "7 days"),
|
||||
(0, "All time"),
|
||||
)
|
||||
|
||||
|
||||
def _clamp_hours(hours: int) -> int:
|
||||
if hours <= 0:
|
||||
return 0
|
||||
return min(hours, MAX_WINDOW_HOURS)
|
||||
|
||||
|
||||
def _clamp_top_n(top_n: int) -> int:
|
||||
return max(1, min(top_n, MAX_TOP_N))
|
||||
|
||||
|
||||
def build_usage(hours: int, top_n: int) -> dict:
|
||||
service = service_manager.get_service("openai")
|
||||
pricing = pricing_from_cfg(service.get_config()) if service is not None else None
|
||||
return build_analytics(_clamp_hours(hours), top_n=_clamp_top_n(top_n), pricing=pricing)
|
||||
|
||||
|
||||
@router.get("/ai-usage", response_class=HTMLResponse)
|
||||
async def admin_ai_usage(request: Request):
|
||||
async def admin_ai_usage(
|
||||
request: Request, hours: int = DEFAULT_WINDOW_HOURS, top_n: int = 10
|
||||
):
|
||||
admin = require_admin(request)
|
||||
usage = build_usage(hours, top_n)
|
||||
base = site_url(request)
|
||||
seo_ctx = base_seo_context(
|
||||
request,
|
||||
@@ -39,14 +69,28 @@ async def admin_ai_usage(request: Request):
|
||||
"request": request,
|
||||
"user": admin,
|
||||
"admin_section": "ai-usage",
|
||||
"usage": usage,
|
||||
"window_choices": WINDOW_CHOICES,
|
||||
"window_hours": usage["window_hours"],
|
||||
**usage,
|
||||
},
|
||||
model=GatewayUsageOut,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/ai-usage/data")
|
||||
async def admin_ai_usage_json(request: Request, hours: int = 48, top_n: int = 10):
|
||||
async def admin_ai_usage_json(
|
||||
request: Request, hours: int = DEFAULT_WINDOW_HOURS, top_n: int = 10
|
||||
):
|
||||
require_admin(request)
|
||||
service = service_manager.get_service("openai")
|
||||
pricing = pricing_from_cfg(service.get_config()) if service is not None else None
|
||||
return JSONResponse(build_analytics(hours, top_n=top_n, pricing=pricing))
|
||||
return JSONResponse(build_usage(hours, top_n))
|
||||
|
||||
|
||||
@router.get("/ai-usage/fragment", response_class=HTMLResponse)
|
||||
async def admin_ai_usage_fragment(
|
||||
request: Request, hours: int = DEFAULT_WINDOW_HOURS, top_n: int = 10
|
||||
):
|
||||
require_admin(request)
|
||||
usage = build_usage(hours, top_n)
|
||||
html = templates.get_template("_ai_usage_report.html").render(usage=usage)
|
||||
return HTMLResponse(html)
|
||||
|
||||
@@ -20,6 +20,8 @@ from devplacepy.services.jobs import queue
|
||||
from devplacepy.utils import is_primary_admin, not_found, require_admin
|
||||
from fastapi import Depends, HTTPException
|
||||
from devplacepy.dependencies import json_or_form
|
||||
from devplacepy.database import db, get_table
|
||||
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
@@ -63,12 +65,16 @@ def _targets() -> list[dict]:
|
||||
]
|
||||
|
||||
async def _dashboard(can_download: bool) -> dict:
|
||||
backups = [_backup_payload(row, can_download) for row in store.list_backups()]
|
||||
backups = [
|
||||
_backup_payload(row, can_download)
|
||||
for row in store.list_backups(limit=ADMIN_LIST_CAP)
|
||||
]
|
||||
schedules = store.list_schedules()
|
||||
storage = await asyncio.to_thread(store.compute_storage_stats)
|
||||
return {
|
||||
"storage": storage,
|
||||
"backups": backups,
|
||||
"backups_total": get_table("backups").count() if "backups" in db.tables else 0,
|
||||
"schedules": schedules,
|
||||
"targets": _targets(),
|
||||
"metrics": _metrics(backups),
|
||||
|
||||
@@ -10,7 +10,7 @@ from urllib.parse import urlencode
|
||||
from fastapi import APIRouter, Form, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from devplacepy.database import get_setting, get_table, get_users_by_uids, resolve_object_url
|
||||
from devplacepy.database import build_pagination, get_setting, get_table, get_users_by_uids, resolve_object_url
|
||||
from devplacepy.database.sync import count_links, identity_map
|
||||
from devplacepy.responses import action_result, json_error, respond
|
||||
from devplacepy.schemas import AdminCommunitiesOut, AdminCommunityLedgerOut, AdminCommunityOut, AdminCommunitySchemaOut
|
||||
@@ -174,8 +174,10 @@ def feed_summary(feed: dict) -> dict:
|
||||
|
||||
|
||||
@router.get("/communities", response_class=HTMLResponse)
|
||||
async def admin_communities(request: Request):
|
||||
async def admin_communities(request: Request, page: int = 1):
|
||||
admin = require_admin(request)
|
||||
pagination = build_pagination(page, store.count())
|
||||
offset = (pagination["page"] - 1) * pagination["per_page"]
|
||||
return respond(
|
||||
request,
|
||||
"admin_communities.html",
|
||||
@@ -183,7 +185,8 @@ async def admin_communities(request: Request):
|
||||
**seo(request, "Communities", LIST_URL, "Communities"),
|
||||
"request": request,
|
||||
"user": admin,
|
||||
"items": [public(row) for row in store.list()],
|
||||
"items": [public(row) for row in store.list(pagination["per_page"], offset)],
|
||||
"pagination": pagination,
|
||||
"sync_enabled": sync_enabled(),
|
||||
**service_flags(),
|
||||
"admin_section": "communities",
|
||||
|
||||
@@ -6,6 +6,7 @@ from fastapi import Depends, APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
||||
|
||||
from devplacepy.database import (
|
||||
build_pagination,
|
||||
db,
|
||||
get_table,
|
||||
get_users_by_uids,
|
||||
@@ -111,10 +112,20 @@ def _audit_admin(request: Request, admin: dict, event_key: str, inst: dict, summ
|
||||
result=result,
|
||||
)
|
||||
|
||||
def _containers_payload(admin: dict, page: int) -> dict:
|
||||
visible = _decorate(store.all_instances(), admin)
|
||||
pagination = build_pagination(page, len(visible))
|
||||
start = (pagination["page"] - 1) * pagination["per_page"]
|
||||
return {
|
||||
"instances": visible[start : start + pagination["per_page"]],
|
||||
"pagination": pagination,
|
||||
}
|
||||
|
||||
|
||||
@router.get("", response_class=HTMLResponse)
|
||||
async def containers_index(request: Request):
|
||||
async def containers_index(request: Request, page: int = 1):
|
||||
admin = require_admin(request)
|
||||
instances = _decorate(store.all_instances(), admin)
|
||||
payload = _containers_payload(admin, page)
|
||||
base = site_url(request)
|
||||
seo_ctx = base_seo_context(
|
||||
request,
|
||||
@@ -136,7 +147,7 @@ async def containers_index(request: Request):
|
||||
**seo_ctx,
|
||||
"request": request,
|
||||
"user": admin,
|
||||
"instances": instances,
|
||||
**payload,
|
||||
"boot_languages": BOOT_LANGUAGES,
|
||||
"restart_policies": RESTART_POLICIES,
|
||||
"admin_section": "containers",
|
||||
@@ -145,9 +156,9 @@ async def containers_index(request: Request):
|
||||
)
|
||||
|
||||
@router.get("/data")
|
||||
async def containers_index_json(request: Request):
|
||||
async def containers_index_json(request: Request, page: int = 1):
|
||||
admin = require_admin(request)
|
||||
return JSONResponse({"instances": _decorate(store.all_instances(), admin)})
|
||||
return JSONResponse(_containers_payload(admin, page))
|
||||
|
||||
@router.get("/projects/search")
|
||||
async def project_search(request: Request, q: str = ""):
|
||||
|
||||
@@ -5,7 +5,13 @@ import logging
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from devplacepy.database import db, get_admin_uids, get_int_setting, get_users_by_uids
|
||||
from devplacepy.database import (
|
||||
build_pagination,
|
||||
db,
|
||||
get_admin_uids,
|
||||
get_int_setting,
|
||||
get_users_by_uids,
|
||||
)
|
||||
from devplacepy.responses import action_result, respond
|
||||
from devplacepy.schemas import AdminDeviiTasksOut
|
||||
from devplacepy.seo import base_seo_context, site_url, website_schema
|
||||
@@ -32,17 +38,26 @@ def _schedule_text(row: dict) -> str:
|
||||
return f"once {row.get('run_at') or ''}".strip()
|
||||
|
||||
|
||||
def _rows(state: str) -> list[dict]:
|
||||
def _page(state: str, page: int) -> tuple[list[dict], dict]:
|
||||
if TABLE not in db.tables:
|
||||
return []
|
||||
return [], build_pagination(page, 0)
|
||||
criteria: dict = {"deleted_at": None}
|
||||
if state == "active":
|
||||
criteria["enabled"] = True
|
||||
elif state == "inactive":
|
||||
criteria["enabled"] = False
|
||||
rows = list(db[TABLE].find(**criteria))
|
||||
rows.sort(key=lambda row: int(row.get("run_count") or 0), reverse=True)
|
||||
return rows
|
||||
table = db[TABLE]
|
||||
pagination = build_pagination(page, table.count(**criteria))
|
||||
offset = (pagination["page"] - 1) * pagination["per_page"]
|
||||
rows = list(
|
||||
table.find(
|
||||
order_by=["-run_count", "-created_at"],
|
||||
_limit=pagination["per_page"],
|
||||
_offset=offset,
|
||||
**criteria,
|
||||
)
|
||||
)
|
||||
return rows, pagination
|
||||
|
||||
|
||||
def _quotas(owner_uids: set[str]) -> dict[str, dict]:
|
||||
@@ -98,11 +113,11 @@ def _require_task(uid: str) -> dict:
|
||||
|
||||
|
||||
@router.get("/devii-tasks", response_class=HTMLResponse)
|
||||
async def admin_devii_tasks(request: Request, state: str = "active"):
|
||||
async def admin_devii_tasks(request: Request, state: str = "active", page: int = 1):
|
||||
admin = require_admin(request)
|
||||
if state not in STATES:
|
||||
state = "active"
|
||||
rows = _rows(state)
|
||||
rows, pagination = _page(state, page)
|
||||
items = _items(rows)
|
||||
bounds = {
|
||||
"max_concurrent": get_int_setting(
|
||||
@@ -149,6 +164,7 @@ async def admin_devii_tasks(request: Request, state: str = "active"):
|
||||
"request": request,
|
||||
"user": admin,
|
||||
"items": items,
|
||||
"pagination": pagination,
|
||||
"state": state,
|
||||
"tabs": tabs,
|
||||
"limits": bounds,
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
||||
from pydantic import ValidationError
|
||||
|
||||
@@ -16,6 +17,7 @@ from devplacepy.schemas import (
|
||||
AdminGatewayQuotaFormOut,
|
||||
)
|
||||
from devplacepy.seo import base_seo_context, site_url, website_schema
|
||||
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP
|
||||
from devplacepy.services.audit import record as audit
|
||||
from devplacepy.services.manager import service_manager
|
||||
from devplacepy.services.openai_gateway import (
|
||||
@@ -24,6 +26,12 @@ from devplacepy.services.openai_gateway import (
|
||||
quota,
|
||||
routing,
|
||||
)
|
||||
from devplacepy.services.openai_gateway.learned import (
|
||||
DEFAULT_PROVIDER,
|
||||
LearnedResetIn,
|
||||
learned_store,
|
||||
)
|
||||
from devplacepy.services.openai_gateway.shape import shape_stats
|
||||
from devplacepy.templating import templates
|
||||
from devplacepy.utils import not_found, require_admin
|
||||
|
||||
@@ -32,6 +40,7 @@ router = APIRouter()
|
||||
|
||||
INDEX_URL = "/admin/gateway"
|
||||
TABS = ("models", "providers", "quota", "stats")
|
||||
DEFAULT_STATS_RANGE = "24h"
|
||||
|
||||
|
||||
def _default_provider_summary() -> dict:
|
||||
@@ -143,31 +152,69 @@ def _error_response(
|
||||
):
|
||||
if wants_json(request):
|
||||
return json_error(status_code, message)
|
||||
return templates.TemplateResponse(
|
||||
return respond(
|
||||
request,
|
||||
template,
|
||||
{**context, "request": request, "error": message},
|
||||
model=AdminGatewayOut,
|
||||
status_code=status_code,
|
||||
)
|
||||
|
||||
|
||||
def _models_with_learned(limit: int = ADMIN_LIST_CAP) -> list[dict]:
|
||||
models = routing.model_store.list()[:limit]
|
||||
for model in models:
|
||||
method = learned_store.get(
|
||||
model["provider"] or DEFAULT_PROVIDER, model["target_model"]
|
||||
)
|
||||
model["learned_shape"] = method.label if method is not None else ""
|
||||
model["learned_provider"] = model["provider"] or DEFAULT_PROVIDER
|
||||
return models
|
||||
|
||||
|
||||
def _reset_learned(request: Request, admin: dict, payload: LearnedResetIn) -> bool:
|
||||
provider = payload.provider or DEFAULT_PROVIDER
|
||||
existed = learned_store.forget(provider, payload.target_model)
|
||||
if existed:
|
||||
audit.record(
|
||||
request,
|
||||
"gateway.learned.reset",
|
||||
user=admin,
|
||||
target_type="gateway_learned_method",
|
||||
target_uid=f"{provider}/{payload.target_model}",
|
||||
target_label=f"{provider}/{payload.target_model}",
|
||||
summary=(
|
||||
f"admin {admin['username']} reset the learned request shape "
|
||||
f"for {provider}/{payload.target_model}"
|
||||
),
|
||||
)
|
||||
return existed
|
||||
|
||||
|
||||
# --- Index page (tabs: models / providers / quota) --------------------------
|
||||
|
||||
|
||||
@router.get("/gateway", response_class=HTMLResponse)
|
||||
async def gateway_config_page(
|
||||
request: Request, tab: str = "models", tested: str = "", test_image: str = ""
|
||||
request: Request,
|
||||
tab: str = "models",
|
||||
tested: str = "",
|
||||
test_image: str = "",
|
||||
stats_range: str = Query(DEFAULT_STATS_RANGE, alias="range"),
|
||||
):
|
||||
admin = require_admin(request)
|
||||
if tab not in TABS:
|
||||
tab = "models"
|
||||
if not test_image.startswith("http"):
|
||||
test_image = ""
|
||||
quota_rules = quota.quota_rule_store.list()
|
||||
all_quota_rules = quota.quota_rule_store.list()
|
||||
quota_rules = all_quota_rules[:ADMIN_LIST_CAP]
|
||||
for rule in quota_rules:
|
||||
rule["spent_24h_usd"] = round(
|
||||
quota.spent_24h(rule["owner_kind"], rule["owner_id"], rule["app_reference"]), 6
|
||||
)
|
||||
all_providers = routing.provider_store.list()
|
||||
stats_context = _stats_context(stats_range) if tab == "stats" else {}
|
||||
return respond(
|
||||
request,
|
||||
"admin_gateway.html",
|
||||
@@ -176,9 +223,13 @@ async def gateway_config_page(
|
||||
"user": admin,
|
||||
"admin_section": "gateway",
|
||||
"tab": tab,
|
||||
"providers": routing.provider_store.list(),
|
||||
"models": routing.model_store.list(),
|
||||
"providers": all_providers[:ADMIN_LIST_CAP],
|
||||
"providers_total": len(all_providers),
|
||||
"models": _models_with_learned(),
|
||||
"models_total": routing.model_store.count(),
|
||||
"quota_rules": quota_rules,
|
||||
"quota_rules_total": len(all_quota_rules),
|
||||
**stats_context,
|
||||
"default_provider": _default_provider_summary(),
|
||||
"quota_defaults": _quota_defaults_summary(),
|
||||
"stats_ranges": list(model_stats_query.RANGE_SECONDS.keys()),
|
||||
@@ -388,6 +439,44 @@ async def list_models(request: Request):
|
||||
)
|
||||
|
||||
|
||||
@router.get("/gateway/learned")
|
||||
async def list_learned(request: Request):
|
||||
require_admin(request)
|
||||
rows = learned_store.list()
|
||||
return JSONResponse(
|
||||
{"learned": rows, "count": len(rows), "stats": shape_stats.snapshot()}
|
||||
)
|
||||
|
||||
|
||||
@router.post("/gateway/learned/reset")
|
||||
async def reset_learned_json(request: Request):
|
||||
admin = require_admin(request)
|
||||
body = await _payload(request)
|
||||
try:
|
||||
payload = LearnedResetIn(**body)
|
||||
except ValidationError as exc:
|
||||
return _validation_error(exc)
|
||||
if not _reset_learned(request, admin, payload):
|
||||
return JSONResponse(
|
||||
{"ok": False, "error": "No learned method for that route"},
|
||||
status_code=404,
|
||||
)
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
@router.post("/gateway/learned/reset-page")
|
||||
async def reset_learned_page(request: Request):
|
||||
admin = require_admin(request)
|
||||
body = await _payload(request)
|
||||
try:
|
||||
payload = LearnedResetIn(**body)
|
||||
except ValidationError as exc:
|
||||
return _validation_error(exc)
|
||||
if not _reset_learned(request, admin, payload):
|
||||
raise not_found("No learned method for that route")
|
||||
return RedirectResponse(url=f"{INDEX_URL}?tab=models", status_code=302)
|
||||
|
||||
|
||||
@router.get("/gateway/provider-models")
|
||||
async def provider_models(request: Request, provider: str = ""):
|
||||
require_admin(request)
|
||||
@@ -1037,8 +1126,28 @@ async def reset_quota_rule_page(request: Request, uid: str):
|
||||
# --- Stats: JSON API for the Stats tab's charts ------------------------------
|
||||
|
||||
|
||||
def _stats_context(range_key: str) -> dict:
|
||||
if range_key not in model_stats_query.RANGE_SECONDS:
|
||||
range_key = DEFAULT_STATS_RANGE
|
||||
summary = model_stats_query.compute_summary(range_key)
|
||||
return _stats_view(summary, range_key)
|
||||
|
||||
|
||||
def _stats_view(summary: dict, range_key: str) -> dict:
|
||||
per_model = summary["per_model"]
|
||||
generated = datetime.fromtimestamp(summary["generated_at"], tz=timezone.utc)
|
||||
return {
|
||||
"stats": summary,
|
||||
"stats_range": range_key,
|
||||
"stats_generated_iso": generated.isoformat(),
|
||||
"stats_models": model_stats_query.list_known_models()[:ADMIN_LIST_CAP],
|
||||
"stats_table_models": per_model[:ADMIN_LIST_CAP],
|
||||
"stats_table_models_total": len(per_model),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/gateway/stats/data")
|
||||
async def gateway_stats_data(request: Request, range: str = "24h"):
|
||||
async def gateway_stats_data(request: Request, range: str = DEFAULT_STATS_RANGE):
|
||||
require_admin(request)
|
||||
try:
|
||||
return JSONResponse(model_stats_query.compute_summary(range))
|
||||
@@ -1046,6 +1155,17 @@ async def gateway_stats_data(request: Request, range: str = "24h"):
|
||||
return json_error(400, f"Unknown range: {range!r}")
|
||||
|
||||
|
||||
@router.get("/gateway/stats/fragment", response_class=HTMLResponse)
|
||||
async def gateway_stats_fragment(request: Request, range: str = DEFAULT_STATS_RANGE):
|
||||
require_admin(request)
|
||||
if range not in model_stats_query.RANGE_SECONDS:
|
||||
return json_error(400, f"Unknown range: {range!r}")
|
||||
context = _stats_context(range)
|
||||
return HTMLResponse(
|
||||
templates.get_template("_gateway_stats_fragment.html").render(**context)
|
||||
)
|
||||
|
||||
|
||||
@router.get("/gateway/stats/models")
|
||||
async def gateway_stats_models(request: Request):
|
||||
require_admin(request)
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from devplacepy.cache import TTLCache
|
||||
from devplacepy.responses import respond
|
||||
from devplacepy.schemas import AdminIssuesPlanningOut
|
||||
from devplacepy.seo import base_seo_context
|
||||
@@ -16,10 +18,20 @@ from devplacepy.utils import require_admin
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
TICKETS_CACHE_SECONDS = 60
|
||||
TICKETS_CACHE_KEY = "open"
|
||||
TICKETS_FETCH_TIMEOUT_SECONDS = 8
|
||||
_tickets_cache = TTLCache(TICKETS_CACHE_SECONDS, max_size=1)
|
||||
|
||||
|
||||
async def _open_tickets() -> tuple[list[dict], bool]:
|
||||
cached = _tickets_cache.get(TICKETS_CACHE_KEY)
|
||||
if cached is not None:
|
||||
return cached, False
|
||||
try:
|
||||
issues = await collect_open_issues(runtime.get_client())
|
||||
issues = await asyncio.wait_for(
|
||||
collect_open_issues(runtime.get_client()), TICKETS_FETCH_TIMEOUT_SECONDS
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("Could not load open tickets for planning: %s", exc)
|
||||
return [], True
|
||||
@@ -35,6 +47,7 @@ async def _open_tickets() -> tuple[list[dict], bool]:
|
||||
}
|
||||
for issue in issues
|
||||
]
|
||||
_tickets_cache.set(TICKETS_CACHE_KEY, tickets)
|
||||
return tickets, False
|
||||
|
||||
|
||||
@@ -49,7 +62,7 @@ async def admin_issues_planning(request: Request):
|
||||
breadcrumbs=[
|
||||
{"name": "Home", "url": "/feed"},
|
||||
{"name": "Admin", "url": "/admin"},
|
||||
{"name": "Issues", "url": "/issues"},
|
||||
{"name": "Ticket Planning", "url": "/admin/issues/planning"},
|
||||
],
|
||||
)
|
||||
configured = gitea_config().is_configured
|
||||
|
||||
@@ -15,6 +15,8 @@ from devplacepy.database.nodes import (
|
||||
DEVICE_BREAKDOWN_COLUMNS,
|
||||
LIMITS,
|
||||
add_event,
|
||||
count_all_devices,
|
||||
count_flags,
|
||||
count_open_requests,
|
||||
device_breakdown,
|
||||
cache_stats,
|
||||
@@ -234,7 +236,7 @@ def overview() -> dict:
|
||||
lifetime = lifetime_counters()
|
||||
outcomes = {name: value for name, value in lifetime.items() if name.startswith(OUTCOME_PREFIX)}
|
||||
devices = recent_devices(ADMIN_LIST_LIMIT)
|
||||
flags = list_flags()[:ADMIN_LIST_LIMIT]
|
||||
flags = list_flags(limit=ADMIN_LIST_LIMIT)
|
||||
device_by_uid = {row["uid"]: row for row in devices}
|
||||
missing = [row["device_uid"] for row in flags if row.get("device_uid") and row["device_uid"] not in device_by_uid]
|
||||
for uid in missing:
|
||||
@@ -251,7 +253,9 @@ def overview() -> dict:
|
||||
**breakdowns,
|
||||
"usage_today": usage_day_totals(),
|
||||
"flags": flag_views(flags, owners, device_by_uid),
|
||||
"flags_total": count_flags(),
|
||||
"devices": device_views(devices, owners),
|
||||
"devices_total": count_all_devices(),
|
||||
"settings": settings_view(),
|
||||
"limits": LIMITS.describe(),
|
||||
"circuits": circuit_views(),
|
||||
|
||||
@@ -4,7 +4,9 @@ import logging
|
||||
from typing import Any
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from devplacepy.templating import templates
|
||||
from devplacepy.responses import respond
|
||||
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP
|
||||
from devplacepy.schemas import ServiceDetailOut, ServicesOut
|
||||
from devplacepy.utils import require_admin, not_found
|
||||
from devplacepy.services.manager import service_manager
|
||||
from devplacepy.seo import base_seo_context, site_url, website_schema
|
||||
@@ -15,10 +17,24 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _services_payload() -> dict:
|
||||
services = service_manager.describe_all()
|
||||
return {
|
||||
"services": services[:ADMIN_LIST_CAP],
|
||||
"services_total": len(services),
|
||||
}
|
||||
|
||||
|
||||
def _service_payload(name: str) -> dict | None:
|
||||
svc = service_manager.get_service(name)
|
||||
if svc is None:
|
||||
return None
|
||||
return {"service": svc.describe()}
|
||||
|
||||
|
||||
@router.get("", response_class=HTMLResponse)
|
||||
async def services_page(request: Request):
|
||||
admin = require_admin(request)
|
||||
services = service_manager.describe_all()
|
||||
base = site_url(request)
|
||||
seo_ctx = base_seo_context(
|
||||
request,
|
||||
@@ -32,32 +48,33 @@ async def services_page(request: Request):
|
||||
],
|
||||
schemas=[website_schema(base)],
|
||||
)
|
||||
return templates.TemplateResponse(
|
||||
return respond(
|
||||
request,
|
||||
"services.html",
|
||||
{
|
||||
**seo_ctx,
|
||||
"request": request,
|
||||
"user": admin,
|
||||
"services": services,
|
||||
**_services_payload(),
|
||||
"admin_section": "services",
|
||||
},
|
||||
model=ServicesOut,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/data")
|
||||
async def services_json(request: Request):
|
||||
require_admin(request)
|
||||
return JSONResponse({"services": service_manager.describe_all()})
|
||||
return JSONResponse({"services": _services_payload()["services"]})
|
||||
|
||||
|
||||
@router.get("/{name}", response_class=HTMLResponse)
|
||||
async def service_detail(request: Request, name: str):
|
||||
admin = require_admin(request)
|
||||
svc = service_manager.get_service(name)
|
||||
if svc is None:
|
||||
payload = _service_payload(name)
|
||||
if payload is None:
|
||||
raise not_found("Service not found")
|
||||
info = svc.describe()
|
||||
info = payload["service"]
|
||||
base = site_url(request)
|
||||
seo_ctx = base_seo_context(
|
||||
request,
|
||||
@@ -73,27 +90,28 @@ async def service_detail(request: Request, name: str):
|
||||
schemas=[website_schema(base)],
|
||||
)
|
||||
tool_groups = tool_prefs.group_overview() if name == "devii" else None
|
||||
return templates.TemplateResponse(
|
||||
return respond(
|
||||
request,
|
||||
"service_detail.html",
|
||||
{
|
||||
**seo_ctx,
|
||||
"request": request,
|
||||
"user": admin,
|
||||
"service": info,
|
||||
**payload,
|
||||
"tool_groups": tool_groups,
|
||||
"admin_section": "services",
|
||||
},
|
||||
model=ServiceDetailOut,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{name}/data")
|
||||
async def service_detail_json(request: Request, name: str):
|
||||
require_admin(request)
|
||||
svc = service_manager.get_service(name)
|
||||
if svc is None:
|
||||
payload = _service_payload(name)
|
||||
if payload is None:
|
||||
return JSONResponse({"error": "unknown service"}, status_code=404)
|
||||
return JSONResponse({"service": svc.describe()})
|
||||
return JSONResponse(payload)
|
||||
|
||||
|
||||
def _audit_service(request: Request, admin: dict, name: str, event_key: str, summary: str, **kwargs: Any) -> None:
|
||||
|
||||
@@ -7,7 +7,7 @@ from devplacepy.responses import respond
|
||||
from devplacepy.schemas.statistics import StatisticsOut
|
||||
from devplacepy.seo import base_seo_context, site_url, website_schema
|
||||
from devplacepy.services.statistics.build import build_statistics_tab
|
||||
from devplacepy.services.statistics.common import VALID_TABS
|
||||
from devplacepy.services.statistics.common import MAX_WINDOW_HOURS, VALID_TABS
|
||||
from devplacepy.utils import require_admin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -32,10 +32,45 @@ TAB_LABELS = (
|
||||
)
|
||||
|
||||
|
||||
@router.get("/statistics", response_class=HTMLResponse)
|
||||
async def admin_statistics(request: Request, tab: str = "overview", hours: int = 168):
|
||||
admin = require_admin(request)
|
||||
STATISTICS_DEFAULT_HOURS = 168
|
||||
STATISTICS_DEFAULT_TOP_N = 10
|
||||
STATISTICS_MAX_TOP_N = 50
|
||||
STATISTICS_WINDOWS = (
|
||||
(24, "Last 24 hours"),
|
||||
(168, "Last 7 days"),
|
||||
(720, "Last 30 days"),
|
||||
(2160, "Last 90 days"),
|
||||
(0, "All time"),
|
||||
)
|
||||
|
||||
|
||||
def clamp_hours(hours: int) -> int:
|
||||
if hours <= 0:
|
||||
return 0
|
||||
return min(hours, MAX_WINDOW_HOURS)
|
||||
|
||||
|
||||
def statistics_view(tab: str, hours: int, compare: int, top_n: int) -> dict:
|
||||
active = tab if tab in VALID_TABS else "overview"
|
||||
bounded_top = max(1, min(top_n, STATISTICS_MAX_TOP_N))
|
||||
return build_statistics_tab(
|
||||
active,
|
||||
clamp_hours(hours),
|
||||
compare=bool(compare),
|
||||
top_n=bounded_top,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/statistics", response_class=HTMLResponse)
|
||||
async def admin_statistics(
|
||||
request: Request,
|
||||
tab: str = "overview",
|
||||
hours: int = STATISTICS_DEFAULT_HOURS,
|
||||
compare: int = 1,
|
||||
):
|
||||
admin = require_admin(request)
|
||||
initial = statistics_view(tab, hours, compare, STATISTICS_DEFAULT_TOP_N)
|
||||
active = initial["tab"]
|
||||
base = site_url(request)
|
||||
seo_ctx = base_seo_context(
|
||||
request,
|
||||
@@ -49,7 +84,6 @@ async def admin_statistics(request: Request, tab: str = "overview", hours: int =
|
||||
],
|
||||
schemas=[website_schema(base)],
|
||||
)
|
||||
initial = build_statistics_tab(active, hours, compare=True, top_n=10)
|
||||
tabs = [
|
||||
{"key": key, "label": label, "icon": icon, "active": key == active}
|
||||
for key, label, icon in TAB_LABELS
|
||||
@@ -64,7 +98,9 @@ async def admin_statistics(request: Request, tab: str = "overview", hours: int =
|
||||
"admin_section": "statistics",
|
||||
"tabs": tabs,
|
||||
"active_tab": active,
|
||||
"window_hours": hours,
|
||||
"window_hours": initial["window_hours"],
|
||||
"compare": initial["compare"],
|
||||
"windows": STATISTICS_WINDOWS,
|
||||
"initial": initial,
|
||||
},
|
||||
model=StatisticsOut,
|
||||
@@ -75,16 +111,9 @@ async def admin_statistics(request: Request, tab: str = "overview", hours: int =
|
||||
async def admin_statistics_data(
|
||||
request: Request,
|
||||
tab: str = "overview",
|
||||
hours: int = 168,
|
||||
hours: int = STATISTICS_DEFAULT_HOURS,
|
||||
compare: int = 1,
|
||||
top_n: int = 10,
|
||||
top_n: int = STATISTICS_DEFAULT_TOP_N,
|
||||
):
|
||||
require_admin(request)
|
||||
return JSONResponse(
|
||||
build_statistics_tab(
|
||||
tab,
|
||||
hours,
|
||||
compare=bool(compare),
|
||||
top_n=top_n,
|
||||
)
|
||||
)
|
||||
return JSONResponse(statistics_view(tab, hours, compare, top_n))
|
||||
|
||||
@@ -6,7 +6,12 @@ from typing import Annotated
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from devplacepy.database import get_projects_by_uids, get_table, get_users_by_uids
|
||||
from devplacepy.database import (
|
||||
build_pagination,
|
||||
get_projects_by_uids,
|
||||
get_table,
|
||||
get_users_by_uids,
|
||||
)
|
||||
from devplacepy.dependencies import json_or_form
|
||||
from devplacepy.models import (
|
||||
EditorPrefsForm,
|
||||
@@ -15,7 +20,7 @@ from devplacepy.models import (
|
||||
WorkspaceSuspendForm,
|
||||
)
|
||||
from devplacepy.responses import action_result, json_error, respond
|
||||
from devplacepy.routers.admin._shared import deny_senior, is_senior_admin
|
||||
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP, deny_senior, is_senior_admin
|
||||
from devplacepy.schemas import AdminWorkspacesOut
|
||||
from devplacepy.seo import base_seo_context
|
||||
from devplacepy.services.audit import record as audit
|
||||
@@ -49,8 +54,32 @@ async def _decorate(rows: list[dict]) -> list[dict]:
|
||||
return decorated
|
||||
|
||||
|
||||
def _all_workspaces() -> list[dict]:
|
||||
return list(get_table("instances").find(is_workspace=1, deleted_at=None))
|
||||
def _workspace_page(page: int) -> tuple[list[dict], dict]:
|
||||
table = get_table("instances")
|
||||
total = table.count(is_workspace=1, deleted_at=None)
|
||||
pagination = build_pagination(page, total)
|
||||
offset = (pagination["page"] - 1) * pagination["per_page"]
|
||||
rows = list(
|
||||
table.find(
|
||||
is_workspace=1,
|
||||
deleted_at=None,
|
||||
order_by=["-created_at"],
|
||||
_limit=pagination["per_page"],
|
||||
_offset=offset,
|
||||
)
|
||||
)
|
||||
return rows, pagination
|
||||
|
||||
|
||||
async def _workspaces_payload(page: int) -> dict:
|
||||
rows, pagination = _workspace_page(page)
|
||||
open_flags = flags.list_flags()
|
||||
return {
|
||||
"workspaces": await _decorate(rows),
|
||||
"flags": open_flags[:ADMIN_LIST_CAP],
|
||||
"flags_total": len(open_flags),
|
||||
"pagination": pagination,
|
||||
}
|
||||
|
||||
|
||||
def _instance_or_404(uid: str) -> dict:
|
||||
@@ -75,13 +104,12 @@ def _audit(request: Request, admin: dict, event_key: str, instance: dict, **extr
|
||||
|
||||
|
||||
@router.get("/workspaces")
|
||||
async def admin_workspaces(request: Request):
|
||||
async def admin_workspaces(request: Request, page: int = 1):
|
||||
admin = require_admin(request)
|
||||
if not isinstance(admin, dict):
|
||||
return admin
|
||||
context = {
|
||||
"workspaces": await _decorate(_all_workspaces()),
|
||||
"flags": flags.list_flags(),
|
||||
**await _workspaces_payload(page),
|
||||
"admin_section": "workspaces",
|
||||
"user": admin,
|
||||
**base_seo_context(
|
||||
@@ -100,13 +128,11 @@ async def admin_workspaces(request: Request):
|
||||
|
||||
|
||||
@router.get("/workspaces/data")
|
||||
async def admin_workspaces_data(request: Request):
|
||||
async def admin_workspaces_data(request: Request, page: int = 1):
|
||||
admin = require_admin(request)
|
||||
if not isinstance(admin, dict):
|
||||
return admin
|
||||
return JSONResponse(
|
||||
{"workspaces": await _decorate(_all_workspaces()), "flags": flags.list_flags()}
|
||||
)
|
||||
return JSONResponse(await _workspaces_payload(page))
|
||||
|
||||
|
||||
@router.post("/workspaces/{uid}/suspend")
|
||||
|
||||
@@ -52,13 +52,14 @@ async def login_page(request: Request, next: str | None = None):
|
||||
|
||||
@router.post("/login")
|
||||
async def login(request: Request, data: Annotated[LoginForm, Depends(json_or_form(LoginForm))]):
|
||||
email = data.email.strip().lower()
|
||||
identifier = data.email.strip()
|
||||
email = identifier.lower()
|
||||
password = data.password
|
||||
remember_me = data.remember_me == "on"
|
||||
|
||||
errors = []
|
||||
users = get_table("users")
|
||||
user = users.find_one(email=email)
|
||||
user = users.find_one(email=email) or users.find_one(username=identifier)
|
||||
|
||||
if not user or not await verify_password_async(password, user["password_hash"]):
|
||||
errors.append("Invalid email or password")
|
||||
|
||||
@@ -22,7 +22,7 @@ async def token(
|
||||
request: Request,
|
||||
data: Annotated[LoginForm, Depends(json_or_form(LoginForm))],
|
||||
):
|
||||
identifier = data.email.strip().lower()
|
||||
identifier = data.email.strip()
|
||||
password = data.password
|
||||
|
||||
if not identifier or not password:
|
||||
@@ -32,7 +32,7 @@ async def token(
|
||||
)
|
||||
|
||||
users = get_table("users")
|
||||
user = users.find_one(email=identifier) or users.find_one(
|
||||
user = users.find_one(email=identifier.lower()) or users.find_one(
|
||||
username=identifier
|
||||
)
|
||||
|
||||
|
||||
@@ -27,6 +27,13 @@ def _war_error(request: Request, message: str, redirect_url: str):
|
||||
)
|
||||
|
||||
|
||||
def _viewable_war(war_uid: str, user: dict | None) -> dict:
|
||||
war = store.get_war(war_uid)
|
||||
if not store.war_viewable(war, user):
|
||||
raise not_found("Battle not found")
|
||||
return war
|
||||
|
||||
|
||||
def _post_url(war: dict) -> str:
|
||||
return resolve_object_url("post", war["post_uid"])
|
||||
|
||||
@@ -76,7 +83,7 @@ async def battles_page(
|
||||
@router.get("/{war_uid}")
|
||||
async def battle_state(request: Request, war_uid: str):
|
||||
user = get_current_user(request)
|
||||
serialized = store.get_war_serialized(store.get_war(war_uid), user)
|
||||
serialized = store.get_war_serialized(_viewable_war(war_uid, user), user)
|
||||
if not serialized:
|
||||
raise not_found("Battle not found")
|
||||
return JSONResponse(WarOut.model_validate(serialized).model_dump())
|
||||
@@ -86,9 +93,7 @@ async def battle_state(request: Request, war_uid: str):
|
||||
async def battle_events(
|
||||
request: Request, war_uid: str, after: int = 0, limit: int = rules.EVENT_LIMIT_DEFAULT
|
||||
):
|
||||
war = store.resolve_if_due(store.get_war(war_uid))
|
||||
if not war:
|
||||
raise not_found("Battle not found")
|
||||
war = store.resolve_if_due(_viewable_war(war_uid, get_current_user(request)))
|
||||
events = store.events_for(war_uid, after_seq=after, limit=limit)
|
||||
return JSONResponse(
|
||||
WarEventsOut.model_validate(
|
||||
@@ -104,9 +109,7 @@ async def join_battle(
|
||||
data: Annotated[WarJoinForm, Depends(json_or_form(WarJoinForm))],
|
||||
):
|
||||
user = require_user(request)
|
||||
war = store.get_war(war_uid)
|
||||
if not war:
|
||||
raise not_found("Battle not found")
|
||||
war = _viewable_war(war_uid, user)
|
||||
url = _post_url(war)
|
||||
try:
|
||||
war = store.join_war(war, user, data.faction, request)
|
||||
@@ -119,9 +122,7 @@ async def join_battle(
|
||||
@router.post("/{war_uid}/fight")
|
||||
async def fight_battle(request: Request, war_uid: str):
|
||||
user = require_user(request)
|
||||
war = store.get_war(war_uid)
|
||||
if not war:
|
||||
raise not_found("Battle not found")
|
||||
war = _viewable_war(war_uid, user)
|
||||
url = _post_url(war)
|
||||
try:
|
||||
war, damage = store.fight(war, user, request)
|
||||
|
||||
@@ -14,7 +14,7 @@ The **Legal** section (`SECTION_LEGAL`, in the `AUDIENCE_START` tier so it is on
|
||||
|
||||
`DOCS_PAGES` entries take optional `admin: True` (hidden + 404 for non-admins, but still indexed and surfaced only to admins by `docs_search`) and `section: "..."` (a nested sidebar group rendered by `docs_base.html`). The sidebar groups `section`s under four ordered **audience tiers** (`AUDIENCES` in `routers/docs/pages.py`): `Start here` (General), `Build with the API` (API, Components, Styles), `Contribute and internals` (Architecture, Services, Devii internals, Bots internals, Testing, Claude Code), and `Operate` (Administration, Production). `nav_groups(visible_pages)` builds the `[(audience, [(section, [pages])])]` tree from the flat visible-page list (so a section's pages collect under one heading regardless of `DOCS_PAGES` order or the API/Administration interleave from `api_doc_pages()`); `views.py` passes it as `nav`, and `docs_base.html` renders an audience super-header (`.sidebar-tier`) above each section subheading (`.sidebar-subheading`). `DOCS_PAGES` stays the canonical list for search/export/routing - the tiering is sidebar-only.
|
||||
|
||||
The public `getting-started` page (`SECTION_GENERAL`) is the new-contributor on-ramp (install/run, the four-faces workflow, validation); gate its deep-internals links with `{% if is_admin(user) %}` so guests get no 404s. Keep one canonical home per concept: the `auth` API group intro in `docs_api.py` defers method detail to the `authentication` prose page rather than re-listing the four methods. The member-facing `devii` prose page is functional; admins also get a `Devii internals` section of `devii-*` technical subpages.
|
||||
The public `getting-started` page (`SECTION_GENERAL`) is the new-contributor on-ramp (install/run, the four-faces workflow, validation); gate its deep-internals links with `{% if is_admin(user) %}` so guests get no 404s. Keep one canonical home per concept: the `auth` API group intro in `docs_api.py` defers method detail to the `authentication` prose page rather than re-listing the auth methods (three account credentials: username+password, email+password, personal API key; the prose page is canonical for precedence, `DEVPLACE_API_KEY`, the `GET /profile` account fetch, and the separate DevRant/WebSocket auth domains). The member-facing `devii` prose page is functional; admins also get a `Devii internals` section of `devii-*` technical subpages.
|
||||
|
||||
## Single source of truth
|
||||
|
||||
|
||||
@@ -328,6 +328,12 @@ DOCS_PAGES = [
|
||||
"kind": "prose",
|
||||
"section": SECTION_COMPONENTS,
|
||||
},
|
||||
{
|
||||
"slug": "component-dp-action-menu",
|
||||
"title": "dp-action-menu",
|
||||
"kind": "prose",
|
||||
"section": SECTION_COMPONENTS,
|
||||
},
|
||||
{
|
||||
"slug": "component-dp-lightbox",
|
||||
"title": "dp-lightbox",
|
||||
@@ -388,6 +394,12 @@ DOCS_PAGES = [
|
||||
"kind": "prose",
|
||||
"section": SECTION_API,
|
||||
},
|
||||
{
|
||||
"slug": "mcp",
|
||||
"title": "MCP server",
|
||||
"kind": "prose",
|
||||
"section": SECTION_API,
|
||||
},
|
||||
{
|
||||
"slug": "xmlrpc",
|
||||
"title": "XML-RPC API",
|
||||
|
||||
@@ -163,6 +163,15 @@ async def docs_page(request: Request, slug: str):
|
||||
prose_html = None
|
||||
group = None
|
||||
if page["kind"] == "prose":
|
||||
mcp_url = ""
|
||||
if user:
|
||||
from devplacepy.services import mcp_tokens as mcp_store
|
||||
|
||||
mcp_row = mcp_store.get_active(user["uid"])
|
||||
if mcp_row:
|
||||
from devplacepy.routers.mcp import mcp_url_for
|
||||
|
||||
mcp_url = mcp_url_for(request, mcp_row["token"])
|
||||
prose_html = docs_prose.render_prose(
|
||||
slug,
|
||||
{
|
||||
@@ -170,6 +179,7 @@ async def docs_page(request: Request, slug: str):
|
||||
"user": user,
|
||||
"username": user.get("username") if user else "",
|
||||
"api_key": user.get("api_key") if user else "",
|
||||
"mcp_url": mcp_url,
|
||||
},
|
||||
)
|
||||
elif page.get("dynamic"):
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
"""Per-user MCP endpoint backed by the Devii tool catalog.
|
||||
|
||||
Transport only: resolves ``/mcp/{token}`` to the token owner, serves the
|
||||
MCP Streamable HTTP surface (``initialize``, ``tools/list``, ``tools/call``
|
||||
over JSON-RPC plus a minimal SSE GET), and maps errors to JSON-RPC. Tool
|
||||
logic lives in the Devii catalog and dispatcher; nothing is reimplemented
|
||||
here.
|
||||
|
||||
The official Python MCP SDK is deliberately not a dependency: the surface we
|
||||
need (three methods, JSON-RPC errors, one SSE stream) is small, and the
|
||||
codebase prefers narrow dependencies over new ones.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
|
||||
from devplacepy.seo import site_url
|
||||
from devplacepy.services import presence
|
||||
from devplacepy.services.audit import record as audit
|
||||
from devplacepy.utils import (
|
||||
_user_from_mcp_token,
|
||||
is_admin,
|
||||
is_primary_admin,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("mcp.router")
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_UNSET = object()
|
||||
|
||||
MCP_SERVER_NAME = "devplace"
|
||||
MCP_SERVER_VERSION = "1.0"
|
||||
|
||||
_ERROR_CODES = {
|
||||
"tool_input_error",
|
||||
"auth_required",
|
||||
"tool_disabled",
|
||||
"network_error",
|
||||
"upstream_error",
|
||||
"llm_error",
|
||||
"unexpected",
|
||||
"error",
|
||||
}
|
||||
|
||||
|
||||
def mcp_url_for(request: Request, token: str) -> str:
|
||||
return f"{site_url(request).rstrip('/')}/mcp/{token}"
|
||||
|
||||
|
||||
def _resolve_mcp_user(request: Request, token: str) -> Optional[dict]:
|
||||
cached = getattr(request.state, "_mcp_user", _UNSET)
|
||||
if cached is not _UNSET:
|
||||
return cached
|
||||
user = _user_from_mcp_token(token)
|
||||
try:
|
||||
request.state._mcp_user = user
|
||||
except Exception:
|
||||
pass
|
||||
return user
|
||||
|
||||
|
||||
def _flags(user: dict) -> tuple[bool, bool, bool]:
|
||||
return True, bool(is_admin(user)), bool(is_primary_admin(user))
|
||||
|
||||
|
||||
def _tool_schemas(user: dict) -> list[dict[str, Any]]:
|
||||
from devplacepy.services.devii.actions.catalog import PLATFORM_CATALOG
|
||||
|
||||
authenticated, admin, primary = _flags(user)
|
||||
return PLATFORM_CATALOG.tool_schemas_for(authenticated, admin, primary)
|
||||
|
||||
|
||||
def _mcp_tools(user: dict) -> list[dict[str, Any]]:
|
||||
tools = []
|
||||
for schema in _tool_schemas(user):
|
||||
function = schema.get("function", {})
|
||||
tools.append(
|
||||
{
|
||||
"name": function.get("name", ""),
|
||||
"description": function.get("description", ""),
|
||||
"inputSchema": function.get("parameters", {"type": "object"}),
|
||||
}
|
||||
)
|
||||
return tools
|
||||
|
||||
|
||||
def _jsonrpc_error(code: int, message: str, request_id: Any = None) -> dict:
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": request_id,
|
||||
"error": {"code": code, "message": message},
|
||||
}
|
||||
|
||||
|
||||
def _jsonrpc_result(result: Any, request_id: Any) -> dict:
|
||||
return {"jsonrpc": "2.0", "id": request_id, "result": result}
|
||||
|
||||
|
||||
def _build_dispatcher(user: dict, base_url: str):
|
||||
import dataclasses
|
||||
|
||||
from devplacepy.database import db
|
||||
from devplacepy.services.devii.actions.catalog import PLATFORM_CATALOG
|
||||
from devplacepy.services.devii.actions.dispatcher import Dispatcher
|
||||
from devplacepy.services.devii.agentic import AgenticController, LessonStore
|
||||
from devplacepy.services.devii.config import load_settings
|
||||
from devplacepy.services.devii.http_client import PlatformClient
|
||||
from devplacepy.services.devii.tasks import TaskController, TaskStore
|
||||
|
||||
settings = dataclasses.replace(
|
||||
load_settings(),
|
||||
base_url=base_url.rstrip("/"),
|
||||
platform_api_key=user.get("api_key", ""),
|
||||
)
|
||||
client = PlatformClient(
|
||||
settings.base_url, settings.timeout_seconds, user.get("api_key", "")
|
||||
)
|
||||
lessons = LessonStore(db, "user", user["uid"])
|
||||
tasks = TaskController(TaskStore(db, "user", user["uid"], operator=True))
|
||||
agentic = AgenticController(lessons, settings)
|
||||
_, admin, primary = _flags(user)
|
||||
dispatcher = Dispatcher(
|
||||
PLATFORM_CATALOG,
|
||||
client,
|
||||
settings,
|
||||
tasks,
|
||||
agentic,
|
||||
is_admin=admin,
|
||||
is_primary_admin=primary,
|
||||
owner_kind="user",
|
||||
owner_id=user["uid"],
|
||||
)
|
||||
return dispatcher, client
|
||||
|
||||
|
||||
async def _handle_single(
|
||||
request: Request, user: dict, payload: dict
|
||||
) -> Optional[dict]:
|
||||
method = payload.get("method", "")
|
||||
request_id = payload.get("id")
|
||||
params = payload.get("params") or {}
|
||||
if not isinstance(params, dict):
|
||||
params = {}
|
||||
|
||||
if method == "initialize":
|
||||
requested = params.get("protocolVersion", "2025-06-18")
|
||||
tools = _mcp_tools(user)
|
||||
logger.info(
|
||||
"MCP initialize for %s: %d tools offered",
|
||||
user.get("username", ""),
|
||||
len(tools),
|
||||
)
|
||||
return _jsonrpc_result(
|
||||
{
|
||||
"protocolVersion": requested,
|
||||
"capabilities": {"tools": {"listChanged": False}},
|
||||
"serverInfo": {
|
||||
"name": MCP_SERVER_NAME,
|
||||
"version": MCP_SERVER_VERSION,
|
||||
},
|
||||
"catalogCount": len(tools),
|
||||
},
|
||||
request_id,
|
||||
)
|
||||
|
||||
if method == "notifications/initialized":
|
||||
return None
|
||||
|
||||
if method == "ping":
|
||||
return _jsonrpc_result({}, request_id)
|
||||
|
||||
if method == "tools/list":
|
||||
return _jsonrpc_result({"tools": _mcp_tools(user)}, request_id)
|
||||
|
||||
if method == "tools/call":
|
||||
name = str(params.get("name", ""))
|
||||
arguments = params.get("arguments") or {}
|
||||
if not isinstance(arguments, dict):
|
||||
arguments = {}
|
||||
from devplacepy.services.devii.actions.catalog import PLATFORM_CATALOG
|
||||
|
||||
if name not in PLATFORM_CATALOG.by_name():
|
||||
audit.record(
|
||||
request,
|
||||
"security.authz.denied",
|
||||
user=user,
|
||||
origin="mcp",
|
||||
result="denied",
|
||||
summary=f"MCP unknown tool: {name}",
|
||||
metadata={"tool": name},
|
||||
)
|
||||
return _jsonrpc_error(-32601, f"Method not found: {name}", request_id)
|
||||
dispatcher, client = _build_dispatcher(user, site_url(request))
|
||||
try:
|
||||
text = await dispatcher.dispatch(name, arguments)
|
||||
finally:
|
||||
try:
|
||||
await client.aclose()
|
||||
except Exception:
|
||||
pass
|
||||
presence.touch(user["uid"])
|
||||
audit.record(
|
||||
request,
|
||||
"mcp.tools.call",
|
||||
user=user,
|
||||
target_label=name,
|
||||
origin="mcp",
|
||||
summary=f"MCP {user.get('username', '')} called {name}",
|
||||
metadata={"tool": name},
|
||||
)
|
||||
is_error = False
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
if isinstance(parsed, dict) and parsed.get("error") in _ERROR_CODES:
|
||||
is_error = True
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return _jsonrpc_result(
|
||||
{
|
||||
"content": [{"type": "text", "text": text}],
|
||||
"isError": is_error,
|
||||
},
|
||||
request_id,
|
||||
)
|
||||
|
||||
return _jsonrpc_error(-32601, f"Method not found: {method}", request_id)
|
||||
|
||||
|
||||
@router.post("/mcp/{token}")
|
||||
async def mcp_endpoint(request: Request, token: str):
|
||||
user = _resolve_mcp_user(request, token)
|
||||
if not user:
|
||||
return JSONResponse({"error": "unknown token"}, status_code=404)
|
||||
try:
|
||||
body = await request.json()
|
||||
except (ValueError, TypeError):
|
||||
return JSONResponse(
|
||||
_jsonrpc_error(-32700, "Parse error"), status_code=200
|
||||
)
|
||||
if isinstance(body, list):
|
||||
replies = []
|
||||
for item in body:
|
||||
if isinstance(item, dict):
|
||||
reply = await _handle_single(request, user, item)
|
||||
if reply is not None:
|
||||
replies.append(reply)
|
||||
return JSONResponse(replies)
|
||||
if not isinstance(body, dict):
|
||||
return JSONResponse(
|
||||
_jsonrpc_error(-32600, "Invalid Request"), status_code=200
|
||||
)
|
||||
reply = await _handle_single(request, user, body)
|
||||
if reply is None:
|
||||
return JSONResponse({"jsonrpc": "2.0", "id": body.get("id"), "result": {}})
|
||||
return JSONResponse(reply)
|
||||
|
||||
|
||||
@router.get("/mcp/{token}")
|
||||
async def mcp_stream(request: Request, token: str):
|
||||
user = _resolve_mcp_user(request, token)
|
||||
if not user:
|
||||
return JSONResponse({"error": "unknown token"}, status_code=404)
|
||||
|
||||
async def events():
|
||||
yield ": connected\n\n"
|
||||
|
||||
return StreamingResponse(events(), media_type="text/event-stream")
|
||||
@@ -4,7 +4,7 @@ import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from devplacepy.database import get_table, db
|
||||
from devplacepy.database import get_table, db, get_notification_grouping_enabled, notification_group_key
|
||||
from devplacepy.templating import (
|
||||
clear_unread_cache,
|
||||
jinja_unread_count,
|
||||
@@ -20,6 +20,7 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
PAGE_SIZE = 25
|
||||
GROUP_FETCH_LIMIT = 250
|
||||
|
||||
|
||||
def _group_label(created_at: str) -> str:
|
||||
@@ -42,24 +43,28 @@ def _group_label(created_at: str) -> str:
|
||||
@router.get("", response_class=HTMLResponse)
|
||||
async def notifications_page(request: Request, before: str = None):
|
||||
user = require_user(request)
|
||||
|
||||
grouping = get_notification_grouping_enabled(user["uid"])
|
||||
next_cursor = None
|
||||
groups = []
|
||||
try:
|
||||
notifications_table = get_table("notifications")
|
||||
filters = {"user_uid": user["uid"]}
|
||||
if before:
|
||||
filters["created_at"] = {"<": before}
|
||||
limit = GROUP_FETCH_LIMIT if grouping else PAGE_SIZE + 1
|
||||
raw_notifications = list(
|
||||
notifications_table.find(
|
||||
**filters, order_by=["-created_at"], _limit=PAGE_SIZE + 1
|
||||
**filters, order_by=["-created_at"], _limit=limit
|
||||
)
|
||||
)
|
||||
|
||||
has_more = len(raw_notifications) > PAGE_SIZE
|
||||
raw_notifications = raw_notifications[:PAGE_SIZE]
|
||||
if has_more and raw_notifications:
|
||||
next_cursor = raw_notifications[-1]["created_at"]
|
||||
|
||||
if grouping:
|
||||
has_more_rows = len(raw_notifications) >= GROUP_FETCH_LIMIT
|
||||
raw_notifications = raw_notifications[:GROUP_FETCH_LIMIT]
|
||||
else:
|
||||
has_more_rows = len(raw_notifications) > PAGE_SIZE
|
||||
raw_notifications = raw_notifications[:PAGE_SIZE]
|
||||
if has_more_rows and raw_notifications:
|
||||
next_cursor = raw_notifications[-1]["created_at"]
|
||||
enriched = []
|
||||
if raw_notifications:
|
||||
from devplacepy.database import get_users_by_uids
|
||||
@@ -78,20 +83,51 @@ async def notifications_page(request: Request, before: str = None):
|
||||
"time_ago": time_ago(n["created_at"]),
|
||||
}
|
||||
)
|
||||
|
||||
groups = []
|
||||
current_label = None
|
||||
current_entries = []
|
||||
current_event_entries = []
|
||||
event_index = {}
|
||||
group_count = 0
|
||||
last_consumed = None
|
||||
for item in enriched:
|
||||
label = _group_label(item["notification"]["created_at"])
|
||||
if label != current_label:
|
||||
if current_entries:
|
||||
groups.append({"label": current_label, "entries": current_entries})
|
||||
if current_entries or current_event_entries:
|
||||
groups.append({"label": current_label, "entries": current_entries, "event_entries": current_event_entries})
|
||||
current_label = label
|
||||
current_entries = []
|
||||
current_entries.append(item)
|
||||
if current_entries:
|
||||
groups.append({"label": current_label, "entries": current_entries})
|
||||
current_event_entries = []
|
||||
event_index = {}
|
||||
if not grouping:
|
||||
current_entries.append(item)
|
||||
continue
|
||||
key = notification_group_key(item["notification"])
|
||||
key_text = "\x1f".join(key)
|
||||
existing = event_index.get(key_text)
|
||||
if existing is None:
|
||||
if group_count >= PAGE_SIZE:
|
||||
continue
|
||||
existing = {
|
||||
"key": key_text,
|
||||
"count": 0,
|
||||
"unread": False,
|
||||
"actors": [],
|
||||
"latest": item,
|
||||
}
|
||||
event_index[key_text] = existing
|
||||
current_event_entries.append(existing)
|
||||
group_count += 1
|
||||
existing["count"] += 1
|
||||
if not item["notification"].get("read"):
|
||||
existing["unread"] = True
|
||||
actor = item["actor"]
|
||||
if actor and all(a.get("uid") != actor.get("uid") for a in existing["actors"]) and len(existing["actors"]) < 3:
|
||||
existing["actors"].append(actor)
|
||||
last_consumed = item["notification"]["created_at"]
|
||||
if current_entries or current_event_entries:
|
||||
groups.append({"label": current_label, "entries": current_entries, "event_entries": current_event_entries})
|
||||
if grouping and (has_more_rows or group_count >= PAGE_SIZE) and last_consumed:
|
||||
next_cursor = last_consumed
|
||||
except Exception as e:
|
||||
logger.exception(f"Error loading notifications: {e}")
|
||||
groups = []
|
||||
@@ -114,11 +150,28 @@ async def notifications_page(request: Request, before: str = None):
|
||||
"user": user,
|
||||
"notification_groups": groups,
|
||||
"next_cursor": next_cursor,
|
||||
"grouping": grouping,
|
||||
},
|
||||
model=NotificationsOut,
|
||||
)
|
||||
|
||||
|
||||
def _mark_group_read(user_uid: str, row) -> int:
|
||||
notifications_table = get_table("notifications")
|
||||
if not get_notification_grouping_enabled(user_uid):
|
||||
if not row["read"]:
|
||||
notifications_table.update({"id": row["id"], "read": True}, ["id"])
|
||||
return 1
|
||||
return 0
|
||||
key = notification_group_key(row)
|
||||
marked = 0
|
||||
for other in notifications_table.find(user_uid=user_uid, read=False):
|
||||
if notification_group_key(other) == key:
|
||||
notifications_table.update({"id": other["id"], "read": True}, ["id"])
|
||||
marked += 1
|
||||
return marked
|
||||
|
||||
|
||||
@router.get("/counts")
|
||||
async def unread_counts(request: Request):
|
||||
user = get_current_user(request)
|
||||
@@ -140,7 +193,7 @@ async def open_notification(request: Request, notification_uid: str):
|
||||
if not n or n["user_uid"] != user["uid"]:
|
||||
return action_result(request, "/notifications")
|
||||
if not n["read"]:
|
||||
notifications_table.update({"id": n["id"], "read": True}, ["id"])
|
||||
_mark_group_read(user["uid"], n)
|
||||
clear_unread_cache(user["uid"])
|
||||
audit.record(
|
||||
request,
|
||||
@@ -160,7 +213,7 @@ async def mark_read(request: Request, notification_uid: str):
|
||||
notifications_table = get_table("notifications")
|
||||
n = notifications_table.find_one(uid=notification_uid)
|
||||
if n and n["user_uid"] == user["uid"]:
|
||||
notifications_table.update({"id": n["id"], "read": True}, ["id"])
|
||||
_mark_group_read(user["uid"], n)
|
||||
clear_unread_cache(user["uid"])
|
||||
audit.record(
|
||||
request,
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
import logging
|
||||
from typing import Annotated
|
||||
from fastapi import Depends, APIRouter, Request
|
||||
from devplacepy.models import CustomizationToggleForm
|
||||
from devplacepy.database import set_customization_pref
|
||||
from devplacepy.models import CustomizationToggleForm, EnterToSubmitForm
|
||||
from devplacepy.database import set_customization_pref, set_enter_to_submit
|
||||
from devplacepy.responses import action_result
|
||||
from devplacepy.services.audit import record as audit
|
||||
|
||||
@@ -47,6 +47,31 @@ async def set_customization_global(
|
||||
):
|
||||
return _toggle_customization(request, username, "global", data.value)
|
||||
|
||||
@router.post("/{username}/enter-to-submit")
|
||||
async def set_enter_to_submit_route(
|
||||
request: Request,
|
||||
username: str,
|
||||
data: Annotated[EnterToSubmitForm, Depends(json_or_form(EnterToSubmitForm))],
|
||||
):
|
||||
target, denied = resolve_customization_target(request, username)
|
||||
if denied is not None:
|
||||
return denied
|
||||
set_enter_to_submit(target["uid"], data.value)
|
||||
audit.record(
|
||||
request,
|
||||
"profile.enter_to_submit.toggle",
|
||||
target_type="user",
|
||||
target_uid=target["uid"],
|
||||
target_label=target["username"],
|
||||
old_value=0 if data.value else 1,
|
||||
new_value=1 if data.value else 0,
|
||||
summary=f"{'enabled' if data.value else 'disabled'} Enter to send for {target['username']}",
|
||||
links=[audit.target("user", target["uid"], target["username"])],
|
||||
)
|
||||
url = f"/profile/{target['username']}"
|
||||
return action_result(request, url, data={"url": url, "enter_to_submit": data.value})
|
||||
|
||||
|
||||
@router.post("/{username}/customization/pagetype")
|
||||
async def set_customization_pagetype(
|
||||
request: Request,
|
||||
|
||||
@@ -11,6 +11,9 @@ from devplacepy.database import (
|
||||
is_listed,
|
||||
get_table,
|
||||
get_customization_prefs,
|
||||
get_enter_to_submit,
|
||||
get_notification_grouping_enabled,
|
||||
get_notification_throttle_enabled,
|
||||
get_notification_prefs,
|
||||
get_user_stars,
|
||||
get_user_rank,
|
||||
@@ -39,7 +42,7 @@ from devplacepy.database.awards import (
|
||||
get_prominent_award,
|
||||
get_user_awards,
|
||||
)
|
||||
from devplacepy.content import can_view_project, enrich_items
|
||||
from devplacepy.content import can_view_project, enrich_items, discoverable_target_rows
|
||||
from devplacepy.routers.nodes.me import _me as node_me_view
|
||||
from devplacepy.routers.profile.consent import consent_view
|
||||
from devplacepy.services.moderation.deletion import grace_hours
|
||||
@@ -155,6 +158,13 @@ async def profile_page(
|
||||
profile_user = users.find_one(username=username)
|
||||
if not profile_user:
|
||||
raise not_found("Profile not found")
|
||||
if tab == "mcp":
|
||||
_mcp_owner = bool(
|
||||
current_user and current_user["uid"] == profile_user["uid"]
|
||||
)
|
||||
_mcp_admin = bool(current_user and current_user.get("role") == "Admin")
|
||||
if not (_mcp_owner or _mcp_admin):
|
||||
tab = "posts"
|
||||
viewing_self = bool(current_user and current_user["uid"] == profile_user["uid"])
|
||||
if current_user:
|
||||
mark_notifications_read_by_target(
|
||||
@@ -277,11 +287,16 @@ async def profile_page(
|
||||
}
|
||||
)
|
||||
comments_table = get_table("comments")
|
||||
for c in comments_table.find(
|
||||
user_uid=profile_user["uid"],
|
||||
deleted_at=None,
|
||||
order_by=["-created_at"],
|
||||
_limit=10,
|
||||
for c in discoverable_target_rows(
|
||||
list(
|
||||
comments_table.find(
|
||||
user_uid=profile_user["uid"],
|
||||
deleted_at=None,
|
||||
order_by=["-created_at"],
|
||||
_limit=10,
|
||||
)
|
||||
),
|
||||
current_user,
|
||||
):
|
||||
target_uid = c.get("target_uid", c.get("post_uid", ""))
|
||||
target_type = c.get("target_type", "post")
|
||||
@@ -322,6 +337,54 @@ async def profile_page(
|
||||
viewer_is_admin = bool(current_user and current_user.get("role") == "Admin")
|
||||
can_view_api_key = bool(current_user and (is_owner or viewer_is_admin))
|
||||
api_key = profile_user.get("api_key") if can_view_api_key else None
|
||||
email = profile_user.get("email") if can_view_api_key else None
|
||||
mcp_url = None
|
||||
mcp_created_at = None
|
||||
mcp_capabilities = []
|
||||
if tab == "mcp" and can_view_api_key:
|
||||
from devplacepy.services import mcp_tokens as mcp_store
|
||||
|
||||
mcp_row = mcp_store.get_active(profile_user["uid"])
|
||||
if mcp_row:
|
||||
from devplacepy.routers.mcp import mcp_url_for
|
||||
|
||||
mcp_url = mcp_url_for(request, mcp_row["token"])
|
||||
mcp_created_at = mcp_row.get("created_at", "")
|
||||
if current_user:
|
||||
from devplacepy.services.devii.actions.catalog import (
|
||||
CATALOG_GROUPS,
|
||||
PLATFORM_CATALOG,
|
||||
)
|
||||
from devplacepy.utils import is_admin as _is_admin_fn
|
||||
|
||||
from devplacepy.utils import is_primary_admin as _is_primary_admin_fn
|
||||
|
||||
viewer_schemas = PLATFORM_CATALOG.tool_schemas_for(
|
||||
True,
|
||||
bool(_is_admin_fn(profile_user)),
|
||||
bool(_is_primary_admin_fn(profile_user)),
|
||||
)
|
||||
viewer_names = {
|
||||
schema.get("function", {}).get("name", "")
|
||||
for schema in viewer_schemas
|
||||
}
|
||||
mcp_capabilities = [
|
||||
{
|
||||
"group": group,
|
||||
"example": next(
|
||||
(
|
||||
action.name
|
||||
for action in actions
|
||||
if action.name in viewer_names
|
||||
),
|
||||
"",
|
||||
),
|
||||
}
|
||||
for group, actions in CATALOG_GROUPS.items()
|
||||
]
|
||||
mcp_capabilities = [
|
||||
entry for entry in mcp_capabilities if entry["example"]
|
||||
]
|
||||
ai_correction_enabled = (
|
||||
bool(profile_user.get("ai_correction_enabled")) if is_owner else False
|
||||
)
|
||||
@@ -390,6 +453,19 @@ async def profile_page(
|
||||
if (tab == "notifications" and can_manage_customization)
|
||||
else []
|
||||
)
|
||||
enter_to_submit = (
|
||||
get_enter_to_submit(profile_user["uid"]) if can_manage_customization else True
|
||||
)
|
||||
notif_grouping_enabled = (
|
||||
get_notification_grouping_enabled(profile_user["uid"])
|
||||
if (tab == "notifications" and can_manage_customization)
|
||||
else True
|
||||
)
|
||||
notif_throttle_enabled = (
|
||||
get_notification_throttle_enabled(profile_user["uid"])
|
||||
if (tab == "notifications" and can_manage_customization)
|
||||
else True
|
||||
)
|
||||
notif_telegram_paired = (
|
||||
telegram_store.is_paired(profile_user["uid"])
|
||||
if (tab == "notifications" and can_manage_customization)
|
||||
@@ -485,6 +561,10 @@ async def profile_page(
|
||||
"media_pagination": media_pagination,
|
||||
"can_view_api_key": can_view_api_key,
|
||||
"api_key": api_key,
|
||||
"email": email,
|
||||
"mcp_url": mcp_url,
|
||||
"mcp_created_at": mcp_created_at,
|
||||
"mcp_capabilities": mcp_capabilities,
|
||||
"ai_correction_enabled": ai_correction_enabled,
|
||||
"ai_correction_sync": ai_correction_sync,
|
||||
"ai_correction_prompt": ai_correction_prompt,
|
||||
@@ -500,6 +580,9 @@ async def profile_page(
|
||||
"can_manage_customization": can_manage_customization,
|
||||
"cust_disable_global": customization_prefs["disable_global"],
|
||||
"cust_disable_pagetype": customization_prefs["disable_pagetype"],
|
||||
"enter_to_submit": enter_to_submit,
|
||||
"notif_grouping_enabled": notif_grouping_enabled,
|
||||
"notif_throttle_enabled": notif_throttle_enabled,
|
||||
"notification_prefs": notification_prefs,
|
||||
"consents": consents,
|
||||
"node_me": node_me,
|
||||
@@ -594,7 +677,62 @@ async def regenerate_api_key(request: Request):
|
||||
summary=f"{user['username']} regenerated their API key",
|
||||
links=[audit.target("user", user["uid"], user["username"])],
|
||||
)
|
||||
return JSONResponse({"api_key": new_key})
|
||||
return JSONResponse(
|
||||
{
|
||||
"api_key": new_key,
|
||||
"username": user["username"],
|
||||
"email": user["email"],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.post("/mcp/regenerate")
|
||||
async def mcp_regenerate(request: Request):
|
||||
user = require_user(request)
|
||||
from devplacepy.routers.mcp import mcp_url_for
|
||||
from devplacepy.services import mcp_tokens as mcp_store
|
||||
|
||||
result = mcp_store.regenerate(user)
|
||||
url = mcp_url_for(request, result["token"])
|
||||
logger.info(f"MCP URL regenerated for {user['username']}")
|
||||
audit.record(
|
||||
request,
|
||||
"profile.mcp.regenerate",
|
||||
user=user,
|
||||
target_type="user",
|
||||
target_uid=user["uid"],
|
||||
target_label=user["username"],
|
||||
summary=f"{user['username']} regenerated their MCP URL",
|
||||
links=[audit.target("user", user["uid"], user["username"])],
|
||||
)
|
||||
return JSONResponse(
|
||||
{
|
||||
"token": result["token"],
|
||||
"mcp_url": url,
|
||||
"username": user["username"],
|
||||
"email": user["email"],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.post("/mcp/revoke")
|
||||
async def mcp_revoke(request: Request):
|
||||
user = require_user(request)
|
||||
from devplacepy.services import mcp_tokens as mcp_store
|
||||
|
||||
revoked = mcp_store.revoke(user["uid"])
|
||||
logger.info(f"MCP URL revoked for {user['username']}")
|
||||
audit.record(
|
||||
request,
|
||||
"profile.mcp.revoke",
|
||||
user=user,
|
||||
target_type="user",
|
||||
target_uid=user["uid"],
|
||||
target_label=user["username"],
|
||||
summary=f"{user['username']} revoked their MCP URL",
|
||||
links=[audit.target("user", user["uid"], user["username"])],
|
||||
)
|
||||
return JSONResponse({"revoked": revoked, "username": user["username"]})
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -3,8 +3,13 @@
|
||||
import logging
|
||||
from typing import Annotated
|
||||
from fastapi import Depends, APIRouter, Request
|
||||
from devplacepy.models import NotificationPrefForm
|
||||
from devplacepy.database import set_notification_pref, reset_notification_prefs
|
||||
from devplacepy.models import NotificationPrefForm, CustomizationToggleForm
|
||||
from devplacepy.database import (
|
||||
set_notification_pref,
|
||||
reset_notification_prefs,
|
||||
set_notification_grouping_enabled,
|
||||
set_notification_throttle_enabled,
|
||||
)
|
||||
from devplacepy.responses import action_result, json_error
|
||||
from devplacepy.services.audit import record as audit
|
||||
|
||||
@@ -60,6 +65,49 @@ async def set_notification_preference(
|
||||
},
|
||||
)
|
||||
|
||||
def _toggle_notification_display(request: Request, username: str, kind: str, value: bool):
|
||||
target, denied = resolve_customization_target(request, username)
|
||||
if denied is not None:
|
||||
return denied
|
||||
if kind == "grouping":
|
||||
set_notification_grouping_enabled(target["uid"], value)
|
||||
field = "notif_grouping_enabled"
|
||||
else:
|
||||
set_notification_throttle_enabled(target["uid"], value)
|
||||
field = "notif_throttle_enabled"
|
||||
audit.record(
|
||||
request,
|
||||
f"profile.notification.{kind}.toggle",
|
||||
target_type="user",
|
||||
target_uid=target["uid"],
|
||||
target_label=target["username"],
|
||||
old_value=0 if value else 1,
|
||||
new_value=1 if value else 0,
|
||||
summary=f"{'enabled' if value else 'disabled'} notification {kind} for {target['username']}",
|
||||
links=[audit.target("user", target["uid"], target["username"])],
|
||||
)
|
||||
url = f"/profile/{target['username']}?tab=notifications"
|
||||
return action_result(request, url, data={"url": url, field: value})
|
||||
|
||||
|
||||
@router.post("/{username}/notifications/grouping")
|
||||
async def set_notification_grouping(
|
||||
request: Request,
|
||||
username: str,
|
||||
data: Annotated[CustomizationToggleForm, Depends(json_or_form(CustomizationToggleForm))],
|
||||
):
|
||||
return _toggle_notification_display(request, username, "grouping", data.value)
|
||||
|
||||
|
||||
@router.post("/{username}/notifications/throttling")
|
||||
async def set_notification_throttling(
|
||||
request: Request,
|
||||
username: str,
|
||||
data: Annotated[CustomizationToggleForm, Depends(json_or_form(CustomizationToggleForm))],
|
||||
):
|
||||
return _toggle_notification_display(request, username, "throttle", data.value)
|
||||
|
||||
|
||||
@router.post("/{username}/notifications/reset")
|
||||
async def reset_notification_preferences(request: Request, username: str):
|
||||
target, denied = resolve_customization_target(request, username)
|
||||
|
||||
@@ -31,7 +31,11 @@ Each project carries a virtual filesystem so it can hold a whole software projec
|
||||
|
||||
## Project visibility and read-only
|
||||
|
||||
Two owner-controlled flags on the `projects` row, both integer `0`/`1` (default `0`, set on the create insert so the columns always exist): `is_private` hides the project from other viewers, `read_only` freezes its filesystem against every mutation. **The full security predicates** (`content.can_view_project`, `owns_instance`, `can_view_project_containers`, `can_view_instance`, `can_manage_instance`, the primary-administrator container isolation rules) are documented once in the root CLAUDE.md's "Project visibility (`is_private`) and read-only" section - this file covers only the project-page/filesystem UI-level behavior that sits on top of those predicates.
|
||||
Two owner-controlled flags on the `projects` row, both integer `0`/`1` (default `0`, set on the create insert so the columns always exist): `is_private` hides the project from other viewers, `read_only` freezes its filesystem against every mutation. **The full security predicates** (documented once, here):
|
||||
|
||||
- Project visibility (`is_private`) and read-only (`read_only`) are owner-controlled flags on `projects`. Read access is gated by the single `content.can_view_project(project, user)` predicate at EVERY read surface, never re-implemented inline. Predicate: `not is_private OR is_owner OR (is_admin AND owner is not an admin)`.
|
||||
- Containers have their own, stricter isolation predicates (`owns_instance`, `can_view_project_containers`, `can_view_instance`, `can_manage_instance`): the primary administrator sees/manages every container; any other admin can VIEW others' containers only on public projects and can MANAGE only instances they own.
|
||||
- Read-only is enforced as a single data-layer guard `project_files._guard_writable(project_uid)` at the top of every mutation entrypoint; add it to any NEW file-mutating function. Devii may flip read-only/visibility only after explicit confirmation.
|
||||
|
||||
**Toggle routes** (owner-only, `routers/projects/index.py`): `POST /projects/{slug}/private` and `POST /projects/{slug}/readonly`, each taking `ProjectFlagForm{value: bool}` and routed through `_set_project_flag`. The create form carries an `is_private` checkbox (`ProjectForm.is_private`); `project_detail.html` shows Private/Read-only badges and owner toggle buttons (**both** the private and read-only buttons carry `data-confirm` so `ModalManager.initConfirmations` gates them through `app.dialog`), and `project_files.html` hides the editing toolbar + shows a banner when read-only. Schemas: `is_private`/`read_only` on `ProjectOut` and `ProjectDetailOut`, `read_only`/`is_private` on `ProjectFilesOut`.
|
||||
|
||||
|
||||
@@ -135,6 +135,9 @@ from devplacepy.schemas.admin import (
|
||||
AdminNewsOut,
|
||||
AdminNotificationsOut,
|
||||
AdminSettingsOut,
|
||||
ServiceDetailOut,
|
||||
ServiceOut,
|
||||
ServicesOut,
|
||||
AdminTrashOut,
|
||||
AdminUserOut,
|
||||
AdminUsersOut,
|
||||
|
||||
@@ -94,12 +94,43 @@ class AdminDeviiTaskItemOut(_Out):
|
||||
|
||||
class AdminDeviiTasksOut(_Out):
|
||||
items: list[AdminDeviiTaskItemOut] = []
|
||||
pagination: Optional[Any] = None
|
||||
state: str = "active"
|
||||
tabs: list[dict] = []
|
||||
limits: dict = {}
|
||||
admin_section: Optional[str] = None
|
||||
|
||||
|
||||
class ServiceOut(_Out):
|
||||
name: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
details: Optional[str] = None
|
||||
enabled: bool = False
|
||||
status: Optional[str] = None
|
||||
interval_seconds: Optional[int] = None
|
||||
last_run: Optional[str] = None
|
||||
next_run: Optional[str] = None
|
||||
heartbeat: Optional[str] = None
|
||||
uptime: Optional[str] = None
|
||||
log_buffer: list[str] = []
|
||||
metrics: dict = {}
|
||||
fields: list[Any] = []
|
||||
field_groups: list[Any] = []
|
||||
|
||||
|
||||
class ServicesOut(_Out):
|
||||
services: list[ServiceOut] = []
|
||||
services_total: Optional[int] = None
|
||||
admin_section: Optional[str] = None
|
||||
|
||||
|
||||
class ServiceDetailOut(_Out):
|
||||
service: ServiceOut
|
||||
tool_groups: Optional[list[Any]] = None
|
||||
admin_section: Optional[str] = None
|
||||
|
||||
|
||||
class AdminGameOut(_Out):
|
||||
era_active: bool = False
|
||||
era_name: str = ""
|
||||
@@ -139,6 +170,7 @@ class AdminCommunityItemOut(_Out):
|
||||
|
||||
class AdminCommunitiesOut(_Out):
|
||||
items: list[AdminCommunityItemOut] = []
|
||||
pagination: Optional[Any] = None
|
||||
sync_enabled: bool = False
|
||||
service_enabled: bool = False
|
||||
service_dry_run: bool = True
|
||||
@@ -316,7 +348,9 @@ class AdminNodesOut(_Out):
|
||||
devices_by_country: dict[str, int] = {}
|
||||
usage_today: dict[str, int] = {}
|
||||
flags: list[AdminNodeFlagOut] = []
|
||||
flags_total: int = 0
|
||||
devices: list[AdminNodeDeviceOut] = []
|
||||
devices_total: int = 0
|
||||
settings: list[AdminNodeSettingOut] = []
|
||||
limits: dict[str, int] = {}
|
||||
circuits: list[AdminNodeCircuitOut] = []
|
||||
|
||||
@@ -72,6 +72,7 @@ class BackupScheduleOut(_Out):
|
||||
class BackupDashboardOut(_Out):
|
||||
storage: dict = {}
|
||||
backups: list[BackupOut] = []
|
||||
backups_total: int = 0
|
||||
schedules: list[BackupScheduleOut] = []
|
||||
targets: list[dict] = []
|
||||
metrics: dict = {}
|
||||
|
||||
@@ -48,6 +48,7 @@ class ContainersOut(_Out):
|
||||
|
||||
class AdminContainersOut(_Out):
|
||||
instances: list = []
|
||||
pagination: Optional[Any] = None
|
||||
projects: list = []
|
||||
boot_languages: list = []
|
||||
restart_policies: list = []
|
||||
@@ -199,5 +200,7 @@ class WorkspaceOut(_Out):
|
||||
class AdminWorkspacesOut(_Out):
|
||||
workspaces: list[WorkspaceViewOut] = []
|
||||
flags: list[WorkspaceFlagOut] = []
|
||||
flags_total: int = 0
|
||||
pagination: Optional[Any] = None
|
||||
admin_section: Optional[str] = None
|
||||
user: Optional[Any] = None
|
||||
|
||||
@@ -50,6 +50,15 @@ class AdminGatewayOut(_Out):
|
||||
default_provider: dict = {}
|
||||
quota_defaults: dict = {}
|
||||
stats_ranges: list = []
|
||||
providers_total: int = 0
|
||||
models_total: int = 0
|
||||
quota_rules_total: int = 0
|
||||
stats: dict = {}
|
||||
stats_range: str = "24h"
|
||||
stats_generated_iso: Optional[str] = None
|
||||
stats_models: list = []
|
||||
stats_table_models: list = []
|
||||
stats_table_models_total: int = 0
|
||||
admin_section: Optional[str] = None
|
||||
tested: str = ""
|
||||
test_image: str = ""
|
||||
|
||||
@@ -85,9 +85,18 @@ class NotificationItemOut(_Out):
|
||||
time_ago: Optional[str] = None
|
||||
|
||||
|
||||
class NotificationEventGroupOut(_Out):
|
||||
key: Optional[str] = None
|
||||
count: int = 0
|
||||
unread: bool = False
|
||||
actors: list[UserOut] = []
|
||||
latest: Optional[NotificationItemOut] = None
|
||||
|
||||
|
||||
class NotificationGroupOut(_Out):
|
||||
label: Optional[str] = None
|
||||
entries: list[NotificationItemOut] = []
|
||||
event_entries: list[NotificationEventGroupOut] = []
|
||||
|
||||
|
||||
class LeaderboardEntryOut(_Out):
|
||||
@@ -262,6 +271,7 @@ class MessagesOut(_Out):
|
||||
class NotificationsOut(_Out):
|
||||
notification_groups: list[NotificationGroupOut] = []
|
||||
next_cursor: Optional[str] = None
|
||||
grouping: bool = True
|
||||
|
||||
|
||||
class LeaderboardOut(_Out):
|
||||
|
||||
@@ -45,6 +45,10 @@ class ProfileOut(_Out):
|
||||
profile_is_admin: bool = False
|
||||
can_view_api_key: bool = False
|
||||
api_key: Optional[str] = None
|
||||
email: Optional[str] = None
|
||||
mcp_url: Optional[str] = None
|
||||
mcp_created_at: Optional[str] = None
|
||||
mcp_capabilities: list[Any] = []
|
||||
ai_correction_enabled: bool = False
|
||||
ai_correction_sync: bool = False
|
||||
ai_correction_prompt: Optional[str] = None
|
||||
@@ -60,6 +64,9 @@ class ProfileOut(_Out):
|
||||
can_manage_customization: bool = False
|
||||
cust_disable_global: bool = False
|
||||
cust_disable_pagetype: bool = False
|
||||
enter_to_submit: bool = True
|
||||
notif_grouping_enabled: bool = True
|
||||
notif_throttle_enabled: bool = True
|
||||
ai_quota: Optional[dict] = None
|
||||
correction_usage: Optional[dict] = None
|
||||
modifier_usage: Optional[dict] = None
|
||||
|
||||
@@ -14,6 +14,9 @@ class StatisticsMetricOut(BaseModel):
|
||||
format: str = "int"
|
||||
delta: Optional[float] = None
|
||||
direction: Optional[str] = None
|
||||
display: Optional[str] = None
|
||||
arrow: Optional[str] = None
|
||||
delta_display: Optional[str] = None
|
||||
|
||||
|
||||
class StatisticsPointOut(BaseModel):
|
||||
@@ -32,6 +35,9 @@ class StatisticsTableOut(BaseModel):
|
||||
title: str
|
||||
columns: list[str]
|
||||
rows: list[list[Any]]
|
||||
column_classes: list[str] = []
|
||||
display_rows: list[list[str]] = []
|
||||
row_count: Optional[str] = None
|
||||
|
||||
|
||||
class StatisticsHighlightOut(BaseModel):
|
||||
|
||||
@@ -123,6 +123,10 @@ devplace devii reset-quota --all # Reset every quota (users and guests)
|
||||
|
||||
`AcceptanceService` is a lock-owner `BaseService` (**opt-in**, `default_enabled = False`, five minutes, floor 60s) that grants every policy agreement to every account which has not declined it, so a production-identical instance used for manual testing never interrupts with an acceptance dialog. It is invisible to the rest of the application by contract: one registration line in `main.py` is the only import anywhere, and there is no route, schema, template, Devii tool or environment flag. The decline register is the consent ledger itself - the service only ever writes `granted`, so any `withdrawn` row was written by a human and that pair is never touched again. Three gates stand between a fresh install and a single written row (service disabled, every agreement disabled, dry run on). Full subsystem detail in `devplacepy/services/acceptance/CLAUDE.md`; the design record is `accept.md` at the repository root.
|
||||
|
||||
## Project blob sweep (`services/project_blob_sweep.py`)
|
||||
|
||||
`ProjectBlobSweepService` is a lock-owner `BaseService` (default-enabled, six hours, floor 300s) that deletes project file blobs which no `project_files` row references and which are older than a minimum age, through `project_files.referenced_project_blobs` + `sweep_project_blob_tree` (the same code `devplace system prune` uses). Two static ceilings guard it: the minimum age (`project_blob_sweep_min_age_seconds`, default 3600, floor 300) so a blob written a moment before its row is never swept, and the orphan cap (`project_blob_sweep_max_orphans`, default 1000, ceiling 100000): above it the service deletes nothing, logs `BLOCKED` and reports Blocked, because that many orphans means a leak is running and a human should look. Full background in `devplacepy/services/containers/CLAUDE.md` ("Bidirectional sync").
|
||||
|
||||
## Multi-worker concurrency (preferred rules)
|
||||
|
||||
`uvicorn --workers N` = N independent processes sharing only the filesystem and SQLite DB. Module-global caches/counters are per-process, so a local `clear()` is invisible to siblings. Full reference: admin docs `Production -> Multi-worker and concurrency` (`templates/docs/production-concurrency.html`). Enforce these:
|
||||
@@ -132,7 +136,7 @@ devplace devii reset-quota --all # Reset every quota (users and guests)
|
||||
- **Deterministic / eventual caches skip version-sync on purpose.** Two caches need no `cache_state` name because correctness does not depend on cross-worker freshness: (1) `docs_prose._render_markdown` is an `@lru_cache` on the **static** prose source string (pure function of template content, so identical on every worker; changes only on deploy), and (2) `routers/landing.py` `_home_cache` (`TTLCache ttl=60`) memoizes the guest `/` blocks - the featured-news block (identical for everyone) and the latest-posts block **only for the no-block case**; a viewer with a non-empty block set bypasses the cache and is computed fresh, so the original block-filter semantics are preserved byte-for-byte and there is zero cross-user leakage. Worst case is a soft-deleted/edited public post lingering on `/` for <=60s. Use a plain `TTLCache`/`lru_cache` (no version name) ONLY when the value is deterministic or its staleness is purely cosmetic; anything whose staleness affects correctness or permissions MUST use the version-sync pattern above.
|
||||
- **Authoritative state lives in the DB**, memory is only a short-TTL accelerator (sessions, the Devii 24h cap via `devii_usage_ledger`, cost counters).
|
||||
- **Global rates/quotas are worker-count-aware or DB-backed.** The rate limiter enforces `ceil(limit / DEVPLACE_WEB_WORKERS)` per process so the aggregate matches the configured value with no per-request write. `DEVPLACE_WEB_WORKERS` MUST equal the real `--workers` (set in `make prod`=2 and the Dockerfile=2; default 1 for dev). Update it whenever you change worker count.
|
||||
- **First-boot side effects are flock-serialized and idempotent.** `init_db()` runs under a blocking `flock` on `devplace-init.lock` (the seed-if-missing inserts would otherwise race to duplicate rows); `ensure_certificates()` early-returns when keys exist and otherwise generates under `.vapid.lock`. Any new run-once-at-startup work follows the same pattern (flock + exists-check / `INSERT OR IGNORE`).
|
||||
- **First-boot side effects are flock-serialized and idempotent.** `init_db()` runs under a blocking `flock` on `devplace-init.lock` (the seed-if-missing inserts would otherwise race to duplicate rows); `ensure_certificates()` early-returns when keys exist and otherwise creates the key directory, then generates under `.vapid.lock`. Any new run-once-at-startup work follows the same pattern (flock + exists-check / `INSERT OR IGNORE`).
|
||||
- **Run-once background work stays behind the services lock**, never per-worker: gate it on `service_manager.owns_lock()` (held via `devplace-services.lock`), as news/bots/Devii hub do.
|
||||
|
||||
## Performance caches (request-path)
|
||||
|
||||
@@ -88,10 +88,14 @@ class CommunityStore:
|
||||
row = table.find_one(slug=ref, deleted_at=None) or table.find_one(uid=ref, deleted_at=None)
|
||||
return decode(row, JSON_COLUMNS)
|
||||
|
||||
def list(self) -> list[dict]:
|
||||
rows = get_table("communities").find(deleted_at=None, order_by=["name"])
|
||||
def list(self, limit: int | None = None, offset: int = 0) -> list[dict]:
|
||||
window = {} if limit is None else {"_limit": limit, "_offset": offset}
|
||||
rows = get_table("communities").find(deleted_at=None, order_by=["name"], **window)
|
||||
return [decode(row, JSON_COLUMNS) for row in rows]
|
||||
|
||||
def count(self) -> int:
|
||||
return get_table("communities").count(deleted_at=None)
|
||||
|
||||
def pending(self, limit: int) -> list[dict]:
|
||||
horizon = iso(now() - timedelta(seconds=LIMITS.run_timeout_seconds))
|
||||
table = get_table("communities")
|
||||
|
||||
@@ -12,7 +12,7 @@ Admin-only. Supervises container instances, all running one shared prebuilt imag
|
||||
|
||||
Mounting the docker socket is root-equivalent on the host. Every run/exec/lifecycle/schedule operation is gated `require_admin` (HTTP) and `requires_admin=True` (Devii). `--privileged` is never passed. User input is never shell-interpolated - every call is an arg-list subprocess, never `shell=True`. Resource limits are applied via `--cpus`/`--memory`.
|
||||
|
||||
On top of the admin gate, **per-user container isolation** applies (see root CLAUDE.md "Project visibility (is_private) and read-only" convention): only the **primary administrator** (earliest-created Admin) and the instance owner (creator or project owner) may manage an instance; other admins get read-only access, and only when the instance's project is public. Enforced via `content.py` predicates `owns_instance`, `can_view_project_containers`, `can_view_instance`, `can_manage_instance` (all reusing `is_primary_admin`): the primary administrator sees and manages every container including those on private projects; any other admin can VIEW containers of others only when the instance's project is public (private-project containers of others are invisible; of private containers they see only their own), and can MANAGE (edit/lifecycle/exec/terminal/sync/delete/schedules) only instances they own - non-owners get 403 plus an audit row with `result="denied"` (WS close `1008`). This is enforced at every entrypoint: `routers/projects/containers/` (`project_for` + `manage_guard` + the exec WS), the admin Containers manager (`_decorate` filtering + per-row `can_manage`, `_viewable_instance_or_404`, `_manage_denied`, create + project-search), the Devii container tools (`ContainerController._project` + `_require_manage`), and the live view relay (broadcast topics never carry private-project instances).
|
||||
On top of the admin gate, **per-user container isolation** applies (predicates documented once in `devplacepy/routers/projects/CLAUDE.md` "Project visibility and read-only" (is_private) and read-only" convention): only the **primary administrator** (earliest-created Admin) and the instance owner (creator or project owner) may manage an instance; other admins get read-only access, and only when the instance's project is public. Enforced via `content.py` predicates `owns_instance`, `can_view_project_containers`, `can_view_instance`, `can_manage_instance` (all reusing `is_primary_admin`): the primary administrator sees and manages every container including those on private projects; any other admin can VIEW containers of others only when the instance's project is public (private-project containers of others are invisible; of private containers they see only their own), and can MANAGE (edit/lifecycle/exec/terminal/sync/delete/schedules) only instances they own - non-owners get 403 plus an audit row with `result="denied"` (WS close `1008`). This is enforced at every entrypoint: `routers/projects/containers/` (`project_for` + `manage_guard` + the exec WS), the admin Containers manager (`_decorate` filtering + per-row `can_manage`, `_viewable_instance_or_404`, `_manage_denied`, create + project-search), the Devii container tools (`ContainerController._project` + `_require_manage`), and the live view relay (broadcast topics never carry private-project instances).
|
||||
|
||||
## One shared image, no in-app builds (load-bearing)
|
||||
|
||||
@@ -423,13 +423,17 @@ sustained over time this leaked **5.9 million orphan blobs (~96GB)** in producti
|
||||
only when the host disk hit 100% full. Both are now closed at their root:
|
||||
|
||||
- **`api._sync_dir_bidirectional_locked`** wraps `project_files.sync_dir_bidirectional`
|
||||
behind a per-`project_uid` `threading.Lock` (`api._sync_lock_for`, a lazily-created
|
||||
registry - both `sync_workspace` and `sync_bidirectional_sync` call it instead of the
|
||||
raw function). The acquire is **non-blocking**: a second sync for a project already mid-sync
|
||||
is skipped outright (returns the zero-counts dict), never queued or awaited. This runs on
|
||||
an `asyncio.to_thread` worker in both call sites, so blocking would tie up a thread pool
|
||||
slot for no reason - a skipped project is simply picked up on the next tick or the user's
|
||||
next explicit sync.
|
||||
behind `locks.project_sync_lock(project_uid)`, a **cross-process** non-blocking `flock` on
|
||||
`LOCKS_DIR/project-sync-<uid>.lock` (both `sync_workspace` and `sync_bidirectional_sync` call it
|
||||
instead of the raw function). It is a file lock, not a `threading.Lock`, because production
|
||||
runs several uvicorn workers: a user-triggered sync served by one worker and the reconciler on
|
||||
the service-lock owner are different processes and an in-process lock never saw each other.
|
||||
The acquire is **non-blocking**: a second sync for a project already mid-sync is skipped
|
||||
outright (returns the zero-counts dict), never queued or awaited. This runs on an
|
||||
`asyncio.to_thread` worker in both call sites, so blocking would tie up a thread pool slot for
|
||||
no reason - a skipped project is simply picked up on the next tick or the user's next explicit
|
||||
sync. The lock file name is the project uid with every character outside `[A-Za-z0-9_-]`
|
||||
replaced, so a uid can never escape `LOCKS_DIR`.
|
||||
- **`project_files.IMPORT_SKIP_NAMES`** gained common build-output directory names (`build`,
|
||||
`dist`, `target`, `out`, `bin`, `obj`, `.next`, `.nuxt`, `.gradle`, `.tox`,
|
||||
`cmake-build-debug`, `cmake-build-release`) and a NEW parallel set,
|
||||
@@ -440,6 +444,26 @@ only when the host disk hit 100% full. Both are now closed at their root:
|
||||
AND the sync path via `SYNC_SKIP_NAMES = IMPORT_SKIP_NAMES | {...}`), so compiled/build
|
||||
artifacts are never imported into a project regardless of entry point, not just never synced.
|
||||
|
||||
- **`project_files.store_upload` never writes a blob it does not need and never strands one.** An
|
||||
import whose bytes equal the existing row's blob (`_blob_matches`: same size, same bytes) returns
|
||||
the existing node untouched, so a `touch`ed file costs no new blob and no row update. The capacity
|
||||
guard runs BEFORE the blob is written, and a failure between writing the blob and writing the row
|
||||
unlinks the new blob before re-raising. The old blob is unlinked only after the row points at the
|
||||
new one.
|
||||
- **A row whose blob is missing is retried at most every `MISSING_BLOB_RETRY_SECONDS` (600).**
|
||||
`project_files._export_with_backoff` remembers `(project_uid, path)` after a failed export in a
|
||||
per-process dict capped at `MISSING_BLOB_MAX_TRACKED` (10000, cleared when full), instead of
|
||||
retrying the copy on every 60s tick forever. Such rows are counted in the throttled "missing
|
||||
blob" warning and are never deleted by sync; repairing them is a human decision.
|
||||
- **A scheduled sweep is the floor under all of the above.** `ProjectBlobSweepService`
|
||||
(`services/project_blob_sweep.py`, lock-owner `BaseService`, default-enabled, every 6h, floor 300s)
|
||||
deletes blobs with no DB reference that are older than `project_blob_sweep_min_age_seconds`
|
||||
(default 3600, floor 300: a blob whose row is not inserted yet is never touched) and refuses to
|
||||
delete anything when more than `project_blob_sweep_max_orphans` (default 1000) are found in one
|
||||
run: it logs `BLOCKED`, shows Blocked on the Overview tab, and a human inspects and runs
|
||||
`devplace system prune`. The tree walk runs in `asyncio.to_thread`; the DB read of the referenced
|
||||
set stays inline. Gap: there is no push notification for Blocked, only the log and the stat card.
|
||||
|
||||
Neither fix requires (or should ever regress into) a redesign of the manifest/reconciliation
|
||||
model above - the lock only prevents two runs from touching the same project's `project_files`
|
||||
rows at once, and the skip sets only shrink what `_walk_workspace_files` yields. Recovering
|
||||
|
||||
@@ -5,11 +5,11 @@ import json
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from devplacepy import config, project_files, stealth
|
||||
from devplacepy.services.containers import store
|
||||
from devplacepy.services.containers.locks import project_sync_lock
|
||||
from devplacepy.services.containers.backend.base import (
|
||||
WORKSPACE_MOUNT,
|
||||
WORKSPACE_STATE_MOUNT,
|
||||
@@ -624,8 +624,6 @@ def run_spec_for(instance: dict, image_tag: str) -> RunSpec:
|
||||
)
|
||||
|
||||
|
||||
_SYNC_LOCKS: dict[str, threading.Lock] = {}
|
||||
_SYNC_LOCKS_GUARD = threading.Lock()
|
||||
_SYNC_EMPTY_COUNTS = {
|
||||
"exported": 0,
|
||||
"imported": 0,
|
||||
@@ -634,15 +632,6 @@ _SYNC_EMPTY_COUNTS = {
|
||||
}
|
||||
|
||||
|
||||
def _sync_lock_for(project_uid: str) -> threading.Lock:
|
||||
with _SYNC_LOCKS_GUARD:
|
||||
lock = _SYNC_LOCKS.get(project_uid)
|
||||
if lock is None:
|
||||
lock = threading.Lock()
|
||||
_SYNC_LOCKS[project_uid] = lock
|
||||
return lock
|
||||
|
||||
|
||||
def _sync_dir_bidirectional_locked(project_uid: str, workspace, user: dict) -> dict:
|
||||
# The user-triggered sync and the reconciler's periodic sync both call
|
||||
# this, unsynchronized. Without this lock, two overlapping runs for the
|
||||
@@ -652,13 +641,10 @@ def _sync_dir_bidirectional_locked(project_uid: str, workspace, user: dict) -> d
|
||||
# nothing - an orphan on every race, forever. A non-blocking skip (never
|
||||
# a blocking wait) is deliberate: this runs on an asyncio.to_thread
|
||||
# worker, and a project mid-sync simply gets picked up on the next tick.
|
||||
lock = _sync_lock_for(project_uid)
|
||||
if not lock.acquire(blocking=False):
|
||||
return dict(_SYNC_EMPTY_COUNTS)
|
||||
try:
|
||||
with project_sync_lock(project_uid) as acquired:
|
||||
if not acquired:
|
||||
return dict(_SYNC_EMPTY_COUNTS)
|
||||
return project_files.sync_dir_bidirectional(project_uid, workspace, user)
|
||||
finally:
|
||||
lock.release()
|
||||
|
||||
|
||||
async def sync_workspace(instance: dict, user: dict) -> dict:
|
||||
|
||||
@@ -1,5 +1,37 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import asyncio
|
||||
import fcntl
|
||||
import re
|
||||
from contextlib import contextmanager
|
||||
|
||||
from devplacepy import config
|
||||
|
||||
NUMBERING_LOCK = asyncio.Lock()
|
||||
|
||||
SYNC_LOCK_PREFIX = "project-sync-"
|
||||
SYNC_LOCK_SUFFIX = ".lock"
|
||||
_UNSAFE_LOCK_CHARS = re.compile(r"[^A-Za-z0-9_-]")
|
||||
|
||||
|
||||
def sync_lock_path(project_uid: str):
|
||||
safe = _UNSAFE_LOCK_CHARS.sub("_", project_uid)
|
||||
return config.LOCKS_DIR / f"{SYNC_LOCK_PREFIX}{safe}{SYNC_LOCK_SUFFIX}"
|
||||
|
||||
|
||||
@contextmanager
|
||||
def project_sync_lock(project_uid: str):
|
||||
path = sync_lock_path(project_uid)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
handle = open(path, "w")
|
||||
try:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError:
|
||||
handle.close()
|
||||
yield False
|
||||
return
|
||||
try:
|
||||
yield True
|
||||
finally:
|
||||
fcntl.flock(handle, fcntl.LOCK_UN)
|
||||
handle.close()
|
||||
|
||||
@@ -114,6 +114,10 @@ The upstream model `deepseek-v4-flash` (what `deepseek-chat` routes to; default
|
||||
|
||||
**`find_compaction_split` must accept any safe boundary, not only a `user`-role message (a second real incident of this same failure class).** `compact_messages` needs a split point where `messages[1:split]` (summarized away) and `messages[split:]` (kept verbatim) each stay internally self-contained - a tool result can never be separated from the assistant `tool_calls` message that produced it, or the provider rejects the request as malformed on the very next call. The original `find_compaction_split` enforced this by scanning backward from `len(messages) - keep_tail` for a `role == "user"` message and returning `1` (a **total no-op** - `compact_messages` then returns `messages` completely unchanged) if none was found before reaching index 1. That guard is correct for ordinary multi-turn chat, but a long single-turn agentic run (many consecutive `assistant` tool_calls + `tool` result pairs with no interleaved `user` message, e.g. a big scheduled task or a chat turn that just keeps calling tools) has **no `user`-role message anywhere in the scan range**, so both the proactive compaction (`context_size(messages) > context_compact_threshold`, checked every iteration) and the reactive overflow retry above silently did nothing at all, turn after turn, while `context_overflow_attempts` still climbed to `MAX_CONTEXT_OVERFLOW_RETRIES` and the loop still failed closed with the provider's raw 400 - "compaction" fired (visibly, as repeated `compact-overflow` trace events) but never actually shrank anything. The fix: track the closest safe fallback boundary (`role != "tool"`, i.e. `user` **or** a non-tool-calling point) seen during the same backward scan, and use it when no `user` message turns up - `assistant` is just as safe a split point as `user` since neither leaves an orphaned tool result on either side of the cut. Given the conversation always starts `[system, user, assistant, ...]`, this fallback is always found once `len(messages) >= keep_tail + 3` (the precondition `compact_messages` already checks before calling it), so the function can no longer degenerate to a permanent no-op. Regression-guarded by `tests/unit/services/devii/agentic/compaction.py` (`test_find_compaction_split_falls_back_to_a_non_tool_boundary_without_a_recent_user_message`, `test_find_compaction_split_never_lands_inside_a_tool_result_run`, `test_compact_messages_shrinks_a_tool_heavy_conversation_with_no_recent_user_message`) - each one fails against the pre-fix code with a synthetic tool-heavy, user-message-free conversation.
|
||||
|
||||
## Persistent big-result refs (summary + sha256, 10-day TTL)
|
||||
|
||||
Big tool results never travel as repeated full dumps. When a dispatched result exceeds `settings.max_response_chars`, `Dispatcher` persists it once through `BigRefStore` (`services/devii/bigrefs/`, owner-scoped over the session's `owned_db`, memory-only for guests/docs) and returns a small envelope `{ref_id: "mem:<hex12>", hash: "sha256:<hex>", summary, description, mime, bytes, total_chars, created_at, expires_at, preview}` with a `ref_read` hint, instead of the session-only `wrap_if_large` chunk path. The model pages slices with `ref_read` (`ref_id` required, optional `hash` verified, `offset`/`length` capped at 65536, default 4096). Every read re-verifies the sha256 and reports `not_found`/`expired`/`stale` instead of serving drifted bytes. Summaries are deterministic structural facts (chars, lines, opening text), never an extra LLM call. Rows expire after `BIGREF_TTL_DAYS` (10), are capped per owner (`BIGREF_MAX_PER_OWNER`, LRU), hard-deleted by `run_once` housekeeping, and never cross owner boundaries. Small results are untouched, so this is strictly an overflow path, not a behavior change.
|
||||
|
||||
## Multi-worker service-lock routing
|
||||
|
||||
Hubs are per-process, so `/devii/ws` is served **only** by the worker that holds the background-service lock (`service_manager.owns_lock()`, set in `main.py` startup); a non-owner worker `close(4013)` (an application code in the private 4000-4999 range, reliably delivered as the browser `CloseEvent.code`). `DeviiSocket.js` recognises 4013 as "wrong worker, not yet settled" and fast-retries in ~200ms **silently** (no "disconnected, reconnecting..." notice), so with 2 prod workers the client converges on the owner in a fraction of a second instead of bouncing every 1500ms. The visible "connected." notice is emitted on the first server frame (`onReady`), never on raw socket open, so an accepted-then-4013-closed handshake on the wrong worker is invisible. The disabled/no-service path keeps the standard `1013` (a real, user-visible disconnect). The cap stays correct regardless because it reads the DB.
|
||||
@@ -259,6 +263,8 @@ Broker uses `present_plain` or emits a plain menu and waits; `parse_plain_reply`
|
||||
|
||||
Every non-docs turn appends `CA_IWP_SYSTEM_FRAGMENT` plus the live channel fragment from `_compose_system_prompt()`. Model rules: prefer `ui_prompt` when gated on; never invent HTML/CE tags; branch on `status` (submitted / cancelled / timeout / superseded / error).
|
||||
|
||||
The composed message ends with the `# CURRENT TIME` block (see Timezone awareness above), rounded to the hour, so the whole system prompt is byte-stable across turns within one hour. That stability is what lets a prefix-caching upstream keep serving a repeated emulated tool catalog from cache until the hour flips (see the gateway file's tool-emulation section).
|
||||
|
||||
### Tests
|
||||
|
||||
Unit coverage under `tests/unit/services/devii/interaction/` (capabilities, schema, markdown, parse, broker, controller) plus session tool-gating assertions and telegram callback emission. Mirror this layout for any extension.
|
||||
|
||||
@@ -208,6 +208,39 @@ GATEWAY_ACTIONS: tuple[Action, ...] = (
|
||||
confirm(),
|
||||
),
|
||||
),
|
||||
Action(
|
||||
name="gateway_learned_list",
|
||||
method="GET",
|
||||
path="/admin/gateway/learned",
|
||||
summary="List the request shapes the gateway learned automatically per provider and target model (admin only)",
|
||||
description=(
|
||||
"Returns JSON: every learned method (provider, target_model, the method label, its "
|
||||
"thinking dialect and dropped keys, when it was learned) plus the resolve/exhausted/"
|
||||
"healed counters. A method is learned when an upstream rejected the default request "
|
||||
"shape with a parsable unrecognized-key 400 and a retry with another shape succeeded."
|
||||
),
|
||||
handler="http",
|
||||
requires_admin=True,
|
||||
read_only=True,
|
||||
),
|
||||
Action(
|
||||
name="gateway_learned_reset",
|
||||
method="POST",
|
||||
path="/admin/gateway/learned/reset",
|
||||
summary="Forget a learned request shape so the gateway re-learns it (admin only, confirmation required)",
|
||||
description=(
|
||||
"Deletes the learned method for one provider and target model; the next request starts "
|
||||
"from the default shape again and re-resolves if the upstream still rejects it. Use "
|
||||
"provider 'default' for the base upstream. 404 when nothing is learned for that route."
|
||||
),
|
||||
handler="http",
|
||||
requires_admin=True,
|
||||
params=(
|
||||
body("provider", "Provider name, or 'default' for the base upstream."),
|
||||
body("target_model", "The upstream (target) model name the method was learned for."),
|
||||
confirm(),
|
||||
),
|
||||
),
|
||||
Action(
|
||||
name="gateway_quota_rule_delete",
|
||||
method="DELETE",
|
||||
|
||||
@@ -61,6 +61,23 @@ PROFILE_ACTIONS: tuple[Action, ...] = (
|
||||
),
|
||||
),
|
||||
),
|
||||
Action(
|
||||
name="mcp_regenerate_url",
|
||||
method="POST",
|
||||
path="/profile/mcp/regenerate",
|
||||
summary="Issue a new MCP server URL and invalidate the current one",
|
||||
description=(
|
||||
"Returns the new MCP URL. Warning: this immediately invalidates any URL currently "
|
||||
"used by connected harnesses, so confirm with the user before calling it."
|
||||
),
|
||||
params=(
|
||||
body(
|
||||
"confirm",
|
||||
"Must be true, set only after the user has explicitly confirmed.",
|
||||
required=True,
|
||||
),
|
||||
),
|
||||
),
|
||||
Action(
|
||||
name="give_award",
|
||||
method="POST",
|
||||
|
||||
@@ -131,6 +131,23 @@ CUSTOMIZATION_ACTIONS: tuple[Action, ...] = (
|
||||
),
|
||||
),
|
||||
),
|
||||
Action(
|
||||
name="enter_to_submit_set",
|
||||
method="LOCAL",
|
||||
path="",
|
||||
summary="Turn Enter to send on or off for comments and direct messages",
|
||||
description=(
|
||||
"When enabled, Enter posts or sends and Shift+Enter adds a new line in comments and "
|
||||
"direct messages. Long editors keep Enter for new lines and use Ctrl+Enter to submit. "
|
||||
"Mirrors the Keyboard toggle on the user's profile page."
|
||||
),
|
||||
handler="customization",
|
||||
requires_auth=True,
|
||||
params=(
|
||||
arg("enabled", "true for Enter to send, false for Enter adds a new line.", required=True, kind="boolean"),
|
||||
arg("confirm", "Must be true after the user has confirmed the change.", required=True, kind="boolean"),
|
||||
),
|
||||
),
|
||||
Action(
|
||||
name="customize_set_enabled",
|
||||
method="LOCAL",
|
||||
|
||||
@@ -60,6 +60,7 @@ CONFIRM_REQUIRED = {
|
||||
"delete_project",
|
||||
"delete_media",
|
||||
"regenerate_api_key",
|
||||
"mcp_regenerate_url",
|
||||
"regenerate_avatar",
|
||||
"delete_post",
|
||||
"delete_comment",
|
||||
@@ -76,10 +77,14 @@ CONFIRM_REQUIRED = {
|
||||
"backup_delete",
|
||||
"backup_schedule_delete",
|
||||
"notification_reset",
|
||||
"enter_to_submit_set",
|
||||
"notification_grouping_set",
|
||||
"notification_throttle_set",
|
||||
"gateway_provider_delete",
|
||||
"gateway_model_delete",
|
||||
"gateway_quota_rule_delete",
|
||||
"gateway_quota_reset",
|
||||
"gateway_learned_reset",
|
||||
"email_account_delete",
|
||||
"email_delete_message",
|
||||
"game_prestige",
|
||||
@@ -196,6 +201,11 @@ def confirmation_error(name: str, arguments: dict[str, Any]) -> ToolInputError |
|
||||
"behaves, and they apply on the next workspace start. Show the user the exact "
|
||||
"values you are about to set, then call again with confirm=true."
|
||||
)
|
||||
if name in ("enter_to_submit_set", "notification_grouping_set", "notification_throttle_set"):
|
||||
return ToolInputError(
|
||||
"This changes how the user's keyboard or notifications behave everywhere. Ask the user "
|
||||
"to confirm, then call again with confirm=true."
|
||||
)
|
||||
if name == "notification_reset":
|
||||
return ToolInputError(
|
||||
"Resetting clears every notification preference and restores the platform defaults; it "
|
||||
@@ -237,6 +247,12 @@ def confirmation_error(name: str, arguments: dict[str, Any]) -> ToolInputError |
|
||||
"scripts or services that use it. Ask the user to confirm explicitly, then call again "
|
||||
"with confirm=true."
|
||||
)
|
||||
if name == "mcp_regenerate_url":
|
||||
return ToolInputError(
|
||||
"Regenerating your MCP URL immediately invalidates the current URL, which disconnects "
|
||||
"every connected harness. Ask the user to confirm explicitly, then call again "
|
||||
"with confirm=true."
|
||||
)
|
||||
if name == "delete_post":
|
||||
slug = str(arguments.get("slug", arguments.get("post_slug", ""))).strip()
|
||||
return ToolInputError(
|
||||
@@ -387,6 +403,7 @@ class Dispatcher:
|
||||
behavior: Any = None,
|
||||
interaction: Any = None,
|
||||
agents: Any = None,
|
||||
bigrefs: Any = None,
|
||||
) -> None:
|
||||
self._actions = catalog.by_name()
|
||||
self._client = client
|
||||
@@ -428,6 +445,7 @@ class Dispatcher:
|
||||
|
||||
self._telegram = TelegramSendController(owner_kind, owner_id)
|
||||
self._virtual_tools = virtual_tools
|
||||
self._bigrefs = bigrefs
|
||||
self._behavior = behavior
|
||||
self._interaction = interaction
|
||||
self._agents = agents
|
||||
@@ -458,6 +476,20 @@ class Dispatcher:
|
||||
action = self._actions.get(name)
|
||||
return bool(action and action.is_read_only)
|
||||
|
||||
def _store_big_result(self, name: str, result: str) -> str | None:
|
||||
try:
|
||||
ref = self._bigrefs.store_result(result, description=f"Large {name} result")
|
||||
except Exception: # noqa: BLE001 - fall back to the session chunk path
|
||||
logger.exception("Bigref store failed for %s", name)
|
||||
return None
|
||||
envelope = dict(ref)
|
||||
envelope["hint"] = (
|
||||
f"Result stored by reference to save context. Call ref_read with "
|
||||
f"ref_id='{ref['ref_id']}' and an offset to read slices; summary and "
|
||||
f"preview above are usually enough."
|
||||
)
|
||||
return json.dumps(envelope, ensure_ascii=False)
|
||||
|
||||
async def dispatch(self, name: str, arguments: dict[str, Any]) -> str:
|
||||
action = self._actions.get(name)
|
||||
if action is None:
|
||||
@@ -514,6 +546,12 @@ class Dispatcher:
|
||||
self._audit_mechanic(action, arguments)
|
||||
if action.handler == "chunks":
|
||||
return result
|
||||
if action.handler == "bigrefs":
|
||||
return result
|
||||
if self._bigrefs is not None and len(result) > self._settings.max_response_chars:
|
||||
ref = self._store_big_result(name, result)
|
||||
if ref is not None:
|
||||
return ref
|
||||
return wrap_if_large(
|
||||
result, self._settings.max_response_chars, resource_key
|
||||
)
|
||||
@@ -604,6 +642,11 @@ class Dispatcher:
|
||||
if action.handler == "chunks":
|
||||
return await self._chunks.dispatch(action.name, arguments)
|
||||
|
||||
if action.handler == "bigrefs":
|
||||
if self._bigrefs is None:
|
||||
return error_result(ToolInputError("Stored refs are not available in this session."))
|
||||
return await self._bigrefs.dispatch(action.name, arguments)
|
||||
|
||||
if action.handler == "rsearch":
|
||||
return await self._rsearch.dispatch(action.name, arguments)
|
||||
|
||||
|
||||
@@ -58,6 +58,32 @@ NOTIFICATION_ACTIONS: tuple[Action, ...] = (
|
||||
),
|
||||
),
|
||||
),
|
||||
Action(
|
||||
name="notification_grouping_set",
|
||||
method="LOCAL",
|
||||
path="",
|
||||
summary="Turn grouped notifications on or off",
|
||||
description="When enabled, similar notifications share one card and the badge counts groups. When disabled, every notification gets its own card and the badge counts every event. Mirrors the profile notifications toggle.",
|
||||
handler="notification",
|
||||
requires_auth=True,
|
||||
params=(
|
||||
arg("enabled", "true to group similar notifications, false to show every event.", required=True, kind="boolean"),
|
||||
arg("confirm", "Must be true after the user has confirmed the change.", required=True, kind="boolean"),
|
||||
),
|
||||
),
|
||||
Action(
|
||||
name="notification_throttle_set",
|
||||
method="LOCAL",
|
||||
path="",
|
||||
summary="Turn throttling of repeat notification alerts on or off",
|
||||
description="When enabled, repeated similar events send at most one push, Telegram message and toast per 5 minutes. In-app notifications are never throttled. Mirrors the profile notifications toggle.",
|
||||
handler="notification",
|
||||
requires_auth=True,
|
||||
params=(
|
||||
arg("enabled", "true to throttle repeat alerts, false to alert on every event.", required=True, kind="boolean"),
|
||||
arg("confirm", "Must be true after the user has confirmed the change.", required=True, kind="boolean"),
|
||||
),
|
||||
),
|
||||
Action(
|
||||
name="notification_reset",
|
||||
method="LOCAL",
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .spec import Action, Param
|
||||
|
||||
REF_ACTIONS: tuple[Action, ...] = (
|
||||
Action(
|
||||
name="ref_read",
|
||||
method="LOCAL",
|
||||
path="",
|
||||
summary="Read a slice of a previously stored big tool result",
|
||||
description=(
|
||||
"When a tool result is too big it is stored once and the tool returns a "
|
||||
"reference envelope with ref_id, sha256 hash, summary, and preview instead of "
|
||||
"the full content. Call ref_read with that ref_id and an offset to page through "
|
||||
"the rest. Stored refs expire after 10 days and are private to your account. "
|
||||
"Never guess a ref_id; only use one returned in this conversation."
|
||||
),
|
||||
handler="bigrefs",
|
||||
requires_auth=False,
|
||||
read_only=True,
|
||||
params=(
|
||||
Param(
|
||||
name="ref_id",
|
||||
location="body",
|
||||
description="The ref_id from a stored-result envelope (mem:...).",
|
||||
required=True,
|
||||
),
|
||||
Param(
|
||||
name="hash",
|
||||
location="body",
|
||||
description="Optional sha256:<64 hex> to verify against the stored hash.",
|
||||
),
|
||||
Param(
|
||||
name="offset",
|
||||
location="body",
|
||||
description="Character offset to read from (use next_offset from the prior part).",
|
||||
type="integer",
|
||||
),
|
||||
Param(
|
||||
name="length",
|
||||
location="body",
|
||||
description="Characters to return, 1-65536, default 4096.",
|
||||
type="integer",
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -44,6 +44,9 @@ SYSTEM_PROMPT = (
|
||||
"call read_more with that chunk_id and offset to page through the rest until remaining_chars "
|
||||
"is 0 whenever you need the full content. Use read_more to continue - never re-run the "
|
||||
"original tool to get more of the same resource; its full content is already cached. "
|
||||
"Very big results are instead stored by reference and return ref_id, hash, summary, "
|
||||
"and preview; call ref_read with that ref_id and an offset to page them, and never "
|
||||
"re-run the original tool either. "
|
||||
"Platform calls return structured JSON: reads give objects with fields like uid, slug, "
|
||||
"next_cursor, and nested authors/comments; write actions return {ok, redirect, data} where "
|
||||
"data has the created resource's uid/slug/url. Always reuse those exact slugs/uids/urls for "
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .controller import BigRefController
|
||||
from .store import (
|
||||
BIGREF_MAX_BYTES,
|
||||
BIGREF_MAX_PER_OWNER,
|
||||
BIGREF_PREVIEW_CHARS,
|
||||
BIGREF_SLICE_DEFAULT,
|
||||
BIGREF_SLICE_MAX,
|
||||
BIGREF_TTL_DAYS,
|
||||
BigRefStore,
|
||||
prune_expired,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"BIGREF_MAX_BYTES",
|
||||
"BIGREF_MAX_PER_OWNER",
|
||||
"BIGREF_PREVIEW_CHARS",
|
||||
"BIGREF_SLICE_DEFAULT",
|
||||
"BIGREF_SLICE_MAX",
|
||||
"BIGREF_TTL_DAYS",
|
||||
"BigRefController",
|
||||
"BigRefStore",
|
||||
"prune_expired",
|
||||
]
|
||||
@@ -0,0 +1,79 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from ..errors import ToolInputError
|
||||
from .store import BIGREF_SLICE_DEFAULT, BIGREF_SLICE_MAX, BigRefStore
|
||||
|
||||
_HASH_RE = re.compile(r"^sha256:[0-9a-f]{64}$")
|
||||
|
||||
|
||||
class BigRefController:
|
||||
def __init__(self, store: BigRefStore) -> None:
|
||||
self._store = store
|
||||
|
||||
def store_result(self, text: str, description: str = "", mime: str = "text/plain") -> dict[str, Any]:
|
||||
ref = self._store.put(text, description=description, mime=mime)
|
||||
if ref is None:
|
||||
raise ToolInputError("Content is empty or exceeds the big-ref size cap.")
|
||||
return ref
|
||||
|
||||
async def dispatch(self, name: str, arguments: dict[str, Any]) -> str:
|
||||
if name != "ref_read":
|
||||
raise ToolInputError(f"Unknown bigref tool: {name}")
|
||||
ref_id = str(arguments.get("ref_id", "")).strip()
|
||||
if not ref_id:
|
||||
raise ToolInputError("ref_read requires a ref_id.")
|
||||
claimed = str(arguments.get("hash", "")).strip()
|
||||
if claimed and not _HASH_RE.match(claimed):
|
||||
raise ToolInputError("hash must look like sha256:<64 hex>.")
|
||||
try:
|
||||
offset = max(0, int(arguments.get("offset", 0) or 0))
|
||||
except (TypeError, ValueError):
|
||||
raise ToolInputError("offset must be a non-negative integer.") from None
|
||||
try:
|
||||
length = int(arguments.get("length", BIGREF_SLICE_DEFAULT) or BIGREF_SLICE_DEFAULT)
|
||||
except (TypeError, ValueError):
|
||||
raise ToolInputError("length must be a positive integer.") from None
|
||||
length = max(1, min(length, BIGREF_SLICE_MAX))
|
||||
result = self._store.read(ref_id, offset, length)
|
||||
status = result.get("status")
|
||||
if status == "not_found":
|
||||
return json.dumps(
|
||||
{
|
||||
"status": "not_found",
|
||||
"message": (
|
||||
f"No stored content for ref_id '{ref_id}'. It may have expired; "
|
||||
"re-run the original tool to get a fresh ref."
|
||||
),
|
||||
}
|
||||
)
|
||||
if status == "expired":
|
||||
return json.dumps(
|
||||
{
|
||||
"status": "expired",
|
||||
"message": f"Stored content for ref_id '{ref_id}' expired after 10 days.",
|
||||
}
|
||||
)
|
||||
if status == "stale":
|
||||
return json.dumps(
|
||||
{
|
||||
"status": "stale",
|
||||
"message": (
|
||||
f"Stored content for ref_id '{ref_id}' failed hash verification. "
|
||||
"Do not use it; re-run the original tool."
|
||||
),
|
||||
}
|
||||
)
|
||||
if claimed and claimed != result.get("hash"):
|
||||
return json.dumps(
|
||||
{
|
||||
"status": "stale",
|
||||
"message": "Hash mismatch: the stored content changed since the ref was issued.",
|
||||
}
|
||||
)
|
||||
return json.dumps(result, ensure_ascii=False)
|
||||
@@ -0,0 +1,186 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
logger = logging.getLogger("devii.bigrefs")
|
||||
|
||||
TABLE = "devii_big_refs"
|
||||
|
||||
BIGREF_TTL_DAYS = 10
|
||||
BIGREF_MAX_PER_OWNER = 100
|
||||
BIGREF_MAX_BYTES = 8_000_000
|
||||
BIGREF_SLICE_DEFAULT = 4096
|
||||
BIGREF_SLICE_MAX = 65536
|
||||
BIGREF_PREVIEW_CHARS = 2000
|
||||
|
||||
COLUMNS = (
|
||||
("uid", ""),
|
||||
("owner_kind", ""),
|
||||
("owner_id", ""),
|
||||
("ref_id", ""),
|
||||
("hash", ""),
|
||||
("summary", ""),
|
||||
("description", ""),
|
||||
("mime", ""),
|
||||
("bytes", 0),
|
||||
("content", ""),
|
||||
("created_at", ""),
|
||||
("expires_at", ""),
|
||||
)
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def digest_of(text: str) -> str:
|
||||
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def summarize(text: str) -> str:
|
||||
chars = len(text)
|
||||
lines = text.count("\n") + 1 if text else 0
|
||||
head = " ".join(text.split())[:160]
|
||||
return f"{chars} chars in {lines} lines. Starts with: {head}" if head else f"{chars} chars in {lines} lines"
|
||||
|
||||
|
||||
class BigRefStore:
|
||||
def __init__(self, db: Any, owner_kind: str, owner_id: str) -> None:
|
||||
self._db = db
|
||||
self._owner_kind = owner_kind
|
||||
self._owner_id = owner_id
|
||||
self._ensure_schema()
|
||||
|
||||
@property
|
||||
def _table(self) -> Any:
|
||||
return self._db[TABLE]
|
||||
|
||||
def _ensure_schema(self) -> None:
|
||||
table = self._db[TABLE]
|
||||
for column, example in COLUMNS:
|
||||
if table.has_column(column):
|
||||
continue
|
||||
try:
|
||||
table.create_column_by_example(column, example)
|
||||
except Exception: # noqa: BLE001 - concurrent DDL from another worker
|
||||
logger.debug("Column %s was created by another process", column)
|
||||
try:
|
||||
table.create_index(["owner_kind", "owner_id"])
|
||||
except Exception: # noqa: BLE001 - index already exists
|
||||
logger.debug("Bigref owner index exists")
|
||||
try:
|
||||
table.create_index(["hash"])
|
||||
except Exception: # noqa: BLE001 - index already exists
|
||||
logger.debug("Bigref hash index exists")
|
||||
|
||||
@property
|
||||
def _scope(self) -> dict[str, str]:
|
||||
return {"owner_kind": self._owner_kind, "owner_id": self._owner_id}
|
||||
|
||||
def put(self, text: str, description: str = "", mime: str = "text/plain") -> Optional[dict[str, Any]]:
|
||||
if not isinstance(text, str) or not text:
|
||||
return None
|
||||
size = len(text.encode("utf-8"))
|
||||
if size > BIGREF_MAX_BYTES:
|
||||
return None
|
||||
hexdigest = digest_of(text)
|
||||
ref_id = "mem:" + hexdigest[:12]
|
||||
full_hash = "sha256:" + hexdigest
|
||||
now = _now_iso()
|
||||
expires = (datetime.now(timezone.utc) + timedelta(days=BIGREF_TTL_DAYS)).isoformat()
|
||||
existing = self._table.find_one(hash=full_hash, **self._scope)
|
||||
if existing is not None:
|
||||
if (existing.get("expires_at") or "") >= now and existing.get("content") == text:
|
||||
self._table.update({"id": existing["id"], "expires_at": expires}, ["id"])
|
||||
return self._envelope(existing, text, now, expires)
|
||||
self._table.delete(id=existing["id"])
|
||||
self._enforce_cap()
|
||||
row = {
|
||||
"uid": uuid.uuid4().hex,
|
||||
"owner_kind": self._owner_kind,
|
||||
"owner_id": self._owner_id,
|
||||
"ref_id": ref_id,
|
||||
"hash": full_hash,
|
||||
"summary": summarize(text),
|
||||
"description": description or "Large tool result stored by reference",
|
||||
"mime": mime,
|
||||
"bytes": size,
|
||||
"content": text,
|
||||
"created_at": now,
|
||||
"expires_at": expires,
|
||||
}
|
||||
self._table.insert(row)
|
||||
return self._envelope(row, text, now, expires)
|
||||
|
||||
def _envelope(self, row: dict[str, Any], text: str, now: str, expires: str) -> dict[str, Any]:
|
||||
return {
|
||||
"stored": True,
|
||||
"ref_id": row["ref_id"],
|
||||
"hash": row["hash"],
|
||||
"summary": row["summary"],
|
||||
"description": row["description"],
|
||||
"mime": row["mime"],
|
||||
"bytes": row["bytes"],
|
||||
"total_chars": len(text),
|
||||
"created_at": row.get("created_at") or now,
|
||||
"expires_at": row.get("expires_at") or expires,
|
||||
"preview": text[:BIGREF_PREVIEW_CHARS],
|
||||
}
|
||||
|
||||
def _enforce_cap(self) -> None:
|
||||
rows = sorted(
|
||||
self._table.find(**self._scope),
|
||||
key=lambda row: row.get("created_at") or "",
|
||||
)
|
||||
overflow = len(rows) - BIGREF_MAX_PER_OWNER + 1
|
||||
for row in rows[: max(0, overflow)]:
|
||||
self._table.delete(id=row["id"])
|
||||
|
||||
def read(self, ref_id: str, offset: int = 0, length: int = BIGREF_SLICE_DEFAULT) -> dict[str, Any]:
|
||||
key = (ref_id or "").strip()
|
||||
if not key.startswith("mem:"):
|
||||
return {"status": "not_found"}
|
||||
row = self._table.find_one(ref_id=key, **self._scope)
|
||||
if row is None:
|
||||
return {"status": "not_found"}
|
||||
if (row.get("expires_at") or "") < _now_iso():
|
||||
self._table.delete(id=row["id"])
|
||||
return {"status": "expired"}
|
||||
content = row.get("content") or ""
|
||||
if digest_of(content) != (row.get("hash") or "").replace("sha256:", "", 1):
|
||||
return {"status": "stale"}
|
||||
total = len(content)
|
||||
start = max(0, offset)
|
||||
stop = min(total, start + max(1, min(length, BIGREF_SLICE_MAX)))
|
||||
piece = content[start:stop]
|
||||
has_more = stop < total
|
||||
return {
|
||||
"status": "success",
|
||||
"ref_id": key,
|
||||
"hash": row.get("hash"),
|
||||
"offset": start,
|
||||
"shown_chars": len(piece),
|
||||
"total_chars": total,
|
||||
"remaining_chars": total - stop,
|
||||
"next_offset": stop if has_more else None,
|
||||
"has_more": has_more,
|
||||
"content": piece,
|
||||
}
|
||||
|
||||
|
||||
def prune_expired(db: Any, now_iso: Optional[str] = None) -> int:
|
||||
if TABLE not in db.tables:
|
||||
return 0
|
||||
cutoff = now_iso or _now_iso()
|
||||
rows = list(db[TABLE].find(expires_at={"<": cutoff}))
|
||||
for row in rows:
|
||||
db[TABLE].delete(id=row["id"])
|
||||
if rows:
|
||||
logger.info("Pruned %d expired big ref(s)", len(rows))
|
||||
return len(rows)
|
||||
@@ -166,6 +166,9 @@ async def run(settings: Settings, prompt: Optional[str] = None) -> None:
|
||||
cost_tracker = CostTracker()
|
||||
chunk_store = ChunkStore()
|
||||
agentic = AgenticController(lessons, settings)
|
||||
from .bigrefs.controller import BigRefController
|
||||
from .bigrefs.store import BigRefStore
|
||||
|
||||
dispatcher = Dispatcher(
|
||||
CATALOG,
|
||||
client,
|
||||
@@ -174,6 +177,7 @@ async def run(settings: Settings, prompt: Optional[str] = None) -> None:
|
||||
agentic,
|
||||
is_admin=True,
|
||||
is_primary_admin=True,
|
||||
bigrefs=BigRefController(BigRefStore(store.db, owner_kind, owner_id)),
|
||||
)
|
||||
from .tool_prefs import filter_disabled
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ from devplacepy.database import (
|
||||
list_custom_overrides,
|
||||
set_custom_override,
|
||||
set_customization_pref,
|
||||
set_enter_to_submit,
|
||||
)
|
||||
from devplacepy.services.devii.errors import ToolInputError
|
||||
|
||||
@@ -41,6 +42,8 @@ class CustomizationController:
|
||||
return self._reset(arguments)
|
||||
if name == "customize_set_enabled":
|
||||
return self._set_enabled(arguments)
|
||||
if name == "enter_to_submit_set":
|
||||
return self._set_enter_to_submit(arguments)
|
||||
raise ToolInputError(f"Unknown customization tool: {name}")
|
||||
|
||||
def _scope(self, arguments: dict[str, Any]) -> str:
|
||||
@@ -123,6 +126,13 @@ class CustomizationController:
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
def _set_enter_to_submit(self, arguments: dict[str, Any]) -> str:
|
||||
if self._owner_kind != "user":
|
||||
raise ToolInputError("Enter to send is only available for signed-in users.")
|
||||
enabled = self._enabled(arguments)
|
||||
set_enter_to_submit(self._owner_id, enabled)
|
||||
return json.dumps({"status": "success", "enter_to_submit": enabled}, ensure_ascii=False)
|
||||
|
||||
def _category(self, arguments: dict[str, Any]) -> str:
|
||||
category = str(arguments.get("category", "")).strip().lower()
|
||||
if category not in CUSTOMIZATION_PREF_COLUMNS:
|
||||
|
||||
@@ -11,6 +11,8 @@ from devplacepy.database import (
|
||||
get_notification_prefs,
|
||||
reset_notification_prefs,
|
||||
set_notification_pref,
|
||||
set_notification_grouping_enabled,
|
||||
set_notification_throttle_enabled,
|
||||
)
|
||||
from devplacepy.services.devii.errors import ToolInputError
|
||||
|
||||
@@ -29,6 +31,10 @@ class NotificationController:
|
||||
return self._set(arguments)
|
||||
if name == "notification_reset":
|
||||
return self._reset()
|
||||
if name == "notification_grouping_set":
|
||||
return self._set_display(arguments, "grouping")
|
||||
if name == "notification_throttle_set":
|
||||
return self._set_display(arguments, "throttle")
|
||||
raise ToolInputError(f"Unknown notification tool: {name}")
|
||||
|
||||
def _require_user(self) -> None:
|
||||
@@ -82,6 +88,15 @@ class NotificationController:
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
def _set_display(self, arguments: dict[str, Any], kind: str) -> str:
|
||||
self._require_user()
|
||||
enabled = self._value(arguments) if "enabled" not in arguments else self._value({**arguments, "value": arguments.get("enabled")})
|
||||
if kind == "grouping":
|
||||
set_notification_grouping_enabled(self._owner_id, enabled)
|
||||
else:
|
||||
set_notification_throttle_enabled(self._owner_id, enabled)
|
||||
return json.dumps({"status": "success", kind: enabled}, ensure_ascii=False)
|
||||
|
||||
def _reset(self) -> str:
|
||||
self._require_user()
|
||||
removed = reset_notification_prefs(self._owner_id)
|
||||
|
||||
@@ -16,6 +16,7 @@ from .actions.docs_actions import DOCS_ACTIONS
|
||||
from .actions.email_actions import EMAIL_ACTIONS
|
||||
from .actions.fetch_actions import FETCH_ACTIONS
|
||||
from .actions.notification_actions import NOTIFICATION_ACTIONS
|
||||
from .actions.ref_actions import REF_ACTIONS
|
||||
from .actions.rsearch_actions import RSEARCH_ACTIONS
|
||||
from .actions.spec import Action, Catalog
|
||||
from .actions.telegram_actions import TELEGRAM_ACTIONS
|
||||
@@ -36,6 +37,7 @@ GROUPS: dict[str, tuple[Action, ...]] = {
|
||||
"docs": DOCS_ACTIONS,
|
||||
"cost": COST_ACTIONS,
|
||||
"chunks": CHUNK_ACTIONS,
|
||||
"bigrefs": REF_ACTIONS,
|
||||
"rsearch": RSEARCH_ACTIONS,
|
||||
"container": CONTAINER_ACTIONS,
|
||||
"workspace": WORKSPACE_ACTIONS,
|
||||
@@ -87,6 +89,7 @@ GROUP_LABELS: dict[str, str] = {
|
||||
"docs": "Docs Search",
|
||||
"cost": "Usage and Cost",
|
||||
"chunks": "Large Result Paging",
|
||||
"bigrefs": "Stored Big Results (10-day refs)",
|
||||
"rsearch": "External Web Search",
|
||||
"container": "Containers",
|
||||
"workspace": "Workspaces",
|
||||
@@ -112,6 +115,7 @@ CATALOG = Catalog(
|
||||
+ DOCS_ACTIONS
|
||||
+ COST_ACTIONS
|
||||
+ CHUNK_ACTIONS
|
||||
+ REF_ACTIONS
|
||||
+ RSEARCH_ACTIONS
|
||||
+ CONTAINER_ACTIONS
|
||||
+ WORKSPACE_ACTIONS
|
||||
|
||||
@@ -487,11 +487,12 @@ class DeviiService(BaseService):
|
||||
pruned = hub.ledger.prune(48)
|
||||
removed = await hub.gc_idle()
|
||||
lessons_pruned = self._prune_old_lessons()
|
||||
if pruned or removed or idle or lessons_pruned or runs_pruned or agents_pruned:
|
||||
bigrefs_pruned = self._prune_bigrefs()
|
||||
if pruned or removed or idle or lessons_pruned or runs_pruned or agents_pruned or bigrefs_pruned:
|
||||
self.log(
|
||||
f"Housekeeping: disabled {idle} idle-owner task(s), pruned {runs_pruned} task-run "
|
||||
f"rows, pruned {agents_pruned} agent rows, pruned {pruned} ledger rows, pruned "
|
||||
f"{lessons_pruned} lessons, closed {removed} idle sessions"
|
||||
f"{lessons_pruned} lessons, pruned {bigrefs_pruned} big refs, closed {removed} idle sessions"
|
||||
)
|
||||
|
||||
def _prune_task_runs(self) -> int:
|
||||
@@ -532,6 +533,16 @@ class DeviiService(BaseService):
|
||||
logger.exception("Devii lessons housekeeping failed")
|
||||
return 0
|
||||
|
||||
def _prune_bigrefs(self) -> int:
|
||||
try:
|
||||
from devplacepy.database import db
|
||||
from .bigrefs.store import prune_expired
|
||||
|
||||
return prune_expired(db)
|
||||
except Exception:
|
||||
logger.exception("Devii bigref housekeeping failed")
|
||||
return 0
|
||||
|
||||
def scheduler(self) -> GlobalScheduler:
|
||||
if self._scheduler is None:
|
||||
from devplacepy.database import db
|
||||
|
||||
@@ -109,6 +109,11 @@ class DeviiSession:
|
||||
)
|
||||
self.store = task_store
|
||||
self.task_controller = TaskController(self.store)
|
||||
from ..bigrefs.controller import BigRefController
|
||||
from ..bigrefs.store import BigRefStore
|
||||
|
||||
self.bigref_store = BigRefStore(self.store.db, owner_kind, owner_id)
|
||||
self.bigrefs = BigRefController(self.bigref_store)
|
||||
self.agentic = AgenticController(lessons, settings)
|
||||
self.cost = CostTracker(pricing=pricing)
|
||||
self.chunks = ChunkStore()
|
||||
@@ -144,6 +149,7 @@ class DeviiSession:
|
||||
behavior=self.behavior,
|
||||
interaction=self.interaction,
|
||||
agents=self.agent_controller,
|
||||
bigrefs=self.bigrefs,
|
||||
)
|
||||
self.tools = self._builtin_tools()
|
||||
self._system_prompt = (
|
||||
|
||||
@@ -11,6 +11,7 @@ from devplacepy.database import (
|
||||
get_user_stars,
|
||||
)
|
||||
from devplacepy.avatar import avatar_seed
|
||||
from devplacepy.content import discoverable_target_rows
|
||||
from devplacepy.services.devrant.avatar import avatar_payload
|
||||
from devplacepy.services.devrant.feed import build_rant_list
|
||||
from devplacepy.services.devrant.ids import to_unix
|
||||
@@ -54,6 +55,7 @@ def _user_comments(user: dict, viewer: Optional[dict]) -> list:
|
||||
_limit=PROFILE_COMMENT_LIMIT,
|
||||
)
|
||||
)
|
||||
comments = discoverable_target_rows(comments, viewer)
|
||||
if not comments:
|
||||
return []
|
||||
target_uids = list({comment["target_uid"] for comment in comments})
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from devplacepy.cache import TTLCache
|
||||
from devplacepy.database import get_table, is_account_active
|
||||
from devplacepy.utils import generate_uid
|
||||
|
||||
TOKEN_KEY_BYTES = 32 # 64-char hex, matching session token size
|
||||
NEGATIVE_TTL = 10
|
||||
|
||||
_misses = TTLCache(ttl=NEGATIVE_TTL, max_size=2000)
|
||||
|
||||
|
||||
def _miss_seen(token: str) -> bool:
|
||||
return _misses.get(token) is not None
|
||||
|
||||
|
||||
def _miss_remember(token: str) -> None:
|
||||
_misses.set(token, True)
|
||||
|
||||
|
||||
def _miss_forget(token: str) -> None:
|
||||
_misses.pop(token)
|
||||
|
||||
|
||||
def issue_token(user: dict, label: str = "default") -> dict:
|
||||
from devplacepy.utils.authcache import clear_user_cache
|
||||
|
||||
token = secrets.token_hex(TOKEN_KEY_BYTES)
|
||||
token_uid = generate_uid()
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
get_table("mcp_tokens").insert(
|
||||
{
|
||||
"uid": token_uid,
|
||||
"token": token,
|
||||
"user_uid": user["uid"],
|
||||
"label": label or "default",
|
||||
"created_at": now,
|
||||
"deleted_at": None,
|
||||
"deleted_by": None,
|
||||
}
|
||||
)
|
||||
_miss_forget(token)
|
||||
clear_user_cache(user["uid"])
|
||||
return {
|
||||
"token": token,
|
||||
"uid": token_uid,
|
||||
"label": label or "default",
|
||||
"created_at": now,
|
||||
}
|
||||
|
||||
|
||||
def get_active(user_uid: str) -> Optional[dict]:
|
||||
rows = list(
|
||||
get_table("mcp_tokens").find(user_uid=user_uid, deleted_at=None)
|
||||
)
|
||||
if not rows:
|
||||
return None
|
||||
return sorted(rows, key=lambda row: row.get("created_at", ""))[-1]
|
||||
|
||||
|
||||
def resolve_token(token: str) -> Optional[dict]:
|
||||
if not token or len(token) != 64:
|
||||
return None
|
||||
row = get_table("mcp_tokens").find_one(token=token, deleted_at=None)
|
||||
if not row:
|
||||
_miss_remember(token)
|
||||
return None
|
||||
user = get_table("users").find_one(uid=row.get("user_uid"))
|
||||
if not user or not is_account_active(user):
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
def resolve_token_cached(token: str) -> Optional[dict]:
|
||||
if not token or len(token) != 64:
|
||||
return None
|
||||
if _miss_seen(token):
|
||||
return None
|
||||
return resolve_token(token)
|
||||
|
||||
|
||||
def regenerate(user: dict, label: str = "default") -> dict:
|
||||
from devplacepy.utils.authcache import clear_user_cache
|
||||
|
||||
stamp = datetime.now(timezone.utc).isoformat()
|
||||
tokens = get_table("mcp_tokens")
|
||||
for row in list(tokens.find(user_uid=user["uid"], deleted_at=None)):
|
||||
tokens.update(
|
||||
{"id": row["id"], "deleted_at": stamp, "deleted_by": "regenerate"},
|
||||
["id"],
|
||||
)
|
||||
clear_user_cache(user["uid"])
|
||||
return issue_token(user, label=label)
|
||||
|
||||
|
||||
def revoke(user_uid: str) -> int:
|
||||
from devplacepy.utils.authcache import clear_user_cache
|
||||
|
||||
tokens = get_table("mcp_tokens")
|
||||
stamp = datetime.now(timezone.utc).isoformat()
|
||||
count = 0
|
||||
for row in list(tokens.find(user_uid=user_uid, deleted_at=None)):
|
||||
tokens.update(
|
||||
{"id": row["id"], "deleted_at": stamp, "deleted_by": "manual"},
|
||||
["id"],
|
||||
)
|
||||
count += 1
|
||||
if count:
|
||||
clear_user_cache(user_uid)
|
||||
return count
|
||||
@@ -85,11 +85,11 @@ Live/echoed message bubbles are NEVER injected as raw HTML. `AppChat._buildBubbl
|
||||
|
||||
## Frontend
|
||||
|
||||
The messaging frontend is the single self-booting custom element `<dp-chat>` (`static/js/components/AppChat.js`), which replaced the old page-controller trio `MessagesLayout.js`/`MessagesSocket.js`/`MessageSearch.js` (all deleted) and `messages.css` (superseded by `static/css/chat.css`) - see `devplacepy/static/js/CLAUDE.md` for the component roster entry. `MobileNav.js` does **not** own the mobile pane (that duplicate was removed; `dp-chat` is the only pane controller). `templates/messages.html` renders `<dp-chat mode="page" self-uid="..." with-uid="..." conversations-url="/messages/conversations" search-url="/messages/search" send-url="/messages/send" ws-url="/messages/ws" ai-indicator="true">` wrapping the SAME server-rendered `.messages-list`/`.messages-main`/`.messages-thread`/`.message-bubble` markup as before (no-JS/crawler fallback), which the component *adopts* on `connectedCallback` rather than discarding. It owns a `ChatSocket` (`static/js/chat/ChatSocket.js`, exponential backoff, `4013` fast-path, 25s ping), sends over WS with an optimistic pending bubble keyed by `client_id`, reconciles on the echoed `message` frame, applies later `ai_processed` frames in place (compare `dp-content[data-source]`, never rendered `textContent`), injects the Report control on every live incoming bubble, catches up with `{type:"sync"}` on reconnect, and switches conversations without dropping the socket (`GET /messages?with_uid=` JSON + `history.pushState`). Older history loads via `GET /messages?with_uid=&before=` when the thread is scrolled to the top. Mobile: CSS hides the inactive pane from `with-uid` / `.show-list` before JS runs (no stacked FOUC); the composer does not auto-focus on coarse pointers; keyboard inset uses `visualViewport.offsetTop + height`; Enter-to-send is desktop-only. **The send button is disabled while `dp-upload` is busy AND while a genuine new send is in flight** (the send-lock, see "Send dedupe" above) - a `.failed`-bubble retry never engages it, so retrying an old message never blocks typing/sending a new one. Presence in `mode="page"` stays on the page-global `PresenceManager`. An opt-in `ai-indicator="true"` attribute shows "Adjusting..." while `ai_pending` and "Adjusted by AI" when the revision lands. Styling is in `static/css/chat.css` using `variables.css` tokens only, responsive down to 360px.
|
||||
The messaging frontend is the single self-booting custom element `<dp-chat>` (`static/js/components/AppChat.js`), which replaced the old page-controller trio `MessagesLayout.js`/`MessagesSocket.js`/`MessageSearch.js` (all deleted) and `messages.css` (superseded by `static/css/chat.css`) - see `devplacepy/static/js/CLAUDE.md` for the component roster entry. `MobileNav.js` does **not** own the mobile pane (that duplicate was removed; `dp-chat` is the only pane controller). `templates/messages.html` renders `<dp-chat mode="page" self-uid="..." with-uid="..." conversations-url="/messages/conversations" search-url="/messages/search" send-url="/messages/send" ws-url="/messages/ws" ai-indicator="true">` wrapping the SAME server-rendered `.messages-list`/`.messages-main`/`.messages-thread`/`.message-bubble` markup as before (no-JS/crawler fallback), which the component *adopts* on `connectedCallback` rather than discarding. In `page`/`embed` mode it owns a `ChatSocket` (`static/js/chat/ChatSocket.js`, exponential backoff, `4013` fast-path, 25s ping); in `window` mode it subscribes through the shared dock hub instead. It sends over WS with an optimistic pending bubble keyed by `client_id`, reconciles on the echoed `message` frame, applies later `ai_processed` frames in place (compare `dp-content[data-source]`, never rendered `textContent`), injects the Report control on every live incoming bubble, catches up with `{type:"sync"}` on reconnect, and switches conversations without dropping the socket (`GET /messages?with_uid=` JSON + `history.pushState`). Older history loads via `GET /messages?with_uid=&before=` when the thread is scrolled to the top. Mobile: CSS hides the inactive pane from `with-uid` / `.show-list` before JS runs (no stacked FOUC); the composer does not auto-focus on coarse pointers; keyboard inset uses `visualViewport.offsetTop + height`; Enter-to-send is desktop-only. **The send button is disabled while `dp-upload` is busy AND while a genuine new send is in flight** (the send-lock, see "Send dedupe" above) - a `.failed`-bubble retry never engages it, so retrying an old message never blocks typing/sending a new one. Presence in `mode="page"` stays on the page-global `PresenceManager`. An opt-in `ai-indicator="true"` attribute shows "Adjusting..." while `ai_pending` and "Adjusted by AI" when the revision lands. Styling is in `static/css/chat.css` using `variables.css` tokens only, responsive down to 360px.
|
||||
|
||||
**Composer layout (every mode).** The message form is `[+] [composer-tools] [composer-field] [send]`: the `.composer-more-btn` toggles `tools-open` on the form, revealing `.composer-tools` (`dp-upload` and `dp-gif-picker`); typing collapses the tools again unless an upload is in flight or attachments are pending, a starting upload (paste, drop, pick) opens them so the count stays visible, and a send collapses them. The textarea lives inside `.composer-field`, the pill that also holds the emoji button (`ContentEnhancer.initEmojiPickers` appends the button into the field and re-homes the picker popup onto the form, and the GIF panel is positioned against the form too, so neither popup is clipped by the narrow pill). `messages.html` and `AppChat._buildComposer` emit the identical structure.
|
||||
|
||||
**Docked windows (`mode="window"`).** On every page except `/messages`, `dp-chat-dock` (see `devplacepy/static/js/CLAUDE.md`) hosts small `dp-chat mode="window"` elements. Window mode builds its own skeleton (header via `_buildHeader` with avatar and name, no back button, no element ids so several windows can coexist), loads history through the same `GET /messages?with_uid=` JSON the page uses (`_loadConversation`, which also marks the conversation and its notifications read) **before** subscribing to the shared socket, so the reconnect `sync` starts from the newest loaded stamp, and never touches `history`. Its thread always counts as active (`_activePane = "thread"`), so read receipts and the active-conversation marker behave exactly as on the page. No server change was needed: the dock uses only `/messages/conversations`, `/messages/search`, `GET /messages?with_uid=` and `WS /messages/ws`.
|
||||
**Docked windows (`mode="window"`).** On every page except `/messages`, `dp-chat-dock` (see `devplacepy/static/js/CLAUDE.md`) hosts small `dp-chat mode="window"` elements. Window mode builds its own skeleton (header via `_buildHeader` with avatar and name, no back button, no element ids so several windows can coexist), loads history through the same `GET /messages?with_uid=` JSON the page uses (`_loadConversation`, which also marks the conversation and its notifications read) **before** subscribing to the shared socket, so the reconnect `sync` starts from the newest loaded stamp, and never touches `history`. Its thread counts as active (`_activePane = "thread"`) only while the document is visible: a message arriving in a hidden tab stays unread server-side, and the conversation is marked read when the tab becomes visible again. No server change was needed: the dock uses only `/messages/conversations`, `/messages/search`, `GET /messages?with_uid=` and `WS /messages/ws`.
|
||||
|
||||
**Auto-scroll never fights a manual scroll-up.** `_startScrollWatcher`/`_stabilizeScroll` force `scrollTop = scrollHeight` on every thread mutation (new bubble, attachment/image finishing loading) ONLY while `_userAtBottom` is true, re-checked every `requestAnimationFrame` up to `STABILIZE_MAX_FRAMES`. The one thing that used to break this: while a multi-frame stabilize loop was in flight (`_stabilizePending`), the real `scroll` event listener (`_bindAutoScroll`) ignored EVERY scroll event outright, including a genuine user wheel/touch scroll-up that happened to land inside that window - so a rapid burst of incoming messages (each restarting the stabilize loop while attachments were still loading) could silently overwrite a user's attempt to scroll up to read history. The fix: every programmatic scroll (`_scrollThreadToEnd`, `_stabilizeScroll`) records the exact `scrollTop` it just set in `_lastForcedScrollTop`; the `scroll` listener only skips its own echo (`_stabilizePending && scrollTop === _lastForcedScrollTop`) and always processes a scroll that lands anywhere else, so a real user scroll-up is detected and `_userAtBottom` flips to `false` immediately, even mid-stabilization. Never gate scroll-intent detection on `_stabilizePending` alone again.
|
||||
|
||||
|
||||
@@ -139,3 +139,7 @@ The client side is `static/js/TermsGate.js` (`app.termsGate`); see `devplacepy/s
|
||||
- A new filter category: add rules to `rules.py` and the reason key to `REPORT_REASONS`; a unit test asserts every rule's category is a real reason.
|
||||
- A new consent: add it to `CONSENT_KINDS` and enforce it at one choke point, never at N call sites.
|
||||
- Never add a second removal path, a second suspension check, or a second consent gate.
|
||||
|
||||
## Account deletion CLI
|
||||
|
||||
`devplace accounts pending` lists deleted accounts awaiting purge; `devplace accounts prune` (with `--dry-run` to preview) permanently purges accounts past the deletion grace window.
|
||||
|
||||
@@ -45,6 +45,10 @@ Per article up to `IMG_PER_ARTICLE=5` candidate image URLs (from `_get_article_i
|
||||
|
||||
After the per-article loop, `_apply_landing_selection` queries recent (`<= LANDING_RECENCY_DAYS`) rows that are published + featured + `has_unique_image` + NOT `landing_locked`, sorts by `(-grade, -synced_at)`, sets `show_on_landing=1` for the top `LANDING_MAX` with `grade >= LANDING_MIN_SCORE` and `show_on_landing=0` for the rest of THAT service-managed set (self-rotating). When an admin manually toggles Featured or Landing (`routers/admin/news.py`), the matching `featured_locked`/`landing_locked` is set to 1 so the service stops auto-managing that row; updates of a locked Featured row never overwrite `featured`. New `news` columns: `ai_grade`, `featured`, `has_unique_image`, `image_url`, `featured_locked`, `landing_locked`, `author`, `article_published` (all added to the `init_db` ensure-block - the stale-schema rule). Audit events `news.service.ingest`/`news.service.publish`/`news.service.draft`/`news.service.reject`/`news.service.landing` (`record_system`, category `news`). New dep: `imagehash` (`Pillow` already present).
|
||||
|
||||
## CLI
|
||||
|
||||
`devplace news clear` deletes every news row; `devplace news sanitize` strips HTML from news descriptions/content.
|
||||
|
||||
## Editorial labels are admin-only on the public surfaces
|
||||
|
||||
The `★ Featured` badge and the `Grade {{ grade }}` chip are internal editorial signals, so on every PUBLIC news surface - the `/news` listing (`news.html`), the article page (`news_detail.html`), and the landing/home Developer News cards (`landing.html`) - both are wrapped in `{% if is_admin(user) %}`. Members and guests never see them; administrators still see them everywhere (including the public pages) and the admin **Manage News** area (`admin_news.html`) is unchanged, where the grade and featured state are the editorial controls. The article's source name and timestamp stay visible to everyone. Gating only the rendered labels does not touch the stored `grade`/`featured` columns, the grading/landing logic, or ordering (`/news` is still ordered by effective `grade`).
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from devplacepy.database import db
|
||||
import time
|
||||
from devplacepy.database import db, count_unread_groups, get_notification_throttle_enabled, notification_group_key, NOTIFICATION_GROUP_KEYS
|
||||
from devplacepy.services.base import BaseService
|
||||
from devplacepy.services.pubsub import publish as pubsub_publish
|
||||
|
||||
@@ -23,6 +24,7 @@ class NotificationRelayService(BaseService):
|
||||
super().__init__(name="notification_relay", interval_seconds=1)
|
||||
self._watermark = 0
|
||||
self._primed = False
|
||||
self._last_toast = {}
|
||||
|
||||
def _max_id(self) -> int:
|
||||
if "notifications" not in db.tables:
|
||||
@@ -32,17 +34,8 @@ class NotificationRelayService(BaseService):
|
||||
return int(value or 0)
|
||||
|
||||
def _counts(self, user_uid: str) -> dict:
|
||||
notifications = 0
|
||||
notifications = count_unread_groups(user_uid)
|
||||
messages = 0
|
||||
if "notifications" in db.tables:
|
||||
rows = list(
|
||||
db.query(
|
||||
"SELECT COUNT(*) AS c FROM notifications "
|
||||
"WHERE user_uid = :u AND read = 0",
|
||||
u=user_uid,
|
||||
)
|
||||
)
|
||||
notifications = int(rows[0]["c"]) if rows else 0
|
||||
if "messages" in db.tables:
|
||||
rows = list(
|
||||
db.query(
|
||||
@@ -63,7 +56,7 @@ class NotificationRelayService(BaseService):
|
||||
return
|
||||
rows = list(
|
||||
db.query(
|
||||
"SELECT id, uid, user_uid, type, message, target_url "
|
||||
"SELECT id, uid, user_uid, type, message, target_url, related_uid "
|
||||
"FROM notifications WHERE id > :wm ORDER BY id ASC LIMIT :lim",
|
||||
wm=self._watermark,
|
||||
lim=BATCH_LIMIT,
|
||||
@@ -73,6 +66,17 @@ class NotificationRelayService(BaseService):
|
||||
return
|
||||
delivered = 0
|
||||
for row in rows:
|
||||
if get_notification_throttle_enabled(row["user_uid"]):
|
||||
if NOTIFICATION_GROUP_KEYS.get(row["type"], "single") != "single":
|
||||
key = (row["user_uid"],) + notification_group_key(row)
|
||||
now_ts = time.time()
|
||||
last = self._last_toast.get(key)
|
||||
if last is not None and now_ts - last < 300:
|
||||
continue
|
||||
self._last_toast[key] = now_ts
|
||||
if len(self._last_toast) > 10000:
|
||||
for old_key in list(self._last_toast)[:1000]:
|
||||
self._last_toast.pop(old_key, None)
|
||||
delivered += await pubsub_publish(
|
||||
f"user.{row['user_uid']}.notifications",
|
||||
{
|
||||
|
||||
@@ -43,7 +43,10 @@ A model route (`gateway_models.tools_mode`, `native` default or `emulated`) decl
|
||||
- **Request seam.** `gateway._chat_upstream_body` calls `emulate_request(payload)` first, BEFORE the Responses/Meta transpile, so the Meta path (`chat_to_responses`, Muse aliasing) simply receives a tool-less Chat payload. As a side effect the Meta reserved tool-name gate never fires, because `tools[]` is gone; `_response_tool_aliases` returns `{}` for emulated routes. `emulate_request` strips `tools`/`tool_choice`/`parallel_tool_calls`/`functions`/`function_call`, appends a Hermes-format catalog (`<tools>` JSON lines plus the `<tool_call>{"name","arguments"}</tool_call>` contract) to the system message (creating one when absent), maps `tool_choice` (`none` drops the catalog, `required`/named add a MUST directive, `parallel_tool_calls: false` adds a one-call rule), rewrites history (assistant `tool_calls` become `<tool_call>` blocks, `role: tool`/`function` messages become one merged user message of `<tool_response>` blocks matched back to names by call id), and adds `<tool_response>` as a stop sequence so the model cannot invent a result. It never mutates the caller's payload.
|
||||
- **Response seams.** Non-streaming: `convert_completion` parses blocks out of `message.content` into `tool_calls` (generated `call_` ids, `finish_reason: "tool_calls"`, leftover text kept, `content: null` when empty), applied on both the chat and the Responses non-stream branches. Streaming: `_emulate_tool_stream` wraps the finished SSE iterator, so ledger/TTFT accounting stays inside the inner generator. `ToolCallStream` relays text live with a partial-`<tool_call>` holdback, buffers once a call opens, and emits each call whole in ONE `tool_calls` delta (never incremental arguments: that is where vLLM's Hermes parser kept breaking). Usage chunks and non-content deltas pass through.
|
||||
- **Parsing is tolerant, validation strict.** Accepts code fences, an array of calls in one block, `parameters` for `arguments`, string-encoded arguments, and an unterminated final block. A call is valid only if the name is declared and the schema's `required` keys are present. An invalid block is NEVER dropped silently: it stays in `content` as text and is logged (`emulated tools: ...`). Known gap: there is no repair retry; an invalid call is returned as text.
|
||||
- **Hard caps (400, no upstream call, no ledger row).** `MAX_TOOLS` 64, `MAX_CATALOG_CHARS` 60000, only `function` tools, `MAX_CALLS_PER_TURN` 8 (extra calls dropped with a warning). The catalog costs prompt tokens on every call, billed like any input.
|
||||
- **No count/size caps (deliberate).** Any number of `function` tools is accepted and the full catalog is always injected - Devii alone declares hundreds of tools, so a count cap would make large catalogs unservable everywhere. Servability is bounded downstream: the context-window precheck routes an oversized request to a fallback model before dispatch, and the upstream's own context limit is relayed when nothing can serve it. What still 400s (no upstream call, no ledger row) is a malformed declaration: non-list `tools`, a non-`function` tool type, or a nameless function. `MAX_CALLS_PER_TURN` 8 (extra calls dropped with a warning) is unchanged. The catalog costs prompt tokens on every call, billed like any input.
|
||||
- **Per-owner catalog cache (`tool_emulation.CatalogCache`, owned by `GatewayRuntime`).** Building the catalog (spec validation + instruction assembly, milliseconds at hundreds of tools) runs once per distinct `(owner, tools, tool_choice, parallel_tool_calls)` fingerprint and is reused across turns, retries, and fallback attempts; the response seams (`_emulated_tools`) resolve declarations from the same entry instead of re-validating. Entries are namespaced by owner (`(owner_kind, owner_id)`, so one user's tool set never serves another's) and bounded (`MAX_ENTRIES` 64, `MAX_CHARS` 2M, oldest-first eviction) - a cache key is content-derived, so no invalidation is needed.
|
||||
- **Injection cadence: once per request, every request.** The catalog is injected exactly once per upstream attempt (one `<tools>` block; history converts without repeated blocks; the stop sequence is added only when absent), but it is re-sent on every turn, retry, and fallback attempt, because the upstream is stateless and each call needs the catalog in context. Fallback attempts never stack injections: every attempt rebuilds from the pristine client payload (`emulate_request` never mutates its input), and the per-owner cache only skips the rebuild, never changes the bytes.
|
||||
- **Upstream prefix caching.** A prefix-caching upstream (DeepSeek context caching, tracked as `prompt_cache_hit_tokens`) can serve the repeated catalog from cache, but only while the bytes before it are stable. The catalog is appended after the client's system content, so anything volatile there re-bills the catalog too. Devii's system prompt is stable within the hour (its trailing `# CURRENT TIME` block is rounded to the hour, see the Devii file), so turns inside one hour share one prefix and the catalog hits; the hour rollover breaks it. Watch the cache-hit token split in `/admin/ai-usage` to confirm.
|
||||
- **Surfaces.** `ModelRouteIn.tools_mode`, the admin model form (**Tool calling** select), the `tools: emulated` badge, `POST /admin/gateway/models` (`tools_mode`, documented in `docs_api`) and the Devii `gateway_model_set` tool.
|
||||
- **Not covered:** constrained/guided decoding (provider-specific), and the format is Hermes JSON only. Tests: `tests/unit/services/openai_gateway/tool_emulation.py` (pure) and the `test_emulated_tools_*` tests in `gateway.py` (through the real Meta Responses path, streaming and non-streaming).
|
||||
|
||||
@@ -71,6 +74,10 @@ A dedicated per-IP throttle protects `/openai/v1/*` against unauthenticated prob
|
||||
|
||||
All config is `config_fields` (upstream url/model/key, force-model, the Prompt group's `gateway_system_preamble` and `gateway_thinking` (default off), timeout, instances, vision url/model/key/cache/toggle, the Embeddings group (`gateway_embed_enabled`/`_url`/`_model`/`_key`), the auth toggles + static key + internal key, plus the Pricing/Reliability/Tracking groups); live metrics (requests/errors/in-flight/vision-calls/embed-calls/latency plus 24h cost/tokens/success rollups) via `collect_metrics`.
|
||||
|
||||
## Vision model (current: `google/gemma-4-31b-it`)
|
||||
|
||||
Image content is described by the vision model before forwarding (augmentation defaults on via `gateway_vision_enabled`). The live value is the `gateway_vision_model` site setting (database, editable in admin UI, hot-reloads); the code fallback for fresh databases is `VISION_MODEL_DEFAULT` in `config.py` with its context window in `MODEL_CONTEXT_MAP_DEFAULT`. Keep the two in sync when switching models: the DB row wins at runtime, the code default wins on a fresh install. History: `gemma-3-12b-it` default, `gemma-3-27b-it` via DB, `gemma-4-31b-it` since 08/11/2026 (cheaper small variant `gemma-4-26b-a4b-it` also verified on OpenRouter and rejected in favour of quality).
|
||||
|
||||
## System-message composition (date awareness + operator preamble)
|
||||
|
||||
`system_message.py` (`apply_system_directives`) runs in `handle_chat` only (NOT `handle_embeddings`/`handle_passthrough`), after vision augmentation and before the upstream payload is assembled, so it reaches every chat consumer (news, bots, Devii guests, per-user direct API calls). It composes ONE system message in a fixed, cache-friendly order: **operator preamble (`gateway_system_preamble`) -> date line (`Current date: DD/MM/YYYY`) -> the client's original system content**.
|
||||
@@ -99,6 +106,8 @@ A structured/deterministic internal caller (one that expects a strict, machine-p
|
||||
- OpenRouter: `reasoning: {"effort": "none"}` or `"high"`
|
||||
- Ollama (`:11434` or a host containing `ollama`): `think: false` or `true`
|
||||
|
||||
`thinking_dialect` can also be `none` (no field written); it is only ever chosen by the auto-resolve ladder when an upstream rejects the thinking key (see "Auto-resolve of request shape").
|
||||
|
||||
Do **not** send `reasoning_effort: "none"` to DeepSeek (400: unknown variant). Conflicting client fields (`think`, `thinking`, `reasoning`, `reasoning_effort`, `enable_thinking`, `chat_template_kwargs.enable_thinking`) are stripped and translated to the dialect above.
|
||||
|
||||
**Default is off.** `gateway_thinking` (Prompt group, bool, default `False`) is the operator override for the silent-client case. A client still wins: `think` / `thinking.type` / `reasoning.effort` / `reasoning.enabled` / `reasoning_effort` / `enable_thinking` on the request body enable or disable thinking for that call. Internal callers (correction, bots, Devii, SEO, quiz grading) send none of those, so they get the fast path.
|
||||
@@ -109,6 +118,20 @@ Vision describe-image calls always disable thinking (they are not a reasoning jo
|
||||
|
||||
`thinking.upstream_capabilities(url, dialect="")` derives per-upstream protocol flags (`supports_stream_options`, `supports_stream_usage`, `supports_thinking_field`) from the same effective dialect. Ollama's OpenAI-compatibility layer ignores `stream_options` (and rejects the request outright on some versions), so `handle_chat`'s streaming branch only sends `stream_options: {"include_usage": true}` upstream when `capabilities.supports_stream_options` is true; otherwise a client that asked for `include_usage` gets a logged notice and its stream relayed with no usage chunk. DeepSeek/OpenRouter (and any unrecognised URL) report full support, so this is a no-op for them.
|
||||
|
||||
## Auto-resolve of request shape (`shape.py`, `learned.py`)
|
||||
|
||||
An upstream with a strict schema can reject a key the gateway adds on its own (observed 2026-11-13: route `vaids` answered `400 {"issues":[{"code":"unrecognized_keys","keys":["thinking"]}]}` because `thinking_dialect` falls back to `deepseek` for any unrecognised URL). A 400 is `bad_request`, never retried and never falls back, so the gateway now LEARNS, per (provider, target model), which shape the upstream accepts and applies it from then on.
|
||||
|
||||
- **One funnel.** `ShapeMethod.apply(payload, cfg, protocol, stream, log)` is the only place stream_options, the thinking dialect and droppable keys are written; chat, every fallback attempt and the vision describe call all go through it, each from the PRISTINE client payload with that attempt's own cfg (fallback attempts used to inherit the primary's already-shaped payload). `ShapeMethod.strip_wire` removes `drop_keys` (and `reasoning` for a Responses `none` method) from the final wire body in `_chat_upstream_body`. A method is a frozen `ShapeMethod(thinking_dialect, drop_keys)`; `thinking_dialect` is `native` (today's behaviour: the URL-sniffed or `gateway_thinking_dialect` dialect, the default and first ladder entry), `none` (write no thinking field at all, new in `thinking.py`), or an explicit `deepseek`/`openrouter`/`ollama`.
|
||||
- **Trigger.** Only a 400/422 whose body names rejected keys (`RejectedKeys.parse`: zod `issues[].keys` with `unrecognized_keys`, OpenAI `Unrecognized request argument supplied`/`Unknown parameter` + `param`, serde `unknown field`, "Extra inputs are not permitted"). An unparsable 400 stays terminal and loud, returned verbatim, never retried blind.
|
||||
- **Ladder and allowlist (static ceilings, no autotuning).** `ShapeResolver.next_method` picks the next untried method: a rejected thinking key (`think`, `thinking`, `reasoning`, `reasoning_effort`, `enable_thinking`, `chat_template_kwargs`) skips every dialect that emits it (`CHAT_LADDER` order: native, none, deepseek, openrouter, ollama; Responses protocol: native, none, rejecting `reasoning`); a rejected key in `DROPPABLE_KEYS` (`stream_options`, `parallel_tool_calls`, `user`, `seed`, `logprobs`, `top_logprobs`, `n`, `presence_penalty`, `frequency_penalty`) is added to `drop_keys`. `messages`, `model`, `tools` and any unknown key are NEVER dropped. Hard cap `MAX_RESOLVE_ATTEMPTS = 4` retries per route attempt.
|
||||
- **Retry placement.** `GatewayRuntime._chat_attempt` (shared by the primary and every fallback attempt) sends, and on a parsable shape 400 re-sends through `ShapeRetrier`; the retry goes through `_send` so the breaker and retries apply, and streaming status is known before any byte is relayed so a retried stream is safe. On success `learned_store.remember` is called (never on a guess) and one `auto-resolved <provider>/<model>: <method>` line is logged. On exhaustion the ORIGINAL 400 response is returned unchanged, nothing is stored, and `shape_stats.exhausted` is incremented. The vision describe call uses the same `ShapeRetrier`, keyed `vision:<host>` + vision model.
|
||||
- **Persistence.** Table `gateway_learned_methods` (`learned.py`, `ensure_table()` from `init_db`): `provider` (`default` for the base upstream), `target_model`, `method` (JSON), `learned_at`, unique index on (provider, target_model), cap `MAX_LEARNED_ROWS` 1000 (oldest by `learned_at` replaced). Cross-worker cache under the `gateway_learned` cache-version name; the upsert is one `ON CONFLICT DO UPDATE` so two workers learning the same route never collide. It is derived data in the garbage-collection class (NOT in `SOFT_DELETE_TABLES`): forget = delete row. Editing a provider's `base_url` or `client_profile`, or deleting it, forgets all its learned methods (`ProviderStore.set`/`remove`).
|
||||
- **Self-healing floor.** If a request using a LEARNED method itself gets a shape 400, the record is forgotten, the ladder restarts once from native, and `shape_stats.healed` counts it.
|
||||
- **Ledger.** One row per client call as before; `resolved_method` (text, `gateway_usage_ledger`) holds the non-native method label that served the call, empty for native.
|
||||
- **Operator surface.** `/admin/gateway` models grid shows a `shape: <method>` badge and a "Reset learned" form (`POST /admin/gateway/learned/reset-page`); JSON `GET /admin/gateway/learned` and `POST /admin/gateway/learned/reset` (audited `gateway.learned.reset`, category `ai`) back the Devii tools `gateway_learned_list` / `gateway_learned_reset` (the reset is in `CONFIRM_REQUIRED` with a declared `confirm`).
|
||||
- **Not covered:** value-level rejections (`unknown variant`), and keys outside the closed allowlists. Tests: `tests/unit/services/openai_gateway/{shape,learned}.py`, the `test_chat_auto_resolve*`/`test_chat_*learned*`/`test_fallback_attempt_is_shaped*` tests in `gateway.py`, `tests/api/admin/gateway/learned.py`, and the grid badge in `tests/e2e/admin/gateway.py`.
|
||||
|
||||
## Real upstream streaming (`GatewayRuntime._stream_chat_response`)
|
||||
|
||||
`stream: true` is forwarded to the upstream verbatim (`payload["stream"] = stream`, no more forced `false`) and the connection is opened with `client.send(request, stream=True)` so the response body is read incrementally via `resp.aiter_lines()` instead of buffered whole. Every retry/circuit-breaker mechanic in `_send`/`retry_send` is shared unchanged with the non-streaming path (a 5xx or connection failure before any bytes are forwarded to the client retries exactly as before; `retry_send` now also closes an unread streamed response before retrying, so a retried streaming attempt never leaks the previous connection). Only once the upstream returns `200` does the code path diverge into `_stream_chat_response`.
|
||||
@@ -230,7 +253,8 @@ Any `gateway_models` route (chat, embed, or image) can optionally name `fallback
|
||||
- **Rebuilt like a fresh routed call, not retried in place.** On failure, `handle_chat`/`handle_embeddings`/`handle_images` recompute the overlay from `base_cfg` (the pre-primary-overlay config) via `chat_overlay(fallback_route.source_model, base_cfg)`/`embed_overlay`/`image_overlay`, so the fallback gets its OWN provider, URL, key, and pricing - never the primary route's. `pricing`/`context_map` for the ledger are (re)computed AFTER the fallback decision so the recorded cost always reflects whichever model actually served the request.
|
||||
- **One ledger row per client call, not one per attempt.** The primary failure never writes a `gateway_usage_ledger` row by itself (only `_send`'s own internal retries and the circuit breaker counters observe it); `finalize()`/`self._ledger.record(...)` still runs exactly once, after the fallback decision, with `model` = whichever model ultimately answered and `requested_model` = the ORIGINALLY requested model name (an existing-but-previously-unpopulated ledger column, now populated by all three handlers) - so a fallback shows up in `/admin/ai-usage` as "requested X, served Y" rather than as two calls.
|
||||
- **Streaming falls back before any byte reaches the client.** `client.send(request, stream=True)` returns as soon as the response headers arrive, so `resp.status_code` is already known before the SSE body is ever touched - `handle_chat` decides whether to fall back at that same point, before it ever opens `_stream_chat_response` to the caller. A stream is therefore never abandoned mid-flight in favor of a fallback; the caller either gets the fallback's own stream from byte one, or the fallback's own definitive failure.
|
||||
- **Known limitation, inherited from the existing provider routing design, not introduced by this feature: the circuit breaker (`self._breaker`) is one instance per `GatewayRuntime`, shared across every route.** A primary attempt that trips the breaker can make the immediately-following fallback attempt itself see `circuit_open` too. This mirrors the pre-existing behavior for the multi-provider routing overlay in general (a struggling route's failures already could open the breaker in front of an unrelated route before fallback existed) and was left as-is rather than redesigning per-provider breakers, which is a materially larger change than "add a fallback model."
|
||||
- **Per-model breakers (`GatewayRuntime._target_breakers`).** Besides the global `self._breaker`, `_send` keeps one `CircuitBreaker(1, gateway_circuit_cooldown_seconds)` per request MODEL name (`_target_key`; the model name alone, so the same model on two providers shares one breaker, and a call with no model, such as passthrough, never uses it). One upstream error opens it at once (`CircuitBreaker.trip()`): exception, 5xx, 429, and any 4xx except a 400/422 whose body names rejected keys (the shape ladder still has to retry those; `_trip_worthy`), plus a 200 with an embedded error body (`_embedded_error`, called by the chat, embed and image handlers). An open model returns `timing["circuit_open"]` with no upstream call, so `_should_fallback` walks the fallback chain. The opening transition logs `ai.gateway.circuit.target_opened` (now with the routed `route=` name) and is reported to every admin with ONE detailed `system` notification per tripped breaker (`_notify_gateway_status(True, detail)`). Chat, embed and image handlers defer every trip of their request into a per-request `trip_sink` (`route_name` threaded through `_chat_attempt`/`_shaped_send`/`_send`/`_embedded_error`) and, once the fallback line has resolved, emit one notification per tripped breaker via `_notify_trips`: each names the local config (`route`, the `source_model` that tripped, plus the requested model), the full recursive route (`_chain_records`/`_format_chain` over `resolve_fallback_chain`, every hop with its upstream target and provider), the redirect (`will redirect to fallback '<next>'`, or `none, end of the fallback line`), and the final outcome (`_request_outcome`: which fallback answered HTTP 200 ok, or that all N routes failed with the last error). The pre-existing fields are unchanged (model, upstream host, error class, status, scrubbed upstream text capped at 300 chars, retries, cooldown), so every breaker in a multi-layer line notifies exactly once, with the complete route and the eventual result. A request that trips nothing notifies nothing; an already-open breaker re-notifies nothing (transition-only, no per-rejection spam). Passthrough has no route or fallback line, so its global trips notify with the default model as the local config and an explicit no-fallback line. Kill switch `gateway_target_circuit_enabled` (Reliability, default on). Open models appear in `metrics()["targets_open"]`. Not persisted across restarts, per worker, no single-probe half-open guard (bounded by the semaphore). Vision uses its own `_vision_breaker` outside `_send`, but its opening transition joins the same per-request `trip_sink` (local config `vision:<model>`, no fallback line) and notifies with the request final outcome. Tests: the `test_trip_*`, `test_a_failed_target_*`, `test_one_bad_request_*`, `test_target_breaker_kill_switch_*`, `test_shape_fixable_400_*`, `test_embedded_200_error_*`, `test_breaker_is_per_model_across_upstreams`, `test_a_request_without_a_model_*`, `test_transition_notifies_*`, `test_trip_notification_*`, `test_trip_notification_redirects_unrouted_default_to_first_fallback`, `test_vision_trip_notifies_with_local_config_and_no_fallback`, `test_trip_notification_outcome_scrubs_secrets` and `test_passthrough_global_trip_carries_local_config` unit tests in `tests/unit/services/openai_gateway/gateway.py`, and the real-server integration tests in `tests/api/admin/gateway/circuit.py` (a local fake upstream behind a routed provider: trip on first error, no second upstream call, one notification per admin with no key leaked, isolation between models, one shared breaker per model across providers, bad request not re-sent, shape-fixable 400 left closed, healthy target silent).
|
||||
- **A 400 is terminal UNLESS its body names rejected keys** the auto-resolve ladder can fix (see "Auto-resolve of request shape"): that case is retried on the SAME route with another shape before any fallback is considered.
|
||||
- **Deliberately NOT covered:** `gateway_max_retries`/`gateway_retry_backoff_ms`, the circuit breaker, and hard docker-adjacent settings are untouched - fallback is additive on top of them, not a replacement retry mechanism.
|
||||
|
||||
**Tests:** `tests/unit/services/openai_gateway/routing.py` (`resolve_fallback` self-reference/kind/active-flag guards, chain skip/cycle/hop-cap/entry tests), `tests/unit/services/openai_gateway/gateway.py` (`test_chat_falls_back_when_the_primary_model_fails`, `test_chat_returns_the_fallback_failure_when_both_models_fail`, `test_chat_without_a_fallback_never_makes_a_second_call`, `test_chat_walks_fallback_chain_past_failures`, `test_chat_preroutes_around_unhealthy_models`, `test_chat_tries_original_when_chain_is_exhausted`), and `tests/api/admin/gateway/models.py` (`test_model_route_fallback_round_trip`, `test_model_route_fallback_must_reference_an_existing_route`, `test_model_route_fallback_must_be_the_same_kind`, `test_model_route_fallback_rejects_self_reference`).
|
||||
@@ -337,15 +361,68 @@ The `muse` headers are defense in depth, NOT the attestation fix:
|
||||
probes proved the key works from any client/TLS stack for plain calls
|
||||
and the gate only fires on reserved `tools[].name` values. The real
|
||||
fix is automatic tool-name aliasing (`muse_code.tool_aliases_for` /
|
||||
`alias_chat_tools`, wired in `_chat_upstream_body` for Meta Responses
|
||||
attempts only): any declared/history/tool_choice name exactly matching
|
||||
`alias_chat_tools`, wired in `_chat_upstream_body` for Meta attempts on
|
||||
BOTH wire protocols): any declared/history/tool_choice name exactly matching
|
||||
`MUSE_RESERVED_TOOL_NAMES` (20 names, each measured denying while
|
||||
near-misses pass) is rewritten to `ext_<name>` (growing underscores
|
||||
on collision) and restored on the way back
|
||||
(`restore_completion_names` / `restore_chunk_names`), so the model
|
||||
(`restore_completion_names` / `restore_chunk_names`, with the alias map
|
||||
threaded through `_stream_chat_response` for streamed chat), so the model
|
||||
sees one consistent world and the client never sees the alias. The
|
||||
map is rebuilt deterministically from the same payload at both ends,
|
||||
so fallbacks crossing providers need no state. Clean requests pass
|
||||
through untouched (same object, no log); aliased ones log
|
||||
map is rebuilt deterministically from the same payload at both ends
|
||||
(`_response_tool_aliases`, protocol-independent), so fallbacks crossing
|
||||
providers need no state. Clean requests pass through untouched (same
|
||||
object, no log, verbatim relay); aliased ones log
|
||||
`Meta reserved tool names aliased: bash->ext_bash, ...`. If 403s
|
||||
return, re-probe: Meta may have added a builtin.
|
||||
|
||||
Incident 2026-11-10 (tai `devplace/molodetz` 403s, Devii unaffected):
|
||||
the gate scans NAMES, not counts. tai's 63-tool catalog shares 7 names
|
||||
with the denylist (`shell`, `read_file`, `write_file`, `edit_file`,
|
||||
`web_fetch`, `web_search`, `search`); Devii's 400+ domain tools share
|
||||
0, so 400 tool calls never tripped it. Three rounds, 2026-11-10: (1) the aliasing
|
||||
originally ran only for `responses`-protocol attempts while tai/detz
|
||||
speak `chat_completions`, so colliding names reached Meta verbatim -
|
||||
fixed by hoisting the aliasing above the protocol branch in
|
||||
`_chat_upstream_body` and restoring names on the chat return paths
|
||||
(non-streaming re-encode, streamed chunk restore); (2) the denylist was
|
||||
missing `shell`, which tai/detz send on EVERY turn (first entry of
|
||||
`CORE_TOOLS`, core loads always) - added (21 names), corroborated by
|
||||
Pi's `pi-meta-oauth` denylist, live via `--reload` 18:26; (3) REFUTED
|
||||
18:33: requests with all 5 known triggers aliased (`shell->ext_shell`
|
||||
on the wire) plus stamped `muse` profile STILL 403. The 21-name gate
|
||||
theory is therefore insufficient. Remaining fork: another ungated name
|
||||
in the payload (candidates never probed by anyone: `web_fetch`,
|
||||
`fork`, `poll`, `ask_user`, `remember`, `recall`, `load_skill`, ...),
|
||||
the `ext_` scheme itself recognized, or the key fully gated for
|
||||
non-genuine clients. Discriminator: two authenticated direct calls
|
||||
against the route, one tool-less and one with a single clean tool -
|
||||
see the research conclusion for the exact probes. If the tool-less call
|
||||
also 403s, stop guessing names and put a pay-as-you-go key on the
|
||||
route. Outcome 19:05, after a clean service restart: single-name live
|
||||
probes proved `web_fetch` denied alone (added as 22nd name) while
|
||||
`fork`, `poll`, `ask_user`, `remember`, `recall`, `load_skill`,
|
||||
`ext_shell` each 200 alone; the full 63-tool tai catalog then 200d in
|
||||
one call, and the journal shows `web_fetch->ext_web_fetch` aliasing on
|
||||
real traffic with 9 upstream 200s and 0 403s since. The gate is names,
|
||||
the denylist at 22 covers the whole static catalog, no key change
|
||||
needed. Count caps measured live 2026-11-10 on the Meta route
|
||||
(native `tools_mode`): 70, 100, 200 and 400 tools per call all HTTP
|
||||
200 (63 real catalog names plus synthetic clean names) - there is no
|
||||
count gate on this path. The only count cap in the system is the
|
||||
gateway's own emulated-tools path (which had a 64-tool cap until
|
||||
it was removed from the working tree the same day - `test_large_catalogs_are_served_with_no_cap`
|
||||
pins 424 tools served, unrelated
|
||||
to Meta). The companion
|
||||
`openrouter/... 401 No cookie auth credentials found` in the same
|
||||
report is unrelated: tai calling OpenRouter with no API key
|
||||
configured, an operator setup gap, not a gateway behavior. Tests:
|
||||
`tests/unit/services/openai_gateway/gateway.py`
|
||||
(`test_meta_tool_names_aliased_on_wire_and_restored` /
|
||||
`test_meta_tool_names_restored_on_stream_chunks` for Responses,
|
||||
`test_meta_tool_names_aliased_on_chat_completions_wire` /
|
||||
`test_meta_tool_names_restored_on_chat_completions_stream` for chat,
|
||||
the chat tests pin `shell`+`read_file` end to end)
|
||||
and `tests/unit/services/openai_gateway/muse_code.py` (denylist
|
||||
membership + alias/round-trip unit tests). Full external-research
|
||||
record: `research/muse-attestation-gate/` in the tai project.
|
||||
|
||||
@@ -13,7 +13,7 @@ SYSTEM_PREAMBLE_DEFAULT = ""
|
||||
THINKING_DEFAULT = False
|
||||
|
||||
VISION_URL_DEFAULT = "https://openrouter.ai/api/v1/chat/completions"
|
||||
VISION_MODEL_DEFAULT = "google/gemma-3-12b-it"
|
||||
VISION_MODEL_DEFAULT = "google/gemma-4-31b-it"
|
||||
VISION_CACHE_SIZE_DEFAULT = 256
|
||||
|
||||
EMBED_URL_DEFAULT = "https://openrouter.ai/api/v1/embeddings"
|
||||
@@ -50,4 +50,5 @@ MODEL_CONTEXT_MAP_DEFAULT = {
|
||||
"deepseek-chat": 1_048_576,
|
||||
"deepseek-reasoner": 1_048_576,
|
||||
"google/gemma-3-12b-it": 8192,
|
||||
"google/gemma-4-31b-it": 262144,
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,165 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from devplacepy.database import (
|
||||
bump_cache_version,
|
||||
db,
|
||||
get_table,
|
||||
sync_local_cache,
|
||||
)
|
||||
from devplacepy.services.openai_gateway.shape import ShapeMethod
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TABLE = "gateway_learned_methods"
|
||||
CACHE_NAME = "gateway_learned"
|
||||
MAX_LEARNED_ROWS = 1000
|
||||
DEFAULT_PROVIDER = "default"
|
||||
|
||||
_LEARNED_CACHE: dict = {}
|
||||
|
||||
|
||||
class LearnedResetIn(BaseModel):
|
||||
provider: str = Field(default="", max_length=120)
|
||||
target_model: str = Field(min_length=1, max_length=200)
|
||||
|
||||
@field_validator("provider", "target_model")
|
||||
@classmethod
|
||||
def _strip(cls, value: str) -> str:
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _provider_key(provider: Optional[str]) -> str:
|
||||
return (provider or DEFAULT_PROVIDER).strip().lower() or DEFAULT_PROVIDER
|
||||
|
||||
|
||||
def ensure_table() -> None:
|
||||
db.query(
|
||||
"CREATE TABLE IF NOT EXISTS "
|
||||
+ TABLE
|
||||
+ " (id INTEGER PRIMARY KEY, provider TEXT, target_model TEXT, "
|
||||
"method TEXT, learned_at TEXT)"
|
||||
)
|
||||
try:
|
||||
db.query(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_gateway_learned_route ON "
|
||||
+ TABLE
|
||||
+ " (provider, target_model)"
|
||||
)
|
||||
db.query(
|
||||
"CREATE INDEX IF NOT EXISTS idx_gateway_learned_at ON "
|
||||
+ TABLE
|
||||
+ " (learned_at)"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("gateway learned index creation failed: %s", exc)
|
||||
|
||||
|
||||
def _load() -> dict:
|
||||
sync_local_cache(CACHE_NAME, _LEARNED_CACHE)
|
||||
if "methods" not in _LEARNED_CACHE:
|
||||
methods: dict = {}
|
||||
try:
|
||||
if TABLE in db.tables:
|
||||
for row in get_table(TABLE).all():
|
||||
method = ShapeMethod.from_json(row.get("method"))
|
||||
if method is None:
|
||||
continue
|
||||
methods[
|
||||
(_provider_key(row.get("provider")), str(row["target_model"]))
|
||||
] = (method, str(row.get("learned_at") or ""))
|
||||
except Exception as exc:
|
||||
logger.warning("gateway learned load failed: %s", exc)
|
||||
_LEARNED_CACHE["methods"] = methods
|
||||
return _LEARNED_CACHE["methods"]
|
||||
|
||||
|
||||
def _invalidate() -> None:
|
||||
bump_cache_version(CACHE_NAME)
|
||||
_LEARNED_CACHE.clear()
|
||||
|
||||
|
||||
class LearnedMethodStore:
|
||||
def get(self, provider: Optional[str], model: str) -> Optional[ShapeMethod]:
|
||||
entry = _load().get((_provider_key(provider), str(model)))
|
||||
return entry[0] if entry else None
|
||||
|
||||
def list(self) -> list[dict]:
|
||||
rows = [
|
||||
{
|
||||
"provider": provider,
|
||||
"target_model": model,
|
||||
"method": method.label,
|
||||
"thinking_dialect": method.thinking_dialect,
|
||||
"drop_keys": list(method.drop_keys),
|
||||
"learned_at": learned_at,
|
||||
}
|
||||
for (provider, model), (method, learned_at) in _load().items()
|
||||
]
|
||||
return sorted(rows, key=lambda r: (r["provider"], r["target_model"]))
|
||||
|
||||
def remember(
|
||||
self, provider: Optional[str], model: str, method: ShapeMethod
|
||||
) -> None:
|
||||
if method.is_native or not model:
|
||||
return
|
||||
try:
|
||||
ensure_table()
|
||||
with db:
|
||||
db.query(
|
||||
"INSERT INTO " + TABLE + " (provider, target_model, method, learned_at) "
|
||||
"VALUES (:provider, :model, :method, :now) "
|
||||
"ON CONFLICT(provider, target_model) DO UPDATE SET "
|
||||
"method = excluded.method, learned_at = excluded.learned_at",
|
||||
provider=_provider_key(provider),
|
||||
model=str(model),
|
||||
method=method.to_json(),
|
||||
now=_now(),
|
||||
)
|
||||
db.query(
|
||||
"DELETE FROM " + TABLE + " WHERE id IN (SELECT id FROM "
|
||||
+ TABLE
|
||||
+ " ORDER BY learned_at ASC, id ASC LIMIT "
|
||||
"MAX((SELECT COUNT(*) FROM " + TABLE + ") - :cap, 0))",
|
||||
cap=MAX_LEARNED_ROWS,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("gateway learned remember failed: %s", exc)
|
||||
return
|
||||
_invalidate()
|
||||
|
||||
def forget(self, provider: Optional[str], model: str) -> bool:
|
||||
if TABLE not in db.tables:
|
||||
return False
|
||||
removed = int(
|
||||
get_table(TABLE).delete(
|
||||
provider=_provider_key(provider), target_model=str(model)
|
||||
)
|
||||
)
|
||||
if removed:
|
||||
_invalidate()
|
||||
return bool(removed)
|
||||
|
||||
def forget_provider(self, provider: str) -> int:
|
||||
if TABLE not in db.tables:
|
||||
return 0
|
||||
table = get_table(TABLE)
|
||||
removed = table.count(provider=_provider_key(provider))
|
||||
if removed:
|
||||
table.delete(provider=_provider_key(provider))
|
||||
_invalidate()
|
||||
return removed
|
||||
|
||||
|
||||
learned_store = LearnedMethodStore()
|
||||
@@ -41,8 +41,12 @@ def _muse_user_agent() -> str:
|
||||
|
||||
# Every one of these trips api.meta.ai's client gate with 403
|
||||
# client_attestation_denied when declared as a tools[] function name
|
||||
# (measured 2026-10-30, all 20 deny, near-misses pass). Text, history,
|
||||
# params, and descriptions are not scanned - only exact tools[].name.
|
||||
# (measured 2026-10-30, all 20 deny, near-misses pass; "shell" and
|
||||
# "web_fetch" added 2026-11-10 after live single-name probes proved
|
||||
# each denied alone - "shell" also independently verified by Pi's
|
||||
# pi-meta-oauth denylist, which names it among its 9 blocking names
|
||||
# while ours covered the other 8). Text, history, params, and
|
||||
# descriptions are not scanned - only exact tools[].name.
|
||||
MUSE_RESERVED_TOOL_NAMES = frozenset(
|
||||
{
|
||||
"workflow",
|
||||
@@ -64,6 +68,8 @@ MUSE_RESERVED_TOOL_NAMES = frozenset(
|
||||
"update_goal",
|
||||
"report_progress",
|
||||
"read_skill",
|
||||
"shell",
|
||||
"web_fetch",
|
||||
"write_todos",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -58,6 +58,10 @@ class CircuitBreaker:
|
||||
if self.threshold > 0 and self.failures >= self.threshold:
|
||||
self.opened_at = time.monotonic()
|
||||
|
||||
def trip(self) -> None:
|
||||
self.failures = max(self.threshold, 1)
|
||||
self.opened_at = time.monotonic()
|
||||
|
||||
|
||||
MAX_RETRY_AFTER_SECONDS = 30.0
|
||||
|
||||
|
||||
@@ -12,10 +12,13 @@ from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
from devplacepy.database import (
|
||||
bump_cache_version,
|
||||
db,
|
||||
get_setting,
|
||||
get_table,
|
||||
set_setting,
|
||||
sync_local_cache,
|
||||
)
|
||||
from devplacepy.services.openai_gateway import muse_code, opencode_zen
|
||||
from devplacepy.services.openai_gateway.learned import learned_store
|
||||
from devplacepy.services.openai_gateway.tool_emulation import (
|
||||
TOOLS_MODE_NATIVE,
|
||||
TOOLS_MODES,
|
||||
@@ -24,6 +27,7 @@ from devplacepy.services.openai_gateway.tool_emulation import (
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PROVIDERS_TABLE = "gateway_providers"
|
||||
DEFAULT_KEY_SETTING = "gateway_api_key"
|
||||
MODELS_TABLE = "gateway_models"
|
||||
CACHE_NAME = "gateway_routing"
|
||||
KINDS = ("chat", "embed", "image")
|
||||
@@ -531,21 +535,41 @@ class ProviderStore:
|
||||
"protocol": payload.protocol,
|
||||
"updated_at": _now(),
|
||||
}
|
||||
endpoint_changed = bool(existing) and (
|
||||
str(existing.get("base_url") or "") != payload.base_url
|
||||
or str(existing.get("client_profile") or "") != payload.client_profile
|
||||
)
|
||||
if existing:
|
||||
table.update({**record, "id": existing["id"]}, ["id"])
|
||||
self._rotate_default_key(str(existing.get("api_key") or ""), payload)
|
||||
else:
|
||||
record["created_at"] = _now()
|
||||
table.insert(record)
|
||||
if endpoint_changed:
|
||||
learned_store.forget_provider(payload.name)
|
||||
bump_cache_version(CACHE_NAME)
|
||||
_ROUTING_CACHE.clear()
|
||||
return self.get(payload.name) or record
|
||||
|
||||
@staticmethod
|
||||
def _rotate_default_key(previous_key: str, payload: ProviderIn) -> None:
|
||||
if not previous_key or not payload.api_key or previous_key == payload.api_key:
|
||||
return
|
||||
if get_setting(DEFAULT_KEY_SETTING, "") != previous_key:
|
||||
return
|
||||
set_setting(DEFAULT_KEY_SETTING, payload.api_key)
|
||||
logger.info(
|
||||
"Provider %s key rotated; default upstream key shared the old value and was rotated with it",
|
||||
payload.name,
|
||||
)
|
||||
|
||||
def remove(self, name: str) -> bool:
|
||||
name = (name or "").strip().lower()
|
||||
if not name or PROVIDERS_TABLE not in db.tables:
|
||||
return False
|
||||
removed = int(get_table(PROVIDERS_TABLE).delete(name=name))
|
||||
if removed:
|
||||
learned_store.forget_provider(name)
|
||||
bump_cache_version(CACHE_NAME)
|
||||
_ROUTING_CACHE.clear()
|
||||
return bool(removed)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user