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
agent_heartbeat.py · 4.8 KB · 133 lines
1"""action_agent_heartbeat -- "still here", and register on the way in.
2
3POST {label?, purpose?, capabilities?, endpoint?}
4
5One verb, not two. An agent's first beat registers it and every later
6beat updates the timestamp, because a separate `register` call is a step
7somebody forgets and then debugs -- and there is nothing a registration
8knows that the first heartbeat does not.
9
10## It registers the CALLER, never a named agent
11
12`agent_id` comes from `_identity`, never from the request body. An agent
13cannot beat on behalf of another, which matters more than it looks: a
14heartbeat is the evidence something is alive, and evidence one party can
15forge about another is not evidence. Same reason action_run_template sets
16`owner_id` from identity rather than accepting it.
17
18## Capabilities are opt-in and only the caller may set them
19
20An agent advertises what it will accept work for. Absent, it advertises
21nothing and is routed nothing -- because nobody's laptop should join a
22compute pool by accident (plan/federated-workers-spec.md). A beat that
23omits `capabilities` LEAVES THEM ALONE rather than clearing them, so a
24minimal keep-alive is safe to send on a timer; passing an empty string
25explicitly is how you withdraw.
26
27## What it deliberately does not do
28
29**It does not report what the agent has done.** That is record_changes,
30which already carries an actor on every write, and app-activity already
31renders it. A heartbeat that also submitted a work summary would be a
32second, forgeable account of the same facts.
33
34**It does not gate on the spend cap.** The cap is evaluated where money
35moves -- the wallet gate -- not at the door of a keep-alive. Refusing a
36heartbeat because an agent is over budget would make it look dead, which
37is the opposite of what an operator needs to see.
38"""
39
40import os
41from datetime import datetime, timezone
42
43import object_agents
44import object_ids
45import object_records
46
47ACTOR = "action_agent_heartbeat"
48COLLECTION = "agent_registry"
49
50
51def _base_dir():
52 return os.environ.get("DBBASIC_DATA_DIR", "data")
53
54
55def _text(value):
56 return str(value if value is not None else "").strip()
57
58
59def _now():
60 return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
61
62
63def _existing(base, agent_id):
64 try:
65 # access: the caller's own row: agent_id comes from _identity, never from the body
66 rows = object_records.read_collection_records(COLLECTION, base_dir=base)
67 except Exception:
68 return None
69 for row in rows:
70 if _text(row.get("agent_id")) == agent_id:
71 return row
72 return None
73
74
75def POST(request):
76 request = request or {}
77 base = _base_dir()
78
79 identity = request.get("_identity") or {}
80 agent_id = _text(identity.get("user_id"))
81 if not agent_id:
82 return {"status": 401,
83 "error": ("A heartbeat identifies the caller, so it needs an "
84 "identity. Sign in or present an API key; an agent "
85 "cannot beat anonymously, and it cannot beat on "
86 "behalf of another.")}
87
88 now = _now()
89 beat = {"heartbeat_at": now}
90 # Present-but-empty withdraws; absent leaves alone. That distinction is
91 # what makes a bare keep-alive safe to send on a timer.
92 for field in ("label", "purpose", "capabilities", "endpoint"):
93 if field in request:
94 beat[field] = _text(request.get(field))
95
96 existing = _existing(base, agent_id)
97 if existing is not None:
98 try:
99 # access: the caller's own row: agent_id comes from _identity, never from the body
100 stored = object_records.update_collection_record(
101 COLLECTION, existing["id"], beat, base_dir=base, actor=agent_id)
102 except Exception as exc:
103 return {"status": 500,
104 "error": f"The heartbeat could not be recorded: {str(exc)[:160]}"}
105 registered = False
106 else:
107 record = {
108 "id": object_ids.new_uuid4(),
109 "agent_id": agent_id,
110 "status": "active",
111 "registered_at": now,
112 "owner_id": agent_id,
113 **beat,
114 }
115 try:
116 # access: the caller's own row: agent_id comes from _identity, never from the body
117 stored = object_records.create_collection_record(
118 COLLECTION, record, base_dir=base, actor=agent_id)
119 except Exception as exc:
120 return {"status": 500,
121 "error": f"The agent could not be registered: {str(exc)[:160]}"}
122 registered = True
123
124 return {
125 "ok": True,
126 "agent_id": agent_id,
127 "registered": registered,
128 "heartbeat_at": now,
129 "capabilities": object_agents.capabilities(stored),
130 "status": _text(stored.get("status")) or "active",
131 "note": ("Registered. Capabilities are opt-in: an agent advertising "
132 "nothing is routed nothing." if registered else ""),
133 }