taskmaster-api 0.1.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.4
2
+ Name: taskmaster-api
3
+ Version: 0.3.0
4
+ Summary: Client for the Taskmaster Computer agent
5
+ Author: Naren Sengodan
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/narensen/taskmaster-api
8
+ Project-URL: Repository, https://github.com/narensen/taskmaster-api
9
+ Keywords: taskmaster,api,client,daemon
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # taskmaster-api
19
+
20
+ Client for the [Taskmaster](https://github.com/narensen/Taskmaster) Computer agent running on your machine.
21
+
22
+ `tm serve .` listens on `http://127.0.0.1:8737`. Pair first. Computer stays off until `computer_enable(True)`.
23
+
24
+ ```python
25
+ from taskmaster_api import Taskmaster
26
+
27
+ tm = Taskmaster()
28
+ tm.set_token(tm.pair("ABCD", label="laptop", kind="agent"))
29
+ tm.computer_enable(True)
30
+
31
+ session = tm.computer_start("Open Chrome and search for the weather")
32
+ tm.computer_resume(session["id"], "Read the first forecast")
33
+ tm.computer_cancel(session["id"])
34
+ ```
35
+
36
+ `computer_act` sends one action on the 0–1000 screen grid. `computer_mode("virtual")` aims the agent at the isolated desktop.
37
+
38
+ ```python
39
+ acted = tm.computer_act("open_url", url="https://example.com", capture_after=True)
40
+ print(acted["result"])
41
+ ```
42
+
43
+ Connect a provider, save an MCP server, or start a deck. `builtin_mcp_url()` is the daemon's own `/mcp`, which already has Computer and the document tools.
44
+
45
+ ```python
46
+ tm.connect_provider("grok")
47
+ tm.connect_provider("openrouter", api_key="sk-...")
48
+ tm.connect_mcp("linear", "npx", args=["-y", "mcp-remote"], secret_env={"LINEAR_API_KEY": "..."})
49
+ session = tm.make_pptx("Q4 plan", "Three slides: goal, plan, ask")
50
+ print(tm.docs())
51
+ ```
52
+
53
+ The standard library is the only dependency. Coding-run methods (`start`, `approve`, `events`) remain. `call(method, path, body)` sends any other route.
54
+
55
+ The same client is published for Rust (`cargo add taskmaster-api`) and JavaScript (`npm install taskmaster-api`).
56
+
57
+ MIT © 2026 Naren Sengodan
@@ -0,0 +1,40 @@
1
+ # taskmaster-api
2
+
3
+ Client for the [Taskmaster](https://github.com/narensen/Taskmaster) Computer agent running on your machine.
4
+
5
+ `tm serve .` listens on `http://127.0.0.1:8737`. Pair first. Computer stays off until `computer_enable(True)`.
6
+
7
+ ```python
8
+ from taskmaster_api import Taskmaster
9
+
10
+ tm = Taskmaster()
11
+ tm.set_token(tm.pair("ABCD", label="laptop", kind="agent"))
12
+ tm.computer_enable(True)
13
+
14
+ session = tm.computer_start("Open Chrome and search for the weather")
15
+ tm.computer_resume(session["id"], "Read the first forecast")
16
+ tm.computer_cancel(session["id"])
17
+ ```
18
+
19
+ `computer_act` sends one action on the 0–1000 screen grid. `computer_mode("virtual")` aims the agent at the isolated desktop.
20
+
21
+ ```python
22
+ acted = tm.computer_act("open_url", url="https://example.com", capture_after=True)
23
+ print(acted["result"])
24
+ ```
25
+
26
+ Connect a provider, save an MCP server, or start a deck. `builtin_mcp_url()` is the daemon's own `/mcp`, which already has Computer and the document tools.
27
+
28
+ ```python
29
+ tm.connect_provider("grok")
30
+ tm.connect_provider("openrouter", api_key="sk-...")
31
+ tm.connect_mcp("linear", "npx", args=["-y", "mcp-remote"], secret_env={"LINEAR_API_KEY": "..."})
32
+ session = tm.make_pptx("Q4 plan", "Three slides: goal, plan, ask")
33
+ print(tm.docs())
34
+ ```
35
+
36
+ The standard library is the only dependency. Coding-run methods (`start`, `approve`, `events`) remain. `call(method, path, body)` sends any other route.
37
+
38
+ The same client is published for Rust (`cargo add taskmaster-api`) and JavaScript (`npm install taskmaster-api`).
39
+
40
+ MIT © 2026 Naren Sengodan
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "taskmaster-api"
7
- version = "0.1.0"
8
- description = "Client for the Taskmaster local daemon HTTP API"
7
+ version = "0.3.0"
8
+ description = "Client for the Taskmaster Computer agent"
9
9
  readme = "README.md"
10
10
  license = "MIT"
11
11
  requires-python = ">=3.9"
@@ -0,0 +1,428 @@
1
+ """HTTP client for one Taskmaster daemon.
2
+
3
+ ``tm serve .`` listens on ``http://127.0.0.1:8737``. Health and pair need no
4
+ token. Every other ``/api`` route needs ``Authorization: Bearer <token>``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import urllib.error
11
+ import urllib.request
12
+ from typing import Any, Mapping, Optional
13
+
14
+ DEFAULT_BASE_URL = "http://127.0.0.1:8737"
15
+ VERSION = "0.3.0"
16
+
17
+
18
+ class TaskmasterError(Exception):
19
+ """The daemon refused the request, or the response was not usable JSON.
20
+
21
+ ``status`` is ``0`` when no HTTP response arrived.
22
+ """
23
+
24
+ def __init__(self, status: int, message: str) -> None:
25
+ super().__init__(message)
26
+ self.status = status
27
+ self.message = message
28
+
29
+
30
+ class Taskmaster:
31
+ """Synchronous client. A token set here is sent on every request."""
32
+
33
+ def __init__(self, base_url: str = DEFAULT_BASE_URL, token: Optional[str] = None, timeout: float = 30) -> None:
34
+ self.base_url = base_url.rstrip("/")
35
+ self.token = token
36
+ self.timeout = timeout
37
+
38
+ def with_token(self, token: str) -> "Taskmaster":
39
+ """A new client with the same origin and a different token."""
40
+ return Taskmaster(self.base_url, token, self.timeout)
41
+
42
+ def set_token(self, token: str) -> None:
43
+ self.token = token
44
+
45
+ def clear_token(self) -> None:
46
+ self.token = None
47
+
48
+ def health(self) -> dict[str, Any]:
49
+ """``GET /api/health``."""
50
+ return self._object(self.call("GET", "/api/health"))
51
+
52
+ def pair(self, code: str, label: Optional[str] = None, kind: Optional[str] = None) -> str:
53
+ """``POST /api/pair``. Returns the device token and does not store it.
54
+
55
+ ``kind`` is ``browser``, ``phone``, ``desktop``, ``machine``, or ``agent``.
56
+ """
57
+ body: dict[str, str] = {"code": code}
58
+ if label:
59
+ body["label"] = label
60
+ if kind:
61
+ body["kind"] = kind
62
+ parsed = self._object(self.call("POST", "/api/pair", body))
63
+ token = parsed.get("token")
64
+ if not isinstance(token, str) or not token:
65
+ raise TaskmasterError(0, "pair response had no token")
66
+ return token
67
+
68
+ def computer_status(self) -> dict[str, Any]:
69
+ """``GET /api/computer/status``."""
70
+ return self._object(self.call("GET", "/api/computer/status"))
71
+
72
+ def computer_enable(self, enabled: bool) -> dict[str, Any]:
73
+ """``POST /api/computer/toggle``. Turns Local computer use on or off."""
74
+ return self._object(self.call("POST", "/api/computer/toggle", {"enabled": enabled}))
75
+
76
+ def computer_mode(self, mode: str) -> dict[str, Any]:
77
+ """``POST /api/computer/mode``. ``mode`` is ``host`` or ``virtual``."""
78
+ return self._object(self.call("POST", "/api/computer/mode", {"mode": mode}))
79
+
80
+ def computer_sessions(self) -> list[Any]:
81
+ """``GET /api/computer/sessions``."""
82
+ listed = self._object(self.call("GET", "/api/computer/sessions"))
83
+ sessions = listed.get("sessions")
84
+ if not isinstance(sessions, list):
85
+ raise TaskmasterError(0, "sessions response had no list")
86
+ return sessions
87
+
88
+ def computer_start(
89
+ self,
90
+ task: str,
91
+ *,
92
+ bot_id: Optional[str] = None,
93
+ harness: Optional[str] = None,
94
+ model: Optional[str] = None,
95
+ parent_session_id: Optional[str] = None,
96
+ attachments: Optional[list[str]] = None,
97
+ ) -> dict[str, Any]:
98
+ """``POST /api/computer/sessions``. Starts the Computer agent on ``task``."""
99
+ body: dict[str, Any] = {"task": task}
100
+ if bot_id is not None:
101
+ body["bot_id"] = bot_id
102
+ if harness is not None:
103
+ body["harness"] = harness
104
+ if model is not None:
105
+ body["model"] = model
106
+ if parent_session_id is not None:
107
+ body["parent_session_id"] = parent_session_id
108
+ if attachments:
109
+ body["attachments"] = attachments
110
+ return self._object(self.call("POST", "/api/computer/sessions", body))
111
+
112
+ def computer_session(self, session_id: str) -> dict[str, Any]:
113
+ """``GET /api/computer/sessions/{id}``."""
114
+ return self._object(self.call("GET", f"/api/computer/sessions/{_segment(session_id)}"))
115
+
116
+ def computer_resume(self, session_id: str, note: Optional[str] = None) -> dict[str, Any]:
117
+ """``POST /api/computer/sessions/{id}/resume``. ``note`` is the next instruction."""
118
+ body: dict[str, Any] = {"note": note} if note else {}
119
+ return self._object(self.call("POST", f"/api/computer/sessions/{_segment(session_id)}/resume", body))
120
+
121
+ def computer_cancel(self, session_id: str) -> Any:
122
+ """``POST /api/computer/sessions/{id}/cancel``. Stops the agent."""
123
+ return self.call("POST", f"/api/computer/sessions/{_segment(session_id)}/cancel", {})
124
+
125
+ def computer_screen(self) -> dict[str, Any]:
126
+ """``POST /api/computer/screen``. ``data`` is base64 PNG bytes."""
127
+ return self._object(self.call("POST", "/api/computer/screen", {}))
128
+
129
+ def computer_act(self, action: str, **args: Any) -> dict[str, Any]:
130
+ """``POST /api/computer/act``.
131
+
132
+ ``action`` is ``click``, ``click_text``, ``type``, ``press``, ``open_url``,
133
+ ``open_app``, and the other names the daemon accepts. Coordinates are a
134
+ 0–1000 grid.
135
+ """
136
+ return self._object(self.call("POST", "/api/computer/act", {"action": action, **args}))
137
+
138
+ def computer_routines(self) -> Any:
139
+ """``GET /api/computer/routines``."""
140
+ return self.call("GET", "/api/computer/routines")
141
+
142
+ def computer_run_routine(self, routine_id: str) -> Any:
143
+ """``POST /api/computer/routines/{id}/run``."""
144
+ return self.call("POST", f"/api/computer/routines/{_segment(routine_id)}/run", {})
145
+
146
+ def builtin_mcp_url(self) -> str:
147
+ """URL of the daemon's own MCP endpoint.
148
+
149
+ Agents already get this server. It carries the dictionary, Computer,
150
+ and the document tools. ``connect_mcp`` adds another server.
151
+ """
152
+ return f"{self.base_url}/mcp"
153
+
154
+ def mcp_servers(self) -> list[Any]:
155
+ """``GET /api/mcp``. User MCP servers saved for this project."""
156
+ listed = self._object(self.call("GET", "/api/mcp"))
157
+ servers = listed.get("servers")
158
+ if not isinstance(servers, list):
159
+ raise TaskmasterError(0, "mcp response had no list")
160
+ return servers
161
+
162
+ def connect_mcp(
163
+ self,
164
+ name: str,
165
+ command: str,
166
+ *,
167
+ args: Optional[list[str]] = None,
168
+ env: Optional[Mapping[str, str]] = None,
169
+ secret_env: Optional[Mapping[str, str]] = None,
170
+ roles: Optional[list[str]] = None,
171
+ enabled: Optional[bool] = None,
172
+ require_approval: Optional[bool] = None,
173
+ ) -> dict[str, Any]:
174
+ """``POST /api/mcp``. Adds or replaces a user MCP server.
175
+
176
+ ``secret_env`` values go to the OS keychain. The daemon does not echo them.
177
+ """
178
+ body: dict[str, Any] = {"name": name, "command": command}
179
+ if args:
180
+ body["args"] = args
181
+ if env:
182
+ body["env"] = dict(env)
183
+ if secret_env:
184
+ body["secret_env"] = dict(secret_env)
185
+ if roles:
186
+ body["roles"] = roles
187
+ if enabled is not None:
188
+ body["enabled"] = enabled
189
+ if require_approval is not None:
190
+ body["require_approval"] = require_approval
191
+ saved = self._object(self.call("POST", "/api/mcp", body))
192
+ server = saved.get("server")
193
+ if not isinstance(server, dict):
194
+ raise TaskmasterError(0, "mcp response had no server")
195
+ return server
196
+
197
+ def disconnect_mcp(self, name: str) -> Any:
198
+ """``POST /api/mcp/{name}/remove``."""
199
+ return self.call("POST", f"/api/mcp/{_segment(name)}/remove", {})
200
+
201
+ def docs(self) -> list[Any]:
202
+ """``GET /api/computer/docs``."""
203
+ listed = self._object(self.call("GET", "/api/computer/docs"))
204
+ docs = listed.get("docs")
205
+ if not isinstance(docs, list):
206
+ raise TaskmasterError(0, "docs response had no list")
207
+ return docs
208
+
209
+ def doc(self, doc_id: str) -> dict[str, Any]:
210
+ """``GET /api/computer/docs/{id}``."""
211
+ return self._object(self.call("GET", f"/api/computer/docs/{_segment(doc_id)}"))
212
+
213
+ def upload_doc(self, name: str, data_base64: str) -> dict[str, Any]:
214
+ """``POST /api/computer/files``. ``data_base64`` is the file bytes."""
215
+ return self._object(self.call("POST", "/api/computer/files", {"name": name, "data_base64": data_base64}))
216
+
217
+ def open_doc(self, doc_id: str) -> Any:
218
+ """``POST /api/computer/docs/{id}/open``. Opens the file in the host's default app."""
219
+ return self.call("POST", f"/api/computer/docs/{_segment(doc_id)}/open", {})
220
+
221
+ def make_pptx(self, title: str, brief: Optional[str] = None) -> dict[str, Any]:
222
+ """Start a Computer session that builds a PowerPoint with ``doc_create_pptx``."""
223
+ return self.computer_start(_document_task("PowerPoint", "doc_create_pptx", title, brief))
224
+
225
+ def make_docx(self, title: str, brief: Optional[str] = None) -> dict[str, Any]:
226
+ """Start a Computer session that builds a Word document with ``doc_create_docx``."""
227
+ return self.computer_start(_document_task("Word document", "doc_create_docx", title, brief))
228
+
229
+ def setup(self) -> dict[str, Any]:
230
+ """``GET /api/setup``. Each provider's install and sign-in state, plus runtimes and jobs."""
231
+ return self._object(self.call("GET", "/api/setup"))
232
+
233
+ def connect_provider(self, provider_id: str, api_key: Optional[str] = None) -> Any:
234
+ """Connect a provider in one call.
235
+
236
+ An ``api_key`` is saved for a provider that uses one (``openrouter``).
237
+ Otherwise this installs the CLI when it is missing, or starts its sign-in
238
+ when it is already installed. A provider that is installed and signed in
239
+ returns ``{"ok": true, "connected": true}``.
240
+ """
241
+ segment = _segment(provider_id)
242
+ if api_key is not None:
243
+ return self.call("POST", f"/api/setup/providers/{segment}/key", {"api_key": api_key})
244
+ setup = self.setup()
245
+ providers = setup.get("providers")
246
+ match = None
247
+ if isinstance(providers, list):
248
+ for item in providers:
249
+ if isinstance(item, dict) and item.get("id") == provider_id:
250
+ match = item
251
+ break
252
+ installed = bool(match and match.get("installed") is True)
253
+ signed_in = bool(match and match.get("signed_in") is True)
254
+ if installed and signed_in:
255
+ return {"ok": True, "connected": True, "id": provider_id}
256
+ action = "login" if installed else "install"
257
+ return self.call("POST", f"/api/setup/providers/{segment}/{action}", {})
258
+
259
+ def runs(self) -> dict[str, Any]:
260
+ """``GET /api/runs``. The body is ``{"runs": [...], "seq": n}``."""
261
+ return self._object(self.call("GET", "/api/runs"))
262
+
263
+ def runs_since(self, since: int) -> dict[str, Any]:
264
+ """``GET /api/runs?since=``. ``since`` is a previous ``seq``."""
265
+ return self._object(self.call("GET", f"/api/runs?since={since}"))
266
+
267
+ def run(self, run_id: str) -> dict[str, Any]:
268
+ """``GET /api/runs/{id}``."""
269
+ return self._object(self.call("GET", f"/api/runs/{_segment(run_id)}"))
270
+
271
+ def start(
272
+ self,
273
+ prompt: Optional[str] = None,
274
+ plan: Optional[Any] = None,
275
+ *,
276
+ yes: bool = False,
277
+ run_id: Optional[str] = None,
278
+ roles: Optional[Mapping[str, str]] = None,
279
+ models: Optional[Mapping[str, Optional[str]]] = None,
280
+ parallel: Optional[int] = None,
281
+ timeout_secs: Optional[int] = None,
282
+ template: Optional[str] = None,
283
+ max_cost_usd: Optional[float] = None,
284
+ mode: Optional[str] = None,
285
+ permission_mode: Optional[str] = None,
286
+ goal: Optional[str] = None,
287
+ goal_max_turns: Optional[int] = None,
288
+ computer_use: Optional[bool] = None,
289
+ ) -> dict[str, Any]:
290
+ """``POST /api/runs``. Send a prompt or a plan, and not both.
291
+
292
+ The daemon answers ``202`` once the run is started. ``yes`` builds
293
+ without waiting for approval.
294
+ """
295
+ body: dict[str, Any] = {}
296
+ if run_id is not None:
297
+ body["id"] = run_id
298
+ if prompt is not None:
299
+ body["prompt"] = prompt
300
+ if plan is not None:
301
+ body["plan"] = plan
302
+ if yes:
303
+ body["yes"] = True
304
+ if roles:
305
+ body["roles"] = dict(roles)
306
+ if models:
307
+ body["models"] = dict(models)
308
+ if parallel is not None:
309
+ body["parallel"] = parallel
310
+ if timeout_secs is not None:
311
+ body["timeout_secs"] = timeout_secs
312
+ if template is not None:
313
+ body["template"] = template
314
+ if max_cost_usd is not None:
315
+ body["max_cost_usd"] = max_cost_usd
316
+ if mode is not None:
317
+ body["mode"] = mode
318
+ if permission_mode is not None:
319
+ body["permission_mode"] = permission_mode
320
+ if goal is not None:
321
+ body["goal"] = goal
322
+ if goal_max_turns is not None:
323
+ body["goal_max_turns"] = goal_max_turns
324
+ if computer_use is not None:
325
+ body["computer_use"] = computer_use
326
+ return self._object(self.call("POST", "/api/runs", body))
327
+
328
+ def approve(self, run_id: str, note: Optional[str] = None) -> dict[str, Any]:
329
+ """``POST /api/runs/{id}/approve``. ``note`` is read by the master first."""
330
+ body: dict[str, Any] = {"note": note} if note else {}
331
+ return self._object(self.call("POST", f"/api/runs/{_segment(run_id)}/approve", body))
332
+
333
+ def reject(self, run_id: str, prompt: Optional[str] = None) -> dict[str, Any]:
334
+ """``POST /api/runs/{id}/reject``. A prompt makes the run plan again."""
335
+ body: dict[str, Any] = {"prompt": prompt} if prompt else {}
336
+ return self._object(self.call("POST", f"/api/runs/{_segment(run_id)}/reject", body))
337
+
338
+ def resume(self, run_id: str) -> dict[str, Any]:
339
+ """``POST /api/runs/{id}/resume``."""
340
+ return self._object(self.call("POST", f"/api/runs/{_segment(run_id)}/resume", {}))
341
+
342
+ def cancel(self, run_id: str) -> dict[str, Any]:
343
+ """``POST /api/runs/{id}/cancel``."""
344
+ return self._object(self.call("POST", f"/api/runs/{_segment(run_id)}/cancel", {}))
345
+
346
+ def undo(self, run_id: str) -> Any:
347
+ """``POST /api/runs/{id}/undo``."""
348
+ return self.call("POST", f"/api/runs/{_segment(run_id)}/undo", {})
349
+
350
+ def events(self, run_id: str, after: Optional[int] = None) -> dict[str, Any]:
351
+ """``GET /api/runs/{id}/events``. ``after`` is the previous ``next``."""
352
+ query = "" if after is None else f"?after={after}"
353
+ return self._object(self.call("GET", f"/api/runs/{_segment(run_id)}/events{query}"))
354
+
355
+ def projects(self) -> Any:
356
+ """``GET /api/projects``."""
357
+ return self.call("GET", "/api/projects")
358
+
359
+ def providers(self) -> Any:
360
+ """``GET /api/providers``."""
361
+ return self.call("GET", "/api/providers")
362
+
363
+ def doctor(self) -> Any:
364
+ """``GET /api/doctor``."""
365
+ return self.call("GET", "/api/doctor")
366
+
367
+ def call(self, method: str, path: str, body: Optional[Any] = None) -> Any:
368
+ """Send any daemon route.
369
+
370
+ ``path`` starts with ``/``. ``body`` is JSON for requests that have one.
371
+ An empty success body becomes ``None``.
372
+ """
373
+ if not path.startswith("/") or "://" in path or "\0" in path:
374
+ raise TaskmasterError(0, f"path must start with /: {path}")
375
+ data = None if body is None else json.dumps(body).encode("utf-8")
376
+ request = urllib.request.Request(self.base_url + path, data=data, method=method)
377
+ if body is not None:
378
+ request.add_header("Content-Type", "application/json")
379
+ if self.token:
380
+ request.add_header("Authorization", f"Bearer {self.token}")
381
+ try:
382
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
383
+ raw = response.read()
384
+ except urllib.error.HTTPError as exc:
385
+ raw = exc.read()
386
+ raise TaskmasterError(exc.code, _error_message(raw, exc.code)) from None
387
+ except urllib.error.URLError as exc:
388
+ raise TaskmasterError(0, str(exc.reason)) from None
389
+ if not raw or not raw.strip():
390
+ return None
391
+ try:
392
+ return json.loads(raw.decode("utf-8"))
393
+ except json.JSONDecodeError as exc:
394
+ raise TaskmasterError(0, "response was not JSON") from exc
395
+
396
+ @staticmethod
397
+ def _object(value: Any) -> dict[str, Any]:
398
+ if not isinstance(value, dict):
399
+ raise TaskmasterError(0, "response was not a JSON object")
400
+ return value
401
+
402
+
403
+ def _document_task(kind: str, tool: str, title: str, brief: Optional[str]) -> str:
404
+ task = f"Make a {kind} with {tool}. Title: {title}. Use one cohesive theme on every page."
405
+ if brief:
406
+ task = f"{task} {brief}"
407
+ return task
408
+
409
+
410
+ def _segment(run_id: str) -> str:
411
+ from urllib.parse import quote
412
+
413
+ return quote(run_id, safe="")
414
+
415
+
416
+ def _error_message(raw: bytes, status: int) -> str:
417
+ text = raw.decode("utf-8", errors="replace").strip()
418
+ if not text:
419
+ return f"HTTP {status}"
420
+ try:
421
+ parsed = json.loads(text)
422
+ except json.JSONDecodeError:
423
+ return text
424
+ if isinstance(parsed, dict):
425
+ message = parsed.get("error")
426
+ if isinstance(message, str) and message:
427
+ return message
428
+ return text
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.4
2
+ Name: taskmaster-api
3
+ Version: 0.3.0
4
+ Summary: Client for the Taskmaster Computer agent
5
+ Author: Naren Sengodan
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/narensen/taskmaster-api
8
+ Project-URL: Repository, https://github.com/narensen/taskmaster-api
9
+ Keywords: taskmaster,api,client,daemon
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # taskmaster-api
19
+
20
+ Client for the [Taskmaster](https://github.com/narensen/Taskmaster) Computer agent running on your machine.
21
+
22
+ `tm serve .` listens on `http://127.0.0.1:8737`. Pair first. Computer stays off until `computer_enable(True)`.
23
+
24
+ ```python
25
+ from taskmaster_api import Taskmaster
26
+
27
+ tm = Taskmaster()
28
+ tm.set_token(tm.pair("ABCD", label="laptop", kind="agent"))
29
+ tm.computer_enable(True)
30
+
31
+ session = tm.computer_start("Open Chrome and search for the weather")
32
+ tm.computer_resume(session["id"], "Read the first forecast")
33
+ tm.computer_cancel(session["id"])
34
+ ```
35
+
36
+ `computer_act` sends one action on the 0–1000 screen grid. `computer_mode("virtual")` aims the agent at the isolated desktop.
37
+
38
+ ```python
39
+ acted = tm.computer_act("open_url", url="https://example.com", capture_after=True)
40
+ print(acted["result"])
41
+ ```
42
+
43
+ Connect a provider, save an MCP server, or start a deck. `builtin_mcp_url()` is the daemon's own `/mcp`, which already has Computer and the document tools.
44
+
45
+ ```python
46
+ tm.connect_provider("grok")
47
+ tm.connect_provider("openrouter", api_key="sk-...")
48
+ tm.connect_mcp("linear", "npx", args=["-y", "mcp-remote"], secret_env={"LINEAR_API_KEY": "..."})
49
+ session = tm.make_pptx("Q4 plan", "Three slides: goal, plan, ask")
50
+ print(tm.docs())
51
+ ```
52
+
53
+ The standard library is the only dependency. Coding-run methods (`start`, `approve`, `events`) remain. `call(method, path, body)` sends any other route.
54
+
55
+ The same client is published for Rust (`cargo add taskmaster-api`) and JavaScript (`npm install taskmaster-api`).
56
+
57
+ MIT © 2026 Naren Sengodan
@@ -0,0 +1,223 @@
1
+ """The client against a tiny local daemon stand-in."""
2
+
3
+ import json
4
+ import threading
5
+ import unittest
6
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
7
+
8
+ from taskmaster_api import Taskmaster, TaskmasterError
9
+
10
+
11
+ class Handler(BaseHTTPRequestHandler):
12
+ def do_GET(self) -> None: # noqa: N802
13
+ self._handle("GET", b"")
14
+
15
+ def do_POST(self) -> None: # noqa: N802
16
+ length = int(self.headers.get("Content-Length", "0"))
17
+ self._handle("POST", self.rfile.read(length) if length else b"")
18
+
19
+ def log_message(self, fmt: str, *args: object) -> None:
20
+ return
21
+
22
+ def _handle(self, method: str, raw: bytes) -> None:
23
+ body = raw.decode("utf-8")
24
+ path = self.path
25
+ authed = self.headers.get("Authorization") == "Bearer tok-1"
26
+ if method == "GET" and path == "/api/health":
27
+ self._send(200, {"ok": True, "version": "2.1.0", "auth": {"methods": ["pairing"]}, "terminal": True})
28
+ return
29
+ if method == "POST" and path == "/api/pair":
30
+ if '"good"' in body:
31
+ self._send(200, {"token": "tok-1"})
32
+ else:
33
+ self._send(401, {"error": "that code was refused"})
34
+ return
35
+ if not authed and (
36
+ path.startswith("/api/runs")
37
+ or path == "/api/doctor"
38
+ or path.startswith("/api/computer")
39
+ or path.startswith("/api/mcp")
40
+ or path.startswith("/api/setup")
41
+ ):
42
+ self._send(401, {"error": "a token is required"})
43
+ return
44
+ if method == "GET" and path == "/api/runs":
45
+ self._send(200, {"runs": [{"id": "run-1", "phase": "awaiting_approval", "needs_you": True, "pages": []}], "seq": 3})
46
+ return
47
+ if method == "GET" and path == "/api/runs/run-1":
48
+ self._send(200, {"id": "run-1", "phase": "awaiting_approval", "prompt": "Add a button", "pages": []})
49
+ return
50
+ if method == "POST" and path == "/api/runs" and "Add a button" in body and '"yes": true' in body:
51
+ self._send(202, {"id": "run-1"})
52
+ return
53
+ if method == "POST" and path == "/api/runs/run-1/approve" and "ship it" in body:
54
+ self._send(202, {"id": "run-1"})
55
+ return
56
+ if method == "GET" and path == "/api/runs/run-1/events?after=1":
57
+ self._send(200, {"next": 2, "events": [{"kind": "done"}]})
58
+ return
59
+ if method == "GET" and path == "/api/doctor":
60
+ self._send(200, {"ok": True})
61
+ return
62
+ if method == "GET" and path == "/api/computer/status":
63
+ self._send(200, {"enabled": False, "mode": "host", "install_hint": "turn it on"})
64
+ return
65
+ if method == "POST" and path == "/api/computer/toggle" and '"enabled": true' in body:
66
+ self._send(200, {"enabled": True, "mode": "host"})
67
+ return
68
+ if method == "POST" and path == "/api/computer/sessions" and "weather" in body:
69
+ self._send(200, {"id": "cs-1", "task": "Open Chrome and search for the weather", "status": "running", "harness": "grok", "final_reply": ""})
70
+ return
71
+ if method == "POST" and path == "/api/computer/sessions" and "doc_create_pptx" in body:
72
+ self._send(200, {"id": "cs-doc", "task": "Make a PowerPoint with doc_create_pptx. Title: Q4 plan.", "status": "running", "final_reply": ""})
73
+ return
74
+ if method == "POST" and path == "/api/computer/sessions" and "doc_create_docx" in body:
75
+ self._send(200, {"id": "cs-docx", "task": "Make a Word document with doc_create_docx. Title: Notes.", "status": "running", "final_reply": ""})
76
+ return
77
+ if method == "GET" and path == "/api/computer/sessions":
78
+ self._send(200, {"sessions": [{"id": "cs-1", "task": "Open Chrome and search for the weather", "status": "running", "step_count": 1, "agent_count": 1}]})
79
+ return
80
+ if method == "GET" and path == "/api/computer/sessions/cs-1":
81
+ self._send(200, {"id": "cs-1", "task": "Open Chrome and search for the weather", "status": "done", "final_reply": "It is 72 F.", "latest_screen": None})
82
+ return
83
+ if method == "POST" and path == "/api/computer/sessions/cs-1/resume" and "forecast" in body:
84
+ self._send(200, {"id": "cs-1", "task": "Open Chrome and search for the weather", "status": "running", "final_reply": ""})
85
+ return
86
+ if method == "POST" and path == "/api/computer/sessions/cs-1/cancel":
87
+ self._send(200, {"ok": True})
88
+ return
89
+ if method == "POST" and path == "/api/computer/act" and "click_text" in body and "Search" in body:
90
+ self._send(200, {"ok": True, "result": "clicked Search"})
91
+ return
92
+ if method == "GET" and path == "/api/mcp":
93
+ self._send(200, {"servers": [{"name": "linear", "command": "npx", "enabled": True}]})
94
+ return
95
+ if method == "POST" and path == "/api/mcp" and "linear" in body and "npx" in body:
96
+ self._send(200, {"server": {"name": "linear", "command": "npx", "enabled": True}})
97
+ return
98
+ if method == "POST" and path == "/api/mcp/linear/remove":
99
+ self._send(200, {"removed": True})
100
+ return
101
+ if method == "GET" and path == "/api/computer/docs":
102
+ self._send(200, {"docs": [{"id": "doc-1", "filename": "Deck.pptx", "kind": "pptx", "title": "Deck"}]})
103
+ return
104
+ if method == "GET" and path == "/api/computer/docs/doc-1":
105
+ self._send(200, {"id": "doc-1", "filename": "Deck.pptx", "kind": "pptx", "title": "Deck"})
106
+ return
107
+ if method == "POST" and path == "/api/computer/files" and "Deck.pptx" in body:
108
+ self._send(200, {"id": "doc-1", "filename": "Deck.pptx", "kind": "pptx", "title": "Deck"})
109
+ return
110
+ if method == "POST" and path == "/api/computer/docs/doc-1/open":
111
+ self._send(200, {"ok": True, "path": "/tmp/Deck.pptx"})
112
+ return
113
+ if method == "GET" and path == "/api/setup":
114
+ self._send(200, {"providers": [{"id": "grok", "installed": True, "signed_in": False}]})
115
+ return
116
+ if method == "POST" and path == "/api/setup/providers/grok/login":
117
+ self._send(202, {"id": "job-1", "state": "running", "action": "login"})
118
+ return
119
+ if method == "POST" and path == "/api/setup/providers/openrouter/key" and "api_key" in body:
120
+ self._send(200, {"ok": True, "configured": True})
121
+ return
122
+ self._send(404, {"error": "no such route"})
123
+
124
+ def _send(self, status: int, payload: object) -> None:
125
+ raw = json.dumps(payload).encode("utf-8")
126
+ self.send_response(status)
127
+ self.send_header("Content-Type", "application/json")
128
+ self.send_header("Content-Length", str(len(raw)))
129
+ self.end_headers()
130
+ self.wfile.write(raw)
131
+
132
+
133
+ class ClientTest(unittest.TestCase):
134
+ def test_talks_to_the_daemon_surface(self) -> None:
135
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
136
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
137
+ thread.start()
138
+ port = server.server_address[1]
139
+ tm = Taskmaster(f"http://127.0.0.1:{port}", timeout=2)
140
+ try:
141
+ health = tm.health()
142
+ self.assertTrue(health["ok"])
143
+ self.assertEqual(health["version"], "2.1.0")
144
+ self.assertEqual(health["auth"]["methods"], ["pairing"])
145
+
146
+ with self.assertRaises(TaskmasterError) as refused:
147
+ tm.pair("nope")
148
+ self.assertEqual(refused.exception.status, 401)
149
+ self.assertEqual(refused.exception.message, "that code was refused")
150
+
151
+ token = tm.pair("good", label="laptop", kind="agent")
152
+ self.assertEqual(token, "tok-1")
153
+ tm.set_token(token)
154
+
155
+ listing = tm.runs()
156
+ self.assertEqual(listing["seq"], 3)
157
+ self.assertEqual(listing["runs"][0]["id"], "run-1")
158
+ self.assertTrue(listing["runs"][0]["needs_you"])
159
+ self.assertEqual(tm.run("run-1")["prompt"], "Add a button")
160
+
161
+ accepted = tm.start("Add a button", yes=True)
162
+ self.assertEqual(accepted["id"], "run-1")
163
+ self.assertEqual(tm.approve("run-1", "ship it")["id"], "run-1")
164
+
165
+ page = tm.events("run-1", after=1)
166
+ self.assertEqual(page["next"], 2)
167
+ self.assertEqual(len(page["events"]), 1)
168
+ self.assertEqual(tm.doctor(), {"ok": True})
169
+
170
+ status = tm.computer_status()
171
+ self.assertFalse(status["enabled"])
172
+ self.assertEqual(status["mode"], "host")
173
+ self.assertTrue(tm.computer_enable(True)["enabled"])
174
+ started = tm.computer_start("Open Chrome and search for the weather")
175
+ self.assertEqual(started["id"], "cs-1")
176
+ self.assertEqual(started["status"], "running")
177
+ self.assertEqual(tm.computer_sessions()[0]["step_count"], 1)
178
+ self.assertEqual(tm.computer_session("cs-1")["final_reply"], "It is 72 F.")
179
+ self.assertEqual(tm.computer_resume("cs-1", "Read the forecast")["status"], "running")
180
+ self.assertEqual(tm.computer_cancel("cs-1"), {"ok": True})
181
+ acted = tm.computer_act("click_text", text="Search")
182
+ self.assertTrue(acted["ok"])
183
+ self.assertEqual(acted["result"], "clicked Search")
184
+
185
+ self.assertTrue(tm.builtin_mcp_url().endswith("/mcp"))
186
+ servers = tm.mcp_servers()
187
+ self.assertEqual(servers[0]["name"], "linear")
188
+ self.assertTrue(servers[0]["enabled"])
189
+ saved = tm.connect_mcp("linear", "npx", args=["-y", "mcp-remote"])
190
+ self.assertEqual(saved["command"], "npx")
191
+ self.assertEqual(tm.disconnect_mcp("linear"), {"removed": True})
192
+ docs = tm.docs()
193
+ self.assertEqual(docs[0]["id"], "doc-1")
194
+ self.assertEqual(docs[0]["kind"], "pptx")
195
+ self.assertEqual(tm.doc("doc-1")["filename"], "Deck.pptx")
196
+ self.assertEqual(tm.upload_doc("Deck.pptx", "QQ==")["id"], "doc-1")
197
+ self.assertEqual(tm.open_doc("doc-1"), {"ok": True, "path": "/tmp/Deck.pptx"})
198
+ deck = tm.make_pptx("Q4 plan", "Three slides: goal, plan, ask")
199
+ self.assertEqual(deck["id"], "cs-doc")
200
+ self.assertIn("doc_create_pptx", deck["task"])
201
+ self.assertEqual(tm.make_docx("Notes")["id"], "cs-docx")
202
+ job = tm.connect_provider("grok")
203
+ self.assertEqual(job["id"], "job-1")
204
+ self.assertEqual(job["action"], "login")
205
+ self.assertTrue(tm.connect_provider("openrouter", api_key="sk-test")["configured"])
206
+
207
+ tm.clear_token()
208
+ with self.assertRaises(TaskmasterError) as missing:
209
+ tm.runs()
210
+ self.assertEqual(missing.exception.status, 401)
211
+ self.assertEqual(missing.exception.message, "a token is required")
212
+
213
+ with self.assertRaises(TaskmasterError) as bad_path:
214
+ tm.call("GET", "api/health")
215
+ self.assertIn("path must start with /", bad_path.exception.message)
216
+ finally:
217
+ server.shutdown()
218
+ thread.join(timeout=2)
219
+ server.server_close()
220
+
221
+
222
+ if __name__ == "__main__":
223
+ unittest.main()
@@ -1,44 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: taskmaster-api
3
- Version: 0.1.0
4
- Summary: Client for the Taskmaster local daemon HTTP API
5
- Author: Naren Sengodan
6
- License-Expression: MIT
7
- Project-URL: Homepage, https://github.com/narensen/taskmaster-api
8
- Project-URL: Repository, https://github.com/narensen/taskmaster-api
9
- Keywords: taskmaster,api,client,daemon
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Operating System :: OS Independent
12
- Classifier: Typing :: Typed
13
- Requires-Python: >=3.9
14
- Description-Content-Type: text/markdown
15
- License-File: LICENSE
16
- Dynamic: license-file
17
-
18
- # taskmaster-api
19
-
20
- Client for a [Taskmaster](https://github.com/narensen/Taskmaster) daemon running on your machine.
21
-
22
- `tm serve .` listens on `http://127.0.0.1:8737`. `GET /api/health` and `POST /api/pair` need no token. Every other `/api` route needs `Authorization: Bearer <token>`.
23
-
24
- ```python
25
- from taskmaster_api import Taskmaster
26
-
27
- tm = Taskmaster()
28
- tm.set_token(tm.pair("ABCD", label="laptop", kind="agent"))
29
-
30
- accepted = tm.start("Add a command palette", yes=True)
31
- page = tm.events(accepted["id"])
32
- print(page["next"])
33
- ```
34
-
35
- `0.1.0` covers health, pairing, projects, providers, doctor, and the run lifecycle: list, get, start, approve, reject, resume, cancel, undo, and events. `call(method, path, body)` sends any other route and returns the JSON value.
36
-
37
- ```python
38
- doctor = tm.doctor()
39
- dictionary = tm.call("GET", "/api/dictionary?q=button")
40
- ```
41
-
42
- The standard library is the only dependency. The same client is published for Rust (`cargo add taskmaster-api`) and JavaScript (`npm install taskmaster-api`).
43
-
44
- MIT © 2026 Naren Sengodan
@@ -1,27 +0,0 @@
1
- # taskmaster-api
2
-
3
- Client for a [Taskmaster](https://github.com/narensen/Taskmaster) daemon running on your machine.
4
-
5
- `tm serve .` listens on `http://127.0.0.1:8737`. `GET /api/health` and `POST /api/pair` need no token. Every other `/api` route needs `Authorization: Bearer <token>`.
6
-
7
- ```python
8
- from taskmaster_api import Taskmaster
9
-
10
- tm = Taskmaster()
11
- tm.set_token(tm.pair("ABCD", label="laptop", kind="agent"))
12
-
13
- accepted = tm.start("Add a command palette", yes=True)
14
- page = tm.events(accepted["id"])
15
- print(page["next"])
16
- ```
17
-
18
- `0.1.0` covers health, pairing, projects, providers, doctor, and the run lifecycle: list, get, start, approve, reject, resume, cancel, undo, and events. `call(method, path, body)` sends any other route and returns the JSON value.
19
-
20
- ```python
21
- doctor = tm.doctor()
22
- dictionary = tm.call("GET", "/api/dictionary?q=button")
23
- ```
24
-
25
- The standard library is the only dependency. The same client is published for Rust (`cargo add taskmaster-api`) and JavaScript (`npm install taskmaster-api`).
26
-
27
- MIT © 2026 Naren Sengodan
@@ -1,230 +0,0 @@
1
- """HTTP client for one Taskmaster daemon.
2
-
3
- ``tm serve .`` listens on ``http://127.0.0.1:8737``. Health and pair need no
4
- token. Every other ``/api`` route needs ``Authorization: Bearer <token>``.
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- import json
10
- import urllib.error
11
- import urllib.request
12
- from typing import Any, Mapping, Optional
13
-
14
- DEFAULT_BASE_URL = "http://127.0.0.1:8737"
15
- VERSION = "0.1.0"
16
-
17
-
18
- class TaskmasterError(Exception):
19
- """The daemon refused the request, or the response was not usable JSON.
20
-
21
- ``status`` is ``0`` when no HTTP response arrived.
22
- """
23
-
24
- def __init__(self, status: int, message: str) -> None:
25
- super().__init__(message)
26
- self.status = status
27
- self.message = message
28
-
29
-
30
- class Taskmaster:
31
- """Synchronous client. A token set here is sent on every request."""
32
-
33
- def __init__(self, base_url: str = DEFAULT_BASE_URL, token: Optional[str] = None, timeout: float = 30) -> None:
34
- self.base_url = base_url.rstrip("/")
35
- self.token = token
36
- self.timeout = timeout
37
-
38
- def with_token(self, token: str) -> "Taskmaster":
39
- """A new client with the same origin and a different token."""
40
- return Taskmaster(self.base_url, token, self.timeout)
41
-
42
- def set_token(self, token: str) -> None:
43
- self.token = token
44
-
45
- def clear_token(self) -> None:
46
- self.token = None
47
-
48
- def health(self) -> dict[str, Any]:
49
- """``GET /api/health``."""
50
- return self._object(self.call("GET", "/api/health"))
51
-
52
- def pair(self, code: str, label: Optional[str] = None, kind: Optional[str] = None) -> str:
53
- """``POST /api/pair``. Returns the device token and does not store it.
54
-
55
- ``kind`` is ``browser``, ``phone``, ``desktop``, ``machine``, or ``agent``.
56
- """
57
- body: dict[str, str] = {"code": code}
58
- if label:
59
- body["label"] = label
60
- if kind:
61
- body["kind"] = kind
62
- parsed = self._object(self.call("POST", "/api/pair", body))
63
- token = parsed.get("token")
64
- if not isinstance(token, str) or not token:
65
- raise TaskmasterError(0, "pair response had no token")
66
- return token
67
-
68
- def runs(self) -> dict[str, Any]:
69
- """``GET /api/runs``. The body is ``{"runs": [...], "seq": n}``."""
70
- return self._object(self.call("GET", "/api/runs"))
71
-
72
- def runs_since(self, since: int) -> dict[str, Any]:
73
- """``GET /api/runs?since=``. ``since`` is a previous ``seq``."""
74
- return self._object(self.call("GET", f"/api/runs?since={since}"))
75
-
76
- def run(self, run_id: str) -> dict[str, Any]:
77
- """``GET /api/runs/{id}``."""
78
- return self._object(self.call("GET", f"/api/runs/{_segment(run_id)}"))
79
-
80
- def start(
81
- self,
82
- prompt: Optional[str] = None,
83
- plan: Optional[Any] = None,
84
- *,
85
- yes: bool = False,
86
- run_id: Optional[str] = None,
87
- roles: Optional[Mapping[str, str]] = None,
88
- models: Optional[Mapping[str, Optional[str]]] = None,
89
- parallel: Optional[int] = None,
90
- timeout_secs: Optional[int] = None,
91
- template: Optional[str] = None,
92
- max_cost_usd: Optional[float] = None,
93
- mode: Optional[str] = None,
94
- permission_mode: Optional[str] = None,
95
- goal: Optional[str] = None,
96
- goal_max_turns: Optional[int] = None,
97
- computer_use: Optional[bool] = None,
98
- ) -> dict[str, Any]:
99
- """``POST /api/runs``. Send a prompt or a plan, and not both.
100
-
101
- The daemon answers ``202`` once the run is started. ``yes`` builds
102
- without waiting for approval.
103
- """
104
- body: dict[str, Any] = {}
105
- if run_id is not None:
106
- body["id"] = run_id
107
- if prompt is not None:
108
- body["prompt"] = prompt
109
- if plan is not None:
110
- body["plan"] = plan
111
- if yes:
112
- body["yes"] = True
113
- if roles:
114
- body["roles"] = dict(roles)
115
- if models:
116
- body["models"] = dict(models)
117
- if parallel is not None:
118
- body["parallel"] = parallel
119
- if timeout_secs is not None:
120
- body["timeout_secs"] = timeout_secs
121
- if template is not None:
122
- body["template"] = template
123
- if max_cost_usd is not None:
124
- body["max_cost_usd"] = max_cost_usd
125
- if mode is not None:
126
- body["mode"] = mode
127
- if permission_mode is not None:
128
- body["permission_mode"] = permission_mode
129
- if goal is not None:
130
- body["goal"] = goal
131
- if goal_max_turns is not None:
132
- body["goal_max_turns"] = goal_max_turns
133
- if computer_use is not None:
134
- body["computer_use"] = computer_use
135
- return self._object(self.call("POST", "/api/runs", body))
136
-
137
- def approve(self, run_id: str, note: Optional[str] = None) -> dict[str, Any]:
138
- """``POST /api/runs/{id}/approve``. ``note`` is read by the master first."""
139
- body: dict[str, Any] = {"note": note} if note else {}
140
- return self._object(self.call("POST", f"/api/runs/{_segment(run_id)}/approve", body))
141
-
142
- def reject(self, run_id: str, prompt: Optional[str] = None) -> dict[str, Any]:
143
- """``POST /api/runs/{id}/reject``. A prompt makes the run plan again."""
144
- body: dict[str, Any] = {"prompt": prompt} if prompt else {}
145
- return self._object(self.call("POST", f"/api/runs/{_segment(run_id)}/reject", body))
146
-
147
- def resume(self, run_id: str) -> dict[str, Any]:
148
- """``POST /api/runs/{id}/resume``."""
149
- return self._object(self.call("POST", f"/api/runs/{_segment(run_id)}/resume", {}))
150
-
151
- def cancel(self, run_id: str) -> dict[str, Any]:
152
- """``POST /api/runs/{id}/cancel``."""
153
- return self._object(self.call("POST", f"/api/runs/{_segment(run_id)}/cancel", {}))
154
-
155
- def undo(self, run_id: str) -> Any:
156
- """``POST /api/runs/{id}/undo``."""
157
- return self.call("POST", f"/api/runs/{_segment(run_id)}/undo", {})
158
-
159
- def events(self, run_id: str, after: Optional[int] = None) -> dict[str, Any]:
160
- """``GET /api/runs/{id}/events``. ``after`` is the previous ``next``."""
161
- query = "" if after is None else f"?after={after}"
162
- return self._object(self.call("GET", f"/api/runs/{_segment(run_id)}/events{query}"))
163
-
164
- def projects(self) -> Any:
165
- """``GET /api/projects``."""
166
- return self.call("GET", "/api/projects")
167
-
168
- def providers(self) -> Any:
169
- """``GET /api/providers``."""
170
- return self.call("GET", "/api/providers")
171
-
172
- def doctor(self) -> Any:
173
- """``GET /api/doctor``."""
174
- return self.call("GET", "/api/doctor")
175
-
176
- def call(self, method: str, path: str, body: Optional[Any] = None) -> Any:
177
- """Send any daemon route.
178
-
179
- ``path`` starts with ``/``. ``body`` is JSON for requests that have one.
180
- An empty success body becomes ``None``.
181
- """
182
- if not path.startswith("/") or "://" in path or "\0" in path:
183
- raise TaskmasterError(0, f"path must start with /: {path}")
184
- data = None if body is None else json.dumps(body).encode("utf-8")
185
- request = urllib.request.Request(self.base_url + path, data=data, method=method)
186
- if body is not None:
187
- request.add_header("Content-Type", "application/json")
188
- if self.token:
189
- request.add_header("Authorization", f"Bearer {self.token}")
190
- try:
191
- with urllib.request.urlopen(request, timeout=self.timeout) as response:
192
- raw = response.read()
193
- except urllib.error.HTTPError as exc:
194
- raw = exc.read()
195
- raise TaskmasterError(exc.code, _error_message(raw, exc.code)) from None
196
- except urllib.error.URLError as exc:
197
- raise TaskmasterError(0, str(exc.reason)) from None
198
- if not raw or not raw.strip():
199
- return None
200
- try:
201
- return json.loads(raw.decode("utf-8"))
202
- except json.JSONDecodeError as exc:
203
- raise TaskmasterError(0, "response was not JSON") from exc
204
-
205
- @staticmethod
206
- def _object(value: Any) -> dict[str, Any]:
207
- if not isinstance(value, dict):
208
- raise TaskmasterError(0, "response was not a JSON object")
209
- return value
210
-
211
-
212
- def _segment(run_id: str) -> str:
213
- from urllib.parse import quote
214
-
215
- return quote(run_id, safe="")
216
-
217
-
218
- def _error_message(raw: bytes, status: int) -> str:
219
- text = raw.decode("utf-8", errors="replace").strip()
220
- if not text:
221
- return f"HTTP {status}"
222
- try:
223
- parsed = json.loads(text)
224
- except json.JSONDecodeError:
225
- return text
226
- if isinstance(parsed, dict):
227
- message = parsed.get("error")
228
- if isinstance(message, str) and message:
229
- return message
230
- return text
@@ -1,44 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: taskmaster-api
3
- Version: 0.1.0
4
- Summary: Client for the Taskmaster local daemon HTTP API
5
- Author: Naren Sengodan
6
- License-Expression: MIT
7
- Project-URL: Homepage, https://github.com/narensen/taskmaster-api
8
- Project-URL: Repository, https://github.com/narensen/taskmaster-api
9
- Keywords: taskmaster,api,client,daemon
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Operating System :: OS Independent
12
- Classifier: Typing :: Typed
13
- Requires-Python: >=3.9
14
- Description-Content-Type: text/markdown
15
- License-File: LICENSE
16
- Dynamic: license-file
17
-
18
- # taskmaster-api
19
-
20
- Client for a [Taskmaster](https://github.com/narensen/Taskmaster) daemon running on your machine.
21
-
22
- `tm serve .` listens on `http://127.0.0.1:8737`. `GET /api/health` and `POST /api/pair` need no token. Every other `/api` route needs `Authorization: Bearer <token>`.
23
-
24
- ```python
25
- from taskmaster_api import Taskmaster
26
-
27
- tm = Taskmaster()
28
- tm.set_token(tm.pair("ABCD", label="laptop", kind="agent"))
29
-
30
- accepted = tm.start("Add a command palette", yes=True)
31
- page = tm.events(accepted["id"])
32
- print(page["next"])
33
- ```
34
-
35
- `0.1.0` covers health, pairing, projects, providers, doctor, and the run lifecycle: list, get, start, approve, reject, resume, cancel, undo, and events. `call(method, path, body)` sends any other route and returns the JSON value.
36
-
37
- ```python
38
- doctor = tm.doctor()
39
- dictionary = tm.call("GET", "/api/dictionary?q=button")
40
- ```
41
-
42
- The standard library is the only dependency. The same client is published for Rust (`cargo add taskmaster-api`) and JavaScript (`npm install taskmaster-api`).
43
-
44
- MIT © 2026 Naren Sengodan
@@ -1,120 +0,0 @@
1
- """The client against a tiny local daemon stand-in."""
2
-
3
- import json
4
- import threading
5
- import unittest
6
- from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
7
-
8
- from taskmaster_api import Taskmaster, TaskmasterError
9
-
10
-
11
- class Handler(BaseHTTPRequestHandler):
12
- def do_GET(self) -> None: # noqa: N802
13
- self._handle("GET", b"")
14
-
15
- def do_POST(self) -> None: # noqa: N802
16
- length = int(self.headers.get("Content-Length", "0"))
17
- self._handle("POST", self.rfile.read(length) if length else b"")
18
-
19
- def log_message(self, fmt: str, *args: object) -> None:
20
- return
21
-
22
- def _handle(self, method: str, raw: bytes) -> None:
23
- body = raw.decode("utf-8")
24
- path = self.path
25
- authed = self.headers.get("Authorization") == "Bearer tok-1"
26
- if method == "GET" and path == "/api/health":
27
- self._send(200, {"ok": True, "version": "2.1.0", "auth": {"methods": ["pairing"]}, "terminal": True})
28
- return
29
- if method == "POST" and path == "/api/pair":
30
- if '"good"' in body:
31
- self._send(200, {"token": "tok-1"})
32
- else:
33
- self._send(401, {"error": "that code was refused"})
34
- return
35
- if not authed and (path.startswith("/api/runs") or path == "/api/doctor"):
36
- self._send(401, {"error": "a token is required"})
37
- return
38
- if method == "GET" and path == "/api/runs":
39
- self._send(200, {"runs": [{"id": "run-1", "phase": "awaiting_approval", "needs_you": True, "pages": []}], "seq": 3})
40
- return
41
- if method == "GET" and path == "/api/runs/run-1":
42
- self._send(200, {"id": "run-1", "phase": "awaiting_approval", "prompt": "Add a button", "pages": []})
43
- return
44
- if method == "POST" and path == "/api/runs" and "Add a button" in body and '"yes": true' in body:
45
- self._send(202, {"id": "run-1"})
46
- return
47
- if method == "POST" and path == "/api/runs/run-1/approve" and "ship it" in body:
48
- self._send(202, {"id": "run-1"})
49
- return
50
- if method == "GET" and path == "/api/runs/run-1/events?after=1":
51
- self._send(200, {"next": 2, "events": [{"kind": "done"}]})
52
- return
53
- if method == "GET" and path == "/api/doctor":
54
- self._send(200, {"ok": True})
55
- return
56
- self._send(404, {"error": "no such route"})
57
-
58
- def _send(self, status: int, payload: object) -> None:
59
- raw = json.dumps(payload).encode("utf-8")
60
- self.send_response(status)
61
- self.send_header("Content-Type", "application/json")
62
- self.send_header("Content-Length", str(len(raw)))
63
- self.end_headers()
64
- self.wfile.write(raw)
65
-
66
-
67
- class ClientTest(unittest.TestCase):
68
- def test_talks_to_the_daemon_surface(self) -> None:
69
- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
70
- thread = threading.Thread(target=server.serve_forever, daemon=True)
71
- thread.start()
72
- port = server.server_address[1]
73
- tm = Taskmaster(f"http://127.0.0.1:{port}", timeout=2)
74
- try:
75
- health = tm.health()
76
- self.assertTrue(health["ok"])
77
- self.assertEqual(health["version"], "2.1.0")
78
- self.assertEqual(health["auth"]["methods"], ["pairing"])
79
-
80
- with self.assertRaises(TaskmasterError) as refused:
81
- tm.pair("nope")
82
- self.assertEqual(refused.exception.status, 401)
83
- self.assertEqual(refused.exception.message, "that code was refused")
84
-
85
- token = tm.pair("good", label="laptop", kind="agent")
86
- self.assertEqual(token, "tok-1")
87
- tm.set_token(token)
88
-
89
- listing = tm.runs()
90
- self.assertEqual(listing["seq"], 3)
91
- self.assertEqual(listing["runs"][0]["id"], "run-1")
92
- self.assertTrue(listing["runs"][0]["needs_you"])
93
- self.assertEqual(tm.run("run-1")["prompt"], "Add a button")
94
-
95
- accepted = tm.start("Add a button", yes=True)
96
- self.assertEqual(accepted["id"], "run-1")
97
- self.assertEqual(tm.approve("run-1", "ship it")["id"], "run-1")
98
-
99
- page = tm.events("run-1", after=1)
100
- self.assertEqual(page["next"], 2)
101
- self.assertEqual(len(page["events"]), 1)
102
- self.assertEqual(tm.doctor(), {"ok": True})
103
-
104
- tm.clear_token()
105
- with self.assertRaises(TaskmasterError) as missing:
106
- tm.runs()
107
- self.assertEqual(missing.exception.status, 401)
108
- self.assertEqual(missing.exception.message, "a token is required")
109
-
110
- with self.assertRaises(TaskmasterError) as bad_path:
111
- tm.call("GET", "api/health")
112
- self.assertIn("path must start with /", bad_path.exception.message)
113
- finally:
114
- server.shutdown()
115
- thread.join(timeout=2)
116
- server.server_close()
117
-
118
-
119
- if __name__ == "__main__":
120
- unittest.main()
File without changes
File without changes