Compare commits

...
Author SHA1 Message Date
blindxfishandClaude Opus 5.5 17da9cb30c Messages: Facebook-style Chats panel and docked chat windows
The topnav Messages icon opens a Chats panel (people search, recent
conversations, New message, link to the full page). Picking a person
opens a small chat window docked bottom-right; windows minimize to
avatar heads with unread counts and survive navigation within the tab.
Profile Send Message, the live message toast and message notifications
on /notifications open the same window. Phones and /messages keep the
full page.

Each window is dp-chat in mode="window", sharing one WebSocket through
chat/ChatSocketHub.js; chat/ConversationItem.js is the shared row
builder. No server changes.

The message input becomes [+] [text + emoji] [send] everywhere: + reveals
the attach and GIF buttons, which tuck away while typing.

Also fixes linked toasts never receiving clicks (pointer-events).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 13:21:29 +01:00
retoorandClaude Sonnet 5.5 920a679dcf Keep GIF picker tiles at a fixed row height so thumbnails are not squashed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 20:02:46 +01:00
retoorandClaude Sonnet 5.5 05d6633204 Render markdown in gist and project sidebar titles; add content visibility and GIF picker
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 17:59:21 +01:00
retoorandClaude Sonnet 5.5 bc11475f29 Send per-app provider attribution titles from one gateway app registry
Add openai_gateway/apps.py as the single list of internal gateway apps and
send X-OpenRouter-Title (plus legacy X-Title and HTTP-Referer) per app to
every upstream. Label the Devii agent, bots, modifier, quiz grading, SEO
metadata, community and sync callers. Shorten two app references that
exceeded the 30 character limit and were recorded as default.
Also includes the pending Muse Code, route health and Responses work.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 18:45:09 +01:00
retoorandClaude Sonnet 5.5 ec30ed408c Open the profile actions menu before clicking Unblock in the report e2e test
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 11:53:55 +01:00
retoorandClaude Sonnet 5.5 f705099928 Inline YouTube Music embeds with one shared embed spec
YouTube Music has no player of its own and music.youtube.com sends
X-Frame-Options SAMEORIGIN, so music links render YouTube's own player
with an Open in YouTube Music caption. Tracks, playlists and OLAK5uy
albums embed; browse, channel, search and library stay plain links.

- embeds.py is the single URL spec (exact host allowlists, query-order
  independent, validated ids only); embed-spec.js is generated from it by
  the embeds-sync CLI command and drift is tested
- rendering.py and ContentRenderer.js both follow it; the old duplicate
  YouTube regexes are removed
- max 3 music embeds per content item, overflow stays a plain link
- fixes evilyoutube.com matching and watch?feature=share&v=ID links
- fixes the invalid unicode CSS escape that printed u2197 after every
  external link in rendered content
