rigsby-server 0.3.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.
- rigsby_server/__init__.py +2 -0
- rigsby_server/activity.py +210 -0
- rigsby_server/agent/__init__.py +0 -0
- rigsby_server/agent/claude.py +237 -0
- rigsby_server/agent/context.py +65 -0
- rigsby_server/agent/executor.py +102 -0
- rigsby_server/agent/orchestrator.py +740 -0
- rigsby_server/agent/planner.py +386 -0
- rigsby_server/agent/safety.py +59 -0
- rigsby_server/app.py +310 -0
- rigsby_server/cli.py +180 -0
- rigsby_server/clipboard.py +94 -0
- rigsby_server/connectors/__init__.py +0 -0
- rigsby_server/connectors/atlas.py +217 -0
- rigsby_server/connectors/github.py +174 -0
- rigsby_server/connectors/slack.py +177 -0
- rigsby_server/devices.py +85 -0
- rigsby_server/enrollment.py +146 -0
- rigsby_server/history.py +75 -0
- rigsby_server/jobs.py +237 -0
- rigsby_server/laptops.py +184 -0
- rigsby_server/mail.py +74 -0
- rigsby_server/memory.py +100 -0
- rigsby_server/phone_link.py +168 -0
- rigsby_server/phone_voice.py +134 -0
- rigsby_server/profile.py +82 -0
- rigsby_server/profiles.py +209 -0
- rigsby_server/room_ids.py +93 -0
- rigsby_server/rooms.py +206 -0
- rigsby_server/runs.py +223 -0
- rigsby_server/sync.py +164 -0
- rigsby_server-0.3.0.dist-info/METADATA +57 -0
- rigsby_server-0.3.0.dist-info/RECORD +36 -0
- rigsby_server-0.3.0.dist-info/WHEEL +4 -0
- rigsby_server-0.3.0.dist-info/entry_points.txt +2 -0
- rigsby_server-0.3.0.dist-info/licenses/LICENSE +661 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""A public, redacted activity log of the Rigsby server.
|
|
2
|
+
|
|
3
|
+
The static page at the server's root (deploy/activity/index.html, served by nginx) polls
|
|
4
|
+
`GET /activity.json` and shows lines such as "Laptop asked the phone to lock" or "Claude chose the
|
|
5
|
+
next step: tap".
|
|
6
|
+
|
|
7
|
+
Redaction is by construction: every line is built from fixed phrases in this file, chosen by the
|
|
8
|
+
*kind* of event (a request method, a phone command path, an action type, a task status). Nothing
|
|
9
|
+
from a request's content is ever copied in: no objective or prompt, typed text, app or package name,
|
|
10
|
+
coordinates, screen content, Slack or GitHub names, answers, summaries, error messages, device
|
|
11
|
+
names, key ids or IP addresses. Unknown kinds fall back to a generic phrase.
|
|
12
|
+
|
|
13
|
+
Kept in memory only (the last MAX_EVENTS); it starts empty when the server restarts.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import threading
|
|
19
|
+
import time
|
|
20
|
+
from collections import deque
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
MAX_EVENTS = 300
|
|
24
|
+
REPEAT_WINDOW_S = 30.0
|
|
25
|
+
|
|
26
|
+
PHONE_COMMANDS = {
|
|
27
|
+
"/device/info": "read the device info",
|
|
28
|
+
"/device/lock_state": "check whether it is locked",
|
|
29
|
+
"/device/unlock": "unlock",
|
|
30
|
+
"/device/lock": "lock",
|
|
31
|
+
"/screen/capture": "take a screenshot",
|
|
32
|
+
"/ui/tree": "read the screen",
|
|
33
|
+
"/input/tap": "tap",
|
|
34
|
+
"/input/swipe": "swipe",
|
|
35
|
+
"/input/double_tap": "double-tap",
|
|
36
|
+
"/input/back": "go back",
|
|
37
|
+
"/input/home": "go home",
|
|
38
|
+
"/input/text": "type text",
|
|
39
|
+
"/app/list": "list its apps",
|
|
40
|
+
"/app/launch": "open an app",
|
|
41
|
+
"/memory/state": "check its copy of the memory",
|
|
42
|
+
"/memory/bundle": "send its memory history",
|
|
43
|
+
"/memory/apply": "update its copy of the memory",
|
|
44
|
+
"/memory/read": "read the memory",
|
|
45
|
+
"/clipboard/set": "update its clipboard",
|
|
46
|
+
"/clipboard/outbox": "send its clipboard",
|
|
47
|
+
"/clipboard/sent": "say where its clipboard went",
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
ACTIONS = {
|
|
51
|
+
"tap": "tap", "long_press": "long-press", "tap_element": "tap", "double_tap": "double-tap",
|
|
52
|
+
"lock_phone": "lock the phone", "swipe": "swipe", "scroll": "scroll", "type_text": "type text",
|
|
53
|
+
"back": "go back", "home": "go home", "launch_app": "open an app", "find_app": "find an app",
|
|
54
|
+
"wait": "wait", "ask_user": "ask the user", "wait_for_user": "wait for the user", "remember": "save a note",
|
|
55
|
+
"slack_lookup": "look something up in Slack", "slack_send": "send a Slack message",
|
|
56
|
+
"github_repos": "check GitHub", "github_workflows": "check GitHub", "github_runs": "check GitHub",
|
|
57
|
+
"github_run_workflow": "start a GitHub workflow",
|
|
58
|
+
"atlas_stats": "ask Atlas", "atlas_area": "ask Atlas", "atlas_roads_near": "ask Atlas",
|
|
59
|
+
"atlas_routes": "ask Atlas", "atlas_plan": "plan a route with Atlas", "atlas_navigate": "start navigation",
|
|
60
|
+
"atlas_navigation_stop": "stop navigation",
|
|
61
|
+
"done": "finish", "fail": "give up",
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
LAPTOP_REQUESTS = {
|
|
65
|
+
"run.start": "started a run",
|
|
66
|
+
"run.cancel": "stopped the run",
|
|
67
|
+
"runs.list": "looked at the run history",
|
|
68
|
+
"runs.get": "looked at a past run",
|
|
69
|
+
"runs.screenshot": "looked at a past run",
|
|
70
|
+
}
|
|
71
|
+
# Frequent polling, not worth a line: status, run.status. phone.call is logged by the phone command.
|
|
72
|
+
|
|
73
|
+
RUN_SOURCES = {"cli": "from the terminal", "voice": "by voice", "portal": "from the portal", "trigger": "from a trigger",
|
|
74
|
+
"room_request": "for someone's request in a room"}
|
|
75
|
+
|
|
76
|
+
RUN_ENDINGS = {
|
|
77
|
+
"completed": "finished",
|
|
78
|
+
"failed": "failed",
|
|
79
|
+
"cancelled": "was stopped",
|
|
80
|
+
"step_limit_reached": "hit its step limit",
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Activity:
|
|
85
|
+
def __init__(self, max_events: int = MAX_EVENTS) -> None:
|
|
86
|
+
self._lock = threading.Lock()
|
|
87
|
+
self._events: deque[dict[str, Any]] = deque(maxlen=max_events)
|
|
88
|
+
self._seq = 0
|
|
89
|
+
self.boot = int(time.time() * 1000) # changes on restart, so pages know the counter started over
|
|
90
|
+
|
|
91
|
+
def add(self, actor: str, text: str) -> None:
|
|
92
|
+
now = round(time.time(), 1)
|
|
93
|
+
with self._lock:
|
|
94
|
+
self._seq += 1
|
|
95
|
+
last = self._events[-1] if self._events else None
|
|
96
|
+
if last is not None and last["actor"] == actor and last["text"] == text and now - last["t"] < REPEAT_WINDOW_S:
|
|
97
|
+
# The same thing again right away (e.g. reading the screen twice): one line with a count.
|
|
98
|
+
# It is re-sent with a new seq, so pages polling with ?after= see the update.
|
|
99
|
+
self._events.pop()
|
|
100
|
+
last = {**last, "seq": self._seq, "t": now, "count": last.get("count", 1) + 1}
|
|
101
|
+
self._events.append(last)
|
|
102
|
+
return
|
|
103
|
+
self._events.append({"seq": self._seq, "t": now, "actor": actor, "text": text})
|
|
104
|
+
|
|
105
|
+
def since(self, after: int = 0) -> list[dict[str, Any]]:
|
|
106
|
+
with self._lock:
|
|
107
|
+
return [e for e in self._events if e["seq"] > after]
|
|
108
|
+
|
|
109
|
+
# --- typed helpers: the only way callers describe events ------------------------------------
|
|
110
|
+
|
|
111
|
+
def connected(self, role: str) -> None:
|
|
112
|
+
self.add(_role(role), "connected")
|
|
113
|
+
|
|
114
|
+
def disconnected(self, role: str) -> None:
|
|
115
|
+
self.add(_role(role), "disconnected")
|
|
116
|
+
|
|
117
|
+
def refused(self, role: str) -> None:
|
|
118
|
+
self.add("Server", f"refused a {_role(role).lower()} connection (failed authentication)")
|
|
119
|
+
|
|
120
|
+
def signed_in(self, role: str) -> None:
|
|
121
|
+
self.add(_role(role), "signed in with an emailed code")
|
|
122
|
+
|
|
123
|
+
def sign_in_refused(self, role: str) -> None:
|
|
124
|
+
self.add("Server", f"refused a {_role(role).lower()} sign-in (wrong code)")
|
|
125
|
+
|
|
126
|
+
def memory_synced(self, how: str) -> None:
|
|
127
|
+
self.add("Server", "synced the memory between devices" + (" (merged)" if how == "merged" else ""))
|
|
128
|
+
|
|
129
|
+
def room_synced(self) -> None:
|
|
130
|
+
self.add("Server", "synced a room's shared notes between its members")
|
|
131
|
+
|
|
132
|
+
def clipboard_shared(self, actor: str) -> None:
|
|
133
|
+
self.add(actor, "shared its clipboard with the other devices")
|
|
134
|
+
|
|
135
|
+
def job_handed(self, actor: str) -> None:
|
|
136
|
+
self.add(actor, "handed a Claude Code job to a laptop")
|
|
137
|
+
|
|
138
|
+
def job_finished(self, status: str) -> None:
|
|
139
|
+
self.add("Laptop", f"finished a Claude Code job ({status})")
|
|
140
|
+
|
|
141
|
+
def memory_conflict(self) -> None:
|
|
142
|
+
self.add("Server", "found a memory conflict for the user to resolve")
|
|
143
|
+
|
|
144
|
+
def laptop_request(self, method: str, params: dict[str, Any] | None = None) -> None:
|
|
145
|
+
text = LAPTOP_REQUESTS.get(method)
|
|
146
|
+
if text is None:
|
|
147
|
+
return
|
|
148
|
+
if method == "run.start":
|
|
149
|
+
source = RUN_SOURCES.get(str((params or {}).get("source") or ""))
|
|
150
|
+
text = f"{text} {source}" if source else text
|
|
151
|
+
self.add("Laptop", text)
|
|
152
|
+
|
|
153
|
+
def phone_command(self, actor: str, path: str, ok: bool) -> None:
|
|
154
|
+
verb = PHONE_COMMANDS.get(path, "run a command")
|
|
155
|
+
self.add(actor, f"asked the phone to {verb}" + ("" if ok else " (it failed)"))
|
|
156
|
+
|
|
157
|
+
def decision(self, action_type: str) -> None:
|
|
158
|
+
self.add("Claude", f"chose the next step: {ACTIONS.get(action_type, 'act')}")
|
|
159
|
+
|
|
160
|
+
def approval_asked(self, device: str = "laptop") -> None:
|
|
161
|
+
self.add("Rigsby", f"asked the {device} for approval")
|
|
162
|
+
|
|
163
|
+
def approval_answered(self, approved: bool, device: str = "laptop") -> None:
|
|
164
|
+
self.add(device.capitalize(), "approved" if approved else "declined, or did not answer")
|
|
165
|
+
|
|
166
|
+
def question_asked(self, device: str = "laptop") -> None:
|
|
167
|
+
self.add("Rigsby", f"asked the {device} a question")
|
|
168
|
+
|
|
169
|
+
def question_answered(self, answered: bool, device: str = "laptop") -> None:
|
|
170
|
+
self.add(device.capitalize(), "answered" if answered else "did not answer")
|
|
171
|
+
|
|
172
|
+
def run_started(self) -> None:
|
|
173
|
+
self.add("Rigsby", "started working on a request, using Claude")
|
|
174
|
+
|
|
175
|
+
def run_finished(self, status: str, steps: int, seconds: float) -> None:
|
|
176
|
+
ending = RUN_ENDINGS.get(status, "ended")
|
|
177
|
+
self.add("Rigsby", f"run {ending} after {steps} step{'s' if steps != 1 else ''} ({_duration(seconds)})")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _role(role: str) -> str:
|
|
181
|
+
return {"phone": "Phone", "laptop": "Laptop"}.get(role, "Device")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _duration(seconds: float) -> str:
|
|
185
|
+
seconds = max(0, int(round(seconds)))
|
|
186
|
+
return f"{seconds} s" if seconds < 90 else f"{round(seconds / 60)} min"
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class LoggedPhone:
|
|
190
|
+
"""A Connection to the phone that records each command (kind only) under `actor`."""
|
|
191
|
+
|
|
192
|
+
def __init__(self, link, activity: Activity, actor: str):
|
|
193
|
+
self.link = link
|
|
194
|
+
self.activity = activity
|
|
195
|
+
self.actor = actor
|
|
196
|
+
|
|
197
|
+
def call(self, path: str, payload: dict[str, Any] | None = None, **kwargs) -> Any:
|
|
198
|
+
try:
|
|
199
|
+
result = self.link.call(path, payload, **kwargs)
|
|
200
|
+
except Exception:
|
|
201
|
+
self.activity.phone_command(self.actor, path, ok=False)
|
|
202
|
+
raise
|
|
203
|
+
self.activity.phone_command(self.actor, path, ok=True)
|
|
204
|
+
return result
|
|
205
|
+
|
|
206
|
+
def health(self) -> dict[str, Any]:
|
|
207
|
+
return self.link.health()
|
|
208
|
+
|
|
209
|
+
def close(self) -> None:
|
|
210
|
+
pass
|
|
File without changes
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""Claude Code CLI as the reasoning engine.
|
|
2
|
+
|
|
3
|
+
Each decision is one stateless `claude -p` call with ALL tools disabled (`--tools ""`),
|
|
4
|
+
no MCP servers and no session persistence, so the model can only look and answer; it can
|
|
5
|
+
never run commands on the laptop. The screenshot is passed inline via stream-json input.
|
|
6
|
+
|
|
7
|
+
Starting `claude` takes over a second, so after each decision the next process is started
|
|
8
|
+
right away ("prewarmed") and waits for its input while the phone carries out the action.
|
|
9
|
+
|
|
10
|
+
With `mcp=True` and an explicit list of allowed connector tools, the class can also use claude.ai
|
|
11
|
+
connectors: built-in tools stay disabled and anything not listed is denied. (Rigsby's own Slack, GitHub
|
|
12
|
+
and Atlas actions don't: they call those services directly with the profile's keys.)
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import atexit
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
import shutil
|
|
22
|
+
import subprocess
|
|
23
|
+
import time
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# Sonnet: ~0.5s faster per step than the CLI's default model (measured on a typical step).
|
|
30
|
+
# Override with --model (e.g. opus) or RIGSBY_MODEL.
|
|
31
|
+
DEFAULT_MODEL = "sonnet"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ReasoningError(Exception):
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class CLIResult:
|
|
40
|
+
output: dict[str, Any]
|
|
41
|
+
events: list[dict[str, Any]] = field(default_factory=list)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ClaudeCLI:
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
model: str | None = None,
|
|
48
|
+
binary: str | None = None,
|
|
49
|
+
timeout: float = 180.0,
|
|
50
|
+
workdir: Path | None = None,
|
|
51
|
+
prewarm: bool = True,
|
|
52
|
+
*,
|
|
53
|
+
mcp: bool = False,
|
|
54
|
+
allowed_tools: list[str] | tuple[str, ...] = (),
|
|
55
|
+
ready_delay: float = 0.0,
|
|
56
|
+
):
|
|
57
|
+
self.model = model or os.environ.get("RIGSBY_MODEL") or DEFAULT_MODEL
|
|
58
|
+
self.binary = binary or os.environ.get("RIGSBY_CLAUDE_BIN") or shutil.which("claude") or "claude"
|
|
59
|
+
self.timeout = timeout
|
|
60
|
+
self.workdir = workdir
|
|
61
|
+
self.prewarm = prewarm
|
|
62
|
+
# mcp=False: no MCP servers at all. mcp=True: the user's claude.ai connectors load, but only
|
|
63
|
+
# `allowed_tools` may be called (dontAsk denies everything else).
|
|
64
|
+
self.mcp = mcp
|
|
65
|
+
self.allowed_tools = tuple(allowed_tools)
|
|
66
|
+
# Connectors connect in the background after `claude` starts; give them this long
|
|
67
|
+
# (counted from the spawn, so a prewarmed process is usually ready at once).
|
|
68
|
+
self.ready_delay = ready_delay
|
|
69
|
+
self._warm: tuple[tuple, subprocess.Popen] | None = None
|
|
70
|
+
|
|
71
|
+
def command(self, system_prompt: str, schema: dict[str, Any] | None) -> list[str]:
|
|
72
|
+
cmd = [
|
|
73
|
+
self.binary,
|
|
74
|
+
"-p",
|
|
75
|
+
"--input-format", "stream-json",
|
|
76
|
+
"--output-format", "stream-json",
|
|
77
|
+
"--verbose",
|
|
78
|
+
"--tools", "",
|
|
79
|
+
"--no-session-persistence",
|
|
80
|
+
"--system-prompt", system_prompt,
|
|
81
|
+
]
|
|
82
|
+
if schema is not None:
|
|
83
|
+
cmd += ["--json-schema", json.dumps(schema)]
|
|
84
|
+
if self.mcp:
|
|
85
|
+
cmd += ["--permission-mode", "dontAsk"]
|
|
86
|
+
if self.allowed_tools:
|
|
87
|
+
cmd += ["--allowedTools", ",".join(self.allowed_tools)]
|
|
88
|
+
else:
|
|
89
|
+
cmd.append("--strict-mcp-config")
|
|
90
|
+
if self.model:
|
|
91
|
+
cmd += ["--model", self.model]
|
|
92
|
+
return cmd
|
|
93
|
+
|
|
94
|
+
def decide(self, system_prompt: str, content: list[dict[str, Any]], schema: dict[str, Any]) -> dict[str, Any]:
|
|
95
|
+
return self.run(system_prompt, content, schema).output
|
|
96
|
+
|
|
97
|
+
def run(self, system_prompt: str, content: list[dict[str, Any]],
|
|
98
|
+
schema: dict[str, Any] | None) -> CLIResult:
|
|
99
|
+
"""One call; returns the structured answer plus every stream-json event (tool calls etc.)."""
|
|
100
|
+
message = {"type": "user", "message": {"role": "user", "content": content}}
|
|
101
|
+
cmd = self.command(system_prompt, schema)
|
|
102
|
+
key = (tuple(cmd), str(self.workdir))
|
|
103
|
+
proc = self._take_warm(key) or self._spawn(cmd)
|
|
104
|
+
if self.ready_delay > 0:
|
|
105
|
+
remaining = self.ready_delay - (time.monotonic() - _started.get(proc.pid, 0.0))
|
|
106
|
+
if remaining > 0:
|
|
107
|
+
time.sleep(remaining)
|
|
108
|
+
try:
|
|
109
|
+
stdout, stderr = proc.communicate(json.dumps(message) + "\n", timeout=self.timeout)
|
|
110
|
+
except subprocess.TimeoutExpired as e:
|
|
111
|
+
proc.kill()
|
|
112
|
+
proc.communicate()
|
|
113
|
+
raise ReasoningError(f"Claude did not answer within {self.timeout:.0f}s") from e
|
|
114
|
+
finally:
|
|
115
|
+
_live.discard(proc)
|
|
116
|
+
_started.pop(proc.pid, None)
|
|
117
|
+
if self.prewarm:
|
|
118
|
+
# Ready for the next decision, which usually has the same system prompt.
|
|
119
|
+
try:
|
|
120
|
+
self._warm = (key, self._spawn(cmd))
|
|
121
|
+
except ReasoningError:
|
|
122
|
+
self._warm = None
|
|
123
|
+
return CLIResult(parse_cli_output(stdout, stderr, proc.returncode), parse_events(stdout))
|
|
124
|
+
|
|
125
|
+
def warm_up(self, system_prompt: str, schema: dict[str, Any] | None) -> None:
|
|
126
|
+
"""Start the process for a call that is likely to come soon, so it is ready by then."""
|
|
127
|
+
cmd = self.command(system_prompt, schema)
|
|
128
|
+
key = (tuple(cmd), str(self.workdir))
|
|
129
|
+
if self._warm is not None and self._warm[0] == key and self._warm[1].poll() is None:
|
|
130
|
+
return
|
|
131
|
+
self.close()
|
|
132
|
+
try:
|
|
133
|
+
self._warm = (key, self._spawn(cmd))
|
|
134
|
+
except ReasoningError:
|
|
135
|
+
self._warm = None
|
|
136
|
+
|
|
137
|
+
def close(self) -> None:
|
|
138
|
+
"""Stop the prewarmed process, if any (call when a run ends)."""
|
|
139
|
+
if self._warm is not None:
|
|
140
|
+
_, proc = self._warm
|
|
141
|
+
self._warm = None
|
|
142
|
+
_kill(proc)
|
|
143
|
+
|
|
144
|
+
def _take_warm(self, key: tuple) -> subprocess.Popen | None:
|
|
145
|
+
if self._warm is None:
|
|
146
|
+
return None
|
|
147
|
+
warm_key, proc = self._warm
|
|
148
|
+
self._warm = None
|
|
149
|
+
if warm_key == key and proc.poll() is None:
|
|
150
|
+
return proc
|
|
151
|
+
_kill(proc) # the prompt changed (e.g. memory was edited) or it exited
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
def _spawn(self, cmd: list[str]) -> subprocess.Popen:
|
|
155
|
+
try:
|
|
156
|
+
proc = subprocess.Popen(
|
|
157
|
+
cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
158
|
+
text=True, cwd=self.workdir,
|
|
159
|
+
)
|
|
160
|
+
except FileNotFoundError as e:
|
|
161
|
+
raise ReasoningError(f"Claude Code CLI not found ({self.binary}). Install it or set RIGSBY_CLAUDE_BIN.") from e
|
|
162
|
+
_live.add(proc)
|
|
163
|
+
_started[proc.pid] = time.monotonic()
|
|
164
|
+
return proc
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
_live: set[subprocess.Popen] = set()
|
|
168
|
+
_started: dict[int, float] = {}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _kill(proc: subprocess.Popen) -> None:
|
|
172
|
+
_live.discard(proc)
|
|
173
|
+
_started.pop(proc.pid, None)
|
|
174
|
+
if proc.poll() is None:
|
|
175
|
+
proc.kill()
|
|
176
|
+
try:
|
|
177
|
+
proc.communicate(timeout=2)
|
|
178
|
+
except (subprocess.TimeoutExpired, ValueError, OSError):
|
|
179
|
+
pass
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@atexit.register
|
|
183
|
+
def _kill_all() -> None:
|
|
184
|
+
for proc in list(_live):
|
|
185
|
+
_kill(proc)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def parse_events(stdout: str) -> list[dict[str, Any]]:
|
|
189
|
+
events = []
|
|
190
|
+
for line in stdout.splitlines():
|
|
191
|
+
line = line.strip()
|
|
192
|
+
if line.startswith("{"):
|
|
193
|
+
try:
|
|
194
|
+
events.append(json.loads(line))
|
|
195
|
+
except ValueError:
|
|
196
|
+
continue
|
|
197
|
+
return events
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def parse_cli_output(stdout: str, stderr: str, returncode: int) -> dict[str, Any]:
|
|
201
|
+
result = None
|
|
202
|
+
for line in stdout.splitlines():
|
|
203
|
+
line = line.strip()
|
|
204
|
+
if not line.startswith("{"):
|
|
205
|
+
continue
|
|
206
|
+
try:
|
|
207
|
+
event = json.loads(line)
|
|
208
|
+
except ValueError:
|
|
209
|
+
continue
|
|
210
|
+
if event.get("type") == "result":
|
|
211
|
+
result = event
|
|
212
|
+
if result is None:
|
|
213
|
+
raise ReasoningError(f"Claude CLI produced no result (exit {returncode}): {stderr.strip()[-500:]}")
|
|
214
|
+
if result.get("is_error") or result.get("subtype") not in (None, "success"):
|
|
215
|
+
raise ReasoningError(f"Claude CLI error ({result.get('subtype')}): {str(result.get('result'))[:500]}")
|
|
216
|
+
|
|
217
|
+
structured = result.get("structured_output")
|
|
218
|
+
if isinstance(structured, dict):
|
|
219
|
+
return structured
|
|
220
|
+
return extract_json(str(result.get("result", "")))
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def extract_json(text: str) -> dict[str, Any]:
|
|
224
|
+
"""Fallback when structured output is absent: take the first JSON object in the text."""
|
|
225
|
+
fenced = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
|
|
226
|
+
candidates = [fenced.group(1)] if fenced else []
|
|
227
|
+
start = text.find("{")
|
|
228
|
+
if start != -1:
|
|
229
|
+
candidates.append(text[start : text.rfind("}") + 1])
|
|
230
|
+
for candidate in candidates:
|
|
231
|
+
try:
|
|
232
|
+
value = json.loads(candidate)
|
|
233
|
+
except ValueError:
|
|
234
|
+
continue
|
|
235
|
+
if isinstance(value, dict):
|
|
236
|
+
return value
|
|
237
|
+
raise ReasoningError(f"Could not find a JSON decision in Claude's reply: {text[:300]}")
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Task context: the task record, what the model needs to know about earlier steps,
|
|
2
|
+
and the on-disk run log (screenshots + task.json) for every run."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from rigsby_core.config import runs_dir
|
|
11
|
+
from rigsby_core.models.observation import DeviceInfo
|
|
12
|
+
from rigsby_core.models.task import Step, Task
|
|
13
|
+
|
|
14
|
+
HISTORY_WINDOW = 15
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TaskContext:
|
|
18
|
+
def __init__(self, task: Task, device: DeviceInfo | None, run_root: Path | None = None):
|
|
19
|
+
self.task = task
|
|
20
|
+
self.device = device
|
|
21
|
+
self.run_dir = (run_root or runs_dir()) / time.strftime("%Y%m%d-%H%M%S")
|
|
22
|
+
self.run_dir.mkdir(parents=True, exist_ok=True)
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def device_line(self) -> str:
|
|
26
|
+
d = self.device
|
|
27
|
+
if d is None:
|
|
28
|
+
return "(not connected yet)"
|
|
29
|
+
return f"{d.manufacturer} {d.model}, Android {d.android_version}, {d.width}x{d.height}px"
|
|
30
|
+
|
|
31
|
+
def add_step(self, step: Step) -> None:
|
|
32
|
+
self.task.steps.append(step)
|
|
33
|
+
self.save()
|
|
34
|
+
|
|
35
|
+
def note(self, text: str) -> None:
|
|
36
|
+
self.task.notes.append(f"(before step {len(self.task.steps) + 1}) {text}")
|
|
37
|
+
self.save()
|
|
38
|
+
|
|
39
|
+
def render_history(self) -> str:
|
|
40
|
+
steps = self.task.steps
|
|
41
|
+
if not steps and not self.task.notes:
|
|
42
|
+
return "(nothing yet: this is the first step)"
|
|
43
|
+
lines = []
|
|
44
|
+
hidden = max(0, len(steps) - HISTORY_WINDOW)
|
|
45
|
+
if hidden:
|
|
46
|
+
lines.append(f"({hidden} earlier steps omitted)")
|
|
47
|
+
for step in steps[hidden:]:
|
|
48
|
+
outcome = "pending" if step.result is None else ("OK" if step.result.ok else "FAILED")
|
|
49
|
+
detail = f" - {step.result.message}" if step.result and step.result.message else ""
|
|
50
|
+
lines.append(f"{step.index}. {step.action.describe()} -> {outcome}{detail}")
|
|
51
|
+
if step.progress:
|
|
52
|
+
lines.append(f" intent: {step.progress}")
|
|
53
|
+
if self.task.notes:
|
|
54
|
+
lines.append("")
|
|
55
|
+
lines.append("NOTES:")
|
|
56
|
+
lines.extend(f"- {n}" for n in self.task.notes[-10:])
|
|
57
|
+
return "\n".join(lines)
|
|
58
|
+
|
|
59
|
+
def save_screenshot(self, step_index: int, png: bytes) -> Path:
|
|
60
|
+
path = self.run_dir / f"step_{step_index:02d}.png"
|
|
61
|
+
path.write_bytes(png)
|
|
62
|
+
return path
|
|
63
|
+
|
|
64
|
+
def save(self) -> None:
|
|
65
|
+
(self.run_dir / "task.json").write_text(json.dumps(self.task.to_json(), indent=2))
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Translates validated actions into phone operations. Coordinates come in image space
|
|
2
|
+
and leave in device pixels."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from rigsby_core.connection import CommandError
|
|
9
|
+
from rigsby_core.phone import Phone
|
|
10
|
+
from rigsby_core.models.action import Action
|
|
11
|
+
from rigsby_core.models.observation import Observation
|
|
12
|
+
from rigsby_core.apps import AppCatalog # noqa: F401 (re-exported)
|
|
13
|
+
from rigsby_core.models.task import StepResult
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Executor:
|
|
17
|
+
def __init__(self, phone: Phone, apps: AppCatalog | None = None):
|
|
18
|
+
self.phone = phone
|
|
19
|
+
self.apps = apps or AppCatalog(phone)
|
|
20
|
+
|
|
21
|
+
def execute(self, action: Action, obs: Observation) -> StepResult:
|
|
22
|
+
try:
|
|
23
|
+
return self._execute(action, obs)
|
|
24
|
+
except CommandError as e:
|
|
25
|
+
if e.code == "not_found":
|
|
26
|
+
return StepResult(False, f"the Rigsby app on the phone is out of date and cannot do {action.type}; "
|
|
27
|
+
"tell the user to install the latest Rigsby app on the phone. Do not imitate "
|
|
28
|
+
"it with other actions.")
|
|
29
|
+
return StepResult(False, f"phone reported {e.code}: {e.message}")
|
|
30
|
+
|
|
31
|
+
def _execute(self, action: Action, obs: Observation) -> StepResult:
|
|
32
|
+
t = action.type
|
|
33
|
+
if t in ("tap", "long_press"):
|
|
34
|
+
x, y = obs.to_device(action["x"], action["y"])
|
|
35
|
+
self.phone.tap(x, y, duration_ms=700 if t == "long_press" else None)
|
|
36
|
+
return StepResult(True, "")
|
|
37
|
+
if t == "tap_element":
|
|
38
|
+
element = obs.tree.get(action["element"]) if obs.tree else None
|
|
39
|
+
if element is None:
|
|
40
|
+
return StepResult(False, f"element [{action['element']}] is not on the current screen")
|
|
41
|
+
self.phone.tap(*element.center)
|
|
42
|
+
return StepResult(True, f"tapped '{element.label[:60]}'" if element.label else "")
|
|
43
|
+
if t == "double_tap":
|
|
44
|
+
if "element" in action.params:
|
|
45
|
+
element = obs.tree.get(action["element"]) if obs.tree else None
|
|
46
|
+
if element is None:
|
|
47
|
+
return StepResult(False, f"element [{action['element']}] is not on the current screen")
|
|
48
|
+
self.phone.double_tap(*element.center)
|
|
49
|
+
return StepResult(True, f"double-tapped '{element.label[:60]}'" if element.label else "")
|
|
50
|
+
self.phone.double_tap(*obs.to_device(action["x"], action["y"]))
|
|
51
|
+
return StepResult(True, "")
|
|
52
|
+
if t == "lock_phone":
|
|
53
|
+
self.phone.lock()
|
|
54
|
+
return StepResult(True, "the phone is locked")
|
|
55
|
+
if t == "swipe":
|
|
56
|
+
x1, y1 = obs.to_device(action["x"], action["y"])
|
|
57
|
+
x2, y2 = obs.to_device(action["x2"], action["y2"])
|
|
58
|
+
self.phone.swipe(x1, y1, x2, y2, action.get("duration_ms", 400))
|
|
59
|
+
return StepResult(True, "")
|
|
60
|
+
if t == "scroll":
|
|
61
|
+
return self._scroll(action, obs)
|
|
62
|
+
if t == "type_text":
|
|
63
|
+
self.phone.type_text(action["text"], submit=action.get("submit", False))
|
|
64
|
+
return StepResult(True, "")
|
|
65
|
+
if t == "back":
|
|
66
|
+
self.phone.back()
|
|
67
|
+
return StepResult(True, "")
|
|
68
|
+
if t == "home":
|
|
69
|
+
self.phone.home()
|
|
70
|
+
return StepResult(True, "")
|
|
71
|
+
if t == "launch_app":
|
|
72
|
+
package, message = self.apps.resolve(action["app"])
|
|
73
|
+
if package is None:
|
|
74
|
+
return StepResult(False, message)
|
|
75
|
+
self.phone.launch_app(package)
|
|
76
|
+
return StepResult(True, f"launched {message} ({package})")
|
|
77
|
+
if t == "wait":
|
|
78
|
+
time.sleep(action["seconds"])
|
|
79
|
+
return StepResult(True, "")
|
|
80
|
+
return StepResult(False, f"action {t} cannot be executed on the phone")
|
|
81
|
+
|
|
82
|
+
def _scroll(self, action: Action, obs: Observation) -> StepResult:
|
|
83
|
+
if "element" in action.params:
|
|
84
|
+
element = obs.tree.get(action["element"]) if obs.tree else None
|
|
85
|
+
if element is None:
|
|
86
|
+
return StepResult(False, f"element [{action['element']}] is not on the current screen")
|
|
87
|
+
left, top, right, bottom = element.bounds
|
|
88
|
+
else:
|
|
89
|
+
# Middle band of the screen: avoids status bar, nav bar and edge-swipe gestures.
|
|
90
|
+
left, right = int(obs.device_width * 0.1), int(obs.device_width * 0.9)
|
|
91
|
+
top, bottom = int(obs.device_height * 0.2), int(obs.device_height * 0.8)
|
|
92
|
+
cx, cy = (left + right) // 2, (top + bottom) // 2
|
|
93
|
+
dx, dy = int((right - left) * 0.3), int((bottom - top) * 0.3)
|
|
94
|
+
# "down" means reveal content further down, so the finger moves up.
|
|
95
|
+
start, end = {
|
|
96
|
+
"down": ((cx, cy + dy), (cx, cy - dy)),
|
|
97
|
+
"up": ((cx, cy - dy), (cx, cy + dy)),
|
|
98
|
+
"right": ((cx + dx, cy), (cx - dx, cy)),
|
|
99
|
+
"left": ((cx - dx, cy), (cx + dx, cy)),
|
|
100
|
+
}[action["direction"]]
|
|
101
|
+
self.phone.swipe(*start, *end, duration_ms=450)
|
|
102
|
+
return StepResult(True, "")
|