mindwire 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mindwire/__init__.py ADDED
@@ -0,0 +1,29 @@
1
+ """Synchronous and asynchronous clients for the MindWire runtime."""
2
+
3
+ from ._client import AsyncMindwire, Mindwire
4
+ from ._errors import (
5
+ APIError,
6
+ ConnectionError,
7
+ MindwireError,
8
+ RunFailedError,
9
+ TimeoutError,
10
+ )
11
+ from ._runs import AsyncRun, Run
12
+ from ._types import Event, RunRecord, WaitResult
13
+ from ._version import __version__
14
+
15
+ __all__ = [
16
+ "APIError",
17
+ "AsyncMindwire",
18
+ "AsyncRun",
19
+ "ConnectionError",
20
+ "Event",
21
+ "Mindwire",
22
+ "MindwireError",
23
+ "Run",
24
+ "RunFailedError",
25
+ "RunRecord",
26
+ "TimeoutError",
27
+ "WaitResult",
28
+ "__version__",
29
+ ]
mindwire/_client.py ADDED
@@ -0,0 +1,277 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import AsyncIterator, Iterator, Mapping
4
+ from typing import Any
5
+
6
+ import httpx
7
+
8
+ from ._errors import MindwireError
9
+ from ._runs import AsyncRun, Run
10
+ from ._transport import (
11
+ Connection,
12
+ async_events,
13
+ decode_response,
14
+ events,
15
+ network_errors,
16
+ run_record,
17
+ segment,
18
+ stream_timeout,
19
+ )
20
+ from ._types import Event
21
+
22
+ Query = Mapping[str, str | int | float | bool | None]
23
+
24
+
25
+ def turn_body(
26
+ chat_id: str,
27
+ message: str,
28
+ cwd: str | None,
29
+ options: Mapping[str, Any] | None,
30
+ request_id: str | None,
31
+ mode: str,
32
+ resolve: Mapping[str, Any] | None,
33
+ ) -> dict[str, Any]:
34
+ body: dict[str, Any] = {"chatId": chat_id, "message": message, "mode": mode}
35
+ for key, value in (
36
+ ("cwd", cwd),
37
+ ("options", options),
38
+ ("requestId", request_id),
39
+ ("resolve", resolve),
40
+ ):
41
+ if value is not None:
42
+ body[key] = value
43
+ return body
44
+
45
+
46
+ class Mindwire:
47
+ """A synchronous connection to an existing local or remote MindWire runtime."""
48
+
49
+ def __init__(
50
+ self,
51
+ *,
52
+ base_url: str,
53
+ token: str | None = None,
54
+ agent: str | None = None,
55
+ timeout: float | None = 120.0,
56
+ headers: Mapping[str, str] | None = None,
57
+ transport: httpx.BaseTransport | None = None,
58
+ ) -> None:
59
+ self._connection = Connection(base_url, token, agent, headers)
60
+ self._http = httpx.Client(
61
+ headers=self._connection.headers,
62
+ timeout=timeout,
63
+ transport=transport,
64
+ follow_redirects=False,
65
+ )
66
+
67
+ def __enter__(self) -> Mindwire:
68
+ return self
69
+
70
+ def __exit__(self, *args: Any) -> None:
71
+ self.close()
72
+
73
+ def close(self) -> None:
74
+ """Close HTTP connections; admitted work continues on the runtime."""
75
+ self._http.close()
76
+
77
+ def request(
78
+ self, method: str, path: str, *, json: Any = None, params: Query | None = None
79
+ ) -> Any:
80
+ """Call any shared API endpoint using its native JSON fields."""
81
+ with network_errors():
82
+ response = self._http.request(
83
+ method, self._connection.url(path), json=json, params=params
84
+ )
85
+ return decode_response(response)
86
+
87
+ def stream(
88
+ self,
89
+ path: str,
90
+ *,
91
+ params: Query | None = None,
92
+ include_open_sentinel: bool = False,
93
+ ) -> Iterator[Event]:
94
+ with network_errors():
95
+ timeout = stream_timeout(self._http.timeout)
96
+ with self._http.stream(
97
+ "GET",
98
+ self._connection.url(path),
99
+ params=params,
100
+ headers={"Accept": "text/event-stream"},
101
+ timeout=timeout,
102
+ ) as response:
103
+ if not response.is_success:
104
+ response.read()
105
+ decode_response(response)
106
+ if "text/event-stream" not in response.headers.get("content-type", ""):
107
+ raise MindwireError(
108
+ "The runtime did not return an SSE event stream"
109
+ )
110
+ response.encoding = "utf-8"
111
+ yield from events(response.iter_lines(), include_open_sentinel)
112
+
113
+ def health(self) -> dict[str, Any]:
114
+ value: dict[str, Any] = self.request("GET", "/healthz")
115
+ return value
116
+
117
+ def catalog(self) -> dict[str, Any]:
118
+ value: dict[str, Any] = self.request("GET", "/catalog")
119
+ return value
120
+
121
+ def turn(
122
+ self,
123
+ *,
124
+ chat_id: str,
125
+ message: str,
126
+ agent: str | None = None,
127
+ cwd: str | None = None,
128
+ options: Mapping[str, Any] | None = None,
129
+ request_id: str | None = None,
130
+ mode: str = "turn",
131
+ resolve: Mapping[str, Any] | None = None,
132
+ ) -> Run:
133
+ """Start work. Reuse request_id when retrying an unacknowledged request."""
134
+ data = self.request(
135
+ "POST",
136
+ "/turns",
137
+ params=self._connection.agent_params(agent),
138
+ json=turn_body(chat_id, message, cwd, options, request_id, mode, resolve),
139
+ )
140
+ return Run(self, run_record(data))
141
+
142
+ def run(self, run_id: str) -> Run:
143
+ return Run(self, run_record(self.request("GET", "/runs/" + segment(run_id))))
144
+
145
+ def latest_run(self, chat_id: str) -> Run | None:
146
+ data = self.request("GET", f"/chats/{segment(chat_id)}/run")
147
+ return Run(self, run_record(data)) if data is not None else None
148
+
149
+ def preview_handoff(self, chat_id: str) -> dict[str, Any]:
150
+ value: dict[str, Any] = self.request(
151
+ "GET", f"/chats/{segment(chat_id)}/handoff"
152
+ )
153
+ return value
154
+
155
+ def handoff(self, chat_id: str, input: Mapping[str, Any]) -> dict[str, Any]:
156
+ """Submit a handoff payload with stable request and destination IDs."""
157
+ value: dict[str, Any] = self.request(
158
+ "POST", f"/chats/{segment(chat_id)}/handoff", json=dict(input)
159
+ )
160
+ return value
161
+
162
+
163
+ class AsyncMindwire:
164
+ """An asynchronous connection for Python applications and background services."""
165
+
166
+ def __init__(
167
+ self,
168
+ *,
169
+ base_url: str,
170
+ token: str | None = None,
171
+ agent: str | None = None,
172
+ timeout: float | None = 120.0,
173
+ headers: Mapping[str, str] | None = None,
174
+ transport: httpx.AsyncBaseTransport | None = None,
175
+ ) -> None:
176
+ self._connection = Connection(base_url, token, agent, headers)
177
+ self._http = httpx.AsyncClient(
178
+ headers=self._connection.headers,
179
+ timeout=timeout,
180
+ transport=transport,
181
+ follow_redirects=False,
182
+ )
183
+
184
+ async def __aenter__(self) -> AsyncMindwire:
185
+ return self
186
+
187
+ async def __aexit__(self, *args: Any) -> None:
188
+ await self.close()
189
+
190
+ async def close(self) -> None:
191
+ await self._http.aclose()
192
+
193
+ async def request(
194
+ self, method: str, path: str, *, json: Any = None, params: Query | None = None
195
+ ) -> Any:
196
+ with network_errors():
197
+ response = await self._http.request(
198
+ method, self._connection.url(path), json=json, params=params
199
+ )
200
+ return decode_response(response)
201
+
202
+ async def stream(
203
+ self,
204
+ path: str,
205
+ *,
206
+ params: Query | None = None,
207
+ include_open_sentinel: bool = False,
208
+ ) -> AsyncIterator[Event]:
209
+ with network_errors():
210
+ timeout = stream_timeout(self._http.timeout)
211
+ async with self._http.stream(
212
+ "GET",
213
+ self._connection.url(path),
214
+ params=params,
215
+ headers={"Accept": "text/event-stream"},
216
+ timeout=timeout,
217
+ ) as response:
218
+ if not response.is_success:
219
+ await response.aread()
220
+ decode_response(response)
221
+ if "text/event-stream" not in response.headers.get("content-type", ""):
222
+ raise MindwireError(
223
+ "The runtime did not return an SSE event stream"
224
+ )
225
+ response.encoding = "utf-8"
226
+ async for event in async_events(
227
+ response.aiter_lines(), include_open_sentinel
228
+ ):
229
+ yield event
230
+
231
+ async def health(self) -> dict[str, Any]:
232
+ value: dict[str, Any] = await self.request("GET", "/healthz")
233
+ return value
234
+
235
+ async def catalog(self) -> dict[str, Any]:
236
+ value: dict[str, Any] = await self.request("GET", "/catalog")
237
+ return value
238
+
239
+ async def turn(
240
+ self,
241
+ *,
242
+ chat_id: str,
243
+ message: str,
244
+ agent: str | None = None,
245
+ cwd: str | None = None,
246
+ options: Mapping[str, Any] | None = None,
247
+ request_id: str | None = None,
248
+ mode: str = "turn",
249
+ resolve: Mapping[str, Any] | None = None,
250
+ ) -> AsyncRun:
251
+ data = await self.request(
252
+ "POST",
253
+ "/turns",
254
+ params=self._connection.agent_params(agent),
255
+ json=turn_body(chat_id, message, cwd, options, request_id, mode, resolve),
256
+ )
257
+ return AsyncRun(self, run_record(data))
258
+
259
+ async def run(self, run_id: str) -> AsyncRun:
260
+ data = await self.request("GET", "/runs/" + segment(run_id))
261
+ return AsyncRun(self, run_record(data))
262
+
263
+ async def latest_run(self, chat_id: str) -> AsyncRun | None:
264
+ data = await self.request("GET", f"/chats/{segment(chat_id)}/run")
265
+ return AsyncRun(self, run_record(data)) if data is not None else None
266
+
267
+ async def preview_handoff(self, chat_id: str) -> dict[str, Any]:
268
+ value: dict[str, Any] = await self.request(
269
+ "GET", f"/chats/{segment(chat_id)}/handoff"
270
+ )
271
+ return value
272
+
273
+ async def handoff(self, chat_id: str, input: Mapping[str, Any]) -> dict[str, Any]:
274
+ value: dict[str, Any] = await self.request(
275
+ "POST", f"/chats/{segment(chat_id)}/handoff", json=dict(input)
276
+ )
277
+ return value
mindwire/_errors.py ADDED
@@ -0,0 +1,32 @@
1
+ from typing import Any
2
+
3
+
4
+ class MindwireError(Exception):
5
+ """Base error raised by the SDK."""
6
+
7
+
8
+ class APIError(MindwireError):
9
+ """A non-success HTTP response, with the daemon's error body preserved."""
10
+
11
+ def __init__(self, status: int, method: str, path: str, body: Any) -> None:
12
+ self.status = status
13
+ self.method = method
14
+ self.path = path
15
+ self.body = body
16
+ detail = body.get("error", "") if isinstance(body, dict) else str(body)
17
+ super().__init__(f"{method} {path} returned {status}: {detail}")
18
+
19
+
20
+ class ConnectionError(MindwireError):
21
+ """The runtime could not be reached or its connection was interrupted."""
22
+
23
+
24
+ class TimeoutError(MindwireError):
25
+ """An HTTP operation timed out. A run may still be executing on the runtime."""
26
+
27
+
28
+ class RunFailedError(MindwireError):
29
+ def __init__(self, run_id: str, status: str, detail: str = "") -> None:
30
+ self.run_id = run_id
31
+ self.status = status
32
+ super().__init__(f"run {run_id} {status}" + (f": {detail}" if detail else ""))
mindwire/_runs.py ADDED
@@ -0,0 +1,135 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import AsyncIterator, Iterator, Mapping
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ from ._errors import RunFailedError
7
+ from ._transport import run_record, segment
8
+ from ._types import Event, RunRecord, WaitResult
9
+
10
+ if TYPE_CHECKING:
11
+ from ._client import AsyncMindwire, Mindwire
12
+
13
+
14
+ def completion(record: RunRecord, result: dict[str, Any] | None) -> WaitResult:
15
+ if record["status"] != "done":
16
+ detail = record.get("error", "")
17
+ if record["status"] not in ("error", "cancelled"):
18
+ detail = "event stream ended before the run reached a terminal state"
19
+ raise RunFailedError(record["id"], record["status"], detail)
20
+ return {"run": record, "result": result}
21
+
22
+
23
+ class _RunBase:
24
+ def __init__(self, record: RunRecord) -> None:
25
+ self._record = run_record(record)
26
+ self._path = "/runs/" + segment(self._record["id"])
27
+
28
+ @property
29
+ def id(self) -> str:
30
+ return self._record["id"]
31
+
32
+ @property
33
+ def chat_id(self) -> str:
34
+ return self._record["chatId"]
35
+
36
+ @property
37
+ def status(self) -> str:
38
+ """The latest known status. Call refresh() to read it from the runtime."""
39
+ return self._record["status"]
40
+
41
+ @property
42
+ def value(self) -> RunRecord:
43
+ return self._record.copy()
44
+
45
+
46
+ class Run(_RunBase):
47
+ def __init__(self, client: Mindwire, record: RunRecord) -> None:
48
+ super().__init__(record)
49
+ self._client = client
50
+
51
+ def stream(
52
+ self, *, after: int | None = None, include_open_sentinel: bool = False
53
+ ) -> Iterator[Event]:
54
+ """Replay and follow events; close the iterator when stopping early."""
55
+ return self._client.stream(
56
+ self._path + "/stream",
57
+ params={"after": after} if after is not None else None,
58
+ include_open_sentinel=include_open_sentinel,
59
+ )
60
+
61
+ def __iter__(self) -> Iterator[Event]:
62
+ return self.stream()
63
+
64
+ def refresh(self) -> RunRecord:
65
+ self._record = run_record(self._client.request("GET", self._path))
66
+ return self.value
67
+
68
+ def snapshot(self) -> dict[str, Any]:
69
+ value: dict[str, Any] = self._client.request("GET", self._path + "/snapshot")
70
+ self._record = run_record(value["run"])
71
+ return value
72
+
73
+ def cancel(self) -> None:
74
+ """Stop the work on the runtime, rather than just disconnecting its stream."""
75
+ self._client.request("POST", self._path + "/cancel")
76
+
77
+ def respond(self, input: Mapping[str, Any]) -> None:
78
+ """Answer an interaction with the shared API's response payload."""
79
+ self._client.request("POST", self._path + "/respond", json=dict(input))
80
+
81
+ def wait(self, *, throw_on_error: bool = True) -> WaitResult:
82
+ result = None
83
+ for event in self.stream():
84
+ if event["type"] == "result":
85
+ result = event.get("result")
86
+ record = self.refresh()
87
+ if throw_on_error:
88
+ return completion(record, result)
89
+ return {"run": record, "result": result}
90
+
91
+
92
+ class AsyncRun(_RunBase):
93
+ def __init__(self, client: AsyncMindwire, record: RunRecord) -> None:
94
+ super().__init__(record)
95
+ self._client = client
96
+
97
+ def stream(
98
+ self, *, after: int | None = None, include_open_sentinel: bool = False
99
+ ) -> AsyncIterator[Event]:
100
+ """Replay and follow events. Use contextlib.aclosing when stopping early."""
101
+ return self._client.stream(
102
+ self._path + "/stream",
103
+ params={"after": after} if after is not None else None,
104
+ include_open_sentinel=include_open_sentinel,
105
+ )
106
+
107
+ def __aiter__(self) -> AsyncIterator[Event]:
108
+ return self.stream()
109
+
110
+ async def refresh(self) -> RunRecord:
111
+ self._record = run_record(await self._client.request("GET", self._path))
112
+ return self.value
113
+
114
+ async def snapshot(self) -> dict[str, Any]:
115
+ value: dict[str, Any] = await self._client.request(
116
+ "GET", self._path + "/snapshot"
117
+ )
118
+ self._record = run_record(value["run"])
119
+ return value
120
+
121
+ async def cancel(self) -> None:
122
+ await self._client.request("POST", self._path + "/cancel")
123
+
124
+ async def respond(self, input: Mapping[str, Any]) -> None:
125
+ await self._client.request("POST", self._path + "/respond", json=dict(input))
126
+
127
+ async def wait(self, *, throw_on_error: bool = True) -> WaitResult:
128
+ result = None
129
+ async for event in self.stream():
130
+ if event["type"] == "result":
131
+ result = event.get("result")
132
+ record = await self.refresh()
133
+ if throw_on_error:
134
+ return completion(record, result)
135
+ return {"run": record, "result": result}
mindwire/_transport.py ADDED
@@ -0,0 +1,166 @@
1
+ import json
2
+ from collections.abc import AsyncIterator, Iterator, Mapping
3
+ from contextlib import contextmanager
4
+ from typing import Any, cast
5
+ from urllib.parse import quote, urlsplit
6
+
7
+ import httpx
8
+
9
+ from ._errors import APIError, ConnectionError, MindwireError, TimeoutError
10
+ from ._types import Event, RunRecord
11
+ from ._version import __version__
12
+
13
+
14
+ def stream_timeout(timeout: httpx.Timeout) -> httpx.Timeout:
15
+ value = httpx.Timeout(timeout)
16
+ value.read = None
17
+ return value
18
+
19
+
20
+ def segment(value: str) -> str:
21
+ if not value or value in (".", ".."):
22
+ raise ValueError("An identifier must be nonempty and cannot be '.' or '..'")
23
+ return quote(value, safe="")
24
+
25
+
26
+ def run_record(value: Any) -> RunRecord:
27
+ if not isinstance(value, dict) or any(
28
+ not isinstance(value.get(key), str) for key in ("id", "chatId", "status")
29
+ ):
30
+ raise MindwireError("The runtime returned an invalid run record")
31
+ return cast(RunRecord, value)
32
+
33
+
34
+ def decode_response(response: httpx.Response) -> Any:
35
+ if not response.is_success:
36
+ try:
37
+ body = response.json()
38
+ except ValueError:
39
+ body = response.text
40
+ raise APIError(
41
+ response.status_code,
42
+ response.request.method,
43
+ response.request.url.path,
44
+ body,
45
+ )
46
+ if response.status_code == 204 or not response.content:
47
+ return None
48
+ try:
49
+ return response.json()
50
+ except ValueError as error:
51
+ raise MindwireError("The runtime returned a non-JSON response") from error
52
+
53
+
54
+ @contextmanager
55
+ def network_errors() -> Iterator[None]:
56
+ try:
57
+ yield
58
+ except httpx.TimeoutException as error:
59
+ raise TimeoutError("The MindWire runtime request timed out") from error
60
+ except httpx.HTTPError as error:
61
+ raise ConnectionError("The MindWire runtime connection failed") from error
62
+
63
+
64
+ class Connection:
65
+ def __init__(
66
+ self,
67
+ base_url: str,
68
+ token: str | None,
69
+ agent: str | None,
70
+ headers: Mapping[str, str] | None,
71
+ ) -> None:
72
+ parsed = urlsplit(base_url)
73
+ if (
74
+ parsed.scheme not in ("http", "https")
75
+ or not parsed.netloc
76
+ or parsed.username is not None
77
+ or parsed.password is not None
78
+ or parsed.query
79
+ or parsed.fragment
80
+ ):
81
+ raise ValueError(
82
+ "base_url must be an HTTP(S) URL without credentials or query"
83
+ )
84
+ self.base_url = base_url.rstrip("/")
85
+ self.agent = agent
86
+ self.headers = httpx.Headers(headers or {})
87
+ self.headers.setdefault("Accept", "application/json")
88
+ self.headers.setdefault("User-Agent", f"mindwire-python/{__version__}")
89
+ if token:
90
+ self.headers["Authorization"] = f"Bearer {token}"
91
+
92
+ def url(self, path: str) -> str:
93
+ # Only relative API paths are accepted; tokens cannot be sent to another origin.
94
+ parsed = urlsplit(path)
95
+ if (
96
+ not path.startswith("/")
97
+ or path.startswith("//")
98
+ or "\\" in path
99
+ or parsed.scheme
100
+ or parsed.netloc
101
+ or parsed.query
102
+ or parsed.fragment
103
+ ):
104
+ raise ValueError(
105
+ "Use an API path beginning with '/', and pass params separately"
106
+ )
107
+ return self.base_url + path
108
+
109
+ def agent_params(self, agent: str | None = None) -> dict[str, str]:
110
+ selected = self.agent if agent is None else agent
111
+ return {"agent": selected} if selected else {}
112
+
113
+
114
+ class SSEDecoder:
115
+ def __init__(self) -> None:
116
+ self.data: list[str] = []
117
+
118
+ def feed(self, line: str) -> Event | None:
119
+ if line == "":
120
+ return self.finish()
121
+ field, _, value = line.partition(":")
122
+ if field == "data":
123
+ self.data.append(value.removeprefix(" "))
124
+ return None
125
+
126
+ def finish(self) -> Event | None:
127
+ if not self.data:
128
+ return None
129
+ payload, self.data = "\n".join(self.data), []
130
+ try:
131
+ value = json.loads(payload)
132
+ except ValueError as error:
133
+ raise MindwireError("The runtime sent an invalid JSON event") from error
134
+ if not isinstance(value, dict) or not isinstance(value.get("type"), str):
135
+ raise MindwireError("The runtime sent an invalid event object")
136
+ return cast(Event, value)
137
+
138
+
139
+ def is_open_sentinel(event: Event) -> bool:
140
+ return (
141
+ event["type"] == "status" and (event.get("meta") or {}).get("stream") == "open"
142
+ )
143
+
144
+
145
+ def events(lines: Iterator[str], include_open_sentinel: bool) -> Iterator[Event]:
146
+ decoder = SSEDecoder()
147
+ for line in lines:
148
+ event = decoder.feed(line)
149
+ if event is not None and (include_open_sentinel or not is_open_sentinel(event)):
150
+ yield event
151
+ event = decoder.finish()
152
+ if event is not None and (include_open_sentinel or not is_open_sentinel(event)):
153
+ yield event
154
+
155
+
156
+ async def async_events(
157
+ lines: AsyncIterator[str], include_open_sentinel: bool
158
+ ) -> AsyncIterator[Event]:
159
+ decoder = SSEDecoder()
160
+ async for line in lines:
161
+ event = decoder.feed(line)
162
+ if event is not None and (include_open_sentinel or not is_open_sentinel(event)):
163
+ yield event
164
+ event = decoder.finish()
165
+ if event is not None and (include_open_sentinel or not is_open_sentinel(event)):
166
+ yield event
mindwire/_types.py ADDED
@@ -0,0 +1,39 @@
1
+ """Wire payloads retain the shared API's field names, including camelCase keys."""
2
+
3
+ from typing import Any, TypedDict
4
+
5
+
6
+ class Event(TypedDict, total=False):
7
+ type: str
8
+ sequence: int
9
+ replay: bool
10
+ itemId: str
11
+ sessionId: str
12
+ text: str
13
+ delta: bool
14
+ result: dict[str, Any]
15
+ tool: dict[str, Any]
16
+ interaction: dict[str, Any]
17
+ error: str
18
+ meta: dict[str, Any]
19
+ at: str
20
+
21
+
22
+ class _RunRequired(TypedDict):
23
+ id: str
24
+ chatId: str
25
+ status: str
26
+
27
+
28
+ class RunRecord(_RunRequired, total=False):
29
+ agent: str
30
+ error: str
31
+ kind: str
32
+ parentId: str
33
+ stopReason: str
34
+ iterations: int
35
+
36
+
37
+ class WaitResult(TypedDict):
38
+ run: RunRecord
39
+ result: dict[str, Any] | None
mindwire/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
mindwire/py.typed ADDED
File without changes
@@ -0,0 +1,188 @@
1
+ Metadata-Version: 2.4
2
+ Name: mindwire
3
+ Version: 0.1.0
4
+ Summary: Python SDK for building products with MindWire's shared coding-agent runtime.
5
+ Project-URL: Homepage, https://mindwire.sh
6
+ Project-URL: Documentation, https://github.com/oblien/mindwire/tree/main/packages/python
7
+ Project-URL: Repository, https://github.com/oblien/mindwire
8
+ Project-URL: Issues, https://github.com/oblien/mindwire/issues
9
+ Author: Oblien
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agents,claude-code,codex,mindwire,sdk
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: httpx<1,>=0.28.1
25
+ Provides-Extra: dev
26
+ Requires-Dist: build<2,>=1.2; extra == 'dev'
27
+ Requires-Dist: mypy<2,>=1.18; extra == 'dev'
28
+ Requires-Dist: pytest<10,>=8; extra == 'dev'
29
+ Requires-Dist: ruff<1,>=0.14; extra == 'dev'
30
+ Requires-Dist: twine<8,>=7; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # MindWire for Python
34
+
35
+ Build products with the same agent runtime used by MindWire's TypeScript and Go
36
+ SDKs. This initial Python SDK connects to an **existing local or remote runtime**
37
+ over HTTP and server-sent events. It includes synchronous and asynchronous clients,
38
+ turns, streaming, run snapshots, cancellation, interaction responses and conversation
39
+ handoffs. The low-level `request()` method exposes the rest of the shared API.
40
+
41
+ Requires Python 3.10 or newer. Licensed under Apache-2.0.
42
+
43
+ ## Install
44
+
45
+ Once the first release is published:
46
+
47
+ ```sh
48
+ pip install mindwire
49
+ ```
50
+
51
+ For development from this repository:
52
+
53
+ ```sh
54
+ python -m pip install -e './packages/python[dev]'
55
+ ```
56
+
57
+ ## Connect and run
58
+
59
+ Start or connect to a [MindWire runtime](https://mindwire.sh/docs/guides/quickstart)
60
+ and authenticate its agent. Set `MINDWIRE_BASE_URL` and `MINDWIRE_TOKEN` in your
61
+ application environment. A local runtime usually listens on `http://127.0.0.1:8790`;
62
+ use its configured bearer token. Use HTTPS for connections across the network.
63
+
64
+ ```python
65
+ import os
66
+ from mindwire import Mindwire
67
+
68
+ with Mindwire(
69
+ base_url=os.environ["MINDWIRE_BASE_URL"],
70
+ token=os.environ["MINDWIRE_TOKEN"],
71
+ agent="codex",
72
+ ) as mw:
73
+ run = mw.turn(
74
+ chat_id="launch",
75
+ message="Read brief.md and write a launch plan.",
76
+ cwd="/workspace/product", # A directory on the runtime's computer.
77
+ )
78
+ for event in run:
79
+ if event["type"] == "text":
80
+ print(event.get("text", ""), end="", flush=True)
81
+ outcome = run.wait()
82
+ print(outcome["run"]["status"])
83
+ ```
84
+
85
+ `run.wait()` consumes the stream and checks the final run record. Calling it after
86
+ iteration replays the stream internally to collect its result. It raises
87
+ `RunFailedError` for errors, cancellation, or a stream ending before a terminal
88
+ status. Pass `throw_on_error=False` to inspect that outcome yourself.
89
+
90
+ The Python SDK does not install, launch or provision the runtime in this release.
91
+ Local, Docker, SSH and cloud environments work when you provide a reachable
92
+ runtime URL and token. Harness authentication and capability support are owned by
93
+ the runtime; the SDK does not sign in to an agent on your behalf.
94
+
95
+ ## Async applications
96
+
97
+ ```python
98
+ import asyncio
99
+ import os
100
+ from mindwire import AsyncMindwire
101
+
102
+ async def main():
103
+ async with AsyncMindwire(
104
+ base_url=os.environ["MINDWIRE_BASE_URL"],
105
+ token=os.environ["MINDWIRE_TOKEN"],
106
+ agent="claude-code",
107
+ ) as mw:
108
+ run = await mw.turn(chat_id="research", message="Summarize this project.")
109
+ async for event in run:
110
+ if event["type"] == "text":
111
+ print(event.get("text", ""), end="", flush=True)
112
+ await run.wait()
113
+
114
+ asyncio.run(main())
115
+ ```
116
+
117
+ ## Runs and streams
118
+
119
+ - `mw.turn(...)` starts a turn. Supply `request_id` and retain it when retrying an
120
+ unacknowledged creation request on runtimes supporting `turnRequestVersion`.
121
+ - `mw.run(run_id)` and `mw.latest_run(chat_id)` reattach to existing work.
122
+ - `run.snapshot()` reads current output and its cursor;
123
+ `run.stream(after=snapshot["sequence"])` follows newer events on runtimes that
124
+ advertise cursor support.
125
+ - `run.cancel()` stops execution. Closing a client or event stream only closes
126
+ observation; the runtime continues admitted work while it remains running.
127
+ - `run.respond({...})` answers a supported interaction using the shared API payload.
128
+ - `mw.turn(..., mode="resolve", resolve={"maxIterations": 5})` runs bounded
129
+ continuation when the selected harness supports it.
130
+
131
+ To stop reading early, explicitly close the stream using `contextlib.closing`
132
+ (sync) or `contextlib.aclosing` (async). For example:
133
+
134
+ ```python
135
+ from contextlib import closing
136
+
137
+ with closing(run.stream()) as stream:
138
+ for event in stream:
139
+ if event["type"] == "interaction":
140
+ break
141
+ ```
142
+
143
+ Unary requests have a configurable timeout (`timeout=120.0`, in seconds). SSE
144
+ streams have no read timeout so an agent can continue working through idle periods.
145
+ The client does not automatically retry turns or reconnect interrupted streams.
146
+
147
+ ## Shared API and handoffs
148
+
149
+ `mw.request(method, path, json=..., params=...)` returns the parsed response body.
150
+ It accepts runtime API paths, not arbitrary URLs. All payloads, response objects,
151
+ turn `options` and event fields retain the shared API's **camelCase** field names.
152
+ Python method parameters use snake_case.
153
+
154
+ ```python
155
+ bots = mw.request("GET", "/bots")
156
+ config = mw.request("GET", "/config", params={"agent": "codex"})
157
+ preview = mw.preview_handoff("launch")
158
+ handoff = mw.handoff("launch", {
159
+ "newChatId": "launch-review",
160
+ "requestId": "launch-review-001",
161
+ "targetAgentId": "saved-claude-profile-id",
162
+ "task": "Review the plan and identify missing steps.",
163
+ })
164
+ review_run = mw.run(handoff["run"]["id"])
165
+ ```
166
+
167
+ Handoffs require a compatible runtime, an eligible source conversation and a saved
168
+ destination agent profile. Use `preview` to inspect the context before submission;
169
+ see the [handoff guide](https://mindwire.sh/docs/guides/handoffs) for field semantics.
170
+
171
+ `APIError` preserves `status`, `method`, `path` and the server's `body`.
172
+ `ConnectionError` and `TimeoutError` identify transport failures. All inherit
173
+ from `MindwireError`. Errors do not expose the configured bearer token.
174
+
175
+ ## Development and releases
176
+
177
+ ```sh
178
+ cd packages/python
179
+ python -m pytest
180
+ ruff check src tests
181
+ mypy src
182
+ python -m build
183
+ python -m twine check --strict dist/*
184
+ ```
185
+
186
+ The Python package has its own version, initially `0.1.0`. The runtime and
187
+ TypeScript package keep their existing release cycle. See [RELEASING.md](RELEASING.md)
188
+ for PyPI setup and publishing.
@@ -0,0 +1,12 @@
1
+ mindwire/__init__.py,sha256=LUqJ0b4sjwnLrAVmOK-zj-gDgKCIUUEYATirpdlAzfs,596
2
+ mindwire/_client.py,sha256=6yPZ8-2vcHNM0REQhwp3sxoGZC_6uMdRuv_6BO6LNTs,9101
3
+ mindwire/_errors.py,sha256=5753JSURYLox7fBdbBenKHT4d7Hq_3ssGw--pFiL4vg,1050
4
+ mindwire/_runs.py,sha256=eKbOQuLna7123BnmGpMfMuXwImus4sxV-k5SuuSH01M,4738
5
+ mindwire/_transport.py,sha256=PqOF6VW12B9coMd2F9dDE87QBGaFgR8ghQbbKhV83n4,5435
6
+ mindwire/_types.py,sha256=jt6UENRrCYGoEp5c2Gb57uGlnUjxB7JHA2cyy-nUPX8,716
7
+ mindwire/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
8
+ mindwire/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ mindwire-0.1.0.dist-info/METADATA,sha256=uH6jK7sIC3NXnZO7bn0nwsGaH3tCdByn-L6OzwrjpPY,6956
10
+ mindwire-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ mindwire-0.1.0.dist-info/licenses/LICENSE,sha256=APFxZEXfaKFVOR1npG2pCZ8xMijDhTFAM9_RKSBQvZ8,11350
12
+ mindwire-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 The mindwire authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.