worldcompute 0.1.0a1__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.
@@ -0,0 +1,13 @@
1
+ name: SDK
2
+ on: [push, pull_request]
3
+ jobs:
4
+ test:
5
+ runs-on: ubuntu-latest
6
+ steps:
7
+ - uses: actions/checkout@v4
8
+ - uses: actions/setup-python@v5
9
+ with:
10
+ python-version: '3.11'
11
+ - run: pip install '.[test]'
12
+ - run: pytest -q
13
+ - run: python -m build
@@ -0,0 +1,53 @@
1
+ name: Publish Python package
2
+ on:
3
+ release:
4
+ types: [published]
5
+ permissions:
6
+ contents: read
7
+ jobs:
8
+ build:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ - uses: actions/setup-python@v5
13
+ with:
14
+ python-version: '3.11'
15
+ - name: Verify release tag matches package version
16
+ env:
17
+ RELEASE_TAG: ${{ github.event.release.tag_name }}
18
+ run: |
19
+ python - <<'PYCODE'
20
+ import os, tomllib
21
+ with open('pyproject.toml', 'rb') as f:
22
+ version = tomllib.load(f)['project']['version']
23
+ assert os.environ['RELEASE_TAG'] == f'v{version}', 'Release tag must match package version'
24
+ PYCODE
25
+ - run: python -m pip install '.[test]' twine
26
+ - run: pytest -q
27
+ - run: python -m build
28
+ - run: python -m twine check --strict dist/*
29
+ - name: Check installed wheel outside source tree
30
+ run: |
31
+ python -m venv /tmp/wc-wheel
32
+ /tmp/wc-wheel/bin/pip install dist/*.whl
33
+ cd /tmp
34
+ /tmp/wc-wheel/bin/worldcompute-quickstart --help
35
+ /tmp/wc-wheel/bin/python -c 'from worldcompute import WorldCompute, RobotSession'
36
+ - uses: actions/upload-artifact@v4
37
+ with:
38
+ name: distributions
39
+ path: dist/
40
+ publish:
41
+ needs: build
42
+ runs-on: ubuntu-latest
43
+ environment:
44
+ name: pypi
45
+ url: https://pypi.org/p/worldcompute
46
+ permissions:
47
+ id-token: write
48
+ steps:
49
+ - uses: actions/download-artifact@v4
50
+ with:
51
+ name: distributions
52
+ path: dist/
53
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,7 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ dist/
6
+ *.egg-info/
7
+ .env
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.5
2
+ Name: worldcompute
3
+ Version: 0.1.0a1
4
+ Summary: Python client for World Compute controls
5
+ Project-URL: Documentation, https://worldcompute.org/docs/controls
6
+ Project-URL: Repository, https://github.com/worldcompute001/worldcompute-python
7
+ Author-email: World Compute <team@worldcompute.org>
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: httpx<1,>=0.27
10
+ Requires-Dist: livekit<2,>=1.0
11
+ Provides-Extra: test
12
+ Requires-Dist: build<2,>=1; extra == 'test'
13
+ Requires-Dist: pytest-asyncio<2,>=0.24; extra == 'test'
14
+ Requires-Dist: pytest<10,>=8; extra == 'test'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # World Compute Python SDK
18
+
19
+ Control a registered World Compute robot from a Python program on your computer.
20
+ Use the same API for its simulated twin and physical arm. Source and primary
21
+ maintainer: [World Compute](https://github.com/worldcompute001), team@worldcompute.org.
22
+
23
+ **Prerelease:** not published to PyPI. Production SDK authentication is deployed.
24
+ The standalone quickstart has passed against the remote simulated twin: OAuth
25
+ login, LiveKit admission, measured reset completion, and stop/release. Physical
26
+ SDK reset also passed on SO100 with all six measured joints within 0.5° of the saved pose, followed by stop/release. Other physical command modes are not qualified by that reset test. Sign in using OAuth PKCE; no API key is required.
27
+
28
+ ## Install and run
29
+
30
+ Until the first PyPI release, use the source installation below. Once version
31
+ `0.1.0a1` is published, install and run without cloning:
32
+
33
+ ```bash
34
+ python -m pip install worldcompute==0.1.0a1
35
+ worldcompute-quickstart
36
+ ```
37
+
38
+ This is an alpha release; pin the version when evaluating the SDK.
39
+
40
+ Requires Python 3.11+, an authorized World Compute account, an online station,
41
+ and outbound HTTPS/WebRTC connectivity. Use a local desktop; login listens only
42
+ on 127.0.0.1:8765. That port must be free. Complete login within ten minutes; use the newly opened
43
+ page rather than an older sign-in tab. Login starts on the canonical OAuth issuer
44
+ to preserve its cookies across account sign-in. It does not work through an arbitrary
45
+ remote notebook without forwarding its loopback callback.
46
+
47
+ ```bash
48
+ git clone https://github.com/worldcompute001/worldcompute-python.git
49
+ cd worldcompute-python
50
+ python3 -m venv .venv
51
+ source .venv/bin/activate
52
+ python -m pip install -e .
53
+ python examples/quickstart.py
54
+ ```
55
+
56
+ The example opens account login, discovers registered arms, connects through
57
+ LiveKit, resets the **simulation**, polls measured completion, and stops/releases
58
+ the session. Simulation does not claim or move the physical arm. The station must
59
+ still be connected. The roster is configuration, not proof of motor readiness.
60
+
61
+ To command hardware, first check the arm and clear its path, then run:
62
+
63
+ ```bash
64
+ python examples/quickstart.py --robot so100 --physical
65
+ ```
66
+
67
+ Physical mode requires an explicit confirmation and grants robot:control during
68
+ login. It uses the existing exclusive queue and calibrated limits. Reset is not
69
+ an out-of-range recovery routine; missing motor limits must be resolved by the
70
+ operator. Stop holds position; it does not remove motor power.
71
+
72
+ ## Your own program
73
+
74
+ ```python
75
+ import asyncio
76
+ from worldcompute import WorldCompute
77
+
78
+ async def main():
79
+ async with WorldCompute() as wc:
80
+ await wc.login() # use physical=True only when you need real motion
81
+ robots = await wc.robots()
82
+ async with wc.robot(robots[0]['id'], mode="simulation") as robot:
83
+ request = await robot.reset()
84
+ result = await robot.wait(request)
85
+ print(result)
86
+
87
+ asyncio.run(main())
88
+ ```
89
+
90
+ OAuth credentials remain in memory. Access tokens refresh while making HTTP
91
+ requests. For automation an already authorized access token may be supplied via
92
+ `WC_ACCESS_TOKEN`; it expires and has no automatic refresh without a login grant.
93
+ Never share tokens, use browser cookies or embed the confidential ChatGPT secret.
94
+
95
+ ## Commands
96
+
97
+ | Method | Input / behavior |
98
+ |---|---|
99
+ | `target(positions)` | Named joint targets, radians |
100
+ | `sequence_targets(waypoints)` | List of `{positions, pause_ms?, timeout_ms?}` |
101
+ | `follow(positions)` | Reliable updates of named target positions |
102
+ | `jog(velocities)` | Initialize a velocity stream, radians/second |
103
+ | `publish_jog(velocities)` | Latest-input data packets after jog initialization |
104
+ | `reset()` | This registered arm's saved reset pose |
105
+ | `wait(request_id)` | Require measured completion, not just acceptance |
106
+ | `state()` | Read state and execution history |
107
+ | `hold()` | End the current action, retain the session |
108
+ | `stop()` | Close and release the session |
109
+
110
+ Target/sequence/reset accept `request_id=` for stable correlation. Command methods
111
+ return that ID after acceptance. Context managers renew sessions every two seconds
112
+ and attempt stop before disconnect. Hold before changing action types. If renewal
113
+ or transport fails, new inputs are blocked; there is no automatic replay.
114
+
115
+ `OutcomeUnknown.request_id` identifies an uncertain command. Inspect the original
116
+ execution rather than resending under a new ID. A transport failure may also leave
117
+ Stop unconfirmed; the SDK raises instead of claiming the arm stopped. A powered
118
+ robot requires an attended hardware stop procedure if communications are lost.
119
+
120
+ ## Development and release
121
+
122
+ ```bash
123
+ python -m pip install -e '.[test]'
124
+ pytest -q
125
+ python -m build
126
+ ```
127
+
128
+ Tests use isolated HTTP/LiveKit doubles and do not qualify physical movement.
129
+ Backend tests separately exercise OAuth and admission. Live end-to-end simulation
130
+ and attended physical testing must be reported separately. See [release instructions](docs/releasing.md) for GitHub-to-PyPI trusted publishing.
131
+ Publishing requires the World Compute PyPI owner to register the publisher first.
@@ -0,0 +1,115 @@
1
+ # World Compute Python SDK
2
+
3
+ Control a registered World Compute robot from a Python program on your computer.
4
+ Use the same API for its simulated twin and physical arm. Source and primary
5
+ maintainer: [World Compute](https://github.com/worldcompute001), team@worldcompute.org.
6
+
7
+ **Prerelease:** not published to PyPI. Production SDK authentication is deployed.
8
+ The standalone quickstart has passed against the remote simulated twin: OAuth
9
+ login, LiveKit admission, measured reset completion, and stop/release. Physical
10
+ SDK reset also passed on SO100 with all six measured joints within 0.5° of the saved pose, followed by stop/release. Other physical command modes are not qualified by that reset test. Sign in using OAuth PKCE; no API key is required.
11
+
12
+ ## Install and run
13
+
14
+ Until the first PyPI release, use the source installation below. Once version
15
+ `0.1.0a1` is published, install and run without cloning:
16
+
17
+ ```bash
18
+ python -m pip install worldcompute==0.1.0a1
19
+ worldcompute-quickstart
20
+ ```
21
+
22
+ This is an alpha release; pin the version when evaluating the SDK.
23
+
24
+ Requires Python 3.11+, an authorized World Compute account, an online station,
25
+ and outbound HTTPS/WebRTC connectivity. Use a local desktop; login listens only
26
+ on 127.0.0.1:8765. That port must be free. Complete login within ten minutes; use the newly opened
27
+ page rather than an older sign-in tab. Login starts on the canonical OAuth issuer
28
+ to preserve its cookies across account sign-in. It does not work through an arbitrary
29
+ remote notebook without forwarding its loopback callback.
30
+
31
+ ```bash
32
+ git clone https://github.com/worldcompute001/worldcompute-python.git
33
+ cd worldcompute-python
34
+ python3 -m venv .venv
35
+ source .venv/bin/activate
36
+ python -m pip install -e .
37
+ python examples/quickstart.py
38
+ ```
39
+
40
+ The example opens account login, discovers registered arms, connects through
41
+ LiveKit, resets the **simulation**, polls measured completion, and stops/releases
42
+ the session. Simulation does not claim or move the physical arm. The station must
43
+ still be connected. The roster is configuration, not proof of motor readiness.
44
+
45
+ To command hardware, first check the arm and clear its path, then run:
46
+
47
+ ```bash
48
+ python examples/quickstart.py --robot so100 --physical
49
+ ```
50
+
51
+ Physical mode requires an explicit confirmation and grants robot:control during
52
+ login. It uses the existing exclusive queue and calibrated limits. Reset is not
53
+ an out-of-range recovery routine; missing motor limits must be resolved by the
54
+ operator. Stop holds position; it does not remove motor power.
55
+
56
+ ## Your own program
57
+
58
+ ```python
59
+ import asyncio
60
+ from worldcompute import WorldCompute
61
+
62
+ async def main():
63
+ async with WorldCompute() as wc:
64
+ await wc.login() # use physical=True only when you need real motion
65
+ robots = await wc.robots()
66
+ async with wc.robot(robots[0]['id'], mode="simulation") as robot:
67
+ request = await robot.reset()
68
+ result = await robot.wait(request)
69
+ print(result)
70
+
71
+ asyncio.run(main())
72
+ ```
73
+
74
+ OAuth credentials remain in memory. Access tokens refresh while making HTTP
75
+ requests. For automation an already authorized access token may be supplied via
76
+ `WC_ACCESS_TOKEN`; it expires and has no automatic refresh without a login grant.
77
+ Never share tokens, use browser cookies or embed the confidential ChatGPT secret.
78
+
79
+ ## Commands
80
+
81
+ | Method | Input / behavior |
82
+ |---|---|
83
+ | `target(positions)` | Named joint targets, radians |
84
+ | `sequence_targets(waypoints)` | List of `{positions, pause_ms?, timeout_ms?}` |
85
+ | `follow(positions)` | Reliable updates of named target positions |
86
+ | `jog(velocities)` | Initialize a velocity stream, radians/second |
87
+ | `publish_jog(velocities)` | Latest-input data packets after jog initialization |
88
+ | `reset()` | This registered arm's saved reset pose |
89
+ | `wait(request_id)` | Require measured completion, not just acceptance |
90
+ | `state()` | Read state and execution history |
91
+ | `hold()` | End the current action, retain the session |
92
+ | `stop()` | Close and release the session |
93
+
94
+ Target/sequence/reset accept `request_id=` for stable correlation. Command methods
95
+ return that ID after acceptance. Context managers renew sessions every two seconds
96
+ and attempt stop before disconnect. Hold before changing action types. If renewal
97
+ or transport fails, new inputs are blocked; there is no automatic replay.
98
+
99
+ `OutcomeUnknown.request_id` identifies an uncertain command. Inspect the original
100
+ execution rather than resending under a new ID. A transport failure may also leave
101
+ Stop unconfirmed; the SDK raises instead of claiming the arm stopped. A powered
102
+ robot requires an attended hardware stop procedure if communications are lost.
103
+
104
+ ## Development and release
105
+
106
+ ```bash
107
+ python -m pip install -e '.[test]'
108
+ pytest -q
109
+ python -m build
110
+ ```
111
+
112
+ Tests use isolated HTTP/LiveKit doubles and do not qualify physical movement.
113
+ Backend tests separately exercise OAuth and admission. Live end-to-end simulation
114
+ and attended physical testing must be reported separately. See [release instructions](docs/releasing.md) for GitHub-to-PyPI trusted publishing.
115
+ Publishing requires the World Compute PyPI owner to register the publisher first.
@@ -0,0 +1,50 @@
1
+ # Standalone Python SDK
2
+
3
+ Owner and primary author: worldcompute001. Package contact: team@worldcompute.org.
4
+ Commits use the GitHub account's numeric-ID noreply address, not the personal account.
5
+
6
+ ## Delivery steps
7
+
8
+ 1. Package foundation and asynchronous session client, with injectable HTTP/LiveKit
9
+ transports and deterministic tests. Repository: worldcompute001/worldcompute-python.
10
+ 2. External developer authentication and admission in the World Compute backend,
11
+ plus Python login and LiveKit connection. Keep browser controls compatible.
12
+ 3. Runnable local simulation quickstart, documented physical opt-in, CI and build
13
+ artifacts. Open a separate PR for each step; do not publish to PyPI yet.
14
+
15
+ ## Existing implementation to reuse
16
+
17
+ world-compute-v0/apps/cloud-mcp/controls-client.ts defines the unified command
18
+ contract. controls-api.ts signs robot, mode, participant, boot and lease-bound
19
+ admission tickets. controls_sessions.py owns execution and measured results.
20
+ Do not implement a second executor or expose the station's private HTTP port.
21
+
22
+ Current public HTTP admission requires same-origin cookies, CSRF and a signed
23
+ browser LiveKit binding. Existing OAuth is registered for the ChatGPT confidential
24
+ client, not a public Python application. A Python package alone cannot provide a
25
+ working external quickstart: backend authentication/admission must be extended.
26
+ Do not document invented API keys, copy browser cookies, distribute client secrets,
27
+ or bypass the existing per-person queue and ownership checks.
28
+
29
+ Evaluate a public OAuth authorization-code client with PKCE and loopback callback,
30
+ reusing the existing identity provider and scoped principal checks. Bind SDK-issued
31
+ LiveKit credentials to the authenticated principal, just as browser credentials
32
+ are bound to their session. Explicit scope checks for read, simulation and motion.
33
+
34
+ ## SDK behavior
35
+
36
+ Async context managers connect and release sessions. Simulation is the default.
37
+ Expose target, sequence, follow, jog, reset, state, hold and stop. Renewal runs
38
+ only for an active session. Transport loss cancels input production; it never
39
+ replays movement. Stable request IDs identify uncertain outcomes. Arrival-waiting
40
+ methods inspect measured completion and report cancellation/timeout distinctly.
41
+ Cleanup attempts stop before disconnect; unconfirmed stop is reported honestly.
42
+
43
+ ## Acceptance evidence
44
+
45
+ Build/install wheel into a clean environment; test denied authentication,
46
+ wrong-owner admission, expired leases, RPC failures, renewal failure, cleanup,
47
+ stream deadlines and measured completion. Run the documented command from outside
48
+ the website against simulation, confirming physical ownership remains untouched.
49
+ A physical reset requires fresh readiness and attended clearance. Mock tests and
50
+ simulation do not establish physical qualification.
@@ -0,0 +1,50 @@
1
+ # Publishing World Compute
2
+
3
+ Use PyPI trusted publishing; do not store a permanent PyPI token in GitHub.
4
+ The author and maintainer are World Compute (team@worldcompute.org).
5
+
6
+ ## One-time owner setup
7
+
8
+ Sign into the intended World Compute PyPI owner account, verify email, and enable
9
+ PyPI-required two-factor authentication. For the first release, add a pending
10
+ publisher at https://pypi.org/manage/account/publishing/ with:
11
+
12
+ | Field | Value |
13
+ |---|---|
14
+ | PyPI project | `worldcompute` |
15
+ | GitHub owner | `worldcompute001` |
16
+ | Repository | `worldcompute-python` |
17
+ | Workflow filename | `publish.yml` |
18
+ | Environment | `pypi` |
19
+
20
+ Create the GitHub repository environment `pypi` before publishing. The first
21
+ successful upload creates the project under the account that registered the
22
+ pending publisher. A name lookup returning 404 does not reserve the name.
23
+ Reference: https://docs.pypi.org/trusted-publishers/creating-a-project-through-oidc/
24
+
25
+ ## Release
26
+
27
+ 1. Merge the release PR with green CI. Check `pyproject.toml` version.
28
+ 2. Publish a GitHub prerelease tagged `v0.1.0a1` from that exact merged commit.
29
+ 3. The `publish.yml` workflow tests, builds and checks the distributions, installs
30
+ the wheel into a clean environment, then publishes using short-lived identity.
31
+ 4. Verify `python -m pip install worldcompute==0.1.0a1` in a new environment.
32
+ 5. Run `worldcompute-quickstart` against simulation with a fresh browser login.
33
+ Physical testing is separate and requires attended clearance.
34
+ 6. Update README and website publication status only after upload succeeds.
35
+
36
+ Do not reuse a published version. For a defective release, yank it on PyPI and
37
+ publish a corrected version. No hardware or service rollout is involved.
38
+
39
+ ## Qualification evidence
40
+
41
+ - Remote simulation: request `339982bb-c4f2-4fdb-af50-2046d1687c75`, completed,
42
+ measured targets, session stopped/released.
43
+ - Attended SO100 reset: request `5bc65e51-2170-4105-871e-ed54726bc64a`, completed,
44
+ all six joints within 0.5 degrees, session stopped/released.
45
+ - These runs used the source SDK. Release wheel installation and public-index
46
+ installation are separate checks; neither implies all physical modes are tested.
47
+ - Release wheel `0.1.0a1`: installed with dependencies into a fresh virtualenv,
48
+ outside the source checkout. Installed `worldcompute-quickstart` completed
49
+ remote simulation request `8c047284-e223-4e2d-be99-1e85c4d103f5`, measured all
50
+ six targets, then stopped/released. Public PyPI installation remains pending.
@@ -0,0 +1,5 @@
1
+ """Run the installed SDK quickstart from a source checkout."""
2
+ from worldcompute.quickstart import run
3
+
4
+ if __name__ == "__main__":
5
+ run()
@@ -0,0 +1,21 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.26,<2"]
3
+ build-backend = "hatchling.build"
4
+ [project]
5
+ name = "worldcompute"
6
+ version = "0.1.0a1"
7
+ description = "Python client for World Compute controls"
8
+ readme = "README.md"
9
+ requires-python = ">=3.11"
10
+ authors = [{name = "World Compute", email = "team@worldcompute.org"}]
11
+ dependencies = ["httpx>=0.27,<1", "livekit>=1.0,<2"]
12
+ [project.scripts]
13
+ worldcompute-quickstart = "worldcompute.quickstart:run"
14
+
15
+ [project.optional-dependencies]
16
+ test = ["pytest>=8,<10", "pytest-asyncio>=0.24,<2", "build>=1,<2"]
17
+ [project.urls]
18
+ Documentation = "https://worldcompute.org/docs/controls"
19
+ Repository = "https://github.com/worldcompute001/worldcompute-python"
20
+ [tool.pytest.ini_options]
21
+ asyncio_mode = "auto"
@@ -0,0 +1,6 @@
1
+ from .session import ControlsError, OutcomeUnknown, RobotSession
2
+
3
+ __all__ = ['ControlsError', 'OutcomeUnknown', 'RobotSession']
4
+
5
+ from .client import WorldCompute
6
+ __all__.append("WorldCompute")
@@ -0,0 +1,108 @@
1
+ """Standalone HTTP admission and LiveKit transport; never direct motor access."""
2
+ import asyncio
3
+ import json
4
+ import os
5
+ import time
6
+ from contextlib import asynccontextmanager
7
+ from urllib.parse import urlparse
8
+ import httpx
9
+ from .session import RobotSession, ControlsError
10
+
11
+
12
+ class WorldCompute:
13
+ def __init__(self, *, base_url='https://worldcompute.org', access_token=None, http=None, room_factory=None):
14
+ url = urlparse(base_url)
15
+ if url.scheme != 'https' or url.username or url.password or url.query or url.fragment or url.path not in ('', '/'):
16
+ raise ValueError('base_url must be an HTTPS origin')
17
+ self.base_url = base_url.rstrip('/')
18
+ self.access_token = access_token or os.environ.get('WC_ACCESS_TOKEN')
19
+ self._refresh_token = None
20
+ self._resource = self.base_url + "/mcp"
21
+ self._expires = 0
22
+ self._refresh_lock = asyncio.Lock()
23
+ self.http = http or httpx.AsyncClient(base_url=self.base_url, timeout=10, follow_redirects=False)
24
+ self._owns_http = http is None
25
+ self.room_factory = room_factory
26
+
27
+ async def login(self, *, physical=False, open_browser=True):
28
+ from .login import authorize
29
+ tokens = await authorize(self.http, self.base_url, physical=physical, open_browser=open_browser)
30
+ self._set_tokens(tokens)
31
+ return self
32
+
33
+ def _set_tokens(self, tokens):
34
+ self.access_token = tokens['access_token']
35
+ self._resource = tokens.get('_resource', self._resource)
36
+ self._refresh_token = tokens.get('refresh_token', self._refresh_token)
37
+ self._expires = time.monotonic() + tokens.get('expires_in', 900)
38
+
39
+ async def _credentials(self):
40
+ async with self._refresh_lock:
41
+ if self._refresh_token and time.monotonic() >= self._expires - 60:
42
+ response = await self.http.post('/oauth/token', data={
43
+ 'grant_type':'refresh_token', 'refresh_token':self._refresh_token,
44
+ 'client_id':'world-compute-python', 'resource':self._resource})
45
+ if response.status_code != 200:
46
+ raise ControlsError('Login expired; authenticate again')
47
+ self._set_tokens(response.json())
48
+ if not self.access_token:
49
+ raise ControlsError('Call await wc.login() or provide WC_ACCESS_TOKEN')
50
+ return {'Authorization':'Bearer '+self.access_token}
51
+
52
+ async def _request(self, method, path, body=None):
53
+ response = await self.http.request(method, path, headers=await self._credentials(), json=body)
54
+ if not response.is_success:
55
+ raise ControlsError(f'World Compute HTTP {response.status_code}: request rejected; do not replay motion automatically')
56
+ return response.json()
57
+
58
+ async def robots(self):
59
+ return (await self._request('GET', '/api/sdk/v1/robots'))['robots']
60
+
61
+ @asynccontextmanager
62
+ async def robot(self, robot_id, *, mode='simulation'):
63
+ from uuid import uuid4
64
+ from urllib.parse import quote
65
+ if mode not in ('simulation', 'physical'):
66
+ raise ValueError('mode must be simulation or physical')
67
+ if self.room_factory is None:
68
+ from livekit import rtc
69
+ room = rtc.Room()
70
+ else:
71
+ room = self.room_factory()
72
+ session = None
73
+ try:
74
+ live = await self._request('POST', '/api/sdk/v1/live-token', {})
75
+ await room.connect(live['url'], live['token'])
76
+ # The production station joins on demand. Wait before requesting its
77
+ # ten-second admission ticket; never retry an uncertain command.
78
+ station = live.get('station', 'canary:station')
79
+ deadline = time.monotonic() + 30
80
+ while station not in room.remote_participants:
81
+ if time.monotonic() >= deadline:
82
+ raise ControlsError('Station did not join LiveKit within 30 seconds')
83
+ await asyncio.sleep(.1)
84
+ admission = await self._request('POST', '/api/sdk/v1/robots/'+quote(robot_id,safe='')+'/sessions', {
85
+ 'request_id':str(uuid4()), 'mode':mode, 'identity':live['identity'], 'binding':live['binding']})
86
+ created = json.loads(await room.local_participant.perform_rpc(
87
+ destination_identity=admission['station'], method='wc.controls.v1',
88
+ payload=json.dumps({'ticket':admission['ticket']}), response_timeout=5))
89
+ if created['status'] not in (200,201):
90
+ raise ControlsError('Session creation rejected')
91
+ body = created['body']
92
+ if body['robot_id'] != robot_id or body['mode'] != mode:
93
+ raise ControlsError('Session identity mismatch; command not sent')
94
+ session = RobotSession(room.local_participant, admission['station'], body, created.get('server_time'))
95
+ # Prevent continued input after disconnect; never reconnect/replay automatically.
96
+ if hasattr(room, 'on'):
97
+ room.on('disconnected', lambda *args: setattr(session, 'failure', ControlsError('LiveKit disconnected')))
98
+ async with session:
99
+ yield session
100
+ finally:
101
+ await room.disconnect()
102
+
103
+ async def __aenter__(self):
104
+ return self
105
+
106
+ async def __aexit__(self, *exc):
107
+ if self._owns_http:
108
+ await self.http.aclose()
@@ -0,0 +1,76 @@
1
+ """Public OAuth client: PKCE S256, loopback callback, in-memory credentials."""
2
+ import asyncio
3
+ import base64
4
+ import hashlib
5
+ import secrets
6
+ import webbrowser
7
+ from urllib.parse import urlencode, urlparse, parse_qs
8
+ from .session import ControlsError
9
+
10
+ CLIENT_ID = 'world-compute-python'
11
+ REDIRECT = 'http://127.0.0.1:8765/callback'
12
+
13
+
14
+ async def authorize(http, origin, *, physical=False, open_browser=True, timeout=600):
15
+ metadata = await http.get('/.well-known/oauth-protected-resource/mcp')
16
+ metadata.raise_for_status()
17
+ resource = metadata.json()['resource']
18
+ discovery = await http.get('/.well-known/oauth-authorization-server/oauth')
19
+ discovery.raise_for_status()
20
+ issuer = discovery.json()['issuer']
21
+ verifier = secrets.token_urlsafe(48)
22
+ state = secrets.token_urlsafe(32)
23
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b'=').decode()
24
+ future = asyncio.get_running_loop().create_future()
25
+
26
+ async def callback(reader, writer):
27
+ try:
28
+ line = await asyncio.wait_for(reader.readline(), 5)
29
+ parts = line.decode('ascii').split()
30
+ target = urlparse(parts[1]) if len(parts) == 3 and parts[0] == 'GET' else None
31
+ query = parse_qs(target.query) if target else {}
32
+ valid = (target and target.path == '/callback' and query.get('state') == [state]
33
+ and query.get('iss') == [issuer])
34
+ code = query.get('code', [])
35
+ if valid and len(code) == 1 and not future.done():
36
+ future.set_result(code[0])
37
+ status, message = '200 OK', 'Authorized. Return to your terminal.'
38
+ else:
39
+ if valid and query.get('error') and not future.done():
40
+ future.set_exception(ControlsError('Authorization denied'))
41
+ status, message = '400 Bad Request', 'Invalid or denied authorization.'
42
+ body = message.encode()
43
+ writer.write(f'HTTP/1.1 {status}\r\nContent-Type: text/plain\r\nCache-Control: no-store\r\nContent-Length: {len(body)}\r\nConnection: close\r\n\r\n'.encode()+body)
44
+ await writer.drain()
45
+ except (ValueError, UnicodeError, asyncio.TimeoutError):
46
+ pass
47
+ finally:
48
+ writer.close()
49
+ await writer.wait_closed()
50
+
51
+ server = await asyncio.start_server(callback, '127.0.0.1', 8765, limit=8192)
52
+ # Account sign-in returns to the canonical issuer; start there so its
53
+ # host-only interaction cookie survives that round trip.
54
+ url = issuer.rstrip('/')+'/auth?'+urlencode({'client_id':CLIENT_ID, 'response_type':'code',
55
+ 'redirect_uri':REDIRECT, 'scope':'robot:read simulator:control offline_access'+(' robot:control' if physical else ''),
56
+ 'resource':resource, 'state':state, 'code_challenge':challenge, 'code_challenge_method':'S256'})
57
+ try:
58
+ print('Sign in to World Compute:', url)
59
+ if open_browser:
60
+ webbrowser.open(url)
61
+ async with server:
62
+ try:
63
+ code = await asyncio.wait_for(future, timeout)
64
+ except asyncio.TimeoutError as error:
65
+ raise ControlsError('Login timed out; rerun the quickstart for a fresh sign-in page') from error
66
+ response = await http.post('/oauth/token', data={'grant_type':'authorization_code',
67
+ 'client_id':CLIENT_ID,'redirect_uri':REDIRECT,'code':code,
68
+ 'code_verifier':verifier,'resource':resource})
69
+ if response.status_code != 200:
70
+ raise ControlsError('Authorization exchange failed; start login again')
71
+ tokens = response.json()
72
+ tokens['_resource'] = resource
73
+ return tokens
74
+ finally:
75
+ server.close()
76
+ await server.wait_closed()
@@ -0,0 +1,35 @@
1
+ """Run from your own computer. Defaults to the remote simulated twin."""
2
+ import argparse
3
+ import asyncio
4
+ from worldcompute import WorldCompute
5
+
6
+ async def main():
7
+ parser = argparse.ArgumentParser()
8
+ parser.add_argument('--robot', help='Registered robot ID; otherwise use the first listed robot')
9
+ parser.add_argument('--base-url', default='https://worldcompute.org')
10
+ parser.add_argument('--physical', action='store_true', help='Command real hardware (requires attended clearance)')
11
+ parser.add_argument('--no-browser', action='store_true', help='Print login URL instead of opening it')
12
+ args = parser.parse_args()
13
+ if args.physical and input('Physical reset moves the arm. Operator present and path clear? Type RESET: ') != 'RESET':
14
+ raise SystemExit('Cancelled; no connection or command sent')
15
+ async with WorldCompute(base_url=args.base_url) as wc:
16
+ if not wc.access_token:
17
+ await wc.login(physical=args.physical, open_browser=not args.no_browser)
18
+ robots = await wc.robots()
19
+ if not robots:
20
+ raise SystemExit('No robots available to this account')
21
+ robot_id = args.robot or robots[0]['id']
22
+ mode = 'physical' if args.physical else 'simulation'
23
+ print(f'Connecting to {robot_id} in {mode} mode')
24
+ async with wc.robot(robot_id, mode=mode) as robot:
25
+ request_id = await robot.reset()
26
+ print('Accepted request:', request_id)
27
+ result = await robot.wait(request_id)
28
+ print('Measured completion:', result)
29
+ print('Session stopped and released')
30
+
31
+ def run():
32
+ asyncio.run(main())
33
+
34
+ if __name__ == '__main__':
35
+ run()
@@ -0,0 +1,153 @@
1
+ """The existing wc.controls.v1 contract, without HTTP or hardware ownership."""
2
+ import asyncio
3
+ import json
4
+ import time
5
+ from datetime import datetime, timezone
6
+ from uuid import uuid4
7
+
8
+
9
+ class ControlsError(RuntimeError):
10
+ pass
11
+
12
+
13
+ class OutcomeUnknown(ControlsError):
14
+ def __init__(self, request_id):
15
+ self.request_id = request_id
16
+ super().__init__(f'Outcome unconfirmed for {request_id}; inspect state before another command')
17
+
18
+
19
+ class RobotSession:
20
+ def __init__(self, participant, station, created, server_time=None):
21
+ self.participant, self.station = participant, station
22
+ self.id, self.mode = created['session_id'], created['mode']
23
+ self.robot_id = created['robot_id']
24
+ self.offset = (server_time - time.time()) if server_time else 0
25
+ self.closed = False
26
+ self.failure = None
27
+ self.sequence = 0
28
+ self.stream_id = None
29
+ self.stream_kind = None
30
+ self._renewal = None
31
+
32
+ async def _rpc(self, operation, body=None):
33
+ if self.closed:
34
+ raise ControlsError('Session closed')
35
+ if self.failure and operation not in ('state', 'hold', 'stop'):
36
+ raise ControlsError('Session renewal failed; reconnect deliberately') from self.failure
37
+ raw = await self.participant.perform_rpc(destination_identity=self.station,
38
+ method='wc.controls.v1', payload=json.dumps({'session_id': self.id,
39
+ 'operation': operation, 'body': body or {}}), response_timeout=3)
40
+ result = json.loads(raw)
41
+ if result['status'] != 200:
42
+ raise ControlsError(result.get('body', {}).get('error', 'Request rejected'))
43
+ return result['body']
44
+
45
+ def _packet(self, action, request_id, lifetime=1):
46
+ packet = {'request_id': request_id, 'action': action}
47
+ if action['type'] in ('joint_follow', 'joint_jog'):
48
+ self.sequence += 1
49
+ packet.update(sequence=self.sequence, expires_at=datetime.fromtimestamp(
50
+ time.time()+self.offset+lifetime, timezone.utc).isoformat())
51
+ return packet
52
+
53
+ async def command(self, action, *, request_id=None):
54
+ request_id = request_id or str(uuid4())
55
+ try:
56
+ result = await self._rpc('commands', self._packet(action, request_id))
57
+ except ControlsError:
58
+ raise
59
+ except Exception as error:
60
+ raise OutcomeUnknown(request_id) from error
61
+ if result.get('state') != 'dispatched':
62
+ raise ControlsError(result.get('reason', 'Command rejected'))
63
+ self.stream_id = result.get('stream_id')
64
+ self.stream_kind = action['type']
65
+ return request_id
66
+
67
+ async def target(self, positions, *, request_id=None):
68
+ return await self.command({'type': 'joint_target', 'positions': positions}, request_id=request_id)
69
+
70
+ async def sequence_targets(self, waypoints, *, request_id=None):
71
+ return await self.command({'type': 'joint_sequence', 'waypoints': waypoints}, request_id=request_id)
72
+
73
+ async def follow(self, positions):
74
+ return await self.command({'type': 'joint_follow', 'positions': positions})
75
+
76
+ async def jog(self, velocities):
77
+ return await self.command({'type': 'joint_jog', 'velocities': velocities})
78
+
79
+ async def publish_jog(self, velocities):
80
+ if self.closed or self.failure or not self.stream_id or self.stream_kind != 'joint_jog':
81
+ raise ControlsError('Initialize a healthy jog session first')
82
+ command = self._packet({'type': 'joint_jog', 'velocities': velocities}, str(uuid4()), .3)
83
+ await self.participant.publish_data(json.dumps({'session_id': self.id, 'operation': 'inputs',
84
+ 'body': {'stream_id': self.stream_id, 'command': command}}).encode(),
85
+ reliable=False, topic='wc.controls.input.v1', destination_identities=[self.station])
86
+
87
+ async def reset(self, *, request_id=None):
88
+ return await self.command({'type': 'reset'}, request_id=request_id)
89
+
90
+ async def state(self):
91
+ return await self._rpc('state')
92
+
93
+ async def wait(self, request_id, *, timeout=30):
94
+ deadline = time.monotonic()+timeout
95
+ while time.monotonic() < deadline:
96
+ result = (await self.state()).get('executions', {}).get(request_id)
97
+ if result:
98
+ if result['state'] == 'completed':
99
+ return result
100
+ if result['state'] not in ('pending', 'running', 'dispatched'):
101
+ raise ControlsError(f'Execution {request_id} ended: {result["state"]}')
102
+ await asyncio.sleep(.1)
103
+ raise OutcomeUnknown(request_id)
104
+
105
+ async def renew(self):
106
+ return await self._rpc('renew')
107
+
108
+ async def hold(self):
109
+ self.stream_id = None
110
+ result = await self._rpc('hold')
111
+ if result.get('state') != 'dispatched':
112
+ raise ControlsError('Hold unconfirmed')
113
+ return result
114
+
115
+ async def stop(self):
116
+ if self.closed:
117
+ return
118
+ self.stream_id = None
119
+ try:
120
+ result = await self._rpc('stop')
121
+ if result.get('state') != 'dispatched':
122
+ raise ControlsError('Stop unconfirmed')
123
+ finally:
124
+ self.closed = True
125
+
126
+ async def _renew_loop(self):
127
+ try:
128
+ while not self.closed:
129
+ await asyncio.sleep(2)
130
+ await self.renew()
131
+ except asyncio.CancelledError:
132
+ raise
133
+ except Exception as error:
134
+ self.failure = error
135
+ self.stream_id = None
136
+ try:
137
+ await self.hold()
138
+ except Exception:
139
+ pass # Never report an unconfirmed hold as success.
140
+
141
+ async def __aenter__(self):
142
+ if self.closed or self._renewal:
143
+ raise ControlsError('Session cannot be entered twice')
144
+ self._renewal = asyncio.create_task(self._renew_loop())
145
+ return self
146
+
147
+ async def __aexit__(self, *exc):
148
+ self._renewal.cancel()
149
+ try:
150
+ await self._renewal
151
+ except asyncio.CancelledError:
152
+ pass
153
+ await self.stop()
@@ -0,0 +1,52 @@
1
+ import json
2
+ import asyncio
3
+ import httpx
4
+ import pytest
5
+ from worldcompute import WorldCompute, ControlsError
6
+
7
+ class Room:
8
+ def __init__(self): self.remote_participants={"canary:station":object()};self.local_participant=self;self.calls=[];self.disconnected=False
9
+ async def connect(self,*args): pass
10
+ async def disconnect(self):self.disconnected=True
11
+ async def perform_rpc(self,**kwargs):
12
+ p=json.loads(kwargs['payload']);self.calls.append(p)
13
+ if 'ticket' in p:body={'session_id':'s','mode':'simulation','robot_id':'arm'}
14
+ elif p['operation']=='state':body={'executions':{'id':{'state':'completed'}}}
15
+ else:body={'state':'dispatched'}
16
+ return json.dumps({'status':200,'body':body})
17
+
18
+ async def test_standalone_admission_and_cleanup():
19
+ requests=[];room=Room()
20
+ room.remote_participants.clear()
21
+ asyncio.get_running_loop().call_later(.15, lambda: room.remote_participants.update({"canary:station":object()}))
22
+ def respond(req):
23
+ requests.append(req)
24
+ assert req.headers['authorization']=='Bearer token'
25
+ if req.url.path.endswith('/live-token'):data={'url':'wss://live','token':'live','identity':'i','binding':'b'}
26
+ elif req.url.path.endswith('/sessions'):
27
+ assert 'canary:station' in room.remote_participants
28
+ assert json.loads(req.content)['mode']=='simulation'
29
+ data={'ticket':'t','station':'station'}
30
+ else:data={'robots':[{'id':'arm'}]}
31
+ return httpx.Response(200,json=data)
32
+ async with httpx.AsyncClient(base_url='https://wc.test',transport=httpx.MockTransport(respond)) as http:
33
+ async with WorldCompute(base_url='https://wc.test',access_token='token',http=http,room_factory=lambda:room) as wc:
34
+ assert await wc.robots()==[{'id':'arm'}]
35
+ async with wc.robot('arm') as arm:
36
+ await arm.reset(request_id='id');assert (await arm.wait('id'))['state']=='completed'
37
+ assert room.calls[-1]['operation']=='stop';assert room.disconnected
38
+ assert len(requests)==3
39
+
40
+ async def test_rejected_admission_disconnects_without_commands():
41
+ room=Room()
42
+ def respond(req):
43
+ return httpx.Response(200,json={'url':'wss://live','token':'live','identity':'i','binding':'b'}) if req.url.path.endswith('/live-token') else httpx.Response(403)
44
+ async with httpx.AsyncClient(base_url='https://wc.test',transport=httpx.MockTransport(respond)) as http:
45
+ wc=WorldCompute(base_url='https://wc.test',access_token='t',http=http,room_factory=lambda:room)
46
+ with pytest.raises(ControlsError):
47
+ async with wc.robot('arm'):pass
48
+ assert room.disconnected;assert room.calls==[]
49
+
50
+ def test_reject_insecure_or_credentialed_origin():
51
+ for url in ['http://example.com','https://user:pass@example.com','https://example.com/path']:
52
+ with pytest.raises(ValueError):WorldCompute(base_url=url)
@@ -0,0 +1,39 @@
1
+ import asyncio
2
+ import hashlib
3
+ import base64
4
+ from urllib.parse import urlparse, parse_qs, urlencode
5
+ import httpx
6
+ from worldcompute.login import authorize
7
+
8
+ async def test_login_checks_callback_state_and_pkce(monkeypatch):
9
+ urls=[];monkeypatch.setattr('webbrowser.open',lambda url:urls.append(url))
10
+ observed={}
11
+ def exchange(req):
12
+ if req.method == "GET":
13
+ return httpx.Response(200,json={"resource":"https://issuer.test/mcp","issuer":"https://issuer.test/oauth"})
14
+ data=parse_qs(req.content.decode());observed.update(data)
15
+ return httpx.Response(200,json={'access_token':'token','refresh_token':'refresh','expires_in':900})
16
+ async with httpx.AsyncClient(base_url='https://wc.test',transport=httpx.MockTransport(exchange)) as http:
17
+ task=asyncio.create_task(authorize(http,'https://wc.test',timeout=5))
18
+ try:
19
+ for _ in range(50):
20
+ if urls:break
21
+ await asyncio.sleep(.01)
22
+ assert urls[0].startswith('https://issuer.test/oauth/auth?')
23
+ query=parse_qs(urlparse(urls[0]).query)
24
+ assert query['client_id']==['world-compute-python']
25
+ assert 'robot:control' not in query['scope'][0]
26
+ async with httpx.AsyncClient(trust_env=False) as callback:
27
+ bad=await callback.get('http://127.0.0.1:8765/callback',params={'state':'wrong','iss':'https://issuer.test/oauth','code':'bad'})
28
+ assert bad.status_code==400;assert not task.done()
29
+ ok=await callback.get('http://127.0.0.1:8765/callback',params={'state':query['state'][0],'iss':'https://issuer.test/oauth','code':'good'})
30
+ assert ok.status_code==200
31
+ assert (await task)['access_token']=='token'
32
+ challenge=base64.urlsafe_b64encode(hashlib.sha256(observed['code_verifier'][0].encode()).digest()).rstrip(b'=').decode()
33
+ assert query['code_challenge']==[challenge]
34
+ assert observed['resource']==['https://issuer.test/mcp'];assert observed['code']==['good'];assert 'client_secret' not in observed
35
+ finally:
36
+ if not task.done():
37
+ task.cancel()
38
+ try:await task
39
+ except asyncio.CancelledError:pass
@@ -0,0 +1,39 @@
1
+ import json
2
+ import pytest
3
+ from worldcompute import RobotSession, ControlsError, OutcomeUnknown
4
+
5
+ class Participant:
6
+ def __init__(self): self.calls=[]; self.fail=False
7
+ async def perform_rpc(self, **kwargs):
8
+ p=json.loads(kwargs['payload']);self.calls.append(p)
9
+ if self.fail: raise TimeoutError()
10
+ body={'state':'dispatched', 'stream_id':'stream'}
11
+ if p['operation']=='state': body={'executions':{'id':{'state':'completed'}}}
12
+ return json.dumps({'status':200,'body':body})
13
+ async def publish_data(self,*args,**kwargs):self.calls.append(kwargs)
14
+
15
+ def session(p): return RobotSession(p,'station',{'session_id':'s','mode':'simulation','robot_id':'arm'})
16
+
17
+ async def test_measured_completion_cleanup():
18
+ p=Participant()
19
+ async with session(p) as s:
20
+ assert await s.reset(request_id='id')=='id'
21
+ assert (await s.wait('id'))['state']=='completed'
22
+ assert p.calls[-1]['operation']=='stop'
23
+ with pytest.raises(ControlsError):await s.reset()
24
+
25
+ async def test_unknown_never_retried():
26
+ p=Participant();p.fail=True;s=session(p)
27
+ with pytest.raises(OutcomeUnknown) as error:await s.reset(request_id='original')
28
+ assert error.value.request_id=='original';assert len(p.calls)==1
29
+
30
+ async def test_hold_invalidates_stream():
31
+ p=Participant();s=session(p)
32
+ await s.jog({'elbow':.1});await s.publish_jog({'elbow':0})
33
+ await s.hold()
34
+ with pytest.raises(ControlsError):await s.publish_jog({'elbow':.1})
35
+
36
+ async def test_failed_renewal_blocks_commands_but_allows_stop():
37
+ p=Participant();s=session(p);s.failure=TimeoutError()
38
+ with pytest.raises(ControlsError):await s.reset()
39
+ await s.stop()