copuppet 0.1.0__tar.gz
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-0.1.0/.gitattributes +1 -0
- copuppet-0.1.0/.github/workflows/release.yml +29 -0
- copuppet-0.1.0/.gitignore +11 -0
- copuppet-0.1.0/CHANGELOG.md +20 -0
- copuppet-0.1.0/CLAUDE.md +16 -0
- copuppet-0.1.0/LICENSE +21 -0
- copuppet-0.1.0/PKG-INFO +100 -0
- copuppet-0.1.0/README.md +81 -0
- copuppet-0.1.0/RELEASING.md +11 -0
- copuppet-0.1.0/config.example/skin.yaml +43 -0
- copuppet-0.1.0/docs/model.md +148 -0
- copuppet-0.1.0/pyproject.toml +27 -0
- copuppet-0.1.0/src/copuppet/__init__.py +2 -0
- copuppet-0.1.0/src/copuppet/actions.py +111 -0
- copuppet-0.1.0/src/copuppet/backend.py +70 -0
- copuppet-0.1.0/src/copuppet/backends/__init__.py +19 -0
- copuppet-0.1.0/src/copuppet/backends/edge.py +573 -0
- copuppet-0.1.0/src/copuppet/backends/winapp.py +27 -0
- copuppet-0.1.0/src/copuppet/calibrate.py +245 -0
- copuppet-0.1.0/src/copuppet/cli.py +266 -0
- copuppet-0.1.0/src/copuppet/driver.py +161 -0
- copuppet-0.1.0/src/copuppet/fake.py +73 -0
- copuppet-0.1.0/src/copuppet/ledger.py +118 -0
- copuppet-0.1.0/src/copuppet/mcp_server.py +124 -0
- copuppet-0.1.0/src/copuppet/policy.py +150 -0
- copuppet-0.1.0/src/copuppet/protocol.py +124 -0
- copuppet-0.1.0/src/copuppet/relay.py +334 -0
- copuppet-0.1.0/src/copuppet/runner.py +103 -0
- copuppet-0.1.0/src/copuppet/session.py +267 -0
- copuppet-0.1.0/src/copuppet/skin.py +85 -0
- copuppet-0.1.0/src/copuppet/tokens.py +28 -0
- copuppet-0.1.0/tests/fixtures/pantry/README.md +12 -0
- copuppet-0.1.0/tests/fixtures/pantry/recorded.json +15 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000001.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000001.q.json +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000002.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000002.q.json +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000003.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000003.q.json +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000004.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000004.q.json +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000005.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000005.q.json +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000006.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000006.q.json +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000007.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000007.q.json +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000008.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000008.q.json +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000009.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000009.q.json +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000010.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000010.q.json +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000011.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000011.q.json +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000013.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/copilot-000013.q.json +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/person-000012.a.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/done/person-000012.q.json +7 -0
- copuppet-0.1.0/tests/fixtures/pantry/run/run.json +5 -0
- copuppet-0.1.0/tests/fixtures/pantry/work/notes/fridge.md +3 -0
- copuppet-0.1.0/tests/fixtures/pantry/work/pantry.md +8 -0
- copuppet-0.1.0/tests/fixtures/pantry/work/recipes/omelette.md +2 -0
- copuppet-0.1.0/tests/fixtures/pantry/work/recipes/pancakes.md +2 -0
- copuppet-0.1.0/tests/fixtures/pantry/work/recipes/shortbread.md +2 -0
- copuppet-0.1.0/tests/fixtures/pantry/work/recipes/tomato-rice.md +2 -0
- copuppet-0.1.0/tests/test_calibrate.py +95 -0
- copuppet-0.1.0/tests/test_driver.py +202 -0
- copuppet-0.1.0/tests/test_ledger_and_fake.py +77 -0
- copuppet-0.1.0/tests/test_mcp_server.py +86 -0
- copuppet-0.1.0/tests/test_protocol_and_session.py +231 -0
- copuppet-0.1.0/tests/test_redteam_3.py +143 -0
- copuppet-0.1.0/tests/test_relay.py +186 -0
- copuppet-0.1.0/tests/test_replay_fixture.py +42 -0
- copuppet-0.1.0/tests/test_skin.py +71 -0
- copuppet-0.1.0/tools/discover_edge.py +382 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tests/fixtures/** -text
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# copuppet - PyPI release via Trusted Publishing (OIDC, no stored tokens).
|
|
2
|
+
# Runs on a published GitHub Release. Requires a configured PyPI Trusted Publisher for this repo
|
|
3
|
+
# (PyPI project settings) so the OIDC handshake can mint a short-lived upload token.
|
|
4
|
+
name: release
|
|
5
|
+
on:
|
|
6
|
+
release:
|
|
7
|
+
types: [published]
|
|
8
|
+
|
|
9
|
+
permissions:
|
|
10
|
+
contents: read
|
|
11
|
+
|
|
12
|
+
jobs:
|
|
13
|
+
pypi:
|
|
14
|
+
name: build + publish to PyPI
|
|
15
|
+
# GATED: runs only once a PyPI Trusted Publisher is configured for this repo AND the repo variable
|
|
16
|
+
# PYPI_ENABLE=true is set (Settings > Secrets and variables > Actions > Variables). Until then it is
|
|
17
|
+
# SKIPPED, so cutting a GitHub Release stays green. See RELEASING.md.
|
|
18
|
+
if: ${{ vars.PYPI_ENABLE == 'true' }}
|
|
19
|
+
runs-on: ubuntu-latest
|
|
20
|
+
environment: pypi
|
|
21
|
+
permissions:
|
|
22
|
+
id-token: write # OIDC -> PyPI Trusted Publishing (no API token)
|
|
23
|
+
steps:
|
|
24
|
+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
|
25
|
+
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
|
26
|
+
with: { python-version: '3.13' }
|
|
27
|
+
- run: pip install build
|
|
28
|
+
- run: python -m build
|
|
29
|
+
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (2026-11-29)
|
|
4
|
+
|
|
5
|
+
First release.
|
|
6
|
+
|
|
7
|
+
- `edge` backend: drives Copilot in the installed Microsoft Edge with a persistent profile; headless by default with
|
|
8
|
+
Windows single sign-on, then off-screen, then visible; paste-first input verified by read-back; reply binding
|
|
9
|
+
(each reply tied to its own prompt); stops on challenge and limit markers.
|
|
10
|
+
- `ask`: one prompt in a fresh temporary chat.
|
|
11
|
+
- Sessions: memory checks with labelled codes, chat rotation on measured limits, a hand-over brief from Python's
|
|
12
|
+
own state, suspect taint after a failed check.
|
|
13
|
+
- `calibrate`: measures the longest accepted prompt and recall depth; sessions use the measured limits after
|
|
14
|
+
three runs of the current method.
|
|
15
|
+
- `drive`: driver mode, Copilot plans and copuppet executes a fixed catalog (list, read, search, plan, ask, finish,
|
|
16
|
+
confirmed writes to an output folder) under a policy that confines paths, hides credentials and redacts secrets.
|
|
17
|
+
- `mcp`: the same as an MCP server over stdio (`copilot_ask`, `copilot_turn`, `copilot_drive`); run settings fixed
|
|
18
|
+
at start.
|
|
19
|
+
- Hash-chained ledger of every step; relay and replay backends for development and regression tests.
|
|
20
|
+
- Verified live: a read-only drive, a drive with one confirmed write, an MCP call, three calibration runs.
|
copuppet-0.1.0/CLAUDE.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# copuppet (public)
|
|
2
|
+
|
|
3
|
+
Public engine: drive Microsoft Copilot from a deterministic Python harness, as a normal user through its own UI.
|
|
4
|
+
|
|
5
|
+
- PUBLIC repository (identity Wombat164, MIT). Never commit environment details, real skins, selectors
|
|
6
|
+
discovered in a session, screenshots, account names, tenant, employer or business references, or decisions.
|
|
7
|
+
Those live in a private companion repository (decisions/, skins/); never name or link it here.
|
|
8
|
+
- Hard constraint: runs as a normal user. No Microsoft Graph, no Copilot APIs, no admin rights, no licence or
|
|
9
|
+
tenant setup, no browser download (Playwright uses the installed Edge, channel "msedge").
|
|
10
|
+
- Primarily Python; every dependency must install in user space (`pip install --user`, pipx; Python via the
|
|
11
|
+
per-user installer): no admin, no system installer, no service, no COM registration, no browser download.
|
|
12
|
+
Check a new dependency against this before adding it.
|
|
13
|
+
- Every Copilot reply is untrusted text: the driver validates it, never executes it.
|
|
14
|
+
- Skins are config as code; a UI change is a skin change. A missing or malformed skin is an error with a next
|
|
15
|
+
step, never a silent default.
|
|
16
|
+
- Tests: `python -m pytest -q`.
|
copuppet-0.1.0/LICENSE
ADDED
|
@@ -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.
|
copuppet-0.1.0/PKG-INFO
ADDED
|
@@ -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).
|
copuppet-0.1.0/README.md
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# copuppet
|
|
2
|
+
|
|
3
|
+
Drive Microsoft Copilot from a deterministic Python harness, the way a normal user does: through its own
|
|
4
|
+
window, in the user's own signed-in session. No API, no Microsoft Graph, no admin rights, no licence setup.
|
|
5
|
+
|
|
6
|
+
The idea is a two-part harness. A deterministic Python **driver** owns the plan, the inputs, the checks and
|
|
7
|
+
the record. Copilot is the **co-harness**: a flexible but unreliable language model that the driver asks for
|
|
8
|
+
the fuzzy parts (rewording, summarising, classifying, drafting) and never trusts blindly.
|
|
9
|
+
|
|
10
|
+
> Status: early. The `edge` backend works end to end, headless by default; the `winapp` backend is not
|
|
11
|
+
> implemented yet.
|
|
12
|
+
|
|
13
|
+
Three ways in, one engine:
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
copuppet ask "Name one primary colour, one word." --skin DIR # one prompt, one reply
|
|
17
|
+
copuppet drive "Does the shopping list have enough lemons for the cake?" --root DIR --skin DIR
|
|
18
|
+
copuppet mcp --root DIR --skin DIR # the same, as an MCP server (stdio)
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
- **ask**: one prompt in a fresh temporary chat; the reply as text or JSON.
|
|
22
|
+
- **drive**: roles reversed. Copilot plans; copuppet executes a fixed set of actions (list, read, search, keep a
|
|
23
|
+
plan; writes only with `--allow-writes`, each one confirmed by you) inside the work folder, and shows you
|
|
24
|
+
Copilot's reasons as it goes. You talk to copuppet, never to the Copilot window: typing there would break the
|
|
25
|
+
link between each prompt and its reply.
|
|
26
|
+
- **mcp**: lets another agent hand work to Copilot through the tools `copilot_ask`, `copilot_turn` (a long session
|
|
27
|
+
that checks the chat's memory and moves to a fresh chat by itself) and `copilot_drive`. Install with
|
|
28
|
+
`copuppet[mcp]`. The work folder and whether writes are allowed are fixed when you start the server; a tool
|
|
29
|
+
call cannot change them. Writes are offered to the client as a confirmation question and declined when the
|
|
30
|
+
client cannot ask one.
|
|
31
|
+
|
|
32
|
+
Before relying on long sessions, measure your own Copilot: `copuppet calibrate --skin DIR` sends at most 45
|
|
33
|
+
paced prompts and records the longest prompt the editor accepts and how far back a chat still remembers. After
|
|
34
|
+
three runs for the same model and display, sessions use the smallest measured values instead of the cautious
|
|
35
|
+
defaults. It stops at once on any captcha, throttle or limit notice.
|
|
36
|
+
|
|
37
|
+
What `drive` will not do: leave the work folder (links, junctions, alternate data streams, network and device
|
|
38
|
+
paths are refused), read `.env` files, keys or credentials (they are not even listed), write code or scripts, or
|
|
39
|
+
send secrets it finds in files (they are redacted before anything leaves the machine). Every step is recorded in
|
|
40
|
+
a hash-chained ledger under `~/.copuppet/runs`.
|
|
41
|
+
|
|
42
|
+
## How it works
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
your script --> driver (deterministic) --> backend --> Copilot's own UI
|
|
46
|
+
^ checks every reply | (Edge or the Windows app)
|
|
47
|
+
+--------- text -----------+
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
- **Backends** talk to one Copilot surface each:
|
|
51
|
+
- `edge`: Copilot in the installed Microsoft Edge, via Playwright with a persistent profile. The user signs
|
|
52
|
+
in once, themselves; replies are read as text.
|
|
53
|
+
- `winapp`: the Windows Copilot app, via Windows UI Automation. More fragile; the app has no documented
|
|
54
|
+
element IDs.
|
|
55
|
+
- **Skins** are configuration as code: the selectors, window paths, timings and prompt templates a backend
|
|
56
|
+
needs for one environment. The engine ships only an example skin; real skins live outside this repository,
|
|
57
|
+
so a UI change is a config change, not a code change.
|
|
58
|
+
- **Every reply is untrusted text.** The driver validates it against what it asked for; it never executes it.
|
|
59
|
+
|
|
60
|
+
## Requirements
|
|
61
|
+
|
|
62
|
+
Everything installs in your own user account: no admin rights, no system-wide installer, no service.
|
|
63
|
+
|
|
64
|
+
- Windows 10 or 11, a normal user account
|
|
65
|
+
- Python 3.10 or newer, from the python.org per-user installer or `winget install Python.Python.3.13 --scope user`
|
|
66
|
+
- For `edge`: `pip install --user "copuppet[edge]"`. It drives the Microsoft Edge that Windows already has, so no
|
|
67
|
+
browser download (`playwright install`) is needed.
|
|
68
|
+
- For `winapp`: the Copilot app and `pip install --user "copuppet[winapp]"`
|
|
69
|
+
|
|
70
|
+
If your PC blocks access to PyPI, download the wheels elsewhere (`pip download "copuppet[edge]" -d wheels`) and
|
|
71
|
+
install them with `pip install --user --no-index --find-links wheels "copuppet[edge]"`.
|
|
72
|
+
|
|
73
|
+
## Use it responsibly
|
|
74
|
+
|
|
75
|
+
copuppet automates a product through its user interface. Check the terms of the Copilot service you use and,
|
|
76
|
+
on a work device, your organisation's acceptable-use policy before running it. It is meant for driving your own
|
|
77
|
+
session at human scale, not for scraping, bulk use or getting around limits.
|
|
78
|
+
|
|
79
|
+
## License
|
|
80
|
+
|
|
81
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Releasing
|
|
2
|
+
|
|
3
|
+
1. Bump `version` in pyproject.toml and `__version__` in src/copuppet/__init__.py; add a CHANGELOG.md entry; run
|
|
4
|
+
the tests (`PYTHONPATH="src;tests" python -m pytest -q`).
|
|
5
|
+
2. Tag `vX.Y.Z` on main, push the tag, and publish a GitHub Release for it.
|
|
6
|
+
3. The `release` workflow builds and uploads to PyPI through Trusted Publishing (OIDC, no stored token). It runs
|
|
7
|
+
only when both are set up once:
|
|
8
|
+
- on PyPI: a (pending) Trusted Publisher for project `copuppet`, owner and repository of this GitHub repo,
|
|
9
|
+
workflow `release.yml`, environment `pypi`;
|
|
10
|
+
- on GitHub: the repository variable `PYPI_ENABLE=true` and an environment named `pypi`.
|
|
11
|
+
Until then the job is skipped and the release stays green.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Example skin: the shape only. Real values (selectors, window paths) are discovered in a supervised session and
|
|
2
|
+
# kept in your own, private skin directory; point copuppet at it with --skin DIR or COPUPPET_SKIN.
|
|
3
|
+
format: 1
|
|
4
|
+
name: example
|
|
5
|
+
|
|
6
|
+
backends:
|
|
7
|
+
edge:
|
|
8
|
+
url: "https://copilot.microsoft.com/" # the Copilot page the user opens in Edge
|
|
9
|
+
profile_dir: "~/.copuppet/edge-profile" # persistent profile: sign in once, by hand
|
|
10
|
+
display: auto # auto: headless, then an off-screen window, then visible (for a manual login)
|
|
11
|
+
input_mode: auto # auto: paste the text in one go (verified by read-back), then type as fallback
|
|
12
|
+
selectors: # CSS or role-based selectors
|
|
13
|
+
input: "REPLACE: the prompt box" # required
|
|
14
|
+
send: "REPLACE: the send button" # required
|
|
15
|
+
reply: "REPLACE: every reply node (one per answer)" # required
|
|
16
|
+
busy: "REPLACE: shown while a reply is still being written" # required
|
|
17
|
+
user_message: "REPLACE: every message node you sent" # binds each reply to its prompt; strongly advised
|
|
18
|
+
done: "REPLACE: appears inside a reply once it is finished" # optional, scoped to the new reply
|
|
19
|
+
temporary_chat: "REPLACE: the temporary-chat toggle" # optional: makes chats that are not kept
|
|
20
|
+
temporary_on: "REPLACE: the same toggle when it is on"
|
|
21
|
+
signed_in: "REPLACE: an element only shown when signed in"
|
|
22
|
+
model: "REPLACE: the model selector (its label is the model name)"
|
|
23
|
+
code: "REPLACE: a code block inside a reply"
|
|
24
|
+
code_text: "REPLACE: the text area inside that code block"
|
|
25
|
+
challenge_marker: "REPLACE: a captcha or throttle notice" # optional: seen means stop at once
|
|
26
|
+
limit_marker: "REPLACE: a conversation-limit notice" # optional: seen means a fresh chat
|
|
27
|
+
timeouts: {reply_seconds: 120, settle_seconds: 1.5}
|
|
28
|
+
signin:
|
|
29
|
+
click_button: false # true: copuppet presses the site's own Sign in button once; the login form
|
|
30
|
+
# itself is always completed by the person, copuppet never types into it
|
|
31
|
+
button: "button:has-text('Sign in')"
|
|
32
|
+
dismiss: # page modals copuppet may close; unknown modals are only reported, never clicked
|
|
33
|
+
- when: "[role='dialog']:has-text('cookies')"
|
|
34
|
+
click: "button:has-text('Reject')" # prefer the button that declines optional cookies
|
|
35
|
+
|
|
36
|
+
winapp:
|
|
37
|
+
window: {title_re: "REPLACE: the Copilot window title"}
|
|
38
|
+
elements:
|
|
39
|
+
input: "REPLACE: UI Automation path of the prompt box"
|
|
40
|
+
reply: "REPLACE: UI Automation path of the reply area"
|
|
41
|
+
|
|
42
|
+
prompts:
|
|
43
|
+
summarise: "Summarise the following in three sentences:\n\n{text}"
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# copuppet model: chat lifecycle, calibration, and driver mode (v3)
|
|
2
|
+
|
|
3
|
+
v3 (2026-11-29) folds in a second red team, after the first live multi-turn sessions. v2 fixed the first red team.
|
|
4
|
+
Every finding is either a rule below or listed under "Build next". Scope: how much a Copilot chat can hold, when to
|
|
5
|
+
rotate, and how to reverse roles so Copilot plans while Python executes.
|
|
6
|
+
|
|
7
|
+
## Principles
|
|
8
|
+
- **P1 Python owns all state**, including the plan and step ids. A chat is a disposable worker.
|
|
9
|
+
- **P2 Measure, do not assume.** Limits are calibrated (n >= 3, keep the minimum, dated, keyed) or marked as
|
|
10
|
+
uncalibrated conservative defaults.
|
|
11
|
+
- **P3 Deterministic decisions.** Rotation, validation and stopping are rules over counted facts.
|
|
12
|
+
- **P4 Untrusted both ways.** Replies are untrusted input; everything sent leaves the machine.
|
|
13
|
+
- **P5 Fail closed, with a reason.** When a precondition cannot be proven, stop instead of continuing weaker.
|
|
14
|
+
- **P6 An incomplete or unbound reply is never usable.** Not for actions, not for canary checks, not returned as an
|
|
15
|
+
answer.
|
|
16
|
+
|
|
17
|
+
## Backend contract
|
|
18
|
+
```
|
|
19
|
+
probe() -> Probe{temporary, signed_in, model_label, display, busy, markers[], url}
|
|
20
|
+
new_chat(temporary) -> ChatHandle{chat_id, started_at, temporary, model_label, display}
|
|
21
|
+
send(chat, prompt) -> Reply{text, code_blocks[], complete, bound, prompt_chars_accepted, prompt_lines,
|
|
22
|
+
type_s, first_token_s, gen_s, markers[], model_label, notes[]}
|
|
23
|
+
ask(prompt) -> new temporary chat + send; close()
|
|
24
|
+
```
|
|
25
|
+
- **Display** (`edge.display`): `auto` = headless, then offscreen, then visible. One-way, and **never on a challenge**:
|
|
26
|
+
a challenge or throttle marker stops the run (it is not a display problem). A manual sign-in is only possible in
|
|
27
|
+
`visible`; in headless and offscreen a sign-in that SSO cannot finish is an error naming `--display visible`.
|
|
28
|
+
Live: headless works, including Windows single sign-on.
|
|
29
|
+
- **Input**: paste first (verified by read-back), typing as fallback; Shift+Enter between lines when typing.
|
|
30
|
+
Read-back compares normalised text (whitespace, zero-width characters U+200B U+200C removed) AND the line count.
|
|
31
|
+
- **Preconditions before every send** (I7, I9, I11): signed in; temporary when asked; model label non-empty and equal
|
|
32
|
+
to the chat's; **not busy**; no challenge marker. Notes from `new_chat` are kept, not reset.
|
|
33
|
+
- **Fail closed on state proofs**: temporary chat = toggle `aria-pressed=true`; signed in = account element; model =
|
|
34
|
+
model selector label. An empty label is "unknown", which fails I9.
|
|
35
|
+
|
|
36
|
+
## Reply binding (new in v3, I10 and I11)
|
|
37
|
+
Before submitting, every existing reply node AND every existing user-message node is marked (`data-copuppet-seen`).
|
|
38
|
+
- **Submitted** = a new unmarked user-message node appears. Only then is the prompt counted as sent.
|
|
39
|
+
- **Resubmit (I10)** only when there is proof that nothing was sent: no new user-message node and no new reply node
|
|
40
|
+
by `start_timeout`. An empty editor alone is not proof (it is also what a successful submit looks like).
|
|
41
|
+
- **First token** = busy marker appears, or a new unmarked reply node appears.
|
|
42
|
+
- **Bound reply (I11)**: exactly one new reply node, placed after THIS turn's user-message node in document order;
|
|
43
|
+
busy was seen and is now gone (or the scoped `done` marker of that node is visible); its text is stable for
|
|
44
|
+
`settle_seconds`. Otherwise the reply is not bound and P6 applies.
|
|
45
|
+
- **Earlier nodes may change** (live): Copilot re-renders an earlier reply as an identical, unmarked copy (matched by
|
|
46
|
+
normalised text, not counted as new) and drops the oldest replies from the DOM as the chat grows (virtualised:
|
|
47
|
+
noted, not a failure, because a vanished node cannot pose as new). Requiring "all marked nodes intact" caused a
|
|
48
|
+
false rotation after every recall check.
|
|
49
|
+
- `done` is scoped to the new reply node, never page-global.
|
|
50
|
+
|
|
51
|
+
## Entities
|
|
52
|
+
| Entity | Holds |
|
|
53
|
+
|---|---|
|
|
54
|
+
| `Session` | backend, skin, Policy, Limits, Ledger, current Chat |
|
|
55
|
+
| `Chat` | chat_id, display, model_label, turns by kind, chars, canaries[], state |
|
|
56
|
+
| `Turn` | kind (`brief`, `work`, `canary`, `canary-plant`, `rule-probe`), prompt hash and length, Reply, timing |
|
|
57
|
+
| `Task` / `Plan` / `Action` / `Observation` / `Policy` | as in v2 (driver mode); step ids are issued by Python |
|
|
58
|
+
| `Limits` | keyed by (skin, signed_in, model_label, display, locale); samples[] {n, min, date} |
|
|
59
|
+
| `Ledger` | hash-chained JSONL, fsync per entry, in-memory step index, tolerant of a torn last line |
|
|
60
|
+
|
|
61
|
+
## Chat lifecycle
|
|
62
|
+
States: `NEW -> BRIEFING -> ACTIVE -> SUBMITTED -> ACTIVE ...`, side states `AWAITING_CONFIRM`, `PAUSED_HUMAN`
|
|
63
|
+
(visible display only), `ROTATING`, terminal `CLOSED`, `FAILED`.
|
|
64
|
+
- `BRIEFING`: the brief's acknowledgement is verified (it must echo the turn nonce), not assumed. Prompts never use
|
|
65
|
+
imperative acknowledgement phrases such as "Reply OK." (consumer Copilot turned one into an email draft); they ask
|
|
66
|
+
for a token instead.
|
|
67
|
+
- An **incomplete or unbound turn**: rotate, retry once in a new chat; a second failure stops (P6).
|
|
68
|
+
- A **failed recall check** taints every work reply since the last passed check (`suspect=true`); the driver must not
|
|
69
|
+
act on a suspect reply.
|
|
70
|
+
|
|
71
|
+
**Rotation triggers** (first match wins): limit marker; recall failure; turns (all kinds count) near the cap; counted
|
|
72
|
+
characters (all kinds) >= recall_chars * 0.5; first-token latency, **per turn kind**, against a measured baseline;
|
|
73
|
+
model label changed (stop or recalibrate: Limits belong to a model). A rotation opens a new chat in the same browser;
|
|
74
|
+
the hand-over brief comes from the Ledger and Plan and must stay within 25% of the recall budget (I5, enforced).
|
|
75
|
+
|
|
76
|
+
**Recall checks**: N labelled, single-use canaries (C1, C2, ...) planted in the brief, so depth is tested; each check
|
|
77
|
+
asks the OLDEST unasked one by label, after zero-width stripping of the reply; never a canary from an earlier chat in a
|
|
78
|
+
later prompt (I4 covers asked AND planted-unasked tokens, except the one being planted). Ask and the next plant can
|
|
79
|
+
share one prompt (fewer turns).
|
|
80
|
+
|
|
81
|
+
## Calibration (`copuppet calibrate`)
|
|
82
|
+
As v2: keyed and dated `Limits`, n >= 3, minimum kept; `max_prompt_chars`, `max_turns`, recall depth with labelled
|
|
83
|
+
canaries and driver-like filler, temporary-chat and memory semantics, typical first token per turn kind. Human-scale
|
|
84
|
+
pacing, a prompt budget, and an immediate stop on any challenge or throttle marker.
|
|
85
|
+
|
|
86
|
+
## Driver mode (roles reversed; built 2026-11-29)
|
|
87
|
+
As v2, with: step ids issued by Python (Copilot echoes them); strict JSON (duplicate keys and NaN rejected);
|
|
88
|
+
`intent` in the Ledger counts as executed (I2 survives a crash between intent and result); suspect replies are
|
|
89
|
+
never acted on (the step is asked again in the fresh chat).
|
|
90
|
+
- Front ends: `copuppet drive` (the person confirms writes and answers questions in the terminal) and
|
|
91
|
+
`copuppet mcp` (stdio). The person or calling agent talks to copuppet, never to the Copilot window.
|
|
92
|
+
- MCP: run settings (root, writes, display, skin) fixed at server start, never by tool arguments; one worker
|
|
93
|
+
thread (Playwright objects are thread-bound; one profile, calls queue); writes need `--allow-writes` AND an
|
|
94
|
+
approved elicitation over a session with a back-channel. The stateless protocol has none (its input-required
|
|
95
|
+
round trip re-runs the tool, and a driver run cannot be replayed), so writes are declined there. An agent client
|
|
96
|
+
may answer an elicitation itself.
|
|
97
|
+
- Recall checks are worded as the user's own test values, not secrets (live: under a planner brief Copilot refused
|
|
98
|
+
"hidden system or prompt-internal reference codes", which looked like forgetting). A refusal is inconclusive;
|
|
99
|
+
two in a row count as a failure.
|
|
100
|
+
- Live 2026-11-29: a read-only drive on a test folder answered two questions correctly in 8 steps, one chat, no
|
|
101
|
+
`.env` content or name sent; MCP over stdio answered a `copilot_ask` in 14.7 s including Edge start.
|
|
102
|
+
|
|
103
|
+
## Relay and replay (development, built 2026-11-29)
|
|
104
|
+
The relay backend replaces the browser with files so an outside stand-in (in development: a subagent) plays Copilot
|
|
105
|
+
on one channel and the person on another, while the harness stays exactly the same. Red team 4 hardened it: a run
|
|
106
|
+
folder per run; questions carry a random token their answer must echo (no pre-created or stale answers); ids are
|
|
107
|
+
digits only; malformed answers are backend errors; a write approval must quote the content's sha256 prefix and a
|
|
108
|
+
timeout declines; answers may carry `complete`, `bound`, `markers`, `model_label`, `first_token_s`, so P6, I9, I12
|
|
109
|
+
and rotation triggers are testable through the relay. One token source (`tokens.py`, seeded per relay run and
|
|
110
|
+
recorded in run.json) makes a finished run replayable prompt for prompt (`ReplayBackend`), with divergence
|
|
111
|
+
reported at the exact character. Any backend error ends a drive with a `task-end` record. The relay cannot stop
|
|
112
|
+
one stand-in from reading its own earlier items; a faithful memory test needs a fresh stand-in per chat.
|
|
113
|
+
Done 2026-11-29: a fresh haiku stand-in per chat with `--max-chat-turns 6` carried a 9-step task (read, write approved by hash, finish) across a hand-over from the brief alone; each stand-in reported the brief as enough. That run found that a rotation triggered after a reply sent the new brief before the step executed (now deferred to the next turn) and is kept as the replay fixture `tests/fixtures/pantry`.
|
|
114
|
+
|
|
115
|
+
## Invariants (each a test on the fake backend)
|
|
116
|
+
I1 execute only when complete, bound, nonce match, exactly one code block. I2 at most once per step, keyed on intent.
|
|
117
|
+
I3 prompt logged before send. I4 no canary token from an earlier chat or an asked one in a later prompt. I5 brief
|
|
118
|
+
<= 25% of the recall budget, enforced. I6 paths inside the root. I7 temporary and signed in before each send.
|
|
119
|
+
I8 exactly one new reply node per turn (identity marks, not counts). I9 model label non-empty and unchanged.
|
|
120
|
+
**I10** resubmit only with proof of no new user message. **I11** a reply is bound only as defined above.
|
|
121
|
+
**I12** a challenge marker stops the run; no display fallback, no retry.
|
|
122
|
+
|
|
123
|
+
## Verified live (2026-11-29)
|
|
124
|
+
Temporary chat is an `aria-pressed` toggle; Shift+Enter newline; zero-width characters at line ends; the editor
|
|
125
|
+
re-renders after a chat switch (keystrokes within ~1-2 s lost; a marked node stable for 1 s is ready); code blocks
|
|
126
|
+
are a "Code Preview" component with a "Code editor" textbox (read with inner_text); reply counts flicker while a
|
|
127
|
+
placeholder is swapped (identity marks needed); earlier replies are re-rendered or virtualised away as the chat grows;
|
|
128
|
+
user messages are `data-testid=chatQuestion` nodes; headless with SSO works; a plain turn ~4.6 s, a turn with a merged
|
|
129
|
+
recall check ~9 s (two-prompt checks were ~15 s); "Reply OK." triggered an email draft (briefs now ask for a token).
|
|
130
|
+
|
|
131
|
+
## Build next (red team 2, in order; items 1-5 built 2026-11-29)
|
|
132
|
+
1. Reply binding I10, I11: mark user messages too; precondition "not busy"; scoped `done`; busy seen then gone;
|
|
133
|
+
marked-node check at the end; read-back line count.
|
|
134
|
+
2. Session: incomplete or unbound means rotate and retry once, else stop; suspect taint after a failed recall;
|
|
135
|
+
I4 over all planted tokens; I5 enforced; latency baseline per turn kind; I9 fails closed on empty labels.
|
|
136
|
+
3. Display fallback: no fallback on challenge (I12); headless sign-in error names `--display visible`; keep
|
|
137
|
+
`new_chat` notes.
|
|
138
|
+
4. Ledger: in-memory step index, intent counts as executed, fsync, torn-tail tolerance.
|
|
139
|
+
5. Protocol: reject duplicate keys and NaN; Python-issued step ids; acknowledgements by token, not "Reply OK.".
|
|
140
|
+
6. Calibration, driver mode and MCP: built. First calibration sample (2026-11-29, headless, model label "Auto", 45
|
|
141
|
+
prompts, no throttle): prompts up to ~32,000 characters accepted intact (the largest probe); a turn-1 code still
|
|
142
|
+
recalled after 36 turns / ~89,000 characters (budget reached before any failure). Both are lower bounds; the
|
|
143
|
+
defaults (8,000 / 20,000) stay until 3 samples exist. Method 2 (three runs, identical): prompt cap between 127,960 (answered) and 135,885 (never submitted); recall >= 378,000 characters / 21 turns. Adopted live: max_prompt_chars 115,164 (90%), recall_chars 377,998 (rotation at half).
|
|
144
|
+
The first-token median (0.03 s) only shows that the busy marker appears at once; it is not a latency measure.
|
|
145
|
+
|
|
146
|
+
## Open (not verified)
|
|
147
|
+
Whether reply images auto-load; consumer memory across temporary chats; current per-message and turn limits; long
|
|
148
|
+
code blocks virtualised; the user-message node selector (to discover).
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "copuppet"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Drive Microsoft Copilot from a deterministic Python harness, as a normal user through its own UI."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = ["pyyaml>=6.0"]
|
|
13
|
+
|
|
14
|
+
[project.optional-dependencies]
|
|
15
|
+
edge = ["playwright>=1.40"]
|
|
16
|
+
winapp = ["pywinauto>=0.6.8"]
|
|
17
|
+
mcp = ["mcp>=2.0"]
|
|
18
|
+
dev = ["pytest>=8.0", "ruff>=0.6"]
|
|
19
|
+
|
|
20
|
+
[project.scripts]
|
|
21
|
+
copuppet = "copuppet.cli:main"
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel]
|
|
24
|
+
packages = ["src/copuppet"]
|
|
25
|
+
|
|
26
|
+
[tool.ruff]
|
|
27
|
+
line-length = 120
|
|
@@ -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}"}
|