sessionyard 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. agent_chat/001_core.sql +172 -0
  2. agent_chat/002_coordination.sql +63 -0
  3. agent_chat/003_harness_admission.sql +10 -0
  4. agent_chat/004_session_titles.sql +3 -0
  5. agent_chat/005_viewer.sql +9 -0
  6. agent_chat/006_quotas.sql +6 -0
  7. agent_chat/007_sender_receipts.sql +20 -0
  8. agent_chat/008_direct_threads.sql +49 -0
  9. agent_chat/009_pm_mark.sql +23 -0
  10. agent_chat/010_quota_backfill.sql +12 -0
  11. agent_chat/011_roles_and_work.sql +31 -0
  12. agent_chat/__init__.py +1 -0
  13. agent_chat/adapter.py +414 -0
  14. agent_chat/admin.py +524 -0
  15. agent_chat/api.py +641 -0
  16. agent_chat/auth.py +226 -0
  17. agent_chat/browser.py +118 -0
  18. agent_chat/browser_verify.py +487 -0
  19. agent_chat/browser_verify_artifacts.py +280 -0
  20. agent_chat/browser_verify_checks.py +236 -0
  21. agent_chat/browser_verify_run.py +523 -0
  22. agent_chat/cli.py +532 -0
  23. agent_chat/client.py +272 -0
  24. agent_chat/deliveries.py +555 -0
  25. agent_chat/events.py +48 -0
  26. agent_chat/feed.py +193 -0
  27. agent_chat/http_boundary.py +154 -0
  28. agent_chat/instance_client.py +349 -0
  29. agent_chat/instance_file.py +207 -0
  30. agent_chat/instance_worker.py +326 -0
  31. agent_chat/mcp/__init__.py +5 -0
  32. agent_chat/mcp/__main__.py +39 -0
  33. agent_chat/mcp/app.py +183 -0
  34. agent_chat/mcp/auth.py +67 -0
  35. agent_chat/mcp/config.py +55 -0
  36. agent_chat/mcp/tools.py +295 -0
  37. agent_chat/metrics.py +60 -0
  38. agent_chat/models.py +430 -0
  39. agent_chat/openapi.py +322 -0
  40. agent_chat/producer.py +208 -0
  41. agent_chat/protocol.py +71 -0
  42. agent_chat/publication.py +252 -0
  43. agent_chat/receipts.py +225 -0
  44. agent_chat/retention.py +154 -0
  45. agent_chat/roles.py +153 -0
  46. agent_chat/rooms.py +179 -0
  47. agent_chat/sessions.py +340 -0
  48. agent_chat/skills/agent-chat/SKILL.md +64 -0
  49. agent_chat/state.py +144 -0
  50. agent_chat/storage.py +110 -0
  51. agent_chat/threads.py +50 -0
  52. agent_chat/web/Manrope-OFL.txt +93 -0
  53. agent_chat/web/Manrope-Variable.ttf +0 -0
  54. agent_chat/web/chat.css +936 -0
  55. agent_chat/web/chat.js +1922 -0
  56. agent_chat/web/i18n.js +340 -0
  57. agent_chat/web/index.html +264 -0
  58. sessionyard-0.7.0.dist-info/METADATA +314 -0
  59. sessionyard-0.7.0.dist-info/RECORD +62 -0
  60. sessionyard-0.7.0.dist-info/WHEEL +4 -0
  61. sessionyard-0.7.0.dist-info/entry_points.txt +3 -0
  62. sessionyard-0.7.0.dist-info/licenses/LICENSE +661 -0
