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

0 downloads

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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
agent_heartbeat.py · 4.6 KB · 130 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 rows = object_records.read_collection_records(COLLECTION, base_dir=base)
66 except Exception:
67 return None
68 for row in rows:
69 if _text(row.get("agent_id")) == agent_id:
70 return row
71 return None
72
73
74def POST(request):
75 request = request or {}
76 base = _base_dir()
77
78 identity = request.get("_identity") or {}
79 agent_id = _text(identity.get("user_id"))
80 if not agent_id:
81 return {"status": 401,
82 "error": ("A heartbeat identifies the caller, so it needs an "
83 "identity. Sign in or present an API key; an agent "
84 "cannot beat anonymously, and it cannot beat on "
85 "behalf of another.")}
86
87 now = _now()
88 beat = {"heartbeat_at": now}
89 # Present-but-empty withdraws; absent leaves alone. That distinction is
90 # what makes a bare keep-alive safe to send on a timer.
91 for field in ("label", "purpose", "capabilities", "endpoint"):
92 if field in request:
93 beat[field] = _text(request.get(field))
94
95 existing = _existing(base, agent_id)
96 if existing is not None:
97 try:
98 stored = object_records.update_collection_record(
99 COLLECTION, existing["id"], beat, base_dir=base, actor=agent_id)
100 except Exception as exc:
101 return {"status": 500,
102 "error": f"The heartbeat could not be recorded: {str(exc)[:160]}"}
103 registered = False
104 else:
105 record = {
106 "id": object_ids.new_uuid4(),
107 "agent_id": agent_id,
108 "status": "active",
109 "registered_at": now,
110 "owner_id": agent_id,
111 **beat,
112 }
113 try:
114 stored = object_records.create_collection_record(
115 COLLECTION, record, base_dir=base, actor=agent_id)
116 except Exception as exc:
117 return {"status": 500,
118 "error": f"The agent could not be registered: {str(exc)[:160]}"}
119 registered = True
120
121 return {
122 "ok": True,
123 "agent_id": agent_id,
124 "registered": registered,
125 "heartbeat_at": now,
126 "capabilities": object_agents.capabilities(stored),
127 "status": _text(stored.get("status")) or "active",
128 "note": ("Registered. Capabilities are opt-in: an agent advertising "
129 "nothing is routed nothing." if registered else ""),
130 }