Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
agents.py · 17.6 KB · 442 lines
1"""site_agents -- the board a human watches while the agents work.
2
3 GET /agents who is here, what they can do, what they are saying
4 GET /agents.json the same fold, for a monitor
5
6## Why a board rather than a list
7
8The generative list renderer already gives `agent_registry` a perfectly
9good table, and it is the wrong shape for the one question this page
10exists to answer: **is everything that should be working, working?** A
11table sorts by whatever column you clicked. A board leads with the
12answer, puts the dead things first, and shows the conversation next to
13the participants.
14
15The model is WOLD's own asset gallery, which earns its keep the same way:
16score, method, verdict and provenance on every card, so an operator can
17scan a hundred of them and see exactly which ones need attention without
18opening anything.
19
20## Liveness is stated with its evidence
21
22Every agent shows its state AND the heartbeat it was computed from, for
23the reason the ledger-integrity page states its method beside its
24verdict: "lost" without "last seen 4 hours ago" is a claim, and the
25operator's next question is always the timestamp. Three states rather
26than a boolean, because the useful distinction is not up-or-down but
27"should I be worried yet".
28
29## The feed is the other half, and it lives somewhere else
30
31`feed_posts` (app-collab) has been the coordination feed since before this
32package existed -- with `claim` and `release` already in its `kind` enum.
33This page renders it rather than duplicating it, and app-collab keeps
34owning it. That is why this package declares no feed collection of its
35own: the channel was already here, it just had no face.
36"""
37
38import html
39import json
40import os
41from datetime import datetime, timezone
42
43import object_access
44import object_agents
45import object_state
46import object_records
47
48REGISTRY = "agent_registry"
49SCHEDULER_RUNS = "scheduler_runs"
50FEED = "feed_posts"
51SETTINGS_COLLECTION = "app_settings"
52STALE_KEY = "agents.stale_seconds"
53LOST_KEY = "agents.lost_seconds"
54
55FEED_LIMIT = 25
56
57_STYLE = """
58.ag { max-width: 54rem; }
59.ag h2 { font-size: 1rem; margin: 1.6rem 0 .5rem; }
60.ag .banner { border: 1px solid var(--line, #38384a); border-radius: 8px;
61 padding: .85rem 1.05rem; margin: 1rem 0 1.4rem; }
62.ag .banner.warn { border-color: var(--accent, #b5713a); }
63.ag .cols { display: grid; gap: 1.2rem; grid-template-columns: 1fr 1fr;
64 align-items: start; }
65@media (max-width: 46rem) { .ag .cols { grid-template-columns: 1fr; } }
66.ag .cards { display: grid; gap: .7rem; }
67.ag .card { border: 1px solid var(--line, #38384a); border-radius: 8px;
68 padding: .7rem .85rem; }
69.ag .card.live { border-left: 3px solid var(--accent, #b5713a); }
70.ag .card.lost, .ag .card.never { border-left: 3px solid #d05a5a; }
71.ag .card.stale { border-left: 3px solid #c9a227; }
72.ag .card h3 { font-size: .95rem; margin: 0 0 .15rem; }
73.ag .state { font-size: .75rem; text-transform: uppercase; letter-spacing: .05em; }
74.ag .state.live { color: var(--accent, #b5713a); }
75.ag .state.lost, .ag .state.never { color: #d05a5a; }
76.ag .state.stale { color: #c9a227; }
77.ag .tag { display: inline-block; border: 1px solid var(--line, #55556a);
78 border-radius: 10px; padding: 0 .45rem; font-size: .72rem;
79 margin: .15rem .15rem 0 0; }
80.ag .muted { opacity: .7; font-size: .82rem; }
81.ag .feed { margin: .4rem 0 0; padding: 0; list-style: none; }
82.ag .feed li { border-bottom: 1px solid var(--line, #38384a); padding: .4rem 0;
83 font-size: .88rem; }
84.ag .kind { font-size: .7rem; text-transform: uppercase; letter-spacing: .05em;
85 border: 1px solid var(--line, #55556a); border-radius: 10px;
86 padding: 0 .4rem; margin-right: .4rem; }
87.ag .note { border-left: 3px solid var(--line, #55556a); padding: .1rem 0 .1rem .7rem;
88 margin: .7rem 0 1.1rem; font-size: .86rem; opacity: .85; }
89.ag table.workers { width: 100%; border-collapse: collapse; font-size: .86rem; }
90.ag table.workers th, .ag table.workers td {
91 text-align: left; padding: .35rem .5rem;
92 border-bottom: 1px solid var(--line, #38384a); vertical-align: top; }
93.ag table.workers th { font-weight: 600; opacity: .8; }
94.ag .pill { font-size: .7rem; text-transform: uppercase; letter-spacing: .05em;
95 border: 1px solid var(--line, #55556a); border-radius: 10px;
96 padding: 0 .45rem; }
97.ag .pill.live { color: var(--accent, #b5713a); border-color: var(--accent, #b5713a); }
98.ag .pill.stale { color: #c9a227; border-color: #c9a227; }
99.ag .pill.lost, .ag .pill.never { color: #d05a5a; border-color: #d05a5a; }
100.ag .workererr { color: #d05a5a; font-size: .78rem; margin-top: .2rem; }
101"""
102
103
104def _esc(value):
105 return html.escape(str(value if value is not None else ""), quote=True)
106
107
108def _base_dir():
109 return os.environ.get("DBBASIC_DATA_DIR", "data")
110
111
112def _text(value):
113 return str(value if value is not None else "").strip()
114
115
116def _now():
117 return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
118
119
120def _rows(collection, base):
121 try:
122 # access: registry and settings rows are registered-readable by design; the wallet_entries caller filters through Access.visible
123 return object_records.read_collection_records(collection, base_dir=base)
124 except Exception:
125 return []
126
127
128def _setting(base, key, default):
129 for row in _rows(SETTINGS_COLLECTION, base):
130 if _text(row.get("key")) == key and _text(row.get("value")):
131 try:
132 return int(_text(row.get("value")))
133 except ValueError:
134 return default
135 return default
136
137
138def _scheduled_tasks(base):
139 """The scheduler's declared tasks, read from its object state.
140
141 Degrades to [] when the scheduler has never been written -- a box
142 with no scheduled work is not a broken box, and the workers panel
143 simply has nothing to show.
144 """
145 try:
146 state = object_state.get_object_state("scheduler", base)
147 except Exception:
148 return []
149 tasks = []
150 for key, value in (state or {}).items():
151 if not str(key).startswith("task_"):
152 continue
153 try:
154 task = json.loads(value) if isinstance(value, str) else value
155 except (ValueError, TypeError):
156 continue
157 if isinstance(task, dict):
158 tasks.append(task)
159 return tasks
160
161
162def _hide_spend_the_caller_cannot_read(fold, access):
163 """Spend is a fold over an agent's wallet_entries, and that ledger is
164 owner-scoped in the API (`owner_id == $user_id`); the registry rows are
165 registered-readable by design, the money is not. Folding the raw
166 ledger here showed every signed-in user every agent's committed spend
167 and over-cap flag (bug-reports/2026-11-28-06-14-42).
168
169 So the ledger is filtered to the rows the caller may read, AND an
170 agent whose ledger the caller may not read at all shows no spend --
171 not "0 of 1000": the cap is on the readable registry row, and a zero
172 computed from rows you were not shown is a confident wrong number.
173 "May read this agent's ledger" is asked of the engine as a read of a
174 row keyed the way the ledger is keyed (owner_id = the agent id).
175 """
176 for row in fold["agents"]:
177 if row["spend"] and not access.can(
178 "read", "wallet_entries", {"owner_id": row["agent_id"]}):
179 row["spend"] = None
180 fold["over_cap"] = [row["agent_id"] for row in fold["agents"]
181 if row["spend"] and row["spend"]["over"]]
182 return fold
183
184
185def report(*, base=None, now=None, access=None):
186 """One fold, two surfaces.
187
188 `access` (object_access.Access) is the caller; the page always passes
189 it. Without one this is an in-process fold by code that can read
190 storage itself, and it sees everything.
191 """
192 base = _base_dir() if base is None else base
193 now = now or _now()
194
195 entries = _rows("wallet_entries", base)
196 if access is not None:
197 entries = access.visible("wallet_entries", entries)
198 fold = object_agents.board(
199 _rows(REGISTRY, base), entries, now=now,
200 stale_seconds=_setting(base, STALE_KEY,
201 object_agents.DEFAULT_STALE_SECONDS),
202 lost_seconds=_setting(base, LOST_KEY,
203 object_agents.DEFAULT_LOST_SECONDS))
204 if access is not None:
205 fold = _hide_spend_the_caller_cannot_read(fold, access)
206
207 # The box's own scheduled work, folded from the run log rather than
208 # from a heartbeat somebody would have to remember to send. Every
209 # scheduled execution already writes a scheduler_runs row, so the
210 # evidence exists; nothing was applying a liveness verdict to it.
211 #
212 # The declared tasks come from the scheduler's own state, and they
213 # matter for exactly one case the run log cannot report: a task that
214 # has NEVER run has no rows at all, and an absence is invisible to a
215 # fold over presences. That is the pass silently doing nothing since
216 # the day it was added -- the failure most worth catching here.
217 fold["workers"] = object_agents.worker_liveness(
218 _rows(SCHEDULER_RUNS, base), tasks=_scheduled_tasks(base), now=now,
219 stale_seconds=_setting(base, STALE_KEY,
220 object_agents.DEFAULT_STALE_SECONDS),
221 lost_seconds=_setting(base, LOST_KEY,
222 object_agents.DEFAULT_LOST_SECONDS))
223
224 posts = sorted(_rows(FEED, base),
225 key=lambda row: _text(row.get("created_at")), reverse=True)
226 fold["feed"] = [{
227 "kind": _text(post.get("kind")) or "status",
228 "body": _text(post.get("body")),
229 "owner_id": _text(post.get("owner_id")),
230 "created_at": _text(post.get("created_at")),
231 # Blank for rows written before feed_posts gained created_at (v2).
232 # Those render WITHOUT a time rather than as "never", because a
233 # post that predates the column is not a post that never happened.
234 "ago": (object_agents.relative_time(post.get("created_at"), now)
235 if _text(post.get("created_at")) else ""),
236 } for post in posts[:FEED_LIMIT]]
237 fold["feed_installed"] = bool(posts) or _rows(FEED, base) != []
238 return fold
239
240
241# --- rendering ---------------------------------------------------------------
242
243def _banner(fold):
244 if not fold["agents"]:
245 return """
246<div class="banner warn">
247<h2>No agents are registered</h2>
248<p>Nothing has introduced itself. An agent registers by sending its first
249heartbeat to <code>action_agent_heartbeat</code> — there is no separate
250registration step, because there is nothing a registration knows that the
251first heartbeat does not.</p>
252</div>"""
253
254 missing = [row for row in fold["agents"]
255 if row["liveness"] in ("lost", "never")]
256 if missing:
257 names = ", ".join(_esc(row["label"]) for row in missing[:4])
258 return f"""
259<div class="banner warn">
260<h2>{len(missing)} of {fold['total']} are not answering</h2>
261<p>{names} last checked in longer ago than this server's patience allows.
262An agent goes quiet for two reasons — it crashed, or it is doing something
263long and is not beating while it works. The heartbeat beside each card is
264what tells them apart.</p>
265</div>"""
266
267 over = fold["over_cap"]
268 if over:
269 return f"""
270<div class="banner warn">
271<h2>{len(over)} over the spend cap</h2>
272<p>{_esc(', '.join(over))} has committed more than its cap allows. The cap is
273a fold over holds and debits in the ledger, not a stored counter, so this
274is the ledger's own arithmetic rather than a number somebody maintained.</p>
275</div>"""
276
277 return f"""
278<div class="banner">
279<h2>All {fold['total']} answering</h2>
280<p>Every registered agent has beaten within the window.</p>
281</div>"""
282
283
284def _card(row):
285 spend = ""
286 if row["spend"]:
287 spend = (f'<p class="muted">spend {row["spend"]["committed_minor"]} / '
288 f'{row["spend"]["cap_minor"]}'
289 f'{" — OVER" if row["spend"]["over"] else ""}</p>')
290 tags = "".join(f'<span class="tag">{_esc(tag)}</span>'
291 for tag in row["capabilities"])
292 if not tags:
293 tags = '<span class="muted">no capabilities advertised</span>'
294 # The phrase, not the stamp: an operator asked "is it still there"
295 # should not have to subtract two datetimes in their head.
296 beat = _esc(row["heartbeat_ago"]) if row["heartbeat_at"] else "never checked in"
297 return f"""
298<div class="card {_esc(row['liveness'])}">
299<h3>{_esc(row['label'])}</h3>
300<p class="state {_esc(row['liveness'])}">{_esc(row['liveness'])}</p>
301<p class="muted">{_esc(row['agent_id'])}</p>
302{f'<p class="muted">{_esc(row["purpose"])}</p>' if row['purpose'] else ''}
303<p>{tags}</p>
304<p class="muted" title="{_esc(row['heartbeat_at'])}">last beat {beat}</p>
305{spend}
306</div>"""
307
308
309def _feed_html(fold):
310 if not fold["feed"]:
311 return ('<p class="muted">Nothing on the feed yet. It is the '
312 '<code>feed_posts</code> collection (app-collab), which has '
313 'carried <code>claim</code> and <code>release</code> in its '
314 'kinds since before this page existed.</p>')
315 # Relative time on the line, the exact stamp in the tooltip. A feed is
316 # read for "how long ago", never for "at what instant" -- and the one
317 # time somebody does want the instant, hovering gives it without
318 # spending a line on it.
319 items = "".join(
320 f'<li><span class="kind">{_esc(post["kind"])}</span>'
321 f'{_esc(post["body"])}'
322 f'<br><span class="muted" title="{_esc(post["created_at"])}">'
323 f'{_esc(post["owner_id"])}'
324 f'{" &middot; " + _esc(post["ago"]) if post["ago"] else ""}</span></li>'
325 for post in fold["feed"])
326 return f'<ul class="feed">{items}</ul>'
327
328
329def _worker_rows(fold):
330 workers = fold.get("workers", {}).get("workers", [])
331 if not workers:
332 return ('<p class="muted">Nothing is scheduled on this server yet.</p>')
333 out = []
334 for row in workers:
335 state = _esc(row["liveness"])
336 when = _esc(row["last_run_ago"]) or "never"
337 schedule = _esc(row["schedule"]) or "&mdash;"
338 # "live, and failing" is a worse state than "lost" and the one a
339 # liveness badge alone would render as healthy, so the error gets
340 # its own line rather than a colour.
341 error = (f'<div class="workererr">last run failed: '
342 f'{_esc(row["last_error"][:160])}</div>'
343 if row["failing"] else "")
344 out.append(
345 f'<tr class="w-{state}">'
346 f'<td><code>{_esc(row["object_id"])}</code>{error}</td>'
347 f'<td><code>{schedule}</code></td>'
348 f'<td><span class="pill {state}">{state}</span></td>'
349 f'<td>{when}</td>'
350 f'</tr>')
351 return ('<table class="workers"><thead><tr><th>Scheduled object</th>'
352 '<th>Schedule</th><th>State</th><th>Last run</th></tr></thead>'
353 f'<tbody>{"".join(out)}</tbody></table>')
354
355
356def _page(fold):
357 cards = "".join(_card(row) for row in fold["agents"])
358 caps = (", ".join(_esc(tag) for tag in fold["capabilities"])
359 or "none advertised")
360 return f"""
361<div class="breadcrumb"><a href="/">Home</a> / Agents</div>
362<h1>Agents</h1>
363<p>Who is operating this server, what they will accept work for, and
364whether they are still answering.</p>
365{_banner(fold)}
366<div class="cols">
367<div>
368<h2>Agents</h2>
369<div class="cards">{cards}</div>
370</div>
371<div>
372<h2>Coordination feed</h2>
373{_feed_html(fold)}
374</div>
375</div>
376<p class="note">Liveness is a <strong>heartbeat</strong>, not a last write.
377An agent reasoning for ten minutes writes nothing and is perfectly alive,
378so "when did it last change a record" cannot answer "is it still there" —
379which is the only reason this collection exists. Everything else about an
380agent is already recorded: what it did is the
381<a href="/activity">change log</a>, who it is, is its user.</p>
382
383<h2>This server's own work</h2>
384<p>The scheduled passes this box runs for itself, and whether they are
385still running. This is <strong>folded from the run log, not from a
386heartbeat</strong>: every scheduled execution already writes a
387<code>scheduler_runs</code> row, and a row saying the work ran is better
388evidence than a process saying it is alive.</p>
389{_worker_rows(fold)}
390<p class="muted">A task that has <em>never</em> run is shown from the
391scheduler's declared tasks rather than the log, because an object with no
392rows is invisible to a fold over rows — and a pass that has quietly done
393nothing since the day it was added is exactly the failure worth
394catching.</p>
395
396<h2>Capabilities on this server</h2>
397<p>{caps}</p>
398<p class="muted">Capabilities are opt-in and empty by default. An agent
399advertising nothing is routed nothing — nobody's machine joins a compute
400pool by accident.</p>
401
402<p class="note"><a href="/agents.json">This page as JSON</a> ·
403<a href="/agent-registry">the registry as a table</a></p>
404"""
405
406
407def GET(request):
408 request = request or {}
409 path = _text((request or {}).get("_path") or "/agents").lower()
410 fold = report(access=object_access.Access(request.get("_identity"),
411 base_dir=_base_dir()))
412
413 if path.endswith(".json"):
414 return {"status": 200,
415 "content_type": "application/json; charset=utf-8",
416 "body": json.dumps(fold, indent=2, sort_keys=True, default=str)}
417
418 return {
419 "status": 200,
420 "content_type": "text/html; charset=utf-8",
421 "body": f"""<!doctype html>
422<html lang="en">
423<head>
424<meta charset="utf-8">
425<meta name="viewport" content="width=device-width, initial-scale=1">
426<title>Agents</title>
427<link rel="stylesheet" href="/style">
428<style>{_STYLE}</style>
429</head>
430<body>
431<div class="wrap ag">
432<header class="app"><h1><a href="/">DBBASIC</a></h1></header>
433{_page(fold)}
434</div>
435<script src="/nav"></script>
436</body>
437</html>""",
438 }
439
440
441def POST(request):
442 return GET(request)