"""A stand-in assistant, built only from kovrex.ai/for-assistants.md. It exists to test that guide the way a real assistant will meet it. It shares no code with Kovrex. It is a command, not a service: run it by hand and it does one step each time, the way an assistant acts when its person speaks. python assistant.py connect --name "Your Name" --email you@example.com \\ --specialist kovrex-test/echo python assistant.py status # has my person answered? python assistant.py wait # keep checking until they do python assistant.py resend # send the email again python assistant.py another northgate/meridian # a further specialist python assistant.py talk kovrex-test/echo "hello" # talk to a specialist python assistant.py record # what Kovrex stored for that conversation python assistant.py card # what the specialist is and its terms python assistant.py talk "Hello" # say something and print the answer python assistant.py talk "Please review this" --file report.pdf # send a file with it # (any file the specialist sends back is read and saved) python assistant.py task # where the last task stands python assistant.py task --wait # keep checking, as Kovrex advises, until it ends python assistant.py task --cancel # cancel it python assistant.py jobs # your person's long-running jobs, whichever assistant asked python assistant.py memory # what the specialist remembers and suggests python assistant.py memory keep ID # also: discard ID, delete ID, correct ID "new text" Its key and what it has asked for are kept in ./assistant-data (or DATA_DIR). Set KOVREX_URL to point it somewhere other than https://kovrex.ai. """ import argparse import base64 import datetime import hashlib import json import os import sys import time import urllib.error import urllib.request import uuid from pathlib import Path from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey KOVREX = os.environ.get("KOVREX_URL", "https://kovrex.ai").rstrip("/") DATA_DIR = Path(os.environ.get("DATA_DIR", "./assistant-data")) STATE = DATA_DIR / "state.json" def b64(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode() def unb64(text: str) -> bytes: return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) # --- step 1 of the guide: the key ---------------------------------------------- def load_key() -> Ed25519PrivateKey: """One key, made once and kept. It is this assistant's identity.""" DATA_DIR.mkdir(parents=True, exist_ok=True) path = DATA_DIR / "key" if path.exists(): return Ed25519PrivateKey.from_private_bytes(unb64(path.read_text().strip())) key = Ed25519PrivateKey.generate() raw = key.private_bytes( serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption() ) path.touch(mode=0o600) path.write_text(b64(raw)) return key def public_key(key: Ed25519PrivateKey) -> str: raw = key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) return b64(raw) # --- "Signing a call" in the guide ---------------------------------------------- def token(key: Ed25519PrivateKey) -> str: now = int(time.time()) header = {"alg": "EdDSA", "typ": "JWT", "kid": public_key(key)} claims = {"aud": KOVREX, "iat": now, "exp": now + 300, "jti": str(uuid.uuid4())} signed = b64(json.dumps(header).encode()) + "." + b64(json.dumps(claims).encode()) return signed + "." + b64(key.sign(signed.encode())) def call(method: str, path: str, body=None, key=None): """One call to Kovrex. Returns (status, parsed JSON).""" request = urllib.request.Request(KOVREX + path, method=method) request.add_header("Content-Type", "application/json") request.add_header("User-Agent", "Kovrex-Stand-In-Assistant/1") if key is not None: request.add_header("Authorization", "Bearer " + token(key)) # a fresh token every call data = json.dumps(body).encode() if body is not None else None try: with urllib.request.urlopen(request, data=data, timeout=30) as response: return response.status, json.loads(response.read()) except urllib.error.HTTPError as error: try: return error.code, json.loads(error.read()) except ValueError: return error.code, {"error": {"code": "unreadable", "message": "the reply was not JSON"}} except (urllib.error.URLError, TimeoutError) as error: return 0, {"error": {"code": "unreachable", "message": str(error)}} def read_state() -> dict: try: return json.loads(STATE.read_text()) except (OSError, ValueError): return {} def write_state(state: dict) -> None: DATA_DIR.mkdir(parents=True, exist_ok=True) STATE.write_text(json.dumps(state, indent=2)) def explain(status: int, reply: dict) -> str: error = reply.get("error", {}) return f"Kovrex refused ({status} {error.get('code', '')}): {error.get('message', reply)}" def say_to_person(specialist: str, code: str) -> None: """Step 3 of the guide: what an assistant tells its person.""" print() print(f"I've asked to connect you to {specialist} on Kovrex.") print('You will get an email from Kovrex titled "Your assistant is asking to connect on Kovrex".') print("Open it, review what the page shows, and type this code where it asks:") print() print(f" {code}") print() print("Then press the button to go ahead. Kovrex does not show the code anywhere,") print("so this is the only place to get it. If you did not ask for this, press Decline.") print() # --- the commands ----------------------------------------------------------------- def connect(args) -> int: state = read_state() pending = state.get("request") if pending and pending.get("status") == "pending": print("A request is already waiting for your person. Use `status`, `wait`, or `resend`.") print("I will not send another: each one emails them.") return 1 key = load_key() status, reply = call("POST", "/v1/enrollments", { "name": args.name, "email": args.email, "specialist": args.specialist, "label": args.label, "public_key": public_key(key), }) if status != 201: print(explain(status, reply)) return 1 state["request"] = { "id": reply["id"], "code": reply["code"], "status": reply["status"], "expires_at": reply["expires_at"], "specialist": args.specialist, } write_state(state) if not reply.get("email_sent", True): print("Kovrex could not send the email. Run `resend` now.") say_to_person(args.specialist, reply["code"]) return 0 def another(args) -> int: state = read_state() key = load_key() status, reply = call("POST", "/v1/relationships", {"specialist": args.specialist}, key=key) if status == 200: print(f"You already use {reply.get('specialist', args.specialist)}. Nothing more is needed.") return 0 if status != 201: print(explain(status, reply)) return 1 state["request"] = { "id": reply["id"], "code": reply["code"], "status": reply["status"], "expires_at": reply["expires_at"], "specialist": args.specialist, } write_state(state) say_to_person(args.specialist, reply["code"]) return 0 def check(state: dict): request = state.get("request") if not request: return None, "I have not asked to connect to anything yet. Use `connect`." status, reply = call("GET", f"/v1/enrollments/{request['id']}", key=load_key()) if status != 200: return None, explain(status, reply) request["status"] = reply["status"] write_state(state) # Say only what is true. told = { "pending": f"Your person has not answered yet. The code they must type is {request['code']}.", "accepted": f"Connected. Your person accepted {request['specialist']}'s terms.", "declined": "Your person declined. Nothing was connected, and I will not ask again unless they do.", "expired": "The request lapsed after 72 hours, or was closed after five wrong codes. I can start again if they want.", } return reply["status"], told.get(reply["status"], reply["status"]) def status(_args) -> int: result, message = check(read_state()) print(message) return 0 if result else 1 def wait(args) -> int: deadline = time.time() + args.minutes * 60 while True: result, message = check(read_state()) if result != "pending": print(message) return 0 if result == "accepted" else 1 if time.time() >= deadline: print(message) return 1 time.sleep(args.every) # the guide: no more than once a minute def resend(_args) -> int: request = read_state().get("request") if not request: print("I have not asked to connect to anything yet. Use `connect`.") return 1 status, reply = call("POST", f"/v1/enrollments/{request['id']}/resend", {}, key=load_key()) if status != 200: print(explain(status, reply)) return 1 print(f"A new email is on its way. The code to type is still {request['code']}; the old link no longer works.") return 0 # --- "Talking to a specialist" in the guide ------------------------------------------ RELAY_TIMEOUT = 150 # seconds of silence before giving up; the guide says to use more than Kovrex's 120 FINAL_STATES = { "TASK_STATE_COMPLETED", "TASK_STATE_FAILED", "TASK_STATE_REJECTED", "TASK_STATE_CANCELED", } # The guide's "Long-running tasks": the extension a deferral and every check of an # open job carry, and the one-minute limit on checking an open task. DEFERRED = "https://kovrex.ai/ext/deferred/v1" CHECK_FLOOR = 60 STATE_WORDS = { "TASK_STATE_SUBMITTED": "Not finished: the specialist has the task but has not started.", "TASK_STATE_WORKING": "Not finished: the specialist is still working.", "TASK_STATE_INPUT_REQUIRED": 'The specialist asked a question. Answer it with `talk "your answer"`.', "TASK_STATE_AUTH_REQUIRED": "Waiting for your person to approve something on Kovrex.", "TASK_STATE_COMPLETED": "Completed.", "TASK_STATE_FAILED": "Ended without an answer: the task failed.", "TASK_STATE_REJECTED": "Ended without an answer: the specialist rejected the task.", "TASK_STATE_CANCELED": "Ended without an answer: the task was canceled.", } # The guide's first table: refusals before the request is read as A2A. HTTP_REFUSALS = { "unauthorized": "Kovrex did not accept this assistant's token. It may not be connected, " "or your person may have disconnected it.", "no_relationship": "Your person has not accepted this specialist's terms, or has ended the " "relationship. Ask with `another`.", "unknown_specialist": "There is no open specialist at that address.", "too_many_requests": "Too many requests in a minute from this assistant. Wait.", "access_required": "Your person does not have access to this specialist, which charges. " "Tell them what the message says.", "specialist_rate_limit": "Your person has sent this specialist as many messages as it takes " "in an hour. Wait as long as the message says.", "relay_off": "Kovrex is not carrying conversations right now.", } # The guide's second table: kovrex_reason -> (what happened, was the message delivered?) REASONS = { "unsupported_part": ("A part of the message was neither text nor a file.", "no"), "empty_message": ("The message had no part at all.", "no"), "url_part_refused": ("A part pointed at an address. Kovrex never fetches or passes on an address; send the bytes.", "no"), "file_type_not_allowed": ("A file's type is not one Kovrex carries.", "no"), "file_type_mismatch": ("A file's bytes are not what its type says.", "no"), "type_not_accepted_by_specialist": ("The specialist's card does not list that file type.", "no"), "file_too_large": ("A file is over 25 MB.", "no"), "file_empty": ("A file has no bytes.", "no"), "too_many_files": ("More than 5 files in one message.", "no"), "message_files_too_large": ("More than 50 MB of files in one message.", "no"), "storage_full": ("Your person has 5 GB of files stored with Kovrex already.", "no"), "files_off": ("Kovrex is not carrying files right now. Send the message without the file.", "no"), "unknown_context": ("Kovrex does not know that conversation as yours. Start a new one with --new.", "no"), "context_mismatch": ("The conversation and the task do not go together. Start a new one with --new.", "no"), "not_carried": ("Kovrex does not carry that method yet.", "no"), "specialist_unreachable": ("Kovrex could not connect to the specialist.", "no"), "specialist_slow": ("The specialist did not answer in time.", "unknown"), "specialist_http_error": ("The specialist answered Kovrex with an HTTP error.", "no"), "specialist_refused_kovrex": ("The specialist refused Kovrex itself: a fault between the two of them.", "no"), "specialist_stopped": ("The specialist started answering and stopped.", "incomplete"), "specialist_stalled": ("The specialist went quiet part-way and Kovrex stopped waiting.", "incomplete"), "specialist_not_a2a": ("The specialist sent something Kovrex could not pass on.", "yes"), "specialist_too_large": ("The specialist sent something too large for Kovrex to pass on.", "yes"), "specialist_file_too_large": ("The specialist's answer had a file over 25 MB, so it stopped there.", "yes"), "specialist_file_type_not_allowed": ("The specialist's answer had a file of a type Kovrex does not carry.", "yes"), "specialist_file_type_mismatch": ("The specialist's answer had a file whose bytes are not its type.", "yes"), "specialist_file_empty": ("The specialist's answer had an empty file.", "yes"), "specialist_too_many_files": ("The specialist's answer had more than 5 files.", "yes"), "specialist_message_files_too_large": ("The specialist's answer had more than 50 MB of files.", "yes"), "specialist_storage_full": ("Your person's file storage is full, so a file in the answer was refused.", "yes"), "specialist_files_off": ("Kovrex is not carrying files right now, so a file in the answer was refused.", "yes"), "kovrex_fault": ("Something failed inside Kovrex.", "unknown"), "specialist_error": ("The specialist itself refused.", "yes"), "too_soon": ("I asked about an unfinished task less than a minute after the last time.", "no"), "job_ended": ("That long-running job has already ended, so there is nothing to cancel.", "no"), } # For errors that carry no kovrex_reason, or one this assistant does not know. CODES = { -32005: ("A part or a file of the message was refused.", "no"), -32602: ("Kovrex did not accept the conversation or task ID. Start a new one with --new.", "no"), -32001: ("Kovrex knows no such task.", "no"), -32002: ("The task has already finished, so it cannot be canceled.", "no"), -32029: ("I asked about an unfinished task too soon after the last time.", "no"), -32004: ("Kovrex does not carry that, or cannot just now.", "no"), -32009: ("The A2A-Version header was missing or wrong.", "no"), -32603: ("Something failed between Kovrex and the specialist.", "unknown"), -32006: ("The specialist's answer did not come through whole.", "yes"), } DELIVERED = { "no": "Your message was NOT delivered.", "yes": "Your message WAS delivered.", "incomplete": "Your message WAS delivered, but the answer is incomplete.", "unknown": "It is NOT KNOWN whether your message was delivered.", } def address_of(specialist: str) -> str: """`https://kovrex.ai/kovrex-test/echo` and `kovrex.ai/kovrex-test/echo` -> `kovrex-test/echo`.""" text = specialist.strip() for scheme in ("https://", "http://"): if text.startswith(scheme): text = text[len(scheme):] for host in {"kovrex.ai", KOVREX.split("://", 1)[-1]}: if text.startswith(host + "/"): text = text[len(host) + 1:] return text.strip("/") def pick_specialist(named, state: dict): chosen = named or state.get("request", {}).get("specialist") return address_of(chosen) if chosen else None def http_refusal(status: int, raw: bytes, header_id): """A refusal before the request was read as A2A (or a JSON-RPC error, if that is what came).""" try: reply = json.loads(raw) except ValueError: reply = {} if isinstance(reply, dict) and "jsonrpc" in reply and isinstance(reply.get("error"), dict): return rpc_refusal(reply["error"], header_id) error = reply.get("error", {}) if isinstance(reply, dict) else {} if not isinstance(error, dict): error = {} code = error.get("code", "") if status == 413: what = "The message was larger than 1 MB." else: what = HTTP_REFUSALS.get(code, "Kovrex refused the request.") return { "label": f"HTTP {status} {code}".strip(), "what": what, "detail": error.get("message", ""), # Refused before it was read, so nothing was passed on. "delivered": "no", "request_id": error.get("request_id") or header_id, } def rpc_refusal(error: dict, header_id): """A JSON-RPC error, alone or as the last event of a stream.""" data = error.get("data") or [] if isinstance(data, dict): data = [data] metadata = {} for entry in data: if isinstance(entry, dict) and isinstance(entry.get("metadata"), dict): metadata = entry["metadata"] break reason = metadata.get("kovrex_reason") code = error.get("code") what, delivered = REASONS.get(reason) or CODES.get(code) or ("Kovrex reported an error.", "unknown") return { "label": f"error {code} {reason or ''}".strip(), "what": what, "detail": error.get("message", ""), "delivered": delivered, "request_id": metadata.get("request_id") or header_id, # Present when the specialist failed: the conversation holding the message and the failure. "context_id": metadata.get("context_id"), # Present when I asked again too soon: how many seconds to wait. "retry_after": metadata.get("retry_after_seconds"), } def lost(error, delivered: str): return { "label": "no reply", "what": "I could not reach Kovrex, or lost the connection to it.", "detail": str(error), "delivered": delivered, "request_id": None, } def say_refusal(refusal: dict, sent_message: bool) -> None: print(f"Refused ({refusal['label']}): {refusal['what']}") if refusal["detail"]: print(f"Kovrex said: {refusal['detail']}") if sent_message: print(DELIVERED[refusal["delivered"]]) def say_conversation(context) -> None: """The conversation's ID on Kovrex: what `record` reads, and what to quote with the request ID.""" if context: print(f"Conversation: {context}") def say_request_id(request_id) -> None: print(f"Kovrex request ID: {request_id or '(none received)'}") def open_relay(address: str, method: str, params: dict, stream: bool = False): """One A2A request to the specialist's address on Kovrex. Returns (response, None) or (None, refusal).""" body = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params} request = urllib.request.Request(KOVREX + "/" + address, method="POST") request.add_header("Authorization", "Bearer " + token(load_key())) # a fresh token every request request.add_header("Content-Type", "application/json") request.add_header("A2A-Version", "1.0") request.add_header("User-Agent", "Kovrex-Stand-In-Assistant/1") if stream: request.add_header("Accept", "text/event-stream") try: return urllib.request.urlopen(request, data=json.dumps(body).encode(), timeout=RELAY_TIMEOUT), None except urllib.error.HTTPError as error: return None, http_refusal(error.code, error.read(), error.headers.get("Kovrex-Request-Id")) except TimeoutError as error: return None, lost(error, "unknown") except urllib.error.URLError as error: timed_out = isinstance(error.reason, TimeoutError) return None, lost(error.reason, "unknown" if timed_out else "no") except OSError as error: return None, lost(error, "unknown") def text_of(parts) -> str: return "".join(part.get("text", "") for part in parts or [] if isinstance(part, dict)) # --- the guide's section on files ----------------------------------------------------- # The types Kovrex carries, by what a file's name ends in. FILE_TYPES = { ".pdf": "application/pdf", ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".txt": "text/plain", ".md": "text/markdown", ".csv": "text/csv", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", } FILES_DIR = DATA_DIR / "downloads" FILE_READ_LIMIT = 30_000_000 # a little over the 25 MB Kovrex allows one file def file_part(path: str) -> dict: """A part that holds a file: its bytes in base64, a filename, and a mediaType.""" file = Path(path) media_type = FILE_TYPES.get(file.suffix.lower()) if media_type is None: raise ValueError(f"{file.name}: Kovrex carries only {', '.join(sorted(FILE_TYPES))} files.") return { "raw": base64.b64encode(file.read_bytes()).decode(), "filename": file.name, "mediaType": media_type, } def files_of(parts): """The parts that stand for files: an address, with name, type, size and sha256.""" return [part for part in parts or [] if isinstance(part, dict) and isinstance(part.get("url"), str)] def read_file(part: dict): """Read one file with a signed GET, check its SHA-256, and keep it under assistant-data/downloads. Returns a line saying what happened.""" url = part["url"] name = os.path.basename(str(part.get("filename") or "file")) or "file" name = "".join(c if c.isalnum() or c in "._- " else "_" for c in name)[:80].strip(". ") or "file" if not url.startswith(KOVREX + "/v1/files/"): return f" file {name}: not one of Kovrex's file addresses, so I did not fetch it." request = urllib.request.Request(url, method="GET") request.add_header("Authorization", "Bearer " + token(load_key())) # a fresh token every read request.add_header("User-Agent", "Kovrex-Stand-In-Assistant/1") try: with urllib.request.urlopen(request, timeout=60) as response: data = response.read(FILE_READ_LIMIT + 1) sent_hash = response.headers.get("X-Content-SHA256", "") except urllib.error.HTTPError as error: return f" file {name}: Kovrex answered {error.code}, so I could not read it." except (urllib.error.URLError, OSError) as error: return f" file {name}: I could not reach Kovrex to read it ({error})." actual = hashlib.sha256(data).hexdigest() expected = (part.get("metadata") or {}).get("sha256") if len(data) > FILE_READ_LIMIT or actual != expected or actual != sent_hash: return f" file {name}: NOT kept. Its SHA-256 does not match what the specialist's answer said." FILES_DIR.mkdir(parents=True, exist_ok=True) saved = FILES_DIR / f"{uuid.uuid4().hex[:8]}-{name}" saved.write_bytes(data) return f" file {name} ({part.get('mediaType', 'unknown type')}, {len(data)} bytes, SHA-256 checked) saved to {saved}" class Heard: """What has come back so far for one message.""" def __init__(self): self.context = None self.task = None self.state = None self.events = 0 self.got_message = False self.refusal = None self.midline = False # the last thing printed did not end its line self.artifact = None # the artifact whose pieces are being printed self.deferred = None # what Kovrex said about a long-running job, if anything def out(self, text: str, own_line: bool = False) -> None: if not text: return if own_line and self.midline: print() self.midline = False print(text, end="", flush=True) self.midline = not text.endswith("\n") if own_line and self.midline: print(flush=True) self.midline = False def files(self, parts) -> None: """Read every file a specialist put in these parts.""" for part in files_of(parts): self.out(read_file(part) + "\n", own_line=True) def status(self, status: dict) -> None: self.state = status.get("state", self.state) message = status.get("message") if isinstance(message, dict): self.out(text_of(message.get("parts")), own_line=True) self.files(message.get("parts")) def take(self, reply: dict, header_id) -> str: """Act on one JSON-RPC reply. Returns a word for the timing line.""" self.events += 1 if "error" in reply: self.refusal = rpc_refusal(reply["error"], header_id) return "error" result = reply.get("result") or {} if "artifactUpdate" in result: update = result["artifactUpdate"] self.context = update.get("contextId", self.context) self.task = update.get("taskId", self.task) artifact = update.get("artifact", {}) if artifact.get("artifactId") != self.artifact: if self.midline: # a different artifact starts on its own line self.out("\n") self.artifact = artifact.get("artifactId") self.out(text_of(artifact.get("parts"))) self.files(artifact.get("parts")) return "artifactUpdate" if "statusUpdate" in result: update = result["statusUpdate"] self.context = update.get("contextId", self.context) self.task = update.get("taskId", self.task) self.status(update.get("status", {})) self.note_deferral(update.get("metadata")) return f"statusUpdate {self.state}" if "message" in result: message = result["message"] self.context = message.get("contextId", self.context) self.got_message = True self.out(text_of(message.get("parts")), own_line=True) self.files(message.get("parts")) return "message" if "task" in result: self.whole_task(result["task"]) return f"task {self.state}" return "unrecognised" def note_deferral(self, metadata) -> None: """Keep what Kovrex says about a long-running job: the fields of the guide's extension.""" fields = (metadata or {}).get(DEFERRED) if isinstance(metadata, dict) else None if isinstance(fields, dict) and fields.get("deferred") is True: self.deferred = fields def whole_task(self, found: dict) -> None: self.context = found.get("contextId", self.context) self.task = found.get("id", self.task) self.note_deferral(found.get("metadata")) for artifact in found.get("artifacts") or []: self.out(text_of(artifact.get("parts")), own_line=True) self.files(artifact.get("parts")) self.status(found.get("status", {})) def seconds_in_words(seconds) -> str: seconds = int(round(float(seconds))) if seconds < 90: return f"{seconds} seconds" if seconds < 90 * 60: return f"{round(seconds / 60)} minutes" return f"{round(seconds / 3600)} hours" def say_deferred(fields: dict) -> None: """What a person should be told about a long-running job (the guide's "What a deferred answer looks like"): it is deferred, the estimate, when Kovrex ends it by itself, and when and how to check.""" print("DEFERRED: the specialist will answer later, not now.") estimate = fields.get("estimate_seconds") print(f" Its estimate: {'about ' + seconds_in_words(estimate) if estimate is not None else 'none given'}" f"{' (cut to the 24-hour limit)' if fields.get('estimate_cut') else ''}.") print(f" Kovrex ends the job by itself at {fields.get('ends_at')}, if it is not finished" f"{' (the 24-hour limit applies)' if fields.get('limit_applied') else ''}.") if fields.get("latest_progress"): print(f" Latest note from the specialist: {fields['latest_progress']}") if fields.get("state", "open") == "open": print(f" Check again in about {seconds_in_words(fields.get('check_again_after_seconds', CHECK_FLOOR))}" f" (never more than once a minute): run `task`, or `task --wait`.") print(" Kovrex never calls me. Any assistant of my person's can collect the result; `jobs` lists them.") def save_conversation(address: str, heard: Heard, incomplete: bool) -> None: """Keep the conversation for this specialist, leaving everything else in the state alone.""" if not heard.context: return state = read_state() state.setdefault("conversations", {})[address] = { "contextId": heard.context, "taskId": heard.task, "state": heard.state, "incomplete": incomplete, } write_state(state) def talk(args) -> int: # `talk kovrex-test/echo "hello"` is the same as `talk "hello" --specialist kovrex-test/echo`. words = args.text if isinstance(args.text, list) else [args.text] if len(words) == 2 and "/" in words[0] and " " not in words[0] and not args.specialist: args.specialist, args.text = words[0], words[1] else: args.text = " ".join(words) state = read_state() address = pick_specialist(args.specialist, state) if not address: print("I do not know which specialist to talk to. Use `connect` first, or --specialist.") return 1 saved = {} if args.new else state.get("conversations", {}).get(address, {}) parts = [{"text": args.text}] try: parts += [file_part(path) for path in args.file or []] except (OSError, ValueError) as error: print(f"I cannot send that file: {error}") return 1 message = {"messageId": str(uuid.uuid4()), "role": "ROLE_USER", "parts": parts} if saved.get("contextId"): message["contextId"] = saved["contextId"] answering = saved.get("state") == "TASK_STATE_INPUT_REQUIRED" and saved.get("taskId") if answering: message["taskId"] = saved["taskId"] # this answers the specialist's question stream = not args.no_stream started = time.monotonic() def timing(what: str) -> None: if args.timing: print(f"[+{time.monotonic() - started:6.2f}s] {what}", file=sys.stderr, flush=True) heard = Heard() request_id = None response, refusal = open_relay( address, "SendStreamingMessage" if stream else "SendMessage", {"message": message}, stream ) if refusal: timing("refused") heard.refusal = refusal else: request_id = response.headers.get("Kovrex-Request-Id") try: with response: if "text/event-stream" in (response.headers.get("Content-Type") or ""): for raw in response: # one line at a time, as it arrives line = raw.decode("utf-8", "replace").rstrip("\r\n") if not line.startswith("data:"): continue # blank lines, `:` comments, `id:` timing(heard.take(json.loads(line[5:]), request_id)) if heard.refusal: break # an error is always the last event else: timing(heard.take(json.loads(response.read()), request_id)) except (OSError, ValueError) as error: # cut off, timed out, or not JSON timing("lost") heard.refusal = lost(error, "incomplete" if heard.events else "unknown") heard.refusal["request_id"] = request_id if heard.midline: print() finished = heard.state in FINAL_STATES or heard.state in ( "TASK_STATE_INPUT_REQUIRED", "TASK_STATE_AUTH_REQUIRED" ) deferred = heard.deferred is not None and heard.state == "TASK_STATE_WORKING" cut_short = (stream and not heard.refusal and not finished and not heard.got_message and not deferred) or heard.events == 0 incomplete = cut_short or bool(heard.refusal and heard.refusal["delivered"] == "incomplete") plain = heard.got_message and heard.task is None if heard.context: # only what Kovrex itself gave back is kept if plain and saved.get("contextId") == heard.context: # A plain message came back: keep what is known of the last task. heard.task, heard.state = saved.get("taskId"), saved.get("state") save_conversation(address, heard, incomplete) print() if heard.refusal: say_refusal(heard.refusal, sent_message=True) if incomplete and heard.events > 1: print("What is printed above is only part of the answer.") say_conversation(heard.context or heard.refusal.get("context_id")) say_request_id(heard.refusal["request_id"] or request_id) return 1 code = 0 if cut_short and heard.events == 0: print("Kovrex sent nothing back. It is NOT KNOWN whether your message was delivered.") code = 1 elif cut_short: print("The stream ended before the task finished. The answer above is incomplete. Run `task` to check.") code = 1 elif deferred: say_deferred(heard.deferred) elif plain or heard.state is None: print("The specialist replied with a message. No task is open for it.") else: print(STATE_WORDS.get(heard.state, f"The task is in a state I do not know: {heard.state}")) if heard.state in FINAL_STATES - {"TASK_STATE_COMPLETED"} or heard.state not in STATE_WORDS: code = 1 elif not finished: print("Run `task` to check on it.") say_conversation(heard.context) say_request_id(request_id) return code def read_task(address: str, saved: dict, method: str): """One GetTask or CancelTask. Returns (what was heard, refusal, request ID).""" response, refusal = open_relay(address, method, {"id": saved["taskId"]}) request_id = None heard = Heard() heard.context, heard.task, heard.state = saved.get("contextId"), saved["taskId"], None if not refusal: request_id = response.headers.get("Kovrex-Request-Id") try: with response: reply = json.loads(response.read()) if "error" in reply: refusal = rpc_refusal(reply["error"], request_id) else: result = reply.get("result") or {} # "The result is the task itself": accept it bare, or wrapped as SendMessage wraps it. heard.whole_task(result["task"] if isinstance(result.get("task"), dict) else result) except (OSError, ValueError) as error: refusal = lost(error, "unknown") return heard, refusal, request_id def task(args) -> int: state = read_state() address = pick_specialist(args.specialist, state) saved = state.get("conversations", {}).get(address, {}) if address else {} if not saved.get("taskId"): print("There is no task to read. Use `talk` first.") return 1 method = "CancelTask" if args.cancel else "GetTask" deadline = time.monotonic() + args.minutes * 60 while True: heard, refusal, request_id = read_task(address, saved, method) if refusal and refusal.get("retry_after") and args.wait and time.monotonic() < deadline: # "Once a minute": Kovrex says when to ask again, and I do as it says. pause = max(1.0, float(refusal["retry_after"])) print(f"Too soon. Kovrex says to ask again in {seconds_in_words(pause)}. Waiting.") time.sleep(pause) continue if refusal: say_refusal(refusal, sent_message=False) if args.cancel: print("The task was NOT canceled, as far as I can tell.") say_request_id(refusal["request_id"] or request_id) return 1 if heard.state is None: print("Kovrex answered, but did not say what state the task is in.") say_request_id(request_id) return 1 save_conversation(address, heard, incomplete=False) print(STATE_WORDS.get(heard.state, f"The task is in a state I do not know: {heard.state}")) if heard.deferred and heard.state == "TASK_STATE_WORKING": say_deferred(heard.deferred) elif heard.deferred and heard.state in FINAL_STATES: ended = heard.deferred.get("ended_by") print(f" The long-running job ended: {ended or heard.deferred.get('state', 'finished')}.") say_request_id(request_id) waiting = args.wait and heard.state not in FINAL_STATES and heard.state != "TASK_STATE_INPUT_REQUIRED" if not waiting or time.monotonic() >= deadline: break pause = max(float(CHECK_FLOOR), float((heard.deferred or {}).get("check_again_after_seconds") or CHECK_FLOOR)) print(f"Checking again in {seconds_in_words(pause)}, as Kovrex advises.") time.sleep(pause) print() if args.cancel and heard.state != "TASK_STATE_CANCELED": return 1 if args.wait and heard.state not in FINAL_STATES: print("Still not finished when I stopped waiting.") return 1 return 0 JOB_WORDS = { "open": "OPEN", "completed": "finished", "failed": "failed", "canceled": "cancelled", "rejected": "declined", } def jobs(args) -> int: """The guide's list_jobs tool: my person's long-running jobs, from any assistant.""" arguments = {} if args.specialist: arguments["specialist"] = address_of(args.specialist) found, refusal, request_id = memory_tool("list_jobs", arguments) if refusal: say_memory_refusal(refusal, changing=False, request_id=request_id) return 1 listed = found.get("jobs") or [] if not listed: print("Your person has no open long-running jobs, and none that ended in the last 7 days.") for job in listed: word = JOB_WORDS.get(job.get("state"), job.get("state")) print(f"{word}: {job.get('specialist_name')} ({job.get('specialist')}), asked by {job.get('asked_by')}") print(f" task {job.get('task_id')} in conversation {job.get('conversation_id')}") estimate = job.get("expected_seconds") print(f" started {when(job.get('started_at'))}; estimate " f"{'about ' + seconds_in_words(estimate) if estimate is not None else 'none'}; " f"ends by itself {when(job.get('ends_at'))}") if job.get("latest_progress"): print(f" latest note: {job['latest_progress']}") if job.get("state") == "open": print(f" check again in about {seconds_in_words(job.get('check_again_after_seconds') or CHECK_FLOOR)}") else: by = job.get("ended_by") print(f" ended {when(job.get('ended_at'))}" + (f", by {by}" if by else "")) if job.get("state") == "completed": if job.get("collected"): print(f" result collected by {job.get('collected_by')} at {when(job.get('collected_at'))}") else: print(" result NOT collected yet: run `task` for it") say_request_id(request_id) return 0 def card(args) -> int: address = pick_specialist(args.specialist, read_state()) if not address: print("I do not know which specialist you mean. Name one, such as kovrex-test/echo.") return 1 # Anyone may read the card; it needs no token. status, found = call("GET", f"/{address}/.well-known/agent-card.json") if status != 200 or not isinstance(found, dict): print(explain(status, found if isinstance(found, dict) else {})) return 1 print(f"{found.get('name', '(no name)')}: {found.get('description', '(no description)')}") interfaces = found.get("supportedInterfaces") or [{}] print(f"Requests go to: {interfaces[0].get('url', '(not given)')}") skills = found.get("skills") or [] print("Skills:" if skills else "Skills: none listed.") for skill in skills: if isinstance(skill, dict): name = skill.get("name") or skill.get("id") or "(unnamed)" about = skill.get("description") print(f" - {name}: {about}" if about else f" - {name}") else: print(f" - {skill}") terms = None for entry in (found.get("capabilities") or {}).get("extensions") or []: if isinstance(entry, dict) and entry.get("uri") == "https://kovrex.ai/ext/terms/v1": # The guide does not say where in the entry the terms sit: look in it and one level down. places = [entry] + [value for value in entry.values() if isinstance(value, dict)] terms = next((place for place in places if "price" in place or "terms" in place), None) if terms is None: print("The card carries no Kovrex terms entry, so I cannot say what your person would be agreeing to.") return 1 print("What your person would be agreeing to:") if terms.get("publisher"): print(f" Published by: {terms['publisher']}") price = terms.get("price") or {} print(f" Price: {price.get('text', '(not given)')}" + (f" ({price['kind']})" if price.get("kind") else "")) memory = terms.get("memory") or {} if "days" in memory: holder = f", held by {memory['held_by']}" if memory.get("held_by") else "" print(f" Memory: it remembers your person for {memory['days']} days{holder}") else: print(" Memory: (not given)") link = terms.get("terms") or {} version = f" (version {link['version']})" if "version" in link else "" print(f" Terms{version}: {link.get('url', '(no link given)')}") return 0 # --- "What a specialist remembers" in the guide -------------------------------------- MCP_VERSION = "2025-11-25" MEMORY_TIMEOUT = 30 # seconds; the guide gives no figure # "When a tool refuses": the guide gives the reason only as text, so the text is what is matched. TOOL_REFUSALS = [ ("There is no such memory", "Kovrex knows no memory of yours with that ID. Run `memory` to see the IDs."), ("That memory has already been answered", "That one has already been answered. Only a suggestion can be kept or discarded, and only once."), ("Your person has not accepted that specialist's terms", "You have not accepted that specialist's terms. Ask with `another`."), ("A memory needs some text", "The new text was empty. A memory needs some text."), ("A memory can be at most 2,000 characters", "The new text was too long. A memory can be at most 2,000 characters."), ] # The section's "Other answers", by HTTP status. MEMORY_HTTP = { 401: "Kovrex did not accept this assistant's token. It may not be connected, " "or your person may have disconnected it.", 406: "Kovrex did not accept this assistant's Accept header. That is a fault in this assistant.", 413: "The request was larger than 256 KB.", 415: "Kovrex did not accept this assistant's Content-Type header. That is a fault in this assistant.", 429: "Too many calls in a minute. Wait before trying again.", 503: "Kovrex cannot read memories right now.", } # What each tool answers when it worked, and what that means for the person. MEMORY_ACTIONS = { "keep": ("keep_memory", "kept", "Kept, because you told me to. The specialist is given this memory from now on. " "Kovrex has recorded that I kept it and asks you to confirm or delete it at https://kovrex.ai/memory."), "discard": ("discard_memory", "discarded", "Discarded. The specialist will never be given it."), "correct": ("correct_memory", "corrected", "Corrected. The memory now holds your wording."), "delete": ("delete_memory", "deleted", "Deleted. The memory is removed, not hidden."), } def memory_refusal(label: str, what: str, detail: str = "", request_id=None, done: str = "no") -> dict: return {"label": label, "what": what, "detail": detail, "request_id": request_id, "done": done} def memory_tool(name: str, arguments: dict): """Call one of Kovrex's memory tools. Returns (structured answer, refusal, request ID).""" body = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": arguments}} request = urllib.request.Request(KOVREX + "/mcp", method="POST") request.add_header("Authorization", "Bearer " + token(load_key())) # a fresh token every request request.add_header("Content-Type", "application/json") request.add_header("Accept", "application/json, text/event-stream") request.add_header("MCP-Protocol-Version", MCP_VERSION) request.add_header("User-Agent", "Kovrex-Stand-In-Assistant/1") request_id = None try: with urllib.request.urlopen(request, data=json.dumps(body).encode(), timeout=MEMORY_TIMEOUT) as response: request_id = response.headers.get("Kovrex-Request-Id") raw = response.read() except urllib.error.HTTPError as error: request_id = error.headers.get("Kovrex-Request-Id") raw = error.read() try: found = json.loads(raw) except ValueError: found = None # 406 and 415 are plain text inner = found.get("error") if isinstance(found, dict) else None if not isinstance(inner, dict): inner = {} code = inner.get("code", "") detail = inner.get("message") or ("" if found is not None else raw.decode("utf-8", "replace").strip()) what = MEMORY_HTTP.get(error.code, "Kovrex refused the request.") if error.code == 503 and code != "memory_off": what = "Kovrex is not available right now." if error.code == 429 and error.headers.get("Retry-After"): what += f" Kovrex says to wait {error.headers['Retry-After']} seconds." return None, memory_refusal( f"HTTP {error.code} {code}".strip(), what, detail, inner.get("request_id") or request_id ), request_id except TimeoutError as error: return None, memory_refusal("no reply", "Kovrex did not answer in time.", str(error), done="unknown"), None except urllib.error.URLError as error: timed_out = isinstance(error.reason, TimeoutError) return None, memory_refusal( "no reply", "Kovrex did not answer in time." if timed_out else "I could not reach Kovrex.", str(error.reason), done="unknown" if timed_out else "no", ), None except OSError as error: return None, memory_refusal( "no reply", "I lost the connection to Kovrex.", str(error), request_id, done="unknown" ), request_id try: reply = json.loads(raw) except ValueError: reply = None if not isinstance(reply, dict): return None, memory_refusal( "unreadable", "Kovrex answered with something that is not JSON.", "", request_id, done="unknown" ), request_id if isinstance(reply.get("error"), dict): # a JSON-RPC error, such as "tool not found" error = reply["error"] message = str(error.get("message", "")) if "tool not found" in message.lower(): what = f"Kovrex has no tool called {name}." else: what = "Kovrex did not accept the request." return None, memory_refusal(f"error {error.get('code')}", what, message, request_id), request_id result = reply.get("result") if not isinstance(result, dict): return None, memory_refusal( "unreadable", "Kovrex's answer had no result in it.", "", request_id, done="unknown" ), request_id content = result.get("content") or [] text = content[0].get("text", "") if content and isinstance(content[0], dict) else "" if result.get("isError"): # the tool refused, with the reason as text plain = text.replace("’", "'") what = next((ours for theirs, ours in TOOL_REFUSALS if theirs in plain), "The tool refused.") return None, memory_refusal("tool refused", what, text, request_id), request_id structured = result.get("structuredContent") if not isinstance(structured, dict): try: # "content[0].text holds the same thing as a string" structured = json.loads(text) except ValueError: structured = None if not isinstance(structured, dict): return None, memory_refusal( "unreadable", "Kovrex's answer did not hold what the guide says it should.", "", request_id, done="unknown", ), request_id return structured, None, request_id def say_memory_refusal(refusal: dict, changing: bool, request_id) -> None: print(f"Refused ({refusal['label']}): {refusal['what']}") if refusal["detail"]: said = "The error was" if refusal["label"] == "no reply" else "Kovrex said" print(f"{said}: {refusal['detail']}") if changing and refusal["done"] == "no": print("Nothing was changed.") elif changing: print("It is NOT KNOWN whether anything was changed. Run `memory` to see.") if refusal["request_id"] or request_id: say_request_id(refusal["request_id"] or request_id) def when(stamp) -> str: """`2026-12-18T09:15:40Z` -> `18 December 2026, 09:15 UTC`.""" if not isinstance(stamp, str) or not stamp: return "(no time given)" try: found = datetime.datetime.fromisoformat(stamp.replace("Z", "+00:00")) except ValueError: return stamp if found.utcoffset() != datetime.timedelta(0): return stamp return f"{found.day} {found:%B %Y}, {found:%H:%M} UTC" def memory_list(args) -> int: address = pick_specialist(args.specialist, read_state()) if not address: print("I do not know which specialist you mean. Use `connect` first, or --specialist.") return 1 found, refusal, request_id = memory_tool("list_memories", {"specialist": address}) if refusal: say_memory_refusal(refusal, changing=False, request_id=request_id) return 1 name = found.get("specialist") or address held_by = found.get("held_by") kept = found.get("kept") or [] suggestions = found.get("suggestions") or [] code = 0 if held_by == "specialist": print(f"{name} keeps its own memory of you. Kovrex cannot show it to you or delete it.") print("That does not mean nothing is remembered: the publisher holds it, not Kovrex.") elif held_by == "kovrex": print(f"Kovrex holds what {name} remembers about you. You decide what is kept.") else: print(f"Kovrex did not say who holds what {name} remembers (held_by: {held_by!r}).") code = 1 if found.get("statement"): print(f"Kovrex said: {found['statement']}") if held_by == "specialist" and not kept and not suggestions: if request_id: say_request_id(request_id) return code print() if kept: print(f"Kept ({len(kept)}). The specialist is given these when it asks:") else: print("Kept: nothing. The specialist is given nothing about you.") for memory in kept: print(f" - {memory.get('text', '(no text)')}") print(f" ID: {memory.get('id', '(none)')}") if memory.get("forgotten_after"): print(f" Given to the specialist until {when(memory['forgotten_after'])}.") else: print(" Kovrex did not say when the specialist stops being given this.") if memory.get("corrected"): print(" Corrected: this is your wording, not the specialist's.") if memory.get("kept_by"): print(f" Kept by: {memory['kept_by']}.") if memory.get("awaiting_review"): print(" Waiting for you: an assistant kept this. Confirm or delete it at https://kovrex.ai/memory.") print() if suggestions: print(f"Suggestions waiting for your answer ({len(suggestions)}). Not remembered unless you keep them:") else: print("Suggestions waiting for your answer: none.") for memory in suggestions: print(f" - {memory.get('text', '(no text)')}") print(f" ID: {memory.get('id', '(none)')}") print(f" Suggested {when(memory.get('created_at'))}.") if memory.get("corrected"): print(" Corrected: this is your wording, not the specialist's.") if suggestions: print(" Answer one with `memory keep ID` or `memory discard ID`.") print("You can also see and change all of this yourself at https://kovrex.ai/memory") if request_id: say_request_id(request_id) return code def memory(args) -> int: if not args.action: if args.id or args.text is not None: print("Say what to do: `memory keep ID`, `discard ID`, `delete ID`, or `correct ID \"new text\"`.") return 1 return memory_list(args) tool_name, expected, said = MEMORY_ACTIONS[args.action] if not args.id: print(f"Which one? Give the memory's ID: `memory {args.action} ID`. Run `memory` to see the IDs.") return 1 arguments = {"id": args.id} if args.action == "correct": if args.text is None: print('Give the new wording: `memory correct ID "new text"`.') return 1 arguments["text"] = args.text elif args.text is not None: print(f"`memory {args.action}` takes only an ID.") return 1 found, refusal, request_id = memory_tool(tool_name, arguments) if refusal: say_memory_refusal(refusal, changing=True, request_id=request_id) return 1 code = 0 if found.get("result") == expected: print(said) else: print(f"Kovrex answered, but not with \"{expected}\": it said {found.get('result')!r}.") print("It is NOT KNOWN whether anything was changed. Run `memory` to see.") code = 1 print(f"Memory ID: {found.get('id', args.id)}") if request_id: say_request_id(request_id) return code # --- "Reading the record" in the guide ------------------------------------------------ FROM_WORDS = {"assistant": "assistant ->", "specialist": "specialist <-", "kovrex": "kovrex !!"} def record(args) -> int: """Print what Kovrex stored for a conversation, in order, as its owner may read it.""" state = read_state() if args.list: arguments = {} if args.specialist: arguments["specialist"] = address_of(args.specialist) found, refusal, request_id = memory_tool("list_conversations", arguments) if refusal: say_memory_refusal(refusal, changing=False, request_id=request_id) return 1 if not found.get("conversations"): print("Kovrex holds no conversations for your person yet.") for one in found.get("conversations", []): print(f"{one['id']} {one['specialist']} {one['events']} events " f"started by {one['started_by']} last activity {when(one['last_event_at'])}") say_request_id(request_id) return 0 conversation = args.conversation if not conversation: address = address_of(pick_specialist(args.specialist, state) or "") conversation = state.get("conversations", {}).get(address, {}).get("contextId") if not conversation: print("I have no conversation saved. Run `talk` first, or give a conversation's ID, or use `record --list`.") return 1 found, refusal, request_id = memory_tool("get_conversation", {"id": conversation}) if refusal: say_memory_refusal(refusal, changing=False, request_id=request_id) return 1 about = found["conversation"] print(f"Conversation {about['id']} with {about['specialist_name']} ({about['specialist']})") print(f"Started {when(about['started_at'])} by {about['started_by']}. {about['events']} events, in the order Kovrex saw them.") print() for event in found["events"]: clock = event["at"][11:19] what = event["kind"] + (f" [{event['state']}]" if event.get("state") else "") said = f" {event['text']!r}" if event.get("text") is not None else "" print(f"{event['number']:>6} {clock} {FROM_WORDS.get(event['from'], event['from']):<13} {what:<28}{said}") for file in event.get("files", []): print(f"{'':>6} {'':8} {'':<13} file: {file.get('name', '(not openable just now)')} " f"({file['media_type']}, {file['size']} bytes) from the {file['from']}, at {file['address']}") print() say_request_id(request_id) return 0 def main() -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) commands = parser.add_subparsers(dest="command", required=True) c = commands.add_parser("connect", help="ask to connect your person to a specialist") c.add_argument("--name", required=True, help="your person's name") c.add_argument("--email", required=True, help="your person's email") c.add_argument("--specialist", required=True, help="such as kovrex-test/echo") c.add_argument("--label", default="Stand-in Assistant", help="what your person calls you") c.set_defaults(run=connect) commands.add_parser("status", help="has your person answered?").set_defaults(run=status) w = commands.add_parser("wait", help="keep checking until your person answers") w.add_argument("--minutes", type=float, default=15) w.add_argument("--every", type=float, default=60, help="seconds between checks") w.set_defaults(run=wait) commands.add_parser("resend", help="send the email again").set_defaults(run=resend) a = commands.add_parser("another", help="ask for a further specialist, once connected") a.add_argument("specialist") a.set_defaults(run=another) k = commands.add_parser("card", help="what a specialist is, and its price, memory and terms") k.add_argument("specialist", nargs="?", help="defaults to the one you asked to connect to") k.set_defaults(run=card) t = commands.add_parser("talk", help="send one message to a specialist and print the answer") t.add_argument("text", nargs="+", help='the message; or a specialist\'s address and then the message') t.add_argument("--specialist", help="defaults to the one you asked to connect to") t.add_argument("--file", action="append", metavar="PATH", help="send a file with the message (repeat for more; up to 5)") t.add_argument("--new", action="store_true", help="start a new conversation") t.add_argument("--no-stream", action="store_true", help="wait for one whole reply") t.add_argument("--timing", action="store_true", help="print on stderr when each event arrived") t.set_defaults(run=talk) j = commands.add_parser("task", help="read where the last task stands, or cancel it") j.add_argument("--specialist", help="defaults to the one you asked to connect to") j.add_argument("--cancel", action="store_true", help="cancel the task") j.add_argument("--wait", action="store_true", help="keep checking, as often as Kovrex advises, until the task ends") j.add_argument("--minutes", type=float, default=30, help="with --wait: how long to keep checking") j.set_defaults(run=task) r = commands.add_parser("record", help="what Kovrex stored for a conversation, in order") r.add_argument("conversation", nargs="?", help="a conversation's ID; defaults to the last one you talked in") r.add_argument("--specialist", help="whose last conversation; defaults to the one you asked to connect to") r.add_argument("--list", action="store_true", help="list your person's conversations instead") r.set_defaults(run=record) o = commands.add_parser("jobs", help="your person's long-running jobs, whichever assistant asked") o.add_argument("--specialist", help="only jobs with this specialist") o.set_defaults(run=jobs) m = commands.add_parser("memory", help="what a specialist remembers and suggests; keep, discard, correct, delete") m.add_argument("action", nargs="?", choices=sorted(MEMORY_ACTIONS), help="leave out to list") m.add_argument("id", nargs="?", help="the memory's ID, as `memory` prints it") m.add_argument("text", nargs="?", help="for correct: the new wording") m.add_argument("--specialist", help="for the list; defaults to the one you asked to connect to") m.set_defaults(run=memory) args = parser.parse_args() return args.run(args) if __name__ == "__main__": sys.exit(main())