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/__init__.py
ADDED
copuppet/actions.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""The fixed action catalog for driver mode. Each action is a plain Python function over the Policy; Copilot can
|
|
2
|
+
only name these, with arguments that pass the protocol's schema check first.
|
|
3
|
+
|
|
4
|
+
Effects: read (no change), write-local (inside the output folder, needs the person's confirmation), external (none
|
|
5
|
+
built in). `set_plan` stores the plan in Python (P1); `ask_user` and `finish` carry Copilot text that is shown to the
|
|
6
|
+
person labelled as Copilot output, never as instructions.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import fnmatch
|
|
11
|
+
import hashlib
|
|
12
|
+
|
|
13
|
+
CATALOG = {
|
|
14
|
+
"set_plan": {"args": {"steps": "list"}, "required": ["steps"], "effect": "read"},
|
|
15
|
+
"list_dir": {"args": {"path": "str"}, "required": [], "effect": "read"},
|
|
16
|
+
"read_file": {"args": {"path": "str", "start_line": "int", "max_lines": "int"}, "required": ["path"],
|
|
17
|
+
"effect": "read"},
|
|
18
|
+
"search_text": {"args": {"query": "str", "path": "str", "glob": "str"}, "required": ["query"], "effect": "read"},
|
|
19
|
+
"write_file": {"args": {"path": "str", "text": "str"}, "required": ["path", "text"], "effect": "write-local"},
|
|
20
|
+
"ask_user": {"args": {"question": "str"}, "required": ["question"], "effect": "read"},
|
|
21
|
+
"finish": {"args": {"answer": "str"}, "required": ["answer"], "effect": "read"},
|
|
22
|
+
}
|
|
23
|
+
TEXT_EXTS = {".txt", ".md", ".csv", ".json", ".yaml", ".yml", ".log", ".ini", ".toml", ".xml", ".html", ".py", ".ps1",
|
|
24
|
+
".js", ".ts", ".sql", ".cfg", ".tsv"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _clip(text: str, limit: int) -> str:
|
|
28
|
+
data = text.encode("utf-8")
|
|
29
|
+
if len(data) <= limit:
|
|
30
|
+
return text
|
|
31
|
+
return data[:limit].decode("utf-8", "ignore") + f"\n[... clipped at {limit} bytes]"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def run(action, policy, *, plan: list, confirm, ask) -> dict:
|
|
35
|
+
"""Execute one validated Action. Returns {"ok", "observation", "done"?, "answer"?}. Never raises for a policy
|
|
36
|
+
refusal: the refusal is the observation, so Copilot can adjust."""
|
|
37
|
+
a = action.args
|
|
38
|
+
if action.name == "set_plan":
|
|
39
|
+
steps = [str(s)[:200] for s in a["steps"]][:20]
|
|
40
|
+
plan[:] = steps
|
|
41
|
+
return {"ok": True, "observation": "plan stored:\n" + "\n".join(f"{i + 1}. {s}" for i, s in enumerate(steps))}
|
|
42
|
+
if action.name == "list_dir":
|
|
43
|
+
d = policy.resolve(a.get("path", "") or ".")
|
|
44
|
+
if not d.is_dir():
|
|
45
|
+
return {"ok": False, "observation": f"not a folder: {a.get('path', '.')}"}
|
|
46
|
+
rows = []
|
|
47
|
+
for p in sorted(d.iterdir(), key=lambda x: (not x.is_dir(), x.name.lower()))[:200]:
|
|
48
|
+
try:
|
|
49
|
+
policy.resolve(p.relative_to(policy.root).as_posix())
|
|
50
|
+
except PermissionError:
|
|
51
|
+
continue # denied entries are not even listed
|
|
52
|
+
rows.append(f"{p.name}/" if p.is_dir() else f"{p.name} ({p.stat().st_size} bytes)")
|
|
53
|
+
return {"ok": True, "observation": "\n".join(rows) or "(empty)"}
|
|
54
|
+
if action.name == "read_file":
|
|
55
|
+
f = policy.resolve(a["path"])
|
|
56
|
+
if not f.is_file():
|
|
57
|
+
return {"ok": False, "observation": f"not a file: {a['path']}"}
|
|
58
|
+
if f.suffix.lower() not in TEXT_EXTS:
|
|
59
|
+
return {"ok": False, "observation": f"only text files can be read ({f.suffix or 'no extension'})"}
|
|
60
|
+
if f.stat().st_size > policy.max_file_bytes:
|
|
61
|
+
return {"ok": False, "observation": f"the file is larger than {policy.max_file_bytes} bytes"}
|
|
62
|
+
lines = f.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
63
|
+
start = max(int(a.get("start_line", 1)), 1)
|
|
64
|
+
count = min(max(int(a.get("max_lines", 200)), 1), 2000)
|
|
65
|
+
chunk = lines[start - 1:start - 1 + count]
|
|
66
|
+
body = "\n".join(f"{start + i}: {line}" for i, line in enumerate(chunk))
|
|
67
|
+
more = f"\n[{len(lines)} lines in total]" if start - 1 + count < len(lines) else ""
|
|
68
|
+
return {"ok": True, "observation": _clip(body + more, policy.max_read_bytes)}
|
|
69
|
+
if action.name == "search_text":
|
|
70
|
+
d = policy.resolve(a.get("path", "") or ".")
|
|
71
|
+
pattern = a.get("glob") or "*"
|
|
72
|
+
q = a["query"].lower()
|
|
73
|
+
hits = []
|
|
74
|
+
for f in sorted(d.rglob("*")):
|
|
75
|
+
if len(hits) >= 100:
|
|
76
|
+
break
|
|
77
|
+
if not f.is_file() or f.suffix.lower() not in TEXT_EXTS or not fnmatch.fnmatch(f.name, pattern):
|
|
78
|
+
continue
|
|
79
|
+
if f.stat().st_size > policy.max_file_bytes:
|
|
80
|
+
continue
|
|
81
|
+
rel = f.relative_to(policy.root).as_posix()
|
|
82
|
+
try:
|
|
83
|
+
policy.resolve(rel)
|
|
84
|
+
except PermissionError:
|
|
85
|
+
continue
|
|
86
|
+
for n, line in enumerate(f.read_text(encoding="utf-8", errors="replace").splitlines(), 1):
|
|
87
|
+
if q in line.lower():
|
|
88
|
+
hits.append(f"{rel}:{n}: {line.strip()[:200]}")
|
|
89
|
+
if len(hits) >= 100:
|
|
90
|
+
break
|
|
91
|
+
return {"ok": True, "observation": _clip("\n".join(hits) or "(no matches)", policy.max_read_bytes)}
|
|
92
|
+
if action.name == "write_file":
|
|
93
|
+
policy.allow_effect("write-local")
|
|
94
|
+
target = policy.resolve(a["path"], for_write=True)
|
|
95
|
+
if target.exists():
|
|
96
|
+
return {"ok": False, "observation": f"{a['path']} already exists; choose a new name (no overwrites)"}
|
|
97
|
+
text = a["text"]
|
|
98
|
+
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]
|
|
99
|
+
preview = text[:300] + ("..." if len(text) > 300 else "")
|
|
100
|
+
if not confirm(f"Copilot asks to write a NEW file {target.relative_to(policy.output).as_posix()} in the output folder ({len(text)} characters, sha256 {digest}). "
|
|
101
|
+
f"Start of the text:\n{preview}\n"):
|
|
102
|
+
return {"ok": False, "observation": "the person declined this write"}
|
|
103
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
104
|
+
with target.open("x", encoding="utf-8") as fh: # never overwrite, even if created meanwhile
|
|
105
|
+
fh.write(text)
|
|
106
|
+
return {"ok": True, "observation": f"wrote {target.relative_to(policy.output).as_posix()}"}
|
|
107
|
+
if action.name == "ask_user":
|
|
108
|
+
return {"ok": True, "observation": "the person answered:\n" + ask(a["question"])}
|
|
109
|
+
if action.name == "finish":
|
|
110
|
+
return {"ok": True, "observation": "finished", "done": True, "answer": a["answer"]}
|
|
111
|
+
return {"ok": False, "observation": f"unknown action {action.name}"}
|
copuppet/backend.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""The contract every Copilot surface implements (model v2, docs/model.md). The driver depends on this, never on a
|
|
2
|
+
concrete backend."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Protocol
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class Probe:
|
|
11
|
+
"""What the page proves right now. Unknown is False: P5, fail closed."""
|
|
12
|
+
temporary: bool
|
|
13
|
+
signed_in: bool
|
|
14
|
+
model_label: str
|
|
15
|
+
markers: list[str]
|
|
16
|
+
reply_count: int
|
|
17
|
+
url: str
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class ChatHandle:
|
|
22
|
+
chat_id: int
|
|
23
|
+
started_at: float
|
|
24
|
+
temporary: bool
|
|
25
|
+
model_label: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Reply:
|
|
30
|
+
"""What a backend read back. `complete` False means the driver must not act on it (I1)."""
|
|
31
|
+
text: str
|
|
32
|
+
backend: str
|
|
33
|
+
complete: bool
|
|
34
|
+
seconds: float
|
|
35
|
+
notes: list[str] = field(default_factory=list)
|
|
36
|
+
code_blocks: list[str] = field(default_factory=list)
|
|
37
|
+
prompt_chars_accepted: int = 0
|
|
38
|
+
type_s: float = 0.0
|
|
39
|
+
first_token_s: float = 0.0
|
|
40
|
+
gen_s: float = 0.0
|
|
41
|
+
markers: list[str] = field(default_factory=list)
|
|
42
|
+
model_label: str = ""
|
|
43
|
+
bound: bool = True # I11: exactly this turn's reply (identity marks intact)
|
|
44
|
+
suspect: bool = False # answered since the last passed recall check, which then failed
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class BackendError(RuntimeError):
|
|
48
|
+
"""The backend could not do its job, with a reason a person can act on."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Backend(Protocol):
|
|
52
|
+
name: str
|
|
53
|
+
|
|
54
|
+
def ready(self) -> list[str]:
|
|
55
|
+
"""Problems that would stop the backend from working, each with a next step; empty when ready."""
|
|
56
|
+
|
|
57
|
+
def probe(self) -> Probe:
|
|
58
|
+
"""The current, proven page state."""
|
|
59
|
+
|
|
60
|
+
def new_chat(self, *, temporary: bool = True) -> ChatHandle:
|
|
61
|
+
"""Start a fresh chat; fails closed when a temporary chat was asked for and cannot be proven."""
|
|
62
|
+
|
|
63
|
+
def send(self, chat: ChatHandle, prompt: str, *, timeout: float | None = None) -> Reply:
|
|
64
|
+
"""One turn in an existing chat. Asserts the chat's preconditions (I7, I9) before typing."""
|
|
65
|
+
|
|
66
|
+
def ask(self, prompt: str, *, timeout: float | None = None) -> Reply:
|
|
67
|
+
"""Convenience: one prompt in a new temporary chat."""
|
|
68
|
+
|
|
69
|
+
def close(self) -> None:
|
|
70
|
+
"""Release the window or browser; never sign the user out."""
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Backends, one per Copilot surface. Each is imported lazily, so the optional dependency of one (Playwright,
|
|
2
|
+
pywinauto) is never needed to use another."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ..backend import Backend, BackendError
|
|
6
|
+
from ..skin import Skin
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def make(name: str, skin: Skin) -> Backend:
|
|
10
|
+
if name == "edge":
|
|
11
|
+
from .edge import EdgeBackend
|
|
12
|
+
return EdgeBackend(skin.backend("edge"))
|
|
13
|
+
if name == "winapp":
|
|
14
|
+
from .winapp import WinAppBackend
|
|
15
|
+
return WinAppBackend(skin.backend("winapp"))
|
|
16
|
+
if name == "relay":
|
|
17
|
+
from ..relay import RelayBackend
|
|
18
|
+
return RelayBackend(skin.backends.get("relay", {}))
|
|
19
|
+
raise BackendError(f"unknown backend '{name}'; known: edge, winapp, relay")
|