jetpack-sdk 0.1.1__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,28 @@
1
+ """JetPack Python Worker SDK.
2
+
3
+ Lightweight, zero-dependency client library for native sandboxed workers
4
+ communicating with `jetpack-daemon` over local IPC.
5
+ """
6
+
7
+ from .client import JetPackClient
8
+ from .decorators import get_opcode_metadata, opcode
9
+ from .framing import (
10
+ FrameHeader,
11
+ HybridFrame,
12
+ decode_stream_frame,
13
+ encode_hybrid_frame,
14
+ pack_msgpack,
15
+ unpack_msgpack,
16
+ )
17
+
18
+ __all__ = [
19
+ "JetPackClient",
20
+ "FrameHeader",
21
+ "HybridFrame",
22
+ "opcode",
23
+ "get_opcode_metadata",
24
+ "encode_hybrid_frame",
25
+ "decode_stream_frame",
26
+ "pack_msgpack",
27
+ "unpack_msgpack",
28
+ ]
jetpack_sdk/client.py ADDED
@@ -0,0 +1,534 @@
1
+ """Local binary IPC client for JetPack sandboxed workers.
2
+
3
+ Connects to the orchestrator daemon via Unix Domain Socket (macOS/Linux)
4
+ or Named Pipe (Windows) specified in the `JETPACK_IPC_ENDPOINT` environment variable.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ctypes
10
+ import os
11
+ import platform
12
+ import socket
13
+ import threading
14
+ import time
15
+ from pathlib import Path
16
+ from typing import Any, Optional
17
+
18
+ from .framing import FrameHeader, HybridFrame, decode_stream_frame, encode_hybrid_frame
19
+
20
+ _ERROR_BROKEN_PIPE = 109
21
+ _ERROR_PIPE_BUSY = 231
22
+ _ERROR_PIPE_NOT_CONNECTED = 233
23
+ _ERROR_OPERATION_ABORTED = 995
24
+ _ERROR_IO_PENDING = 997
25
+
26
+
27
+ class _SocketStreamReader:
28
+ """Helper wrapping a socket to provide read(n) semantics."""
29
+
30
+ def __init__(self, sock: socket.socket):
31
+ self._sock = sock
32
+
33
+ def read(self, n: int) -> bytes:
34
+ chunks = []
35
+ bytes_left = n
36
+ while bytes_left > 0:
37
+ try:
38
+ chunk = self._sock.recv(bytes_left)
39
+ except (BlockingIOError, socket.timeout):
40
+ break
41
+ if not chunk:
42
+ break
43
+ chunks.append(chunk)
44
+ bytes_left -= len(chunk)
45
+ return b"".join(chunks)
46
+
47
+
48
+ class _Win32OverlappedPipe:
49
+ """Thread-safe full-duplex Windows Named Pipe transport using FILE_FLAG_OVERLAPPED.
50
+
51
+ Standard synchronous `open(..., "r+b")` on a Windows named pipe serializes all I/O
52
+ requests on the kernel FILE_OBJECT, causing a blocking `ReadFile` on the main loop
53
+ thread to deadlock any concurrent `WriteFile` from a background worker thread.
54
+ Using `FILE_FLAG_OVERLAPPED` with separate read and write `OVERLAPPED` events allows
55
+ simultaneous reading and writing without deadlocking.
56
+ """
57
+
58
+ def __init__(self, endpoint: str, connect_attempts: int = 40):
59
+ from ctypes import wintypes
60
+
61
+ self._wintypes = wintypes
62
+ self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
63
+ self._configure_win32_api()
64
+
65
+ self._read_lock = threading.Lock()
66
+ self._write_lock = threading.Lock()
67
+ self._closed = False
68
+ self._handle: Any = None
69
+ self._read_event: Any = None
70
+ self._write_event: Any = None
71
+
72
+ GENERIC_READ = 0x80000000
73
+ GENERIC_WRITE = 0x40000000
74
+ OPEN_EXISTING = 3
75
+ FILE_ATTRIBUTE_NORMAL = 0x00000080
76
+ FILE_FLAG_OVERLAPPED = 0x40000000
77
+ INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
78
+
79
+ last_err: Optional[OSError] = None
80
+ handle = None
81
+ for _ in range(connect_attempts):
82
+ handle = self._kernel32.CreateFileW(
83
+ endpoint,
84
+ GENERIC_READ | GENERIC_WRITE,
85
+ 0,
86
+ None,
87
+ OPEN_EXISTING,
88
+ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
89
+ None,
90
+ )
91
+ if handle and handle != INVALID_HANDLE_VALUE:
92
+ break
93
+ err = ctypes.get_last_error()
94
+ last_err = ctypes.WinError(err)
95
+ if err == _ERROR_PIPE_BUSY:
96
+ self._kernel32.WaitNamedPipeW(endpoint, 50)
97
+ time.sleep(0.025)
98
+ continue
99
+ raise last_err
100
+ else:
101
+ if last_err is not None:
102
+ raise last_err
103
+ raise OSError(f"Failed to open named pipe: {endpoint}")
104
+
105
+ read_event = self._kernel32.CreateEventW(None, True, False, None)
106
+ if not read_event:
107
+ err = ctypes.get_last_error()
108
+ self._kernel32.CloseHandle(handle)
109
+ raise ctypes.WinError(err)
110
+
111
+ write_event = self._kernel32.CreateEventW(None, True, False, None)
112
+ if not write_event:
113
+ err = ctypes.get_last_error()
114
+ self._kernel32.CloseHandle(read_event)
115
+ self._kernel32.CloseHandle(handle)
116
+ raise ctypes.WinError(err)
117
+
118
+ self._handle = handle
119
+ self._read_event = read_event
120
+ self._write_event = write_event
121
+
122
+ def _configure_win32_api(self) -> None:
123
+ wintypes = self._wintypes
124
+ k32 = self._kernel32
125
+
126
+ class _OverlappedOffset(ctypes.Structure):
127
+ _fields_ = [
128
+ ("Offset", wintypes.DWORD),
129
+ ("OffsetHigh", wintypes.DWORD),
130
+ ]
131
+
132
+ class _OverlappedUnion(ctypes.Union):
133
+ _fields_ = [
134
+ ("_offset", _OverlappedOffset),
135
+ ("Pointer", ctypes.c_void_p),
136
+ ]
137
+
138
+ class _OVERLAPPED(ctypes.Structure):
139
+ _fields_ = [
140
+ ("Internal", ctypes.c_size_t),
141
+ ("InternalHigh", ctypes.c_size_t),
142
+ ("_u", _OverlappedUnion),
143
+ ("hEvent", wintypes.HANDLE),
144
+ ]
145
+
146
+ self._OVERLAPPED = _OVERLAPPED
147
+ LPOVERLAPPED = ctypes.POINTER(_OVERLAPPED)
148
+
149
+ k32.CreateFileW.argtypes = [
150
+ wintypes.LPCWSTR,
151
+ wintypes.DWORD,
152
+ wintypes.DWORD,
153
+ ctypes.c_void_p,
154
+ wintypes.DWORD,
155
+ wintypes.DWORD,
156
+ wintypes.HANDLE,
157
+ ]
158
+ k32.CreateFileW.restype = wintypes.HANDLE
159
+
160
+ k32.WaitNamedPipeW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD]
161
+ k32.WaitNamedPipeW.restype = wintypes.BOOL
162
+
163
+ k32.CreateEventW.argtypes = [
164
+ ctypes.c_void_p,
165
+ wintypes.BOOL,
166
+ wintypes.BOOL,
167
+ wintypes.LPCWSTR,
168
+ ]
169
+ k32.CreateEventW.restype = wintypes.HANDLE
170
+
171
+ k32.ResetEvent.argtypes = [wintypes.HANDLE]
172
+ k32.ResetEvent.restype = wintypes.BOOL
173
+
174
+ k32.ReadFile.argtypes = [
175
+ wintypes.HANDLE,
176
+ ctypes.c_void_p,
177
+ wintypes.DWORD,
178
+ ctypes.POINTER(wintypes.DWORD),
179
+ LPOVERLAPPED,
180
+ ]
181
+ k32.ReadFile.restype = wintypes.BOOL
182
+
183
+ k32.WriteFile.argtypes = [
184
+ wintypes.HANDLE,
185
+ ctypes.c_void_p,
186
+ wintypes.DWORD,
187
+ ctypes.POINTER(wintypes.DWORD),
188
+ LPOVERLAPPED,
189
+ ]
190
+ k32.WriteFile.restype = wintypes.BOOL
191
+
192
+ k32.GetOverlappedResult.argtypes = [
193
+ wintypes.HANDLE,
194
+ LPOVERLAPPED,
195
+ ctypes.POINTER(wintypes.DWORD),
196
+ wintypes.BOOL,
197
+ ]
198
+ k32.GetOverlappedResult.restype = wintypes.BOOL
199
+
200
+ k32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
201
+ k32.WaitForSingleObject.restype = wintypes.DWORD
202
+
203
+ k32.CancelIoEx.argtypes = [wintypes.HANDLE, LPOVERLAPPED]
204
+ k32.CancelIoEx.restype = wintypes.BOOL
205
+
206
+ k32.CloseHandle.argtypes = [wintypes.HANDLE]
207
+ k32.CloseHandle.restype = wintypes.BOOL
208
+
209
+ def read(self, n: int, timeout: Optional[float] = None) -> bytes:
210
+ if n <= 0:
211
+ return b""
212
+
213
+ WAIT_OBJECT_0 = 0x00000000
214
+ deadline = (time.monotonic() + timeout) if timeout is not None else None
215
+
216
+ with self._read_lock:
217
+ if self._closed or self._handle is None:
218
+ return b""
219
+
220
+ chunks = []
221
+ bytes_left = n
222
+ while bytes_left > 0:
223
+ if self._closed or self._handle is None:
224
+ break
225
+
226
+ buf = (ctypes.c_ubyte * bytes_left)()
227
+ n_read = self._wintypes.DWORD(0)
228
+ ov = self._OVERLAPPED()
229
+ ov.hEvent = self._read_event
230
+ self._kernel32.ResetEvent(self._read_event)
231
+
232
+ ok = self._kernel32.ReadFile(
233
+ self._handle,
234
+ buf,
235
+ bytes_left,
236
+ ctypes.byref(n_read),
237
+ ctypes.byref(ov),
238
+ )
239
+ if not ok:
240
+ err = ctypes.get_last_error()
241
+ if err == _ERROR_IO_PENDING:
242
+ if deadline is None:
243
+ ok2 = self._kernel32.GetOverlappedResult(
244
+ self._handle,
245
+ ctypes.byref(ov),
246
+ ctypes.byref(n_read),
247
+ True,
248
+ )
249
+ if not ok2:
250
+ err2 = ctypes.get_last_error()
251
+ if (
252
+ err2 in (_ERROR_BROKEN_PIPE, _ERROR_PIPE_NOT_CONNECTED, _ERROR_OPERATION_ABORTED)
253
+ or self._closed
254
+ ):
255
+ break
256
+ raise ctypes.WinError(err2)
257
+ else:
258
+ rem_ms = max(0, int((deadline - time.monotonic()) * 1000))
259
+ wait_rc = self._kernel32.WaitForSingleObject(self._read_event, rem_ms)
260
+ if wait_rc == WAIT_OBJECT_0:
261
+ ok2 = self._kernel32.GetOverlappedResult(
262
+ self._handle,
263
+ ctypes.byref(ov),
264
+ ctypes.byref(n_read),
265
+ False,
266
+ )
267
+ if not ok2:
268
+ err2 = ctypes.get_last_error()
269
+ if (
270
+ err2 in (_ERROR_BROKEN_PIPE, _ERROR_PIPE_NOT_CONNECTED, _ERROR_OPERATION_ABORTED)
271
+ or self._closed
272
+ ):
273
+ break
274
+ raise ctypes.WinError(err2)
275
+ else:
276
+ self._kernel32.CancelIoEx(self._handle, ctypes.byref(ov))
277
+ ok2 = self._kernel32.GetOverlappedResult(
278
+ self._handle,
279
+ ctypes.byref(ov),
280
+ ctypes.byref(n_read),
281
+ True,
282
+ )
283
+ if ok2 and n_read.value > 0:
284
+ chunks.append(bytes(memoryview(buf)[: n_read.value]))
285
+ bytes_left -= n_read.value
286
+ break
287
+ elif (
288
+ err in (_ERROR_BROKEN_PIPE, _ERROR_PIPE_NOT_CONNECTED, _ERROR_OPERATION_ABORTED)
289
+ or self._closed
290
+ ):
291
+ break
292
+ else:
293
+ raise ctypes.WinError(err)
294
+
295
+ count = n_read.value
296
+ if count == 0:
297
+ break
298
+ chunks.append(bytes(memoryview(buf)[:count]))
299
+ bytes_left -= count
300
+
301
+ return b"".join(chunks)
302
+
303
+ def write_all(self, data: bytes) -> None:
304
+ if not data:
305
+ return
306
+
307
+ view = memoryview(data)
308
+ with self._write_lock:
309
+ if self._closed or self._handle is None:
310
+ raise RuntimeError("Client is not connected")
311
+
312
+ offset = 0
313
+ total = len(data)
314
+ while offset < total:
315
+ chunk_len = total - offset
316
+ buf = (ctypes.c_ubyte * chunk_len).from_buffer_copy(view[offset:])
317
+ n_written = self._wintypes.DWORD(0)
318
+ ov = self._OVERLAPPED()
319
+ ov.hEvent = self._write_event
320
+ self._kernel32.ResetEvent(self._write_event)
321
+
322
+ ok = self._kernel32.WriteFile(
323
+ self._handle,
324
+ buf,
325
+ chunk_len,
326
+ ctypes.byref(n_written),
327
+ ctypes.byref(ov),
328
+ )
329
+ if not ok:
330
+ err = ctypes.get_last_error()
331
+ if err == _ERROR_IO_PENDING:
332
+ ok2 = self._kernel32.GetOverlappedResult(
333
+ self._handle,
334
+ ctypes.byref(ov),
335
+ ctypes.byref(n_written),
336
+ True,
337
+ )
338
+ if not ok2:
339
+ raise ctypes.WinError(ctypes.get_last_error())
340
+ else:
341
+ raise ctypes.WinError(err)
342
+
343
+ written = n_written.value
344
+ if written == 0:
345
+ raise BrokenPipeError("Named pipe WriteFile returned 0 bytes")
346
+ offset += written
347
+
348
+ def close(self) -> None:
349
+ if self._closed:
350
+ return
351
+ self._closed = True
352
+ handle = self._handle
353
+ if handle is not None:
354
+ try:
355
+ self._kernel32.CancelIoEx(handle, None)
356
+ except Exception:
357
+ pass
358
+ with self._read_lock:
359
+ with self._write_lock:
360
+ if self._handle is not None:
361
+ try:
362
+ self._kernel32.CloseHandle(self._handle)
363
+ except Exception:
364
+ pass
365
+ self._handle = None
366
+ if self._read_event is not None:
367
+ try:
368
+ self._kernel32.CloseHandle(self._read_event)
369
+ except Exception:
370
+ pass
371
+ self._read_event = None
372
+ if self._write_event is not None:
373
+ try:
374
+ self._kernel32.CloseHandle(self._write_event)
375
+ except Exception:
376
+ pass
377
+ self._write_event = None
378
+
379
+
380
+ class _TimedPipeReader:
381
+ """Adapter enforcing a shared deadline across decode_stream_frame reads."""
382
+
383
+ def __init__(self, pipe: _Win32OverlappedPipe, timeout: Optional[float]):
384
+ self._pipe = pipe
385
+ self._deadline = (time.monotonic() + timeout) if timeout is not None else None
386
+
387
+ def read(self, n: int) -> bytes:
388
+ if self._deadline is None:
389
+ return self._pipe.read(n)
390
+ remaining = max(0.0, self._deadline - time.monotonic())
391
+ return self._pipe.read(n, timeout=remaining)
392
+
393
+
394
+ class JetPackClient:
395
+ """Bidirectional binary IPC client communicating with `jetpack-daemon`."""
396
+
397
+ def __init__(self, endpoint: Optional[str] = None):
398
+ if endpoint is None:
399
+ endpoint = os.environ.get("JETPACK_IPC_ENDPOINT")
400
+ if not endpoint:
401
+ raise ValueError(
402
+ "No IPC endpoint specified and JETPACK_IPC_ENDPOINT environment variable is unset"
403
+ )
404
+ self.endpoint = endpoint
405
+ self._sock: Optional[socket.socket] = None
406
+ self._pipe: Optional[_Win32OverlappedPipe] = None
407
+ self._reader: Any = None
408
+ self._write_lock = threading.Lock()
409
+ self._opcode_handlers: dict[str, Any] = {}
410
+ self._connect()
411
+
412
+ def opcode(
413
+ self,
414
+ name: str,
415
+ *,
416
+ request: Any = None,
417
+ response: Any = None,
418
+ binary: bool = False,
419
+ stream: bool = False,
420
+ ) -> Any:
421
+ """Decorator registering an opcode handler on this client instance."""
422
+ from .decorators import opcode as _opcode_decorator
423
+
424
+ base_decorator = _opcode_decorator(
425
+ name,
426
+ request=request,
427
+ response=response,
428
+ binary=binary,
429
+ stream=stream,
430
+ )
431
+
432
+ def register(fn: Any) -> Any:
433
+ decorated = base_decorator(fn)
434
+ self._opcode_handlers[name.strip()] = decorated
435
+ return decorated
436
+
437
+ return register
438
+
439
+ def _connect(self) -> None:
440
+ if platform.system() == "Windows" or self.endpoint.startswith(r"\\.\pipe" + "\\"):
441
+ self._pipe = _Win32OverlappedPipe(self.endpoint)
442
+ self._reader = self._pipe
443
+ else:
444
+ # Unix Domain Socket on macOS / Linux
445
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
446
+ sock.connect(self.endpoint)
447
+ self._sock = sock
448
+ self._reader = _SocketStreamReader(sock)
449
+
450
+ @property
451
+ def proxy_endpoint(self) -> Optional[str]:
452
+ """Returns the in-daemon userspace proxy endpoint if configured."""
453
+ return (
454
+ os.environ.get("JETPACK_PROXY_ENDPOINT")
455
+ or os.environ.get("HTTP_PROXY")
456
+ or os.environ.get("ALL_PROXY")
457
+ )
458
+
459
+ @property
460
+ def app_home(self) -> Path:
461
+ """Returns the isolated per-app persistent data directory (`JETPACK_APP_HOME`)."""
462
+ raw = (os.environ.get("JETPACK_APP_HOME") or "").strip()
463
+ if not raw:
464
+ raise RuntimeError("JETPACK_APP_HOME environment variable is unset or empty")
465
+ return Path(raw)
466
+
467
+ def send(self, frame: HybridFrame) -> None:
468
+ """Sends a HybridFrame to the daemon."""
469
+ raw = encode_hybrid_frame(frame.header, frame.payload)
470
+ self._write_all(raw)
471
+
472
+ def send_frame(
473
+ self,
474
+ opcode: str,
475
+ payload: bytes = b"",
476
+ channel_id: int = 0,
477
+ correlation_id: Optional[int] = None,
478
+ target_worker: Optional[str] = None,
479
+ ) -> None:
480
+ """Constructs and sends a hybrid frame."""
481
+ header = FrameHeader(
482
+ channel_id=channel_id,
483
+ opcode=opcode,
484
+ correlation_id=correlation_id,
485
+ target_worker=target_worker,
486
+ )
487
+ self.send(HybridFrame(header=header, payload=payload))
488
+
489
+ def _write_all(self, data: bytes) -> None:
490
+ if self._sock is not None:
491
+ with self._write_lock:
492
+ self._sock.sendall(data)
493
+ elif self._pipe is not None:
494
+ self._pipe.write_all(data)
495
+ else:
496
+ raise RuntimeError("Client is not connected")
497
+
498
+ def read_frame(self, timeout: Optional[float] = None) -> Optional[HybridFrame]:
499
+ """Reads a hybrid frame from the daemon, with optional timeout in seconds."""
500
+ if self._sock is not None and timeout is not None:
501
+ orig_timeout = self._sock.gettimeout()
502
+ self._sock.settimeout(timeout)
503
+ try:
504
+ return decode_stream_frame(self._reader)
505
+ finally:
506
+ self._sock.settimeout(orig_timeout)
507
+ elif self._pipe is not None:
508
+ return decode_stream_frame(_TimedPipeReader(self._pipe, timeout))
509
+ elif self._reader is not None:
510
+ return decode_stream_frame(self._reader)
511
+ else:
512
+ raise RuntimeError("Client is not connected")
513
+
514
+ def close(self) -> None:
515
+ """Closes the IPC connection."""
516
+ if self._sock is not None:
517
+ try:
518
+ self._sock.close()
519
+ except Exception:
520
+ pass
521
+ self._sock = None
522
+ if self._pipe is not None:
523
+ try:
524
+ self._pipe.close()
525
+ except Exception:
526
+ pass
527
+ self._pipe = None
528
+ self._reader = None
529
+
530
+ def __enter__(self) -> JetPackClient:
531
+ return self
532
+
533
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
534
+ self.close()
@@ -0,0 +1,46 @@
1
+ """Optional typed opcode decorator helpers for JetPack Python workers.
2
+
3
+ Pure-stdlib implementation (zero mandatory third-party dependencies) so workers can
4
+ annotate opcode handlers for `jetpack codegen` while staying 100% compatible with
5
+ existing manual `while True: frame = client.read_frame()` loops.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Callable, Optional, TypeVar
11
+
12
+ F = TypeVar("F", bound=Callable[..., Any])
13
+
14
+
15
+ def opcode(
16
+ name: str,
17
+ *,
18
+ request: Any = None,
19
+ response: Any = None,
20
+ binary: bool = False,
21
+ stream: bool = False,
22
+ ) -> Callable[[F], F]:
23
+ """Attach JetPack opcode contract metadata (`__jetpack_opcode__`) to a handler function."""
24
+ cleaned = name.strip()
25
+ if not cleaned:
26
+ raise ValueError("opcode name must be a non-empty string")
27
+
28
+ metadata = {
29
+ "opcode": cleaned,
30
+ "request": request,
31
+ "response": response,
32
+ "binary": bool(binary),
33
+ "stream": bool(stream),
34
+ }
35
+
36
+ def decorator(fn: F) -> F:
37
+ setattr(fn, "__jetpack_opcode__", metadata)
38
+ return fn
39
+
40
+ return decorator
41
+
42
+
43
+ def get_opcode_metadata(fn: Callable[..., Any]) -> Optional[dict[str, Any]]:
44
+ """Return attached `__jetpack_opcode__` metadata if present."""
45
+ meta = getattr(fn, "__jetpack_opcode__", None)
46
+ return dict(meta) if isinstance(meta, dict) else None
jetpack_sdk/framing.py ADDED
@@ -0,0 +1,287 @@
1
+ """Hybrid binary framing codec for JetPack local IPC.
2
+
3
+ Frame wire format:
4
+ [4-byte uint32 LE frame length] + [4-byte uint32 LE header length] + [MsgPack Header] + [Raw Payload]
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import io
10
+ import struct
11
+ from dataclasses import dataclass
12
+ from typing import Any, Dict, Optional, Tuple
13
+
14
+ # Try importing standard msgpack if installed, otherwise use built-in mini-msgpack
15
+ try:
16
+ import msgpack as _fast_msgpack # type: ignore
17
+ except ImportError:
18
+ _fast_msgpack = None
19
+
20
+
21
+ # --- Minimal MsgPack Encoder / Decoder ---
22
+
23
+ def _pack_obj(obj: Any) -> bytes:
24
+ if obj is None:
25
+ return b"\xc0"
26
+ elif isinstance(obj, bool):
27
+ return b"\xc3" if obj else b"\xc2"
28
+ elif isinstance(obj, int):
29
+ if obj >= 0:
30
+ if obj <= 0x7F:
31
+ return struct.pack("B", obj)
32
+ elif obj <= 0xFF:
33
+ return b"\xcc" + struct.pack("B", obj)
34
+ elif obj <= 0xFFFF:
35
+ return b"\xcd" + struct.pack(">H", obj)
36
+ elif obj <= 0xFFFFFFFF:
37
+ return b"\xce" + struct.pack(">I", obj)
38
+ else:
39
+ return b"\xcf" + struct.pack(">Q", obj)
40
+ else:
41
+ if obj >= -32:
42
+ return struct.pack("b", obj)
43
+ elif obj >= -128:
44
+ return b"\xd0" + struct.pack("b", obj)
45
+ elif obj >= -32768:
46
+ return b"\xd1" + struct.pack(">h", obj)
47
+ elif obj >= -2147483648:
48
+ return b"\xd2" + struct.pack(">i", obj)
49
+ else:
50
+ return b"\xd3" + struct.pack(">q", obj)
51
+ elif isinstance(obj, str):
52
+ utf8 = obj.encode("utf-8")
53
+ n = len(utf8)
54
+ if n <= 31:
55
+ return bytes([0xA0 | n]) + utf8
56
+ elif n <= 0xFF:
57
+ return b"\xd9" + struct.pack("B", n) + utf8
58
+ elif n <= 0xFFFF:
59
+ return b"\xda" + struct.pack(">H", n) + utf8
60
+ else:
61
+ return b"\xdb" + struct.pack(">I", n) + utf8
62
+ elif isinstance(obj, (bytes, bytearray)):
63
+ n = len(obj)
64
+ if n <= 0xFF:
65
+ return b"\xc4" + struct.pack("B", n) + bytes(obj)
66
+ elif n <= 0xFFFF:
67
+ return b"\xc5" + struct.pack(">H", n) + bytes(obj)
68
+ else:
69
+ return b"\xc6" + struct.pack(">I", n) + bytes(obj)
70
+ elif isinstance(obj, (list, tuple)):
71
+ n = len(obj)
72
+ if n <= 15:
73
+ prefix = bytes([0x90 | n])
74
+ elif n <= 0xFFFF:
75
+ prefix = b"\xdc" + struct.pack(">H", n)
76
+ else:
77
+ prefix = b"\xdd" + struct.pack(">I", n)
78
+ return prefix + b"".join(_pack_obj(x) for x in obj)
79
+ elif isinstance(obj, dict):
80
+ n = len(obj)
81
+ if n <= 15:
82
+ prefix = bytes([0x80 | n])
83
+ elif n <= 0xFFFF:
84
+ prefix = b"\xde" + struct.pack(">H", n)
85
+ else:
86
+ prefix = b"\xdf" + struct.pack(">I", n)
87
+ body = io.BytesIO()
88
+ for k, v in obj.items():
89
+ body.write(_pack_obj(k))
90
+ body.write(_pack_obj(v))
91
+ return prefix + body.getvalue()
92
+ else:
93
+ raise TypeError(f"Unsupported msgpack type: {type(obj)}")
94
+
95
+
96
+ def _unpack_obj(stream: io.BytesIO) -> Any:
97
+ b = stream.read(1)
98
+ if not b:
99
+ raise EOFError("Unexpected end of msgpack stream")
100
+ byte = b[0]
101
+
102
+ # positive fixint
103
+ if byte <= 0x7F:
104
+ return byte
105
+ # fixmap
106
+ if 0x80 <= byte <= 0x8F:
107
+ count = byte & 0x0F
108
+ return {str(_unpack_obj(stream)): _unpack_obj(stream) for _ in range(count)}
109
+ # fixarray
110
+ if 0x90 <= byte <= 0x9F:
111
+ count = byte & 0x0F
112
+ return [_unpack_obj(stream) for _ in range(count)]
113
+ # fixstr
114
+ if 0xA0 <= byte <= 0xBF:
115
+ length = byte & 0x1F
116
+ return stream.read(length).decode("utf-8", errors="replace")
117
+ # negative fixint
118
+ if byte >= 0xE0:
119
+ return struct.unpack("b", bytes([byte]))[0]
120
+
121
+ # Special tags
122
+ if byte == 0xC0:
123
+ return None
124
+ elif byte == 0xC2:
125
+ return False
126
+ elif byte == 0xC3:
127
+ return True
128
+ elif byte == 0xC4: # bin 8
129
+ n = struct.unpack("B", stream.read(1))[0]
130
+ return stream.read(n)
131
+ elif byte == 0xC5: # bin 16
132
+ n = struct.unpack(">H", stream.read(2))[0]
133
+ return stream.read(n)
134
+ elif byte == 0xC6: # bin 32
135
+ n = struct.unpack(">I", stream.read(4))[0]
136
+ return stream.read(n)
137
+ elif byte == 0xCC: # uint 8
138
+ return struct.unpack("B", stream.read(1))[0]
139
+ elif byte == 0xCD: # uint 16
140
+ return struct.unpack(">H", stream.read(2))[0]
141
+ elif byte == 0xCE: # uint 32
142
+ return struct.unpack(">I", stream.read(4))[0]
143
+ elif byte == 0xCF: # uint 64
144
+ return struct.unpack(">Q", stream.read(8))[0]
145
+ elif byte == 0xD0: # int 8
146
+ return struct.unpack("b", stream.read(1))[0]
147
+ elif byte == 0xD1: # int 16
148
+ return struct.unpack(">h", stream.read(2))[0]
149
+ elif byte == 0xD2: # int 32
150
+ return struct.unpack(">i", stream.read(4))[0]
151
+ elif byte == 0xD3: # int 64
152
+ return struct.unpack(">q", stream.read(8))[0]
153
+ elif byte == 0xD9: # str 8
154
+ n = struct.unpack("B", stream.read(1))[0]
155
+ return stream.read(n).decode("utf-8", errors="replace")
156
+ elif byte == 0xDA: # str 16
157
+ n = struct.unpack(">H", stream.read(2))[0]
158
+ return stream.read(n).decode("utf-8", errors="replace")
159
+ elif byte == 0xDB: # str 32
160
+ n = struct.unpack(">I", stream.read(4))[0]
161
+ return stream.read(n).decode("utf-8", errors="replace")
162
+ elif byte == 0xDC: # array 16
163
+ n = struct.unpack(">H", stream.read(2))[0]
164
+ return [_unpack_obj(stream) for _ in range(n)]
165
+ elif byte == 0xDD: # array 32
166
+ n = struct.unpack(">I", stream.read(4))[0]
167
+ return [_unpack_obj(stream) for _ in range(n)]
168
+ elif byte == 0xDE: # map 16
169
+ n = struct.unpack(">H", stream.read(2))[0]
170
+ return {str(_unpack_obj(stream)): _unpack_obj(stream) for _ in range(n)}
171
+ elif byte == 0xDF: # map 32
172
+ n = struct.unpack(">I", stream.read(4))[0]
173
+ return {str(_unpack_obj(stream)): _unpack_obj(stream) for _ in range(n)}
174
+ else:
175
+ raise ValueError(f"Unknown msgpack header byte: 0x{byte:02x}")
176
+
177
+
178
+ def pack_msgpack(data: Any) -> bytes:
179
+ if _fast_msgpack is not None:
180
+ return _fast_msgpack.packb(data, use_bin_type=True)
181
+ return _pack_obj(data)
182
+
183
+
184
+ def unpack_msgpack(raw: bytes) -> Any:
185
+ if _fast_msgpack is not None:
186
+ return _fast_msgpack.unpackb(raw, raw=False)
187
+ return _unpack_obj(io.BytesIO(raw))
188
+
189
+
190
+ # --- JetPack Hybrid Frame Data Structures ---
191
+
192
+ @dataclass
193
+ class FrameHeader:
194
+ channel_id: int
195
+ opcode: str
196
+ correlation_id: Optional[int] = None
197
+ target_worker: Optional[str] = None
198
+
199
+ def to_dict(self) -> Dict[str, Any]:
200
+ d: Dict[str, Any] = {
201
+ "channel_id": self.channel_id,
202
+ "opcode": self.opcode,
203
+ }
204
+ if self.correlation_id is not None:
205
+ d["correlation_id"] = self.correlation_id
206
+ if self.target_worker is not None:
207
+ d["target_worker"] = self.target_worker
208
+ return d
209
+
210
+ @classmethod
211
+ def from_dict(cls, d: Dict[str, Any]) -> FrameHeader:
212
+ return cls(
213
+ channel_id=int(d["channel_id"]),
214
+ opcode=str(d["opcode"]),
215
+ correlation_id=d.get("correlation_id"),
216
+ target_worker=d.get("target_worker"),
217
+ )
218
+
219
+
220
+ @dataclass
221
+ class HybridFrame:
222
+ header: FrameHeader
223
+ payload: bytes
224
+
225
+ @property
226
+ def opcode(self) -> str:
227
+ return self.header.opcode
228
+
229
+ @property
230
+ def channel_id(self) -> int:
231
+ return self.header.channel_id
232
+
233
+ @property
234
+ def correlation_id(self) -> Optional[int]:
235
+ return self.header.correlation_id
236
+
237
+ @property
238
+ def target_worker(self) -> Optional[str]:
239
+ return self.header.target_worker
240
+
241
+
242
+ # --- Encoding & Decoding Functions ---
243
+
244
+ def encode_hybrid_frame(header: FrameHeader, payload: bytes = b"") -> bytes:
245
+ """Encodes a hybrid frame into length-prefixed stream bytes.
246
+
247
+ Layout:
248
+ [4-byte frame length LE] + [4-byte header length LE] + [MsgPack Header] + [Raw Payload]
249
+ Where frame length = 4 + len(MsgPack Header) + len(Raw Payload).
250
+ """
251
+ header_bytes = pack_msgpack(header.to_dict())
252
+ header_len = len(header_bytes)
253
+ total_len = 4 + header_len + len(payload)
254
+ return struct.pack("<II", total_len, header_len) + header_bytes + payload
255
+
256
+
257
+ def decode_stream_frame(stream_reader: Any) -> Optional[HybridFrame]:
258
+ """Reads a complete length-prefixed hybrid frame from a blocking file/socket stream.
259
+
260
+ Returns None on EOF before any bytes are read.
261
+ """
262
+ len_buf = stream_reader.read(4)
263
+ if not len_buf:
264
+ return None
265
+ if len(len_buf) < 4:
266
+ raise io.IncompleteReadError(len_buf, 4)
267
+
268
+ total_len = struct.unpack("<I", len_buf)[0]
269
+ if total_len < 4:
270
+ raise ValueError(f"Invalid frame length: {total_len} (must be >= 4)")
271
+
272
+ frame_bytes = stream_reader.read(total_len)
273
+ if len(frame_bytes) < total_len:
274
+ raise io.IncompleteReadError(frame_bytes, total_len)
275
+
276
+ header_len = struct.unpack("<I", frame_bytes[:4])[0]
277
+ if 4 + header_len > total_len:
278
+ raise ValueError(
279
+ f"Corrupt frame: declared header length {header_len} exceeds frame {total_len}"
280
+ )
281
+
282
+ raw_header = frame_bytes[4 : 4 + header_len]
283
+ raw_payload = frame_bytes[4 + header_len :]
284
+
285
+ header_dict = unpack_msgpack(raw_header)
286
+ header = FrameHeader.from_dict(header_dict)
287
+ return HybridFrame(header=header, payload=raw_payload)
jetpack_sdk/py.typed ADDED
File without changes
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.3
2
+ Name: jetpack-sdk
3
+ Version: 0.1.1
4
+ Summary: Lightweight Python Worker SDK for JetPack local IPC and proxy orchestration
5
+ Project-URL: Homepage, https://jetpack-desktop.github.io
6
+ Project-URL: Documentation, https://jetpack-desktop.github.io/sdk/worker/python-sdk
7
+ Project-URL: Repository, https://github.com/jetpack-desktop/jetpack
8
+ Project-URL: Issues, https://github.com/jetpack-desktop/jetpack/issues
9
+ Author: JetPack Contributors
10
+ License: MIT OR Apache-2.0
11
+ Keywords: ai,gpu,ipc,jetpack,msgpack,sandbox,worker,zero-copy
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Classifier: Topic :: System :: Networking
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.9
27
+ Provides-Extra: msgpack
28
+ Requires-Dist: msgpack>=1.0.0; extra == 'msgpack'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # `jetpack-sdk`
32
+
33
+ Lightweight, zero-dependency Python Worker SDK for [JetPack](https://jetpack-desktop.github.io) local IPC, zero-copy binary framing, and sandboxed GPU worker orchestration.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install jetpack-sdk
39
+ ```
40
+
41
+ Or using `uv`:
42
+
43
+ ```bash
44
+ uv add jetpack-sdk
45
+ ```
46
+
47
+ For faster Cython-accelerated MsgPack header encoding/decoding, install the optional `msgpack` extra (otherwise `jetpack-sdk` uses its built-in pure-Python MsgPack codec with zero external runtime dependencies):
48
+
49
+ ```bash
50
+ pip install "jetpack-sdk[msgpack]"
51
+ ```
52
+
53
+ > **Note:** When running inside a worker managed by `jetpack-daemon`, `jetpack-sdk` is also embedded offline inside the daemon and provisioned into `.venv` automatically if `requirements = ["jetpack-sdk"]` is declared in `app.toml`.
54
+
55
+ ## Quick Start
56
+
57
+ ```python
58
+ from jetpack_sdk import JetPackClient
59
+
60
+ with JetPackClient() as client:
61
+ while True:
62
+ frame = client.read_frame()
63
+ if frame is None:
64
+ break # Daemon closed IPC channel
65
+
66
+ if frame.opcode == "worker.ping":
67
+ client.send_frame(
68
+ opcode="worker.pong",
69
+ payload=frame.payload or b"pong",
70
+ channel_id=frame.channel_id,
71
+ correlation_id=frame.correlation_id,
72
+ )
73
+ ```
74
+
75
+ ## Typed Opcode Contracts (`@opcode`)
76
+
77
+ Decorate handlers with `@opcode` and generate strict TypeScript `JetPackOpcodeMap` definitions via `jetpack codegen`:
78
+
79
+ ```python
80
+ from pydantic import BaseModel
81
+ from jetpack_sdk import JetPackClient, opcode
82
+
83
+ class ResizeMeta(BaseModel):
84
+ width: int
85
+ height: int
86
+
87
+ @opcode("image.resize", request=ResizeMeta, response=dict, binary=True)
88
+ def handle_resize(client: JetPackClient, frame) -> None:
89
+ mv = memoryview(frame.payload)
90
+ # Process binary bytes zero-copy...
91
+ client.send_frame(
92
+ opcode="image.resize.ok",
93
+ payload=bytes(mv),
94
+ channel_id=frame.channel_id,
95
+ correlation_id=frame.correlation_id,
96
+ )
97
+ ```
98
+
99
+ ## Documentation
100
+
101
+ - [Python Worker SDK & GPU Wheels](https://jetpack-desktop.github.io/sdk/worker/python-sdk)
102
+ - [Volumes & Userspace Network Proxy](https://jetpack-desktop.github.io/sdk/worker/volumes-and-network)
103
+ - [Manifest Reference (`app.toml`)](https://jetpack-desktop.github.io/publishing/manifest-reference)
@@ -0,0 +1,9 @@
1
+ jetpack_sdk/__init__.py,sha256=FXTMV72-eObsjXn2zcZP5hARvY8av-AHJSjLAcpiIzY,605
2
+ jetpack_sdk/client.py,sha256=ZD1MVvKqM4Yj92XJ29ZWZqJqh4I3RvgCQy2uYLrPntU,19033
3
+ jetpack_sdk/decorators.py,sha256=7xIFUM0Eh1LWfnGT-44efBwgOICknw6nrMfEkVJBj4k,1365
4
+ jetpack_sdk/framing.py,sha256=ZT_Og_gGHImf2tp3AdknAUdzCWlqTPDhMxEMkgk-P2w,9539
5
+ jetpack_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ jetpack_sdk-0.1.1.dist-info/METADATA,sha256=XnIG_meRkLV5bcRUhEe45zm1Vq2UN2dKK_lWwGoiG9Q,3661
7
+ jetpack_sdk-0.1.1.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
8
+ jetpack_sdk-0.1.1.dist-info/licenses/LICENSE,sha256=KOwaiHnPx5_DiGZcOebTxENqy7ixqRv3lbeD9BbZVko,1314
9
+ jetpack_sdk-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.26.3
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,30 @@
1
+ JetPack (`jetpack-sdk`) is dual-licensed under either:
2
+
3
+ - Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4
+ - MIT License (http://opensource.org/licenses/MIT)
5
+
6
+ at your option.
7
+
8
+ ---
9
+
10
+ MIT License
11
+
12
+ Copyright (c) 2026 JetPack Contributors
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above content does NOT show the above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.