worldcompute 0.1.0a1__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.
- worldcompute/__init__.py +6 -0
- worldcompute/client.py +108 -0
- worldcompute/login.py +76 -0
- worldcompute/quickstart.py +35 -0
- worldcompute/session.py +153 -0
- worldcompute-0.1.0a1.dist-info/METADATA +131 -0
- worldcompute-0.1.0a1.dist-info/RECORD +9 -0
- worldcompute-0.1.0a1.dist-info/WHEEL +4 -0
- worldcompute-0.1.0a1.dist-info/entry_points.txt +2 -0
worldcompute/__init__.py
ADDED
worldcompute/client.py
ADDED
|
@@ -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()
|
worldcompute/login.py
ADDED
|
@@ -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()
|
worldcompute/session.py
ADDED
|
@@ -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,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,9 @@
|
|
|
1
|
+
worldcompute/__init__.py,sha256=tVOoHmitcg5CXVeZiFAYJ_NnZJBEP8YrWlDm4z15lUM,193
|
|
2
|
+
worldcompute/client.py,sha256=dmsb6iq2qon4sQ-4jT8p_M9GUeuEhTE4zN3baP9dyAU,5385
|
|
3
|
+
worldcompute/login.py,sha256=mIc-v57uCNgmHLllZ3ZvcuqIyPAMGE7QYzGjsx50_xs,3765
|
|
4
|
+
worldcompute/quickstart.py,sha256=N-XdJe_YYHOSWsc_zOcL8_InREfP91kppsd23qEjvCw,1668
|
|
5
|
+
worldcompute/session.py,sha256=P5OhTwnJur7vLVA73O4Dfjxvbb1URYZZ0De8Yp-Hax4,6101
|
|
6
|
+
worldcompute-0.1.0a1.dist-info/METADATA,sha256=E1TuO0DZwO6B3-Esy4AjfyiEMmMT4ZauJ-3IZdUyztA,5732
|
|
7
|
+
worldcompute-0.1.0a1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
worldcompute-0.1.0a1.dist-info/entry_points.txt,sha256=a-yqWJEioWRGQ-NW4Txol_0-X4NW5zk0rhkkcktyA0U,72
|
|
9
|
+
worldcompute-0.1.0a1.dist-info/RECORD,,
|