taskseam 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.
taskseam/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Local task state and handoff tools."""
2
+
3
+ __version__ = "0.1.0"
taskseam/__main__.py ADDED
@@ -0,0 +1,230 @@
1
+ """Command-line entry point: python -m taskseam."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .store import Store
10
+ from .workspace import active_task, browser_token, database_path, find_workspace, initialize
11
+
12
+
13
+ def default_db():
14
+ workspace = find_workspace()
15
+ if workspace:
16
+ return str(database_path(workspace))
17
+ return str(Path.home() / ".local/share/taskseam/taskseam.db")
18
+
19
+
20
+ def parser():
21
+ p = argparse.ArgumentParser(prog="taskseam", description="Local task checkpoints and context deltas")
22
+ p.add_argument("--db", default=None,
23
+ help="SQLite database path (or set TASKSEAM_DB)")
24
+ commands = p.add_subparsers(dest="command", required=True)
25
+ task = commands.add_parser("task", help="Create, list, or inspect tasks")
26
+ task_sub = task.add_subparsers(dest="action", required=True)
27
+ task_sub.add_parser("list")
28
+ create = task_sub.add_parser("create")
29
+ create.add_argument("title")
30
+ show = task_sub.add_parser("show")
31
+ show.add_argument("task_id")
32
+
33
+ event = commands.add_parser("event", help="Record a source event")
34
+ event.add_argument("task_id")
35
+ event.add_argument("body")
36
+ event.add_argument("--source", default="manual")
37
+
38
+ item = commands.add_parser("item", help="Record a decision, question, or constraint")
39
+ item.add_argument("task_id")
40
+ item.add_argument("kind", choices=("decision", "question", "constraint"))
41
+ item.add_argument("body")
42
+ item.add_argument("--source", default="manual")
43
+ item.add_argument("--supersedes", help="ID of an earlier item in the same task")
44
+
45
+ checkpoint = commands.add_parser("checkpoint", help="Save current task state")
46
+ checkpoint.add_argument("task_id", nargs="?", help="Defaults to the active workspace task")
47
+ delta = commands.add_parser("delta", help="Compare two checkpoints")
48
+ delta.add_argument("base")
49
+ delta.add_argument("head")
50
+ context = commands.add_parser("context", help="Show current task state")
51
+ context.add_argument("task_id", nargs="?", help="Defaults to the active workspace task")
52
+ explain = commands.add_parser("explain", help="Show an item's source event")
53
+ explain.add_argument("item_id")
54
+ serve = commands.add_parser("serve", help="Run the localhost JSON API")
55
+ serve.add_argument("--host", default="127.0.0.1")
56
+ serve.add_argument("--port", default=8765, type=int)
57
+ commands.add_parser("mcp", help="Run the MCP server over standard input/output")
58
+ commands.add_parser("version", help="Print the installed version")
59
+ init = commands.add_parser("init", help="Initialize TaskSeam in the current directory")
60
+ init.add_argument("title", nargs="?", help="Title of the first task")
61
+ commands.add_parser("status", help="Show the current workspace and active task")
62
+ record = commands.add_parser("record", help="Record state on the active workspace task")
63
+ record.add_argument("kind", choices=("decision", "question", "constraint"))
64
+ record.add_argument("body")
65
+ record.add_argument("--source", default="manual")
66
+ record.add_argument("--supersedes")
67
+ setup = commands.add_parser("setup", help="Auto-detect and configure supported AI tools")
68
+ setup.add_argument("tool", nargs="?", choices=("codex", "claude-code"),
69
+ help="Configure one tool; omit to configure every detected tool")
70
+ setup.add_argument("--dry-run", action="store_true")
71
+ commands.add_parser("prompt", help="Print the prompt for creating an import packet")
72
+ import_command = commands.add_parser("import", help="Preview or apply a TaskSeam state packet")
73
+ import_command.add_argument("path", nargs="?", help="JSON file; omit to read standard input")
74
+ import_command.add_argument("--source", required=True)
75
+ import_command.add_argument("--apply", action="store_true", help="Write the reviewed packet")
76
+ resolve = commands.add_parser("resolve", help="Resolve a question into an accepted decision")
77
+ resolve.add_argument("question_id")
78
+ resolve.add_argument("decision")
79
+ resolve.add_argument("--source", default="manual")
80
+ resolve.add_argument("--supersedes", help="Existing decision replaced by the resolution")
81
+ supersede = commands.add_parser("supersede", help="Correctly link an old item to its replacement")
82
+ supersede.add_argument("old_item_id")
83
+ supersede.add_argument("--with", dest="new_item_id", required=True)
84
+ handoff = commands.add_parser("handoff", help="Deliver changes since a target's last handoff")
85
+ handoff.add_argument("--to", required=True, dest="target")
86
+ handoff.add_argument("--task-id", help="Defaults to the active workspace task")
87
+ return p
88
+
89
+
90
+ def main(argv=None):
91
+ args = parser().parse_args(argv)
92
+ try:
93
+ if args.command == "init":
94
+ title = args.title or Path.cwd().name
95
+
96
+ def create_task(path, task_title):
97
+ store = Store(path)
98
+ try:
99
+ return store.create_task(task_title)
100
+ finally:
101
+ store.close()
102
+
103
+ root, config = initialize(Path.cwd(), title, create_task)
104
+ print(json.dumps({"workspace": str(root), "project": config["project"],
105
+ "active_task": config["active_task"]}, indent=2))
106
+ return 0
107
+ if args.command == "prompt":
108
+ from .importer import PACKET_PROMPT
109
+ print(PACKET_PROMPT)
110
+ return 0
111
+ workspace = find_workspace()
112
+ args.db = args.db or os.environ.get("TASKSEAM_DB") or default_db()
113
+ if args.command == "status":
114
+ if not workspace:
115
+ raise ValueError("No TaskSeam workspace found; run 'taskseam init'")
116
+ store = Store(args.db)
117
+ try:
118
+ result = {"workspace": str(workspace[0]), "database": args.db,
119
+ "active_task": store.context(active_task(workspace))}
120
+ print(json.dumps(result, indent=2))
121
+ return 0
122
+ finally:
123
+ store.close()
124
+ if args.command == "setup":
125
+ from .setup import setup_claude, setup_codex, setup_detected
126
+ if args.tool == "codex":
127
+ result = setup_codex(sys.executable, args.dry_run)
128
+ elif args.tool == "claude-code":
129
+ result = setup_claude(sys.executable, args.dry_run)
130
+ else:
131
+ result = setup_detected(sys.executable, args.dry_run)
132
+ print(json.dumps(result, indent=2))
133
+ return 0
134
+ if args.command == "import":
135
+ from .importer import parse_packet
136
+ if not workspace:
137
+ raise ValueError("No TaskSeam workspace found; run 'taskseam init'")
138
+ raw = Path(args.path).read_text(encoding="utf-8") if args.path else sys.stdin.read()
139
+ packet = parse_packet(raw)
140
+ if not args.apply:
141
+ print(json.dumps({"preview": packet["items"], "source": args.source,
142
+ "applied": False,
143
+ "next": "Review the items, then rerun with --apply"}, indent=2))
144
+ return 0
145
+ store = Store(args.db)
146
+ try:
147
+ imported = store.import_items(active_task(workspace), args.source, raw, packet["items"])
148
+ result = {"applied": True, "source": args.source, **imported,
149
+ "items": packet["items"]}
150
+ print(json.dumps(result, indent=2))
151
+ return 0
152
+ finally:
153
+ store.close()
154
+ if args.command == "serve":
155
+ from .api import serve
156
+ if not workspace:
157
+ raise ValueError("No TaskSeam workspace found; run 'taskseam init'")
158
+ task_id = active_task(workspace)
159
+ token = browser_token(workspace)
160
+ print("Browser pairing token: " + token, flush=True)
161
+ serve(args.db, args.host, args.port, token, task_id)
162
+ return 0
163
+ if args.command == "mcp":
164
+ from .mcp import run
165
+ run(args.db, task_id=active_task(workspace) if workspace else None)
166
+ return 0
167
+ if args.command == "version":
168
+ from . import __version__
169
+ print(__version__)
170
+ return 0
171
+ store = Store(args.db)
172
+ try:
173
+ if args.command == "task":
174
+ if args.action == "create":
175
+ result = {"id": store.create_task(args.title), "title": args.title}
176
+ elif args.action == "list":
177
+ result = store.tasks()
178
+ else:
179
+ result = {"task": store.task(args.task_id), "items": store.current_items(args.task_id)}
180
+ elif args.command == "event":
181
+ result = {"event_id": store.add_event(args.task_id, args.source, args.body)}
182
+ elif args.command == "item":
183
+ result = {"item_id": store.add_item(args.task_id, args.kind, args.body,
184
+ args.source, args.supersedes)}
185
+ elif args.command == "record":
186
+ if not workspace:
187
+ raise ValueError("No TaskSeam workspace found; run 'taskseam init'")
188
+ result = {"item_id": store.add_item(active_task(workspace), args.kind, args.body,
189
+ args.source, args.supersedes)}
190
+ elif args.command == "resolve":
191
+ if not workspace:
192
+ raise ValueError("No TaskSeam workspace found; run 'taskseam init'")
193
+ result = {"item_id": store.resolve_question(active_task(workspace), args.question_id,
194
+ args.decision, args.source, args.supersedes),
195
+ "resolved_question": args.question_id}
196
+ elif args.command == "supersede":
197
+ if not workspace:
198
+ raise ValueError("No TaskSeam workspace found; run 'taskseam init'")
199
+ store.set_supersession(active_task(workspace), args.old_item_id, args.new_item_id)
200
+ result = {"superseded": args.old_item_id, "replacement": args.new_item_id}
201
+ elif args.command == "handoff":
202
+ task_id = args.task_id or (active_task(workspace) if workspace else None)
203
+ if not task_id:
204
+ raise ValueError("Provide a task ID or run this command in a TaskSeam workspace")
205
+ result = store.handoff(task_id, args.target)
206
+ elif args.command == "checkpoint":
207
+ task_id = args.task_id or (active_task(workspace) if workspace else None)
208
+ if not task_id:
209
+ raise ValueError("Provide a task ID or run this command in a TaskSeam workspace")
210
+ result = {"checkpoint_id": store.checkpoint(task_id)}
211
+ elif args.command == "delta":
212
+ result = store.delta(args.base, args.head)
213
+ elif args.command == "context":
214
+ task_id = args.task_id or (active_task(workspace) if workspace else None)
215
+ if not task_id:
216
+ raise ValueError("Provide a task ID or run this command in a TaskSeam workspace")
217
+ result = store.context(task_id)
218
+ else:
219
+ result = store.explain(args.item_id)
220
+ print(json.dumps(result, indent=2))
221
+ return 0
222
+ finally:
223
+ store.close()
224
+ except (ValueError, OSError) as exc:
225
+ print("taskseam: " + str(exc), file=sys.stderr)
226
+ return 1
227
+
228
+
229
+ if __name__ == "__main__":
230
+ sys.exit(main())
taskseam/api.py ADDED
@@ -0,0 +1,164 @@
1
+ """A small localhost-only JSON API for TaskSeam clients."""
2
+
3
+ import json
4
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
5
+ from urllib.parse import urlparse
6
+
7
+ from . import __version__
8
+ from .store import Store
9
+
10
+
11
+ def _json(handler, status, payload):
12
+ body = json.dumps(payload).encode("utf-8")
13
+ handler.send_response(status)
14
+ handler.send_header("Content-Type", "application/json")
15
+ handler.send_header("Content-Length", str(len(body)))
16
+ handler.send_header("Cache-Control", "no-store")
17
+ origin = handler.headers.get("Origin", "")
18
+ if origin.startswith("chrome-extension://") or origin.startswith("moz-extension://"):
19
+ handler.send_header("Access-Control-Allow-Origin", origin)
20
+ handler.send_header("Vary", "Origin")
21
+ handler.end_headers()
22
+ handler.wfile.write(body)
23
+
24
+
25
+ def make_handler(db_path, token=None, active_task_id=None):
26
+ class Handler(BaseHTTPRequestHandler):
27
+ server_version = "TaskSeam/" + __version__
28
+
29
+ def log_message(self, fmt, *args):
30
+ return
31
+
32
+ def _body(self):
33
+ try:
34
+ length = int(self.headers.get("Content-Length", "0"))
35
+ if length > 1_000_000:
36
+ raise ValueError("Request body is too large")
37
+ return json.loads(self.rfile.read(length) or b"{}")
38
+ except (ValueError, json.JSONDecodeError) as exc:
39
+ raise ValueError("Invalid JSON body") from exc
40
+
41
+ def _run(self, action):
42
+ store = Store(db_path)
43
+ try:
44
+ return action(store)
45
+ finally:
46
+ store.close()
47
+
48
+ def _authorized(self):
49
+ if token is None:
50
+ return True
51
+ return self.headers.get("Authorization") == "Bearer " + token
52
+
53
+ def _require_auth(self):
54
+ if self._authorized():
55
+ return True
56
+ _json(self, 401, {"error": "Invalid or missing TaskSeam pairing token"})
57
+ return False
58
+
59
+ def do_OPTIONS(self):
60
+ origin = self.headers.get("Origin", "")
61
+ if not (origin.startswith("chrome-extension://") or
62
+ origin.startswith("moz-extension://")):
63
+ return _json(self, 403, {"error": "Extension origin required"})
64
+ self.send_response(204)
65
+ self.send_header("Access-Control-Allow-Origin", origin)
66
+ self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type")
67
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
68
+ self.send_header("Access-Control-Max-Age", "600")
69
+ self.end_headers()
70
+
71
+ def do_GET(self):
72
+ parts = [part for part in urlparse(self.path).path.split("/") if part]
73
+ try:
74
+ if parts == ["health"]:
75
+ result = {"status": "ok", "version": __version__, "storage": "local"}
76
+ elif parts == ["v1", "active"]:
77
+ if not self._require_auth():
78
+ return
79
+ if not active_task_id:
80
+ raise ValueError("No active workspace task")
81
+ result = self._run(lambda store: store.context(active_task_id))
82
+ elif parts == ["v1", "tasks"]:
83
+ if not self._require_auth():
84
+ return
85
+ result = self._run(lambda store: store.tasks())
86
+ elif len(parts) == 4 and parts[:2] == ["v1", "tasks"] and parts[3] == "context":
87
+ if not self._require_auth():
88
+ return
89
+ result = self._run(lambda store: store.context(parts[2]))
90
+ elif len(parts) == 3 and parts[:2] == ["v1", "items"]:
91
+ if not self._require_auth():
92
+ return
93
+ result = self._run(lambda store: store.explain(parts[2]))
94
+ else:
95
+ return _json(self, 404, {"error": "Not found"})
96
+ _json(self, 200, result)
97
+ except ValueError as exc:
98
+ _json(self, 404, {"error": str(exc)})
99
+
100
+ def do_POST(self):
101
+ parts = [part for part in urlparse(self.path).path.split("/") if part]
102
+ try:
103
+ if not self._require_auth():
104
+ return
105
+ body = self._body()
106
+ if parts == ["v1", "tasks"]:
107
+ title = _required(body, "title")
108
+ result = self._run(lambda store: {"id": store.create_task(title), "title": title})
109
+ elif len(parts) == 4 and parts[:2] == ["v1", "tasks"] and parts[3] == "items":
110
+ result = self._run(lambda store: {"item_id": store.add_item(
111
+ parts[2], _required(body, "kind"), _required(body, "body"),
112
+ body.get("source", "api"), body.get("supersedes")
113
+ )})
114
+ elif len(parts) == 4 and parts[:2] == ["v1", "tasks"] and parts[3] == "checkpoint":
115
+ result = self._run(lambda store: {"checkpoint_id": store.checkpoint(parts[2])})
116
+ elif parts == ["v1", "delta"]:
117
+ result = self._run(lambda store: store.delta(
118
+ _required(body, "base"), _required(body, "head")
119
+ ))
120
+ elif parts == ["v1", "active", "import"]:
121
+ if not active_task_id:
122
+ raise ValueError("No active workspace task")
123
+ items = body.get("items")
124
+ if not isinstance(items, list) or not items:
125
+ raise ValueError("Missing or empty field: items")
126
+ normalized = []
127
+ for item in items:
128
+ if not isinstance(item, dict):
129
+ raise ValueError("Each item must be an object")
130
+ kind = _required(item, "kind")
131
+ if kind not in ("decision", "constraint", "question"):
132
+ raise ValueError("Unsupported item kind: " + kind)
133
+ normalized.append({"kind": kind, "body": _required(item, "body")})
134
+ source = body.get("source", "browser-extension")
135
+ evidence = body.get("evidence", json.dumps({"items": normalized}))
136
+ result = self._run(lambda store: store.import_items(
137
+ active_task_id, source, evidence, normalized))
138
+ else:
139
+ return _json(self, 404, {"error": "Not found"})
140
+ _json(self, 201, result)
141
+ except ValueError as exc:
142
+ _json(self, 400, {"error": str(exc)})
143
+
144
+ return Handler
145
+
146
+
147
+ def _required(body, key):
148
+ value = body.get(key)
149
+ if not isinstance(value, str) or not value.strip():
150
+ raise ValueError("Missing or empty field: " + key)
151
+ return value.strip()
152
+
153
+
154
+ def serve(db_path, host="127.0.0.1", port=8765, token=None, active_task_id=None):
155
+ if host not in ("127.0.0.1", "localhost", "::1"):
156
+ raise ValueError("TaskSeam only binds to a localhost address")
157
+ server = ThreadingHTTPServer((host, port), make_handler(db_path, token, active_task_id))
158
+ print("TaskSeam listening on http://{}:{}".format(host, server.server_port), flush=True)
159
+ try:
160
+ server.serve_forever()
161
+ except KeyboardInterrupt:
162
+ pass
163
+ finally:
164
+ server.server_close()
taskseam/importer.py ADDED
@@ -0,0 +1,41 @@
1
+ """Validated, review-first imports of structured task state."""
2
+
3
+ import json
4
+
5
+
6
+ PACKET_PROMPT = """Return a TaskSeam state packet for our current work.
7
+ Include only conclusions I explicitly accepted and questions that remain unresolved.
8
+ Do not turn suggestions or hypothetical options into decisions.
9
+ Return JSON only, using this exact shape:
10
+ {
11
+ "version": 1,
12
+ "items": [
13
+ {"kind": "decision", "body": "one current accepted decision"},
14
+ {"kind": "constraint", "body": "one active constraint"},
15
+ {"kind": "question", "body": "one unresolved question"}
16
+ ]
17
+ }
18
+ Omit categories that have no supported items. Keep each body concise and self-contained."""
19
+
20
+
21
+ def parse_packet(text):
22
+ try:
23
+ packet = json.loads(text)
24
+ except json.JSONDecodeError as exc:
25
+ raise ValueError("Import must be valid JSON: " + str(exc)) from exc
26
+ if not isinstance(packet, dict) or packet.get("version") != 1:
27
+ raise ValueError("Import packet version must be 1")
28
+ items = packet.get("items")
29
+ if not isinstance(items, list) or not items:
30
+ raise ValueError("Import packet must contain at least one item")
31
+ normalized = []
32
+ for item in items:
33
+ if not isinstance(item, dict):
34
+ raise ValueError("Each imported item must be an object")
35
+ kind, body = item.get("kind"), item.get("body")
36
+ if kind not in ("decision", "question", "constraint"):
37
+ raise ValueError("Invalid imported item kind: " + str(kind))
38
+ if not isinstance(body, str) or not body.strip():
39
+ raise ValueError("Each imported item requires a non-empty body")
40
+ normalized.append({"kind": kind, "body": body.strip()})
41
+ return {"version": 1, "items": normalized}
taskseam/mcp.py ADDED
@@ -0,0 +1,140 @@
1
+ """Minimal MCP stdio server exposing TaskSeam's local state."""
2
+
3
+ import json
4
+ import sys
5
+
6
+ from . import __version__
7
+ from .store import Store
8
+
9
+
10
+ SERVER_INSTRUCTIONS = """Use TaskSeam for continuity when an active workspace task is available.
11
+ At the start of relevant project work, call taskseam_continue once with a stable lowercase target
12
+ for this agent. Use the returned state as evidence and do not invent missing context. During normal
13
+ work, call taskseam_record only for a decision the user explicitly accepts, an active constraint,
14
+ or a material unresolved question. Never store brainstorming, unaccepted recommendations, secrets,
15
+ or unrelated personal context. Use taskseam_resolve when the user explicitly answers a stored
16
+ question. Keep durable items concise and self-contained, preserve supersession links, and use the
17
+ host's normal approval flow for writes. Do not ask the user to run TaskSeam CLI record commands when
18
+ an MCP write tool can complete the operation."""
19
+
20
+
21
+ TOOLS = [
22
+ {"name": "taskseam_list_tasks", "description": "List local TaskSeam tasks",
23
+ "inputSchema": {"type": "object", "properties": {}},
24
+ "annotations": {"readOnlyHint": True}},
25
+ {"name": "taskseam_context", "description": "Get the current state of a task",
26
+ "inputSchema": {"type": "object", "properties": {"task_id": {"type": "string"}},
27
+ "required": ["task_id"]}, "annotations": {"readOnlyHint": True}},
28
+ {"name": "taskseam_delta", "description": "Get changes between two checkpoints",
29
+ "inputSchema": {"type": "object", "properties": {
30
+ "base": {"type": "string"}, "head": {"type": "string"}},
31
+ "required": ["base", "head"]}, "annotations": {"readOnlyHint": True}},
32
+ {"name": "taskseam_explain", "description": "Show the source evidence for a state item",
33
+ "inputSchema": {"type": "object", "properties": {"item_id": {"type": "string"}},
34
+ "required": ["item_id"]}, "annotations": {"readOnlyHint": True}},
35
+ {"name": "taskseam_continue",
36
+ "description": "Return changes since a target last received this task, then mark them delivered",
37
+ "inputSchema": {"type": "object", "properties": {
38
+ "task_id": {"type": "string", "description": "Omit for the active workspace task"},
39
+ "target": {"type": "string", "description": "Receiving tool, such as codex"}},
40
+ "required": ["target"]}},
41
+ {"name": "taskseam_record",
42
+ "description": "Record one user-accepted decision, active constraint, or unresolved question",
43
+ "inputSchema": {"type": "object", "properties": {
44
+ "task_id": {"type": "string", "description": "Omit for the active workspace task"},
45
+ "kind": {"type": "string", "enum": ["decision", "constraint", "question"]},
46
+ "body": {"type": "string"},
47
+ "source": {"type": "string", "description": "Originating agent or user"},
48
+ "supersedes": {"type": "string", "description": "Earlier item replaced by this item"}},
49
+ "required": ["kind", "body", "source"]},
50
+ "annotations": {"readOnlyHint": False}},
51
+ {"name": "taskseam_resolve",
52
+ "description": "Resolve an open question with an explicitly accepted decision",
53
+ "inputSchema": {"type": "object", "properties": {
54
+ "task_id": {"type": "string", "description": "Omit for the active workspace task"},
55
+ "question_id": {"type": "string"},
56
+ "decision": {"type": "string"},
57
+ "source": {"type": "string", "description": "Originating agent or user"},
58
+ "supersedes": {"type": "string", "description": "Earlier decision replaced by this resolution"}},
59
+ "required": ["question_id", "decision", "source"]},
60
+ "annotations": {"readOnlyHint": False}},
61
+ ]
62
+
63
+
64
+ def _result(request_id, value):
65
+ return {"jsonrpc": "2.0", "id": request_id, "result": value}
66
+
67
+
68
+ def _error(request_id, code, message):
69
+ return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
70
+
71
+
72
+ def handle(store, request, active_task_id=None):
73
+ request_id, method = request.get("id"), request.get("method")
74
+ if method == "initialize":
75
+ return _result(request_id, {
76
+ "protocolVersion": "2025-06-18",
77
+ "capabilities": {"tools": {"listChanged": False}},
78
+ "serverInfo": {"name": "taskseam", "version": __version__},
79
+ "instructions": SERVER_INSTRUCTIONS,
80
+ })
81
+ if method == "ping":
82
+ return _result(request_id, {})
83
+ if method == "tools/list":
84
+ return _result(request_id, {"tools": TOOLS})
85
+ if method == "notifications/initialized":
86
+ return None
87
+ if method != "tools/call":
88
+ return _error(request_id, -32601, "Method not found")
89
+ params = request.get("params") or {}
90
+ name, args = params.get("name"), params.get("arguments") or {}
91
+ try:
92
+ if name == "taskseam_list_tasks":
93
+ value = store.tasks()
94
+ elif name == "taskseam_context":
95
+ value = store.context(args["task_id"])
96
+ elif name == "taskseam_delta":
97
+ value = store.delta(args["base"], args["head"])
98
+ elif name == "taskseam_explain":
99
+ value = store.explain(args["item_id"])
100
+ elif name == "taskseam_continue":
101
+ task_id = args.get("task_id") or active_task_id
102
+ if not task_id:
103
+ raise ValueError("task_id is required outside an initialized workspace")
104
+ value = store.handoff(task_id, args["target"])
105
+ elif name == "taskseam_record":
106
+ task_id = args.get("task_id") or active_task_id
107
+ if not task_id:
108
+ raise ValueError("task_id is required outside an initialized workspace")
109
+ item_id = store.add_item(task_id, args["kind"], args["body"], args["source"],
110
+ args.get("supersedes"))
111
+ value = {"item_id": item_id, "recorded": True}
112
+ elif name == "taskseam_resolve":
113
+ task_id = args.get("task_id") or active_task_id
114
+ if not task_id:
115
+ raise ValueError("task_id is required outside an initialized workspace")
116
+ item_id = store.resolve_question(task_id, args["question_id"], args["decision"],
117
+ args["source"], args.get("supersedes"))
118
+ value = {"item_id": item_id, "resolved_question": args["question_id"]}
119
+ else:
120
+ return _error(request_id, -32602, "Unknown tool: " + str(name))
121
+ return _result(request_id, {"content": [{"type": "text", "text": json.dumps(value, indent=2)}]})
122
+ except (KeyError, ValueError) as exc:
123
+ return _result(request_id, {"content": [{"type": "text", "text": str(exc)}], "isError": True})
124
+
125
+
126
+ def run(db_path, input_stream=None, output_stream=None, task_id=None):
127
+ input_stream = input_stream or sys.stdin
128
+ output_stream = output_stream or sys.stdout
129
+ store = Store(db_path)
130
+ try:
131
+ for line in input_stream:
132
+ try:
133
+ response = handle(store, json.loads(line), task_id)
134
+ except (json.JSONDecodeError, TypeError) as exc:
135
+ response = _error(None, -32700, "Parse error: " + str(exc))
136
+ if response is not None:
137
+ output_stream.write(json.dumps(response, separators=(",", ":")) + "\n")
138
+ output_stream.flush()
139
+ finally:
140
+ store.close()
taskseam/setup.py ADDED
@@ -0,0 +1,77 @@
1
+ """Configuration helpers for supported AI tools."""
2
+
3
+ import shutil
4
+ import subprocess
5
+ import sys
6
+
7
+
8
+ def codex_command(python_executable=None):
9
+ codex = shutil.which("codex")
10
+ if not codex:
11
+ raise ValueError("Codex CLI was not found on PATH")
12
+ python = python_executable or sys.executable
13
+ return [codex, "mcp", "add", "taskseam", "--", python, "-m", "taskseam", "mcp"]
14
+
15
+
16
+ def claude_command(python_executable=None):
17
+ claude = shutil.which("claude")
18
+ if not claude:
19
+ raise ValueError("Claude Code CLI was not found on PATH")
20
+ python = python_executable or sys.executable
21
+ return [claude, "mcp", "add", "--scope", "user", "taskseam", "--",
22
+ python, "-m", "taskseam", "mcp"]
23
+
24
+
25
+ def setup_codex(python_executable=None, dry_run=False):
26
+ command = codex_command(python_executable)
27
+ if dry_run:
28
+ return {"configured": False, "command": command}
29
+
30
+ existing = subprocess.run([command[0], "mcp", "get", "taskseam"],
31
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
32
+ if existing.returncode == 0:
33
+ removed = subprocess.run([command[0], "mcp", "remove", "taskseam"],
34
+ capture_output=True, text=True)
35
+ if removed.returncode != 0:
36
+ raise ValueError(removed.stderr.strip() or "Could not update the existing TaskSeam MCP server")
37
+ added = subprocess.run(command, capture_output=True, text=True)
38
+ if added.returncode != 0:
39
+ raise ValueError(added.stderr.strip() or "Could not configure TaskSeam in Codex")
40
+ return {"configured": True, "server": "taskseam", "command": command,
41
+ "message": added.stdout.strip()}
42
+
43
+
44
+ def setup_claude(python_executable=None, dry_run=False):
45
+ command = claude_command(python_executable)
46
+ if dry_run:
47
+ return {"configured": False, "command": command}
48
+
49
+ existing = subprocess.run([command[0], "mcp", "get", "taskseam"],
50
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
51
+ if existing.returncode == 0:
52
+ removed = subprocess.run([command[0], "mcp", "remove", "--scope", "user", "taskseam"],
53
+ capture_output=True, text=True)
54
+ if removed.returncode != 0:
55
+ raise ValueError(removed.stderr.strip() or
56
+ "Could not update the existing TaskSeam MCP server")
57
+ added = subprocess.run(command, capture_output=True, text=True)
58
+ if added.returncode != 0:
59
+ raise ValueError(added.stderr.strip() or "Could not configure TaskSeam in Claude Code")
60
+ return {"configured": True, "server": "taskseam", "command": command,
61
+ "message": added.stdout.strip()}
62
+
63
+
64
+ def setup_detected(python_executable=None, dry_run=False):
65
+ """Configure every supported local agent found on PATH."""
66
+ installers = (("codex", setup_codex), ("claude-code", setup_claude))
67
+ detected = []
68
+ skipped = []
69
+ for name, installer in installers:
70
+ executable = "claude" if name == "claude-code" else name
71
+ if not shutil.which(executable):
72
+ skipped.append({"tool": name, "reason": "not found on PATH"})
73
+ continue
74
+ result = installer(python_executable, dry_run)
75
+ detected.append({"tool": name, **result})
76
+ return {"configured": detected, "skipped": skipped,
77
+ "web_assistants": "ChatGPT and Claude web support is available as a developer-preview browser extension"}