agent_chat/roles.py ADDED
@@ -0,0 +1,153 @@
1
+ """Room role marks: pm (the Forgejo PM), github_pm and delivery_manager.
2
+
3
+ At most one holder per role per room and at most one live role per session. Only the operator sets or clears a
4
+ mark; a mark grants no permission, approval, ordering, lock or scheduling authority. The Forgejo PM's wire
5
+ stamp stays `pm` (the historical value, so existing messages and `--from pm` keep their meaning); the other
6
+ roles stamp their own value. A mark lapses after `ROLE_EXPIRY_HOURS` without its holder's own authenticated
7
+ publication or acknowledgement; expiry is final until the operator sets it again. Every writer holds the event
8
+ clock first, as every mutation does.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any
14
+ from uuid import UUID
15
+
16
+ from psycopg import Connection
17
+
18
+ from . import events
19
+ from .auth import authorize_room, member, require_current
20
+ from .models import ROLE_EXPIRY_HOURS, ROLE_NAMES, ROLE_SELECTORS, Actor, ChatError
21
+
22
+ # The three storage roles; `forgejo-pm`/`forgejo_pm` are aliases of `pm`.
23
+ ROLES = ROLE_NAMES
24
+
25
+
26
+ def canonical(role: str) -> str:
27
+ """The storage role for a selector or storage name; INVALID_REQUEST for anything else."""
28
+ if role in ROLES:
29
+ return role
30
+ try:
31
+ return ROLE_SELECTORS[role]
32
+ except KeyError:
33
+ raise ChatError("INVALID_REQUEST") from None
34
+
35
+
36
+ def current_all(db: Connection[dict[str, Any]], room: UUID) -> dict[str, dict[str, Any] | None]:
37
+ """Every live mark of the room as a role-keyed map; an invalid or expired row reads as None."""
38
+ rows = db.execute(
39
+ """
40
+ SELECT rr.role, rr.session_id, rr.set_at, rr.last_activity_at,
41
+ rr.last_activity_at + make_interval(hours => %(hours)s) AS expires_at
42
+ FROM agent_chat.room_roles rr
43
+ JOIN agent_chat.sessions s ON s.id = rr.session_id
44
+ JOIN agent_chat.principals p ON p.id = s.principal_id AND NOT p.revoked
45
+ JOIN agent_chat.principal_rooms pr ON pr.principal_id = p.id AND pr.room_id = rr.room_id
46
+ JOIN agent_chat.memberships m ON m.session_id = rr.session_id AND m.room_id = rr.room_id
47
+ WHERE rr.room_id = %(room)s AND rr.role = ANY(%(roles)s)
48
+ AND rr.last_activity_at > clock_timestamp() - make_interval(hours => %(hours)s)
49
+ ORDER BY rr.role
50
+ """,
51
+ {"room": room, "roles": list(ROLES), "hours": ROLE_EXPIRY_HOURS},
52
+ ).fetchall()
53
+ fields = ("session_id", "set_at", "last_activity_at", "expires_at")
54
+ live = {row["role"]: {key: row[key] for key in fields} for row in rows}
55
+ return {role: live.get(role) for role in ROLES}
56
+
57
+
58
+ def current(db: Connection[dict[str, Any]], room: UUID, role: str) -> dict[str, Any] | None:
59
+ """The live mark of one role, or None. One definition: `current_all`."""
60
+ return current_all(db, room)[canonical(role)]
61
+
62
+
63
+ def touch(db: Connection[dict[str, Any]], room: UUID, session: UUID) -> list[str]:
64
+ """Extend every live role `session` holds in `room`; return the roles it extended.
65
+
66
+ The holder's authenticated publication or first acknowledgement is the only action that reaches here. The
67
+ caller has already authorized the action; the update and the liveness test are one statement.
68
+ """
69
+ rows = db.execute(
70
+ """
71
+ UPDATE agent_chat.room_roles SET last_activity_at = clock_timestamp()
72
+ WHERE room_id = %s AND session_id = %s
73
+ AND last_activity_at > clock_timestamp() - make_interval(hours => %s)
74
+ RETURNING role
75
+ """,
76
+ (room, session, ROLE_EXPIRY_HOURS),
77
+ ).fetchall()
78
+ return [row["role"] for row in rows]
79
+
80
+
81
+ def stamp(db: Connection[dict[str, Any]], room: UUID, actor: Actor) -> str | None:
82
+ """The wire role to store on a message `actor` is publishing now, or None.
83
+
84
+ Only server state decides it. An operator has no session and so never carries a role. One live role per
85
+ session is enforced by `assign`, so at most one stamp can apply.
86
+ """
87
+ if actor.session_id is None:
88
+ return None
89
+ held = touch(db, room, actor.session_id)
90
+ return held[0] if held else None
91
+
92
+
93
+ def assign(
94
+ db: Connection[dict[str, Any]], actor: Actor, room: UUID, role: str, session: UUID
95
+ ) -> dict[str, Any]:
96
+ """Operator only: make `session` the holder of `role`, replacing that role's previous holder.
97
+
98
+ A session that already holds a different live role is refused with ROLE_CONFLICT: the one-hop layering
99
+ (the delivery manager coordinates the two PMs) requires one role per session.
100
+ """
101
+ target = canonical(role)
102
+ with db.transaction():
103
+ events.lock(db)
104
+ access = authorize_room(db, actor, room)
105
+ if access != "operator":
106
+ raise ChatError("SESSION_FORBIDDEN")
107
+ if not member(db, room, session):
108
+ raise ChatError("INVALID_RECIPIENT")
109
+ held = db.execute(
110
+ """
111
+ SELECT role FROM agent_chat.room_roles
112
+ WHERE room_id = %s AND session_id = %s
113
+ AND last_activity_at > clock_timestamp() - make_interval(hours => %s)
114
+ FOR UPDATE
115
+ """,
116
+ (room, session, ROLE_EXPIRY_HOURS),
117
+ ).fetchall()
118
+ if any(row["role"] != target for row in held):
119
+ raise ChatError("ROLE_CONFLICT")
120
+ db.execute(
121
+ """
122
+ INSERT INTO agent_chat.room_roles (room_id, role, session_id, set_at, last_activity_at)
123
+ SELECT %s::uuid, %s::text, %s::uuid, clock.t, clock.t
124
+ FROM (SELECT clock_timestamp() AS t) AS clock
125
+ ON CONFLICT (room_id, role) DO UPDATE SET
126
+ session_id = EXCLUDED.session_id, set_at = EXCLUDED.set_at,
127
+ last_activity_at = EXCLUDED.last_activity_at
128
+ """,
129
+ (room, target, session),
130
+ )
131
+ require_current(db, actor, access)
132
+ return {"room_id": room, "roles": current_all(db, room)}
133
+
134
+
135
+ def clear(
136
+ db: Connection[dict[str, Any]], actor: Actor, room: UUID, role: str, session: UUID
137
+ ) -> dict[str, Any]:
138
+ """Operator only: remove the live mark of `role`, which must be `session`'s. Anything else is NOT_FOUND."""
139
+ target = canonical(role)
140
+ with db.transaction():
141
+ events.lock(db)
142
+ access = authorize_room(db, actor, room)
143
+ if access != "operator":
144
+ raise ChatError("SESSION_FORBIDDEN")
145
+ live = current(db, room, target)
146
+ if live is None or live["session_id"] != session:
147
+ raise ChatError("NOT_FOUND")
148
+ db.execute(
149
+ "DELETE FROM agent_chat.room_roles WHERE room_id = %s AND role = %s AND session_id = %s",
150
+ (room, target, session),
151
+ )
152
+ require_current(db, actor, access)
153
+ return {"room_id": room, "roles": current_all(db, room)}
agent_chat/rooms.py ADDED
@@ -0,0 +1,179 @@
1
+ """Operator room administration never expands another principal's credential scope."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+ from uuid import UUID, uuid4
7
+
8
+ from psycopg import Connection
9
+
10
+ from . import roles
11
+ from .auth import authorize_room, lock_actor, require_current
12
+ from .models import LEASE_SECONDS, Actor, ChatError, RoomCreation, pr_ref_parts
13
+
14
+
15
+ def visible(db: Connection[dict[str, Any]], actor: Actor, *, read: bool = False) -> list[dict[str, Any]]:
16
+ """Granted rooms, narrowed to joined rooms for an instance. Viewer reads must opt in."""
17
+ with db.transaction():
18
+ access = lock_actor(db, actor, allow_closed=True, read=read)
19
+ granted = db.execute(
20
+ """
21
+ SELECT r.id, r.slug, r.label FROM agent_chat.rooms r
22
+ JOIN agent_chat.principal_rooms pr ON pr.room_id = r.id
23
+ WHERE pr.principal_id = %s ORDER BY r.slug FOR SHARE OF r, pr
24
+ """,
25
+ (actor.principal_id,),
26
+ ).fetchall()
27
+ if access in ("operator", "viewer"):
28
+ require_current(db, actor, access)
29
+ return granted
30
+ # Keep grant-before-membership lock order, as authorize_room does. A stream
31
+ # batch must not lose its authorization between listing rooms and reading events.
32
+ memberships = db.execute(
33
+ "SELECT room_id FROM agent_chat.memberships WHERE session_id = %s FOR SHARE", (actor.session_id,)
34
+ ).fetchall()
35
+ # Grant and membership locks can block; refuse an expired lease only once they are held.
36
+ require_current(db, actor, access)
37
+ joined = {row["room_id"] for row in memberships}
38
+ return [row for row in granted if row["id"] in joined]
39
+
40
+
41
+ def create(db: Connection[dict[str, Any]], actor: Actor, request: RoomCreation) -> dict[str, Any]:
42
+ with db.transaction():
43
+ access = lock_actor(db, actor)
44
+ if access != "operator":
45
+ raise ChatError("SESSION_FORBIDDEN")
46
+ created = db.execute(
47
+ """
48
+ INSERT INTO agent_chat.rooms(id, slug, label) VALUES (%s, %s, %s)
49
+ ON CONFLICT (slug) DO NOTHING RETURNING id, slug, label
50
+ """,
51
+ (uuid4(), request.slug, request.label),
52
+ ).fetchone()
53
+ if created is not None:
54
+ db.execute("INSERT INTO agent_chat.principal_rooms VALUES (%s, %s)", (actor.principal_id, created["id"]))
55
+ require_current(db, actor, access)
56
+ return created
57
+ existing = db.execute(
58
+ """
59
+ SELECT r.id, r.slug, r.label FROM agent_chat.rooms r
60
+ JOIN agent_chat.principal_rooms pr ON pr.room_id = r.id
61
+ WHERE r.slug = %s AND pr.principal_id = %s AND r.label = %s
62
+ """,
63
+ (request.slug, actor.principal_id, request.label),
64
+ ).fetchone()
65
+ require_current(db, actor, access)
66
+ if existing is None:
67
+ raise ChatError("ROOM_CONFLICT")
68
+ return existing
69
+
70
+
71
+ def join(db: Connection[dict[str, Any]], actor: Actor, room: UUID, session: UUID) -> dict[str, Any]:
72
+ with db.transaction():
73
+ access = authorize_room(db, actor, room)
74
+ if access != "operator":
75
+ raise ChatError("SESSION_FORBIDDEN")
76
+ permitted = db.execute(
77
+ """
78
+ SELECT s.id FROM agent_chat.sessions s JOIN agent_chat.principals p ON p.id = s.principal_id
79
+ JOIN agent_chat.principal_rooms pr ON pr.principal_id = p.id
80
+ WHERE s.id = %s AND pr.room_id = %s AND NOT p.revoked FOR SHARE OF s, p, pr
81
+ """,
82
+ (session, room),
83
+ ).fetchone()
84
+ require_current(db, actor, access)
85
+ if permitted is None:
86
+ raise ChatError("INVALID_RECIPIENT")
87
+ db.execute("INSERT INTO agent_chat.memberships VALUES (%s, %s) ON CONFLICT DO NOTHING", (room, session))
88
+ require_current(db, actor, access)
89
+ return {"room_id": room, "session_id": session}
90
+
91
+
92
+ def participants(
93
+ db: Connection[dict[str, Any]],
94
+ actor: Actor,
95
+ room: UUID,
96
+ after: UUID | None = None,
97
+ limit: int = 100,
98
+ online: bool = False,
99
+ ) -> dict[str, Any]:
100
+ """Roster page by session id. `online` keeps only open instances inside the lease, before paging."""
101
+ if not 1 <= limit <= 100:
102
+ raise ChatError("INVALID_REQUEST")
103
+ with db.transaction():
104
+ authorize_room(db, actor, room, read=True)
105
+ rows = db.execute(
106
+ """
107
+ SELECT s.id AS session_id, s.label, s.title, p.host, p.harness, s.native_session_id,
108
+ s.muted, i.id AS instance_id, i.heartbeat_at,
109
+ COALESCE(i.heartbeat_at > clock_timestamp() - make_interval(secs => %(lease)s), false) AS online,
110
+ i.native_state, i.stopped, i.plan_mode,
111
+ i.lane, i.lane_since,
112
+ floor(extract(epoch FROM clock_timestamp() - i.lane_since))::integer AS lane_age_seconds,
113
+ COALESCE(i.repositories, '{}'::jsonb) AS repositories,
114
+ (SELECT max(m.created_at) FROM agent_chat.messages m
115
+ WHERE m.sender_session_id = s.id AND m.room_id = %(room)s AND m.body IS NOT NULL)
116
+ AS last_published_at,
117
+ (SELECT count(*) FROM agent_chat.messages m
118
+ WHERE m.sender_session_id = s.id AND m.room_id = %(room)s AND m.body IS NOT NULL
119
+ AND m.created_at > clock_timestamp() - interval '24 hours') AS messages_24h,
120
+ COALESCE(announced.refs, '[]'::jsonb) AS announced_refs
121
+ FROM agent_chat.memberships m JOIN agent_chat.sessions s ON s.id = m.session_id
122
+ JOIN agent_chat.principals p ON p.id = s.principal_id
123
+ JOIN agent_chat.principal_rooms pr ON pr.principal_id = p.id AND pr.room_id = m.room_id
124
+ LEFT JOIN agent_chat.instances i ON i.session_id = s.id AND i.ended_at IS NULL
125
+ LEFT JOIN LATERAL (
126
+ SELECT jsonb_agg(jsonb_build_object('ref_key', x.ref_key, 'created_at', x.created_at)
127
+ ORDER BY x.created_at DESC) AS refs
128
+ FROM (
129
+ SELECT t.ref_key, root.created_at
130
+ FROM agent_chat.threads t
131
+ JOIN agent_chat.messages root ON root.id = t.root_message_id
132
+ WHERE t.room_id = %(room)s AND t.ref_key LIKE 'pr:%%' AND root.sender_session_id = s.id
133
+ ORDER BY root.created_at DESC
134
+ LIMIT 20
135
+ ) x
136
+ ) announced ON true
137
+ WHERE m.room_id = %(room)s AND NOT p.revoked AND (%(after)s::uuid IS NULL OR s.id > %(after)s)
138
+ AND (NOT %(online)s::boolean OR COALESCE(i.heartbeat_at > clock_timestamp()
139
+ - make_interval(secs => %(lease)s), false))
140
+ ORDER BY s.id LIMIT %(limit)s
141
+ """,
142
+ {
143
+ "lease": LEASE_SECONDS,
144
+ "room": room,
145
+ "after": after,
146
+ "online": online,
147
+ "limit": limit + 1,
148
+ },
149
+ ).fetchall()
150
+ page = rows[:limit]
151
+ for row in page:
152
+ announced = []
153
+ for ref in row.pop("announced_refs") or []:
154
+ parts = pr_ref_parts(ref["ref_key"])
155
+ if parts is not None:
156
+ announced.append(
157
+ {
158
+ "ref_key": ref["ref_key"],
159
+ "repository": parts[0],
160
+ "number": parts[1],
161
+ "created_at": ref["created_at"],
162
+ }
163
+ )
164
+ row["announced_prs"] = announced
165
+ # A lapsed lease cannot resume (only a fresh join revives the session): never report its last beat.
166
+ # The work declaration belongs to the live instance, so an offline row keeps its historical lane
167
+ # but reports no repositories; otherwise abandoned work would look current.
168
+ if not row["online"]:
169
+ row["native_state"] = "unknown"
170
+ row["stopped"] = row["plan_mode"] = True
171
+ row["repositories"] = {}
172
+ # The mark is a room fact: it does not depend on the page, the `online` filter or the holder's lease.
173
+ live = roles.current_all(db, room)
174
+ return {
175
+ "participants": page,
176
+ "next_session_id": page[-1]["session_id"] if len(rows) > limit else None,
177
+ "roles": live,
178
+ "pm": live["pm"],
179
+ }
agent_chat/sessions.py ADDED
@@ -0,0 +1,340 @@
1
+ """Logical sessions survive resume; a process binding never does."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+ from uuid import UUID, uuid4
7
+
8
+ from psycopg import Connection
9
+ from psycopg.errors import UniqueViolation
10
+ from psycopg.types.json import Jsonb
11
+
12
+ from . import deliveries, events
13
+ from .auth import lock_actor, lock_agent, require_current
14
+ from .models import (
15
+ LEASE_SECONDS,
16
+ MAX_LIVE_INSTANCES_PER_PRINCIPAL,
17
+ MAX_REGISTRATIONS_PER_PRINCIPAL_HOUR,
18
+ QUOTA_WINDOW_SECONDS,
19
+ Actor,
20
+ ChatError,
21
+ Heartbeat,
22
+ LaneDeclaration,
23
+ Registration,
24
+ WorkDeclaration,
25
+ )
26
+ from .protocol import session_label
27
+ from .rooms import visible
28
+
29
+
30
+ def _quota(db: Connection[dict[str, Any]], principal: UUID) -> None:
31
+ """Refuse a new instance beyond the principal's live or hourly caps; `register` holds the principal's lock."""
32
+ live = db.execute(
33
+ """
34
+ SELECT count(*) AS n FROM agent_chat.instances i JOIN agent_chat.sessions s ON s.id = i.session_id
35
+ WHERE s.principal_id = %s AND i.ended_at IS NULL
36
+ AND i.heartbeat_at > clock_timestamp() - make_interval(secs => %s)
37
+ """,
38
+ (principal, LEASE_SECONDS),
39
+ ).fetchone()
40
+ recent = db.execute(
41
+ """
42
+ SELECT count(*) AS n FROM agent_chat.instances i JOIN agent_chat.sessions s ON s.id = i.session_id
43
+ WHERE s.principal_id = %s AND i.created_at > clock_timestamp() - make_interval(secs => %s)
44
+ """,
45
+ (principal, QUOTA_WINDOW_SECONDS),
46
+ ).fetchone()
47
+ assert live is not None and recent is not None
48
+ if live["n"] >= MAX_LIVE_INSTANCES_PER_PRINCIPAL:
49
+ raise ChatError("INSTANCE_LIMIT")
50
+ if recent["n"] >= MAX_REGISTRATIONS_PER_PRINCIPAL_HOUR:
51
+ raise ChatError("REGISTRATION_LIMIT")
52
+
53
+
54
+ def register(db: Connection[dict[str, Any]], actor: Actor, request: Registration) -> dict[str, Any]:
55
+ if actor.session_id is not None or actor.instance_id is not None:
56
+ raise ChatError("SESSION_FORBIDDEN")
57
+ try:
58
+ with db.transaction():
59
+ principal = db.execute(
60
+ """
61
+ SELECT host, harness FROM agent_chat.principals
62
+ WHERE id = %s AND kind = 'agent' AND NOT revoked FOR SHARE
63
+ """,
64
+ (actor.principal_id,),
65
+ ).fetchone()
66
+ if principal is None:
67
+ raise ChatError("UNAUTHENTICATED")
68
+ # Shared principal locks do not exclude one another. This lock serializes one principal's registrations
69
+ # so the quota counts are exact. It follows the principal lock and precedes every session and instance
70
+ # lock, so no registration waits on it while holding a row its holder needs.
71
+ db.execute(
72
+ "SELECT pg_advisory_xact_lock(hashtextextended('agent_chat.register:' || %s::text, 0))",
73
+ (actor.principal_id,),
74
+ )
75
+ room = db.execute(
76
+ """
77
+ SELECT r.id FROM agent_chat.rooms r JOIN agent_chat.principal_rooms pr ON pr.room_id = r.id
78
+ WHERE r.slug = 'homelab' AND pr.principal_id = %s FOR SHARE OF pr
79
+ """,
80
+ (actor.principal_id,),
81
+ ).fetchone()
82
+ if room is None:
83
+ raise ChatError("ROOM_FORBIDDEN")
84
+ if (
85
+ db.execute(
86
+ "SELECT 1 FROM agent_chat.principals WHERE credential_hash = %s", (request.instance_token_hash,)
87
+ ).fetchone()
88
+ is not None
89
+ ):
90
+ raise ChatError("BINDING_CONFLICT")
91
+ # Prune takes the event clock before its membership snapshot, so this
92
+ # registration takes the same lock before its session and instance
93
+ # writes: a batch that saw no open instance cannot then delete the
94
+ # membership the new instance relies on. Taken after the
95
+ # grant read, not while a room grant is waited on.
96
+ events.lock(db)
97
+ db.execute(
98
+ """
99
+ INSERT INTO agent_chat.sessions(id, principal_id, native_session_id, label)
100
+ VALUES (%s, %s, %s, %s) ON CONFLICT (principal_id, native_session_id) DO NOTHING
101
+ """,
102
+ (
103
+ uuid4(),
104
+ actor.principal_id,
105
+ request.native_session_id,
106
+ session_label(principal["harness"], principal["host"], request.native_session_id),
107
+ ),
108
+ )
109
+ session = db.execute(
110
+ """
111
+ SELECT id FROM agent_chat.sessions WHERE principal_id = %s AND native_session_id = %s FOR UPDATE
112
+ """,
113
+ (actor.principal_id, request.native_session_id),
114
+ ).fetchone()
115
+ assert session is not None
116
+ previous = db.execute(
117
+ """
118
+ SELECT id, token_hash, ended_at IS NULL AND
119
+ heartbeat_at > clock_timestamp() - make_interval(secs => %s) AS live
120
+ FROM agent_chat.instances WHERE session_id = %s AND boot_id = %s FOR UPDATE
121
+ """,
122
+ (LEASE_SECONDS, session["id"], request.boot_id),
123
+ ).fetchone()
124
+ if previous is not None:
125
+ if previous["token_hash"] != request.instance_token_hash:
126
+ raise ChatError("BINDING_CONFLICT")
127
+ if not previous["live"]:
128
+ raise ChatError("STALE_INSTANCE")
129
+ instance_id = previous["id"]
130
+ else:
131
+ current = db.execute(
132
+ """
133
+ SELECT id, heartbeat_at > clock_timestamp() - make_interval(secs => %s) AS live
134
+ FROM agent_chat.instances WHERE session_id = %s AND ended_at IS NULL FOR UPDATE
135
+ """,
136
+ (LEASE_SECONDS, session["id"]),
137
+ ).fetchone()
138
+ if current is not None:
139
+ if current["live"]:
140
+ raise ChatError("BINDING_CONFLICT")
141
+ db.execute(
142
+ "UPDATE agent_chat.instances SET ended_at = clock_timestamp() WHERE id = %s", (current["id"],)
143
+ )
144
+ _quota(db, actor.principal_id)
145
+ instance_id = uuid4()
146
+ db.execute(
147
+ """
148
+ INSERT INTO agent_chat.instances(id, session_id, boot_id, token_hash, lane, lane_since)
149
+ VALUES (%s, %s, %s, %s, %s::text, CASE WHEN %s::text IS NULL THEN NULL ELSE clock_timestamp() END)
150
+ """,
151
+ (
152
+ instance_id,
153
+ session["id"],
154
+ request.boot_id,
155
+ request.instance_token_hash,
156
+ request.lane,
157
+ request.lane,
158
+ ),
159
+ )
160
+ db.execute(
161
+ "INSERT INTO agent_chat.memberships VALUES (%s, %s) ON CONFLICT DO NOTHING",
162
+ (room["id"], session["id"]),
163
+ )
164
+ return {
165
+ "session_id": session["id"],
166
+ "instance_id": instance_id,
167
+ "room_id": room["id"],
168
+ "host": principal["host"],
169
+ "harness": principal["harness"],
170
+ }
171
+ except UniqueViolation:
172
+ # A reused token hash conflicts; its value never enters an HTTP error or log.
173
+ raise ChatError("BINDING_CONFLICT") from None
174
+
175
+
176
+ def heartbeat(db: Connection[dict[str, Any]], actor: Actor, request: Heartbeat) -> dict[str, Any]:
177
+ with db.transaction():
178
+ # Take the session lock exclusively up front: no SHARE-to-UPDATE upgrade
179
+ # against concurrent heartbeat/registration. Only this live instance owns its title.
180
+ if lock_actor(db, actor, exclusive_session="title" in request.model_fields_set) != "instance":
181
+ raise ChatError("SESSION_FORBIDDEN")
182
+ if "title" in request.model_fields_set:
183
+ db.execute(
184
+ "UPDATE agent_chat.sessions SET title = %s WHERE id = %s AND title IS DISTINCT FROM %s",
185
+ (request.title, actor.session_id, request.title),
186
+ )
187
+ row = db.execute(
188
+ """
189
+ UPDATE agent_chat.instances SET heartbeat_at = clock_timestamp(), native_state = %s,
190
+ stopped = %s, plan_mode = %s WHERE id = %s
191
+ RETURNING id AS instance_id, heartbeat_at, native_state, stopped, plan_mode
192
+ """,
193
+ (request.native_state, request.stopped, request.plan_mode, actor.instance_id),
194
+ ).fetchone()
195
+ assert row is not None
196
+ return row
197
+
198
+
199
+ def declare_work(db: Connection[dict[str, Any]], actor: Actor, request: WorkDeclaration) -> dict[str, Any]:
200
+ """Set or clear the live instance's advisory work map. Nothing reads it for authorization or delivery."""
201
+ with db.transaction():
202
+ lock_agent(db, actor)
203
+ row = db.execute(
204
+ """
205
+ UPDATE agent_chat.instances SET repositories = %s::jsonb
206
+ WHERE id = %s
207
+ RETURNING id AS instance_id, repositories
208
+ """,
209
+ (Jsonb(request.repositories), actor.instance_id),
210
+ ).fetchone()
211
+ assert row is not None
212
+ return row
213
+
214
+
215
+ def declare_lane(db: Connection[dict[str, Any]], actor: Actor, request: LaneDeclaration) -> dict[str, Any]:
216
+ """Set or clear the advisory lane. Nothing reads it for authorization, delivery or admission."""
217
+ with db.transaction():
218
+ lock_agent(db, actor)
219
+ # `lane_since` moves only when the value changes; a repeat keeps the declaration's age.
220
+ row = db.execute(
221
+ """
222
+ UPDATE agent_chat.instances
223
+ SET lane = %s::text,
224
+ lane_since = CASE WHEN %s::text IS NULL THEN NULL
225
+ WHEN lane IS DISTINCT FROM %s::text THEN clock_timestamp() ELSE lane_since END
226
+ WHERE id = %s
227
+ RETURNING id AS instance_id, lane, lane_since,
228
+ floor(extract(epoch FROM clock_timestamp() - lane_since))::integer AS lane_age_seconds
229
+ """,
230
+ (request.lane, request.lane, request.lane, actor.instance_id),
231
+ ).fetchone()
232
+ assert row is not None
233
+ return row
234
+
235
+
236
+ def end(db: Connection[dict[str, Any]], actor: Actor) -> dict[str, Any]:
237
+ with db.transaction():
238
+ # End also settles abandoned reservations; preserve clock-first ordering.
239
+ events.lock(db)
240
+ # A repeated end may close only this same old binding, never its replacement.
241
+ lock_agent(db, actor, allow_closed=True)
242
+ row = db.execute(
243
+ """
244
+ UPDATE agent_chat.instances SET ended_at = COALESCE(ended_at, clock_timestamp()),
245
+ native_state = 'unknown', stopped = true, plan_mode = true WHERE id = %s
246
+ RETURNING id AS instance_id, ended_at
247
+ """,
248
+ (actor.instance_id,),
249
+ ).fetchone()
250
+ assert row is not None
251
+ deliveries.reconcile(db, instance_id=actor.instance_id)
252
+ return row
253
+
254
+
255
+ def status(db: Connection[dict[str, Any]], actor: Actor, *, delivery_enabled: bool = False) -> dict[str, Any]:
256
+ with db.transaction():
257
+ events.read_clock(db)
258
+ lock_agent(db, actor)
259
+ allowed = visible(db, actor)
260
+ state = db.execute(
261
+ """
262
+ SELECT s.id AS session_id, s.label, s.title, s.muted, i.id AS instance_id,
263
+ i.heartbeat_at, i.native_state, i.stopped, i.plan_mode, i.lane, i.lane_since, i.repositories,
264
+ floor(extract(epoch FROM clock_timestamp() - i.lane_since))::integer AS lane_age_seconds,
265
+ i.heartbeat_at > clock_timestamp() - make_interval(secs => %s) AS online
266
+ FROM agent_chat.sessions s JOIN agent_chat.instances i ON i.session_id = s.id
267
+ WHERE i.id = %s
268
+ """,
269
+ (LEASE_SECONDS, actor.instance_id),
270
+ ).fetchone()
271
+ assert state is not None
272
+ counts = db.execute(
273
+ """
274
+ SELECT count(*) FILTER (WHERE r.uncertainty_reason IS NULL) AS pending,
275
+ count(*) FILTER (WHERE r.uncertainty_reason IS NOT NULL) AS uncertain
276
+ FROM agent_chat.recipients r JOIN agent_chat.messages m ON m.id = r.message_id
277
+ WHERE r.session_id = %s AND m.room_id = ANY(%s::uuid[])
278
+ AND m.body IS NOT NULL AND m.expires_at > clock_timestamp()
279
+ AND r.acknowledged_at IS NULL AND r.replying_message_id IS NULL
280
+ """,
281
+ (actor.session_id, [room["id"] for room in allowed]),
282
+ ).fetchone()
283
+ state.update(counts or {})
284
+ assert actor.session_id is not None
285
+ state.update(
286
+ rooms=allowed,
287
+ delivery_supported=delivery_enabled,
288
+ wake_budget=deliveries.budget(db, actor.session_id) if delivery_enabled else None,
289
+ )
290
+ return state
291
+
292
+
293
+ def mute(db: Connection[dict[str, Any]], actor: Actor, session: UUID, muted: bool) -> dict[str, Any]:
294
+ with db.transaction():
295
+ events.lock(db)
296
+ # Self mutation needs the session UPDATE lock before the instance lock.
297
+ # Upgrading SHARE afterwards would deadlock against a concurrent heartbeat.
298
+ access = lock_actor(db, actor, exclusive_session=True)
299
+ operator = access == "operator"
300
+ if not operator and actor.session_id != session:
301
+ raise ChatError("SESSION_FORBIDDEN")
302
+ if operator:
303
+ owner = db.execute("SELECT principal_id FROM agent_chat.sessions WHERE id = %s", (session,)).fetchone()
304
+ if (
305
+ owner is None
306
+ or db.execute(
307
+ "SELECT id FROM agent_chat.principals WHERE id = %s AND NOT revoked FOR SHARE",
308
+ (owner["principal_id"],),
309
+ ).fetchone()
310
+ is None
311
+ ):
312
+ raise ChatError("NOT_FOUND")
313
+ target = db.execute(
314
+ "SELECT principal_id, muted FROM agent_chat.sessions WHERE id = %s FOR UPDATE", (session,)
315
+ ).fetchone()
316
+ if target is None:
317
+ raise ChatError("NOT_FOUND")
318
+ target_rooms = db.execute(
319
+ """
320
+ SELECT m.room_id FROM agent_chat.memberships m
321
+ JOIN agent_chat.principal_rooms pr ON pr.room_id = m.room_id
322
+ JOIN agent_chat.principals p ON p.id = pr.principal_id
323
+ WHERE m.session_id = %s AND pr.principal_id = %s AND NOT p.revoked
324
+ FOR SHARE OF pr, m, p
325
+ """,
326
+ (session, target["principal_id"]),
327
+ ).fetchall()
328
+ room_ids = {row["room_id"] for row in target_rooms}
329
+ if operator:
330
+ permitted = {row["id"] for row in visible(db, actor)}
331
+ # This is one global session flag; partial room access cannot authorize
332
+ # changing that flag for hidden rooms.
333
+ if not room_ids or not room_ids.issubset(permitted):
334
+ raise ChatError("NOT_FOUND")
335
+ require_current(db, actor, access)
336
+ if target["muted"] != muted:
337
+ db.execute("UPDATE agent_chat.sessions SET muted = %s WHERE id = %s", (muted, session))
338
+ for room in sorted(room_ids):
339
+ events.append(db, room, "control", session=session)
340
+ return {"session_id": session, "muted": muted}