d5i-openpi 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.
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.5
2
+ Name: d5i-openpi
3
+ Version: 0.1.0
4
+ Summary: Desktop control room for the pi coding agent
5
+ Author-email: dsient <dsient@users.noreply.github.com>
6
+ Requires-Python: >=3.14
7
+ Requires-Dist: click>=8.5.1
8
+ Requires-Dist: cryptography>=50.0.2
9
+ Requires-Dist: markdown-it-py>=4.3.0
10
+ Requires-Dist: msgspec>=0.22.0
11
+ Requires-Dist: pyside6>=6.12.0
12
+ Description-Content-Type: text/markdown
13
+
14
+ # openpi
15
+
16
+ A control room for the [pi](https://github.com/earendil-works/pi) coding agent: a desktop app,
17
+ a background web server, and a relay so the same sessions are reachable from a phone.
18
+
19
+ PySide6 + click + msgspec. It drives `pi --mode rpc` child processes and reads pi's own session
20
+ files. No database, no account, no extension sandbox.
21
+
22
+ ## Status
23
+
24
+ M0 (protocol spine), M1 (desktop chat control room), and M2 (web server + relay) are built,
25
+ with desktop client mode, per-device pairing tokens, and relay E2E (TLS + CA pinning) on top:
26
+ session list, live multi-session streaming, markdown transcript, tool cards, model/thinking
27
+ pickers, extension dialogs, context/cost footer, project trust, a browser client, and a
28
+ self-hosted relay. M3 (git, branches, worktrees) is next — see [`docs/plan.md`](docs/plan.md).
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ uv tool install d5i-openpi # from PyPI (the `openpi` name was taken; this is the same app)
34
+ # or from source:
35
+ uv tool install git+https://github.com/D5-Interactive/OpenPi
36
+ ```
37
+
38
+ The installed command is `openpi`; the PyPI distribution is named `d5i-openpi` because `openpi`
39
+ is reserved on PyPI by Physical Intelligence.
40
+
41
+ First run creates `~/.openpi/` (override with `OPENPI_HOME`) for `settings.json`, `pairings.json`,
42
+ the server token, TLS material, and reserved `extensions/`/`skills/` dirs.
43
+
44
+ `openpi setup` checks pi and installs or updates it (`pi update --self`), so the desktop and
45
+ server always drive a current pi.
46
+
47
+ ## Quickstart (from a checkout)
48
+
49
+ ```bash
50
+ uv sync
51
+ uv run openpi # open the GUI in the current folder
52
+ uv run openpi --project ~/repo # open a specific folder
53
+ uv run openpi --connect http://host:7717 --token … # GUI attached to a server
54
+ uv run openpi --connect https://… --tls-ca server.crt # same, over TLS (pinned cert)
55
+ uv run openpi setup # create ~/.openpi, install/update pi
56
+ uv run openpi doctor # pi binary, version, session dir, models
57
+ uv run openpi sessions # list pi sessions from disk
58
+ uv run pytest # 74 tests, headless
59
+ uv run pytest -m live # plus 3 live pi/network contract tests
60
+ ```
61
+
62
+ ## Remote access
63
+
64
+ ```bash
65
+ # on the machine with the repos
66
+ uv run openpi serve # http://127.0.0.1:7717/?token=…
67
+ uv run openpi serve --tls # HTTPS (self-signed cert), end-to-end through the relay
68
+ uv run openpi serve --host 0.0.0.0 # LAN
69
+ uv run openpi serve --relay relay.example.com:7719 --relay-token … # behind NAT
70
+
71
+ # on a small public host
72
+ uv run openpi relay --token … --public-port 7718 --instance-port 7719
73
+ ```
74
+
75
+ The server prints the URL with its token (stored in `~/.openpi/server-token`).
76
+ Issue per-device tokens with `openpi token new`; they're revocable and reloaded live. The relay
77
+ is a byte pipe, so `--tls` gives end-to-end encryption: the desktop pins the cert with
78
+ `--tls-ca`, the browser accepts it once.
79
+
80
+ Requires `pi` on `PATH` (tested against 1.5.2). Override with `OPENPI_PI_BINARY=/path/to/pi`.
81
+
82
+ ## What it does
83
+
84
+ - Keep every opened session streaming in the background; switching costs nothing.
85
+ - Render text, thinking, tool calls, bash output, compaction, and retries as they happen.
86
+ - Attach images to a prompt (desktop and browser).
87
+ - Answer extension dialogs (`ctx.ui.select/confirm/input/editor`) with real Qt dialogs.
88
+ - Show context, token, and cost usage from pi's own numbers.
89
+ - `/` autocomplete for skills, templates, and commands; tray notification when work settles.
90
+ - Reach the same sessions from a browser or another desktop (`--connect`), including through a
91
+ relay with end-to-end TLS.
92
+
93
+ Planned next (M3 git, M4 orchestration): a working-tree diff pane with agent-written commit
94
+ messages, branch (`fork`/`clone`) and worktree sessions, multi-model runs, scheduled tasks, and
95
+ a diff walkthrough.
96
+
97
+ It deliberately does **not** reimplement permissions, provider config, MCP, skills, notes, or a
98
+ plugin sandbox: pi already has those.
99
+
100
+ Not there yet: git/diff pane, branch tree, worktrees, multi-run, scheduled tasks.
101
+
102
+ ## Releasing
103
+
104
+ Tag a version that matches `pyproject.toml` and push it; `.github/workflows/release.yml` runs
105
+ the tests, builds, publishes to PyPI under the D5-Interactive org (`secrets.PYPI_TOKEN`), and
106
+ creates the GitHub release:
107
+
108
+ ```bash
109
+ uv run pytest # sanity first
110
+ # bump version in pyproject.toml, then:
111
+ git tag v0.1.0 && git push --tags
112
+ ```
113
+
114
+ ## Docs
115
+
116
+ - [`docs/plan.md`](docs/plan.md) — milestones, risks, open decisions
117
+ - [`docs/research/openchamber.md`](docs/research/openchamber.md) — what OpenChamber does and
118
+ what transfers
119
+ - [`.agents/pi-protocol.md`](.agents/pi-protocol.md) — pi RPC/JSONL/session-file reference used
120
+ by the client
121
+ - [`.agents/architecture.md`](.agents/architecture.md) — module map and invariants
@@ -0,0 +1,35 @@
1
+ openpi/__init__.py,sha256=tiHCL2QqT54cKRTXs97edDrSovHTSVBF4dRfDraXd8I,112
2
+ openpi/cli.py,sha256=XPBhhScxdgHyZ_ZD6sJ2l3jF4x8A88rl0ftzRFyWzCQ,7561
3
+ openpi/config.py,sha256=F3-_ihoCjHJpp6BlC6Vn0o4VYwxdByCzn8hmLgeMmJU,4868
4
+ openpi/relay.py,sha256=jKI07LVT_mutduBiRzJxSBeQzmsD9oUmWMlZtHYMomg,9144
5
+ openpi/pi/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ openpi/pi/doctor.py,sha256=ZjjViS6H2PHSym4jOX2fmBGxEHQl7fEz7pD1Zi5O7bw,2803
7
+ openpi/pi/index.py,sha256=dM9OwUbd3Mj5buJAXM_Gav26gJVxt_dgpBc2e0RG16s,3470
8
+ openpi/pi/install.py,sha256=Phs_hnNwsuEAT-fg_k7_jhacpPpleOtY6WK6DvB28KA,2726
9
+ openpi/pi/process.py,sha256=-0yMgyFUzM2NIepPUzyg5cQIVdoHvjPKiLONbd91oxw,3566
10
+ openpi/pi/session.py,sha256=GUDDGqlvR4t6CWp4rpnDnrYCPGONBMVkpb57PTVHPis,7237
11
+ openpi/pi/transcript.py,sha256=N3R3EMkM0dsj3AhK6tFVkWGix7QuMxkrCGeVliEP3Jg,11312
12
+ openpi/protocol/__init__.py,sha256=328HOy7FtB2RwlBKRv9JNocl5VtZRa0nc0smxtcOtc8,107
13
+ openpi/protocol/codec.py,sha256=9mK1m9SgfvmhB7VGEpMbZlUsXK79p774LPRmJGvXnS4,722
14
+ openpi/protocol/records.py,sha256=oMCjPD60hUjWSPzhsh7k9A1PqXqS6oI_Y323O8pupic,3790
15
+ openpi/server/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ openpi/server/client.py,sha256=149LBdRPwBNKyZp12hjv0LY8Db4ntWsA4i-FizwAJBI,11707
17
+ openpi/server/http.py,sha256=pjTB1JbO0KrZgVYa4RCQhahqY7Gl9DQ5z-zZMh7JikI,8538
18
+ openpi/server/hub.py,sha256=Y2BrSJf_SKpyi-ulT1HF4X6qz9FCaufZ0KnKGHqzwTY,10620
19
+ openpi/server/serve.py,sha256=YAdSj0tZqyHhqAhUVdUG-uqWzDGVAkUtxHXWzle09M0,3794
20
+ openpi/server/tls.py,sha256=26mCd0umbGoMOvGpa1uH4uVdjvuWS6dQ0388m-Rm7ms,3266
21
+ openpi/server/web/index.html,sha256=LOFZRJt4mBBjbac5Pv7BtUvDpi4nW7G_4J2_iaw5uUs,18457
22
+ openpi/ui/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
+ openpi/ui/app.py,sha256=xz51JLfnxqVLqtaD4_bcHgX8dZYlktNMhjEPNsA65kA,1192
24
+ openpi/ui/composer.py,sha256=fYVnM_dEWZ4AGsKvB-nHnmsuirwcUMPEKqT-ytK0gEE,7159
25
+ openpi/ui/dialogs.py,sha256=Lviy6c9ZYV3_0Pby-onAcCjpdJZ8lNKiW14GVgiwht0,2931
26
+ openpi/ui/markdown.py,sha256=wlMlfgOwzEIh5__8xIA45lvK5t7AU795arM45G0hHF0,872
27
+ openpi/ui/pane.py,sha256=rPK2nrgcTk0aEnERjJomVZpNTOuRArvk0VBrkSj1G7c,7589
28
+ openpi/ui/tasks.py,sha256=6q3NiJkgRelEDysSXEauEB2SKLKOsIFNgCYBvymTm6o,825
29
+ openpi/ui/theme.py,sha256=MOfFihFznqCBDczUbGvbqLPp9OCpPrurHaiBdPkaa-Y,2852
30
+ openpi/ui/transcript.py,sha256=pME_DOvfjkxaOJ5Pbg52PcdvghjT6sjL5RbyaqUMucw,7796
31
+ openpi/ui/window.py,sha256=4NB_9zeD0JZTcsyuJ6UixRu3trdcuRwem-I3liLQNms,14513
32
+ d5i_openpi-0.1.0.dist-info/METADATA,sha256=8HRJXCzS7cjT9HaWv7i8W4dg-DpGUToyU3OkVoO-pE8,5204
33
+ d5i_openpi-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
34
+ d5i_openpi-0.1.0.dist-info/entry_points.txt,sha256=Lo9PEzOMMLMSnMWF6E0N66Aq3c9dwE6BpSPH9G0nj1c,39
35
+ d5i_openpi-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ openpi = openpi:main
openpi/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """openpi — desktop control room for the pi coding agent."""
2
+
3
+ from openpi.cli import main
4
+
5
+ __all__ = ["main"]
openpi/cli.py ADDED
@@ -0,0 +1,186 @@
1
+ """Command line: `openpi` opens the app; the rest are small operators' helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import click
8
+
9
+ from openpi import config
10
+
11
+
12
+ class OpenpiGroup(click.Group):
13
+ """Ensure ~/.openpi exists on every invocation, not just when the GUI opens."""
14
+
15
+ def invoke(self, ctx: click.Context):
16
+ config.ensure_home()
17
+ return super().invoke(ctx)
18
+
19
+
20
+ @click.group(cls=OpenpiGroup, invoke_without_command=True)
21
+ @click.option("--project", type=click.Path(file_okay=False), default=None,
22
+ help="folder to open (default: current folder)")
23
+ @click.option("--session-root", type=click.Path(file_okay=False), envvar="OPENPI_SESSION_ROOT",
24
+ help="pi session directory (default: ~/.pi/agent/sessions)")
25
+ @click.option("--connect", metavar="URL", help="connect to a running `openpi serve` instead of "
26
+ "spawning pi locally (e.g. http://host:7717)")
27
+ @click.option("--token", help="server token for --connect (or put ?token= in the URL)")
28
+ @click.option("--tls-ca", type=click.Path(exists=True, dir_okay=False),
29
+ help="CA/cert file to trust when --connect is https:// (the server's self-signed cert)")
30
+ @click.pass_context
31
+ def main(ctx: click.Context, project: str | None, session_root: str | None,
32
+ connect: str | None, token: str | None, tls_ca: str | None) -> None:
33
+ """Desktop control room for the pi coding agent.
34
+
35
+ `openpi` opens the app in the current folder; `openpi --project PATH` opens PATH.
36
+ """
37
+ if ctx.invoked_subcommand is not None:
38
+ return
39
+ from .ui.app import launch
40
+
41
+ if project and not Path(project).is_dir():
42
+ raise click.BadParameter(f"not a directory: {project}", param_hint="--project")
43
+ ctx.exit(launch(project=project, session_root=session_root, connect=connect, token=token,
44
+ tls_ca=tls_ca))
45
+
46
+
47
+ @main.command()
48
+ @click.option("--session-root", type=click.Path(file_okay=False))
49
+ @click.option("--limit", default=20, show_default=True)
50
+ def sessions(session_root: str | None, limit: int) -> None:
51
+ """List pi sessions on disk."""
52
+ from pathlib import Path
53
+
54
+ from .pi.index import default_session_dir, scan
55
+
56
+ metas = scan(Path(session_root) if session_root else default_session_dir())
57
+ if not metas:
58
+ click.echo("no sessions found")
59
+ return
60
+ for meta in metas[:limit]:
61
+ flag = "*" if meta.name else " "
62
+ click.echo(f"{flag} {meta.id[:8]} {meta.cwd}\n {meta.title[:90]}")
63
+
64
+
65
+ @main.command()
66
+ @click.option("--host", default="127.0.0.1", show_default=True)
67
+ @click.option("--port", default=7717, show_default=True, type=int)
68
+ @click.option("--cwd", type=click.Path(file_okay=False), help="default folder for new sessions")
69
+ @click.option("--token", envvar="OPENPI_SERVER_TOKEN", help="access token (default: generated)")
70
+ @click.option("--trust/--no-trust", default=False,
71
+ help="load project-local pi resources in every project")
72
+ @click.option("--relay", help="relay host:port of its instance listener (e.g. relay.example.com:7719)")
73
+ @click.option("--relay-token", envvar="OPENPI_RELAY_TOKEN", help="token shared with the relay")
74
+ @click.option("--tls/--no-tls", default=False,
75
+ help="serve HTTPS with a self-signed cert (end-to-end encryption through the relay)")
76
+ def serve(host: str, port: int, cwd: str | None, token: str | None, trust: bool,
77
+ relay: str | None, relay_token: str | None, tls: bool) -> None:
78
+ """Run the background web server (browser + relay access)."""
79
+ from .server.serve import run
80
+
81
+ raise SystemExit(run(host=host, port=port, cwd=cwd, token=token, trust=trust,
82
+ relay=relay, relay_token=relay_token, tls=tls))
83
+
84
+
85
+ @main.command()
86
+ @click.option("--public-port", default=7718, show_default=True, type=int,
87
+ help="port browsers connect to")
88
+ @click.option("--instance-port", default=7719, show_default=True, type=int,
89
+ help="port the openpi server dials out to")
90
+ @click.option("--token", envvar="OPENPI_RELAY_TOKEN", required=True,
91
+ help="shared secret; also pass it to `openpi serve --relay-token`")
92
+ @click.option("--host", default="0.0.0.0", show_default=True)
93
+ def relay(public_port: int, instance_port: int, token: str, host: str) -> None:
94
+ """Run a relay so a server behind NAT is reachable without an open port."""
95
+ import time
96
+
97
+ from .relay import start_relay
98
+
99
+ actual_public, actual_instance, _thread, _loop = start_relay(
100
+ token, public_port, instance_port, host)
101
+ click.echo(f"relay public {host}:{actual_public}")
102
+ click.echo(f"relay instance {host}:{actual_instance} (openpi serve --relay host:{actual_instance})")
103
+ click.echo("ctrl-c to stop")
104
+ try:
105
+ while True:
106
+ time.sleep(3600)
107
+ except KeyboardInterrupt:
108
+ pass
109
+
110
+
111
+ @main.group()
112
+ def token() -> None:
113
+ """Manage per-device tokens for a server."""
114
+
115
+
116
+ @token.command("new")
117
+ @click.option("--name", default="", help="label for the device")
118
+ def token_new(name: str) -> None:
119
+ """Issue a token. The server picks it up without a restart."""
120
+ from openpi import config
121
+
122
+ pairing = config.Pairings().add(name)
123
+ click.echo(f"id: {pairing.id}")
124
+ click.echo(f"name: {pairing.name or '(no name)'}")
125
+ click.echo(f"token: {pairing.token}")
126
+
127
+
128
+ @token.command("list")
129
+ def token_list() -> None:
130
+ """List issued device tokens (the tokens themselves are not shown)."""
131
+ from openpi import config
132
+
133
+ for pairing in config.Pairings().list():
134
+ click.echo(f"{pairing.id} {pairing.name or '(no name)'}")
135
+
136
+
137
+ @token.command("revoke")
138
+ @click.argument("pairing_id")
139
+ def token_revoke(pairing_id: str) -> None:
140
+ """Revoke a device token by id."""
141
+ from openpi import config
142
+
143
+ if not config.Pairings().revoke(pairing_id):
144
+ click.echo("no such pairing")
145
+ raise SystemExit(1)
146
+ click.echo("revoked")
147
+
148
+
149
+ @main.command()
150
+ def setup() -> None:
151
+ """Create ~/.openpi and install/update the pi coding agent."""
152
+ from openpi import config
153
+ from openpi.pi.install import ensure_pi, installed_version, latest_version
154
+
155
+ home = config.ensure_home()
156
+ click.echo(f"home: {home}")
157
+ before = installed_version()
158
+ binary = ensure_pi(update=True)
159
+ click.echo(f"pi: {before or 'not installed'} -> {installed_version(binary)}")
160
+ click.echo(f"latest: {latest_version() or 'unknown (no network?)'}")
161
+
162
+
163
+ @main.command()
164
+ def doctor() -> None:
165
+ """Check the pi binary, version, models, and session directory."""
166
+ from .pi.doctor import probe
167
+ from .pi.index import default_session_dir, scan
168
+ from .pi.install import installed_version, latest_version
169
+
170
+ root = default_session_dir()
171
+ report = probe()
172
+ click.echo(f"binary: {report['binary']}")
173
+ click.echo(f"version: {report['version'] or 'unknown'}")
174
+ latest = latest_version()
175
+ click.echo(f"pi latest: {latest or 'unknown'}")
176
+ if latest and installed_version() != latest:
177
+ click.echo(" run `openpi setup` to update pi")
178
+ click.echo(f"session dir: {root} ({len(scan(root))} sessions)")
179
+ if report["ok"]:
180
+ state = report["state"] or {}
181
+ click.echo(f"model: {state.get('model')} (thinking {state.get('thinking')})")
182
+ click.echo(f"models: {report['models']} available")
183
+ click.echo(f"thinking: {', '.join(report['thinking_levels']) or 'none'}")
184
+ else:
185
+ click.echo(f"error: {report['error'] or 'pi did not answer the RPC probe'}")
186
+ raise SystemExit(1)
openpi/config.py ADDED
@@ -0,0 +1,151 @@
1
+ """openpi's own state. Not pi's: settings here never belong to the agent.
2
+
3
+ Home layout (created on first run, `OPENPI_HOME` overrides the default `~/.openpi`):
4
+
5
+ ~/.openpi/
6
+ settings.json Settings struct
7
+ pairings.json per-device tokens
8
+ server-token admin token for `openpi serve`
9
+ server.crt/.key self-signed TLS material
10
+ extensions/ reserved for openpi extensions
11
+ skills/ reserved for openpi skills
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import secrets
18
+ import shutil
19
+ import threading
20
+ from pathlib import Path
21
+
22
+ import msgspec
23
+
24
+ LEGACY_FILES = ("settings.json", "pairings.json", "server-token", "server.crt", "server.key")
25
+ RESERVED_DIRS = ("extensions", "skills")
26
+
27
+
28
+ class Settings(msgspec.Struct):
29
+ projects: list[str] = msgspec.field(default_factory=list)
30
+ last_project: str = ""
31
+ trusted: list[str] = msgspec.field(default_factory=list)
32
+ untrusted: list[str] = msgspec.field(default_factory=list)
33
+ last_model: str = ""
34
+ live_cap: int = 8
35
+
36
+
37
+ class Pairing(msgspec.Struct):
38
+ id: str
39
+ name: str
40
+ token: str
41
+
42
+
43
+ def home_dir() -> Path:
44
+ return Path(os.environ.get("OPENPI_HOME") or Path.home() / ".openpi")
45
+
46
+
47
+ def legacy_dir() -> Path:
48
+ base = os.environ.get("OPENPI_STATE_DIR") or os.environ.get("XDG_STATE_HOME") \
49
+ or str(Path.home() / ".local" / "state")
50
+ return Path(base) / "openpi"
51
+
52
+
53
+ def state_dir() -> Path: # kept as an alias; new code should use home_dir()
54
+ return home_dir()
55
+
56
+
57
+ def ensure_home(directory: Path | None = None) -> Path:
58
+ """Create the home layout and migrate any pre-`~/.openpi` state into it."""
59
+ explicit = directory is not None
60
+ directory = directory or home_dir()
61
+ directory.mkdir(parents=True, exist_ok=True)
62
+ for sub in RESERVED_DIRS:
63
+ (directory / sub).mkdir(exist_ok=True)
64
+ if not explicit and "OPENPI_HOME" not in os.environ:
65
+ legacy = legacy_dir()
66
+ if legacy != directory and legacy.is_dir():
67
+ for name in LEGACY_FILES:
68
+ src, dst = legacy / name, directory / name
69
+ if src.exists() and not dst.exists():
70
+ try:
71
+ shutil.copy2(src, dst)
72
+ except OSError:
73
+ pass
74
+ return directory
75
+
76
+
77
+ def _atomic_write(path: Path, data: bytes) -> None:
78
+ path.parent.mkdir(parents=True, exist_ok=True)
79
+ tmp = path.with_suffix(path.suffix + ".tmp")
80
+ tmp.write_bytes(data)
81
+ os.replace(tmp, path)
82
+
83
+
84
+ def load(directory: Path | None = None) -> Settings:
85
+ directory = directory or home_dir()
86
+ path = directory / "settings.json"
87
+ try:
88
+ return msgspec.json.decode(path.read_bytes(), type=Settings)
89
+ except (OSError, msgspec.DecodeError):
90
+ return Settings()
91
+
92
+
93
+ def save(settings: Settings, directory: Path | None = None) -> None:
94
+ _atomic_write((directory or home_dir()) / "settings.json", msgspec.json.encode(settings))
95
+
96
+
97
+ class Pairings:
98
+ """Per-device tokens, reloaded from disk on change so `openpi token` works while serving."""
99
+
100
+ def __init__(self, directory: Path | None = None) -> None:
101
+ self.directory = directory or home_dir()
102
+ self._lock = threading.Lock()
103
+ self._mtime: float = -1.0
104
+ self._by_token: dict[str, Pairing] = {}
105
+
106
+ def _path(self) -> Path:
107
+ return self.directory / "pairings.json"
108
+
109
+ def _load(self) -> dict[str, Pairing]:
110
+ path = self._path()
111
+ try:
112
+ mtime = path.stat().st_mtime
113
+ except OSError:
114
+ return {}
115
+ if mtime == self._mtime:
116
+ return self._by_token
117
+ try:
118
+ pairings = msgspec.json.decode(path.read_bytes(), type=list[Pairing])
119
+ except (OSError, msgspec.DecodeError):
120
+ return {}
121
+ self._mtime = mtime
122
+ self._by_token = {p.token: p for p in pairings}
123
+ return self._by_token
124
+
125
+ def _save(self, pairings: list[Pairing]) -> None:
126
+ _atomic_write(self._path(), msgspec.json.encode(pairings))
127
+ self._mtime = -1.0 # force reload on next read
128
+
129
+ def valid(self, token: str) -> bool:
130
+ return token in self._load()
131
+
132
+ def add(self, name: str) -> Pairing:
133
+ with self._lock:
134
+ pairings = list(self._load().values())
135
+ pairing = Pairing(id=secrets.token_hex(4), name=name,
136
+ token=secrets.token_urlsafe(24))
137
+ pairings.append(pairing)
138
+ self._save(pairings)
139
+ return pairing
140
+
141
+ def list(self) -> list[Pairing]:
142
+ return list(self._load().values())
143
+
144
+ def revoke(self, pairing_id: str) -> bool:
145
+ with self._lock:
146
+ pairings = [p for p in self._load().values() if p.id != pairing_id]
147
+ if len(pairings) == len(self._load()):
148
+ return False
149
+ self._save(pairings)
150
+ return True
151
+
openpi/pi/__init__.py ADDED
File without changes
openpi/pi/doctor.py ADDED
@@ -0,0 +1,74 @@
1
+ """Ask a throwaway pi process what it can do. Used by `openpi doctor`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import selectors
6
+ import subprocess
7
+ import time
8
+
9
+ import msgspec
10
+
11
+ from openpi.pi.process import pi_binary
12
+
13
+
14
+ def probe(binary: str | None = None, timeout: float = 20.0) -> dict:
15
+ binary = binary or pi_binary()
16
+ result = {"binary": binary, "version": None, "ok": False, "error": None,
17
+ "state": None, "models": 0, "thinking_levels": []}
18
+ try:
19
+ version = subprocess.run([binary, "--version"], capture_output=True, text=True,
20
+ timeout=timeout)
21
+ text = (version.stdout or version.stderr).strip()
22
+ result["version"] = text.splitlines()[0] if text else None
23
+ except (OSError, subprocess.SubprocessError) as exc:
24
+ result["error"] = f"cannot run {binary}: {exc}"
25
+ return result
26
+
27
+ process = subprocess.Popen(
28
+ [binary, "--mode", "rpc", "--no-session", "--no-extensions", "--no-mcp"],
29
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
30
+ )
31
+ assert process.stdin and process.stdout
32
+ for cid, command in (("1", "get_state"), ("2", "get_available_models"),
33
+ ("3", "get_available_thinking_levels")):
34
+ process.stdin.write(msgspec.json.encode({"id": cid, "type": command}) + b"\n")
35
+ process.stdin.flush()
36
+
37
+ selector = selectors.DefaultSelector()
38
+ selector.register(process.stdout, selectors.EVENT_READ)
39
+ deadline = time.monotonic() + timeout
40
+ seen = 0
41
+ while seen < 3 and time.monotonic() < deadline:
42
+ if not selector.select(timeout=0.5):
43
+ continue
44
+ line = process.stdout.readline()
45
+ if not line:
46
+ break
47
+ try:
48
+ record = msgspec.json.decode(line)
49
+ except msgspec.DecodeError:
50
+ continue
51
+ if record.get("type") != "response" or not record.get("success"):
52
+ if record.get("error"):
53
+ result["error"] = record["error"]
54
+ continue
55
+ seen += 1
56
+ data = record.get("data") or {}
57
+ if record.get("command") == "get_state":
58
+ result["state"] = {
59
+ "session_id": data.get("sessionId"),
60
+ "model": (data.get("model") or {}).get("id"),
61
+ "thinking": data.get("thinkingLevel"),
62
+ }
63
+ elif record.get("command") == "get_available_models":
64
+ result["models"] = len(data.get("models") or [])
65
+ elif record.get("command") == "get_available_thinking_levels":
66
+ result["thinking_levels"] = data.get("levels") or []
67
+
68
+ process.stdin.close()
69
+ try:
70
+ process.wait(timeout=5)
71
+ except subprocess.TimeoutExpired:
72
+ process.kill()
73
+ result["ok"] = result["state"] is not None
74
+ return result