copuppet 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.
copuppet/relay.py ADDED
@@ -0,0 +1,334 @@
1
+ """Relay: the backend contract over files, so an outside intelligence can play Copilot (and, on its own channel,
2
+ the person). Python stays fully deterministic; only the answers come from outside. For development and tests: in
3
+ real use the edge backend sits in the same place.
4
+
5
+ copuppet drive "GOAL" --root DIR --backend relay --relay RELAYDIR [--person relay]
6
+ copuppet relay next --dir RELAYDIR [--channel copilot|person] [--wait 300]
7
+ copuppet relay answer --dir RELAYDIR --id 000007 [--meta '{"bound": false}'] # answer text on stdin or --file
8
+
9
+ Layout: every run gets its own folder `RELAYDIR/run-<id>/` (copilot/, person/, done/, run.json, END.json) and
10
+ `RELAYDIR/CURRENT.json` names the active run, so nothing from an earlier run can answer a new question.
11
+ - A question is `<channel>/NNNNNN.q.json` with a random `token`; its answer `NNNNNN.a.json` must echo that token, so
12
+ an answer cannot be written before the question exists. A pre-existing answer file is deleted when a question is
13
+ posted. Consumed pairs move to done/, so the stand-in sees only open items.
14
+ - One writer per run (the drive process); ids are created with exclusive create.
15
+ - Person channel: a write is approved only by `yes <sha256 prefix>` of the content shown, so an approval binds to
16
+ that content; anything else declines; a timeout declines.
17
+ - Answers may carry optional fields (`complete`, `bound`, `markers`, `model_label`, `first_token_s`) so tests can
18
+ drive the session's invariants (P6, I9, I12, rotation triggers) through the relay.
19
+ - run.json records the token seed: a finished run folder can be replayed prompt for prompt (ReplayBackend).
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import os
25
+ import re
26
+ import secrets
27
+ import shutil
28
+ import time
29
+ from pathlib import Path
30
+
31
+ from . import tokens
32
+ from .backend import BackendError, ChatHandle, Probe, Reply
33
+
34
+ CHANNELS = ("copilot", "person")
35
+ ID_RE = re.compile(r"\d{1,9}")
36
+ META = {"complete": bool, "bound": bool, "markers": list, "model_label": str, "first_token_s": (int, float)}
37
+ NO_PERSON = "(no person available; decide yourself)"
38
+
39
+
40
+ def _write(path: Path, data: dict, *, exclusive: bool = False) -> None:
41
+ if exclusive:
42
+ with path.open("x", encoding="utf-8") as fh:
43
+ json.dump(data, fh, ensure_ascii=False, indent=1)
44
+ fh.flush()
45
+ os.fsync(fh.fileno())
46
+ return
47
+ tmp = path.with_name(path.name + f".{secrets.token_hex(3)}.tmp")
48
+ with tmp.open("w", encoding="utf-8") as fh:
49
+ json.dump(data, fh, ensure_ascii=False, indent=1)
50
+ fh.flush()
51
+ os.fsync(fh.fileno())
52
+ for _ in range(20): # Windows: the target may be open in a reader for a moment
53
+ try:
54
+ tmp.replace(path)
55
+ return
56
+ except PermissionError:
57
+ time.sleep(0.05)
58
+ tmp.replace(path)
59
+
60
+
61
+ def _read(path: Path):
62
+ return json.loads(path.read_bytes().decode("utf-8-sig"))
63
+
64
+
65
+ class Relay:
66
+ """One run's file queue. Python side: Relay.start(); the stand-in's side: Relay.attach()."""
67
+
68
+ def __init__(self, run_dir: Path):
69
+ self.run = Path(run_dir)
70
+ self.seq = 0
71
+
72
+ @classmethod
73
+ def start(cls, directory, *, seed: int | None = None) -> Relay:
74
+ base = Path(directory).expanduser().resolve()
75
+ run_id = time.strftime("%Y%m%d-%H%M%S") + "-" + secrets.token_hex(2)
76
+ run = base / f"run-{run_id}"
77
+ for sub in (*CHANNELS, "done"):
78
+ (run / sub).mkdir(parents=True, exist_ok=True)
79
+ _write(run / "run.json", {"run_id": run_id, "seed": seed, "started": time.time()})
80
+ _write(base / "CURRENT.json", {"run_id": run_id})
81
+ return cls(run)
82
+
83
+ @classmethod
84
+ def attach(cls, directory) -> Relay:
85
+ base = Path(directory).expanduser().resolve()
86
+ cur = base / "CURRENT.json"
87
+ if not cur.exists():
88
+ raise BackendError(f"no relay run in {base} yet; start the drive first")
89
+ return cls(base / f"run-{_read(cur)['run_id']}")
90
+
91
+ @property
92
+ def seed(self):
93
+ return _read(self.run / "run.json").get("seed")
94
+
95
+ # ---------- Python side ----------
96
+ def post(self, channel: str, text: str, **meta) -> str:
97
+ if channel not in CHANNELS:
98
+ raise BackendError(f"unknown relay channel {channel}")
99
+ while True:
100
+ self.seq += 1
101
+ qid = f"{self.seq:06d}"
102
+ q = self.run / channel / f"{qid}.q.json"
103
+ a = q.with_name(f"{qid}.a.json")
104
+ if a.exists():
105
+ a.unlink() # pre-created answers never count
106
+ try:
107
+ _write(q, {"id": qid, "channel": channel, "token": secrets.token_hex(8), "text": text, **meta},
108
+ exclusive=True)
109
+ return qid
110
+ except FileExistsError:
111
+ continue
112
+
113
+ def wait(self, qid: str, channel: str, timeout: float) -> dict:
114
+ q = self.run / channel / f"{qid}.q.json"
115
+ a = q.with_name(f"{qid}.a.json")
116
+ token = _read(q)["token"]
117
+ deadline = time.monotonic() + timeout
118
+ bad = 0
119
+ while time.monotonic() < deadline:
120
+ if a.exists():
121
+ try:
122
+ data = _read(a)
123
+ if not isinstance(data, dict) or not isinstance(data.get("text"), str):
124
+ raise ValueError("the answer needs a text string")
125
+ if data.get("token") != token:
126
+ raise ValueError("the answer does not echo the question's token")
127
+ except (ValueError, UnicodeDecodeError) as e:
128
+ bad += 1
129
+ if bad >= 3: # a partial write gets two more looks, then it is wrong
130
+ raise BackendError(f"relay answer {qid} ({channel}) is invalid: {e}") from None
131
+ time.sleep(0.2)
132
+ continue
133
+ for f in (q, a):
134
+ shutil.move(str(f), str(self.run / "done" / f"{channel}-{f.name}"))
135
+ return data
136
+ time.sleep(0.2)
137
+ raise BackendError(f"no answer to relay item {qid} ({channel}) within {timeout:g}s")
138
+
139
+ def end(self, status: str) -> None:
140
+ _write(self.run / "END.json", {"status": status})
141
+
142
+ # ---------- the stand-in's side ----------
143
+ def pending(self, channel: str | None = None) -> list[dict]:
144
+ out = []
145
+ for ch in ([channel] if channel else CHANNELS):
146
+ for q in sorted((self.run / ch).glob("*.q.json")):
147
+ if not q.with_name(q.name.replace(".q.json", ".a.json")).exists():
148
+ item = _read(q)
149
+ item.pop("token", None) # the stand-in never needs to see it
150
+ out.append(item)
151
+ return sorted(out, key=lambda i: i["id"])
152
+
153
+ def answer(self, qid: str, text: str, meta: dict | None = None) -> str:
154
+ if not ID_RE.fullmatch(qid or ""):
155
+ raise BackendError(f"invalid relay id {qid!r}; ids are digits")
156
+ qid = f"{int(qid):06d}"
157
+ for ch in CHANNELS:
158
+ q = self.run / ch / f"{qid}.q.json"
159
+ if q.exists():
160
+ a = q.with_name(f"{qid}.a.json")
161
+ if a.exists():
162
+ raise BackendError(f"relay item {qid} is already answered")
163
+ data = {"id": qid, "token": _read(q)["token"], "text": text}
164
+ for k, v in (meta or {}).items():
165
+ if k not in META or not isinstance(v, META[k]):
166
+ raise BackendError(f"unknown or mistyped answer field {k!r}; known: {', '.join(META)}")
167
+ data[k] = v
168
+ _write(a, data)
169
+ return f"{ch}/{a.name}"
170
+ raise BackendError(f"no open relay item {qid}")
171
+
172
+ def ended(self) -> str:
173
+ p = self.run / "END.json"
174
+ return _read(p)["status"] if p.exists() else ""
175
+
176
+
177
+ # ---------- replies ----------
178
+ def code_blocks(text: str) -> tuple[list[str], bool]:
179
+ """Line-anchored fences (``` or ~~~), like rendered code blocks; returns (blocks, closed)."""
180
+ blocks, cur, fence = [], None, ""
181
+ for line in text.splitlines():
182
+ s = line.strip()
183
+ if cur is None and (s.startswith("```") or s.startswith("~~~")):
184
+ fence, cur = s[:3], []
185
+ elif cur is not None and s.startswith(fence) and s.strip(fence[0]) == "":
186
+ blocks.append("\n".join(cur) + "\n")
187
+ cur = None
188
+ elif cur is not None:
189
+ cur.append(line)
190
+ return blocks, cur is None
191
+
192
+
193
+ def _reply(data: dict, backend: str, label: str, seconds: float) -> Reply:
194
+ text = data["text"].strip()
195
+ blocks, closed = code_blocks(text)
196
+ return Reply(text=text, backend=backend, complete=bool(data.get("complete", True)) and bool(text) and closed,
197
+ bound=bool(data.get("bound", True)), seconds=round(seconds, 2), code_blocks=blocks,
198
+ model_label=data.get("model_label", label), markers=list(data.get("markers", [])),
199
+ first_token_s=float(data.get("first_token_s", 0.0)),
200
+ notes=[] if closed else ["an unclosed code fence: the reply is treated as incomplete"])
201
+
202
+
203
+ class RelayBackend:
204
+ """Backend contract over the relay. The model label can be changed by an answer (to test I9)."""
205
+ name = "relay"
206
+
207
+ def __init__(self, config: dict):
208
+ relay = config.get("_relay")
209
+ if relay is None:
210
+ if not config.get("dir"):
211
+ raise BackendError("the relay backend needs a folder; pass --relay DIR")
212
+ relay = Relay.start(config["dir"], seed=config.get("seed", secrets.randbits(32)))
213
+ self.relay = relay
214
+ tokens.seed(relay.seed) # recorded in run.json: the run can be replayed
215
+ self.timeout = float(config.get("reply_seconds", 600))
216
+ self.model_label = str(config.get("model_label", "relay"))
217
+ self.chats = 0
218
+ self.turn = 0
219
+ self.mode_used = "relay"
220
+
221
+ def ready(self) -> list[str]:
222
+ return []
223
+
224
+ def probe(self) -> Probe:
225
+ return Probe(temporary=True, signed_in=True, model_label=self.model_label, markers=[],
226
+ reply_count=self.turn, url=f"relay://{self.relay.run.name}")
227
+
228
+ def new_chat(self, *, temporary: bool = True) -> ChatHandle:
229
+ self.chats += 1
230
+ self.turn = 0
231
+ return ChatHandle(chat_id=self.chats, started_at=time.time(), temporary=temporary,
232
+ model_label=self.model_label)
233
+
234
+ def send(self, chat: ChatHandle, prompt: str, *, timeout: float | None = None) -> Reply:
235
+ if chat.chat_id != self.chats:
236
+ raise BackendError(f"chat #{chat.chat_id} is no longer the open chat (relay)")
237
+ if chat.model_label != self.model_label:
238
+ raise BackendError("the model changed under the chat (relay); refusing to send (I9)")
239
+ self.turn += 1
240
+ t0 = time.monotonic()
241
+ qid = self.relay.post("copilot", prompt, chat_id=chat.chat_id, chat_turn=self.turn)
242
+ data = self.relay.wait(qid, "copilot", timeout or self.timeout)
243
+ if data.get("model_label"):
244
+ self.model_label = data["model_label"]
245
+ return _reply(data, self.name, self.model_label, time.monotonic() - t0)
246
+
247
+ def ask(self, prompt: str, *, timeout: float | None = None) -> Reply:
248
+ return self.send(self.new_chat(), prompt, timeout=timeout)
249
+
250
+ def close(self) -> None:
251
+ pass
252
+
253
+
254
+ def person(relay: Relay, timeout: float = 600):
255
+ """confirm/ask callables on the relay's person channel. An approval must quote the content hash shown."""
256
+ def confirm(message: str) -> bool:
257
+ m = re.search(r"sha256 ([0-9a-f]{12})", message)
258
+ want = f"yes {m.group(1)}" if m else "yes"
259
+ qid = relay.post("person", message + f"\nTo approve, answer exactly: {want}\nAnything else declines.",
260
+ kind="confirm")
261
+ try:
262
+ return relay.wait(qid, "person", timeout)["text"].strip().lower() == want
263
+ except BackendError:
264
+ return False # no answer or an invalid one: declined
265
+
266
+ def ask(question: str) -> str:
267
+ qid = relay.post("person", question, kind="question")
268
+ try:
269
+ return relay.wait(qid, "person", timeout)["text"]
270
+ except BackendError:
271
+ return NO_PERSON
272
+ return confirm, ask
273
+
274
+
275
+ # ---------- replay ----------
276
+ class ReplayBackend(RelayBackend):
277
+ """Replays a finished relay run: the same seed gives the same prompts; each prompt must equal the recorded one
278
+ (else the run diverged), and the recorded answer is returned. For regression tests of the deterministic side."""
279
+ name = "replay"
280
+
281
+ def __init__(self, run_dir, *, model_label: str = "relay"):
282
+ self.relay = Relay(Path(run_dir))
283
+ tokens.seed(self.relay.seed)
284
+ self.items = self._load("copilot")
285
+ self.people = self._load("person")
286
+ self.model_label = model_label
287
+ self.chats = 0
288
+ self.turn = 0
289
+ self.mode_used = "replay"
290
+ self.timeout = 0
291
+
292
+ def _load(self, channel: str) -> list:
293
+ done = self.relay.run / "done"
294
+ out = []
295
+ for q in sorted(done.glob(f"{channel}-*.q.json")):
296
+ a = q.with_name(q.name.replace(".q.json", ".a.json"))
297
+ out.append((_read(q), _read(a)))
298
+ return out
299
+
300
+ def send(self, chat: ChatHandle, prompt: str, *, timeout: float | None = None) -> Reply:
301
+ if chat.chat_id != self.chats:
302
+ raise BackendError(f"chat #{chat.chat_id} is no longer the open chat (replay)")
303
+ if not self.items:
304
+ raise BackendError("replay exhausted: the run asks more than was recorded")
305
+ q, a = self.items.pop(0)
306
+ if q["text"] != prompt:
307
+ i = next((n for n, (x, y) in enumerate(zip(q["text"], prompt)) if x != y), min(len(q["text"]), len(prompt)))
308
+ raise BackendError(f"replay diverged at item {q['id']}, character {i}: recorded "
309
+ f"{q['text'][max(0, i - 30):i + 30]!r}, now {prompt[max(0, i - 30):i + 30]!r}")
310
+ self.turn += 1
311
+ if a.get("model_label"):
312
+ self.model_label = a["model_label"]
313
+ return _reply(a, self.name, self.model_label, 0.0)
314
+
315
+ def person(self):
316
+ def next_answer(kind):
317
+ if not self.people or self.people[0][0].get("kind") != kind:
318
+ raise BackendError(f"replay diverged: no recorded person {kind} here")
319
+ return self.people.pop(0)[1]["text"]
320
+
321
+ def confirm(message: str) -> bool:
322
+ m = re.search(r"sha256 ([0-9a-f]{12})", message)
323
+ return next_answer("confirm").strip().lower() == (f"yes {m.group(1)}" if m else "yes")
324
+ return confirm, lambda q: next_answer("question")
325
+
326
+
327
+ def render(item: dict) -> str:
328
+ """What `relay next` prints for the stand-in."""
329
+ if item["channel"] == "copilot":
330
+ head = (f"id {item['id']} | channel copilot | chat {item['chat_id']} | message {item['chat_turn']} in this chat"
331
+ + (" (NEW chat: you remember nothing from earlier chats)" if item["chat_turn"] == 1 else ""))
332
+ else:
333
+ head = f"id {item['id']} | channel person | kind {item.get('kind', '')}"
334
+ return head + "\n----- text -----\n" + item["text"] + "\n----- end -----"
copuppet/runner.py ADDED
@@ -0,0 +1,103 @@
1
+ """One way to build a backend, session and policy, shared by the CLI and the MCP server.
2
+
3
+ Run settings come from the person who starts copuppet (command-line flags), never from a caller's tool arguments:
4
+ the work folder, whether writes are allowed, display and skin are fixed when the runner is made.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import time
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from .backends import make
13
+ from .driver import Driver
14
+ from .ledger import Ledger
15
+ from .policy import Policy
16
+ from .session import Limits, Session
17
+ from .skin import load
18
+
19
+ RUNS = Path.home() / ".copuppet" / "runs"
20
+
21
+
22
+ @dataclass
23
+ class RunConfig:
24
+ skin: str | None = None
25
+ backend: str = "edge"
26
+ display: str | None = None
27
+ verbose: bool = False
28
+ root: str | None = None # work folder for driver mode; None means drive is unavailable
29
+ allow_writes: bool = False
30
+ keep_text: bool = False # ledger keeps prompt/reply text (off: hashes and sizes only)
31
+ max_steps: int = 25
32
+ max_seconds: float = 900
33
+ max_chat_turns: int | None = None # development: force early rotations (tests the hand-over brief)
34
+
35
+
36
+ class Runner:
37
+ """Owns at most one backend (one Edge profile) and makes sessions and drivers on it. Not thread-safe by
38
+ design: callers serialise (the MCP server runs every call on one worker thread)."""
39
+
40
+ def __init__(self, cfg: RunConfig):
41
+ self.cfg = cfg
42
+ self.skin = load(cfg.skin)
43
+ conf = self.skin.backends.setdefault(cfg.backend, {})
44
+ if cfg.verbose:
45
+ conf["_verbose"] = True
46
+ if cfg.display:
47
+ conf["display"] = cfg.display
48
+ self._backend = None
49
+ self._session = None
50
+
51
+ @property
52
+ def backend(self):
53
+ if self._backend is None:
54
+ self._backend = make(self.cfg.backend, self.skin)
55
+ return self._backend
56
+
57
+ def ledger(self, kind: str) -> Ledger:
58
+ RUNS.mkdir(parents=True, exist_ok=True)
59
+ return Ledger(RUNS / f"{time.strftime('%Y%m%d-%H%M%S')}-{kind}.jsonl", keep_text=self.cfg.keep_text)
60
+
61
+ def ask(self, prompt: str, timeout: float | None = None):
62
+ self._session = None # ask opens its own chat: a session's handle would be stale
63
+ return self.backend.ask(prompt, timeout=timeout)
64
+
65
+ def limits(self) -> Limits:
66
+ """The Limits a new session would start with (calibrated values need the model, known after a chat)."""
67
+ return Limits()
68
+
69
+ def _adopt(self, model_label: str, display: str) -> dict:
70
+ """Calibrated limits for this skin, model and display, once there are 3 samples (P2)."""
71
+ from .calibrate import measured
72
+ got = measured({"skin": getattr(self.skin, "name", ""), "model_label": model_label, "display": display})
73
+ out = {}
74
+ if "max_prompt_chars" in got:
75
+ out["max_prompt_chars"] = int(got["max_prompt_chars"] * 0.9) # a margin below the measured cap
76
+ if "recall_chars" in got:
77
+ out["recall_chars"] = got["recall_chars"]
78
+ return out
79
+
80
+ def session(self, *, reset: bool = False, brief: str = "") -> Session:
81
+ if reset or self._session is None:
82
+ self._session = Session(self.backend, self.ledger("session"), limits=Limits(),
83
+ brief=(lambda: brief) if brief else None, adopt=self._adopt)
84
+ return self._session
85
+
86
+ def policy(self) -> Policy:
87
+ if not self.cfg.root:
88
+ raise PermissionError("driver mode needs a work folder; start copuppet with --root DIR")
89
+ effects = ("read", "write-local") if self.cfg.allow_writes else ("read",)
90
+ return Policy(Path(self.cfg.root), effects=effects)
91
+
92
+ def driver(self, goal: str, *, confirm=None, ask=None, show=None) -> Driver:
93
+ self._session = None # the drive opens its own chats
94
+ limits = Limits(max_turns=self.cfg.max_chat_turns, margin_turns=0) if self.cfg.max_chat_turns else Limits()
95
+ s = Session(self.backend, self.ledger("drive"), limits=limits, adopt=self._adopt)
96
+ return Driver(s, self.policy(), goal=goal, max_steps=self.cfg.max_steps, max_seconds=self.cfg.max_seconds,
97
+ confirm=confirm, ask=ask, show=show)
98
+
99
+ def close(self) -> None:
100
+ if self._backend is not None:
101
+ self._backend.close()
102
+ self._backend = None
103
+ self._session = None