fivefold 0.1.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.
- fivefold/__init__.py +4 -0
- fivefold/_data/db/bootstrap.sql +26 -0
- fivefold/_data/db/migrations/0001_schemas.sql +67 -0
- fivefold/_data/db/migrations/0002_gateway.sql +224 -0
- fivefold/_data/db/migrations/0003_gateway_record_0010.sql +91 -0
- fivefold/_data/db/migrations/0004_harness.sql +141 -0
- fivefold/_data/db/migrations/0005_sim.sql +679 -0
- fivefold/_data/db/migrations/0006_gateway_reads.sql +66 -0
- fivefold/_data/db/migrations/0007_eval.sql +33 -0
- fivefold/_data/db/migrations/0008_run_stop.sql +18 -0
- fivefold/_data/db/migrations/0009_message_copies.sql +69 -0
- fivefold/_data/db/migrations/0010_gateway_g1_check.sql +14 -0
- fivefold/_data/db/migrations/0011_model_calls.sql +37 -0
- fivefold/_data/db/migrations/0012_recovery_latency.sql +23 -0
- fivefold/_data/db/migrations/0013_split_topology.sql +33 -0
- fivefold/_data/db/migrations/0014_tool_call_args.sql +20 -0
- fivefold/_data/db/registry/0001_registry.sql +31 -0
- fivefold/_data/faults/expected.yaml +406 -0
- fivefold/_data/scenarios/dev/dev-001-single-po.yaml +45 -0
- fivefold/_data/scenarios/dev/dev-002-human-approval.yaml +47 -0
- fivefold/agents/__init__.py +7 -0
- fivefold/agents/branch.py +187 -0
- fivefold/agents/checkpoint.py +77 -0
- fivefold/agents/connection.py +153 -0
- fivefold/agents/live.py +492 -0
- fivefold/agents/policy.py +426 -0
- fivefold/agents/remote.py +333 -0
- fivefold/agents/replay.py +170 -0
- fivefold/agents/scripted.py +122 -0
- fivefold/agents/tools.py +229 -0
- fivefold/agents/worker.py +164 -0
- fivefold/domain/__init__.py +5 -0
- fivefold/domain/api.py +517 -0
- fivefold/domain/authority.py +149 -0
- fivefold/domain/contracts.py +80 -0
- fivefold/domain/identity.py +113 -0
- fivefold/domain/prices.py +178 -0
- fivefold/domain/report.py +92 -0
- fivefold/domain/rules.py +346 -0
- fivefold/domain/scenario.py +524 -0
- fivefold/evaluator/__init__.py +155 -0
- fivefold/evaluator/__main__.py +127 -0
- fivefold/evaluator/authorization.py +146 -0
- fivefold/evaluator/checks.py +331 -0
- fivefold/evaluator/evaluate.py +109 -0
- fivefold/evaluator/evidence.py +392 -0
- fivefold/evaluator/freshness.py +136 -0
- fivefold/evaluator/liveness.py +236 -0
- fivefold/evaluator/load.py +354 -0
- fivefold/evaluator/metrics.py +95 -0
- fivefold/evaluator/records.py +452 -0
- fivefold/evaluator/recovery.py +209 -0
- fivefold/evaluator/report.py +1096 -0
- fivefold/evaluator/result.py +344 -0
- fivefold/evaluator/store.py +83 -0
- fivefold/faults/__init__.py +5 -0
- fivefold/faults/catalog.py +278 -0
- fivefold/faults/plan.py +538 -0
- fivefold/gateway/__init__.py +6 -0
- fivefold/gateway/admin.py +179 -0
- fivefold/gateway/admin_api.py +398 -0
- fivefold/gateway/codec.py +372 -0
- fivefold/gateway/destination.py +64 -0
- fivefold/gateway/dispatcher.py +379 -0
- fivefold/gateway/freshness.py +83 -0
- fivefold/gateway/invariants.py +761 -0
- fivefold/gateway/memory.py +277 -0
- fivefold/gateway/pg_store.py +657 -0
- fivefold/gateway/records.py +592 -0
- fivefold/gateway/server.py +102 -0
- fivefold/gateway/sim_client.py +295 -0
- fivefold/gateway/state_machine.py +376 -0
- fivefold/gateway/steps.py +897 -0
- fivefold/gateway/store.py +635 -0
- fivefold/gateway/tools.py +424 -0
- fivefold/gateway/twin.py +199 -0
- fivefold/gateway/wire.py +138 -0
- fivefold/harness/__init__.py +6 -0
- fivefold/harness/actors.py +230 -0
- fivefold/harness/cells.py +303 -0
- fivefold/harness/clock.py +209 -0
- fivefold/harness/demo.py +397 -0
- fivefold/harness/fault_effects.py +122 -0
- fivefold/harness/live_options.py +159 -0
- fivefold/harness/log.py +540 -0
- fivefold/harness/mcp_link.py +409 -0
- fivefold/harness/migrations.py +520 -0
- fivefold/harness/models.py +368 -0
- fivefold/harness/registry.py +105 -0
- fivefold/harness/reports.py +100 -0
- fivefold/harness/rng.py +57 -0
- fivefold/harness/run.py +881 -0
- fivefold/harness/scheduler.py +441 -0
- fivefold/harness/sim_points.py +215 -0
- fivefold/harness/split/__init__.py +34 -0
- fivefold/harness/split/__main__.py +275 -0
- fivefold/harness/split/credentials.py +74 -0
- fivefold/harness/split/faults.py +75 -0
- fivefold/harness/split/gateway.py +769 -0
- fivefold/harness/split/hops.py +291 -0
- fivefold/harness/split/lifecycle.py +322 -0
- fivefold/harness/split/rundir.py +152 -0
- fivefold/harness/split/service.py +157 -0
- fivefold/harness/split/simulator.py +432 -0
- fivefold/harness/study.py +643 -0
- fivefold/harness/transport.py +533 -0
- fivefold/paths.py +24 -0
- fivefold/py.typed +0 -0
- fivefold/recorder/__init__.py +18 -0
- fivefold/recorder/__main__.py +308 -0
- fivefold/recorder/cassette.py +322 -0
- fivefold/recorder/playback.py +316 -0
- fivefold/recorder/recording.py +133 -0
- fivefold/sim/__init__.py +37 -0
- fivefold/sim/config.py +52 -0
- fivefold/sim/endpoint.py +176 -0
- fivefold/sim/ledger.py +583 -0
- fivefold/sim/service.py +834 -0
- fivefold/viewer/__init__.py +14 -0
- fivefold/viewer/__main__.py +75 -0
- fivefold/viewer/app.py +122 -0
- fivefold/viewer/records.py +108 -0
- fivefold/viewer/source.py +196 -0
- fivefold/viewer/timeline.py +61 -0
- fivefold-0.1.0.dist-info/METADATA +169 -0
- fivefold-0.1.0.dist-info/RECORD +128 -0
- fivefold-0.1.0.dist-info/WHEEL +4 -0
- fivefold-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
"""Gateway records, step inputs and agent-facing results (0001, 0002, 0003).
|
|
2
|
+
|
|
3
|
+
The record types mirror the `gw` tables in record 0003's data model. Stores build them,
|
|
4
|
+
step functions read and replace them, and the invariant checks read nothing else. All
|
|
5
|
+
records are immutable; mappings inside them are read-only views.
|
|
6
|
+
|
|
7
|
+
Two fields go beyond the data model, as implementation detail:
|
|
8
|
+
|
|
9
|
+
- `CheckRecord.seen_seq`: the seq of the action's latest event when the dispatch check
|
|
10
|
+
began. A send commits only if no event was added since (0003, dispatch; I3).
|
|
11
|
+
- `ToolCall.as_of_seq`: the event seq a response reflects, which I5 compares against.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import Mapping
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from enum import StrEnum
|
|
19
|
+
from types import MappingProxyType
|
|
20
|
+
|
|
21
|
+
from fivefold.domain.contracts import Capability, Contract
|
|
22
|
+
from fivefold.gateway.state_machine import (
|
|
23
|
+
ANSWER_REASONS,
|
|
24
|
+
ActionState,
|
|
25
|
+
AnswerClass,
|
|
26
|
+
CheckKind,
|
|
27
|
+
EventKind,
|
|
28
|
+
GrantState,
|
|
29
|
+
Note,
|
|
30
|
+
Reason,
|
|
31
|
+
ReconcileHow,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def frozen[K, V](mapping: Mapping[K, V]) -> Mapping[K, V]:
|
|
36
|
+
"""Return a read-only copy of `mapping`."""
|
|
37
|
+
return MappingProxyType(dict(mapping))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
NO_VERSIONS: Mapping[str, int] = MappingProxyType({})
|
|
41
|
+
NO_DETAILS: Mapping[str, object] = MappingProxyType({})
|
|
42
|
+
NO_ARGS: Mapping[str, object] = MappingProxyType({})
|
|
43
|
+
"""The arguments of a call that has none."""
|
|
44
|
+
|
|
45
|
+
# Records -------------------------------------------------------------------------------
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Action:
|
|
50
|
+
"""One logical effect (0001, 0003). `identity` is on in G2 and off in G1 (0008).
|
|
51
|
+
|
|
52
|
+
`idempotency_key` is the action's own key, its id, in both configurations. A request
|
|
53
|
+
carries it only where a contract takes keys (C2, C3) and only in G2 (0005, 0008).
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
action_id: str
|
|
57
|
+
task_id: str
|
|
58
|
+
intent_id: str
|
|
59
|
+
operation: str
|
|
60
|
+
target: str
|
|
61
|
+
args: Mapping[str, str | int]
|
|
62
|
+
action_key: str
|
|
63
|
+
identity: bool
|
|
64
|
+
contract: Contract
|
|
65
|
+
basis: Mapping[str, int]
|
|
66
|
+
state: ActionState
|
|
67
|
+
grant_id: str | None
|
|
68
|
+
idempotency_key: str
|
|
69
|
+
effect_id: str | None
|
|
70
|
+
created_vt: int
|
|
71
|
+
updated_vt: int
|
|
72
|
+
"""The virtual time of the latest state change; notes do not change it."""
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def authorization_only(self) -> bool:
|
|
76
|
+
"""Whether this is a G1 action: one with identity off (0003, 0008).
|
|
77
|
+
|
|
78
|
+
G1 is authorization only. It files one approval request per write call, checks the
|
|
79
|
+
approval and no fact before its one send, and has no idempotency keys, status
|
|
80
|
+
probes, retries, escalation, report checks or run closing.
|
|
81
|
+
"""
|
|
82
|
+
return not self.identity
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def request_key(self) -> str | None:
|
|
86
|
+
"""The idempotency key a request for this action carries, if any (0005, 0008)."""
|
|
87
|
+
if self.authorization_only or not self.contract.has(Capability.IDEMPOTENCY_KEY):
|
|
88
|
+
return None
|
|
89
|
+
return self.idempotency_key
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True)
|
|
93
|
+
class Grant:
|
|
94
|
+
"""The binding of one approval to one action (0002, rules 12 to 16)."""
|
|
95
|
+
|
|
96
|
+
grant_id: str
|
|
97
|
+
action_id: str
|
|
98
|
+
approval_id: str
|
|
99
|
+
state: GrantState
|
|
100
|
+
requested_vt: int
|
|
101
|
+
consumed_vt: int | None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class ApprovalStatus(StrEnum):
|
|
105
|
+
"""An approval's status as the approvals service reports it (0002, rules 6 to 9)."""
|
|
106
|
+
|
|
107
|
+
PENDING = "pending"
|
|
108
|
+
APPROVED = "approved"
|
|
109
|
+
DENIED = "denied"
|
|
110
|
+
REVOKED = "revoked"
|
|
111
|
+
EXPIRED = "expired"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass(frozen=True)
|
|
115
|
+
class StaleFact:
|
|
116
|
+
"""A cited fact that broke a dependency rule, as the agent is told (0003)."""
|
|
117
|
+
|
|
118
|
+
key: str
|
|
119
|
+
cited_version: int
|
|
120
|
+
current_version: int
|
|
121
|
+
changed_fields: tuple[str, ...]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True)
|
|
125
|
+
class BasisCheck:
|
|
126
|
+
"""The result of checking an action's basis against current facts (0004, property 3).
|
|
127
|
+
|
|
128
|
+
`sufficient_ok` is None when only the exact rules were checked (a C2 retry, I3).
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
exact_ok: bool
|
|
132
|
+
sufficient_ok: bool | None
|
|
133
|
+
versions_seen: Mapping[str, int] = NO_VERSIONS
|
|
134
|
+
stale: tuple[StaleFact, ...] = ()
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def fresh(self) -> bool:
|
|
138
|
+
"""Whether every dependency rule holds."""
|
|
139
|
+
return self.exact_ok and self.sufficient_ok is True
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass(frozen=True)
|
|
143
|
+
class CheckRecord:
|
|
144
|
+
"""The check made before a send, stored with the attempt (I3).
|
|
145
|
+
|
|
146
|
+
`approval_expires_at` is the approval's expiry as the approvals service reported it,
|
|
147
|
+
recorded exactly when the approval is approved: an approval that expires before a
|
|
148
|
+
send could commit counts as expired (0010, change 4).
|
|
149
|
+
|
|
150
|
+
An `authority_only` check, G1's (0008), records the approval and no basis, because G1
|
|
151
|
+
reads no fact before it sends.
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
kind: CheckKind
|
|
155
|
+
approval: ApprovalStatus | None
|
|
156
|
+
basis: BasisCheck | None
|
|
157
|
+
seen_seq: int
|
|
158
|
+
check_vt: int
|
|
159
|
+
approval_expires_at: int | None = None
|
|
160
|
+
|
|
161
|
+
def __post_init__(self) -> None:
|
|
162
|
+
if self.kind is CheckKind.EXEMPT:
|
|
163
|
+
if self.approval is not None or self.basis is not None:
|
|
164
|
+
raise ValueError("an exempt check records no approval and no basis")
|
|
165
|
+
if self.approval_expires_at is not None:
|
|
166
|
+
raise ValueError("an exempt check records no approval expiry")
|
|
167
|
+
return
|
|
168
|
+
if self.kind is CheckKind.AUTHORITY_ONLY:
|
|
169
|
+
if self.approval is None or self.basis is not None:
|
|
170
|
+
raise ValueError("an authority_only check records the approval and no basis")
|
|
171
|
+
elif self.approval is None or self.basis is None:
|
|
172
|
+
raise ValueError(f"a {self.kind} check records the approval and the basis")
|
|
173
|
+
elif (self.kind is CheckKind.FULL) != (self.basis.sufficient_ok is not None):
|
|
174
|
+
raise ValueError(
|
|
175
|
+
"a full check covers the sufficient rules; an exact_only check does not"
|
|
176
|
+
)
|
|
177
|
+
if (self.approval is ApprovalStatus.APPROVED) != (self.approval_expires_at is not None):
|
|
178
|
+
raise ValueError("an approved approval's expiry is recorded, and only that")
|
|
179
|
+
|
|
180
|
+
def approval_at_send(self, sent_vt: int, settle_ms: int) -> ApprovalStatus | None:
|
|
181
|
+
"""The approval's status for a send at `sent_vt` (0002 rule 17, 0010 change 4).
|
|
182
|
+
|
|
183
|
+
A request sent at `sent_vt` commits by `sent_vt + S` or never, so an approved
|
|
184
|
+
approval that expires by then counts as expired. The send is at or after the
|
|
185
|
+
check, so this also keeps the approval alive past the check's time plus S.
|
|
186
|
+
"""
|
|
187
|
+
expires_at = self.approval_expires_at
|
|
188
|
+
approved = self.approval is ApprovalStatus.APPROVED
|
|
189
|
+
if approved and expires_at is not None and expires_at <= sent_vt + settle_ms:
|
|
190
|
+
return ApprovalStatus.EXPIRED
|
|
191
|
+
return self.approval
|
|
192
|
+
|
|
193
|
+
def passes(self, sent_vt: int, settle_ms: int) -> bool:
|
|
194
|
+
"""Whether this check allows a send at `sent_vt` (0002 rule 17, I3)."""
|
|
195
|
+
if self.kind is CheckKind.EXEMPT:
|
|
196
|
+
return True
|
|
197
|
+
approved = self.approval_at_send(sent_vt, settle_ms) is ApprovalStatus.APPROVED
|
|
198
|
+
if self.kind is CheckKind.AUTHORITY_ONLY:
|
|
199
|
+
return approved
|
|
200
|
+
if not approved or self.basis is None:
|
|
201
|
+
return False
|
|
202
|
+
return self.basis.exact_ok and self.basis.sufficient_ok is not False
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
@dataclass(frozen=True)
|
|
206
|
+
class Attempt:
|
|
207
|
+
"""One send of an action (0003). `answer_class` is None while the attempt is open."""
|
|
208
|
+
|
|
209
|
+
attempt_id: str
|
|
210
|
+
action_id: str
|
|
211
|
+
attempt_no: int
|
|
212
|
+
idempotency_key: str
|
|
213
|
+
grant_id: str
|
|
214
|
+
check: CheckRecord
|
|
215
|
+
sent_vt: int
|
|
216
|
+
answer_class: AnswerClass | None
|
|
217
|
+
answer_ref: str | None
|
|
218
|
+
answered_vt: int | None
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@dataclass(frozen=True)
|
|
222
|
+
class ActionEvent:
|
|
223
|
+
"""One append-only row of the action's log (I6). Notes keep the state unchanged."""
|
|
224
|
+
|
|
225
|
+
seq: int
|
|
226
|
+
action_id: str
|
|
227
|
+
kind: EventKind
|
|
228
|
+
from_state: ActionState | None
|
|
229
|
+
to_state: ActionState
|
|
230
|
+
reason: Reason | Note
|
|
231
|
+
details: Mapping[str, object]
|
|
232
|
+
vt: int
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class Resolution(StrEnum):
|
|
236
|
+
"""What a human attests about an escalated action (0003, escalation)."""
|
|
237
|
+
|
|
238
|
+
COMMITTED = "committed"
|
|
239
|
+
NOT_COMMITTED = "not_committed"
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@dataclass(frozen=True)
|
|
243
|
+
class Escalation:
|
|
244
|
+
"""A request for a human to resolve an unknown outcome (0003, escalation)."""
|
|
245
|
+
|
|
246
|
+
escalation_id: str
|
|
247
|
+
action_id: str
|
|
248
|
+
opened_vt: int
|
|
249
|
+
resolved_vt: int | None
|
|
250
|
+
resolution: Resolution | None
|
|
251
|
+
effect_id: str | None
|
|
252
|
+
actor: str | None
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
# Step inputs ---------------------------------------------------------------------------
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def check_text(value: str, what: str) -> None:
|
|
259
|
+
"""Refuse text that no store can keep: PostgreSQL text cannot hold a NUL character."""
|
|
260
|
+
if "\x00" in value:
|
|
261
|
+
raise ValueError(f"{what} contains a NUL character")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
@dataclass(frozen=True)
|
|
265
|
+
class Proposal:
|
|
266
|
+
"""A write proposal that passed the schema and read checks (0001, item 17).
|
|
267
|
+
|
|
268
|
+
The store checks the intent and applies the matching rule. Arguments are text or
|
|
269
|
+
integers and versions are integers (0001, item 6); this is checked here, so every
|
|
270
|
+
store refuses the same proposals.
|
|
271
|
+
"""
|
|
272
|
+
|
|
273
|
+
intent_id: str
|
|
274
|
+
operation: str
|
|
275
|
+
target: str
|
|
276
|
+
args: Mapping[str, str | int]
|
|
277
|
+
action_key: str
|
|
278
|
+
basis: Mapping[str, int]
|
|
279
|
+
|
|
280
|
+
def __post_init__(self) -> None:
|
|
281
|
+
for what in ("intent_id", "operation", "target", "action_key"):
|
|
282
|
+
check_text(getattr(self, what), what)
|
|
283
|
+
for key, value in self.args.items():
|
|
284
|
+
check_text(key, "an argument name")
|
|
285
|
+
if isinstance(value, bool) or not isinstance(value, str | int):
|
|
286
|
+
raise ValueError(f"argument {key} must be text or an integer")
|
|
287
|
+
if isinstance(value, str):
|
|
288
|
+
check_text(value, f"argument {key}")
|
|
289
|
+
for key, version in self.basis.items():
|
|
290
|
+
check_text(key, "a fact key")
|
|
291
|
+
if isinstance(version, bool) or not isinstance(version, int):
|
|
292
|
+
raise ValueError(f"the version of {key} must be an integer")
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
@dataclass(frozen=True)
|
|
296
|
+
class WriteCall:
|
|
297
|
+
"""A write tool call that passed the schema check, as the store admits it (0001).
|
|
298
|
+
|
|
299
|
+
`based_on` holds the read ids the agent cited. `dependencies` holds the fact keys the
|
|
300
|
+
operation depends on (0004, dependency rules), which the citations must cover. The
|
|
301
|
+
store resolves the citations against its read records in the transaction that checks
|
|
302
|
+
the intent and applies the matching rule, so every check runs in the order of 0001,
|
|
303
|
+
item 17. The action's basis is the cited version of each dependency; a dependency
|
|
304
|
+
cited more than once takes its newest cited version. Extra citations are recorded on
|
|
305
|
+
the proposal but are not part of the basis (item 15).
|
|
306
|
+
"""
|
|
307
|
+
|
|
308
|
+
intent_id: str
|
|
309
|
+
operation: str
|
|
310
|
+
target: str
|
|
311
|
+
args: Mapping[str, str | int]
|
|
312
|
+
action_key: str
|
|
313
|
+
based_on: tuple[str, ...]
|
|
314
|
+
dependencies: tuple[str, ...]
|
|
315
|
+
|
|
316
|
+
def __post_init__(self) -> None:
|
|
317
|
+
for what in ("intent_id", "operation", "target", "action_key"):
|
|
318
|
+
check_text(getattr(self, what), what)
|
|
319
|
+
for text in (*self.based_on, *self.dependencies):
|
|
320
|
+
check_text(text, "a citation or a dependency")
|
|
321
|
+
for key, value in self.args.items():
|
|
322
|
+
check_text(key, "an argument name")
|
|
323
|
+
if isinstance(value, bool) or not isinstance(value, str | int):
|
|
324
|
+
raise ValueError(f"argument {key} must be text or an integer")
|
|
325
|
+
if isinstance(value, str):
|
|
326
|
+
check_text(value, f"argument {key}")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
@dataclass(frozen=True)
|
|
330
|
+
class ReadRecord:
|
|
331
|
+
"""A read the gateway served, which a proposal can cite by its id (0001, item 13).
|
|
332
|
+
|
|
333
|
+
`data` is the fact's value at that version, decoded from JSON, which the dependency
|
|
334
|
+
rules compare with the value now (0004).
|
|
335
|
+
"""
|
|
336
|
+
|
|
337
|
+
read_id: str
|
|
338
|
+
key: str
|
|
339
|
+
version: int
|
|
340
|
+
data: Mapping[str, object]
|
|
341
|
+
vt: int
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
class Admission(StrEnum):
|
|
345
|
+
"""What admission did with a write call (0001, items 10 and 17)."""
|
|
346
|
+
|
|
347
|
+
ADMITTED = "admitted"
|
|
348
|
+
"""It created a new action."""
|
|
349
|
+
|
|
350
|
+
ATTACHED = "attached"
|
|
351
|
+
"""It returned an existing action with the same key."""
|
|
352
|
+
|
|
353
|
+
REFUSED = "refused"
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
@dataclass(frozen=True)
|
|
357
|
+
class ProposalRecord:
|
|
358
|
+
"""One write call and its outcome; every call has one, admitted or refused (0001).
|
|
359
|
+
|
|
360
|
+
`args` holds the business arguments in normal form, or, for a call refused with
|
|
361
|
+
`invalid_args`, the arguments as the agent sent them. `intent_id` is None only when
|
|
362
|
+
such a call named no intent as text. `action_id` names the action the call created
|
|
363
|
+
or attached to, or the one an `intent_busy` or `intent_done` refusal names.
|
|
364
|
+
"""
|
|
365
|
+
|
|
366
|
+
proposal_id: str
|
|
367
|
+
operation: str
|
|
368
|
+
intent_id: str | None
|
|
369
|
+
args: Mapping[str, object]
|
|
370
|
+
based_on: tuple[str, ...]
|
|
371
|
+
admission: Admission
|
|
372
|
+
reason: RefusalReason | None
|
|
373
|
+
action_id: str | None
|
|
374
|
+
vt: int
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
@dataclass(frozen=True)
|
|
378
|
+
class CheckTicket:
|
|
379
|
+
"""What a dispatcher needs to check an action before a send (0003, dispatch)."""
|
|
380
|
+
|
|
381
|
+
action_id: str
|
|
382
|
+
attempt_no: int
|
|
383
|
+
kind: CheckKind
|
|
384
|
+
seen_seq: int
|
|
385
|
+
not_before_vt: int
|
|
386
|
+
|
|
387
|
+
def record(
|
|
388
|
+
self,
|
|
389
|
+
*,
|
|
390
|
+
approval: ApprovalStatus | None,
|
|
391
|
+
basis: BasisCheck | None,
|
|
392
|
+
check_vt: int,
|
|
393
|
+
expires_at: int | None = None,
|
|
394
|
+
) -> CheckRecord:
|
|
395
|
+
"""Return the check record for what the dispatcher found.
|
|
396
|
+
|
|
397
|
+
`expires_at` is the approval's expiry, given exactly when it is approved.
|
|
398
|
+
"""
|
|
399
|
+
return CheckRecord(self.kind, approval, basis, self.seen_seq, check_vt, expires_at)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
@dataclass(frozen=True)
|
|
403
|
+
class Answer:
|
|
404
|
+
"""A destination's answer to an attempt, or the gateway's own timeout (0003)."""
|
|
405
|
+
|
|
406
|
+
answer_class: AnswerClass
|
|
407
|
+
reason: Reason
|
|
408
|
+
effect_id: str | None = None
|
|
409
|
+
|
|
410
|
+
def __post_init__(self) -> None:
|
|
411
|
+
if self.reason not in ANSWER_REASONS[self.answer_class]:
|
|
412
|
+
raise ValueError(f"a {self.answer_class} answer cannot have reason {self.reason}")
|
|
413
|
+
if (self.answer_class is AnswerClass.COMMITTED) != (self.effect_id is not None):
|
|
414
|
+
raise ValueError("an effect id comes with committed answers and only with them")
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
@dataclass(frozen=True)
|
|
418
|
+
class ProbeAnswer:
|
|
419
|
+
"""A C1 status query's result (0005). Unanswered when no answer came within T."""
|
|
420
|
+
|
|
421
|
+
answered: bool
|
|
422
|
+
effect_ids: tuple[str, ...] = ()
|
|
423
|
+
as_of_vt: int | None = None
|
|
424
|
+
|
|
425
|
+
def __post_init__(self) -> None:
|
|
426
|
+
if self.answered != (self.as_of_vt is not None):
|
|
427
|
+
raise ValueError("an answered probe has as_of_vt; an unanswered one does not")
|
|
428
|
+
if not self.answered and self.effect_ids:
|
|
429
|
+
raise ValueError("an unanswered probe lists no effects")
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
class ClaimStatus(StrEnum):
|
|
433
|
+
"""A final report's claim about one intent (0004, property 5)."""
|
|
434
|
+
|
|
435
|
+
DONE = "done"
|
|
436
|
+
NOT_DONE = "not_done"
|
|
437
|
+
UNKNOWN = "unknown"
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
@dataclass(frozen=True)
|
|
441
|
+
class Claim:
|
|
442
|
+
"""One claim of a final report. `effect_ids` is non-empty exactly for `done`."""
|
|
443
|
+
|
|
444
|
+
intent_id: str
|
|
445
|
+
status: ClaimStatus
|
|
446
|
+
effect_ids: tuple[str, ...] = ()
|
|
447
|
+
note: str = ""
|
|
448
|
+
|
|
449
|
+
def __post_init__(self) -> None:
|
|
450
|
+
if (self.status is ClaimStatus.DONE) != bool(self.effect_ids):
|
|
451
|
+
raise ValueError("effect_ids must be non-empty for done and empty otherwise")
|
|
452
|
+
for text in (self.intent_id, self.note, *self.effect_ids):
|
|
453
|
+
check_text(text, "a claim")
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
# Agent-facing results ------------------------------------------------------------------
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
@dataclass(frozen=True)
|
|
460
|
+
class Reconcile:
|
|
461
|
+
"""How an unknown outcome is being resolved (0003). Only with `outcome_unknown`.
|
|
462
|
+
|
|
463
|
+
`what` says in words which effect may or may not exist.
|
|
464
|
+
"""
|
|
465
|
+
|
|
466
|
+
contract: Contract
|
|
467
|
+
how: ReconcileHow
|
|
468
|
+
escalation_id: str | None
|
|
469
|
+
what: str
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
@dataclass(frozen=True)
|
|
473
|
+
class ActionResult:
|
|
474
|
+
"""The `{"result": "action", ...}` shape of 0003. `reason` is the latest transition's."""
|
|
475
|
+
|
|
476
|
+
action_id: str
|
|
477
|
+
intent_id: str
|
|
478
|
+
state: ActionState
|
|
479
|
+
effect_id: str | None
|
|
480
|
+
reason: Reason
|
|
481
|
+
stale: tuple[StaleFact, ...]
|
|
482
|
+
reconcile: Reconcile | None
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
class RefusalReason(StrEnum):
|
|
486
|
+
"""Refusal reasons (0001, 0003)."""
|
|
487
|
+
|
|
488
|
+
INVALID_ARGS = "invalid_args"
|
|
489
|
+
UNKNOWN_INTENT = "unknown_intent"
|
|
490
|
+
WRONG_OPERATION = "wrong_operation"
|
|
491
|
+
UNKNOWN_READ = "unknown_read"
|
|
492
|
+
MISSING_BASIS = "missing_basis"
|
|
493
|
+
INTENT_BUSY = "intent_busy"
|
|
494
|
+
INTENT_DONE = "intent_done"
|
|
495
|
+
RUN_CLOSED = "run_closed"
|
|
496
|
+
REPORT_INCONSISTENT = "report_inconsistent"
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
@dataclass(frozen=True)
|
|
500
|
+
class RecordedAction:
|
|
501
|
+
"""The gateway's record of one action, as a report refusal names it (0003).
|
|
502
|
+
|
|
503
|
+
`effect_ids` holds every effect id the gateway learned for the action.
|
|
504
|
+
"""
|
|
505
|
+
|
|
506
|
+
action_id: str
|
|
507
|
+
state: ActionState
|
|
508
|
+
effect_ids: tuple[str, ...]
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
@dataclass(frozen=True)
|
|
512
|
+
class ClaimConflict:
|
|
513
|
+
"""A report claim that contradicts the gateway's records (0003, final report)."""
|
|
514
|
+
|
|
515
|
+
intent_id: str
|
|
516
|
+
claimed: ClaimStatus
|
|
517
|
+
claimed_effect_ids: tuple[str, ...]
|
|
518
|
+
recorded: tuple[RecordedAction, ...]
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
@dataclass(frozen=True)
|
|
522
|
+
class Refusal:
|
|
523
|
+
"""The `{"result": "refused", ...}` shape of 0003, with its details.
|
|
524
|
+
|
|
525
|
+
`unknown_reads` lists the cited read ids the gateway never issued (`unknown_read`),
|
|
526
|
+
`missing_keys` the dependencies no citation covers (`missing_basis`), and `message`
|
|
527
|
+
says what broke the schema (`invalid_args`).
|
|
528
|
+
"""
|
|
529
|
+
|
|
530
|
+
reason: RefusalReason
|
|
531
|
+
action_id: str | None = None
|
|
532
|
+
state: ActionState | None = None
|
|
533
|
+
effect_id: str | None = None
|
|
534
|
+
args: Mapping[str, str | int] | None = None
|
|
535
|
+
conflicts: tuple[ClaimConflict, ...] = ()
|
|
536
|
+
unknown_reads: tuple[str, ...] = ()
|
|
537
|
+
missing_keys: tuple[str, ...] = ()
|
|
538
|
+
message: str = ""
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
@dataclass(frozen=True)
|
|
542
|
+
class ReportAccepted:
|
|
543
|
+
"""A final report the gateway accepted, with the claims it accepted."""
|
|
544
|
+
|
|
545
|
+
claims: tuple[Claim, ...]
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
@dataclass(frozen=True)
|
|
549
|
+
class ToolCall:
|
|
550
|
+
"""One agent-facing response, logged for I5. `as_of_seq` is the event seq it reflects.
|
|
551
|
+
|
|
552
|
+
`args` are the arguments of the call it answers, as the gateway received them, kept as
|
|
553
|
+
`fivefold.gateway.codec.storable` makes them: arrays as tuples, objects as read-only
|
|
554
|
+
mappings.
|
|
555
|
+
"""
|
|
556
|
+
|
|
557
|
+
call_no: int
|
|
558
|
+
tool: str
|
|
559
|
+
args: Mapping[str, object]
|
|
560
|
+
action_id: str | None
|
|
561
|
+
result: ActionResult | Refusal | ReportAccepted
|
|
562
|
+
as_of_seq: int
|
|
563
|
+
vt: int
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
# Snapshots -----------------------------------------------------------------------------
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
@dataclass(frozen=True)
|
|
570
|
+
class Snapshot:
|
|
571
|
+
"""Every gateway record of one run, for the invariant checks.
|
|
572
|
+
|
|
573
|
+
`attempts` maps each action id to its attempts in attempt order. `events` and
|
|
574
|
+
`tool_calls` are in seq and call order. `closed_intents` are the intents an accepted
|
|
575
|
+
`not_done` claim closed, and `reports` maps each agent worker whose report was
|
|
576
|
+
accepted to the call number of its first accepted report (0010, item 6). `reads`
|
|
577
|
+
maps each read id to the read it names, and `proposals` lists every write call in
|
|
578
|
+
the order the calls came (0001, items 13 and 17).
|
|
579
|
+
"""
|
|
580
|
+
|
|
581
|
+
intents: Mapping[str, str]
|
|
582
|
+
actions: Mapping[str, Action]
|
|
583
|
+
grants: Mapping[str, Grant]
|
|
584
|
+
attempts: Mapping[str, tuple[Attempt, ...]]
|
|
585
|
+
events: tuple[ActionEvent, ...]
|
|
586
|
+
escalations: Mapping[str, Escalation]
|
|
587
|
+
tool_calls: tuple[ToolCall, ...]
|
|
588
|
+
run_closed: bool
|
|
589
|
+
closed_intents: frozenset[str] = frozenset()
|
|
590
|
+
reports: Mapping[str, int] = field(default_factory=lambda: frozen({}))
|
|
591
|
+
reads: Mapping[str, ReadRecord] = field(default_factory=lambda: frozen({}))
|
|
592
|
+
proposals: tuple[ProposalRecord, ...] = ()
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""The gateway's MCP server: one low-level MCP `Server` per agent connection (0008, 0009).
|
|
2
|
+
|
|
3
|
+
Each connection is a `Link` from the harness, whose `agent` names the agent worker. The
|
|
4
|
+
worker's name comes from the connection, not from anything the agent sends, and stays
|
|
5
|
+
the same when the worker resumes from its checkpoint (0009), so the report check knows
|
|
6
|
+
whose report it is (0010). Each request the link delivers carries its message seq on the
|
|
7
|
+
handler context's `request`, so the report sink can record which message carried a
|
|
8
|
+
report, a copy that F4 delivered included (0004).
|
|
9
|
+
|
|
10
|
+
A tool's result goes back as JSON text and as structured content. A `ToolError` becomes
|
|
11
|
+
an MCP tool error (`is_error`), with the error code and message as JSON text.
|
|
12
|
+
|
|
13
|
+
MCP SDK calls used (mcp 2.3.0): `mcp.server.lowlevel.server.Server(name, on_list_tools=,
|
|
14
|
+
on_call_tool=, get_tool_input_schema=)`, `Server.run(read, write,
|
|
15
|
+
Server.create_initialization_options())`, the handler context's `request`
|
|
16
|
+
(`mcp.server.context.ServerRequestContext`), and the `mcp_types` models `Tool`,
|
|
17
|
+
`ListToolsResult`, `CallToolRequestParams`, `CallToolResult` and `TextContent`.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
from collections.abc import Callable
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
import mcp_types as types
|
|
27
|
+
from mcp.server.lowlevel.server import Server
|
|
28
|
+
|
|
29
|
+
from fivefold.gateway.tools import TOOLS, GatewayTools, ToolError
|
|
30
|
+
from fivefold.harness.mcp_link import Link, delivered_seq
|
|
31
|
+
|
|
32
|
+
SERVER_NAME = "fivefold-gateway"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _tool_list() -> types.ListToolsResult:
|
|
36
|
+
return types.ListToolsResult(
|
|
37
|
+
tools=[
|
|
38
|
+
types.Tool(name=t.name, description=t.description, input_schema=t.input_schema())
|
|
39
|
+
for t in TOOLS
|
|
40
|
+
]
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def server_for(tools: GatewayTools, link: Link) -> Server[Any]:
|
|
45
|
+
"""An MCP server that serves `tools` to the agent worker at the other end of `link`."""
|
|
46
|
+
return worker_server(lambda: tools, link.agent)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def worker_server(tools: Callable[[], GatewayTools], worker: str) -> Server[Any]:
|
|
50
|
+
"""An MCP server that serves the gateway's tools to the agent worker `worker`.
|
|
51
|
+
|
|
52
|
+
`tools` gives the tools of the gateway's current incarnation when a call arrives. The
|
|
53
|
+
split topology serves its one agent worker this way, over streamable HTTP
|
|
54
|
+
(`fivefold.harness.split.gateway`).
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
async def list_tools(ctx: Any, params: Any) -> types.ListToolsResult:
|
|
58
|
+
return _tool_list()
|
|
59
|
+
|
|
60
|
+
async def call_tool(ctx: Any, params: types.CallToolRequestParams) -> types.CallToolResult:
|
|
61
|
+
try:
|
|
62
|
+
result = await tools().call(
|
|
63
|
+
params.name,
|
|
64
|
+
params.arguments or {},
|
|
65
|
+
worker=worker,
|
|
66
|
+
message_seq=delivered_seq(ctx.request),
|
|
67
|
+
)
|
|
68
|
+
except ToolError as error:
|
|
69
|
+
failure = {"error": error.code, "message": error.message}
|
|
70
|
+
return types.CallToolResult(
|
|
71
|
+
content=[types.TextContent(text=json.dumps(failure, sort_keys=True))],
|
|
72
|
+
is_error=True,
|
|
73
|
+
)
|
|
74
|
+
return types.CallToolResult(
|
|
75
|
+
content=[types.TextContent(text=json.dumps(result, sort_keys=True))],
|
|
76
|
+
structured_content=result,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
return Server(
|
|
80
|
+
SERVER_NAME,
|
|
81
|
+
on_list_tools=list_tools,
|
|
82
|
+
on_call_tool=call_tool,
|
|
83
|
+
get_tool_input_schema=tool_input_schema,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def tool_input_schema(name: str) -> dict[str, object] | None:
|
|
88
|
+
"""A tool's input schema by name, or None for a name that is no tool.
|
|
89
|
+
|
|
90
|
+
The SDK checks a 2026-07-28 request's `Mcp-Param-*` headers against it, instead of
|
|
91
|
+
asking the server for its tool list (mcp 2.3.0, `Server(get_tool_input_schema=)`).
|
|
92
|
+
"""
|
|
93
|
+
for tool in TOOLS:
|
|
94
|
+
if tool.name == name:
|
|
95
|
+
return tool.input_schema()
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
async def serve(tools: GatewayTools, link: Link) -> None:
|
|
100
|
+
"""Serve one connection until the agent's end closes."""
|
|
101
|
+
server = server_for(tools, link)
|
|
102
|
+
await server.run(link.server_read, link.server_write, server.create_initialization_options())
|