- docs, privacy third-party row, parser table tests, server/client parity

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 11:53:55 +01:00
retoor 762c06886c Ok 2026-10-26 02:55:25 +01:00
retoor 3bfde87fdb Introduce Devii agents subsystem with supervisor, policy, and evals
- Add agents package: controller, runner, store, tools, actions, evals, policy
- Wire agents into Devii service, session, registry, CLI, and dispatcher
- Extend database schema and config for agent persistence
- Add news and telegram bridge updates plus landing UI and docs
- Cover agents, news, and telegram flows with unit tests
2026-10-26 02:54:44 +01:00
retoor 407673bf57 Nodes 2026-10-20 16:58:31 +02:00
retoor 52a4ebbe58 Merge pull request 'Code Farm: front-view server rack and API-backed terminal' (#176) from blindxfish/devplacepy:codex/code-farm-rack-terminal into master
Reviewed-on: retoor/devplacepy#176
2026-10-20 16:52:54 +02:00
263 changed files with 14912 additions and 811 deletions
+6
View File
@@ -105,6 +105,7 @@ 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)
```
@@ -165,6 +166,7 @@ Nested `CLAUDE.md` files (loaded automatically by Claude Code only when a file i
| `devplacepy/services/game/CLAUDE.md` | Code Farm idle game (economy invariants, raids, the one-pure-function rule) |
| `devplacepy/services/opinionwar/CLAUDE.md` | Opinion Wars (week-long faction battles on posts: atomic fight/resolve transitions, cooldown-before-coins compensation, event seq allocation, relay-on-lock-owner) |
| `devplacepy/services/quiz/CLAUDE.md` | Quizzes (the terminal publish lock, attempt atomicity, answer-key withholding, AI free-text grading, the best-attempt scoreboard) |
| `devplacepy/services/giphy/CLAUDE.md` | GIF picker: GIPHY search through the server, admin-held API key, GIFs stored as ordinary attachments, cache and per-user caps |
| `devplacepy/services/skills/CLAUDE.md` | Agent Skills: strict `SKILL.md` parser, SSRF-guarded fetcher, the bounded prompt index, per-user privacy, soft delete and account-deletion cascade, why a skill is data and never code |
| `devplacepy/services/nodes/CLAUDE.md` | Community node network: the protocol specification (single source of truth), the no-open-proxy rule, the two transports and their trust levels, the decisions taken, and the gaps per phase |
| `devplacepy/services/community/CLAUDE.md` | Community discovery: rsearch + feed detection, one-time structure learning, generated collectors, dry run, the failure floor, admin-only visibility |
@@ -205,6 +207,7 @@ Routers in `devplacepy/routers/` are organised as a **directory tree that mirror
| `/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` |
@@ -240,6 +243,8 @@ The CLIENT pipeline (`ContentRenderer.js`, `dp-content`/`dp-title`) is retained
**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.
@@ -307,6 +312,7 @@ The escape hatch is deliberately two-factor and must never be self-served: after
- **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`.
- **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)
+24 -1
View File
@@ -89,7 +89,7 @@ devplacepy/
| `/admin/trash` | Admin **Trash**: review, restore, and permanently purge soft-deleted content (posts, comments, gists, projects, news, project files, attachments) across the platform |
| `/admin/devii-tasks` | Admin **Devii tasks**: every scheduled task across all owners with its schedule, run count, expiry and failure streak, plus per-task disable and delete |
| `/notifications` | Notification list, mark read, live unread counts (`/notifications/counts`) |
| `/messages` | Real-time direct messaging over WebSocket (`/messages/ws`): live bidirectional delivery, optimistic send, typing indicators, read receipts, reconnect catch-up, and online/last-seen presence. Messages render through the shared content pipeline (emoji shortcodes, image, video and audio embeds, autolink, sanitization). AI content correction and the AI modifier apply to direct messages: the original is delivered immediately, then a second `message` frame with `ai_processed` replaces the bubble for both participants when the rewrite lands (including across workers). An opened conversation loads its 500 most recent messages and can page older rows with `?before=`; switching threads does not drop the socket. `GET /messages/conversations` returns the conversation list as JSON for a live client refresh; the `POST /messages/send` form remains as a no-JavaScript fallback and now accepts an attachment-only, empty-content message. `POST /messages/ws-ticket` exchanges a session/API-key auth to a short-lived (30s), single-use ticket a browser WebSocket can carry as `?ticket=...` on the handshake, since a native `WebSocket` cannot set an `Authorization`/`X-API-KEY` header - this is what makes off-session embedding of the chat possible. CLI: `devplace messaging prune-tickets` removes expired tickets |
| `/messages` | Real-time direct messaging over WebSocket (`/messages/ws`): live bidirectional delivery, optimistic send, typing indicators, read receipts, reconnect catch-up, and online/last-seen presence. Messages render through the shared content pipeline (emoji shortcodes, image, video and audio embeds, autolink, sanitization). AI content correction and the AI modifier apply to direct messages: the original is delivered immediately, then a second `message` frame with `ai_processed` replaces the bubble for both participants when the rewrite lands (including across workers). An opened conversation loads its 500 most recent messages and can page older rows with `?before=`; switching threads does not drop the socket. `GET /messages/conversations` returns the conversation list as JSON for a live client refresh; the `POST /messages/send` form remains as a no-JavaScript fallback and now accepts an attachment-only, empty-content message. An administrator can delete the messages they themselves sent (`POST /messages/{uid}/delete`, soft delete, confirmation in the chat UI and in Devii); the bubble disappears live for both participants. `POST /messages/ws-ticket` exchanges a session/API-key auth to a short-lived (30s), single-use ticket a browser WebSocket can carry as `?ticket=...` on the handshake, since a native `WebSocket` cannot set an `Authorization`/`X-API-KEY` header - this is what makes off-session embedding of the chat possible. CLI: `devplace messaging prune-tickets` removes expired tickets. On every other page the topnav Messages icon opens a **Chats** panel (people search, recent conversations, a New message button and a link to the full page), and picking a person opens a small chat window docked at the bottom of the screen, as on Facebook. Up to three windows sit side by side (fewer on narrow screens); a window minimizes to an avatar head that counts unread messages, and open chats survive page navigation within the tab. A profile's Send Message button and a message notification (the live toast and the entry on `/notifications`) open the same docked window instead of leaving the page. Phones keep the full `/messages` page. The message input follows the same layout everywhere: a + button reveals the attachment and GIF buttons, which tuck away again while you type, and the emoji button sits inside the text field |
| `/votes` | Upvote/downvote on posts, comments, projects |
| `/reactions` | Emoji reactions on posts, comments, gists, projects |
| `/bookmarks` | Save/unsave content; `/bookmarks/saved` personal list |
@@ -229,6 +229,10 @@ The rack's **control terminal** supports every current game API route. Try `help
The farm refreshes live over the pub/sub bus (a watered build appears on the owner's screen at once) and every plot countdown ticks client-side. Every endpoint also answers JSON, and Devii can play the game on the member's behalf via the `game_*` tools (`game_state`, `game_plant`, `game_harvest`, `game_plot_stop`, `game_buy_plot`, `game_upgrade_ci`, `game_fertilize`, `game_daily`, `game_claim_quest`, `game_water`, `game_steal`, `game_view_farm`, `game_leaderboard`, `game_upgrade_perk`, `game_upgrade_legacy`, `game_prestige`, `game_claim_grant`, `game_upgrade_mastery`, `game_buy_infrastructure`, `game_upgrade_defense`, `game_buy_cosmetic`, `game_equip_cosmetic`, `game_downgrade_defense`). See the API reference group **Code Farm** and the full player guide at `/docs/code-farm.html`.
## Content visibility
Posts, gists, projects and news carry a status: **published** (default), **hidden**, **offline** or **draft**. Hidden items drop out of every list, search, topic page, profile and the sitemap but still open by direct link (marked `noindex`). Offline and draft items are visible only to their owner and administrators; everyone else gets a 404 and cannot comment, vote, react or bookmark them. The field is optional and backwards compatible: omitted on create it defaults to published, omitted on edit the current value is kept, and old rows read as published. Owners set it with the Visibility field in the create and edit forms (and the `visibility` parameter of the API and the Devii create and edit tools); administrators set a news article's status from the admin news page (`POST /admin/news/{uid}/visibility`, Devii `admin_set_news_visibility`). The specification is `devplacepy/database/visibility.py` (a NULL value reads as published, so no data migration), and the user-facing page is `/docs/content-visibility.html`. The website offers published, hidden and offline; draft is accepted by the API and reserved for a future drafting flow.
## Engagement
- **Emoji reactions** - react with **any** emoji on posts, comments, gists, and projects, separate from voting and carrying no ranking weight. A short quick-pick palette covers the common reactions, and a `+` button next to it opens the full searchable emoji picker (every standard emoji, including skin tones), so a reaction is never limited to a preset list. Emoji already used on an item are shown as counted chips beside the palette.
@@ -256,6 +260,12 @@ DevPlace is open in the sense that it does not editorialise technical opinion. I
- **Account deletion.** Self-service at `/profile/{username}/delete`, reauthenticated with the account password. Sessions and tokens are revoked, the profile is anonymised immediately, and all content is removed under one deletion event that stays restorable for `account_deletion_grace_hours` (default 24) before `devplace accounts prune` (and the Moderation housekeeping service) purges it permanently. The devRant `DELETE /api/users/me` routes into the same cascade.
- **Legal pages**: [Terms of Service](/docs/terms.html), [Community Guidelines](/docs/community-guidelines.html), [Privacy Policy](/docs/privacy.html), [How moderation works](/docs/content-moderation.html), [Notice and takedown](/docs/intellectual-property.html) and [Contact](/docs/contact.html). All six are indexed in the sitemap and reachable from the docs index; the footer of every page links Terms, Privacy, Community Guidelines and Contact. Contact details come from the `contact_email`, `contact_phone` and `contact_address` settings, so the in-product page and any app-store trader declaration have one source of truth.
## GIF picker (GIPHY)
A "GIF" button beside the attachment button in the post composer, every comment form and the message input (behind its + button) opens a searchable GIPHY panel (trending first, "Powered by GIPHY" attribution). A picked GIF is downloaded by the server and stored as an ordinary attachment, so it renders in the attachment gallery, can be reported and deleted like any file, and counts against the normal attachment limits.
An administrator enters the GIPHY API key under **Admin > Services > Giphy** (also the content rating, default `pg`, and the API base URL); the key is stored in `site_settings`, never reaches a browser, and the button stays hidden until it is set. Searches run on the server, are cached for five minutes, and each member may make 30 per minute. Routes: `GET /giphy/status`, `/giphy/search?q=`, `/giphy/trending`, `POST /giphy/attach` (documented under Uploads at `/docs/uploads.html`); Devii has `search_gifs`, `trending_gifs` and `attach_gif`. Details: `devplacepy/services/giphy/CLAUDE.md`.
## Skills
Members can install [Agent Skills](https://agentskills.io) from a URL at `/skills` so Devii can use them. A skill is a `SKILL.md` (YAML frontmatter plus markdown instructions) with optional text files under `scripts/`, `references/` and `assets/`. Skills are private to their owner, count against a per-user cap, and only the name and a one-line description of enabled skills are added to Devii's system prompt; Devii loads the full text on demand. A skill is untrusted third-party text: it can never grant Devii a tool, bypass a confirmation or run a script. Deleting a skill is a soft delete and needs confirmation when Devii does it. Documented in the API docs under *Skills* and in `devplacepy/services/skills/CLAUDE.md`.
@@ -1188,6 +1198,19 @@ Two background services bridge persisted state onto the bus so the interface upd
- Session-scoped browser context with per-test cookie clearing
- `page.locator(...).wait_for(state="visible")` preferred over bare selectors
## Media embeds (YouTube and YouTube Music)
A bare YouTube or YouTube Music link in a post, comment, message or description renders as an inline player. YouTube Music has no player of its own: its track and playlist ids are YouTube's, so the embed is YouTube's own player, shown with an "Open in YouTube Music" caption that links back to the original.
| Link | Result |
|------|--------|
| `youtube.com/watch?v=ID`, `youtu.be/ID`, `/embed/ID`, `/v/ID`, `/shorts/ID`, `m.` and `-nocookie` hosts | Video player; `t=` / `start=` seconds are kept |
| `music.youtube.com/watch?v=ID[&list=ID]` | Track player with the caption, queue kept when `list=` is a valid playlist id |
| `music.youtube.com/playlist?list=ID`, `youtube.com/playlist?list=ID` | Playlist or album player (`OLAK5uy...` album ids work) |
| `music.youtube.com/browse/...`, `/channel/...`, `/search`, `/library` | Plain link: these URLs carry no playlist id |
Parsing is by exact host allowlist and query parameter, in any order, so look-alike hosts such as `evilyoutube.com` never embed. A single post renders at most 3 music embeds; further music links stay plain links. The URL rules live in one place, `devplacepy/embeds.py`; the browser gets them through the generated `static/js/embed-spec.js` (`devplace embeds-sync` after changing the table, never hand-edit) and `static/js/EmbedParser.js`. A unit test fails when the generated file drifts and an e2e test runs one shared case table through both parsers.
## Avatars
Uses [Multiavatar](https://github.com/multiavatar/multiavatar-python) - generates deterministic SVG avatars locally from a seed string (the username). No external API calls, no network dependency. Generation takes <5ms. Results are cached in-memory (cleared on server restart).
+2 -1
View File
@@ -44,7 +44,7 @@ from devplacepy.cli.containers import (
cmd_containers_gc_workspaces,
)
from devplacepy.cli.quiz import cmd_quiz_prune
from devplacepy.cli.migrate import cmd_emoji_sync, cmd_migrate_data
from devplacepy.cli.migrate import cmd_embeds_sync, cmd_emoji_sync, cmd_migrate_data
from devplacepy.cli.system import cmd_system_prune
__all__ = [
@@ -90,6 +90,7 @@ __all__ = [
"cmd_containers_prune_builds",
"cmd_containers_gc_workspaces",
"cmd_quiz_prune",
"cmd_embeds_sync",
"cmd_emoji_sync",
"cmd_migrate_data",
"cmd_system_prune",
+13
View File
@@ -131,6 +131,14 @@ def cmd_emoji_sync(args):
print(f"Wrote {count} emoji shortcodes to {EMOJI_JS_PATH}")
def cmd_embeds_sync(args):
from devplacepy.embeds import EMBED_JS_PATH, EmbedParser
count = EmbedParser.write_module()
_audit_cli("cli.embeds.sync", f"CLI regenerated the embed spec ({count} keys)", metadata={"count": count})
print(f"Wrote {count} embed spec keys to {EMBED_JS_PATH}")
def cmd_migrate_data(args):
import os
from pathlib import Path
@@ -221,6 +229,11 @@ def register_migrate(subparsers):
help="Regenerate static/js/emoji-shortcodes.js from the emoji library",
).set_defaults(func=cmd_emoji_sync)
subparsers.add_parser(
"embeds-sync",
help="Regenerate static/js/embed-spec.js from devplacepy/embeds.py",
).set_defaults(func=cmd_embeds_sync)
migrate = subparsers.add_parser(
"migrate-data",
help="Relocate legacy runtime files into the consolidated data/ directory",
+4
View File
@@ -92,6 +92,10 @@ INTERNAL_IMAGE_MODEL = "molodetz-img-small"
AQUALITY_NEWS_GRADING_URL = "https://aquality.cloud.pravda.education/v1/chat/completions"
AQUALITY_NEWS_GRADING_MODEL = "aquality"
# The aquality scoring service above was retired (no backend serves that
# hostname anymore), so news grading defaults back to the internal gateway.
# Kept so the settings migration can recognize and heal stale values.
NEWS_GRADING_MODEL_DEFAULT = "free"
AWARD_GIVE_COOLDOWN_HOURS_DEFAULT = 24
AWARD_RECEIVE_COOLDOWN_HOURS_DEFAULT = 24
+140 -5
View File
@@ -41,6 +41,13 @@ from devplacepy.database import (
db,
get_user_recent_items,
invalidate_user_recent_cache,
VISIBILITY_COLUMNS,
TARGET_TABLES,
item_visibility,
is_listed,
is_open,
listed_clause,
normalize_visibility,
)
from devplacepy.utils import (
time_ago,
@@ -67,7 +74,14 @@ from devplacepy.services.moderation.screening import (
screen_fields,
)
CREATE_METADATA_KEYS = ("project_type", "is_private", "language", "topic", "status")
CREATE_METADATA_KEYS = (
"project_type",
"is_private",
"language",
"topic",
"status",
"visibility",
)
BOOKMARKABLE_TYPES = {"post", "gist", "project", "news", "quiz"}
REACTABLE_TYPES = {"post", "comment", "gist", "project", "quiz"}
@@ -95,6 +109,26 @@ def is_owner(item: dict | None, user: dict | None) -> bool:
return bool(item and user and item["user_uid"] == user["uid"])
def can_view_item(table_name: str, item: dict | None, user: dict | None) -> bool:
if not item:
return False
if is_open(table_name, item):
return True
if not user:
return False
return bool(item.get("user_uid") == user.get("uid") or is_admin(user))
def can_view_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
return can_view_item(table_name, item, user)
def mature_hidden_by_default() -> bool:
return get_int_setting("moderation_mature_default_hidden", 1) != 0
@@ -128,6 +162,8 @@ def _owner_is_admin(project: dict) -> bool:
def can_view_project(project: dict | None, user: dict | None) -> bool:
if not project:
return False
if not can_view_item("projects", project, user):
return False
if not project.get("is_private"):
return True
if is_owner(project, user):
@@ -138,14 +174,17 @@ def can_view_project(project: dict | None, user: dict | None) -> bool:
def get_user_sidebar_gists(user_uid: str, limit: int = 5) -> list[dict]:
return get_user_recent_items("gists", user_uid)[:limit]
rows = get_user_recent_items("gists", user_uid)
return [g for g in rows if is_listed("gists", g)][:limit]
def get_user_sidebar_projects(
user_uid: str, viewer: dict | None, limit: int = 5
) -> list[dict]:
rows = get_user_recent_items("projects", user_uid)
visible = [p for p in rows if can_view_project(p, viewer)]
visible = [
p for p in rows if is_listed("projects", p) and can_view_project(p, viewer)
]
return visible[:limit]
@@ -246,6 +285,13 @@ def first_image_url(item: dict, attachments: list | None) -> str | None:
return None
def _with_visibility(table_name: str, fields: dict) -> dict:
column = VISIBILITY_COLUMNS.get(table_name)
if not column:
return fields
return {**fields, column: normalize_visibility(fields.get(column))}
def create_content_item(
table_name: str,
target_type: str,
@@ -258,6 +304,7 @@ def create_content_item(
attachment_uids: list | None,
request=None,
) -> tuple[str, str]:
fields = _with_visibility(table_name, fields)
screening = screen_fields(table_name, fields)
refuse_if_blocked(screening)
uid = generate_uid()
@@ -284,7 +331,10 @@ def create_content_item(
award_rewards(user["uid"], xp, badge)
if attachment_uids:
link_attachments(attachment_uids, target_type, uid)
create_mention_notifications(mention_text, user["uid"], f"/{table_name}/{slug}")
if is_open(table_name, fields):
create_mention_notifications(
mention_text, user["uid"], f"/{table_name}/{slug}"
)
logger.info(f"{target_type} {uid} created by {user['username']}")
label = fields.get("title") or slug
links = [audit.target(target_type, uid, label)]
@@ -667,6 +717,81 @@ def detail_context(
return context
def apply_visibility(
request,
table_name: str,
target_type: str,
user: dict,
item: dict,
value: str,
) -> tuple[str, str]:
column = VISIBILITY_COLUMNS[table_name]
old_value = item_visibility(table_name, item)
new_value = normalize_visibility(value)
get_table(table_name).update({"uid": item["uid"], column: new_value}, ["uid"])
owner_uid = item.get("user_uid")
if owner_uid:
invalidate_user_recent_cache(table_name, owner_uid)
if table_name == "posts":
clear_user_post_count(owner_uid)
if table_name == "projects":
from devplacepy.templating import clear_user_projects_cache
clear_user_projects_cache(owner_uid)
label = item.get("title") or item["uid"]
logger.info(
f"{target_type} {item['uid']} visibility {old_value} -> {new_value} by {user['username']}"
)
audit.record(
request,
f"{target_type}.visibility.set",
user=user,
target_type=target_type,
target_uid=item["uid"],
target_label=label,
old_value=old_value,
new_value=new_value,
summary=f"{user['username']} set {target_type} {label} to {new_value}",
links=[audit.target(target_type, item["uid"], label)],
)
return old_value, new_value
def set_visibility_item(
request,
table_name: str,
target_type: str,
user: dict,
slug: str,
value: str,
redirect_fail: str,
):
from devplacepy.responses import action_result, wants_json, json_error
item = resolve_by_slug(get_table(table_name), slug)
if not item or not is_admin(user):
audit.record(
request,
f"{target_type}.visibility.set",
user=user,
result="denied",
target_type=target_type,
target_uid=item["uid"] if item else slug,
target_label=item.get("title") if item else slug,
summary=f"{user['username']} denied changing visibility of {target_type} {slug}",
)
if wants_json(request):
return json_error(403, "Not allowed")
return RedirectResponse(url=redirect_fail, status_code=302)
_, new_value = apply_visibility(request, table_name, target_type, user, item, value)
url = f"/{table_name}/{item.get('slug') or item['uid']}"
return action_result(
request,
url,
data={"uid": item["uid"], "visibility": new_value, "url": url},
)
def edit_content_item(
request,
table_name: str,
@@ -681,6 +806,7 @@ def edit_content_item(
kind = target_type or table_name.rstrip("s")
table = get_table(table_name)
item = resolve_by_slug(table, slug)
visibility_value = update_fields.pop("visibility", None)
if not is_owner(item, user):
audit.record(
request,
@@ -703,6 +829,10 @@ def edit_content_item(
}
table.update({"uid": item["uid"], **update_fields}, ["uid"])
invalidate_user_recent_cache(table_name, item["user_uid"])
if visibility_value is not None and normalize_visibility(
visibility_value
) != item_visibility(table_name, item):
apply_visibility(request, table_name, kind, user, item, visibility_value)
record_screening(
screening,
target_type=kind,
@@ -817,6 +947,8 @@ def load_detail(
item = resolve_by_slug(get_table(table_name), slug)
if not item:
return None
if not can_view_item(table_name, item, user):
return None
if user and item["user_uid"] in get_blocked_uids(user["uid"]):
return None
author = get_users_by_uids([item["user_uid"]]).get(item["user_uid"])
@@ -898,7 +1030,10 @@ def enrich_items(
def count_project_devlog(project_uid: str) -> int:
return get_table("posts").count(project_uid=project_uid, deleted_at=None)
posts = get_table("posts")
listed = listed_clause(posts)
clauses = [listed] if listed is not None else []
return posts.count(*clauses, project_uid=project_uid, deleted_at=None)
def get_project_devlog(
+21 -2
View File
@@ -198,8 +198,8 @@ Site settings are seeded on startup (`site_settings` table):
| `site_name` / `site_description` / `site_tagline` | DevPlace branding | General site metadata |
| `news_grade_threshold` | `"7"` | Minimum AI grade for auto-publish |
| `news_api_url` | `"https://news.app.molodetz.nl/api"` | News source API |
| `news_ai_url` | `"https://aquality.cloud.pravda.education/v1/chat/completions"` | AI grading endpoint - the free, local aquality quality model by default (see `devplacepy/services/news/CLAUDE.md`) |
| `news_ai_model` | `"aquality"` | AI model identifier |
| `news_ai_url` | internal AI gateway (`INTERNAL_GATEWAY_URL`) | AI grading endpoint - the gateway's free model pool by default (see `devplacepy/services/news/CLAUDE.md`) |
| `news_ai_model` | `"free"` | AI model identifier |
| `max_upload_size_mb` / `allowed_file_types` / `max_attachments_per_resource` | `"10"` / `""` / `"10"` | Upload limits |
| `rate_limit_per_minute` | `"60"` | Mutating requests per IP per window (`main.py` middleware); a `429` carries a `Retry-After: <window>` header |
| `rate_limit_window_seconds` | `"60"` | Rolling window for the rate limit (also the `Retry-After` value) |
@@ -246,3 +246,22 @@ Operational settings - read sites and rules:
**Booleans are `<select>`, never checkboxes.** The settings save handler (`admin.py`) skips empty form values so empty fields don't clobber existing rows. An unchecked checkbox submits nothing, so it could never be turned off - `registration_open` and `maintenance_mode` use `<option value="1">`/`<option value="0">` so a value is always submitted.
## Content visibility (`database/visibility.py`, the single specification)
Posts, gists, projects and news carry one status from `VISIBILITY_VALUES`: `published` (default), `hidden`, `draft`, `offline`. The module is the specification; routers, forms, schemas, templates, Devii and the docs import it and never repeat a literal.
| Status | Listed (feed, search, topics, profiles, sitemap, counters) | Opens by link | Who |
|---|---|---|---|
| `published` | yes | yes | everyone |
| `hidden` | no | yes, `noindex,nofollow` | everyone with the link |
| `offline` | no | no (404) | owner and administrators |
| `draft` | no | no (404) | owner and administrators; accepted by every API but not offered by the UI (`VISIBILITY_CHOICES` is the three user-facing values) |
- **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.
- **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.
+24
View File
@@ -7,6 +7,7 @@ from .settings import _settings_cache, get_setting, get_int_setting, set_setting
from .users import get_users_by_uids, _admins_cache, invalidate_admins_cache, get_admin_uids, set_user_timezone, set_last_seen, get_online_users, get_primary_admin_uid, is_account_active, search_users_by_username
from .relations import _relations_cache, get_user_relations, get_blocked_uids, get_muted_uids, get_silenced_uids, invalidate_user_relations
from .pagination import PAGE_SIZE, paginate, interleave_by_author, paginate_diverse, get_user_post_count, clear_user_post_count, build_pagination
from .visibility import PUBLISHED, HIDDEN, DRAFT, OFFLINE, VISIBILITY_VALUES, VISIBILITY_CHOICES, DEFAULT_VISIBILITY, LISTED_VALUES, OPEN_VALUES, VISIBILITY_COLUMNS, TARGET_TABLES, VISIBILITY_LABELS, VISIBILITY_HINTS, normalize_visibility, visibility_column, item_visibility, is_listed, is_open, listed_clause, listed_sql, ensure_visibility_columns, visibility_options, visibility_label
from .soft_delete import SOFT_DELETE_TABLES, ensure_soft_delete_columns, soft_delete, soft_delete_in, restore, purge, list_deleted, count_deleted, restore_event, purge_event
from .engagement import _comment_count_cache, get_comment_counts_by_post_uids, get_post_counts_by_user_uids, get_vote_counts, get_user_votes, get_reactions_by_targets, get_user_bookmarks, get_user_notes, get_polls_by_post_uids, get_poll_for_post
from .usage import _add_usage, _get_usage, add_correction_usage, get_correction_usage, add_modifier_usage, get_modifier_usage, NEWS_USAGE_KEY, add_news_usage, get_news_usage, ISSUE_USAGE_KEY, add_issue_usage, get_issue_usage, SEO_USAGE_KEY, add_seo_usage, get_seo_usage, AWARD_USAGE_KEY, add_award_usage, get_award_usage
@@ -143,6 +144,29 @@ __all__ = [
"clear_user_post_count",
"build_pagination",
"SOFT_DELETE_TABLES",
"PUBLISHED",
"HIDDEN",
"DRAFT",
"OFFLINE",
"VISIBILITY_VALUES",
"VISIBILITY_CHOICES",
"DEFAULT_VISIBILITY",
"LISTED_VALUES",
"OPEN_VALUES",
"VISIBILITY_COLUMNS",
"TARGET_TABLES",
"VISIBILITY_LABELS",
"VISIBILITY_HINTS",
"normalize_visibility",
"visibility_column",
"item_visibility",
"is_listed",
"is_open",
"listed_clause",
"listed_sql",
"ensure_visibility_columns",
"visibility_options",
"visibility_label",
"ensure_soft_delete_columns",
"soft_delete",
"soft_delete_in",
+2 -1
View File
@@ -1,6 +1,7 @@
# retoor <retoor@molodetz.nl>
from .core import TTLCache, datetime, db, timedelta, timezone
from .visibility import listed_sql
def record_activity(user_uid: str, action: str) -> int:
@@ -79,7 +80,7 @@ def get_activity_calendar(user_uid: str) -> dict:
if sources:
cutoff = (datetime.now(timezone.utc) - timedelta(days=364)).date().isoformat()
union = " UNION ALL ".join(
f"SELECT created_at FROM {table} WHERE user_uid = :u AND deleted_at IS NULL"
f"SELECT created_at FROM {table} WHERE user_uid = :u AND deleted_at IS NULL AND {listed_sql(table)}"
for table in sources
)
rows = db.query(
+2
View File
@@ -7,6 +7,7 @@ from collections import Counter
from devplacepy.cache import TTLCache
from .core import db, get_table, or_
from .visibility import listed_sql
_daily_topic_cache = TTLCache(ttl=60, max_size=1)
_trending_cache = TTLCache(ttl=15, max_size=1)
@@ -284,6 +285,7 @@ def get_trending_topics(limit: int = 6) -> list[dict]:
return []
rows = db.query(
"SELECT topic FROM posts WHERE deleted_at IS NULL "
f"AND {listed_sql('posts')} "
"AND topic IS NOT NULL AND topic != '' "
"ORDER BY created_at DESC LIMIT 200"
)
+1
View File
@@ -16,6 +16,7 @@ from devplacepy.config import (
DEFAULT_CORRECTION_PROMPT,
DEFAULT_MODIFIER_PROMPT,
INTERNAL_GATEWAY_URL,
NEWS_GRADING_MODEL_DEFAULT,
ensure_data_dirs,
)
+2 -1
View File
@@ -1,6 +1,7 @@
# retoor <retoor@molodetz.nl>
from .core import TTLCache, _in_clause, db, defaultdict
from .visibility import listed_sql
_comment_count_cache = TTLCache(ttl=15, max_size=10000)
@@ -36,7 +37,7 @@ def get_post_counts_by_user_uids(user_uids):
return {}
placeholders, params = _in_clause(user_uids)
rows = db.query(
f"SELECT user_uid, COUNT(*) as c FROM posts WHERE user_uid IN ({placeholders}) AND deleted_at IS NULL GROUP BY user_uid",
f"SELECT user_uid, COUNT(*) as c FROM posts WHERE user_uid IN ({placeholders}) AND deleted_at IS NULL AND {listed_sql('posts')} GROUP BY user_uid",
**params,
)
return {r["user_uid"]: r["c"] for r in rows}
+10 -1
View File
@@ -3,6 +3,7 @@
from devplacepy.cache import TTLCache
from .core import db, get_table
from .relations import get_blocked_uids
from .visibility import listed_clause
PAGE_SIZE = 25
@@ -19,10 +20,14 @@ def paginate(
cursor_field="created_at",
viewer_uid=None,
limit=PAGE_SIZE,
include_unlisted_of=None,
**filters,
):
order = order or ["-" + cursor_field]
clauses = list(clauses)
listed = listed_clause(table, own_uid=include_unlisted_of)
if listed is not None:
clauses.append(listed)
if table.has_column("deleted_at") and "deleted_at" not in filters:
clauses.append(table.table.columns.deleted_at.is_(None))
if viewer_uid and table.has_column("user_uid"):
@@ -66,6 +71,7 @@ def paginate_diverse(
uid_key="user_uid",
viewer_uid=None,
limit=PAGE_SIZE,
include_unlisted_of=None,
**filters,
):
rows, next_cursor = paginate(
@@ -76,6 +82,7 @@ def paginate_diverse(
cursor_field=cursor_field,
viewer_uid=viewer_uid,
limit=limit,
include_unlisted_of=include_unlisted_of,
**filters,
)
return interleave_by_author(rows, uid_key=uid_key), next_cursor
@@ -91,7 +98,9 @@ def get_user_post_count(user_uid: str) -> int:
return cached
if "posts" not in db.tables:
return 0
count = get_table("posts").count(user_uid=user_uid, deleted_at=None)
listed = listed_clause(get_table("posts"))
clauses = [listed] if listed is not None else []
count = get_table("posts").count(*clauses, user_uid=user_uid, deleted_at=None)
_user_post_count_cache.set(user_uid, count)
return count
+55 -9
View File
@@ -1,9 +1,10 @@
# retoor <retoor@molodetz.nl>
from devplacepy.services.nodes.spec import SPEC as NODES_SPEC
from .core import AQUALITY_NEWS_GRADING_MODEL, AQUALITY_NEWS_GRADING_URL, DEFAULT_CORRECTION_PROMPT, DEFAULT_MODIFIER_PROMPT, INTERNAL_GATEWAY_URL, _drop_index, _index, _uid_index, db, defaultdict, get_table, logger
from .core import AQUALITY_NEWS_GRADING_MODEL, AQUALITY_NEWS_GRADING_URL, DEFAULT_CORRECTION_PROMPT, DEFAULT_MODIFIER_PROMPT, INTERNAL_GATEWAY_URL, NEWS_GRADING_MODEL_DEFAULT, _drop_index, _index, _uid_index, db, defaultdict, get_table, logger
from .settings import get_setting, set_setting
from .soft_delete import SOFT_DELETE_TABLES, ensure_soft_delete_columns
from .visibility import ensure_visibility_columns
from .ranking import _authors_cache
@@ -181,6 +182,8 @@ def init_db():
("created_at", ""),
("updated_at", ""),
("client_id", ""),
("deleted_at", ""),
("deleted_by", ""),
):
if not messages.has_column(column):
messages.create_column_by_example(column, example)
@@ -584,6 +587,41 @@ def init_db():
_index(
db, "devii_tasks", "idx_devii_tasks_due", ["enabled", "status", "next_run_at"]
)
agent_runs = get_table("devii_agent_runs")
for column, example in (
("uid", ""),
("owner_kind", ""),
("owner_id", ""),
("channel", ""),
("category", ""),
("label", ""),
("task", ""),
("output_format", ""),
("tools_extra", ""),
("effort", ""),
("task_scope", 0),
("status", ""),
("progress", ""),
("result", ""),
("error", ""),
("checks", 0),
("nudges_used", 0),
("retries_used", 0),
("error_streak", 0),
("iterations", 0),
("tokens", 0),
("cost_usd", 0.0),
("needs_question", ""),
("pending_ask_id", ""),
("check_at", ""),
("last_progress_at", ""),
("created_at", ""),
("updated_at", ""),
):
if not agent_runs.has_column(column):
agent_runs.create_column_by_example(column, example)
_index(db, "devii_agent_runs", "idx_devii_agents_owner", ["owner_kind", "owner_id"])
_index(db, "devii_agent_runs", "idx_devii_agents_due", ["status", "check_at"])
_index(db, "devii_lessons", "idx_devii_lessons_owner", ["owner_kind", "owner_id"])
_index(db, "devii_lessons", "idx_devii_lessons_owner_created", ["owner_kind", "owner_id", "created_at"])
_index(
@@ -1864,6 +1902,8 @@ def init_db():
for table in SOFT_DELETE_TABLES:
ensure_soft_delete_columns(table)
ensure_visibility_columns()
from .sync import ensure_export_indexes
ensure_export_indexes()
@@ -1961,8 +2001,8 @@ def init_db():
news_defaults = {
"news_grade_threshold": "7",
"news_api_url": "https://news.app.molodetz.nl/api",
"news_ai_url": AQUALITY_NEWS_GRADING_URL,
"news_ai_model": AQUALITY_NEWS_GRADING_MODEL,
"news_ai_url": INTERNAL_GATEWAY_URL,
"news_ai_model": NEWS_GRADING_MODEL_DEFAULT,
}
for key, value in news_defaults.items():
existing = db["site_settings"].find_one(key=key)
@@ -2662,12 +2702,18 @@ def migrate_ai_gateway_settings() -> None:
if get_setting(key, "") == OLD_GATEWAY_URL:
set_setting(key, INTERNAL_GATEWAY_URL)
logger.info(f"Migrated {key} to the internal gateway")
if get_setting("news_ai_url", "") == INTERNAL_GATEWAY_URL:
set_setting("news_ai_url", AQUALITY_NEWS_GRADING_URL)
logger.info("Migrated news_ai_url to the free aquality grading model")
if get_setting("news_ai_model", "") in ("molodetz", ""):
set_setting("news_ai_model", AQUALITY_NEWS_GRADING_MODEL)
logger.info("Migrated news_ai_model to aquality")
if get_setting("news_ai_url", "") == AQUALITY_NEWS_GRADING_URL:
set_setting("news_ai_url", INTERNAL_GATEWAY_URL)
logger.info(
"Migrated news_ai_url from the retired aquality endpoint "
"to the internal gateway"
)
if get_setting("news_ai_model", "") == AQUALITY_NEWS_GRADING_MODEL:
set_setting("news_ai_model", NEWS_GRADING_MODEL_DEFAULT)
logger.info(
"Migrated news_ai_model from the retired aquality scorer "
"to the free gateway model"
)
if get_setting("bot_model", "") == "deepseek-chat":
set_setting("bot_model", "molodetz")
logger.info("Migrated bot_model to molodetz")
+1
View File
@@ -17,6 +17,7 @@ SOFT_DELETE_TABLES = [
"reactions",
"bookmarks",
"notes",
"messages",
"skills",
"communities",
"node_devices",
+13 -11
View File
@@ -2,6 +2,7 @@
from .core import TTLCache, datetime, db, timedelta, timezone
from .ranking import get_top_authors
from .visibility import listed_clause
_stats_cache = TTLCache(ttl=30, max_size=50)
@@ -16,19 +17,20 @@ def get_site_stats() -> dict:
.replace(hour=0, minute=0, second=0, microsecond=0)
.isoformat()
)
def listed_count(name, **filters):
if name not in db.tables:
return 0
listed = listed_clause(db[name])
clauses = [listed] if listed is not None else []
return db[name].count(*clauses, **filters)
stats = {
"total_members": db["users"].count() if "users" in db.tables else 0,
"posts_today": db["posts"].count(
created_at={">=": today_start}, deleted_at=None
)
if "posts" in db.tables
else 0,
"total_projects": db["projects"].count(deleted_at=None)
if "projects" in db.tables
else 0,
"total_gists": db["gists"].count(deleted_at=None)
if "gists" in db.tables
else 0,
"posts_today": listed_count(
"posts", created_at={">=": today_start}, deleted_at=None
),
"total_projects": listed_count("projects", deleted_at=None),
"total_gists": listed_count("gists", deleted_at=None),
}
_stats_cache.set("site", stats)
return stats
+112
View File
@@ -0,0 +1,112 @@
# retoor <retoor@molodetz.nl>
from sqlalchemy import or_
from .core import db, get_table, _index
PUBLISHED = "published"
HIDDEN = "hidden"
DRAFT = "draft"
OFFLINE = "offline"
VISIBILITY_VALUES = (PUBLISHED, HIDDEN, DRAFT, OFFLINE)
VISIBILITY_CHOICES = (PUBLISHED, HIDDEN, OFFLINE)
DEFAULT_VISIBILITY = PUBLISHED
LISTED_VALUES = (PUBLISHED,)
OPEN_VALUES = (PUBLISHED, HIDDEN)
VISIBILITY_COLUMNS = {
"posts": "visibility",
"gists": "visibility",
"projects": "visibility",
"news": "status",
}
TARGET_TABLES = {
"post": "posts",
"gist": "gists",
"project": "projects",
"news": "news",
}
VISIBILITY_LABELS = {
PUBLISHED: "Published",
HIDDEN: "Hidden",
DRAFT: "Draft",
OFFLINE: "Offline",
}
VISIBILITY_HINTS = {
PUBLISHED: "Listed everywhere and open to everyone.",
HIDDEN: "Not listed or searchable; anyone with the link can still open it.",
DRAFT: "Only you can see it. Not published yet.",
OFFLINE: "Taken offline for now. Only you can see it; publish it again at any time.",
}
def normalize_visibility(value, fallback: str = DEFAULT_VISIBILITY) -> str:
text = str(value or "").strip().lower()
return text if text in VISIBILITY_VALUES else fallback
def visibility_column(table_name: str) -> str | None:
return VISIBILITY_COLUMNS.get(table_name)
def item_visibility(table_name: str, item: dict | None) -> str:
column = visibility_column(table_name)
if not column or not item:
return DEFAULT_VISIBILITY
return normalize_visibility(item.get(column))
def is_listed(table_name: str, item: dict | None) -> bool:
return item_visibility(table_name, item) in LISTED_VALUES
def is_open(table_name: str, item: dict | None) -> bool:
return item_visibility(table_name, item) in OPEN_VALUES
def listed_clause(table, own_uid: str | None = None):
name = getattr(table, "name", None) or getattr(table.table, "name", None)
column_name = visibility_column(name)
if not column_name or not table.exists:
return None
columns = table.table.columns
if column_name not in columns:
return None
column = columns[column_name]
clause = or_(column.is_(None), column.in_(LISTED_VALUES))
if own_uid and "user_uid" in columns:
clause = or_(clause, columns.user_uid == own_uid)
return clause
def listed_sql(table_name: str, alias: str = "") -> str:
column = visibility_column(table_name)
if not column or table_name not in db.tables:
return "1 = 1"
if not get_table(table_name).has_column(column):
return "1 = 1"
prefix = f"{alias}." if alias else ""
return f"COALESCE({prefix}{column}, '{DEFAULT_VISIBILITY}') = '{PUBLISHED}'"
def ensure_visibility_columns() -> None:
for table_name, column in VISIBILITY_COLUMNS.items():
if table_name == "news" or table_name not in db.tables:
continue
table = get_table(table_name)
if not table.has_column(column):
table.create_column_by_example(column, "")
_index(db, table_name, f"idx_{table_name}_visibility", [column])
def visibility_options(values=VISIBILITY_CHOICES) -> list[dict]:
return [
{"value": v, "label": VISIBILITY_LABELS[v], "hint": VISIBILITY_HINTS[v]}
for v in values
]
def visibility_label(value) -> str:
return VISIBILITY_LABELS[normalize_visibility(value)]
+68
View File
@@ -99,3 +99,71 @@ NON_BODY_ENDPOINTS = {
"notifications-open",
"admin-bots-frame",
}
VISIBILITY_VALUES = ["published", "hidden", "offline", "draft"]
VISIBILITY_DESCRIPTION = (
"published (default): listed and open to everyone. hidden: not listed, searched or indexed, "
"anyone with the link can open it. offline: only the owner and administrators can open it. "
"draft: only the owner, not yet published."
)
VISIBILITY_OMITTED = {
"create": " Optional and backwards compatible: when omitted the item is published.",
"edit": " Optional and backwards compatible: when omitted the current value is kept.",
"value": "",
}
def visibility_field(mode="create"):
return field(
"value" if mode == "value" else "visibility",
"form",
"enum",
mode == "value",
"published",
VISIBILITY_DESCRIPTION + VISIBILITY_OMITTED[mode],
VISIBILITY_VALUES,
)
def visibility_endpoint(id, kind, path, slug_name, example, auth="user"):
area = kind if kind == "news" else f"{kind}s"
owner_text = (
"Administrators only." if auth == "admin" else "Only the owner can change it."
)
return endpoint(
id=id,
method="POST",
path=path,
title=f"Set {kind} visibility",
summary=(
f"Set the visibility of a {kind} to published, hidden, offline or draft. "
f"{owner_text} Hidden items disappear from every listing, search and sitemap but "
"open by direct link; offline and draft items are visible only to the owner and "
"administrators (everyone else gets a 404)."
),
auth=auth,
encoding="form",
params=[
field(
slug_name,
"path",
"string",
True,
example,
f"Slug or UID of the {kind}.",
),
visibility_field("value"),
],
sample_response={
"ok": True,
"redirect": f"/{area}/example-slug",
"data": {
"uid": "0190c0de-0000-7000-8000-000000000000",
"visibility": "hidden",
"url": f"/{area}/example-slug",
},
},
)
+10 -1
View File
@@ -1,6 +1,6 @@
# retoor <retoor@molodetz.nl>
from .._shared import endpoint, field
from .._shared import endpoint, field, visibility_endpoint
GROUP = {
"slug": "admin",
@@ -482,6 +482,14 @@ four ways to sign requests.
field("uid", "path", "string", True, "NEWS_UID", "Article UID.")
],
),
visibility_endpoint(
"admin-news-visibility",
"news",
"/admin/news/{uid}/visibility",
"uid",
"NEWS_UID",
auth="admin",
),
endpoint(
id="admin-news-landing",
method="POST",
@@ -718,6 +726,7 @@ four ways to sign requests.
field("target_model", "json", "string", True, "x-ai/grok-4.3", "Model actually sent upstream."),
field("provider", "json", "string", False, "openrouter", "Provider name to route through. Blank = the default provider."),
field("fallback_model", "json", "string", False, "molodetz-pro", "Another already-configured source_model of the same kind, tried once automatically when this route fails after its own retries are exhausted. Blank = no fallback."),
field("tools_mode", "json", "string", False, "emulated", "'native' (default) forwards tools untouched. 'emulated' declares that this model does not support tool calling: tools are rewritten into the system prompt before sending and the reply is converted back into OpenAI tool_calls."),
],
),
endpoint(
+15 -2
View File
@@ -1,6 +1,13 @@
# retoor <retoor@molodetz.nl>
from .._shared import COMMENT_TARGETS, GIST_LANGUAGES, PROJECT_TYPES, endpoint, field
from .._shared import (
COMMENT_TARGETS,
GIST_LANGUAGES,
PROJECT_TYPES,
endpoint,
field,
visibility_field,
)
from devplacepy.constants import TOPICS
GROUP = {
@@ -143,6 +150,7 @@ four ways to sign requests.
encoding="form",
destructive=True,
params=[
visibility_field(),
field(
"content",
"form",
@@ -276,6 +284,7 @@ four ways to sign requests.
encoding="form",
destructive=True,
params=[
visibility_field("edit"),
field(
"post_slug",
"path",
@@ -548,6 +557,7 @@ four ways to sign requests.
encoding="form",
destructive=True,
params=[
visibility_field(),
field(
"title",
"form",
@@ -649,6 +659,7 @@ four ways to sign requests.
encoding="form",
destructive=True,
params=[
visibility_field("edit"),
field(
"project_slug",
"path",
@@ -771,7 +782,7 @@ four ways to sign requests.
id="projects-private",
method="POST",
path="/projects/{project_slug}/private",
title="Set project visibility",
title="Make a project private or public",
summary="Mark a project you own private or public. Send value=1 for private, value=0 for public. A project you hide as a member stays visible to administrators; a project you hide as an administrator is visible only to you, not to other administrators (this also hides its files and any attached containers).",
auth="user",
encoding="form",
@@ -1023,6 +1034,7 @@ four ways to sign requests.
encoding="form",
destructive=True,
params=[
visibility_field(),
field(
"title",
"form",
@@ -1068,6 +1080,7 @@ four ways to sign requests.
encoding="form",
destructive=True,
params=[
visibility_field("edit"),
field(
"gist_slug",
"path",
+25
View File
@@ -79,6 +79,31 @@ four ways to sign requests.
),
],
),
endpoint(
id="messages-delete",
method="POST",
path="/messages/{message_uid}/delete",
title="Delete a sent message",
summary="Soft-delete a direct message. Administrators only, and only messages they sent themselves; the bubble is removed live for both participants.",
auth="admin",
encoding="none",
destructive=True,
params=[
field(
"message_uid",
"path",
"string",
True,
"MESSAGE_UID",
"Uid of the message to delete.",
),
],
sample_response={
"ok": True,
"redirect": "/messages?with_uid=RECEIVER_UID",
"data": {"deleted_uid": "MESSAGE_UID"},
},
),
endpoint(
id="messages-conversations",
method="GET",
+1 -1
View File
@@ -106,7 +106,7 @@ page. Every endpoint follows the shared [Conventions & Errors](/docs/conventions
],
sample_response={"device": DEVICE_SAMPLE, "secret": "dpn_EXAMPLE_SECRET_SHOWN_ONCE"},
notes=[
"Refused with `403` and a `reason` (`kill_switch`, `no_consent`, `not_enabled`, `not_adult`, `deletion_pending`, `suspended`, `account_inactive`) unless donation is switched on, you are an adult, you have given the `bandwidth_sharing` consent and enabled donation for yourself.",
"Refused with `403` and a `reason` (`kill_switch`, `no_consent`, `not_enabled`, `deletion_pending`, `suspended`, `account_inactive`) unless donation is switched on, you have given the `bandwidth_sharing` consent and enabled donation for yourself.",
"Refused with `409` when you already have the maximum number of devices.",
"The response is `201` and is never cached.",
],
+77 -1
View File
@@ -11,7 +11,7 @@ GROUP = {
Attachment storage. Upload a file - or hand the server a public URL to fetch - to receive an
attachment record, then reference its `uid` in an `attachment_uids` field when creating a post,
comment, project, gist, message, or issue - see
[Posts, Comments, Projects, Gists & News](/docs/content.html). Images and videos embed and
[Posts, Comments, Projects, Gists & News](/docs/content.html). GIFs from GIPHY are attached the same way, through `/giphy/attach`. Images and videos embed and
play inline once posted; other types render as download links. The record's `is_image` and
`is_video` flags indicate how the file is displayed.
@@ -112,6 +112,82 @@ four ways to sign requests.
"mime_type": "image/png",
},
),
endpoint(
id="giphy-status",
method="GET",
path="/giphy/status",
title="GIF picker availability",
summary="Tell whether an administrator has configured GIPHY, so a client knows whether to offer a GIF picker.",
auth="user",
sample_response={"configured": True},
),
endpoint(
id="giphy-search",
method="GET",
path="/giphy/search",
title="Search GIFs",
summary="Search GIPHY by keyword through the server, so the API key never reaches a browser.",
auth="user",
params=[
field("q", "query", "string", True, "happy dance", "Search keywords, 1-200 characters."),
field("limit", "query", "integer", False, "24", "Number of results, 1-50 (default 24)."),
],
notes=[
"Results are capped to the content rating an administrator configured (default `pg`) and cached for five minutes.",
"Each member may make 30 GIF searches or trending requests per minute; beyond that the answer is `429` with `Retry-After`. `503` means GIPHY is not configured, `400` a missing `q`, `502` an upstream failure.",
],
sample_response={"query": "happy dance", "results": [{
"id": "xT9IgDEI1iZyb2wqo8",
"title": "happy dance GIF",
"url": "https://giphy.com/gifs/xT9IgDEI1iZyb2wqo8",
"preview": {"url": "https://media.giphy.com/media/xT9IgDEI1iZyb2wqo8/200w.gif", "width": 200, "height": 150, "size": 90210},
"original": {"url": "https://media.giphy.com/media/xT9IgDEI1iZyb2wqo8/giphy.gif", "width": 480, "height": 360, "size": 1048576},
}]},
),
endpoint(
id="giphy-trending",
method="GET",
path="/giphy/trending",
title="Trending GIFs",
summary="List the GIFs currently trending on GIPHY, in the same shape as Search GIFs.",
auth="user",
params=[
field("limit", "query", "integer", False, "24", "Number of results, 1-50 (default 24)."),
],
notes=["Shares the per-member rate limit, the cache and the error codes of Search GIFs."],
sample_response={"results": [{
"id": "xT9IgDEI1iZyb2wqo8",
"title": "happy dance GIF",
"url": "https://giphy.com/gifs/xT9IgDEI1iZyb2wqo8",
"preview": {"url": "https://media.giphy.com/media/xT9IgDEI1iZyb2wqo8/200w.gif", "width": 200, "height": 150, "size": 90210},
"original": {"url": "https://media.giphy.com/media/xT9IgDEI1iZyb2wqo8/giphy.gif", "width": 480, "height": 360, "size": 1048576},
}]},
),
endpoint(
id="giphy-attach",
method="POST",
path="/giphy/attach",
title="Attach a GIF",
summary="Download a GIPHY GIF on the server and store it as an attachment, exactly like an upload.",
auth="user",
encoding="json",
params=[
field("gif_id", "json", "string", True, "xT9IgDEI1iZyb2wqo8", "GIPHY id from Search GIFs or Trending GIFs."),
field("title", "json", "string", False, "happy dance", "Optional title used as the attachment's filename."),
],
notes=[
"Accepts a JSON body or a form. Returns `201` with the same record as Upload a file; reference its `uid` in `attachment_uids`. `413` if larger than the upload limit, `415` when GIF uploads are disabled, `404` for an unknown id.",
],
sample_response={
"uid": "ATTACHMENT_UID",
"original_filename": "happy dance.gif",
"url": "/static/uploads/attachments/ab/cd/ATTACHMENT_UID.gif",
"file_size": 1048576,
"mime_type": "image/gif",
"is_image": True,
"is_video": False,
},
),
endpoint(
id="uploads-list",
method="GET",
+1 -1
View File
@@ -72,7 +72,7 @@ def _user_facts(user: dict) -> dict:
"following": _count("follows", follower_uid=uid),
"bookmarks": _count("bookmarks", user_uid=uid),
"unread_notifications": _count("notifications", user_uid=uid, read=False),
"unread_messages": _count("messages", receiver_uid=uid, read=False),
"unread_messages": _count("messages", receiver_uid=uid, read=False, deleted_at=None),
},
"recent_posts": [
{
+163
View File
@@ -0,0 +1,163 @@
# retoor <retoor@molodetz.nl>
import json
import re
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import parse_qs, urlencode, urlparse
EMBED_JS_PATH = Path(__file__).parent / "static" / "js" / "embed-spec.js"
YOUTUBE_HOSTS = frozenset(
{
"youtube.com",
"www.youtube.com",
"m.youtube.com",
"youtube-nocookie.com",
"www.youtube-nocookie.com",
}
)
MUSIC_HOSTS = frozenset({"music.youtube.com"})
SHORT_HOSTS = frozenset({"youtu.be", "www.youtu.be"})
VIDEO_ID_PATTERN = "[A-Za-z0-9_-]{11}"
LIST_ID_PATTERN = "[A-Za-z0-9_-]{13,64}"
START_PATTERN = "[0-9]{1,6}s?"
MAX_START_SECONDS = 86400
MAX_MUSIC_EMBEDS = 3
EMBED_BASE = "https://www.youtube.com/embed"
PLAYLIST_SLUG = "videoseries"
EMBED_ALLOW = (
"accelerometer; autoplay; clipboard-write; encrypted-media; "
"gyroscope; picture-in-picture"
)
MUSIC_CAPTION = "Open in YouTube Music"
PATH_VIDEO_PREFIXES = ("embed", "v", "shorts")
_VIDEO_ID_RE = re.compile(VIDEO_ID_PATTERN)
_LIST_ID_RE = re.compile(LIST_ID_PATTERN)
_START_RE = re.compile(START_PATTERN)
@dataclass(frozen=True)
class Embed:
kind: str
video_id: str
list_id: str
start: int
music: bool
class EmbedParser:
@staticmethod
def parse(url: str) -> Embed | None:
try:
parts = urlparse(url)
except ValueError:
return None
if parts.scheme not in ("http", "https"):
return None
host = (parts.hostname or "").lower()
query = parse_qs(parts.query)
segments = [segment for segment in parts.path.split("/") if segment]
start = EmbedParser._start(query)
if host in SHORT_HOSTS:
if len(segments) != 1 or not _VIDEO_ID_RE.fullmatch(segments[0]):
return None
return Embed("video", segments[0], "", start, False)
music = host in MUSIC_HOSTS
if not music and host not in YOUTUBE_HOSTS:
return None
list_id = EmbedParser._list_id(query)
if segments == ["watch"]:
return EmbedParser._from_watch(query, list_id, start, music)
if segments == ["playlist"]:
return EmbedParser._playlist(list_id, music)
if music:
return None
if segments == ["embed"] and query.get("listType", [""])[0] == "playlist":
return EmbedParser._playlist(list_id, False)
if len(segments) == 2 and segments[0] in PATH_VIDEO_PREFIXES:
return EmbedParser._from_path(segments, list_id, start)
return None
@staticmethod
def src(embed: Embed) -> str:
if embed.kind == "playlist":
return f"{EMBED_BASE}/{PLAYLIST_SLUG}?{urlencode({'list': embed.list_id})}"
params: dict[str, str | int] = {}
if embed.list_id:
params["list"] = embed.list_id
if embed.start:
params["start"] = embed.start
suffix = f"?{urlencode(params)}" if params else ""
return f"{EMBED_BASE}/{embed.video_id}{suffix}"
@staticmethod
def spec() -> dict:
return {
"youtubeHosts": sorted(YOUTUBE_HOSTS),
"musicHosts": sorted(MUSIC_HOSTS),
"shortHosts": sorted(SHORT_HOSTS),
"videoIdPattern": VIDEO_ID_PATTERN,
"listIdPattern": LIST_ID_PATTERN,
"startPattern": START_PATTERN,
"maxStartSeconds": MAX_START_SECONDS,
"maxMusicEmbeds": MAX_MUSIC_EMBEDS,
"embedBase": EMBED_BASE,
"playlistSlug": PLAYLIST_SLUG,
"allow": EMBED_ALLOW,
"musicCaption": MUSIC_CAPTION,
"pathVideoPrefixes": list(PATH_VIDEO_PREFIXES),
}
@staticmethod
def write_module(path: Path = EMBED_JS_PATH) -> int:
spec = EmbedParser.spec()
body = json.dumps(spec, ensure_ascii=False, sort_keys=True, indent=4)
path.write_text(
f"// retoor <retoor@molodetz.nl>\n\nexport const EMBED_SPEC = {body};\n",
encoding="utf-8",
)
return len(spec)
@staticmethod
def _first(query: dict, key: str) -> str:
values = query.get(key)
return values[0] if values else ""
@staticmethod
def _list_id(query: dict) -> str:
value = EmbedParser._first(query, "list")
return value if _LIST_ID_RE.fullmatch(value) else ""
@staticmethod
def _start(query: dict) -> int:
raw = EmbedParser._first(query, "start") or EmbedParser._first(query, "t")
if not _START_RE.fullmatch(raw):
return 0
seconds = int(raw.rstrip("s"))
return seconds if seconds <= MAX_START_SECONDS else 0
@staticmethod
def _playlist(list_id: str, music: bool) -> Embed | None:
if not list_id:
return None
return Embed("playlist", "", list_id, 0, music)
@staticmethod
def _from_watch(query: dict, list_id: str, start: int, music: bool) -> Embed | None:
video_id = EmbedParser._first(query, "v")
if _VIDEO_ID_RE.fullmatch(video_id):
return Embed("video", video_id, list_id, start, music)
return EmbedParser._playlist(list_id, music)
@staticmethod
def _from_path(segments: list[str], list_id: str, start: int) -> Embed | None:
slug = segments[1]
if slug == PLAYLIST_SLUG:
return EmbedParser._playlist(list_id, False)
if not _VIDEO_ID_RE.fullmatch(slug):
return None
return Embed("video", slug, list_id, start, False)
+3 -1
View File
@@ -31,9 +31,11 @@ def _post_pool() -> list[str]:
if cached is not None:
return cached
slugs: list[str] = []
from devplacepy.database import listed_sql
if "posts" in db.tables:
rows = db.query(
"SELECT slug, uid FROM posts WHERE deleted_at IS NULL ORDER BY RANDOM() LIMIT :limit",
f"SELECT slug, uid FROM posts WHERE deleted_at IS NULL AND {listed_sql('posts')} ORDER BY RANDOM() LIMIT :limit",
limit=POOL_SIZE,
)
slugs = [row["slug"] or row["uid"] for row in rows]
+2
View File
@@ -24,6 +24,7 @@ from devplacepy.services.containers.service import ContainerService
from devplacepy.services.containers.workspace_service import WorkspaceService
from devplacepy.services.dbapi.service import DbApiJobService
from devplacepy.services.devii import DeviiService
from devplacepy.services.giphy.service import GiphyService
from devplacepy.services.gitea.service import IssueTrackerService
from devplacepy.services.jobs.award_service import AwardService
from devplacepy.services.jobs.deepsearch.service import DeepsearchService
@@ -73,6 +74,7 @@ SERVICE_CLASSES = [
IssueCreateService,
PlanningReportService,
IssueTrackerService,
GiphyService,
ContainerService,
WorkspaceService,
XmlrpcService,
+3
View File
@@ -38,6 +38,7 @@ from devplacepy.routers import (
gists,
quizzes,
uploads,
giphy,
media,
push,
leaderboard,
@@ -72,6 +73,7 @@ logging.basicConfig(
level=getattr(logging, LOG_LEVEL, logging.INFO),
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logging.getLogger("alembic.runtime.migration").setLevel(logging.WARNING)
app = FastAPI(
title="DevPlace",
@@ -125,6 +127,7 @@ app.include_router(issues.router, prefix="/issues")
app.include_router(gists.router, prefix="/gists")
app.include_router(news.router, prefix="/news")
app.include_router(uploads.router, prefix="/uploads")
app.include_router(giphy.router, prefix="/giphy")
app.include_router(media.router, prefix="/media")
app.include_router(zips.router, prefix="/zips")
app.include_router(forks.router, prefix="/forks")
+8
View File
@@ -6,6 +6,9 @@ from devplacepy.models.shared import (
normalize_poll_options,
_declared_age,
normalize_index_list,
VisibilityForm,
VisibilityCreateMixin,
VisibilityEditMixin,
)
from devplacepy.models.auth import (
SignupForm,
@@ -78,6 +81,7 @@ from devplacepy.models.uploads import (
UploadUrlForm,
GenerateImageForm,
AttachmentRenameForm,
GiphyAttachForm,
)
from devplacepy.models.tools import (
PlanningForm,
@@ -161,6 +165,9 @@ __all__ = [
"normalize_poll_options",
"_declared_age",
"normalize_index_list",
"VisibilityForm",
"VisibilityCreateMixin",
"VisibilityEditMixin",
"SignupForm",
"LoginForm",
"ForgotPasswordForm",
@@ -217,6 +224,7 @@ __all__ = [
"IssueAttachmentForm",
"IssueStatusForm",
"UploadUrlForm",
"GiphyAttachForm",
"GenerateImageForm",
"AttachmentRenameForm",
"PlanningForm",
+3 -2
View File
@@ -2,6 +2,7 @@
from typing import Literal, Optional
from pydantic import BaseModel, Field
from devplacepy.models.shared import VisibilityCreateMixin, VisibilityEditMixin
class SkillInstallForm(BaseModel):
@@ -23,7 +24,7 @@ class MessageForm(BaseModel):
client_id: Optional[str] = Field(default=None, max_length=64)
class GistForm(BaseModel):
class GistForm(VisibilityCreateMixin):
title: str = Field(min_length=1, max_length=200)
description: str = Field(default="", max_length=5000)
source_code: str = Field(min_length=1, max_length=400000)
@@ -31,7 +32,7 @@ class GistForm(BaseModel):
attachment_uids: list[str] = []
class GistEditForm(BaseModel):
class GistEditForm(VisibilityEditMixin):
title: str = Field(min_length=1, max_length=200)
description: str = Field(default="", max_length=5000)
source_code: str = Field(min_length=1, max_length=400000)
+7 -3
View File
@@ -4,10 +4,14 @@ from typing import Literal
from pydantic import BaseModel, Field, field_validator, model_validator
from devplacepy.constants import TOPICS
from devplacepy.rendering import is_single_emoji
from devplacepy.models.shared import normalize_poll_options
from devplacepy.models.shared import (
normalize_poll_options,
VisibilityCreateMixin,
VisibilityEditMixin,
)
class PostForm(BaseModel):
class PostForm(VisibilityCreateMixin):
content: str = Field(min_length=10, max_length=125000)
title: str = Field(default="", max_length=500)
topic: str = "random"
@@ -50,7 +54,7 @@ class WarJoinForm(BaseModel):
return value
class PostEditForm(BaseModel):
class PostEditForm(VisibilityEditMixin):
content: str = Field(min_length=10, max_length=125000)
title: str = Field(default="", max_length=500)
topic: str = "random"
+8 -3
View File
@@ -2,10 +2,15 @@
from typing import Literal
from pydantic import BaseModel, Field, field_validator
from devplacepy.models.shared import normalize_european_date, normalize_website_url
from devplacepy.models.shared import (
normalize_european_date,
normalize_website_url,
VisibilityCreateMixin,
VisibilityEditMixin,
)
class ProjectForm(BaseModel):
class ProjectForm(VisibilityCreateMixin):
title: str = Field(min_length=1, max_length=200)
description: str = Field(min_length=1, max_length=5000)
release_date: str = ""
@@ -33,7 +38,7 @@ class ProjectForm(BaseModel):
return normalize_website_url(value)
class ProjectEditForm(BaseModel):
class ProjectEditForm(VisibilityEditMixin):
title: str = Field(min_length=1, max_length=200)
description: str = Field(min_length=1, max_length=5000)
release_date: str = ""
+41
View File
@@ -1,7 +1,10 @@
# retoor <retoor@molodetz.nl>
from datetime import datetime
from typing import Optional
from urllib.parse import urlparse
from pydantic import BaseModel, field_validator
from devplacepy.database.visibility import VISIBILITY_VALUES, DEFAULT_VISIBILITY
def normalize_european_date(value):
@@ -73,3 +76,41 @@ def normalize_index_list(value):
except (TypeError, ValueError):
continue
return indexes
def parse_visibility(value, default):
text = str(value if value is not None else "").strip().lower()
if not text:
return default
if text not in VISIBILITY_VALUES:
raise ValueError(
"Visibility must be one of: " + ", ".join(VISIBILITY_VALUES)
)
return text
class VisibilityCreateMixin(BaseModel):
visibility: str = DEFAULT_VISIBILITY
@field_validator("visibility", mode="before")
@classmethod
def valid_visibility(cls, value):
return parse_visibility(value, DEFAULT_VISIBILITY)
class VisibilityEditMixin(BaseModel):
visibility: Optional[str] = None
@field_validator("visibility", mode="before")
@classmethod
def valid_visibility(cls, value):
return parse_visibility(value, None)
class VisibilityForm(BaseModel):
value: str
@field_validator("value", mode="before")
@classmethod
def valid_value(cls, value):
return parse_visibility(value, None) or DEFAULT_VISIBILITY
+5
View File
@@ -16,3 +16,8 @@ class GenerateImageForm(BaseModel):
class AttachmentRenameForm(BaseModel):
filename: str = Field(min_length=1, max_length=255)
class GiphyAttachForm(BaseModel):
gif_id: str = Field(min_length=1, max_length=64)
title: Optional[str] = Field(default=None, max_length=255)
+43 -22
View File
@@ -12,6 +12,8 @@ import emoji
import mistune
from markupsafe import Markup
from devplacepy.embeds import EMBED_ALLOW, MAX_MUSIC_EMBEDS, MUSIC_CAPTION, EmbedParser
EMOJI_JS_PATH = Path(__file__).parent / "static" / "js" / "emoji-shortcodes.js"
CUSTOM_SHORTCODES = {
@@ -55,11 +57,6 @@ _WIDGET_RE = re.compile(r"<dp-widget>(.*?)</dp-widget>", re.DOTALL | re.IGNORECA
_WIDGET_PH = "\x00WIDGET_{}\x00"
_SHORTCODE_RE = re.compile(r":([A-Za-z0-9_+\-]+):")
_YOUTUBE_RE = re.compile(
r"(?:https?://)?(?:www\.)?"
r"(?:youtube\.com/(?:watch\?v=|embed/|v/|shorts/)|youtu\.be/)"
r"([A-Za-z0-9_-]{11})"
)
_IMAGE_RE = re.compile(r"\.(jpg|jpeg|png|gif|webp|svg|bmp)(\?.*)?$", re.I)
_VIDEO_RE = re.compile(r"\.(mp4|webm|ogg|ogv|mov|m4v)(\?.*)?$", re.I)
_AUDIO_RE = re.compile(r"\.(mp3|wav|flac|ogg|aac|m4a|wma|opus)(\?.*)?$", re.I)
@@ -90,11 +87,6 @@ def _split_trailing_punct(url: str) -> tuple[str, str]:
break
return url, "".join(reversed(trailing))
_YOUTUBE_ALLOW = (
"accelerometer; autoplay; clipboard-write; encrypted-media; "
"gyroscope; picture-in-picture"
)
_EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b")
_EMAIL_KEEP_DOMAIN = "molodetz.nl"
@@ -192,16 +184,44 @@ def _alt_from_url(url: str) -> str:
return name if name else "Embedded image"
def _embed_url(url: str) -> str:
youtube = _YOUTUBE_RE.search(url)
class _EmbedBudget:
def __init__(self) -> None:
self.music = 0
def allows(self, music: bool) -> bool:
if not music:
return True
if self.music >= MAX_MUSIC_EMBEDS:
return False
self.music += 1
return True
def _youtube_embed(url: str, budget: _EmbedBudget) -> str | None:
embed = EmbedParser.parse(url)
if embed is None or not budget.allows(embed.music):
return None
lazy = " loading=\"lazy\"" if embed.music else ""
frame = (
f'<div class="embed-youtube"><iframe '
f'src="{html.escape(EmbedParser.src(embed), quote=True)}" '
f'frameborder="0" allowfullscreen{lazy} allow="{EMBED_ALLOW}">'
f"</iframe></div>"
)
if not embed.music:
return frame
return (
f'<div class="embed-music">{frame}'
f'<a class="embed-music-caption" href="{html.escape(url, quote=True)}" '
f'target="_blank" rel="noopener noreferrer">{html.escape(MUSIC_CAPTION)}</a>'
f"</div>"
)
def _embed_url(url: str, budget: _EmbedBudget) -> str:
youtube = _youtube_embed(url, budget)
if youtube:
video_id = youtube.group(1)
return (
f'<div class="embed-youtube"><iframe '
f'src="https://www.youtube.com/embed/{video_id}" '
f'frameborder="0" allowfullscreen allow="{_YOUTUBE_ALLOW}">'
f"</iframe></div>"
)
return youtube
escaped = html.escape(url, quote=True)
if _IMAGE_RE.search(url):
alt = html.escape(_alt_from_url(url), quote=True)
@@ -230,7 +250,7 @@ def _mask_emails(text: str) -> str:
return _EMAIL_RE.sub(_mask_email, text)
def _transform_text(text: str) -> str:
def _transform_text(text: str, budget: _EmbedBudget) -> str:
out: list[str] = []
pos = 0
for match in _TOKEN_RE.finditer(text):
@@ -238,7 +258,7 @@ def _transform_text(text: str) -> str:
out.append(html.escape(_mask_emails(text[pos:match.start()])))
if match.group("url"):
url, trailing = _split_trailing_punct(match.group("url"))
out.append(_embed_url(url))
out.append(_embed_url(url, budget))
if trailing:
out.append(html.escape(trailing))
else:
@@ -269,6 +289,7 @@ class _MediaProcessor(HTMLParser):
super().__init__(convert_charrefs=True)
self._out: list[str] = []
self._skip_depth = 0
self._budget = _EmbedBudget()
def handle_starttag(self, tag: str, attrs: list) -> None:
self._out.append(_emit_tag(tag, attrs))
@@ -287,7 +308,7 @@ class _MediaProcessor(HTMLParser):
if self._skip_depth > 0:
self._out.append(html.escape(_mask_emails(data)))
else:
self._out.append(_transform_text(data))
self._out.append(_transform_text(data, self._budget))
def result(self) -> str:
return "".join(self._out)
+5
View File
@@ -34,6 +34,7 @@ Prefixes are wired in `main.py`:
| `/issues` | issues/ package - issue tracker backed by Gitea (no local issue store): `index.py` (list `?state=`/`?page=`, detail `/{number}` with comments), `create.py` (async AI-enhanced filing `/create` enqueues a `issue_create` job, status at `/jobs/{uid}`), `comment.py` (synchronous, pushes to Gitea + notifies admins), `status.py` (admin open/closed), `attachments.py` (file attachments on open issues + comments, mirrored to Gitea native assets; add/list/delete with owner-or-admin + open-state guards) |
| `/gists` | gists.py |
| `/news` | news.py |
| `/giphy` | giphy.py - GIF picker backend: `GET /giphy/status`, `GET /giphy/search`, `GET /giphy/trending` (cached, 30 calls/min/user, pure JSON) and `POST /giphy/attach` (stores the GIF as an attachment, audit `attachment.giphy`); see `services/giphy/CLAUDE.md` |
| `/uploads` | uploads.py - attachment management CRUD for the signed-in user over the ONE `attachments` table (the same rows that appear on posts/comments/projects/gists/issues). Create: `POST /upload` (multipart), `POST /upload-url` (server-side fetch). Read: `GET ""` (own attachments, paginated 24/page newest-first, `?page=`, `?linked=true|false` via `database.get_user_attachments`), `GET /{attachment_uid}` (one, via `database.get_user_attachment`). Update: `PATCH /{attachment_uid}` (rename display filename via `attachments.rename_attachment`; the original file extension is ALWAYS preserved - renaming can never change the file type, the upload-time security control - audit `attachment.rename`). Delete: `DELETE /delete/{attachment_uid}` (soft delete). All `require_user_api` (401 for guests); read/rename/delete of another user's row is owner-or-admin. JSON-only router (no HTML/`respond`); list uses `UploadsListOut`, single/rename return `UploadItemOut`. Devii tools mirror every face: `upload_file`/`attach_url`/`list_attachments`/`get_attachment`/`rename_attachment`/`delete_attachment` |
| `/media` | media.py - profile media gallery item soft delete/restore: `POST /media/{uid}/delete` and `POST /media/{uid}/restore` (owner or admin) |
| `/openai` | openai_gateway.py |
@@ -377,3 +378,7 @@ The profile **Activity** tab (`/profile/{username}?tab=activity`, public) interl
- **Comment items** get `"url": f"{resolve_object_url(target_type, target_uid)}#comment-{c['uid']}"`, the SEO-friendly parent detail URL plus the `#comment-{uid}` anchor. This is **byte-identical to a comment notification's `target_url`** (`content.create_comment_record`), so clicking an activity comment reproduces the notification click exactly: it lands on the parent post and `NotificationManager.js` scrolls to / highlights the `id="comment-{uid}"` element (`_comment.html`). Reuse `resolve_object_url` (`database.py`) - never rebuild this URL by hand, and do not call `resolve_object_url("comment", uid)` here (it re-fetches the row the loop already has).
- **Frontend:** the card is wrapped in the shared full-card overlay link (`card-link-host` + `_card_link.html`), the same pattern `_post_card.html` uses; inner content links (mentions, URLs rendered by `render_content`) stay clickable via the existing `card-link-host a:not(.card-link)` z-index rule (`base.css`). No new CSS.
- **API:** `ProfileOut.activities` is `list[Any]`, so the added `url` (and, on comments, the existing `target_type` + `uid` = parent target uid) flow into the JSON response with no schema change - this is the parent-post reference exposed on each comment item.
## 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`.
+69 -2
View File
@@ -2,6 +2,7 @@
import logging
from typing import Optional
from urllib.parse import quote
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
@@ -17,7 +18,12 @@ from devplacepy.schemas import (
from devplacepy.seo import base_seo_context, site_url, website_schema
from devplacepy.services.audit import record as audit
from devplacepy.services.manager import service_manager
from devplacepy.services.openai_gateway import model_stats_query, quota, routing
from devplacepy.services.openai_gateway import (
health,
model_stats_query,
quota,
routing,
)
from devplacepy.templating import templates
from devplacepy.utils import not_found, require_admin
@@ -149,10 +155,14 @@ def _error_response(
@router.get("/gateway", response_class=HTMLResponse)
async def gateway_config_page(request: Request, tab: str = "models"):
async def gateway_config_page(
request: Request, tab: str = "models", tested: str = "", test_image: str = ""
):
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()
for rule in quota_rules:
rule["spent_24h_usd"] = round(
@@ -172,6 +182,8 @@ async def gateway_config_page(request: Request, tab: str = "models"):
"default_provider": _default_provider_summary(),
"quota_defaults": _quota_defaults_summary(),
"stats_ranges": list(model_stats_query.RANGE_SECONDS.keys()),
"tested": tested,
"test_image": test_image,
},
model=AdminGatewayOut,
)
@@ -472,6 +484,7 @@ MODEL_FORM_DEFAULTS = {
"off_peak_end": "",
"off_peak_discount_pct": "0",
"fallback_model": "",
"tools_mode": "native",
"is_active": "1",
}
@@ -505,6 +518,7 @@ def _model_form_values_from_route(route: dict) -> dict:
"off_peak_end": _minutes_to_time(route.get("off_peak_end_minute")),
"off_peak_discount_pct": _num("off_peak_discount_pct"),
"fallback_model": route.get("fallback_model", ""),
"tools_mode": route.get("tools_mode", "native"),
"is_active": _bool_str(route.get("is_active", True)),
}
@@ -548,6 +562,7 @@ def _model_payload_kwargs(data: dict) -> dict:
"off_peak_end_minute": _time_to_minutes(data.get("off_peak_end", "")),
"off_peak_discount_pct": _num("off_peak_discount_pct"),
"fallback_model": data.get("fallback_model", ""),
"tools_mode": data.get("tools_mode", "native"),
"is_active": data.get("is_active", "1"),
}
@@ -675,6 +690,58 @@ async def delete_model_page(request: Request, source_model: str):
return RedirectResponse(url=f"{INDEX_URL}?tab=models", status_code=302)
@router.post("/gateway/models/test-all")
async def test_all_models_page(request: Request):
admin = require_admin(request)
tested, failed = await health.test_all()
audit.record(
request,
"gateway.models.test_all",
user=admin,
target_type="gateway_models",
target_uid="all",
target_label=f"{tested} routes",
summary=(
f"admin {admin['username']} tested all gateway model routes: "
f"{tested - failed} ok, {failed} failed"
),
)
return RedirectResponse(
url=f"{INDEX_URL}?tab=models&tested=all", status_code=302
)
@router.post("/gateway/models/{source_model:path}/test")
async def test_model_page(request: Request, source_model: str):
admin = require_admin(request)
route = routing.model_store.get(source_model)
if route is None:
raise not_found("Model route not found")
result = await health.probe_route(source_model)
health.record_health(source_model, result)
audit.record(
request,
"gateway.model.test",
user=admin,
target_type="gateway_model",
target_uid=source_model,
target_label=source_model,
summary=(
f"admin {admin['username']} tested gateway model route "
f"{source_model}: {'ok' if result.ok else result.code}"
),
)
url = f"{INDEX_URL}?tab=models&tested={quote(source_model, safe='')}"
if (
result.ok
and route.kind == "image"
and result.image_url.startswith("http")
and len(result.image_url) <= 2000
):
url += f"&test_image={quote(result.image_url, safe='')}"
return RedirectResponse(url=url, status_code=302)
# --- Quota rules: JSON API (Devii + programmatic clients) -------------------
+23 -1
View File
@@ -1,7 +1,8 @@
# retoor <retoor@molodetz.nl>
import logging
from fastapi import APIRouter, Request
from typing import Annotated
from fastapi import Depends, APIRouter, Request
from fastapi.responses import HTMLResponse
from devplacepy.database import (
get_table,
@@ -15,6 +16,9 @@ from devplacepy.seo import base_seo_context, site_url, website_schema
from devplacepy.responses import respond, action_result
from devplacepy.schemas import AdminNewsOut
from devplacepy.services.audit import record as audit
from devplacepy.models import VisibilityForm
from devplacepy.content import set_visibility_item
from devplacepy.dependencies import json_or_form
logger = logging.getLogger(__name__)
router = APIRouter()
@@ -182,3 +186,21 @@ async def admin_news_delete(request: Request, uid: str):
links=[audit.target("news", uid, article.get("title"))],
)
return action_result(request, "/admin/news")
@router.post("/news/{uid}/visibility")
async def admin_news_visibility(
request: Request,
uid: str,
data: Annotated[VisibilityForm, Depends(json_or_form(VisibilityForm))],
):
admin = require_admin(request)
return set_visibility_item(
request,
"news",
"news",
admin,
uid,
data.value,
"/admin/news",
)
+5 -1
View File
@@ -6,6 +6,7 @@ from fastapi.responses import RedirectResponse, JSONResponse, HTMLResponse
from devplacepy.database import get_table, db, paginate, resolve_object_url, _now_iso
from devplacepy.utils import generate_uid, require_user, time_ago, redirect_back
from devplacepy.seo import base_seo_context
from devplacepy.content import can_view_item, can_view_target
from devplacepy.responses import respond
from devplacepy.schemas import SavedOut
from devplacepy.services.audit import record as audit
@@ -50,7 +51,8 @@ async def saved_page(request: Request, before: str = None):
if table.has_column("deleted_at"):
clauses.append(table.table.columns.deleted_at.is_(None))
for obj in table.find(*clauses):
resolved[(target_type, obj["uid"])] = obj
if can_view_item(table_name, obj, user):
resolved[(target_type, obj["uid"])] = obj
items = []
for row in rows:
@@ -95,6 +97,8 @@ async def toggle_bookmark(request: Request, target_type: str, target_uid: str):
user = require_user(request)
if target_type not in BOOKMARKABLE:
return JSONResponse({"error": "Invalid target"}, status_code=400)
if not can_view_target(target_type, target_uid, user):
return JSONResponse({"error": "Not found"}, status_code=404)
bookmarks = get_table("bookmarks")
existing = bookmarks.find_one(
+4 -1
View File
@@ -8,11 +8,12 @@ from fastapi.responses import JSONResponse
from devplacepy.database import get_table, resolve_object_url
from devplacepy.content import (
is_owner,
can_view_target,
create_comment_record,
delete_comment_record,
edit_comment_record,
)
from devplacepy.utils import require_user, is_admin
from devplacepy.utils import require_user, is_admin, not_found
from devplacepy.models import CommentForm, CommentEditForm
from devplacepy.responses import action_result, wants_json, json_error
from devplacepy.schemas import CommentEditOut
@@ -26,6 +27,8 @@ router = APIRouter()
async def create_comment(request: Request, data: Annotated[CommentForm, Depends(json_or_form(CommentForm))]):
user = require_user(request)
target_uid = data.target_uid or data.post_uid
if not can_view_target(data.target_type, target_uid, user):
raise not_found("Not found")
comment_uid, comment_url = create_comment_record(
request,
user,
+6 -6
View File
@@ -114,7 +114,7 @@ async def create_rant(request: Request):
async def get_rant(request: Request, rant_id: str):
params = await merge_params(request)
viewer = resolve_actor(request, params)
post = post_by_id(rant_id)
post = post_by_id(rant_id, viewer)
if not post:
return dr_error("This rant does not exist.")
detail = load_rant_detail(post, viewer)
@@ -127,7 +127,7 @@ async def edit_rant(request: Request, rant_id: str):
user = resolve_actor(request, params)
if not user:
return unauthorized()
post = post_by_id(rant_id)
post = post_by_id(rant_id, user)
if not post:
return dr_error("This rant does not exist.", fail_reason="not_found")
if not is_owner(post, user):
@@ -166,7 +166,7 @@ async def delete_rant(request: Request, rant_id: str):
user = resolve_actor(request, params)
if not user:
return unauthorized()
post = post_by_id(rant_id)
post = post_by_id(rant_id, user)
if not post:
return dr_error("This rant does not exist.")
if not (is_owner(post, user) or is_admin(user)):
@@ -181,7 +181,7 @@ async def vote_rant(request: Request, rant_id: str):
user = resolve_actor(request, params)
if not user:
return unauthorized()
post = post_by_id(rant_id)
post = post_by_id(rant_id, user)
if not post:
return dr_error("This rant does not exist.")
value = as_int(params.get("vote"))
@@ -208,7 +208,7 @@ async def _set_favorite(request: Request, rant_id: str, saved: bool):
user = resolve_actor(request, params)
if not user:
return unauthorized()
post = post_by_id(rant_id)
post = post_by_id(rant_id, user)
if not post:
return dr_error("This rant does not exist.")
set_bookmark(request, user, "post", post["uid"], saved)
@@ -221,7 +221,7 @@ async def comment_rant(request: Request, rant_id: str):
user = resolve_actor(request, params)
if not user:
return unauthorized()
post = post_by_id(rant_id)
post = post_by_id(rant_id, user)
if not post:
return dr_error("This rant does not exist.")
text = (params.get("comment") or "").strip()
+12
View File
@@ -69,6 +69,12 @@ DOCS_PAGES = [
"kind": "prose",
"section": SECTION_GENERAL,
},
{
"slug": "content-visibility",
"title": "Content visibility",
"kind": "prose",
"section": SECTION_GENERAL,
},
{
"slug": "code-farm",
"title": "Code Farm",
@@ -292,6 +298,12 @@ DOCS_PAGES = [
"kind": "prose",
"section": SECTION_COMPONENTS,
},
{
"slug": "component-dp-gif-picker",
"title": "dp-gif-picker",
"kind": "prose",
"section": SECTION_COMPONENTS,
},
{
"slug": "component-dp-upload",
"title": "dp-upload",
+126
View File
@@ -0,0 +1,126 @@
# retoor <retoor@molodetz.nl>
import logging
from typing import Annotated
from urllib.parse import urlparse
from fastapi import APIRouter, Depends, Query, Request
from fastapi.responses import JSONResponse
from devplacepy.attachments import (
RemoteFetchError,
is_extension_allowed,
store_attachment_from_url,
)
from devplacepy.dependencies import json_or_form
from devplacepy.models import GiphyAttachForm
from devplacepy.responses import json_error
from devplacepy.services.audit import record as audit
from devplacepy.services.giphy import runtime
from devplacepy.services.giphy.client import MAX_LIMIT, GiphyError
from devplacepy.services.giphy.config import giphy_config
from devplacepy.services.giphy.limits import UserRateLimiter
from devplacepy.utils import require_user_api, track_action
logger = logging.getLogger(__name__)
router = APIRouter()
limiter = UserRateLimiter()
@router.get("/status")
async def giphy_status(request: Request):
require_user_api(request)
return JSONResponse({"configured": giphy_config().is_configured})
def _limit_value(limit: int) -> int:
return max(1, min(int(limit), MAX_LIMIT))
def _error(exc: GiphyError) -> JSONResponse:
status = exc.status if 400 <= exc.status < 600 else 502
return json_error(status, exc.message)
def _throttled(user: dict) -> JSONResponse | None:
if limiter.allow(user["uid"]):
return None
response = json_error(429, "Too many GIF searches, slow down")
response.headers["Retry-After"] = str(int(limiter.window_seconds))
return response
@router.get("/search")
async def search_gifs(
request: Request, q: str = Query(default="", max_length=200), limit: int = 24
):
user = require_user_api(request)
query = q.strip()
if not query:
return json_error(400, "q is required")
if (refused := _throttled(user)) is not None:
return refused
try:
gifs = await runtime.get_client().search(query, limit=_limit_value(limit))
except GiphyError as exc:
return _error(exc)
return JSONResponse({"query": query, "results": gifs})
@router.get("/trending")
async def trending_gifs(request: Request, limit: int = 24):
user = require_user_api(request)
if (refused := _throttled(user)) is not None:
return refused
try:
gifs = await runtime.get_client().trending(limit=_limit_value(limit))
except GiphyError as exc:
return _error(exc)
return JSONResponse({"results": gifs})
@router.post("/attach")
async def attach_gif(
request: Request,
data: Annotated[GiphyAttachForm, Depends(json_or_form(GiphyAttachForm))],
):
user = require_user_api(request)
client = runtime.get_client()
try:
gif = await client.get_gif(data.gif_id)
except GiphyError as exc:
return _error(exc)
url = (gif.get("original") or {}).get("url") or (gif.get("preview") or {}).get("url")
if not url:
return json_error(502, "GIPHY returned no downloadable file")
stem = (data.title or gif.get("title") or gif.get("id") or "giphy").strip()
filename = f"{stem[:200]}.gif"
if not is_extension_allowed(".gif"):
return json_error(415, "GIF uploads are disabled")
try:
result = await store_attachment_from_url(url, user["uid"], filename)
except RemoteFetchError as exc:
logger.warning("Giphy attach failed for %s: %s", gif.get("id"), exc.message)
return json_error(exc.status, exc.message)
audit.record(
request,
"attachment.giphy",
user=user,
target_type="attachment",
target_uid=result.get("uid"),
target_label=filename,
metadata={
"gif_id": gif.get("id"),
"source_host": urlparse(url).hostname,
"size": result.get("file_size"),
"mime": result.get("mime_type"),
},
summary=f"{user['username']} attached a GIF from Giphy",
links=[audit.attachment_link(result.get("uid"), filename)],
)
track_action(user["uid"], "upload")
return JSONResponse(result, status_code=201)
+11 -1
View File
@@ -11,6 +11,8 @@ from devplacepy.database import (
get_gist_languages,
get_recent_comments_by_target_uids,
paginate,
listed_clause,
is_listed,
text_search_clause,
resolve_object_url,
mark_notifications_read_by_target,
@@ -84,13 +86,17 @@ def get_gists_list(user_uid=None, language=None, search="", before=None, viewer=
gists_table, search, ("title", "description"), author_field="user_uid"
)
clauses = [search_match] if search_match is not None else []
own_uid = viewer["uid"] if viewer and viewer["uid"] == user_uid else None
listed = listed_clause(gists_table, own_uid=own_uid)
count_clauses = clauses + ([listed] if listed is not None else [])
total = gists_table.count(*clauses, deleted_at=None, **filters)
total = gists_table.count(*count_clauses, deleted_at=None, **filters)
gists, next_cursor = paginate(
gists_table,
*clauses,
before=before,
viewer_uid=viewer["uid"] if viewer else None,
include_unlisted_of=own_uid,
**filters,
)
@@ -167,6 +173,7 @@ async def gist_detail(request: Request, gist_slug: str):
title=gist.get("title", "Gist"),
description=gist.get("description") or "",
seo_target=("gist", gist["uid"]),
robots="index,follow" if is_listed("gists", gist) else "noindex,nofollow",
og_type="article",
og_image=first_image_url(gist, detail["attachments"]),
breadcrumbs=[
@@ -216,6 +223,7 @@ async def create_gist(request: Request, data: Annotated[GistForm, Depends(json_o
"description": description or None,
"source_code": source_code,
"language": language,
"visibility": data.visibility,
},
title,
XP_GIST,
@@ -245,6 +253,7 @@ async def edit_gist(
"description": data.description.strip() or None,
"source_code": data.source_code.strip(),
"language": language,
"visibility": data.visibility,
},
"/gists",
target_type="gist",
@@ -254,3 +263,4 @@ async def edit_gist(
async def delete_gist(request: Request, gist_slug: str):
user = require_user(request)
return delete_content_item(request, "gists", "gist", user, gist_slug, "/gists")
+42 -8
View File
@@ -6,7 +6,7 @@ from datetime import datetime
from typing import Annotated, Optional
from fastapi import Depends, APIRouter, Request, WebSocket, WebSocketDisconnect
from devplacepy.models import MessageForm
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from devplacepy.database import (
get_table,
db,
@@ -19,12 +19,14 @@ from devplacepy.attachments import get_attachments_batch
from devplacepy.templating import clear_messages_cache
from devplacepy.utils import (
require_user,
is_admin,
not_found,
time_ago,
_user_from_session,
_user_from_api_key,
)
from devplacepy.seo import base_seo_context
from devplacepy.responses import respond, action_result
from devplacepy.responses import respond, action_result, json_error, wants_json
from devplacepy.schemas import ConversationOut, MessagesOut
from devplacepy.services import presence
from devplacepy.services.audit import record as audit
@@ -36,6 +38,8 @@ from devplacepy.services.messaging import (
message_frame,
message_hub,
message_relay,
broadcast_deleted,
delete_message_record,
persist_message,
redeem_ticket,
stamp_content_revision,
@@ -66,7 +70,7 @@ def mark_conversation_read(user_uid: str, other_uid: str) -> None:
return
with db:
db.query(
"UPDATE messages SET read = 1 WHERE receiver_uid = :me AND sender_uid = :other AND read = 0",
"UPDATE messages SET read = 1 WHERE receiver_uid = :me AND sender_uid = :other AND read = 0 AND deleted_at IS NULL",
me=user_uid,
other=other_uid,
)
@@ -85,7 +89,7 @@ def get_conversations(user_uid: str):
" ORDER BY created_at DESC, id DESC"
" ) AS rn"
" FROM messages"
" WHERE sender_uid = :me OR receiver_uid = :me"
" WHERE (sender_uid = :me OR receiver_uid = :me) AND deleted_at IS NULL"
") WHERE rn = 1 ORDER BY created_at DESC",
me=user_uid,
)
@@ -127,7 +131,7 @@ def get_conversation_messages(user_uid: str, other_uid: str, before: str = ""):
"SELECT * FROM messages"
" WHERE ((sender_uid = :me AND receiver_uid = :other)"
" OR (sender_uid = :other AND receiver_uid = :me))"
" AND created_at < :before"
" AND created_at < :before AND deleted_at IS NULL"
" ORDER BY created_at DESC, id DESC LIMIT :lim",
me=user_uid,
other=other_uid,
@@ -139,8 +143,9 @@ def get_conversation_messages(user_uid: str, other_uid: str, before: str = ""):
msgs = list(
db.query(
"SELECT * FROM messages"
" WHERE (sender_uid = :me AND receiver_uid = :other)"
" OR (sender_uid = :other AND receiver_uid = :me)"
" WHERE ((sender_uid = :me AND receiver_uid = :other)"
" OR (sender_uid = :other AND receiver_uid = :me))"
" AND deleted_at IS NULL"
" ORDER BY created_at DESC, id DESC LIMIT :lim",
me=user_uid,
other=other_uid,
@@ -293,6 +298,33 @@ async def send_message(request: Request, data: Annotated[MessageForm, Depends(js
request, f"/messages?with_uid={receiver_uid}", data=frame
)
@router.post("/{message_uid}/delete")
async def delete_message(request: Request, message_uid: str):
user = require_user(request)
message = get_table("messages").find_one(uid=message_uid, deleted_at=None)
if not is_admin(user) or (message and message["sender_uid"] != user["uid"]):
audit.record(
request,
"message.delete",
user=user,
result="denied",
target_type="message",
target_uid=message_uid,
summary=f"{user['username']} denied deleting message {message_uid}",
)
if wants_json(request):
return json_error(403, "Not allowed")
return RedirectResponse(url="/messages", status_code=302)
if not message:
raise not_found("Message not found")
delete_message_record(request, user, message)
await broadcast_deleted(message)
return action_result(
request,
f"/messages?with_uid={message['receiver_uid']}",
data={"deleted_uid": message_uid},
)
async def broadcast_message(
sender: dict, message: dict, client_id: Optional[str] = None,
ai_processed: bool = False, ai_pending: bool = False,
@@ -312,7 +344,7 @@ async def _await_ai_and_push(
) -> bool:
await asyncio.gather(*pending, return_exceptions=True)
pending.clear()
row = get_table("messages").find_one(uid=message["uid"])
row = get_table("messages").find_one(uid=message["uid"], deleted_at=None)
if not row:
return False
changed = row.get("content") != message.get("content")
@@ -358,6 +390,7 @@ async def _sync_missed(user_uid: str, data: dict, websocket: WebSocket) -> None:
" OR (sender_uid = :other AND receiver_uid = :me))"
" AND (created_at > :since"
" OR (updated_at IS NOT NULL AND updated_at > :since))"
" AND deleted_at IS NULL"
" ORDER BY created_at ASC, id ASC LIMIT :lim",
me=user_uid,
other=with_uid,
@@ -372,6 +405,7 @@ async def _sync_missed(user_uid: str, data: dict, websocket: WebSocket) -> None:
" WHERE (sender_uid = :me OR receiver_uid = :me)"
" AND (created_at > :since"
" OR (updated_at IS NOT NULL AND updated_at > :since))"
" AND deleted_at IS NULL"
" ORDER BY created_at ASC, id ASC LIMIT :lim",
me=user_uid,
since=since,
+5 -1
View File
@@ -15,11 +15,12 @@ from devplacepy.database import (
get_user_bookmarks,
get_user_notes,
paginate,
is_listed,
resolve_object_url,
mark_notifications_read_by_target,
)
from devplacepy.utils import get_current_user, time_ago, not_found
from devplacepy.content import canonical_redirect
from devplacepy.content import canonical_redirect, can_view_item
from devplacepy.seo import (
base_seo_context,
website_schema,
@@ -105,6 +106,8 @@ async def news_detail_page(request: Request, news_slug: str):
article = resolve_by_slug(news_table, news_slug)
if not article:
raise not_found("News article not found")
if not can_view_item("news", article, user):
raise not_found("News article not found")
redirect = canonical_redirect("news", article, news_slug)
if redirect:
return redirect
@@ -139,6 +142,7 @@ async def news_detail_page(request: Request, news_slug: str):
title=article.get("title", "News Article"),
description=article.get("description", "") or "",
seo_target=("news", article["uid"]),
robots="index,follow" if is_listed("news", article) else "noindex,nofollow",
og_type="article",
og_image=image_url or None,
breadcrumbs=[
+5 -1
View File
@@ -8,6 +8,7 @@ from devplacepy.database import get_table, db, paginate, resolve_object_url, _no
from devplacepy.models import NoteForm
from devplacepy.utils import generate_uid, require_user, time_ago, redirect_back
from devplacepy.seo import base_seo_context
from devplacepy.content import can_view_item, can_view_target
from devplacepy.responses import respond
from devplacepy.schemas import NotesOut
from devplacepy.services.audit import record as audit
@@ -52,7 +53,8 @@ async def notes_page(request: Request, before: str = None):
if table.has_column("deleted_at"):
clauses.append(table.table.columns.deleted_at.is_(None))
for obj in table.find(*clauses):
resolved[(target_type, obj["uid"])] = obj
if can_view_item(table_name, obj, user):
resolved[(target_type, obj["uid"])] = obj
items = []
for row in rows:
@@ -104,6 +106,8 @@ async def set_note(
user = require_user(request)
if target_type not in NOTABLE:
return JSONResponse({"error": "Invalid target"}, status_code=400)
if not can_view_target(target_type, target_uid, user):
return JSONResponse({"error": "Not found"}, status_code=404)
notes = get_table("notes")
existing = notes.find_one(
+9 -3
View File
@@ -14,6 +14,8 @@ from devplacepy.database import (
mark_notifications_read_by_target,
get_featured_topics,
get_blocked_uids,
listed_sql,
is_listed,
)
from devplacepy.utils import (
get_current_user,
@@ -83,6 +85,7 @@ async def create_post(request: Request, data: Annotated[PostForm, Depends(json_o
"topic": topic,
"project_uid": project_uid or None,
"image": image_filename,
"visibility": data.visibility,
},
slug_text,
XP_POST,
@@ -147,7 +150,7 @@ def _next_post_url(post: dict, viewer: dict | None) -> str | None:
blocked = get_blocked_uids(viewer["uid"]) if viewer else frozenset()
rows = db.query(
"SELECT slug, uid, user_uid FROM posts WHERE created_at < :created_at "
"AND deleted_at IS NULL ORDER BY created_at DESC LIMIT :limit",
f"AND deleted_at IS NULL AND {listed_sql('posts')} ORDER BY created_at DESC LIMIT :limit",
created_at=post["created_at"],
limit=10,
)
@@ -177,7 +180,8 @@ def post_page_context(
request,
title=post.get("title") or "Post",
description=post.get("content", ""),
robots=robots or "index,follow",
robots=robots
or ("index,follow" if is_listed("posts", post) else "noindex,nofollow"),
seo_target=("post", post["uid"]),
breadcrumbs=[
{"name": "Home", "url": "/feed"},
@@ -207,7 +211,7 @@ def post_page_context(
if "posts" in db.tables:
rows = list(
db.query(
"SELECT p.*, u.username FROM posts p JOIN users u ON p.user_uid = u.uid WHERE p.topic = :t AND p.uid != :uid AND p.deleted_at IS NULL ORDER BY p.created_at DESC LIMIT 5",
f"SELECT p.*, u.username FROM posts p JOIN users u ON p.user_uid = u.uid WHERE p.topic = :t AND p.uid != :uid AND p.deleted_at IS NULL AND {listed_sql('posts', 'p')} ORDER BY p.created_at DESC LIMIT 5",
t=post.get("topic", ""),
uid=post["uid"],
)
@@ -275,6 +279,7 @@ async def edit_post(
"content": data.content.strip(),
"title": data.title.strip() or None,
"topic": data.topic,
"visibility": data.visibility,
},
"/feed",
target_type="post",
@@ -297,3 +302,4 @@ async def delete_post(request: Request, post_slug: str):
return delete_content_item(
request, "posts", "post", user, post_slug, "/feed", inline_image_field="image"
)
+19 -1
View File
@@ -7,6 +7,8 @@ from devplacepy.models import ProfileForm
from fastapi.responses import HTMLResponse, JSONResponse
from devplacepy.database import (
get_setting,
listed_clause,
is_listed,
get_table,
get_customization_prefs,
get_notification_prefs,
@@ -138,6 +140,12 @@ async def my_profile_page(request: Request, tab: str = "posts", page: int = 1):
user = require_user(request)
return await profile_page(request, user["username"], tab, page)
def _visible_clauses(table, viewer, profile_user):
own_uid = viewer["uid"] if viewer and viewer["uid"] == profile_user["uid"] else None
listed = listed_clause(table, own_uid=own_uid)
return [listed] if listed is not None else []
@router.get("/{username}", response_class=HTMLResponse)
async def profile_page(
request: Request, username: str, tab: str = "posts", page: int = 1
@@ -147,6 +155,7 @@ async def profile_page(
profile_user = users.find_one(username=username)
if not profile_user:
raise not_found("Profile not found")
viewing_self = bool(current_user and current_user["uid"] == profile_user["uid"])
if current_user:
mark_notifications_read_by_target(
current_user["uid"], f"/profile/{profile_user['username']}"
@@ -188,6 +197,7 @@ async def profile_page(
posts_table = get_table("posts")
raw_posts = list(
posts_table.find(
*_visible_clauses(posts_table, current_user, profile_user),
user_uid=profile_user["uid"],
deleted_at=None,
order_by=["-created_at"],
@@ -229,13 +239,20 @@ async def profile_page(
projects = list(
get_table("projects").find(user_uid=profile_user["uid"], deleted_at=None)
)
projects = [p for p in projects if can_view_project(p, current_user)]
projects = [
p
for p in projects
if (viewing_self or is_listed("projects", p))
and can_view_project(p, current_user)
]
gists = []
if tab == "gists" or include_collections:
gists_raw = list(
get_table("gists").find(user_uid=profile_user["uid"], deleted_at=None)
)
for g in gists_raw:
if not (viewing_self or is_listed("gists", g)):
continue
gists.append({"gist": g, "time_ago": time_ago(g["created_at"])})
posts_count = get_user_post_count(profile_user["uid"])
@@ -243,6 +260,7 @@ async def profile_page(
if tab == "activity":
posts_table = get_table("posts")
for p in posts_table.find(
*_visible_clauses(posts_table, current_user, profile_user),
user_uid=profile_user["uid"],
deleted_at=None,
order_by=["-created_at"],
+1 -1
View File
@@ -11,7 +11,7 @@ Each project card links to `/projects/{project_uid}` showing full project detail
**Project overview page.** The detail page is a dedicated project showcase: one encompassing dark card (`.project-shell`, the site `--bg-card` surface with clipped corners) wraps the hero, the section tab bar and the two-column body, and every inner panel (tab bar, sidebar cards, devlog post cards, empty state, comments section) sits one elevation lighter on `--bg-secondary`. The hero's cover banner is the attachment referenced by `projects.cover_attachment_uid`, falling back to the first image attachment (brand-gradient band when neither exists); the title block, type/platform chips and author row render OVERLAID on the banner behind a bottom scrim (dark text-shadow for readability) beside the optional `projects.logo_attachment_uid` tile, with an owner-set **Visit Website** CTA (`projects.website_url`). Cover and logo ride the ONE existing upload pipeline: `dp-upload` widgets (`name="cover_attachment_uid"`/`"logo_attachment_uid"`, `max-files="1"`) in the create/edit modals upload to `/uploads/upload`, the route validates each uid via `database.get_user_attachment` (must exist, belong to the actor, be an image - `_hero_attachment_uid`) and links it to the project through `attachments.link_attachments`; an empty value on edit keeps the current image (no removal control). `website_url`/`repo_url` are normalized by `models.normalize_website_url` (scheme-less input gets `https://`, non-http(s) rejected) and render with `rel="noopener nofollow"`. Below the hero an anchor **section tab bar** (`.project-tabs`, underline style, Overview `.active`) links `#about` / `#devlog` / `#screenshots` (only when gallery images exist) / `#comments` / the Files page - server-rendered anchors, no JS tab state. The main column holds **About** (description + non-image attachments), the **Devlog** (every post whose `project_uid` points at the project via `_post_card.html` - the template loads `feed.css` for the card styles alongside `post.css`, the same rule as `news.html`) with `devlog_count` (`content.count_project_devlog`) and an owner **Post update** button (`.project-devlog-post-btn`) opening the shared composer preset to `topic=devlog` + this project (the form lives ONCE in `templates/_post_composer_form.html`, locals `_composer_topic`/`_composer_project`, included by `feed.html` and `project_detail.html` - never fork a second copy), a **Screenshots** gallery (image attachments minus the cover/logo, thumbnails, `data-lightbox`, capped at 12 rendered), and the comment thread; the sidebar holds Links (website/repository/files/fork source), the Stats card (5 `.project-stat` entries + a last-update line) and the Author card. Owners add gallery images via the More-menu **Add screenshots** modal: `_attachment_form.html` uploads, then `POST /projects/{slug}/screenshots` (`ProjectScreenshotsForm`, owner-only, audit `project.screenshots.add`) links the uids through the same `link_attachments` choke point; Devii action `project_add_screenshots`, docs id `projects-screenshots`. `comment_count`/`devlog_count` ride `ProjectDetailOut`; the new project fields ride `ProjectOut`; the page og:image prefers the cover attachment. **Locator discipline:** the page has several `Files` anchors (action row, tab bar, sidebar) and, for owners, a second hidden `textarea[name='content']`/Post button inside the composer modal - tests MUST scope (`.project-detail-actions a:has-text('Files')`, `.comment-form textarea[name='content']`).
**Action row overflow.** The detail page has more actions than fit one line, so `project_detail.html` keeps the engagement actions inline (Files, Share, star vote, bookmark, reactions) and collapses the rest behind a single **More** button (`.project-actions-more`) that opens the shared `app.contextMenu`. The secondary actions (Download zip, Fork, the owner Edit/Private/Read-only/Delete controls) live as real elements inside a hidden `.project-actions-overflow` container, each tagged `data-menu-action` plus `data-menu-icon`/`data-menu-label`. `static/js/ProjectActionsMenu.js` builds the menu from those elements and each item's `onSelect` simply `.click()`s the real element, so all existing wiring is reused unchanged - `app.zipDownloader` (`data-zip-download`), `app.projectForker` (`data-fork-project`), `data-share`, the `data-modal` Edit trigger, and the delegated `data-confirm`/`data-confirm-danger` dialog on the owner forms. The open handler must `stopPropagation()` because `app.contextMenu`'s document-level close listener would otherwise dismiss it on the same click (every other caller opens it from a right-click `attach`, not a left-click). Reuse this pattern - a `More` trigger over `[data-menu-action]` real elements - for any future action row that overflows; do not duplicate controller logic into menu callbacks.
**Action row overflow.** The detail page has more actions than fit one line, so `project_detail.html` keeps the engagement actions inline (Files, Share, star vote, bookmark, reactions) and collapses the rest into a `dp-action-menu` component. The trigger is `<button data-action-menu-trigger>` labelled **More**; the secondary actions (Download zip, Fork, the owner Edit/Private/Read-only/Delete controls) are real elements inside `<div data-action-menu-source hidden>`, each tagged `data-menu-action` plus `data-menu-icon`/`data-menu-label`. `static/js/components/AppActionMenu.js` (auto-defined via `components/index.js`) builds the menu through `app.contextMenu` and each item's `onSelect` activates the real element, so all existing wiring is reused unchanged - `app.zipDownloader` (`data-zip-download`), `app.projectForker` (`data-fork-project`), the `data-modal` Edit trigger, and the `data-confirm`/`data-confirm-danger` forms, which the component confirms itself before re-clicking (the element sits in a hidden container, so delegated handlers would never see it). Reuse `<dp-action-menu>` for any future action row that overflows; do not write a bespoke controller.
**Owner editing.** Mirrors post editing exactly: an owner-only **Edit** menu item (`data-modal="edit-project-modal"`) opens the `modal()` macro's `edit-project-modal`, a plain `POST` form to `/projects/edit/{slug}` (route `edit_project` in `routers/projects/index.py`, body `ProjectEditForm`, owner-gated through the shared `content.edit_content_item` which returns 403 JSON / redirect for non-owners and stamps `updated_at`). The modal is the create modal pre-filled from the `project` row (title, description, type/status radios pre-checked, dates via `format_date()` back to DD/MM/YYYY). `is_private`/`read_only` are NOT edited here - they stay on their dedicated toggles. The platforms tag widget reuses the create modal's `platforms-input`/`platforms`/`platforms-tags` ids; `ProfileEditor.initPlatformTags` now **seeds existing tags** from the hidden `#platforms` value on load, so both the empty create form and the pre-filled edit form work from the same code. Devii tool `edit_project`; documented in `docs_api.py` (`projects-edit`).
+15 -2
View File
@@ -35,6 +35,8 @@ from devplacepy.database import (
count_forks,
get_top_authors,
get_user_attachment,
listed_clause,
is_listed,
)
from devplacepy.project_files import count_files
from devplacepy.services.jobs import queue
@@ -116,13 +118,17 @@ def get_projects_list(
clauses.append(visible)
order = ["-stars", "-created_at"] if tab == "popular" else ["-created_at"]
total = projects.count(*clauses, **filters)
own_uid = viewer["uid"] if viewer and viewer["uid"] == user_uid else None
listed = listed_clause(projects, own_uid=own_uid)
count_clauses = clauses + ([listed] if listed is not None else [])
total = projects.count(*count_clauses, **filters)
page, next_cursor = paginate(
projects,
*clauses,
before=before,
order=order,
viewer_uid=viewer["uid"] if viewer else None,
include_unlisted_of=own_uid,
**filters,
)
@@ -234,7 +240,11 @@ async def project_detail(request: Request, project_slug: str, before: str = None
)
base = site_url(request)
robots = "noindex,nofollow" if project.get("is_private") else "index,follow"
robots = (
"noindex,nofollow"
if project.get("is_private") or not is_listed("projects", project)
else "index,follow"
)
cover_url = next(
(
a["url"]
@@ -465,6 +475,7 @@ async def create_project(request: Request, data: Annotated[ProjectForm, Depends(
"cover_attachment_uid": cover_uid,
"logo_attachment_uid": logo_uid,
"is_private": 1 if data.is_private else 0,
"visibility": data.visibility,
"read_only": 0,
},
title,
@@ -495,6 +506,7 @@ async def edit_project(
"status": data.status,
"website_url": data.website_url or None,
"repo_url": data.repo_url or None,
"visibility": data.visibility,
}
hero_uids = []
for field in ("cover_attachment_uid", "logo_attachment_uid"):
@@ -616,3 +628,4 @@ async def set_project_readonly(
return _set_project_flag(request, project_slug, "read_only", data.value)
+3
View File
@@ -7,6 +7,7 @@ from fastapi.responses import RedirectResponse, JSONResponse
from devplacepy.database import get_table, db, _now_iso
from devplacepy.utils import generate_uid, require_user, track_action, redirect_back
from devplacepy.models import ReactionForm
from devplacepy.content import can_view_target
from devplacepy.services.audit import record as audit
from devplacepy.dependencies import json_or_form
@@ -25,6 +26,8 @@ async def react(
user = require_user(request)
if target_type not in REACTABLE:
return JSONResponse({"error": "Invalid target"}, status_code=400)
if not can_view_target(target_type, target_uid, user):
return JSONResponse({"error": "Not found"}, status_code=404)
emoji = data.emoji
reactions = get_table("reactions")
+4 -2
View File
@@ -3,7 +3,7 @@
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from devplacepy.constants import TOPICS, TOPIC_LABELS
from devplacepy.database import get_table
from devplacepy.database import get_table, listed_clause
from devplacepy.routers.feed import get_feed_posts, enrich_post_cards
from devplacepy.utils import get_current_user, not_found
from devplacepy.seo import list_page_seo, next_page_url
@@ -17,11 +17,13 @@ router = APIRouter()
async def topics_hub(request: Request):
user = get_current_user(request)
posts_table = get_table("posts")
listed_match = listed_clause(posts_table)
listed = [listed_match] if listed_match is not None else []
topics = [
{
"key": topic,
"label": TOPIC_LABELS.get(topic, topic.title()),
"post_count": posts_table.count(topic=topic, deleted_at=None),
"post_count": posts_table.count(*listed, topic=topic, deleted_at=None),
}
for topic in TOPICS
]
+1 -1
View File
@@ -118,7 +118,7 @@ async def generate_image(request: Request, data: Annotated[GenerateImageForm, De
}
headers = {
"Content-Type": "application/json",
"X-App-Reference": "devplace-generate-image-v-1-0-0",
"X-App-Reference": "devplace-image-gen-v-1-0-0",
"Authorization": f"Bearer {user.get('api_key', '')}",
}
try:
+3 -1
View File
@@ -5,7 +5,7 @@ from typing import Annotated
from fastapi import Depends, APIRouter, Request
from fastapi.responses import RedirectResponse, JSONResponse
from devplacepy.utils import require_user, redirect_back
from devplacepy.content import apply_vote
from devplacepy.content import apply_vote, can_view_target
from devplacepy.models import VoteForm
from devplacepy.dependencies import json_or_form
@@ -25,6 +25,8 @@ async def vote(
user = require_user(request)
if target_type not in VOTABLE:
return JSONResponse({"error": "Invalid target"}, status_code=400)
if not can_view_target(target_type, target_uid, user):
return JSONResponse({"error": "Not found"}, status_code=404)
result = apply_vote(request, user, target_type, target_uid, data.value)
if request.headers.get("x-requested-with") == "fetch":
+14 -4
View File
@@ -4,11 +4,21 @@ from __future__ import annotations
from typing import Any, Optional
from pydantic import ConfigDict, Field
from pydantic import ConfigDict, Field, field_validator
from devplacepy.database.visibility import normalize_visibility
from devplacepy.schemas.base import _Out
class VisibleOut(_Out):
visibility: str = "published"
@field_validator("visibility", mode="before")
@classmethod
def default_visibility(cls, value):
return normalize_visibility(value)
class UserOut(_Out):
uid: str = ""
username: str = ""
@@ -80,7 +90,7 @@ class ProjectLinkOut(_Out):
url: Optional[str] = None
class PostOut(_Out):
class PostOut(VisibleOut):
uid: str = ""
slug: Optional[str] = None
user_uid: Optional[str] = None
@@ -94,7 +104,7 @@ class PostOut(_Out):
updated_at: Optional[str] = None
class GistOut(_Out):
class GistOut(VisibleOut):
uid: str = ""
slug: Optional[str] = None
user_uid: Optional[str] = None
@@ -107,7 +117,7 @@ class GistOut(_Out):
updated_at: Optional[str] = None
class ProjectOut(_Out):
class ProjectOut(VisibleOut):
uid: str = ""
slug: Optional[str] = None
user_uid: Optional[str] = None
+2
View File
@@ -51,6 +51,8 @@ class AdminGatewayOut(_Out):
quota_defaults: dict = {}
stats_ranges: list = []
admin_section: Optional[str] = None
tested: str = ""
test_image: str = ""
class AdminGatewayProviderFormOut(_Out):
+8 -2
View File
@@ -421,9 +421,13 @@ def make_sitemap(base_url):
def _collect(table, limit, label, **query):
from devplacepy.database import listed_clause
if table.has_column("deleted_at") and "deleted_at" not in query:
query["deleted_at"] = None
rows = list(table.find(_limit=limit, **query))
listed = listed_clause(table)
clauses = [listed] if listed is not None else []
rows = list(table.find(*clauses, _limit=limit, **query))
if len(rows) >= limit:
logger.warning("sitemap: %s truncated at %d entries", label, limit)
return rows
@@ -574,11 +578,13 @@ def _build_sitemap(base_url):
)
)
from devplacepy.database import listed_sql
if "users" in db.tables:
post_counts = {}
if "posts" in db.tables:
for row in db.query(
"SELECT user_uid, COUNT(*) AS c FROM posts WHERE deleted_at IS NULL GROUP BY user_uid"
f"SELECT user_uid, COUNT(*) AS c FROM posts WHERE deleted_at IS NULL AND {listed_sql('posts')} GROUP BY user_uid"
):
post_counts[row["user_uid"]] = row["c"]
users = _collect(
+2
View File
@@ -7,6 +7,7 @@ from devplacepy.config import DEFAULT_MODIFIER_PROMPT, INTERNAL_MODEL
from devplacepy.database import add_modifier_usage, get_setting, get_table
from devplacepy.services.ai_context import build_context
from devplacepy.services.background import background
from devplacepy.services.openai_gateway.apps import APP_REFERENCE_MODIFIER
from devplacepy.services.correction import (
CORRECTABLE_FIELDS,
gateway_complete,
@@ -50,6 +51,7 @@ def modify_text(
None,
model=modifier_model(),
bypass_preamble=True,
app_reference=APP_REFERENCE_MODIFIER,
)
+1 -1
View File
@@ -27,7 +27,7 @@ Admin-only, enterprise-grade backups built on the **same async-job pattern as zi
**`prune_orphans` (`devplace backups prune`) is offload-aware for the same reason:** a `done` row with a confirmed `remote_uploaded_at` is skipped even when its `local_path` is empty/missing - that is the normal steady state after `enforce_local_retention` purges the local copy, not an orphan. Only a `done` row with no confirmed remote copy AND a missing local file counts as truly orphaned and gets hard-deleted. Without this check, running the CLI prune after offload has done its job would delete the DB record for every successfully offloaded backup, discarding the only pointer to its `remote_path`.
**Operational prerequisite (production, not automatic):** the `rclone` binary is installed in the shipped Docker image, but a working WebDAV remote still needs to exist at `config.RCLONE_CONFIG_FILE` (default `$HOME/.config/rclone/rclone.conf` inside the app container, overridable via `DEVPLACE_RCLONE_CONFIG`) with a remote named to match `config.BACKUP_OFFLOAD_REMOTE`'s prefix (default `storagebox`) pointing at the Hetzner Storage Box's WebDAV endpoint and credentials - `rclone config` (interactive) or a hand-written `rclone.conf` generates it. Until that file exists, every `upload_pending` attempt fails fast (`rclone` errors "didn't find section") and is logged and retried next cycle; local retention and rotation both stay disabled the whole time (see above), so backups simply accumulate locally with no data loss, they just never leave the box. **In Docker, `HOME=/app` (the bind-mounted repo root, `docker-compose.yml`), so the default config path resolves to `<repo>/.config/rclone/rclone.conf` on the host - `.gitignore` excludes `/.config/` precisely because this file holds live remote-storage credentials; never force-add it.**
**Operational prerequisite (production, not automatic):** the `rclone` binary is installed in the shipped Docker image, but a working WebDAV remote still needs to exist at `config.RCLONE_CONFIG_FILE` (default `$HOME/.config/rclone/rclone.conf` inside the app container, overridable via `DEVPLACE_RCLONE_CONFIG`) with a remote named to match `config.BACKUP_OFFLOAD_REMOTE`'s prefix (default `storagebox`) pointing at the Hetzner Storage Box's WebDAV endpoint and credentials - `rclone config` (interactive) or a hand-written `rclone.conf` generates it. Until that file exists, every `upload_pending` attempt fails fast (`rclone` errors "didn't find section") and is logged and retried next cycle; local retention and rotation both stay disabled the whole time (see above), so backups simply accumulate locally with no data loss, they just never leave the box. **In Docker, `HOME=/app` (the bind-mounted repo root, `docker-compose.yml`), so the default config path resolves to `<repo>/.config/rclone/rclone.conf` on the host - `.gitignore` excludes `/.config/` precisely because this file holds live remote-storage credentials; never force-add it.** When the `rclone` binary itself is absent (`shutil.which(config.RCLONE_BIN)` finds nothing, e.g. bare-metal hosts without rclone installed), `run_cycle` skips the whole cycle with one `Offload skipped: rclone binary not found ...` log line naming the `backup_offload_enabled` kill-switch, and retries next cycle - installing rclone needs no restart.
## Disk usage warning
+7
View File
@@ -2,6 +2,7 @@
import asyncio
import json
import shutil
from pathlib import Path
from devplacepy import config
@@ -118,6 +119,12 @@ async def enforce_remote_retention(keep_remote: int, log=lambda message: None) -
async def run_cycle(*, keep_local: int, keep_remote: int, log=lambda message: None) -> dict:
if shutil.which(config.RCLONE_BIN) is None:
log(
f"Offload skipped: rclone binary not found ({config.RCLONE_BIN}); "
"install rclone or disable backup_offload_enabled"
)
return {"uploaded": 0, "purged_local": 0, "removed_remote": 0}
uploaded = await upload_pending(log=log)
purged_local = await enforce_local_retention(keep_local, log=log)
removed_remote = await enforce_remote_retention(keep_remote, log=log)
+5 -1
View File
@@ -20,6 +20,7 @@ from devplacepy.services.bot.config import (
TRIVIAL_GIST_TERMS,
)
from devplacepy.services.bot.handles import MAX_HANDLE_LEN, sanitize_handle
from devplacepy.services.openai_gateway.apps import APP_REFERENCE_BOTS
from devplacepy.services.openai_gateway.usage import parse_usage_headers
HANDLE_CANDIDATE_TARGET = 8
@@ -71,7 +72,10 @@ class LLMClient:
resp = client.post(
self.api_url,
json=payload,
headers={"Authorization": f"Bearer {self.api_key}"},
headers={
"Authorization": f"Bearer {self.api_key}",
"X-App-Reference": APP_REFERENCE_BOTS,
},
)
raw = resp.content
logger.info("LLM <<< %s", raw[:2000].decode(errors="replace"))
+2 -1
View File
@@ -97,10 +97,11 @@ class AiAssistant:
if not self.enabled():
return None
from devplacepy.services.correction import gateway_complete
from devplacepy.services.openai_gateway.apps import APP_REFERENCE_COMMUNITY
model = get_setting("community_ai_model", "") or INTERNAL_MODEL
reply, usage = await asyncio.to_thread(
gateway_complete, internal_gateway_key(), system, user, AI_TIMEOUT_SECONDS, None, model, True, False
gateway_complete, internal_gateway_key(), system, user, AI_TIMEOUT_SECONDS, None, model, True, False, APP_REFERENCE_COMMUNITY
)
if usage is None:
logger.warning("ai: the %s model is unreachable, continuing with heuristics only", model)
+3 -1
View File
@@ -8,6 +8,7 @@ from concurrent.futures import ThreadPoolExecutor
import httpx
from devplacepy import stealth
from devplacepy.services.openai_gateway.apps import APP_REFERENCE_CORRECTION, APP_REFERENCE_HEADER
from devplacepy.config import (
DEFAULT_CORRECTION_PROMPT,
INTERNAL_GATEWAY_URL,
@@ -101,6 +102,7 @@ def gateway_complete(
model: str = INTERNAL_MODEL,
bypass_preamble: bool = False,
check_structure: bool = False,
app_reference: str = APP_REFERENCE_CORRECTION,
) -> tuple[str, dict | None]:
text = text or ""
if not text.strip():
@@ -117,7 +119,7 @@ def gateway_complete(
payload["bypass_preamble"] = True
headers = {
"Content-Type": "application/json",
"X-App-Reference": "devplace-correction-v-1-0-0",
APP_REFERENCE_HEADER: app_reference,
}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
+27 -23
View File
@@ -122,32 +122,36 @@ class DbApiJobService(JobService):
}
async def _stream(self, uid: str, sql: str, max_rows: int):
connection = sqlite3.connect(
f"file:{_database_path()}?mode=ro", uri=True, timeout=30
)
db_path = _database_path()
loop = asyncio.get_running_loop()
rows: list[dict] = []
truncated = False
try:
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA query_only=ON")
cursor = connection.execute(sql)
while True:
batch = cursor.fetchmany(BATCH_SIZE)
if not batch:
break
for raw in batch:
if len(rows) >= max_rows:
truncated = True
def _run() -> tuple[list[dict], bool]:
out: list[dict] = []
stop = False
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30)
try:
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA query_only=ON")
cursor = conn.execute(sql)
while True:
batch = cursor.fetchmany(BATCH_SIZE)
if not batch:
break
rows.append(dict(raw))
hub.publish(
uid, {"type": "progress", "row_count": len(rows)}
)
if truncated:
break
await asyncio.sleep(0)
finally:
connection.close()
for raw in batch:
if len(out) >= max_rows:
stop = True
break
out.append(dict(raw))
loop.call_soon_threadsafe(hub.publish, uid, {"type": "progress", "row_count": len(out)})
if stop:
break
finally:
conn.close()
return out, stop
rows, truncated = await asyncio.to_thread(_run)
return rows, truncated
def cleanup(self, job: dict) -> None:
+13
View File
@@ -269,3 +269,16 @@ Two more Devii-side controllers live under `services/devii/` but their full mech
- **Per-user customization tools** (`services/devii/customization/`, `handler="customization"`): `customize_list`/`get`/`set_css`/`set_js`/`reset` (all `requires_auth=False`) plus `customize_set_enabled` (`requires_auth=True`, the suppression toggles). `CustomizationController(owner_kind, owner_id)` is built in `Dispatcher.__init__`; set/reset are in `CONFIRM_REQUIRED` so `confirmation_error` forces Devii to ask **page-type vs global** before `confirm=true`. Devii previews live with `run_js` (ids `devii-preview-css`/`devii-preview-js`) and `reload_page` after saving. For the storage model, injection pipeline, and per-user suppression flags, see `devplacepy/customization.py` and its own documentation.
- **Container tools** (`services/devii/container/ContainerController`, `handler="container"`): wraps `services/containers/api.py`, the same operations shared by `routers/containers.py`. For the reconciler, backend ABC, ingress proxy, and workspace sync mechanism, see `devplacepy/services/containers/CLAUDE.md`.
## Async subagents (`services/devii/agents/`, `handler="agent"`)
The agent-as-tool layer next to sync `delegate` (which is untouched): the orchestrator keeps the user conversation and clones itself into supervised background runs for slow work. Gated by the `devii_agents_enabled` ConfigField (default off); when off the six schemas are hidden in `_builtin_tools` and dispatch refuses with `ToolDisabledError`, so flag-off behavior is byte-identical to before. Guests see only the read tools (`agent_status`/`agent_result`/`agent_list`); spawning and cancelling are `requires_auth=True`. The docs channel never sees any of them. The standalone CLI excludes agent-handler tools explicitly.
- **Contract.** `agent_start(category, task, output_format, tools_extra, budget_hint)` carries the four-part delegation contract (objective plus boundaries, output shape, tool guidance, effort scale). Categories, budgets, and the denied set live in `agents/policy.py` (`CATEGORIES`, `ORCHESTRATOR_ONLY_TOOLS`); `agents/tools.py` `build_subagent_tools` computes inheritance (parent effective tools minus denied plus category/model extras plus `ask_user`, re-filtered by role and `tool_prefs`).
- **Run shape.** `agents/store.py` `AgentStore` over `devii_agent_runs` (statuses `queued`/`running`/`needs_user`/`done`/`failed`/`cancelled`/`interrupted`, transient `checking` for the atomic claim). Runs are execution records like `devii_task_runs`: hard-pruned after 48h by `run_once`, never soft-deleted.
- **Runner.** `agents/runner.py` runs one `react_loop` per segment with its own messages/state/cost/chunks, sharing dispatcher and LLM client. It never takes `session._lock`, so the user keeps chatting; `session._agents` pins the session against `gc_idle` (see `is_busy`). `ask_user` pauses mid-loop by end-detection (the paused tool result stays in history, so no sibling result is ever lost and nothing is retried); resume replaces that result's content in place, never appending a duplicate `tool_call_id`.
- **Supervisor.** `agents/supervisor.py` `AgentSupervisor` (owned by `DeviiService`, started/stopped with it, 1s tick, 4 global plus 2 per-owner slots) claims due rows atomically, builds a snapshot, and applies `policy.decide` (cancel first, then retry-else, nudge, wait, continue). Terminal writes go through the conditional `complete()` so a cancel always wins over a racing finish. Boot reaps `running`/`checking` rows as `interrupted` and notifies owners. Metrics surface as `Subagents` on/off and `Agents running` in `collect_metrics`.
- **Money and audit.** Each segment ledgers its cost delta to `devii_usage_ledger` under the agent uid in a `finally`; quota is gated at spawn, at every check, and inside the runner. Audit keys `devii.agent.start` (dispatcher mechanic), `devii.agent.done`/`devii.agent.cancel` (supervisor).
- **Nesting.** `task_scope` is captured at spawn; a run spawned from a task run executes inside `task_run_scope`, so `nesting_allowed` holds with no new bypass. Async depth is 1: subagents never see `agent_*`.
- **Frames.** Runs emit `trace` frames tagged with `agent`/`uid` (rendered `[label]`-prefixed in the terminal and Telegram progress) plus an `agent` frame family (`started`/`needs_user`/`done`/`failed`/`cancelled`/`interrupted`), buffered for web, never buffered for telegram (late telegram delivery goes direct instead - see below).
- **Tests.** Unit coverage under `tests/unit/services/devii/agents/` (policy decision table, store plus a multiprocess claim race, builder, controller, runner, supervisor, flag parity, prompt gating, stubbed-loop drive paths with ledger attribution). `EVALS` in `agents/evals.py` is the 20-query end-state eval set; live runs need a gateway and stay manual.
@@ -47,3 +47,16 @@ def confirm() -> Param:
ATTACHMENTS = "Comma separated attachment uids returned by upload_file."
TARGET_TYPE = "Target type, e.g. post, comment, project, gist."
VISIBILITY = (
"Visibility: published (default, listed and open to everyone), hidden (not listed or "
"searchable, anyone with the link can open it), offline (taken offline, only you can see "
"it, publish again at any time) or draft (only you, not yet published). "
)
VISIBILITY_CREATE = VISIBILITY + "Optional: omit it and the item is published."
VISIBILITY_EDIT = VISIBILITY + "Optional: omit it to keep the current value."
VISIBILITY_VALUE = (
"New visibility: published, hidden, offline or draft. Only the owner can change it. "
"Offline and draft hide the item from everyone but the owner and administrators."
)
@@ -3,7 +3,7 @@
from __future__ import annotations
from ..spec import Action
from ._shared import body, confirm, path, query
from ._shared import VISIBILITY_VALUE, body, confirm, path, query
ADMIN_ACTIONS: tuple[Action, ...] = (
@@ -218,6 +218,17 @@ ADMIN_ACTIONS: tuple[Action, ...] = (
params=(path("uid", "News uid."),),
requires_admin=True,
),
Action(
name="admin_set_news_visibility",
method="POST",
path="/admin/news/{uid}/visibility",
summary="Set the visibility of a news article (published, hidden, offline or draft)",
params=(
path("uid", "News uid."),
body("value", VISIBILITY_VALUE, required=True),
),
requires_admin=True,
),
Action(
name="admin_landing_news",
method="POST",
@@ -127,6 +127,7 @@ GATEWAY_ACTIONS: tuple[Action, ...] = (
Param(name="off_peak_end_minute", location="body", description="Off-peak window end, UTC minutes since midnight (0-1439). A value less than the start wraps past midnight.", required=False, type="integer"),
Param(name="off_peak_discount_pct", location="body", description="Percentage discount (0-100) applied to the active tier's rates during the off-peak window.", required=False, type="number"),
body("fallback_model", "Another already-configured source_model of the same kind, tried once automatically when this route fails after its own retries are exhausted. Blank disables fallback."),
body("tools_mode", "'native' (default) forwards tools untouched; 'emulated' declares the model does not support tool calling, so the gateway rewrites tools into the prompt and converts the reply back into OpenAI tool_calls."),
Param(name="is_active", location="body", description="Whether the route is active ('1' or '0').", required=False, type="boolean"),
),
),
@@ -3,7 +3,15 @@
from __future__ import annotations
from ..spec import Action
from ._shared import ATTACHMENTS, body, confirm, path, query
from ._shared import (
ATTACHMENTS,
VISIBILITY_CREATE,
VISIBILITY_EDIT,
body,
confirm,
path,
query,
)
GIST_ACTIONS: tuple[Action, ...] = (
@@ -44,6 +52,7 @@ GIST_ACTIONS: tuple[Action, ...] = (
body("description", "Gist description."),
body("language", "Programming language."),
body("attachment_uids", ATTACHMENTS),
body("visibility", VISIBILITY_CREATE),
),
),
Action(
@@ -60,6 +69,7 @@ GIST_ACTIONS: tuple[Action, ...] = (
body("source_code", "Gist source code.", required=True),
body("description", "Gist description."),
body("language", "Programming language."),
body("visibility", VISIBILITY_EDIT),
),
),
Action(
@@ -3,7 +3,7 @@
from __future__ import annotations
from ..spec import Action
from ._shared import ATTACHMENTS, body, query
from ._shared import ATTACHMENTS, body, confirm, path, query
MESSAGE_ACTIONS: tuple[Action, ...] = (
@@ -34,5 +34,12 @@ MESSAGE_ACTIONS: tuple[Action, ...] = (
body("receiver_uid", "Recipient user uid.", required=True),
body("attachment_uids", ATTACHMENTS),
),
), Action(
name="delete_message",
method="POST",
path="/messages/{message_uid}/delete",
summary="Delete a direct message you sent (administrators only, own messages only). Soft delete, confirmation required",
params=(path("message_uid", "Uid of the message."), confirm()),
requires_admin=True,
),
)
@@ -3,7 +3,15 @@
from __future__ import annotations
from ..spec import Action
from ._shared import ATTACHMENTS, body, confirm, path, query
from ._shared import (
ATTACHMENTS,
VISIBILITY_CREATE,
VISIBILITY_EDIT,
body,
confirm,
path,
query,
)
POSTS_ACTIONS: tuple[Action, ...] = (
@@ -63,6 +71,7 @@ POSTS_ACTIONS: tuple[Action, ...] = (
"war_faction_b",
"Optional Opinion War faction B name (max 30 chars). Must differ from faction A.",
),
body("visibility", VISIBILITY_CREATE),
),
),
Action(
@@ -99,6 +108,7 @@ POSTS_ACTIONS: tuple[Action, ...] = (
"poll_options",
"Poll options as a JSON array of strings, or one option per line, or comma separated. At least two are required for the poll to be created.",
),
body("visibility", VISIBILITY_EDIT),
),
),
Action(
@@ -3,7 +3,15 @@
from __future__ import annotations
from ..spec import Action
from ._shared import ATTACHMENTS, body, confirm, path, query
from ._shared import (
ATTACHMENTS,
VISIBILITY_CREATE,
VISIBILITY_EDIT,
body,
confirm,
path,
query,
)
PROJECTS_ACTIONS: tuple[Action, ...] = (
@@ -52,6 +60,7 @@ PROJECTS_ACTIONS: tuple[Action, ...] = (
body("cover_attachment_uid", "Attachment uid of an uploaded cover image (upload_file/attach_url first)."),
body("logo_attachment_uid", "Attachment uid of an uploaded project logo (upload_file/attach_url first)."),
body("attachment_uids", ATTACHMENTS),
body("visibility", VISIBILITY_CREATE),
),
),
Action(
@@ -75,6 +84,7 @@ PROJECTS_ACTIONS: tuple[Action, ...] = (
body("repo_url", "Updated source repository URL (http/https)."),
body("cover_attachment_uid", "Attachment uid of a new cover image; empty keeps the current one."),
body("logo_attachment_uid", "Attachment uid of a new project logo; empty keeps the current one."),
body("visibility", VISIBILITY_EDIT),
),
),
Action(
@@ -73,6 +73,46 @@ UPLOAD_ACTIONS: tuple[Action, ...] = (
),
),
),
Action(
name="search_gifs",
method="GET",
path="/giphy/search",
summary="Search GIPHY for GIFs by keyword",
description=(
"Searches GIPHY and returns {query, results}. Each result carries id, title, preview (a small "
"still-animated rendition) and original (the full GIF). Pass a result's id to attach_gif to "
"attach it. Answers 503 when GIPHY is not configured by an administrator and 429 when you search "
"too fast."
),
params=(
query("q", "Search keywords, 1-200 characters.", required=True),
query("limit", "Number of results, 1-50 (default 24)."),
),
),
Action(
name="trending_gifs",
method="GET",
path="/giphy/trending",
summary="List the GIFs currently trending on GIPHY",
description="Returns {results} in the same shape as search_gifs. Pass a result's id to attach_gif.",
params=(query("limit", "Number of results, 1-50 (default 24)."),),
),
Action(
name="attach_gif",
method="POST",
path="/giphy/attach",
summary="Store a GIPHY GIF as an attachment, returning its uid",
description=(
"Downloads the GIF with the given GIPHY id on the server and stores it as an attachment exactly "
"like an upload, returning {uid, url, mime_type, ...}. Pass the returned uid in attachment_uids "
"when you create_post, create_comment or send_message to attach it. Find ids with search_gifs or "
"trending_gifs."
),
params=(
body("gif_id", "GIPHY id of the GIF, from search_gifs or trending_gifs.", required=True),
body("title", "Optional title used as the attachment's filename."),
),
),
Action(
name="generate_image",
method="POST",
@@ -63,6 +63,7 @@ CONFIRM_REQUIRED = {
"regenerate_avatar",
"delete_post",
"delete_comment",
"delete_message",
"delete_gist",
"delete_attachment",
"delete_issue_attachment",
@@ -150,6 +151,7 @@ _DEVII_MECHANIC_EVENTS = {
"email_set_flags": "email.message.flag",
"telegram_send": "telegram.send",
"interactions_set": "profile.interactions",
"agent_start": "devii.agent.start",
}
_DEVII_CONTAINER_EVENTS = {
@@ -247,6 +249,12 @@ def confirmation_error(name: str, arguments: dict[str, Any]) -> ToolInputError |
f"Deleting comment '{uid}' is permanent and cannot be undone. "
"Ask the user to confirm explicitly, then call again with confirm=true."
)
if name == "delete_message":
uid = str(arguments.get("message_uid", "")).strip() or "(unspecified)"
return ToolInputError(
f"Deleting message '{uid}' removes it from the conversation for both participants. "
"Show the user the exact message, get explicit confirmation, then call again with confirm=true."
)
if name == "community_delete":
slug = str(arguments.get("slug", "")).strip() or "(unspecified)"
return ToolInputError(
@@ -378,6 +386,7 @@ class Dispatcher:
virtual_tools: Any = None,
behavior: Any = None,
interaction: Any = None,
agents: Any = None,
) -> None:
self._actions = catalog.by_name()
self._client = client
@@ -421,6 +430,7 @@ class Dispatcher:
self._virtual_tools = virtual_tools
self._behavior = behavior
self._interaction = interaction
self._agents = agents
self._read_files: set[tuple[str, str]] = set()
def set_admin(self, is_admin: bool, is_primary_admin: bool) -> None:
@@ -648,6 +658,24 @@ class Dispatcher:
)
return await self._virtual_tools.dispatch(action.name, arguments)
if action.handler == "agent":
if self._agents is None:
return error_result(
ToolInputError(
"Subagents are not available in this context."
)
)
from ..agents.policy import enabled as agents_enabled
if not agents_enabled():
self._audit_denied(action.name, "disabled by administrator", arguments)
raise ToolDisabledError(
"Subagents have been disabled by an administrator. Do not retry "
"them; tell the user they are unavailable.",
tool=action.name,
)
return await self._agents.dispatch(action.name, arguments)
if action.handler == "avatar":
if self._avatar is None:
return error_result(
@@ -52,6 +52,7 @@ class Action:
"email",
"telegram",
"interaction",
"agent",
] = "http"
freeform_body: bool = False
ajax: bool = False
@@ -0,0 +1,31 @@
# retoor <retoor@molodetz.nl>
from .actions import AGENT_ACTIONS
from .controller import AgentController
from .evals import EVALS
from .policy import (
CATEGORIES,
ORCHESTRATOR_ONLY_TOOLS,
decide,
enabled,
next_check_in,
)
from .runner import AgentRunner
from .store import AgentStore
from .supervisor import AgentSupervisor
from .tools import build_subagent_tools
__all__ = [
"AGENT_ACTIONS",
"CATEGORIES",
"EVALS",
"ORCHESTRATOR_ONLY_TOOLS",
"AgentController",
"AgentRunner",
"AgentStore",
"AgentSupervisor",
"build_subagent_tools",
"decide",
"enabled",
"next_check_in",
]
+148
View File
@@ -0,0 +1,148 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
from ..actions.spec import Action, Param
def field(
name: str, description: str, required: bool = False, kind: str = "string"
) -> Param:
return Param(
name=name,
location="body",
description=description,
required=required,
type=kind,
)
AGENT_ACTIONS: tuple[Action, ...] = (
Action(
name="agent_start",
method="LOCAL",
path="",
summary="Clone yourself into a supervised async subagent for slow or multi-step work",
description=(
"Spawns a subagent with its own context window, its own category system prompt, "
"and your effective tool list plus the category extras. Returns a process uid "
"immediately; the subagent runs in the background while you keep chatting. Poll "
"with agent_status, read the outcome with agent_result, stop it with agent_cancel. "
"The four-part contract is mandatory: a clear objective in task, the exact shape "
"of the answer in output_format, tool and source guidance via tools_extra, and "
"hard task boundaries inside task. Only the orchestrator talks to the user: a "
"subagent that needs input pauses as needs_user and you resume it through "
"agent_result with an answer."
),
handler="agent",
requires_auth=True,
params=(
field(
"category",
"One of research, files, planning-report, email-triage, containers, "
"long-mutation. Picks the subagent system prompt, tool extras, and budgets.",
required=True,
),
field(
"task",
"Complete self-contained objective plus hard boundaries: what to do, what "
"to touch, and what to leave alone. The subagent has no other context.",
required=True,
),
field(
"output_format",
"Exact shape of the expected answer, e.g. 'a markdown table with columns "
"name, url, verdict, one row per finding' or 'the list of paths changed "
"plus one summary line'.",
required=True,
),
field(
"tools_extra",
"Optional extra tool names beyond the inherited set, e.g. a tool the "
"category does not include by default.",
kind="array",
),
field(
"budget_hint",
"Effort scale: quick (half budgets), standard, or deep (double budgets). "
"Match it to the query complexity; default standard.",
),
field("label", "Optional short human-readable label for the run."),
),
),
Action(
name="agent_status",
method="LOCAL",
path="",
summary="Check one subagent run's progress without blocking",
handler="agent",
requires_auth=False,
params=(field("uid", "Process uid returned by agent_start.", required=True),),
),
Action(
name="agent_result",
method="LOCAL",
path="",
summary="Read a subagent run's outcome, or resume it with an answer",
description=(
"Returns the final result once the run is done, or the current progress "
"otherwise. When the run pauses as needs_user, pass answer to resume it: "
"ask the user first through ui_prompt, then hand their answer back here."
),
handler="agent",
requires_auth=False,
params=(
field("uid", "Process uid returned by agent_start.", required=True),
field(
"answer",
"Answer to the pending needs_user question. Only used while the run "
"is paused as needs_user; ignored otherwise.",
),
),
),
Action(
name="agent_cancel",
method="LOCAL",
path="",
summary="Stop a running or paused subagent run",
handler="agent",
requires_auth=True,
params=(field("uid", "Process uid returned by agent_start.", required=True),),
),
Action(
name="agent_list",
method="LOCAL",
path="",
summary="List your subagent runs and their statuses",
handler="agent",
requires_auth=False,
params=(
field(
"status",
"Filter by status: queued, running, needs_user, done, failed, "
"cancelled, interrupted.",
),
),
),
Action(
name="ask_user",
method="LOCAL",
path="",
summary="Pause this subagent run and ask the user one question (subagents only)",
description=(
"Pauses the run as needs_user. The orchestrator asks the user through "
"its own channel and resumes the run with the answer, which arrives as "
"this call's result. Call it alone, then stop: end the turn with a short "
"note of what is awaited and call no further tools until the answer arrives."
),
handler="agent",
requires_auth=False,
params=(
field(
"question",
"The exact question for the user, including the decision or target.",
required=True,
),
),
),
)
@@ -0,0 +1,258 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
import json
import logging
from datetime import datetime, timezone
from typing import Any
import uuid_utils
from ..errors import ToolInputError
from ..tasks.context import in_task_run
from .policy import CATEGORIES, EFFORT_SCALE, ORCHESTRATOR_ONLY_TOOLS, TERMINAL_STATUSES, enabled
from .store import ACTIVE_STATUSES, AgentStore
from .supervisor import DEFAULT_MAX_PER_OWNER
logger = logging.getLogger("devii.agents.controller")
RESULT_PREVIEW_CHARS = 500
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat(timespec="microseconds")
def _serialize(row: dict[str, Any], full: bool) -> dict[str, Any]:
view: dict[str, Any] = {
"uid": row.get("uid"),
"label": row.get("label"),
"category": row.get("category"),
"status": row.get("status"),
"effort": row.get("effort"),
"progress": row.get("progress"),
"checks": int(row.get("checks") or 0),
"iterations": int(row.get("iterations") or 0),
"tokens": int(row.get("tokens") or 0),
"check_at": row.get("check_at"),
"created_at": row.get("created_at"),
}
question = row.get("needs_question")
if question:
view["needs_question"] = question
error = row.get("error")
if error:
view["error"] = error
result = row.get("result")
if result:
view["result"] = result if full else result[:RESULT_PREVIEW_CHARS]
return view
class AgentController:
def __init__(self, session: Any, supervisor: Any = None) -> None:
self._session = session
self._supervisor_override = supervisor
@property
def _store(self) -> AgentStore:
return AgentStore(
self._session.store.db,
self._session.owner_kind,
self._session.owner_id,
)
def _supervisor(self) -> Any:
if self._supervisor_override is not None:
return self._supervisor_override
from devplacepy.services.manager import service_manager
svc = service_manager.get_service("devii")
if svc is None or not svc.is_enabled():
return None
return svc.agent_supervisor()
async def dispatch(self, name: str, arguments: dict[str, Any]) -> str:
handlers = {
"agent_start": self.start,
"agent_status": self.status,
"agent_result": self.result,
"agent_cancel": self.cancel,
"agent_list": self.list_runs,
"ask_user": self.ask,
}
handler = handlers.get(name)
if handler is None:
raise ToolInputError(f"Unknown agent tool: {name}")
return await handler(arguments)
async def start(self, arguments: dict[str, Any]) -> str:
if not enabled():
raise ToolInputError("Subagents are disabled by the administrator.")
category = str(arguments.get("category", "")).strip()
if category not in CATEGORIES:
valid = ", ".join(sorted(CATEGORIES))
raise ToolInputError(f"Unknown category '{category}'. Use one of: {valid}.")
effort = str(arguments.get("budget_hint") or "standard").strip()
if effort not in EFFORT_SCALE:
raise ToolInputError(
f"Unknown budget_hint '{effort}'. Use one of: quick, standard, deep."
)
task = str(arguments.get("task", "")).strip()
if not task:
raise ToolInputError("agent_start requires a non-empty task.")
output_format = str(arguments.get("output_format", "")).strip()
if not output_format:
raise ToolInputError("agent_start requires a non-empty output_format.")
extra = self._clean_extra(arguments.get("tools_extra"))
if self._session._quota_snapshot()["limit_reached"]:
raise ToolInputError("Daily AI quota reached (100%). Try again later.")
if self._store.count_active() >= DEFAULT_MAX_PER_OWNER:
raise ToolInputError(
f"You already have {DEFAULT_MAX_PER_OWNER} active subagent runs. "
"Wait for one to finish or cancel it first."
)
supervisor = self._supervisor()
if supervisor is None:
raise ToolInputError("Subagents are not available in this context.")
now = _now_iso()
record = {
"uid": uuid_utils.uuid7().hex,
"channel": self._session.channel,
"category": category,
"label": str(arguments.get("label") or "").strip() or None,
"task": task,
"output_format": output_format,
"tools_extra": json.dumps(extra),
"effort": effort,
"task_scope": 1 if in_task_run() else 0,
"status": "queued",
"progress": "queued",
"result": None,
"error": None,
"checks": 0,
"nudges_used": 0,
"retries_used": 0,
"error_streak": 0,
"iterations": 0,
"tokens": 0,
"cost_usd": 0.0,
"needs_question": None,
"pending_ask_id": None,
"check_at": now,
"last_progress_at": now,
"created_at": now,
"updated_at": now,
}
self._store.create(record)
await self._session.emit_agent(
{
"type": "agent",
"kind": "started",
"uid": record["uid"],
"label": record["label"] or record["uid"][:8],
"payload": category,
}
)
return json.dumps(
{"status": "queued", "run": _serialize(record, full=False)},
ensure_ascii=False,
)
async def status(self, arguments: dict[str, Any]) -> str:
row = self._require_row(arguments)
return json.dumps({"run": _serialize(row, full=False)}, ensure_ascii=False)
async def result(self, arguments: dict[str, Any]) -> str:
row = self._require_row(arguments)
answer = str(arguments.get("answer", "") or "").strip()
if answer and str(row.get("status")) == "needs_user":
supervisor = self._supervisor()
if supervisor is None:
raise ToolInputError("Subagents are not available in this context.")
resumed = await supervisor.resume(str(row["uid"]), answer)
row = self._require_row(arguments)
if not resumed:
if str(row.get("status")) == "needs_user":
self._store.update(
str(row["uid"]),
{
"status": "interrupted",
"error": "run lost its worker; start a new run",
"updated_at": _now_iso(),
},
)
raise ToolInputError(
"That run lost its worker (restart). Start a new run instead."
)
raise ToolInputError(
f"Run {row['uid']} is already {row.get('status')}."
)
return json.dumps({"run": _serialize(row, full=True)}, ensure_ascii=False)
async def cancel(self, arguments: dict[str, Any]) -> str:
row = self._require_row(arguments)
if str(row.get("status")) in TERMINAL_STATUSES:
raise ToolInputError(f"Run {row['uid']} is already {row.get('status')}.")
supervisor = self._supervisor()
if supervisor is None:
raise ToolInputError("Subagents are not available in this context.")
await supervisor.cancel(str(row["uid"]), "cancelled by orchestrator")
row = self._require_row(arguments)
return json.dumps(
{"status": row.get("status"), "uid": row["uid"]}, ensure_ascii=False
)
async def list_runs(self, arguments: dict[str, Any]) -> str:
status = str(arguments.get("status", "") or "").strip() or None
if status is not None and status not in ACTIVE_STATUSES + tuple(TERMINAL_STATUSES):
raise ToolInputError(f"Unknown status '{status}'.")
rows = self._store.list(status=status)
return json.dumps(
{
"count": len(rows),
"runs": [_serialize(row, full=False) for row in rows],
},
ensure_ascii=False,
)
async def ask(self, arguments: dict[str, Any]) -> str:
question = str(arguments.get("question", "")).strip()
if not question:
raise ToolInputError("ask_user requires a non-empty question.")
return json.dumps(
{"status": "paused_for_user", "question": question}, ensure_ascii=False
)
def _clean_extra(self, raw: Any) -> list[str]:
if raw is None:
return []
if not isinstance(raw, list):
raise ToolInputError("tools_extra must be a list of tool names.")
from ..registry import CATALOG
known = set(CATALOG.by_name())
cleaned: list[str] = []
for name in raw:
text = str(name or "").strip()
if not text:
continue
if text not in known:
raise ToolInputError(f"Unknown tool '{text}' in tools_extra.")
if text in ORCHESTRATOR_ONLY_TOOLS:
raise ToolInputError(
f"Tool '{text}' is orchestrator-only and cannot be delegated."
)
if text not in cleaned:
cleaned.append(text)
return cleaned
def _require_row(self, arguments: dict[str, Any]) -> dict[str, Any]:
uid = str(arguments.get("uid", "")).strip()
if not uid:
raise ToolInputError("This agent tool requires a uid.")
row = self._store.get(uid)
if row is None:
raise ToolInputError(f"No agent run found with uid {uid}.")
return row
+169
View File
@@ -0,0 +1,169 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
from typing import Any
EVALS: tuple[dict[str, Any], ...] = (
{
"uid": "eval-direct-quota",
"channel": "main",
"prompt": "How much of my AI quota have I used today?",
"expect": "direct",
"end_state": "Reply states the quota percentage and turn count, no dollar figure.",
"tools": ("usage_quota",),
},
{
"uid": "eval-direct-time",
"channel": "main",
"prompt": "What time is it in UTC right now, exactly?",
"expect": "direct",
"end_state": "Reply states the current UTC time to the second.",
"tools": ("current_time",),
},
{
"uid": "eval-direct-docs",
"channel": "main",
"prompt": "How do I pair Telegram on this site?",
"expect": "direct",
"end_state": "Reply links the documented pairing page.",
"tools": ("search_docs",),
},
{
"uid": "eval-direct-site-stats",
"channel": "main",
"prompt": "How many members and posts does this site have?",
"expect": "direct",
"end_state": "Reply states member and content totals from one aggregate call.",
"tools": ("site_analytics",),
},
{
"uid": "eval-direct-lesson",
"channel": "main",
"prompt": "Remember that I prefer concise replies with no preamble.",
"expect": "direct",
"end_state": "A behavior rule persists and the next reply is concise.",
"tools": ("update_behavior",),
},
{
"uid": "eval-task-reminder",
"channel": "main",
"prompt": "Remind me in 60 seconds to drink water.",
"expect": "direct",
"end_state": "A notify task exists and fires once with an in-app notification.",
"tools": ("create_task", "list_tasks"),
},
{
"uid": "eval-task-recurring",
"channel": "main",
"prompt": "Every morning at 8 post a good-morning message to the general feed.",
"expect": "direct",
"end_state": "A cron task exists with max_runs and expiry bounds set.",
"tools": ("create_task", "get_task"),
},
{
"uid": "eval-telegram-quick",
"channel": "telegram",
"prompt": "What can you help me with?",
"expect": "direct",
"end_state": "One Telegram message answers; placeholder edits precede it.",
"tools": (),
},
{
"uid": "eval-telegram-quota",
"channel": "telegram",
"prompt": "Have I used much AI quota today?",
"expect": "direct",
"end_state": "One Telegram message states the quota percentage only.",
"tools": ("usage_quota",),
},
{
"uid": "eval-telegram-photo",
"channel": "telegram",
"prompt": "[photo of a cat] What is in this picture?",
"expect": "direct",
"end_state": "One Telegram message describes the image; no base64 persists.",
"tools": (),
},
{
"uid": "eval-research-web",
"channel": "main",
"prompt": "Compare the three most discussed Python web frameworks this week and summarize the tradeoffs.",
"expect": "research",
"end_state": "Reply holds one comparison table with source links; user could chat meanwhile.",
"tools": ("agent_start", "agent_status", "agent_result", "rsearch"),
},
{
"uid": "eval-research-platform",
"channel": "main",
"prompt": "What do people outside this site say about HTMX versus Alpine.js?",
"expect": "research",
"end_state": "Reply summarizes outside discussion with per-platform reach notes.",
"tools": ("agent_start", "agent_result", "social_search"),
},
{
"uid": "eval-files-build",
"channel": "main",
"prompt": "In my project demo-site, add a contact page with a form and wire it into the nav.",
"expect": "files",
"end_state": "Contact page exists in the project, nav links it, no other file touched.",
"tools": ("agent_start", "agent_result", "project_write_file"),
},
{
"uid": "eval-files-edit",
"channel": "main",
"prompt": "In my project demo-site, rename the footer copyright holder across every page.",
"expect": "files",
"end_state": "Every page shows the new holder; nothing else changed.",
"tools": ("agent_start", "agent_result", "project_replace_lines"),
},
{
"uid": "eval-planning-report",
"channel": "main",
"prompt": "Audit who changed admin settings in the last 7 days and report it.",
"expect": "planning-report",
"end_state": "Reply lists the changes with actor and time, grounded in docs and audit.",
"tools": ("agent_start", "agent_result", "audit_log", "search_docs"),
},
{
"uid": "eval-email-triage",
"channel": "main",
"prompt": "Triage my unread inbox mail from this week into urgent and bulk.",
"expect": "email-triage",
"end_state": "A disposition list exists; nothing sent, nothing deleted.",
"tools": ("agent_start", "agent_result", "email_search", "email_mark"),
},
{
"uid": "eval-containers-status",
"channel": "main",
"prompt": "Check every container instance on my projects and report which ones are unhealthy.",
"expect": "containers",
"end_state": "Reply lists each instance with health verdict and log evidence.",
"tools": ("agent_start", "agent_result", "container_list_instances"),
},
{
"uid": "eval-long-mutation",
"channel": "main",
"prompt": "Publish my draft posts about gardening that are older than a week.",
"expect": "long-mutation",
"end_state": "Exactly the matching drafts are published; the rest untouched.",
"tools": ("agent_start", "agent_result"),
},
{
"uid": "eval-needs-user",
"channel": "main",
"prompt": "Research newsletter platforms and recommend one, asking me about budget first.",
"expect": "research",
"end_state": "Run pauses as needs_user, orchestrator asks, answer resumes it to done.",
"tools": ("agent_start", "agent_status", "agent_result", "ui_prompt"),
},
{
"uid": "eval-cancel",
"channel": "main",
"prompt": "Start a deep comparison of static site generators, then cancel it right away.",
"expect": "research",
"end_state": "Run ends cancelled; ledger holds only the spend before cancel.",
"tools": ("agent_start", "agent_cancel", "agent_status"),
},
)
+253
View File
@@ -0,0 +1,253 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
from typing import Any, NamedTuple
class Category(NamedTuple):
key: str
label: str
fragment: str
extras: tuple[str, ...]
time_budget_seconds: int
iteration_budget: int
token_budget: int
check_interval_seconds: int
grace_seconds: int
max_nudges: int
max_retries: int
CATEGORIES: dict[str, Category] = {
"research": Category(
key="research",
label="Web research",
fragment=(
"You are a research subagent. Explore broadly first with short queries, "
"then narrow down. Prefer primary sources. Return findings condensed to "
"what the output contract asks for, with source URLs inline."
),
extras=("rsearch", "rsearch_answer", "fetch_url", "http_request", "social_search"),
time_budget_seconds=900,
iteration_budget=25,
token_budget=200000,
check_interval_seconds=5,
grace_seconds=90,
max_nudges=2,
max_retries=1,
),
"files": Category(
key="files",
label="Project files",
fragment=(
"You are a project-files subagent. Read before overwriting, prefer the "
"surgical line tools over full rewrites, and emit one file write per turn. "
"Return the list of paths changed plus a short summary."
),
extras=(
"project_read_file",
"project_read_lines",
"project_replace_lines",
"project_insert_lines",
"project_delete_lines",
"project_append_file",
"project_write_file",
),
time_budget_seconds=1200,
iteration_budget=40,
token_budget=300000,
check_interval_seconds=5,
grace_seconds=120,
max_nudges=2,
max_retries=1,
),
"planning-report": Category(
key="planning-report",
label="Planning report",
fragment=(
"You are a planning subagent. Ground every platform claim in search_docs "
"results from this run and in site_analytics aggregates; never page list "
"endpoints to count. Return the report in the requested output format."
),
extras=("search_docs", "site_analytics", "audit_log"),
time_budget_seconds=600,
iteration_budget=20,
token_budget=150000,
check_interval_seconds=5,
grace_seconds=60,
max_nudges=1,
max_retries=1,
),
"email-triage": Category(
key="email-triage",
label="Email triage",
fragment=(
"You are an email-triage subagent. Read and organise only; never send "
"mail and never delete without an explicit instruction in the task. "
"Return a per-message disposition list."
),
extras=(
"email_list_messages",
"email_search",
"email_read_message",
"email_mark",
"email_move_message",
),
time_budget_seconds=600,
iteration_budget=25,
token_budget=150000,
check_interval_seconds=5,
grace_seconds=90,
max_nudges=1,
max_retries=1,
),
"containers": Category(
key="containers",
label="Container operations",
fragment=(
"You are a container-operations subagent. Inspect before acting, confirm "
"destructive commands through the needs_user pause, and never expose "
"backend detail. Return the commands run plus their outcomes."
),
extras=("container_list_instances", "container_logs", "container_exec"),
time_budget_seconds=1200,
iteration_budget=40,
token_budget=200000,
check_interval_seconds=10,
grace_seconds=180,
max_nudges=2,
max_retries=1,
),
"long-mutation": Category(
key="long-mutation",
label="Long multi-step change",
fragment=(
"You are a general long-task subagent. Plan first, verify after every "
"mutation, and stop at the first confirmation-gated action to ask via "
"the needs_user pause. Return what changed, before and after."
),
extras=(),
time_budget_seconds=900,
iteration_budget=30,
token_budget=200000,
check_interval_seconds=5,
grace_seconds=90,
max_nudges=2,
max_retries=1,
),
}
EFFORT_SCALE: dict[str, float] = {"quick": 0.5, "standard": 1.0, "deep": 2.0}
MAX_ERROR_STREAK = 3
NEEDS_USER_TIMEOUT_SECONDS = 1800
CHECK_BACKOFF_FACTOR = 1.5
CHECK_INTERVAL_MAX_SECONDS = 60
TERMINAL_STATUSES = frozenset({"done", "failed", "cancelled", "interrupted"})
def enabled() -> bool:
from devplacepy.database import get_setting
from ..config import FIELD_AGENTS_ENABLED
try:
raw = get_setting(FIELD_AGENTS_ENABLED, "")
except Exception:
return False
if raw is None or str(raw).strip() == "":
return False
if isinstance(raw, bool):
return raw
if isinstance(raw, (int, float)):
return raw != 0
return str(raw).strip().lower() in ("1", "true", "yes", "on")
ORCHESTRATOR_ONLY_TOOLS = frozenset(
{
"agent_start",
"agent_status",
"agent_cancel",
"agent_result",
"agent_list",
"ui_prompt",
"ui_cancel",
"ui_notify",
"interactions_get",
"interactions_set",
"get_page_context",
"run_js",
"highlight_element",
"clear_highlights",
"show_toast",
"scroll_to_element",
"navigate_to",
"reload_page",
"discover_elements",
"read_element",
"click_element",
"fill_field",
"set_control",
"submit_form",
"wait_for",
"press_key",
"run_sequence",
"open_terminal",
"avatar_show",
"avatar_hide",
"avatar_speak",
"avatar_list_animations",
"avatar_play_animation",
"avatar_random_animation",
"avatar_move_to",
"avatar_gesture_at",
"avatar_get_viewport",
"avatar_stop",
"avatar_list_characters",
"avatar_switch_character",
}
)
def next_check_in(checks_done: int, base_seconds: int) -> int:
grown = int(base_seconds * (CHECK_BACKOFF_FACTOR**max(0, checks_done)))
return min(grown, CHECK_INTERVAL_MAX_SECONDS)
def decide(snapshot: dict[str, Any], category_key: str) -> tuple[str, str]:
category = CATEGORIES[category_key]
scale = EFFORT_SCALE.get(str(snapshot.get("effort") or "standard"), 1.0)
if str(snapshot.get("status")) in TERMINAL_STATUSES:
return ("settle", "already terminal")
if not snapshot.get("quota_ok", True):
return ("cancel", "quota spent")
if (
int(snapshot.get("age_seconds", 0))
> category.time_budget_seconds * scale
or int(snapshot.get("iterations", 0)) > category.iteration_budget * scale
or int(snapshot.get("tokens", 0)) > category.token_budget * scale
):
return ("cancel", "budget exceeded")
if int(snapshot.get("error_streak", 0)) >= MAX_ERROR_STREAK:
return ("cancel", "error streak")
if snapshot.get("failed"):
if int(snapshot.get("retries_used", 0)) < category.max_retries:
return ("retry_else", "run failed with retries left")
return ("cancel", "run failed without retries left")
if str(snapshot.get("status")) == "needs_user":
if snapshot.get("answered"):
return ("continue", "answer arrived")
if int(snapshot.get("age_seconds", 0)) > NEEDS_USER_TIMEOUT_SECONDS:
return ("cancel", "needs_user timed out")
return ("wait", "awaiting user")
if snapshot.get("progress"):
return ("continue", "progress observed")
if int(snapshot.get("idle_seconds", 0)) <= category.grace_seconds:
return ("wait", "within grace")
if int(snapshot.get("retries_used", 0)) < category.max_retries:
return ("retry_else", "stalled with retries left")
if int(snapshot.get("nudges_used", 0)) < category.max_nudges:
return ("nudge", "stalled with nudges left")
return ("cancel", "stalled without nudges or retries left")
+201
View File
@@ -0,0 +1,201 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
import json
import logging
from typing import Any
from ..agentic import AgentState, react_loop
from ..chunks import ChunkStore
from ..cost import CostTracker
from ..tasks.context import task_run_scope
from .policy import CATEGORIES, EFFORT_SCALE
logger = logging.getLogger("devii.agents.runner")
SUBAGENT_BASE_PROMPT = (
"You are a Devii subagent running in the background. The orchestrator owns "
"the user conversation; you never address the user directly and you have no "
"browser, no widgets, and no avatar. Investigate with read actions before "
"changing anything. When you need a decision, an answer, or a confirmation "
"from the user, call ask_user with the exact question and then stop: end "
"your turn with a short note of what you await and call no further tools "
"until the answer arrives as the ask_user result. Confirmation-gated "
"actions always go through ask_user first. Work only inside the task "
"boundaries below and shape your final message exactly like the output "
"format demands."
)
def _ask_question(call: dict[str, Any]) -> str:
raw = call.get("function", {}).get("arguments") or "{}"
try:
arguments = json.loads(raw) if isinstance(raw, str) else raw
except (ValueError, TypeError):
return ""
if not isinstance(arguments, dict):
return ""
return str(arguments.get("question") or "").strip()
class AgentRunner:
def __init__(
self,
session: Any,
uid: str,
label: str,
category_key: str,
effort: str,
task: str,
output_format: str,
tools: list[dict[str, Any]],
task_scope: bool,
behavior_text: str = "",
) -> None:
self._session = session
self.uid = uid
self.label = label
self.category = CATEGORIES[category_key]
self.effort = effort
self._task_scope = task_scope
self._tools = tools
self.state = AgentState()
self.cost = CostTracker(pricing=session.cost.pricing)
self.chunks = ChunkStore()
self.messages: list[dict[str, Any]] = [
{"role": "system", "content": self._system_prompt(task, output_format, behavior_text)},
{"role": "user", "content": f"Task: {task}\n\nOutput format: {output_format}"},
]
self.answered_asks: set[str] = set()
self.tool_calls = 0
self.error_streak = 0
self.progress_note = "started"
self._on_progress: Any = None
self._on_trace_emit: Any = None
def _system_prompt(self, task: str, output_format: str, behavior_text: str) -> str:
parts = [SUBAGENT_BASE_PROMPT, self.category.fragment]
if behavior_text.strip():
parts.append(f"# OWNER BEHAVIOR RULES\n{behavior_text.strip()}")
parts.append(f"# CONTRACT\nTask: {task}\nOutput format: {output_format}")
return "\n\n".join(parts)
def on_progress(self, callback: Any) -> None:
self._on_progress = callback
def on_trace_emit(self, callback: Any) -> None:
self._on_trace_emit = callback
def counts(self) -> tuple[int, int, float]:
tokens = (
self.cost.prompt_tokens
+ self.cost.completion_tokens
+ self.cost.cache_hit_tokens
+ self.cost.cache_miss_tokens
)
return self.state.iteration, tokens, self.cost.cost_usd()["total"]
def usage(self) -> dict[str, int]:
return {
"prompt_tokens": self.cost.prompt_tokens,
"completion_tokens": self.cost.completion_tokens,
"cache_hit_tokens": self.cost.cache_hit_tokens,
"cache_miss_tokens": self.cost.cache_miss_tokens,
}
def _trace(self, event: str, name: str = "", detail: str = "") -> None:
if event == "call":
self.tool_calls += 1
elif event == "err":
self.error_streak += 1
elif event == "ok":
self.error_streak = 0
if event in ("call", "ok", "err"):
self.progress_note = f"{event} {name} {detail}".strip()[:300]
if self._on_progress is not None:
self._on_progress(event, name, detail)
if self._on_trace_emit is not None:
self._on_trace_emit(self.uid, self.label, event, name, detail)
def _quota_spent(self) -> bool:
limit = float(self._session.settings.daily_limit_usd or 0.0)
if limit <= 0:
return False
spent = self._session._ledger.spent_24h(
self._session.owner_kind, self._session.owner_id
)
return spent >= limit
def _pending_ask(self) -> tuple[str, str] | None:
asked: dict[str, str] = {}
for message in self.messages:
for call in message.get("tool_calls") or []:
if call.get("function", {}).get("name") == "ask_user":
call_id = str(call.get("id") or "")
if call_id and call_id not in self.answered_asks:
asked[call_id] = _ask_question(call)
if not asked:
return None
call_id = next(reversed(asked))
return call_id, asked[call_id]
def apply_answer(self, answer: str) -> None:
pending = self._pending_ask()
if pending is None:
return
call_id, _ = pending
for message in self.messages:
if (
message.get("role") == "tool"
and str(message.get("tool_call_id") or "") == call_id
):
message["content"] = json.dumps(
{"status": "answered", "answer": answer}, ensure_ascii=False
)
self.answered_asks.add(call_id)
self.messages.append(
{"role": "user", "content": f"The user answered: {answer}"}
)
def nudge(self, text: str) -> None:
self.messages.append({"role": "user", "content": text})
async def run_once(self) -> tuple[str, str]:
if self._quota_spent():
return ("error", "quota spent")
scale = EFFORT_SCALE.get(self.effort, 1.0)
budget = int(self.category.iteration_budget * scale)
if self.state.iteration >= budget:
return ("error", "iteration budget spent")
if self._task_scope:
with task_run_scope():
return await self._loop(budget)
return await self._loop(budget)
async def _loop(self, budget: int) -> tuple[str, str]:
session = self._session
try:
final = await react_loop(
llm=session._llm,
dispatcher=session.dispatcher,
messages=self.messages,
tools=self._tools,
state=self.state,
settings=session.settings,
max_iterations=budget,
plan_required=session.settings.plan_required,
verify_required=session.settings.verify_required,
on_trace=self._trace,
cost_tracker=self.cost,
chunk_store=self.chunks,
)
except Exception as exc: # noqa: BLE001 - recorded on the run, decided by policy
logger.exception("Agent run %s crashed", self.uid)
return ("error", str(exc)[:1000])
pending = self._pending_ask()
if pending is not None:
return ("needs_user", pending[1])
if final.startswith(("[model error]", "[stopped]")):
return ("error", final[:1000])
return ("done", final)
+223
View File
@@ -0,0 +1,223 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
import logging
from datetime import datetime, timezone
from typing import Any
import sqlalchemy
from .policy import TERMINAL_STATUSES
logger = logging.getLogger("devii.agents.store")
TABLE = "devii_agent_runs"
INDEXED_COLUMNS = (
["owner_kind", "owner_id"],
["uid"],
["status"],
["status", "check_at"],
)
AGENT_COLUMNS = (
("uid", ""),
("owner_kind", ""),
("owner_id", ""),
("channel", ""),
("category", ""),
("label", ""),
("task", ""),
("output_format", ""),
("tools_extra", ""),
("effort", ""),
("task_scope", 0),
("status", ""),
("progress", ""),
("result", ""),
("error", ""),
("checks", 0),
("nudges_used", 0),
("retries_used", 0),
("error_streak", 0),
("iterations", 0),
("tokens", 0),
("cost_usd", 0.0),
("needs_question", ""),
("pending_ask_id", ""),
("check_at", ""),
("last_progress_at", ""),
("created_at", ""),
("updated_at", ""),
)
DUE_SQL = (
"SELECT * FROM devii_agent_runs WHERE status IN ('queued', 'running', 'needs_user') "
"AND check_at IS NOT NULL AND check_at <= :now ORDER BY check_at LIMIT :limit"
)
CLAIM_SQL = (
"UPDATE devii_agent_runs SET status = 'checking', updated_at = :now WHERE uid = :uid "
"AND status IN ('queued', 'running', 'needs_user')"
)
COMPLETE_STATUSES = ("running", "checking")
ACTIVE_STATUSES = ("queued", "running", "needs_user", "checking")
def due_rows(db: Any, now_iso: str, limit: int) -> list[dict[str, Any]]:
if TABLE not in db.tables:
return []
return list(db.query(DUE_SQL, now=now_iso, limit=limit))
def claim(db: Any, uid: str, now_iso: str) -> bool:
statement = sqlalchemy.text(CLAIM_SQL)
with db:
result = db.executable.execute(statement, {"uid": uid, "now": now_iso})
return result.rowcount == 1
def prune_terminal(db: Any, cutoff_iso: str) -> int:
if TABLE not in db.tables:
return 0
names = ", ".join(f"'{name}'" for name in sorted(TERMINAL_STATUSES))
statement = sqlalchemy.text(
f"DELETE FROM devii_agent_runs WHERE status IN ({names}) "
"AND updated_at IS NOT NULL AND updated_at < :cutoff"
)
with db:
result = db.executable.execute(statement, {"cutoff": cutoff_iso})
return int(result.rowcount or 0)
def _seconds_between(earlier_iso: str, later: datetime) -> int:
try:
earlier = datetime.fromisoformat(str(earlier_iso))
except ValueError:
return 0
if earlier.tzinfo is None:
earlier = earlier.replace(tzinfo=timezone.utc)
return max(0, int((later - earlier).total_seconds()))
def snapshot_for(row: dict[str, Any], reference: datetime) -> dict[str, Any]:
return {
"status": row.get("status"),
"age_seconds": _seconds_between(str(row.get("created_at") or ""), reference),
"idle_seconds": _seconds_between(
str(row.get("last_progress_at") or row.get("created_at") or ""), reference
),
"iterations": int(row.get("iterations") or 0),
"tokens": int(row.get("tokens") or 0),
"checks": int(row.get("checks") or 0),
"nudges_used": int(row.get("nudges_used") or 0),
"retries_used": int(row.get("retries_used") or 0),
"error_streak": int(row.get("error_streak") or 0),
"quota_ok": True,
"failed": bool(row.get("error")),
"answered": False,
"progress": False,
"effort": str(row.get("effort") or "standard"),
}
class AgentStore:
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_indexes()
def _ensure_indexes(self) -> None:
if TABLE not in self._db.tables:
return
self._ensure_schema()
for columns in INDEXED_COLUMNS:
try:
self._table.create_index(columns)
except sqlalchemy.exc.OperationalError as exc:
if "already exists" not in str(exc).lower():
raise
logger.debug("Index on %s was created by another process", columns)
def _ensure_schema(self) -> None:
table = self._db[TABLE]
for column, example in AGENT_COLUMNS:
if table.has_column(column):
continue
try:
table.create_column_by_example(column, example)
except sqlalchemy.exc.OperationalError as exc:
if "duplicate column" not in str(exc).lower():
raise
logger.debug("Column %s was added by another process", column)
table._reflect_table()
@property
def db(self) -> Any:
return self._db
@property
def _table(self) -> Any:
return self._db[TABLE]
@property
def _scope(self) -> dict[str, str]:
return {"owner_kind": self._owner_kind, "owner_id": self._owner_id}
def create(self, record: dict[str, Any]) -> None:
self._ensure_schema()
row = {**record, **self._scope}
self._table.insert(row)
logger.info(
"Agent run created uid=%s owner=%s/%s category=%s",
record.get("uid"),
self._owner_kind,
self._owner_id,
record.get("category"),
)
def get(self, uid: str) -> dict[str, Any] | None:
if TABLE not in self._db.tables:
return None
return self._table.find_one(uid=uid, **self._scope)
def list(self, status: str | None = None) -> list[dict[str, Any]]:
if TABLE not in self._db.tables:
return []
criteria: dict[str, Any] = dict(self._scope)
if status:
criteria["status"] = status
rows = list(self._table.find(**criteria))
rows.sort(key=lambda row: str(row.get("created_at") or ""))
return rows
def update(self, uid: str, changes: dict[str, Any]) -> None:
changes = {**changes, "uid": uid, **self._scope}
self._table.update(changes, ["uid", "owner_kind", "owner_id"])
logger.debug("Agent run updated uid=%s changes=%s", uid, list(changes))
def complete(self, uid: str, changes: dict[str, Any]) -> bool:
statement = sqlalchemy.text(
"UPDATE devii_agent_runs SET status = :status, result = :result, "
"error = :error, iterations = :iterations, tokens = :tokens, "
"cost_usd = :cost_usd, updated_at = :now "
"WHERE uid = :uid AND status IN ('running', 'checking')"
)
params = {
"status": changes.get("status"),
"result": changes.get("result"),
"error": changes.get("error"),
"iterations": int(changes.get("iterations") or 0),
"tokens": int(changes.get("tokens") or 0),
"cost_usd": float(changes.get("cost_usd") or 0.0),
"now": changes.get("updated_at"),
"uid": uid,
}
with self._db:
result = self._db.executable.execute(statement, params)
return result.rowcount == 1
def count_active(self) -> int:
if TABLE not in self._db.tables:
return 0
rows = self._table.find(**self._scope)
return sum(1 for row in rows if row.get("status") in ACTIVE_STATUSES)
@@ -0,0 +1,664 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
import asyncio
import json
import logging
from datetime import datetime, timedelta, timezone
from typing import Any, Callable, Optional
from .policy import CATEGORIES, TERMINAL_STATUSES, decide, next_check_in
from .runner import AgentRunner
from .store import AgentStore, claim, due_rows
from .tools import build_subagent_tools
logger = logging.getLogger("devii.agents.supervisor")
DEFAULT_TICK_SECONDS = 1.0
DEFAULT_MAX_CONCURRENT = 4
DEFAULT_MAX_PER_OWNER = 2
DUE_BATCH_LIMIT = 200
RETRY_NOTE_CHARS = 500
NUDGE_TEXT = (
"Progress check: no new tool result since the last check. Continue the task "
"now with your next tool call. If you are blocked on a decision, an answer, "
"or a confirmation, call ask_user with the exact question instead of waiting."
)
def _now() -> datetime:
return datetime.now(timezone.utc)
def _iso(moment: datetime) -> str:
return moment.isoformat(timespec="microseconds")
def _audit(uid: str, event: str, owner_id: str, summary: str, metadata: dict) -> None:
from devplacepy.services.audit import record as audit
audit.record_system(
event,
actor_kind="user",
actor_uid=owner_id,
actor_role="user",
origin="devii",
via_agent=1,
result="success",
target_type="agent_run",
target_uid=uid,
summary=summary,
metadata=metadata,
)
class AgentSupervisor:
def __init__(
self,
db: Any,
resolve: Callable[[dict[str, Any]], Any],
tick_seconds: float = DEFAULT_TICK_SECONDS,
max_concurrent: int = DEFAULT_MAX_CONCURRENT,
max_per_owner: int = DEFAULT_MAX_PER_OWNER,
) -> None:
self._db = db
self._resolve = resolve
self._tick_seconds = tick_seconds
self._max_concurrent = max_concurrent
self._max_per_owner = max_per_owner
self._loop_task: asyncio.Task[None] | None = None
self._running: dict[str, dict[str, Any]] = {}
self._runners: dict[str, AgentRunner] = {}
self._last_progress: dict[str, str] = {}
@property
def running(self) -> int:
return len(self._running)
def configure(self, max_concurrent: int, max_per_owner: int) -> None:
self._max_concurrent = max_concurrent
self._max_per_owner = max_per_owner
def counts(self) -> dict[str, int]:
from .store import TABLE
out: dict[str, int] = {}
if TABLE not in self._db.tables:
return out
for row in self._db[TABLE].find():
status = str(row.get("status") or "")
out[status] = out.get(status, 0) + 1
return out
def start(self) -> None:
self._reap_stuck()
if self._loop_task is None:
self._loop_task = asyncio.create_task(self._loop())
logger.info("Agent supervisor started")
async def stop(self) -> None:
if self._loop_task is None:
return
self._loop_task.cancel()
try:
await self._loop_task
except asyncio.CancelledError:
pass
self._loop_task = None
for entry in list(self._running.values()):
entry["task"].cancel()
for uid, runner in list(self._runners.items()):
try:
runner._session._agents.pop(uid, None)
except Exception: # noqa: BLE001 - mirror cleanup is best-effort
pass
self._running.clear()
self._runners.clear()
self._last_progress.clear()
logger.info("Agent supervisor stopped")
def _reap_stuck(self) -> None:
from .store import TABLE
if TABLE not in self._db.tables:
return
now = _iso(_now())
reaped = 0
for row in list(self._db[TABLE].find()):
if str(row.get("status")) not in ("running", "checking"):
continue
store = AgentStore(
self._db, str(row.get("owner_kind") or ""), str(row.get("owner_id") or "")
)
store.update(
str(row["uid"]),
{"status": "interrupted", "error": "supervisor restarted", "updated_at": now},
)
self._notify(str(row.get("owner_id") or ""), str(row.get("label") or row["uid"]))
reaped += 1
if reaped:
logger.info("Reaped %d stuck agent run(s)", reaped)
def _notify(self, owner_id: str, label: str) -> None:
if not owner_id:
return
try:
from devplacepy.utils import create_notification
create_notification(
owner_id,
"reminder",
f"Subagent '{label}' was interrupted by a restart.".strip()[:500],
owner_id,
target_url="/devii",
)
except Exception: # noqa: BLE001 - notification must never break supervision
logger.exception("Failed to notify %s about an interrupted agent run", owner_id)
async def _deliver_terminal(
self, session: Any, row: dict[str, Any], kind: str, text: str
) -> None:
frame = {
"type": "agent",
"kind": kind,
"uid": str(row["uid"]),
"label": str(row.get("label") or row["uid"][:8]),
"payload": text[:2000],
}
delivered = await session.emit_agent(frame)
if delivered or str(row.get("channel") or "") != "telegram":
return
await self._send_telegram(
str(row.get("owner_id") or ""), frame["label"], kind, text
)
async def _send_telegram(
self, owner_id: str, label: str, kind: str, text: str
) -> None:
if not owner_id:
return
try:
from devplacepy.services.manager import service_manager
from devplacepy.services.telegram import store as telegram_store
link = telegram_store.link_for_user(owner_id)
service = service_manager.get_service("telegram")
if (
not link
or service is None
or not service.is_enabled()
or not service_manager.owns_lock()
or not service.worker_alive()
):
return
head = {
"done": "finished",
"needs_user": "needs you",
"cancelled": "cancelled",
"failed": "failed",
"interrupted": "interrupted",
}.get(kind, kind)
body = text.strip()[:3000] or "(no output)"
await service.send_markdown(
int(link["chat_id"]), f"Subagent '{label}' {head}:\n{body}"
)
except Exception: # noqa: BLE001 - late delivery must never break supervision
logger.exception("Late agent delivery to Telegram failed for %s", owner_id)
async def _loop(self) -> None:
while True:
try:
await self._tick()
except Exception: # noqa: BLE001 - the supervisor must never die
logger.exception("Agent supervisor tick failed")
await asyncio.sleep(self._tick_seconds)
async def _tick(self) -> None:
now = _now()
for row in due_rows(self._db, _iso(now), DUE_BATCH_LIMIT):
if len(self._running) >= self._max_concurrent:
continue
if self._owner_running(str(row.get("owner_id") or "")) >= self._max_per_owner:
continue
if not claim(self._db, str(row["uid"]), _iso(now)):
continue
await self._check(row, now)
def _owner_running(self, owner_id: str) -> int:
return sum(
1 for entry in self._running.values() if entry["owner_id"] == owner_id
)
def _store_for(self, row: dict[str, Any]) -> AgentStore:
return AgentStore(
self._db, str(row.get("owner_kind") or ""), str(row.get("owner_id") or "")
)
async def _check(self, row: dict[str, Any], now: datetime) -> None:
uid = str(row["uid"])
original = str(row.get("status") or "")
store = self._store_for(row)
session = self._resolve(row)
if session is None:
store.update(
uid,
{"status": "interrupted", "error": "owner gone", "updated_at": _iso(now)},
)
return
if original == "queued":
if session._quota_snapshot()["limit_reached"]:
await self.cancel(uid, "quota spent")
return
self._start(uid, session, row, now)
return
from .store import snapshot_for
snapshot = snapshot_for(row, now)
snapshot["status"] = original
snapshot["quota_ok"] = not session._quota_snapshot()["limit_reached"]
snapshot["progress"] = self._saw_progress(uid, str(row.get("progress") or ""))
category_key = str(row.get("category") or "long-mutation")
if category_key not in CATEGORIES:
category_key = "long-mutation"
decision, reason = decide(snapshot, category_key)
logger.info("Agent run %s check: %s (%s)", uid, decision, reason)
if decision == "settle":
self._restore(store, row, original, now)
elif decision == "cancel":
await self.cancel(uid, reason)
elif decision == "retry_else":
self._retry(uid, session, row, reason, now)
elif decision == "nudge":
self._nudge(uid, session, row, now)
else:
self._restore(store, row, original, now, count_check=True)
def _saw_progress(self, uid: str, note: str) -> bool:
previous = self._last_progress.get(uid)
self._last_progress[uid] = note
return previous is not None and note != previous and bool(note)
def _restore(
self,
store: AgentStore,
row: dict[str, Any],
status: str,
now: datetime,
count_check: bool = False,
) -> None:
uid = str(row["uid"])
checks = int(row.get("checks") or 0) + (1 if count_check else 0)
category = CATEGORIES.get(str(row.get("category") or ""), CATEGORIES["long-mutation"])
wait = next_check_in(checks, category.check_interval_seconds)
changes: dict[str, Any] = {
"status": status,
"checks": checks,
"check_at": _iso(now + timedelta(seconds=wait)),
"updated_at": _iso(now),
}
runner = self._runners.get(uid)
if runner is not None:
iterations, tokens, _ = runner.counts()
changes["iterations"] = iterations
changes["tokens"] = tokens
changes["error_streak"] = runner.error_streak
store.update(uid, changes)
def _start(
self, uid: str, session: Any, row: dict[str, Any], now: datetime
) -> None:
from ..tool_prefs import filter_disabled
category_key = str(row.get("category") or "long-mutation")
if category_key not in CATEGORIES:
category_key = "long-mutation"
try:
extra = tuple(json.loads(str(row.get("tools_extra") or "[]")) or ())
except (ValueError, TypeError):
extra = ()
parent = filter_disabled(
[
s
for s in session._builtin_tools()
if s.get("function", {}).get("name") != "ask_user"
]
)
try:
virtual = session._virtual_tool_store.tool_schemas()
except Exception: # noqa: BLE001 - virtual tools are best-effort here
virtual = []
tools = build_subagent_tools(
parent + virtual,
category_key,
extra,
session.client.authenticated,
session.is_admin,
session.is_primary_admin,
)
try:
behavior = session._behavior_store.text()
except Exception: # noqa: BLE001 - behavior is best-effort here
behavior = ""
runner = AgentRunner(
session,
uid,
str(row.get("label") or uid[:8]),
category_key,
str(row.get("effort") or "standard"),
str(row.get("task") or ""),
str(row.get("output_format") or ""),
tools,
bool(row.get("task_scope")),
behavior_text=behavior,
)
runner.on_progress(lambda e, n, d: self._progress(uid, runner, e, n, d))
runner.on_trace_emit(session.trace_agent)
self._runners[uid] = runner
task = asyncio.create_task(self._drive(uid, session))
self._running[uid] = {
"task": task,
"owner_id": str(row.get("owner_id") or ""),
"ledgered": {"prompt_tokens": 0, "completion_tokens": 0, "cache_hit_tokens": 0, "cache_miss_tokens": 0, "cost": 0.0},
}
session._agents[uid] = task
self._store_for(row).update(
uid,
{
"status": "running",
"checks": int(row.get("checks") or 0) + 1,
"check_at": _iso(now + timedelta(seconds=CATEGORIES[category_key].check_interval_seconds)),
"last_progress_at": _iso(now),
"updated_at": _iso(now),
},
)
logger.info("Agent run %s started (%s)", uid, category_key)
def _progress(
self, uid: str, runner: AgentRunner, event: str, name: str, detail: str
) -> None:
if event not in ("call", "ok", "err"):
return
entry = self._running.get(uid)
if entry is None:
return
store = AgentStore(self._db, "user", entry["owner_id"])
if store.get(uid) is None:
return
iterations, tokens, _ = runner.counts()
store.update(
uid,
{
"progress": runner.progress_note,
"iterations": iterations,
"tokens": tokens,
"error_streak": runner.error_streak,
"last_progress_at": _iso(_now()),
},
)
def _nudge(self, uid: str, session: Any, row: dict[str, Any], now: datetime) -> None:
runner = self._runners.get(uid)
if runner is None or uid in self._running:
self._restore(self._store_for(row), row, str(row.get("status") or "running"), now)
return
runner.nudge(NUDGE_TEXT)
task = asyncio.create_task(self._drive(uid, session))
self._running[uid] = {
"task": task,
"owner_id": str(row.get("owner_id") or ""),
"ledgered": self._ledgered_base(runner),
}
session._agents[uid] = task
self._store_for(row).update(
uid,
{
"status": "running",
"nudges_used": int(row.get("nudges_used") or 0) + 1,
"checks": int(row.get("checks") or 0) + 1,
"check_at": _iso(now + timedelta(seconds=30)),
"updated_at": _iso(now),
},
)
def _retry(
self, uid: str, session: Any, row: dict[str, Any], reason: str, now: datetime
) -> None:
old = self._runners.get(uid)
if old is not None:
self._ledger_delta(uid, session, old)
previous = self._running.pop(uid, None)
if previous is not None:
previous["task"].cancel()
session._agents.pop(uid, None)
task_text = str(row.get("task") or "")
note = str(row.get("error") or row.get("progress") or reason)[:RETRY_NOTE_CHARS]
self._runners.pop(uid, None)
fresh = dict(row)
fresh["task"] = (
f"{task_text}\n\nPrevious attempt {reason} ({note}). "
"Simplify: produce the smallest complete version of the output format."
)
self._store_for(row).update(
uid,
{
"status": "queued",
"task": fresh["task"],
"error": None,
"error_streak": 0,
"retries_used": int(row.get("retries_used") or 0) + 1,
"check_at": _iso(now),
"updated_at": _iso(now),
},
)
async def resume(self, uid: str, answer: str) -> bool:
runner = self._runners.get(uid)
if runner is None or uid in self._running:
return False
target = None
for row in self._all_rows():
if str(row.get("uid")) == uid:
target = row
break
if target is None or str(target.get("status")) != "needs_user":
return False
session = self._resolve(target)
if session is None:
return False
runner.apply_answer(answer)
task = asyncio.create_task(self._drive(uid, session))
self._running[uid] = {
"task": task,
"owner_id": str(target.get("owner_id") or ""),
"ledgered": self._ledgered_base(runner),
}
session._agents[uid] = task
self._store_for(target).update(
uid,
{
"status": "running",
"needs_question": None,
"pending_ask_id": None,
"check_at": _iso(_now() + timedelta(seconds=30)),
"updated_at": _iso(_now()),
},
)
return True
def _all_rows(self) -> list[dict[str, Any]]:
from .store import TABLE
if TABLE not in self._db.tables:
return []
return list(self._db[TABLE].find())
async def cancel(self, uid: str, reason: str) -> bool:
target = None
for row in self._all_rows():
if str(row.get("uid")) == uid:
target = row
break
if target is None or str(target.get("status")) in TERMINAL_STATUSES:
return False
store = self._store_for(target)
store.update(
uid, {"status": "cancelled", "error": reason[:500], "updated_at": _iso(_now())}
)
runner = self._runners.get(uid)
session = self._resolve(target)
if runner is not None and session is not None:
self._ledger_delta(uid, session, runner)
entry = self._running.pop(uid, None)
if entry is not None:
entry["task"].cancel()
self._runners.pop(uid, None)
if session is not None:
session._agents.pop(uid, None)
await self._deliver_terminal(session, target, "cancelled", reason)
_audit(uid, "devii.agent.cancel", str(target.get("owner_id") or ""), f"Agent run {uid} cancelled: {reason}", {"reason": reason[:200]})
self._last_progress.pop(uid, None)
return True
def _ledgered_base(self, runner: AgentRunner) -> dict[str, float]:
usage = runner.usage()
_, _, cost = runner.counts()
return {
"prompt_tokens": usage["prompt_tokens"],
"completion_tokens": usage["completion_tokens"],
"cache_hit_tokens": usage["cache_hit_tokens"],
"cache_miss_tokens": usage["cache_miss_tokens"],
"cost": cost,
}
def _ledger_delta(self, uid: str, session: Any, runner: AgentRunner) -> None:
entry = self._running.get(uid)
base = entry["ledgered"] if entry else self._ledgered_base(runner)
usage = runner.usage()
_, _, cost = runner.counts()
delta = {
"prompt_tokens": usage["prompt_tokens"] - int(base["prompt_tokens"]),
"completion_tokens": usage["completion_tokens"] - int(base["completion_tokens"]),
"cache_hit_tokens": usage["cache_hit_tokens"] - int(base["cache_hit_tokens"]),
"cache_miss_tokens": usage["cache_miss_tokens"] - int(base["cache_miss_tokens"]),
}
cost_delta = round(cost - float(base["cost"]), 8)
if entry is not None:
entry["ledgered"] = self._ledgered_base(runner)
if cost_delta <= 0 and all(v <= 0 for v in delta.values()):
return
session.record_agent_spend(uid, delta, cost_delta)
async def _drive(self, uid: str, session: Any) -> None:
runner = self._runners.get(uid)
if runner is None:
return
try:
try:
outcome, text = await runner.run_once()
except Exception as exc: # noqa: BLE001 - recorded, decided by policy
logger.exception("Agent run %s drive crashed", uid)
outcome, text = "error", str(exc)[:1000]
self._ledger_delta(uid, session, runner)
if outcome == "needs_user":
await self._park_needs_user(uid, session, runner, text)
elif outcome == "done":
await self._finish(uid, session, runner, "done", text, None)
else:
await self._fail(uid, session, runner, text)
finally:
self._running.pop(uid, None)
session._agents.pop(uid, None)
async def _park_needs_user(
self, uid: str, session: Any, runner: AgentRunner, question: str
) -> None:
pending = runner._pending_ask()
ask_id = pending[0] if pending else ""
target = None
for row in self._all_rows():
if str(row.get("uid")) == uid:
target = row
break
if target is None or str(target.get("status")) in TERMINAL_STATUSES:
return
iterations, tokens, cost = runner.counts()
self._store_for(target).update(
uid,
{
"status": "needs_user",
"needs_question": question[:2000],
"pending_ask_id": ask_id,
"iterations": iterations,
"tokens": tokens,
"cost_usd": cost,
"error": None,
"check_at": _iso(_now() + timedelta(seconds=30)),
"updated_at": _iso(_now()),
},
)
await self._deliver_terminal(session, target, "needs_user", question)
async def _finish(
self,
uid: str,
session: Any,
runner: AgentRunner,
status: str,
result: Optional[str],
error: Optional[str],
) -> None:
iterations, tokens, cost = runner.counts()
store = None
for row in self._all_rows():
if str(row.get("uid")) == uid:
store = self._store_for(row)
owner_id = str(row.get("owner_id") or "")
break
if store is None:
self._runners.pop(uid, None)
return
won = store.complete(
uid,
{
"status": status,
"result": result,
"error": error,
"iterations": iterations,
"tokens": tokens,
"cost_usd": cost,
"updated_at": _iso(_now()),
},
)
self._runners.pop(uid, None)
self._last_progress.pop(uid, None)
if not won:
return
await self._deliver_terminal(session, row, status, result or error or "")
_audit(uid, "devii.agent.done", owner_id, f"Agent run {uid} finished: {status}", {"status": status})
logger.info("Agent run %s finished: %s", uid, status)
async def _fail(self, uid: str, session: Any, runner: AgentRunner, error: str) -> None:
target = None
for row in self._all_rows():
if str(row.get("uid")) == uid:
target = row
break
if target is None or str(target.get("status")) in TERMINAL_STATUSES:
self._runners.pop(uid, None)
return
iterations, tokens, cost = runner.counts()
self._store_for(target).update(
uid,
{
"status": "running",
"error": error[:1000],
"error_streak": runner.error_streak,
"iterations": iterations,
"tokens": tokens,
"cost_usd": cost,
"check_at": _iso(_now()),
"updated_at": _iso(_now()),
},
)
+49
View File
@@ -0,0 +1,49 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
from typing import Any
from .policy import CATEGORIES, ORCHESTRATOR_ONLY_TOOLS
def build_subagent_tools(
parent_schemas: list[dict[str, Any]],
category_key: str,
tools_extra: tuple[str, ...],
authenticated: bool,
is_admin: bool,
is_primary_admin: bool,
) -> list[dict[str, Any]]:
from ..registry import CATALOG
from ..tool_prefs import disabled_tool_names
by_name = CATALOG.by_name()
disabled = disabled_tool_names()
kept: list[dict[str, Any]] = []
seen: set[str] = set()
for schema in parent_schemas:
name = str(schema.get("function", {}).get("name") or "")
if not name or name in ORCHESTRATOR_ONLY_TOOLS or name in seen:
continue
seen.add(name)
kept.append(schema)
wanted = list(CATEGORIES[category_key].extras) + list(tools_extra or ())
for name in wanted:
if name in seen or name in ORCHESTRATOR_ONLY_TOOLS or name in disabled:
continue
action = by_name.get(name)
if action is None:
continue
if action.requires_auth and not authenticated:
continue
if action.requires_admin and not is_admin:
continue
if action.requires_primary_admin and not is_primary_admin:
continue
seen.add(name)
kept.append(action.tool_schema())
asker = by_name.get("ask_user")
if asker is not None and "ask_user" not in disabled:
kept.append(asker.tool_schema())
return kept
+10 -4
View File
@@ -177,11 +177,17 @@ async def run(settings: Settings, prompt: Optional[str] = None) -> None:
)
from .tool_prefs import filter_disabled
tools = filter_disabled(
CATALOG.tool_schemas_for(
client.authenticated, is_admin=True, is_primary_admin=True
by_name = CATALOG.by_name()
tools = [
schema
for schema in filter_disabled(
CATALOG.tool_schemas_for(
client.authenticated, is_admin=True, is_primary_admin=True
)
)
)
if by_name.get(schema.get("function", {}).get("name"), None) is None
or by_name[schema["function"]["name"]].handler != "agent"
]
agentic.bind(
llm=llm,
dispatcher=dispatcher,
+1
View File
@@ -204,6 +204,7 @@ FIELD_TASK_DAILY_USD = "devii_task_daily_usd"
FIELD_TASK_MAX_FAILURES = "devii_task_max_failures"
FIELD_TASK_IDLE_DAYS = "devii_task_owner_idle_days"
FIELD_DISABLED_TOOLS = "devii_disabled_tools"
FIELD_AGENTS_ENABLED = "devii_agents_enabled"
DEFAULT_TASK_MAX_CONCURRENT = 4
DEFAULT_TASK_DAILY_USD = 0.5
+2
View File
@@ -9,6 +9,7 @@ from typing import Any, Callable
import httpx
from devplacepy import stealth
from devplacepy.services.openai_gateway.apps import APP_REFERENCE_DEVII
from .config import Settings
from .cost import record_cost, record_usage
from .errors import LLMError
@@ -67,6 +68,7 @@ class LLMClient:
headers={
"Authorization": f"Bearer {settings.ai_key}",
"Content-Type": "application/json",
"X-App-Reference": APP_REFERENCE_DEVII,
},
)
+4
View File
@@ -23,6 +23,7 @@ from .actions.workspace_actions import WORKSPACE_ACTIONS
from .interaction.actions import INTERACTION_ACTIONS
from .virtual_tools.actions import VIRTUAL_TOOL_ACTIONS
from .agentic.actions import AGENTIC_ACTIONS
from .agents.actions import AGENT_ACTIONS
from .tasks.actions import TASK_ACTIONS
GROUPS: dict[str, tuple[Action, ...]] = {
@@ -47,6 +48,7 @@ GROUPS: dict[str, tuple[Action, ...]] = {
"telegram": TELEGRAM_ACTIONS,
"interaction": INTERACTION_ACTIONS,
"virtual_tool": VIRTUAL_TOOL_ACTIONS,
"agents": AGENT_ACTIONS,
}
GROUP_LABELS: dict[str, str] = {
@@ -97,6 +99,7 @@ GROUP_LABELS: dict[str, str] = {
"telegram": "Telegram Bridge",
"interaction": "Interactive Widgets (UI prompts)",
"virtual_tool": "User-Defined Tools",
"agents": "Subagents (async)",
}
CATALOG = Catalog(
@@ -121,6 +124,7 @@ CATALOG = Catalog(
+ TELEGRAM_ACTIONS
+ INTERACTION_ACTIONS
+ VIRTUAL_TOOL_ACTIONS
+ AGENT_ACTIONS
)
+80 -3
View File
@@ -133,6 +133,16 @@ class DeviiService(BaseService):
"raw JavaScript execution; read-only tools (context, discover, read) are unaffected.",
group="Agent",
),
ConfigField(
config.FIELD_AGENTS_ENABLED,
"Enable async subagents",
type="bool",
default=False,
help="Let Devii clone itself into supervised background subagents (agent_* "
"tools) while the user keeps chatting. When off, the tools are hidden "
"and refused. Guests never get them.",
group="Agent",
),
ConfigField(
config.FIELD_INTERACTIONS_DEFAULT,
"Interactive widgets default",
@@ -364,6 +374,7 @@ class DeviiService(BaseService):
super().__init__(name="devii", interval_seconds=60)
self._hub = None
self._scheduler = None
self._agent_supervisor = None
def hub(self):
if self._hub is None:
@@ -472,14 +483,15 @@ class DeviiService(BaseService):
self._configure_scheduler()
idle = self._disable_idle_owner_tasks()
runs_pruned = self._prune_task_runs()
agents_pruned = self._prune_agent_runs()
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:
if pruned or removed or idle or lessons_pruned or runs_pruned or agents_pruned:
self.log(
f"Housekeeping: disabled {idle} idle-owner task(s), pruned {runs_pruned} task-run "
f"rows, pruned {pruned} ledger rows, pruned {lessons_pruned} lessons, closed "
f"{removed} idle sessions"
f"rows, pruned {agents_pruned} agent rows, pruned {pruned} ledger rows, pruned "
f"{lessons_pruned} lessons, closed {removed} idle sessions"
)
def _prune_task_runs(self) -> int:
@@ -492,6 +504,19 @@ class DeviiService(BaseService):
logger.exception("Failed to prune Devii task-run rows")
return 0
def _prune_agent_runs(self) -> int:
from datetime import datetime, timedelta, timezone
from devplacepy.database import db
from .agents.store import prune_terminal
try:
cutoff = (datetime.now(timezone.utc) - timedelta(hours=48)).isoformat()
return prune_terminal(db, cutoff)
except Exception: # noqa: BLE001 - a bad read must not stop housekeeping
logger.exception("Failed to prune Devii agent rows")
return 0
def _prune_old_lessons(self) -> int:
try:
from devplacepy.database import db
@@ -529,6 +554,42 @@ class DeviiService(BaseService):
int(cfg[config.FIELD_TASK_MAX_FAILURES]),
)
def agent_supervisor(self):
if self._agent_supervisor is None:
from devplacepy.database import db
from .agents.supervisor import AgentSupervisor
self._agent_supervisor = AgentSupervisor(db, self._resolve_agent_owner)
return self._agent_supervisor
def _resolve_agent_owner(self, row: dict):
from devplacepy.database import db
from devplacepy.utils import is_admin, is_primary_admin
owner_id = str(row.get("owner_id") or "")
if str(row.get("owner_kind") or "") != "user" or not owner_id:
return None
users = db["users"] if "users" in db.tables else None
user = users.find_one(uid=owner_id, deleted_at=None) if users else None
if not user:
return None
channel = str(row.get("channel") or "main")
if channel not in ("main", "telegram"):
channel = "main"
session = self.hub().get_or_create(
"user",
owner_id,
user.get("username", ""),
user.get("api_key", ""),
self.instance_base_url(),
is_admin=is_admin(user),
is_primary_admin=is_primary_admin(user),
channel=channel,
)
session.set_timezone(user.get("timezone") or "")
return session
def automation_budget_exceeded(self, owner_kind: str, owner_id: str) -> bool:
limit = float(self.get_config()[config.FIELD_TASK_DAILY_USD] or 0.0)
return limit > 0 and self.spent_24h(owner_kind, owner_id) >= limit
@@ -592,11 +653,15 @@ class DeviiService(BaseService):
async def on_enable(self) -> None:
self.scheduler().start()
self.agent_supervisor().start()
async def on_disable(self) -> None:
if self._scheduler is not None:
await self._scheduler.stop()
self._scheduler = None
if self._agent_supervisor is not None:
await self._agent_supervisor.stop()
self._agent_supervisor = None
if self._hub is not None:
await self._hub.aclose()
self._hub = None
@@ -641,6 +706,18 @@ class DeviiService(BaseService):
else "0"
),
},
{
"label": "Subagents",
"value": "on" if cfg[config.FIELD_AGENTS_ENABLED] else "off",
},
{
"label": "Agents running",
"value": (
f"{self._agent_supervisor.running}"
if self._agent_supervisor is not None
else "0"
),
},
{"label": "Model", "value": cfg[config.FIELD_AI_MODEL]},
]
}
@@ -10,6 +10,7 @@ from .prompts import (
DOCS_TOOLS,
LOGIN_REQUEST,
NON_ADMIN_COST_RULE,
ORCHESTRATION_FRAGMENT,
TOPIC_CLASSIFIER_PROMPT,
_parse_topic,
_system_prompt_for,
@@ -23,6 +24,7 @@ __all__ = [
"DOCS_TOOLS",
"LOGIN_REQUEST",
"NON_ADMIN_COST_RULE",
"ORCHESTRATION_FRAGMENT",
"TOPIC_CLASSIFIER_PROMPT",
"_parse_topic",
"_system_prompt_for",
+98 -18
View File
@@ -11,6 +11,7 @@ import uuid_utils
from ..actions import Dispatcher
from ..agent import Agent
from ..agentic import AgenticController, LessonStore
from ..agents.controller import AgentController
from ..avatar import AvatarController
from ..behavior import BehaviorController
from ..chunks import ChunkStore
@@ -39,6 +40,7 @@ from .prompts import (
DOCS_SYSTEM_PROMPT,
DOCS_TOOLS,
LOGIN_REQUEST,
ORCHESTRATION_FRAGMENT,
SKILLS_HEADER,
SKILLS_RULES,
TASK_RUN_ADMIN,
@@ -61,7 +63,7 @@ INTERNAL_PREFIXES = (
"[stopped]",
"Protocol violation:",
)
BUFFERED_TYPES = ("task", "error", "reply", "status")
BUFFERED_TYPES = ("task", "error", "reply", "status", "agent")
class DeviiSession:
@@ -116,6 +118,7 @@ class DeviiSession:
)
self._behavior_store = behavior_store
self.behavior = BehaviorController(behavior_store)
self.agent_controller = AgentController(self)
self.interaction_broker = InteractionBroker(
session_channel=channel,
owner_kind=owner_kind,
@@ -140,6 +143,7 @@ class DeviiSession:
virtual_tools=self.virtual_tools,
behavior=self.behavior,
interaction=self.interaction,
agents=self.agent_controller,
)
self.tools = self._builtin_tools()
self._system_prompt = (
@@ -182,6 +186,7 @@ class DeviiSession:
self._turn_tool_calls = 0
self._pending_session: str | None = None
self._turns: set[asyncio.Task] = set()
self._agents: dict[str, asyncio.Task] = {}
self._turn_epoch = 0
@property
@@ -327,7 +332,24 @@ class DeviiSession:
)
def is_busy(self) -> bool:
return self._lock.locked() or bool(self._turns)
return self._lock.locked() or bool(self._turns) or bool(self._agents)
def record_agent_spend(
self, uid: str, usage: dict[str, int], cost_usd: float
) -> None:
try:
self._ledger.record(
self.owner_kind,
self.owner_id,
uid,
usage,
cost_usd,
self.settings.ai_model,
)
except Exception: # noqa: BLE001 - ledgering must never break supervision
logger.exception(
"Failed to record agent spend for %s/%s", self.owner_kind, self.owner_id
)
def set_clientinfo(self, timezone_name: str, offset_minutes: int | None) -> None:
if timezone_name:
@@ -420,23 +442,34 @@ class DeviiSession:
self._turns.add(task)
task.add_done_callback(self._turns.discard)
async def cancel_turns(self) -> None:
async def cancel_turns(self, include_agents: bool = False) -> None:
self._turn_epoch += 1
turns = [task for task in self._turns if not task.done()]
if not turns:
return
for task in turns:
task.cancel()
try:
await asyncio.wait_for(
asyncio.gather(*turns, return_exceptions=True), timeout=10
)
except asyncio.TimeoutError:
logger.warning(
"cancel_turns: a turn did not unwind within 10s for %s/%s (epoch-guarded)",
self.owner_kind,
self.owner_id,
)
if turns:
for task in turns:
task.cancel()
try:
await asyncio.wait_for(
asyncio.gather(*turns, return_exceptions=True), timeout=10
)
except asyncio.TimeoutError:
logger.warning(
"cancel_turns: a turn did not unwind within 10s for %s/%s (epoch-guarded)",
self.owner_kind,
self.owner_id,
)
if include_agents and self._agents:
from devplacepy.services.manager import service_manager
svc = service_manager.get_service("devii")
supervisor = svc.agent_supervisor() if svc is not None else None
for uid in list(self._agents):
if supervisor is not None:
await supervisor.cancel(uid, "turn stopped")
else:
task = self._agents.pop(uid, None)
if task is not None:
task.cancel()
async def reset(self) -> None:
await self.cancel_turns()
@@ -509,6 +542,7 @@ class DeviiSession:
track_action(self.owner_id, "devii")
def _builtin_tools(self) -> list[dict[str, Any]]:
from ..agents.policy import enabled as agents_enabled
from ..tool_prefs import filter_disabled
schemas = filter_disabled(
@@ -516,6 +550,15 @@ class DeviiSession:
self.client.authenticated, self.is_admin, self.is_primary_admin
)
)
by_name = CATALOG.by_name()
available = agents_enabled()
schemas = [
schema
for schema in schemas
if self._agent_visible(
schema, by_name, available
)
]
if self.channel == "docs":
return [
s
@@ -530,6 +573,18 @@ class DeviiSession:
or s.get("function", {}).get("name") in allowed
]
@staticmethod
def _agent_visible(
schema: dict[str, Any], by_name: dict[str, Any], available: bool
) -> bool:
name = schema.get("function", {}).get("name")
action = by_name.get(name)
if action is None or action.handler != "agent":
return True
if not available:
return False
return name != "ask_user"
def _refresh_tools(self) -> None:
if self.channel == "docs":
self.tools[:] = self._builtin_tools()
@@ -548,6 +603,7 @@ class DeviiSession:
f"{CA_IWP_SYSTEM_FRAGMENT}\n\n"
f"{channel_block}\n\n"
f"{self._task_run_block()}"
f"{self._orchestration_block()}"
f"{self._skills_block()}"
f"{section}\n\n"
f"{self._clock_line()}"
@@ -573,6 +629,26 @@ class DeviiSession:
body = TASK_RUN_ADMIN if self.is_admin else TASK_RUN_MEMBER
return f"{TASK_RUN_HEADER}\n{body}\n\n"
def _orchestration_block(self) -> str:
from ..agents.policy import enabled as agents_enabled
if not agents_enabled():
return ""
return f"{ORCHESTRATION_FRAGMENT}\n\n"
def trace_agent(
self, uid: str, label: str, event: str, name: str = "", detail: str = ""
) -> None:
payload = {
"type": "trace",
"event": event,
"name": name,
"detail": detail,
"agent": label,
"uid": uid,
}
asyncio.create_task(self._emit(payload, buffer=False))
def _clock_line(self) -> str:
from datetime import datetime, timedelta, timezone
@@ -833,7 +909,7 @@ class DeviiSession:
async with self._send_lock:
await ws.send_json(payload)
async def _emit(self, payload: dict[str, Any], buffer: bool = True) -> None:
async def _emit(self, payload: dict[str, Any], buffer: bool = True) -> bool:
delivered = False
for ws in list(self._conns):
try:
@@ -846,6 +922,10 @@ class DeviiSession:
self._buffer.append(payload)
if len(self._buffer) > 100:
self._buffer = self._buffer[-100:]
return delivered
async def emit_agent(self, payload: dict[str, Any]) -> bool:
return await self._emit(payload, buffer=self.channel != "telegram")
async def _emit_interaction(self, payload: dict[str, Any]) -> None:
await self._emit(payload, buffer=False)
@@ -36,6 +36,34 @@ TASK_RUN_ADMIN = (
"schedules itself repeatedly will exhaust them."
)
ORCHESTRATION_FRAGMENT = (
"# ORCHESTRATION (ASYNC SUBAGENTS)\n"
"You are the orchestrator and you own this conversation. Answer quick things "
"yourself, DIRECTLY, with your own tools: reads of any kind, usage_quota, "
"current_time, plan/verify/reflect/recall, task CRUD, notification and "
"interaction tools, search_docs for a single lookup, and one get_page_context "
"to see where the user is. Delegate everything slow or multi-step with "
"agent_start and keep chatting meanwhile: multi-step writes of any kind, "
"project file builds and edits (files), web research chains (research), "
"audit and analytics reports (planning-report), inbox triage (email-triage), "
"and container operations (containers).\n"
"Every spawn carries the four-part contract: a clear objective plus hard "
"boundaries in task, the exact answer shape in output_format, tool and "
"source guidance via tools_extra, and an effort scale via budget_hint "
"(quick for fact-finding, standard normally, deep for genuinely complex "
"work). agent_start returns a process uid at once; check progress with "
"agent_status, read the outcome with agent_result, stop work with "
"agent_cancel, and track everything with agent_list. Narrate progress to "
"the user in your own words while runs continue.\n"
"Only you talk to the user. A run that needs input pauses as needs_user "
"with its question: ask the user through ui_prompt (or plain text where "
"widgets are off), then resume the run by calling agent_result with the "
"uid and their answer. The same path relays confirmations: the run names "
"the exact target, you get a clear yes, and the answer carries the "
"confirmation back. Never invent an answer and never leave a needs_user "
"run hanging without telling the user it waits on them."
)
SKILLS_HEADER = "# INSTALLED SKILLS"
SKILLS_RULES = (
+15 -3
View File
@@ -5,6 +5,7 @@ from typing import Optional
from devplacepy.attachments import get_attachments_batch
from devplacepy.database import (
get_table,
listed_clause,
get_users_by_uids,
get_user_votes,
get_vote_counts,
@@ -49,9 +50,15 @@ def build_rant_list(posts: list, viewer: Optional[dict]) -> list:
def list_rants(sort: str, limit: int, skip: int, viewer: Optional[dict]) -> list:
order = SORT_ORDER.get(sort, SORT_ORDER["recent"])
posts_table = get_table("posts")
listed = listed_clause(posts_table)
posts = list(
get_table("posts").find(
deleted_at=None, order_by=order, _limit=limit, _offset=skip
posts_table.find(
*([listed] if listed is not None else []),
deleted_at=None,
order_by=order,
_limit=limit,
_offset=skip,
)
)
return build_rant_list(posts, viewer)
@@ -64,9 +71,14 @@ def search_rants(term: str, viewer: Optional[dict], limit: int = 50) -> list:
)
if clause is None:
return []
listed = listed_clause(posts_table)
posts = list(
posts_table.find(
clause, deleted_at=None, order_by=["-created_at"], _limit=limit
clause,
*([listed] if listed is not None else []),
deleted_at=None,
order_by=["-created_at"],
_limit=limit,
)
)
return build_rant_list(posts, viewer)
+7 -2
View File
@@ -29,11 +29,16 @@ def now_unix() -> int:
return int(datetime.now(timezone.utc).timestamp())
def post_by_id(rant_id: object) -> Optional[dict]:
def post_by_id(rant_id: object, viewer: Optional[dict] = None) -> Optional[dict]:
from devplacepy.content import can_view_item
identifier = as_int(rant_id)
if not identifier:
return None
return get_table("posts").find_one(id=identifier, deleted_at=None)
post = get_table("posts").find_one(id=identifier, deleted_at=None)
if post and not can_view_item("posts", post, viewer):
return None
return post
def comment_by_id(comment_id: object) -> Optional[dict]:
+6 -1
View File
@@ -4,6 +4,7 @@ from typing import Optional
from devplacepy.database import (
get_table,
listed_clause,
get_users_by_uids,
get_user_votes,
get_vote_counts,
@@ -28,8 +29,12 @@ def skills_from_bio(bio: Optional[str]) -> str:
def _user_rants(user: dict, viewer: Optional[dict]) -> list:
posts_table = get_table("posts")
own_uid = viewer["uid"] if viewer and viewer["uid"] == user["uid"] else None
listed = listed_clause(posts_table, own_uid=own_uid)
posts = list(
get_table("posts").find(
posts_table.find(
*([listed] if listed is not None else []),
user_uid=user["uid"],
deleted_at=None,
order_by=["-created_at"],
+31
View File
@@ -0,0 +1,31 @@
# Giphy (GIF picker)
Members search GIPHY from a "GIF" button beside the attachment button in the post composer, every comment form and the direct-message input. A picked GIF is stored as a normal attachment. There is no local GIF store, no table and no client-side key.
## Layout
| File | Role |
|------|------|
| `config.py` | `giphy_api_key` (secret), `giphy_base_url`, `giphy_rating` as `CONFIG_FIELDS` (the admin-editable settings), `giphy_config()` reads them through `get_setting` |
| `client.py` | `GiphyClient` (`search`, `trending`, `get_gif`), `normalize_gif`, `GiphyError(message, status)`, the module-level 5 minute `TtlCache` |
| `limits.py` | `TtlCache` (256 entries, 300 s) and `UserRateLimiter` (30 calls per 60 s per user, 2048 users tracked) |
| `runtime.py` | `get_client()` / `set_client()`, the test seam (the gitea `runtime` pattern) |
| `fake.py` | `FakeGiphyClient` for tests |
| `service.py` | `GiphyService` (`BaseService`, off by default): a daily health probe against `trending` and the home of the admin config fields |
| `routers/giphy.py` | `/giphy/status`, `/search`, `/trending`, `/attach` |
## Rules
- **A GIF is an attachment, never markup.** `POST /giphy/attach` downloads the GIF through `attachments.store_attachment_from_url` (SSRF guarded, size capped, the same pipeline as an upload) and returns the upload record. The picker fires `dp-gif:attached` and the form's `dp-upload` (attachment mode) adds the uid to `attachment_uids`. Nothing is inserted into the textarea; the GIF renders in the attachment gallery like any file. Do not add a markdown insertion path: it would render the GIF twice.
- **The key never leaves the server.** The browser talks only to `/giphy/*`. The picker hides itself when `/giphy/status` says `configured: false`. The key is edited in `/admin/services` (the Giphy service), stored in `site_settings`, never hardcoded.
- **Hard caps.** `limit` is clamped to `MAX_LIMIT` (50), `q` to 200 characters, the cache to 256 entries / 300 s, the per-user limiter to 30 calls per 60 s (`429` with `Retry-After`). The cache is keyed without the API key and never stores errors. These are static ceilings on purpose: a free GIPHY key allows roughly 100 calls an hour, so repeated and rapid queries must not reach the upstream.
- **Errors use `responses.json_error`** (`{"error": {"status", "message"}}`) so `Http` shows the message. `503` not configured, `400` missing `q`, `404` unknown id, `429` throttled, `502` upstream failure.
- **Outbound HTTP is the stealth client only** (`stealth.stealth_async_client`); attachments go through `guarded_async_client`.
- **Audit:** `attachment.giphy` (`events.md`), recorded with the gif id and the source host. The GIF is a normal attachment afterwards, so it is reportable and soft-deletable like every other.
- **Privacy:** GIPHY receives the search words and a picked id from the server, never the member's IP or account. Disclosed in `/docs/privacy.html`.
- **Attribution:** the panel shows "Powered by GIPHY"; do not remove it (GIPHY terms).
- **Devii:** `search_gifs`, `trending_gifs`, `attach_gif` (`catalog/uploads.py`), docs in `docs_api/groups/uploads.py`. Not load tested: the routes call a third party with a rate-limited key, so `locustfile.py` deliberately has no task for them.
## Testing
`runtime.set_client(FakeGiphyClient())` swaps the client in-process (api and unit tiers). The e2e tier runs the server in a subprocess, so it points `giphy_base_url` at a local fake GIPHY HTTP server through the settings table instead, and stubs only `/giphy/attach` in the browser (the SSRF guard rightly refuses a loopback GIF URL).
+5
View File
@@ -0,0 +1,5 @@
# retoor <retoor@molodetz.nl>
from devplacepy.services.giphy.service import GiphyService
__all__ = ["GiphyService"]
+134
View File
@@ -0,0 +1,134 @@
# retoor <retoor@molodetz.nl>
import logging
import httpx
from devplacepy import stealth
from devplacepy.services.giphy.config import (
HTTP_TIMEOUT_SECONDS,
RESULT_LIMIT_DEFAULT,
GiphyConfig,
giphy_config,
)
from devplacepy.services.giphy.limits import TtlCache
logger = logging.getLogger(__name__)
MAX_LIMIT = 50
_cache = TtlCache()
def clear_cache() -> None:
_cache.clear()
class GiphyError(Exception):
def __init__(self, message: str, status: int = 0):
super().__init__(message)
self.status = status
self.message = message
def _pick_image(images: dict, keys: tuple[str, ...]) -> dict:
for key in keys:
image = images.get(key)
if not isinstance(image, dict):
continue
url = image.get("url") or image.get("webp") or ""
if not url:
continue
return {
"url": url,
"width": int(image.get("width") or 0),
"height": int(image.get("height") or 0),
"size": int(image.get("size") or 0),
}
return {}
def normalize_gif(item: dict) -> dict:
images = item.get("images") or {}
return {
"id": str(item.get("id") or ""),
"title": str(item.get("title") or "").strip(),
"url": str(item.get("url") or ""),
"preview": _pick_image(images, ("fixed_width", "downsized", "original")),
"original": _pick_image(images, ("original", "downsized")),
}
class GiphyClient:
def __init__(self, config: GiphyConfig | None = None):
self.config = config or giphy_config()
def _require_config(self) -> None:
if not self.config.is_configured:
raise GiphyError("Giphy integration is not configured", status=503)
def _params(self, **extra) -> dict:
return {"api_key": self.config.api_key, "rating": self.config.rating, **extra}
def _cache_key(self, path: str, params: dict) -> tuple:
shared = {k: v for k, v in params.items() if k != "api_key"}
return (self.config.base_url, path, tuple(sorted(shared.items())))
async def _get(self, path: str, params: dict) -> dict:
self._require_config()
key = self._cache_key(path, params)
cached = _cache.get(key)
if cached is not None:
return cached
data = await self._fetch(path, params)
_cache.put(key, data)
return data
async def _fetch(self, path: str, params: dict) -> dict:
url = f"{self.config.base_url.rstrip('/')}/{path}"
logger.debug("Giphy GET %s", path)
try:
async with stealth.stealth_async_client(timeout=HTTP_TIMEOUT_SECONDS) as client:
response = await client.get(url, params=params)
except httpx.HTTPError as exc:
logger.warning("Giphy request failed: %s", exc)
raise GiphyError(f"Giphy request failed: {exc}") from exc
if response.status_code >= 400:
logger.warning(
"Giphy %s returned %s: %s",
path,
response.status_code,
response.text[:200],
)
raise GiphyError(
f"Giphy returned {response.status_code}", status=response.status_code
)
return response.json()
async def search(self, query: str, limit: int = RESULT_LIMIT_DEFAULT) -> list[dict]:
data = await self._get(
"search",
self._params(
q=query,
limit=max(1, min(int(limit), MAX_LIMIT)),
offset=0,
lang="en",
),
)
return [normalize_gif(item) for item in data.get("data", [])]
async def trending(self, limit: int = RESULT_LIMIT_DEFAULT) -> list[dict]:
data = await self._get(
"trending",
self._params(limit=max(1, min(int(limit), MAX_LIMIT)), offset=0),
)
return [normalize_gif(item) for item in data.get("data", [])]
async def get_gif(self, gif_id: str) -> dict:
if not gif_id:
raise GiphyError("missing GIF id", status=400)
data = await self._get(gif_id, self._params())
item = data.get("data") or {}
if not item:
raise GiphyError("GIF not found", status=404)
return normalize_gif(item)
+59
View File
@@ -0,0 +1,59 @@
# retoor <retoor@molodetz.nl>
from dataclasses import dataclass
from devplacepy.database import get_setting
from devplacepy.services.base import ConfigField
API_BASE_DEFAULT = "https://api.giphy.com/v1/gifs"
HTTP_TIMEOUT_SECONDS = 15.0
RESULT_LIMIT_DEFAULT = 24
@dataclass(frozen=True)
class GiphyConfig:
api_key: str
base_url: str
rating: str
@property
def is_configured(self) -> bool:
return bool(self.api_key)
CONFIG_FIELDS: list[ConfigField] = [
ConfigField(
"giphy_api_key",
"Giphy API key",
type="password",
default="",
secret=True,
help="API key from the Giphy developer dashboard. Without it the GIF picker stays hidden.",
group="Giphy",
),
ConfigField(
"giphy_base_url",
"Giphy API base URL",
type="url",
default=API_BASE_DEFAULT,
help="Endpoint root of the Giphy API, without the trailing search or trending path.",
group="Giphy",
),
ConfigField(
"giphy_rating",
"Content rating",
type="choice",
default="pg",
options=["g", "pg", "pg-13", "r"],
help="Highest content rating returned by search and trending.",
group="Giphy",
),
]
def giphy_config() -> GiphyConfig:
return GiphyConfig(
api_key=get_setting("giphy_api_key", ""),
base_url=get_setting("giphy_base_url", API_BASE_DEFAULT) or API_BASE_DEFAULT,
rating=get_setting("giphy_rating", "pg") or "pg",
)

Some files were not shown because too many files have changed in this diff Show More