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/__init__.py +2 -0
- copuppet/actions.py +111 -0
- copuppet/backend.py +70 -0
- copuppet/backends/__init__.py +19 -0
- copuppet/backends/edge.py +573 -0
- copuppet/backends/winapp.py +27 -0
- copuppet/calibrate.py +245 -0
- copuppet/cli.py +266 -0
- copuppet/driver.py +161 -0
- copuppet/fake.py +73 -0
- copuppet/ledger.py +118 -0
- copuppet/mcp_server.py +124 -0
- copuppet/policy.py +150 -0
- copuppet/protocol.py +124 -0
- copuppet/relay.py +334 -0
- copuppet/runner.py +103 -0
- copuppet/session.py +267 -0
- copuppet/skin.py +85 -0
- copuppet/tokens.py +28 -0
- copuppet-0.1.0.dist-info/METADATA +100 -0
- copuppet-0.1.0.dist-info/RECORD +24 -0
- copuppet-0.1.0.dist-info/WHEEL +4 -0
- copuppet-0.1.0.dist-info/entry_points.txt +2 -0
- copuppet-0.1.0.dist-info/licenses/LICENSE +21 -0
copuppet/session.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""Session: the chat lifecycle (docs/model.md v3). Python owns the state; chats are disposable.
|
|
2
|
+
|
|
3
|
+
s = Session(backend, ledger, limits=Limits(...), brief=lambda: "...")
|
|
4
|
+
reply = s.turn("prompt") # rotates by itself when a trigger fires; never returns an unusable reply (P6)
|
|
5
|
+
|
|
6
|
+
- Brief: plants `canaries_per_chat` labelled single-use canaries (depth is tested) and asks for an acknowledgement
|
|
7
|
+
token, verified (no imperative "Reply OK.": consumer Copilot once turned one into an email draft).
|
|
8
|
+
- Recall check (every `check_every` work turns): ONE prompt asks the oldest unasked canary by label and, when the
|
|
9
|
+
chat runs low on canaries, plants the next one in the same prompt (speed: one turn instead of two).
|
|
10
|
+
- P6: an incomplete or unbound reply triggers a rotation and one retry in a new chat; a second failure stops.
|
|
11
|
+
- A failed recall check marks the work replies since the last passed check as suspect (they were answered by a chat
|
|
12
|
+
that may have lost its context).
|
|
13
|
+
- I4: no canary token that was asked, or that belongs to another chat, ever appears in a later prompt.
|
|
14
|
+
- I5: the brief must fit in 25% of the recall budget.
|
|
15
|
+
- Latency trigger: per turn kind, against a baseline measured from the first turns of that kind.
|
|
16
|
+
- I9: a changed or empty model label stops the session (Limits belong to a model).
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import dataclasses
|
|
21
|
+
import re
|
|
22
|
+
from . import tokens
|
|
23
|
+
import statistics
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
|
|
26
|
+
from .backend import BackendError
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Limits:
|
|
31
|
+
max_turns: int = 30
|
|
32
|
+
margin_turns: int = 4
|
|
33
|
+
recall_chars: int = 20000 # uncalibrated conservative default
|
|
34
|
+
char_safety: float = 0.5
|
|
35
|
+
check_every: int = 6 # recall check every N work turns
|
|
36
|
+
canaries_per_chat: int = 3
|
|
37
|
+
latency_factor: float = 4.0
|
|
38
|
+
latency_n: int = 2
|
|
39
|
+
latency_baseline_turns: int = 3
|
|
40
|
+
max_rotations: int = 20
|
|
41
|
+
max_prompt_chars: int = 8000 # uncalibrated conservative default; longer prompts are refused
|
|
42
|
+
calibrated: bool = False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class ChatState:
|
|
47
|
+
handle: object
|
|
48
|
+
turns: int = 0
|
|
49
|
+
chars: int = 0
|
|
50
|
+
canaries: list = field(default_factory=list) # dicts: token, label, asked
|
|
51
|
+
slow: dict = field(default_factory=dict) # kind -> consecutive slow turns
|
|
52
|
+
since_check: list = field(default_factory=list) # work replies since the last passed check
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
REFUSAL = re.compile(r"(?i)\b(can.?t|cannot|unable to|won.?t|not able to|not allowed to)\b.{0,60}"
|
|
56
|
+
r"\b(provide|share|reveal|disclose|repeat|give)\b")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class SessionStop(BackendError):
|
|
60
|
+
"""The session cannot continue safely; the message says why and what to do."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class Session:
|
|
64
|
+
def __init__(self, backend, ledger, *, limits: Limits | None = None, brief=None, rule_probe=None, adopt=None):
|
|
65
|
+
self.adopt = adopt # (model_label, display) -> {measure: value}; calibrated Limits (P2)
|
|
66
|
+
self.backend = backend
|
|
67
|
+
self.ledger = ledger
|
|
68
|
+
self.limits = limits or Limits()
|
|
69
|
+
self.brief = brief or (lambda: "")
|
|
70
|
+
self.rule_probe = rule_probe # (question, check(reply_text) -> bool)
|
|
71
|
+
self.chat: ChatState | None = None
|
|
72
|
+
self.rotations = 0
|
|
73
|
+
self.work_turns = 0
|
|
74
|
+
self._labels = 0
|
|
75
|
+
self._all_tokens: set[str] = set() # every canary ever planted
|
|
76
|
+
self._asked: set[str] = set()
|
|
77
|
+
self._latency: dict = {} # kind -> [first_token_s, ...]
|
|
78
|
+
self._inconclusive = 0 # recall checks in a row that were refused, not answered
|
|
79
|
+
self._rotate_next = "" # a trigger seen after a reply: rotate before the next work turn
|
|
80
|
+
self.model_label = None
|
|
81
|
+
|
|
82
|
+
# ---------- canaries ----------
|
|
83
|
+
def _new_canary(self) -> dict:
|
|
84
|
+
while True:
|
|
85
|
+
tok = f"CANARY-{tokens.hex_token(3).upper()}"
|
|
86
|
+
if tok not in self._all_tokens:
|
|
87
|
+
self._all_tokens.add(tok)
|
|
88
|
+
break
|
|
89
|
+
self._labels += 1
|
|
90
|
+
return {"token": tok, "label": f"C{self._labels}", "asked": False}
|
|
91
|
+
|
|
92
|
+
def _forbidden_tokens(self, allowed: set) -> list:
|
|
93
|
+
"""I4: tokens that must not appear in the next prompt: asked ones, and those of other chats."""
|
|
94
|
+
mine = {c["token"] for c in (self.chat.canaries if self.chat else [])}
|
|
95
|
+
return [t for t in self._all_tokens if (t in self._asked or t not in mine) and t not in allowed]
|
|
96
|
+
|
|
97
|
+
# ---------- chats ----------
|
|
98
|
+
def _open_chat(self, reason: str) -> None:
|
|
99
|
+
handle = self.backend.new_chat(temporary=True)
|
|
100
|
+
if not handle.model_label:
|
|
101
|
+
raise SessionStop("the model label is unknown (empty); refusing to run (I9)")
|
|
102
|
+
if self.model_label is None:
|
|
103
|
+
self.model_label = handle.model_label
|
|
104
|
+
got = self.adopt(handle.model_label, getattr(self.backend, "mode_used", "") or "") if self.adopt else {}
|
|
105
|
+
if got:
|
|
106
|
+
self.limits = dataclasses.replace(self.limits, calibrated=True,
|
|
107
|
+
**{k: v for k, v in got.items() if hasattr(self.limits, k)})
|
|
108
|
+
self.ledger.append("limits", source="calibrated", **got)
|
|
109
|
+
elif handle.model_label != self.model_label:
|
|
110
|
+
raise SessionStop(f"the model changed ('{self.model_label}' -> '{handle.model_label}'); Limits belong to "
|
|
111
|
+
"a model; next: recalibrate, then start a new session (I9)")
|
|
112
|
+
self.chat = ChatState(handle=handle)
|
|
113
|
+
self.ledger.append("chat", chat_id=handle.chat_id, reason=reason, model_label=handle.model_label)
|
|
114
|
+
planted = [self._new_canary() for _ in range(max(self.limits.canaries_per_chat, 1))]
|
|
115
|
+
ack = f"ACK-{tokens.hex_token(3).upper()}"
|
|
116
|
+
opening = self.brief()
|
|
117
|
+
if len(opening) > 0.25 * self.limits.recall_chars:
|
|
118
|
+
raise SessionStop(f"the hand-over brief is {len(opening)} characters, more than 25% of the recall budget "
|
|
119
|
+
f"({int(0.25 * self.limits.recall_chars)}); the task state is too large (I5)")
|
|
120
|
+
codes = "; ".join(f"reference code {c['label']} is {c['token']}" for c in planted)
|
|
121
|
+
text = ((opening + "\n\n") if opening else "") + \
|
|
122
|
+
"These are my own test values, not secrets; I will ask for them later to check your memory. " \
|
|
123
|
+
f"Remember them and do not repeat them until I ask: {codes}.\n" \
|
|
124
|
+
f"To confirm, answer with only this token: {ack}"
|
|
125
|
+
self.chat.canaries.extend(planted)
|
|
126
|
+
r = self._send(text, kind="brief", allowed={c["token"] for c in planted})
|
|
127
|
+
if ack not in r.text:
|
|
128
|
+
raise SessionStop("the brief was not acknowledged with its token; the chat did not take the brief")
|
|
129
|
+
|
|
130
|
+
def rotate(self, reason: str) -> None:
|
|
131
|
+
self.rotations += 1
|
|
132
|
+
if self.rotations > self.limits.max_rotations:
|
|
133
|
+
raise SessionStop(f"rotation limit ({self.limits.max_rotations}) reached; last reason: {reason}")
|
|
134
|
+
self.ledger.append("rotate", reason=reason, from_chat=self.chat.handle.chat_id if self.chat else None)
|
|
135
|
+
self._open_chat(reason)
|
|
136
|
+
|
|
137
|
+
# ---------- turns ----------
|
|
138
|
+
def _send(self, prompt: str, *, kind: str, allowed: set = frozenset()):
|
|
139
|
+
c = self.chat
|
|
140
|
+
if any(t in prompt for t in self._forbidden_tokens(set(allowed))):
|
|
141
|
+
raise SessionStop(f"I4 violated: a used or foreign canary would be sent ({kind})")
|
|
142
|
+
if len(prompt) > self.limits.max_prompt_chars:
|
|
143
|
+
raise SessionStop(f"a {kind} prompt of {len(prompt)} characters is longer than the limit "
|
|
144
|
+
f"({self.limits.max_prompt_chars}); the editor could truncate it")
|
|
145
|
+
self.ledger.prompt(c.handle.chat_id, prompt, role=kind) # I3: before sending
|
|
146
|
+
reply = self.backend.send(c.handle, prompt)
|
|
147
|
+
self.ledger.reply(c.handle.chat_id, reply, role=kind)
|
|
148
|
+
c.turns += 1
|
|
149
|
+
c.chars += len(prompt) + len(reply.text)
|
|
150
|
+
self._track_latency(kind, reply.first_token_s)
|
|
151
|
+
if not (reply.complete and getattr(reply, "bound", True)):
|
|
152
|
+
raise _Unusable(kind, reply)
|
|
153
|
+
if "challenge_marker" in reply.markers:
|
|
154
|
+
raise SessionStop("a challenge or throttle marker appeared; stopping, never retrying through it (I12)")
|
|
155
|
+
return reply
|
|
156
|
+
|
|
157
|
+
def _track_latency(self, kind: str, first_token_s: float) -> None:
|
|
158
|
+
hist = self._latency.setdefault(kind, [])
|
|
159
|
+
L = self.limits
|
|
160
|
+
if len(hist) >= L.latency_baseline_turns:
|
|
161
|
+
base = statistics.median(hist[:L.latency_baseline_turns])
|
|
162
|
+
slow = first_token_s > L.latency_factor * max(base, 0.05)
|
|
163
|
+
self.chat.slow[kind] = self.chat.slow.get(kind, 0) + 1 if slow else 0
|
|
164
|
+
hist.append(first_token_s)
|
|
165
|
+
|
|
166
|
+
def _trigger(self, reply=None) -> str:
|
|
167
|
+
c, L = self.chat, self.limits
|
|
168
|
+
if reply is not None and "limit_marker" in reply.markers:
|
|
169
|
+
return "limit marker"
|
|
170
|
+
if c.turns >= L.max_turns - L.margin_turns:
|
|
171
|
+
return f"turns {c.turns} near the cap {L.max_turns}"
|
|
172
|
+
if c.chars >= L.recall_chars * L.char_safety:
|
|
173
|
+
return f"chars {c.chars} past {int(L.recall_chars * L.char_safety)}"
|
|
174
|
+
slow = [k for k, n in c.slow.items() if n >= L.latency_n]
|
|
175
|
+
if slow:
|
|
176
|
+
return f"first-token latency high for {slow[0]} turns"
|
|
177
|
+
return ""
|
|
178
|
+
|
|
179
|
+
def _recall_check(self) -> str:
|
|
180
|
+
"""One prompt: ask the oldest unasked canary by label; plant the next one in the same prompt when this chat
|
|
181
|
+
has none left in reserve. Returns a failure reason, or ''."""
|
|
182
|
+
c = self.chat
|
|
183
|
+
pending = [x for x in c.canaries if not x["asked"]]
|
|
184
|
+
if not pending:
|
|
185
|
+
return ""
|
|
186
|
+
target = pending[0]
|
|
187
|
+
target["asked"] = True
|
|
188
|
+
self._asked.add(target["token"])
|
|
189
|
+
plant = self._new_canary() if len(pending) <= 1 else None
|
|
190
|
+
prompt = (f"What is reference code {target['label']}? It is one of my own test values from earlier in this "
|
|
191
|
+
"chat. Answer with only that code.")
|
|
192
|
+
allowed = set()
|
|
193
|
+
if plant:
|
|
194
|
+
c.canaries.append(plant)
|
|
195
|
+
prompt += (f" After that, also remember reference code {plant['label']}, another test value of mine, "
|
|
196
|
+
f"without repeating it: {plant['token']}.")
|
|
197
|
+
allowed.add(plant["token"])
|
|
198
|
+
r = self._send(prompt, kind="canary", allowed=allowed)
|
|
199
|
+
if target["token"] not in r.text:
|
|
200
|
+
if REFUSAL.search(r.text):
|
|
201
|
+
# a refusal is not forgetting (live: Copilot took the codes for hidden prompt internals); one is
|
|
202
|
+
# inconclusive, two in a row count as a failure
|
|
203
|
+
self._inconclusive += 1
|
|
204
|
+
self.ledger.append("check-refused", label=target["label"], streak=self._inconclusive)
|
|
205
|
+
if self._inconclusive < 2:
|
|
206
|
+
return ""
|
|
207
|
+
return f"recall checks refused twice in a row ({target['label']})"
|
|
208
|
+
return f"canary {target['label']} not recalled"
|
|
209
|
+
self._inconclusive = 0
|
|
210
|
+
if plant and plant["token"] in r.text:
|
|
211
|
+
return f"canary {plant['label']} was repeated instead of kept"
|
|
212
|
+
if self.rule_probe:
|
|
213
|
+
question, check = self.rule_probe
|
|
214
|
+
if not check(self._send(question, kind="rule-probe").text):
|
|
215
|
+
return "rule probe failed"
|
|
216
|
+
return ""
|
|
217
|
+
|
|
218
|
+
def turn(self, prompt: str):
|
|
219
|
+
retried = False
|
|
220
|
+
while True:
|
|
221
|
+
try:
|
|
222
|
+
return self._turn_once(prompt)
|
|
223
|
+
except _Unusable as u:
|
|
224
|
+
self.ledger.append("unusable", turn_kind=u.kind, complete=u.reply.complete,
|
|
225
|
+
bound=getattr(u.reply, "bound", True), notes=u.reply.notes)
|
|
226
|
+
if retried:
|
|
227
|
+
raise SessionStop(f"two unusable replies in a row ({u.kind}); stopping (P6): "
|
|
228
|
+
f"{'; '.join(u.reply.notes) or 'incomplete'}") from None
|
|
229
|
+
retried = True
|
|
230
|
+
self.rotate(f"unusable {u.kind} reply")
|
|
231
|
+
|
|
232
|
+
def _turn_once(self, prompt: str):
|
|
233
|
+
if self.chat is None:
|
|
234
|
+
self._open_chat("start")
|
|
235
|
+
reason, self._rotate_next = self._rotate_next or self._trigger(), ""
|
|
236
|
+
if reason:
|
|
237
|
+
self.rotate(reason)
|
|
238
|
+
reply = self._send(prompt, kind="work")
|
|
239
|
+
self.work_turns += 1
|
|
240
|
+
self.chat.since_check.append(reply)
|
|
241
|
+
reason = self._trigger(reply)
|
|
242
|
+
if not reason and self.work_turns % max(self.limits.check_every, 1) == 0:
|
|
243
|
+
reason = self._recall_check()
|
|
244
|
+
if reason:
|
|
245
|
+
# the chat may have lost its context: everything answered since the last passed check is suspect
|
|
246
|
+
self.ledger.append("suspect", replies=len(self.chat.since_check), reason=reason)
|
|
247
|
+
reply = dataclasses.replace(reply, suspect=True,
|
|
248
|
+
notes=list(reply.notes) + [f"suspect: {reason}"])
|
|
249
|
+
else:
|
|
250
|
+
self.chat.since_check = []
|
|
251
|
+
if reason:
|
|
252
|
+
# deferred to the start of the next turn: the caller first executes and records this reply's step, so
|
|
253
|
+
# the hand-over brief includes it (live relay run: the brief went out while a write awaited approval)
|
|
254
|
+
self.ledger.append("trigger", reason=reason, chat_id=self.chat.handle.chat_id)
|
|
255
|
+
self._rotate_next = reason
|
|
256
|
+
return reply
|
|
257
|
+
|
|
258
|
+
def close(self) -> None:
|
|
259
|
+
self.ledger.append("end", rotations=self.rotations)
|
|
260
|
+
self.backend.close()
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class _Unusable(Exception):
|
|
264
|
+
def __init__(self, kind, reply):
|
|
265
|
+
super().__init__(kind)
|
|
266
|
+
self.kind = kind
|
|
267
|
+
self.reply = reply
|
copuppet/skin.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Skins: configuration as code for one environment (selectors, window paths, timings, sign-in, prompts).
|
|
2
|
+
|
|
3
|
+
The engine never hard-codes how a Copilot surface looks. A skin is a directory with `skin.yaml`; the path comes
|
|
4
|
+
from `--skin` or the COPUPPET_SKIN environment variable. A missing or malformed skin is an error that says what
|
|
5
|
+
to fix, never a silent default.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import yaml
|
|
14
|
+
|
|
15
|
+
FORMAT = 1
|
|
16
|
+
BACKENDS = ("edge", "winapp")
|
|
17
|
+
REQUIRED = {
|
|
18
|
+
"edge": ("url", "selectors"),
|
|
19
|
+
"winapp": ("window",),
|
|
20
|
+
}
|
|
21
|
+
EDGE_SELECTORS = ("input", "send", "reply", "busy")
|
|
22
|
+
# optional, but the backend refuses to send without the two proofs: temporary_chat, temporary_on, signed_in,
|
|
23
|
+
# model, done, code, limit_marker, error_marker, challenge_marker
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SkinError(ValueError):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Skin:
|
|
32
|
+
path: Path
|
|
33
|
+
name: str
|
|
34
|
+
backends: dict
|
|
35
|
+
prompts: dict
|
|
36
|
+
|
|
37
|
+
def backend(self, name: str) -> dict:
|
|
38
|
+
if name not in self.backends:
|
|
39
|
+
raise SkinError(f"skin '{self.name}' has no '{name}' section; add one to {self.path / 'skin.yaml'}")
|
|
40
|
+
return self.backends[name]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def locate(explicit: str | None = None) -> Path:
|
|
44
|
+
raw = explicit or os.environ.get("COPUPPET_SKIN")
|
|
45
|
+
if not raw:
|
|
46
|
+
raise SkinError("no skin given: pass --skin DIR or set COPUPPET_SKIN (see config.example/ for the format)")
|
|
47
|
+
return Path(raw).expanduser()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def load(path: str | Path | None = None) -> Skin:
|
|
51
|
+
root = locate(str(path) if path else None)
|
|
52
|
+
f = root / "skin.yaml"
|
|
53
|
+
try:
|
|
54
|
+
data = yaml.safe_load(f.read_text(encoding="utf-8")) or {}
|
|
55
|
+
except OSError as e:
|
|
56
|
+
raise SkinError(f"cannot read {f}: {e.strerror}") from None
|
|
57
|
+
except yaml.YAMLError as e:
|
|
58
|
+
raise SkinError(f"{f} is not valid YAML: {e}") from None
|
|
59
|
+
if data.get("format") != FORMAT:
|
|
60
|
+
raise SkinError(f"{f}: format is {data.get('format')!r}, this copuppet reads format {FORMAT}")
|
|
61
|
+
backends = data.get("backends") or {}
|
|
62
|
+
unknown = sorted(set(backends) - set(BACKENDS))
|
|
63
|
+
if unknown:
|
|
64
|
+
raise SkinError(f"{f}: unknown backend(s) {unknown}; known: {list(BACKENDS)}")
|
|
65
|
+
for name, section in backends.items():
|
|
66
|
+
missing = [k for k in REQUIRED[name] if not (section or {}).get(k)]
|
|
67
|
+
if missing:
|
|
68
|
+
raise SkinError(f"{f}: backend '{name}' is missing {missing}")
|
|
69
|
+
if name == "edge":
|
|
70
|
+
sel = section["selectors"]
|
|
71
|
+
gaps = [k for k in EDGE_SELECTORS if not sel.get(k)]
|
|
72
|
+
if gaps:
|
|
73
|
+
raise SkinError(f"{f}: edge selectors missing {gaps}")
|
|
74
|
+
signin = section.get("signin") or {}
|
|
75
|
+
if not isinstance(signin, dict):
|
|
76
|
+
raise SkinError(f"{f}: edge.signin must be a mapping (click_button, button)")
|
|
77
|
+
if "click_button" in signin and not isinstance(signin["click_button"], bool):
|
|
78
|
+
raise SkinError(f"{f}: edge.signin.click_button must be true or false")
|
|
79
|
+
if signin.get("click_button") and not signin.get("button"):
|
|
80
|
+
raise SkinError(f"{f}: edge.signin.click_button is on, so edge.signin.button must name the element")
|
|
81
|
+
for i, rule in enumerate(section.get("dismiss") or []):
|
|
82
|
+
if not isinstance(rule, dict) or not rule.get("when") or not rule.get("click"):
|
|
83
|
+
raise SkinError(f"{f}: edge.dismiss[{i}] needs both 'when' (the modal) and 'click' (the button)")
|
|
84
|
+
return Skin(path=root, name=str(data.get("name") or root.name), backends=backends,
|
|
85
|
+
prompts=data.get("prompts") or {})
|
copuppet/tokens.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""One source for the random tokens copuppet puts in prompts (nonces, acknowledgement tokens, canaries).
|
|
2
|
+
|
|
3
|
+
Unseeded it uses `secrets`. Seeded (`seed(n)`, or COPUPPET_SEED in the environment) it is reproducible, so a recorded
|
|
4
|
+
relay run can be replayed prompt for prompt (tests and regression runs). Never seed a real run without a reason:
|
|
5
|
+
predictable nonces only matter against an adversary who cannot see the prompt, but there is no need to give that up.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import random
|
|
11
|
+
import secrets
|
|
12
|
+
|
|
13
|
+
_rng: random.Random | None = None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def seed(value: int | None) -> None:
|
|
17
|
+
global _rng
|
|
18
|
+
_rng = random.Random(value) if value is not None else None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def hex_token(nbytes: int) -> str:
|
|
22
|
+
if _rng is None:
|
|
23
|
+
return secrets.token_hex(nbytes)
|
|
24
|
+
return "".join(f"{_rng.randrange(256):02x}" for _ in range(nbytes))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
if os.environ.get("COPUPPET_SEED"):
|
|
28
|
+
seed(int(os.environ["COPUPPET_SEED"]))
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: copuppet
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Drive Microsoft Copilot from a deterministic Python harness, as a normal user through its own UI.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: pyyaml>=6.0
|
|
9
|
+
Provides-Extra: dev
|
|
10
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
11
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
12
|
+
Provides-Extra: edge
|
|
13
|
+
Requires-Dist: playwright>=1.40; extra == 'edge'
|
|
14
|
+
Provides-Extra: mcp
|
|
15
|
+
Requires-Dist: mcp>=2.0; extra == 'mcp'
|
|
16
|
+
Provides-Extra: winapp
|
|
17
|
+
Requires-Dist: pywinauto>=0.6.8; extra == 'winapp'
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# copuppet
|
|
21
|
+
|
|
22
|
+
Drive Microsoft Copilot from a deterministic Python harness, the way a normal user does: through its own
|
|
23
|
+
window, in the user's own signed-in session. No API, no Microsoft Graph, no admin rights, no licence setup.
|
|
24
|
+
|
|
25
|
+
The idea is a two-part harness. A deterministic Python **driver** owns the plan, the inputs, the checks and
|
|
26
|
+
the record. Copilot is the **co-harness**: a flexible but unreliable language model that the driver asks for
|
|
27
|
+
the fuzzy parts (rewording, summarising, classifying, drafting) and never trusts blindly.
|
|
28
|
+
|
|
29
|
+
> Status: early. The `edge` backend works end to end, headless by default; the `winapp` backend is not
|
|
30
|
+
> implemented yet.
|
|
31
|
+
|
|
32
|
+
Three ways in, one engine:
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
copuppet ask "Name one primary colour, one word." --skin DIR # one prompt, one reply
|
|
36
|
+
copuppet drive "Does the shopping list have enough lemons for the cake?" --root DIR --skin DIR
|
|
37
|
+
copuppet mcp --root DIR --skin DIR # the same, as an MCP server (stdio)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
- **ask**: one prompt in a fresh temporary chat; the reply as text or JSON.
|
|
41
|
+
- **drive**: roles reversed. Copilot plans; copuppet executes a fixed set of actions (list, read, search, keep a
|
|
42
|
+
plan; writes only with `--allow-writes`, each one confirmed by you) inside the work folder, and shows you
|
|
43
|
+
Copilot's reasons as it goes. You talk to copuppet, never to the Copilot window: typing there would break the
|
|
44
|
+
link between each prompt and its reply.
|
|
45
|
+
- **mcp**: lets another agent hand work to Copilot through the tools `copilot_ask`, `copilot_turn` (a long session
|
|
46
|
+
that checks the chat's memory and moves to a fresh chat by itself) and `copilot_drive`. Install with
|
|
47
|
+
`copuppet[mcp]`. The work folder and whether writes are allowed are fixed when you start the server; a tool
|
|
48
|
+
call cannot change them. Writes are offered to the client as a confirmation question and declined when the
|
|
49
|
+
client cannot ask one.
|
|
50
|
+
|
|
51
|
+
Before relying on long sessions, measure your own Copilot: `copuppet calibrate --skin DIR` sends at most 45
|
|
52
|
+
paced prompts and records the longest prompt the editor accepts and how far back a chat still remembers. After
|
|
53
|
+
three runs for the same model and display, sessions use the smallest measured values instead of the cautious
|
|
54
|
+
defaults. It stops at once on any captcha, throttle or limit notice.
|
|
55
|
+
|
|
56
|
+
What `drive` will not do: leave the work folder (links, junctions, alternate data streams, network and device
|
|
57
|
+
paths are refused), read `.env` files, keys or credentials (they are not even listed), write code or scripts, or
|
|
58
|
+
send secrets it finds in files (they are redacted before anything leaves the machine). Every step is recorded in
|
|
59
|
+
a hash-chained ledger under `~/.copuppet/runs`.
|
|
60
|
+
|
|
61
|
+
## How it works
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
your script --> driver (deterministic) --> backend --> Copilot's own UI
|
|
65
|
+
^ checks every reply | (Edge or the Windows app)
|
|
66
|
+
+--------- text -----------+
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
- **Backends** talk to one Copilot surface each:
|
|
70
|
+
- `edge`: Copilot in the installed Microsoft Edge, via Playwright with a persistent profile. The user signs
|
|
71
|
+
in once, themselves; replies are read as text.
|
|
72
|
+
- `winapp`: the Windows Copilot app, via Windows UI Automation. More fragile; the app has no documented
|
|
73
|
+
element IDs.
|
|
74
|
+
- **Skins** are configuration as code: the selectors, window paths, timings and prompt templates a backend
|
|
75
|
+
needs for one environment. The engine ships only an example skin; real skins live outside this repository,
|
|
76
|
+
so a UI change is a config change, not a code change.
|
|
77
|
+
- **Every reply is untrusted text.** The driver validates it against what it asked for; it never executes it.
|
|
78
|
+
|
|
79
|
+
## Requirements
|
|
80
|
+
|
|
81
|
+
Everything installs in your own user account: no admin rights, no system-wide installer, no service.
|
|
82
|
+
|
|
83
|
+
- Windows 10 or 11, a normal user account
|
|
84
|
+
- Python 3.10 or newer, from the python.org per-user installer or `winget install Python.Python.3.13 --scope user`
|
|
85
|
+
- For `edge`: `pip install --user "copuppet[edge]"`. It drives the Microsoft Edge that Windows already has, so no
|
|
86
|
+
browser download (`playwright install`) is needed.
|
|
87
|
+
- For `winapp`: the Copilot app and `pip install --user "copuppet[winapp]"`
|
|
88
|
+
|
|
89
|
+
If your PC blocks access to PyPI, download the wheels elsewhere (`pip download "copuppet[edge]" -d wheels`) and
|
|
90
|
+
install them with `pip install --user --no-index --find-links wheels "copuppet[edge]"`.
|
|
91
|
+
|
|
92
|
+
## Use it responsibly
|
|
93
|
+
|
|
94
|
+
copuppet automates a product through its user interface. Check the terms of the Copilot service you use and,
|
|
95
|
+
on a work device, your organisation's acceptable-use policy before running it. It is meant for driving your own
|
|
96
|
+
session at human scale, not for scraping, bulk use or getting around limits.
|
|
97
|
+
|
|
98
|
+
## License
|
|
99
|
+
|
|
100
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
copuppet/__init__.py,sha256=k9PZTbA7aFHGhHtg3dPev9hBxjm6mK5K6xJJ6n2qUkI,136
|
|
2
|
+
copuppet/actions.py,sha256=SyYWCa80CUeXjVmfyGMh2FCyyrB0ynR7Dy1Sz1QLk9k,6269
|
|
3
|
+
copuppet/backend.py,sha256=eJ-sJU6GLOFpoj_6JehjHN6Yd6equwNClaLiMo0FwLE,2266
|
|
4
|
+
copuppet/calibrate.py,sha256=uEhwTJ35QxVA1Y12Tn5E6LZ0t4d5lrHVPaOrlm3UtrQ,11553
|
|
5
|
+
copuppet/cli.py,sha256=M0zjrh8Q12LmBNUcgXH55EPfHXAYF6NnnE0DBVf9Rsg,11863
|
|
6
|
+
copuppet/driver.py,sha256=_UUAyhcWnic43pBGn9p75lqDHdxRlz60fbfz9drbji0,9286
|
|
7
|
+
copuppet/fake.py,sha256=nI-umyMpfoarJrILT966Eyuo-mub02GRX1t41qIF1yw,3183
|
|
8
|
+
copuppet/ledger.py,sha256=KIgWl8dU9LEkmcvqoiA9b0XYG6CTp0ePIyHhzGpy-tA,5142
|
|
9
|
+
copuppet/mcp_server.py,sha256=LlrHFMSNRPfI7D2PS8HcD9QvCO9QYK_roVLqoaVSM1c,5984
|
|
10
|
+
copuppet/policy.py,sha256=Qv-QDLk_Tzz1NO0Z3CIthwI5m4DvqwkDzwDyQLNj2Pw,7970
|
|
11
|
+
copuppet/protocol.py,sha256=sE92rLPpDxMuhOnSGz_rf3y4GVJPbjngY7r1ivfIGQg,5713
|
|
12
|
+
copuppet/relay.py,sha256=c73wqYFJTBhDkHpp6w3VbdlJEce2GaDztRK_0VEHLqM,15321
|
|
13
|
+
copuppet/runner.py,sha256=yPLzKYNsdEBE5SA-c5rAN-al9LWpNOHPVPFOux79TgQ,4416
|
|
14
|
+
copuppet/session.py,sha256=XzQXPtdEZHhb1w9AqLhcIlMOrpSjG6cNyXQfeRzE1Z4,13681
|
|
15
|
+
copuppet/skin.py,sha256=2FsJubsY4LvNx9sMr8hPHPIiiYxLDzdScUWA2ZDMfHo,3615
|
|
16
|
+
copuppet/tokens.py,sha256=rJb0iJpXd8A-IE1grZiqXPtoVnpHg7fPKPXBEIpDFMA,938
|
|
17
|
+
copuppet/backends/__init__.py,sha256=82y8ikzKk5Fv5yZ_GoQaO7Vlxgk61jH7UlScGDR8EH0,741
|
|
18
|
+
copuppet/backends/edge.py,sha256=szxvJQCPQwuIFzSVBqowxtZ-HFi302ca0gx3ZH50l9Y,29828
|
|
19
|
+
copuppet/backends/winapp.py,sha256=poh9qXjfb10uJPxQSJFDlUzZ69Nix3kIbn4ZZLdG4FM,940
|
|
20
|
+
copuppet-0.1.0.dist-info/METADATA,sha256=cCM1Aq_50m0EUhiYgqk2eo2PEKw888WxWNBnomd5WzA,5321
|
|
21
|
+
copuppet-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
22
|
+
copuppet-0.1.0.dist-info/entry_points.txt,sha256=zTy-sOUMCiXS3rIMDIyX0GNxp9N9HAQs6tbKcZDGsyo,47
|
|
23
|
+
copuppet-0.1.0.dist-info/licenses/LICENSE,sha256=No7JpzGb2XLaaMR4TnwHUVOjnEtX_3QoEN_gdPkTmYo,1078
|
|
24
|
+
copuppet-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 copuppet contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|