#!/usr/bin/env python3
"""The fixed, stdio Argoni MCP tool surface for one fenced Claude sitting."""
import importlib.machinery
import importlib.util
import json
import os
import re
import signal
import subprocess
import sys

# Never write a cache beside the runner's files: inside the signed app it breaks the seal.
sys.dont_write_bytecode = True

RUNNER = os.path.join(os.path.dirname(__file__), "argoni-runner")
loader = importlib.machinery.SourceFileLoader("argoni_runner_tools", RUNNER)
spec = importlib.util.spec_from_loader(loader.name, loader)
r = importlib.util.module_from_spec(spec)
loader.exec_module(r)

LIMIT = 16 * 1024
SCHEMAS = {
    "search_notes": {"query": (str, 1, 500)},
    "project_status": {"name": (str, 1, 120)},
    "today": {},
    "needs_me": {},
    "file_note": {"text": (str, 1, 4000)},
    "set_reminder": {"text": (str, 1, 500), "at": (str, 1, 100)},
    "propose_standing_order": {"text": (str, 1, 1000)},
    "propose_plan": {"project": (str, 1, 2000)},
}
# Keys a tool may leave out (0435: the reminder's line in Argoni's voice).
OPTIONAL = {"set_reminder": {"title": (str, 1, 80)}}
DESCRIPTIONS = {
    "search_notes": ("Find notes by words and meaning. Each hit names its file and line: open the file with Read "
                     "before you rely on it."),
    "project_status": "Read a project's state, reports, decisions, and next step with sources.",
    "today": "Read today's work and outcomes with sources.",
    "needs_me": "Read what waits for the user now with sources.",
    "file_note": "File a note requested in the current user's own message.",
    "set_reminder": ("Set a one-off reminder requested in the current user's own message. text: what to do, short, "
                     "in the user's words (\"Call my mom\"), never the whole message. at: the time the user said, in "
                     "one of these shapes: \"in 2 hours\", \"in 10 minutes\", \"6:30 pm\", \"9 am tomorrow\", "
                     "\"tomorrow morning\"; a relative time stays relative (never worked out into a clock time). "
                     "title: the line the reminder shows, in your voice: short, to the user, one sentence with a "
                     "full stop, no exclamation mark, keeping their meaning and adding nothing (\"Time to stand up.\" "
                     "for \"stand up\"; \"Call your mom about the dinner.\"); no time, day or number they did not say."),
    "propose_standing_order": "Offer a standing-order card from the current user's own message.",
    "propose_plan": "Offer a plan card for a granted project named in the current user's own message.",
}
CAPABILITIES = {n: "read" if n in ("search_notes", "project_status", "today", "needs_me") else "change" for n in SCHEMAS}


def schema(name):
    every = dict(SCHEMAS[name], **OPTIONAL.get(name, {}))
    return {"type": "object", "properties": {k: {"type": "string", "minLength": lo, "maxLength": hi}
            for k, (_, lo, hi) in every.items()}, "required": list(SCHEMAS[name]), "additionalProperties": False}


def denied(code, reason, action):
    return {"ok": False, "origin": "own_data",
            "refusal": {"code": code, "reason": reason, "action": action}}


def context(path):
    with open(path, encoding="utf-8") as f:
        c = json.load(f)
    if not isinstance(c, dict) or not c.get("turn") or not c.get("data"):
        raise ValueError("no recorded turn is active")
    return c


def valid(name, args):
    shape = SCHEMAS.get(name)
    if shape is None:
        return False
    shape = dict(shape, **{k: v for k, v in OPTIONAL.get(name, {}).items() if isinstance(args, dict) and k in args})
    if not isinstance(args, dict) or set(args) != set(shape):
        return False
    return all(isinstance(args[k], typ) and lo <= len(args[k]) <= hi and "\x00" not in args[k]
               for k, (typ, lo, hi) in shape.items())


def action(c, name, result):
    r.dlog(c["data"], "tools.log.jsonl", {"at": r.now().isoformat(timespec="seconds"),
        "turn": c["turn"], "run": c.get("run"), "budget_left": c.get("budget_left"),
        "tool": name, "capability": CAPABILITIES.get(name, "unknown"),
        "ok": bool(result.get("ok")), "code": (result.get("refusal") or {}).get("code"),
        "origin": result.get("origin", "unknown")})
    return result


def origin(c, path):
    if not r.same_or_under(path, c["data"]):
        return "granted_external_file"
    marks = r.read_json(os.path.join(r.director_dir(c["data"]), "outside.json"), {})
    try:
        identity = (lambda st: (st.st_dev, st.st_ino))(os.stat(path))
        if isinstance(marks, dict):
            for rel in marks:
                try:
                    marked = os.stat(os.path.join(c["data"], rel))
                except OSError:
                    continue
                if (marked.st_dev, marked.st_ino) == identity:
                    return "imported_content"
    except OSError:
        return "unknown"
    return "own_data"


def reader_origin(c, data):
    """Use the worst origin of every file that contributed to a reader result."""
    result = "own_data"
    def check(rel):
        nonlocal result
        if not isinstance(rel, str) or not rel or os.path.isabs(rel) or "\x00" in rel or any(
                part in ("", ".", "..") for part in rel.split("/")):
            result = "unknown"
            return
        found = origin(c, os.path.join(c["data"], rel))
        if found == "unknown" or result == "unknown":
            result = "unknown"
        elif found == "imported_content":
            result = "imported_content"
        elif found != "own_data" and result == "own_data":
            result = found
    def visit(obj):
        if isinstance(obj, dict):
            source = obj.get("source")
            if isinstance(source, dict) and "path" in source:
                check(source["path"])
            if "page" in obj:
                check(obj["page"])
            for child in obj.values():
                visit(child)
        elif isinstance(obj, list):
            for child in obj:
                visit(child)
    visit(data)
    return result


def needs_view(data, hidden):
    """What waits for the user, as the letter counts it (0432): the items the user put off with
    Not now are left out, the needs stay oldest first, and the oldest is named."""
    hidden = {str(k) for k in hidden}
    items = [x for x in data.get("items") or [] if not (isinstance(x, dict) and x.get("key") in hidden)]
    data = dict(data, items=items)
    needs = [x for x in items if isinstance(x, dict) and x.get("kind") == "need"]
    decisions = [x for x in items if isinstance(x, dict) and x.get("kind") == "decision"]
    if data.get("letter"):
        data["counts"] = {"needs": len(needs), "decisions": len(decisions)}
        data["oldest"] = needs[0].get("text") if needs else None
    return data


def dispatch(path, name, args):
    try:
        c = context(path)
    except (OSError, ValueError):
        return denied("no_turn", "I cannot verify this turn.", "Send the message again.")
    if not valid(name, args):
        return action(c, name, denied("schema", "Those details do not fit this action.", "Use shorter, complete details."))
    entry = r.record_find(c["data"], c["turn"])
    if not entry or entry.get("who") != "user":
        return action(c, name, denied("no_turn", "I cannot verify the user's message.", "Send the message again."))
    words = entry.get("text") or ""
    if c.get("read_only") and name not in r.BUSY_ONLY:
        return action(c, name, denied("busy", "I can't do that this minute.", "Send it again in a minute."))
    try:
        if name == "search_notes":
            env = r.engine_env(c["top"], c["engine"], c["data"], c["opts"])
            p = subprocess.run([os.path.join(c["engine"], "bin", "memory"), "find", "-k", "5", "--json", args["query"]],
                               env=env, cwd=c["top"], capture_output=True, text=True, timeout=30)
            if p.returncode:
                raise ValueError("I could not search the notes")
            found = json.loads(p.stdout).get("found") or []
            rows = []
            result_origin = "own_data"
            for hit in found[:5]:
                # 0222: the hit's place, opened with Claude Code's own Read (inside the granted folders only);
                # the narrow open_source and read_file tools are gone.
                at = str(hit.get("file") or "")
                if at and origin(c, at) != "own_data":
                    result_origin = origin(c, at)
                rows.append({"file": at, "line": hit.get("line"),
                             "title": str(hit.get("show") or hit.get("title") or "note")[:120],
                             "excerpt": " ".join(hit.get("lines") or [])[:500]})
            result = {"ok": True, "origin": result_origin, "results": rows}
        elif name in ("project_status", "today", "needs_me"):
            sub = {"project_status": "project", "today": "today", "needs_me": "needs"}[name]
            command = [os.path.join(c["engine"], "bin", "argoni-read"), sub]
            if name == "project_status":
                command.append(args["name"])
            command.append(os.path.dirname(c["data"]))
            p = subprocess.run(command, cwd=c["top"], capture_output=True, text=True, timeout=30,
                               env=r.engine_env(c["top"], c["engine"], c["data"], c["opts"]))
            if p.returncode:
                raise ValueError("I could not read that part of your folder")
            if len(p.stdout.encode("utf-8")) > LIMIT:
                raise ValueError("The reader returned too much text.")
            data = json.loads(p.stdout)
            if name == "needs_me":
                data = needs_view(data, c.get("hidden_needs") or [])
            found = reader_origin(c, data)
            # The letter's items from a project (a report waiting, a decision in a repo) were written
            # from that project's files: they count as a granted folder's text (staff 0432 r1).
            if name == "needs_me" and data.get("letter") and found == "own_data" and any(
                    isinstance(x, dict) and x.get("came_from") in ("project-report", "github", "repo")
                    for x in data.get("items") or []):
                found = "granted_external_file"
            result = {"ok": True, "origin": found, "data": data}
        elif name == "file_note":
            # "do it" to Argoni's own offer ("Want me to save that as a note?"): the note may be what
            # that offer and his message before it said, and nothing else (0435, his choice).
            offered = False
            if r.is_confirmation(words):
                context_words = r.reminder_words(c["data"], entry)
                # Only when Argoni's question offered a note (staff 0435 r1), never after any question.
                offered = context_words != words and re.search(r"(?i)\b(?:note|save|keep|write|remember|file)\b",
                                                               context_words.rsplit("\n", 1)[-1]) is not None and (
                    args["text"] in context_words or r.reminder_text_in_words(args["text"], context_words))
            if not offered and args["text"] not in words:
                return action(c, name, denied("user_words", "This note was not in your message.", "Ask me to save the note in your words."))
            result = {"ok": True, "origin": "own_data", "saved": r.capture(c["data"], args["text"])}
        elif name == "set_reminder":
            confirmed = r.confirmed_reminder_text(c["data"], entry)
            if confirmed:
                # A bare yes approves the task Argoni asked, not a rewording of his raw request.
                prior = r._exchange_before(c["data"], entry)[0].get("text") or ""
                if args["text"].casefold() != confirmed.casefold() and args["text"].casefold() not in prior.casefold():
                    return action(c, name, denied("user_words", "That is not the reminder Argoni asked about.", "Ask for it directly."))
                args = dict(args, text=confirmed, title="Time to %s." % confirmed.rstrip("."))
            # A word the app's spelling check marked in this message (0432, "remind me to stan in a
            # minute" was set as "stan"): Argoni asks "Did you mean …?" first; the user's yes then
            # sets the words of that question (0430's yes path), which carry no marked word.
            # A word Argoni itself said in its last reply ("Call Zaid?") is one the user just saw and
            # answered: it is not asked about again (staff 0432 r1).
            said = r.recent_exchanges(c["data"], c["turn"], 1)
            said = str(said[-1][1].get("text") or "") if said else ""
            def has(word, text):
                return re.search(r"(?<!\w)%s(?!\w)" % re.escape(word), text, re.I) is not None
            unsure = [w for w in c.get("unsure_words") or [] if has(w, args["text"]) and not has(w, said)]
            if unsure:
                return action(c, name, denied("unsure_words", '"%s" may be a typo.' % unsure[0],
                    'Do not set it yet. Ask the user one short question with your best guess, like "Stand up in a minute?", and set it after their yes.'))
            words = r.reminder_words(c["data"], entry)   # a short yes allows what Argoni just asked (0430)
            try:
                spec = r.reminder_tool_spec(args["text"], args["at"], words)
                if args.get("title"):
                    spec["title"] = args["title"]
            except r.Refused:
                # His message holds a marked word ("remnd me to buy dates tmrw at 5"): ask what he
                # meant rather than fail; his yes sets the words of that question (0432).
                if any(has(w, words) for w in c.get("unsure_words") or []):
                    return action(c, name, denied("unsure_words", "Some words in the message may be typos.",
                        'Do not set it yet. Ask the user one short question with your best reading, like "Buy dates for mom tomorrow at 5 PM?", and set it after their yes.'))
                return action(c, name, denied("user_words", "You did not ask for this reminder in this turn.", "Ask me directly to remind you."))
            spec = r.reminder_spec(spec, words)
            # chat-fix (2 Nov): his own message in this turn asks for exactly this reminder (text and time held
            # to its words above): set at once even in a tainted sitting. A follow-up ("yes", "at 3pm") borrows
            # words from Argoni's question, which a tainted turn may have written: still a card.
            if c.get("tainted") and not confirmed:
                # A line in Argoni's voice written in a tainted turn is never kept, set or card (staff 0435 r1).
                spec.pop("title", None)
            if c.get("tainted") and not confirmed and not r.own_reminder_request(c["data"], entry, words, spec.get("text")):
                # The card shows his words only: a line nobody saw is not kept (staff 0435 r1).
                spec.pop("title", None)
                result = {"ok": True, "origin": "own_data", "card": {"kind": "reminder", "spec": spec,
                    "text": args["text"], "token": r.token_make("reminder-card", [r.folder_key(c["data"]), c["turn"], json.dumps(spec, sort_keys=True)]),
                    "actions": ["Set reminder", "Not now"]},
                    # 0433: the reply said "I've set it" while a card waited for his click.
                    "set": False, "note": "Not set yet: the user sees it under your reply and sets it with one click on Set reminder. Say so in one line."}
            else:
                with open(c["pending"], "a", encoding="utf-8") as f:
                    # The title dropped from the spec (a tainted turn) is dropped from the request too, or the
                    # runner's recheck (staged_reminder_matches) refuses what the model was told is queued (staff r1).
                    request = {k: v for k, v in args.items() if k != "title" or "title" in spec}
                    f.write(json.dumps({"turn": c["turn"], "spec": spec, "request": request}, ensure_ascii=False) + "\n")
                result = {"ok": True, "origin": "own_data", "queued": True}
        elif name == "propose_plan":
            import project_plan
            project = args["project"]
            if os.path.basename(os.path.normpath(project)).casefold() not in words.casefold():
                return action(c, name, denied("user_words", "That project was not named in your message.", "Name the project to plan in."))
            card = project_plan.propose(r, c["opts"], c["top"], project, c["turn"])
            result = {"ok": True, "origin": "own_data", "card": card}
        else:
            # 0222: his own message, word for word, is offered as a card even after the chat read a project: the
            # card waits for his Keep, so what the chat read cannot add a rule; only his words reach it.
            if args["text"] != words:
                return action(c, name, denied("user_words", "I can keep only your own words as a rule.", "Say the rule in your own words."))
            card = r.order_card(c["data"], entry, None)
            if not card or card.get("card") != "order":
                return action(c, name, denied("order", "That is not a rule I can offer to keep.", "Use Settings for access or spending rules."))
            result = {"ok": True, "origin": "own_data", "card": card}
        if result.get("origin") == "unknown":
            return action(c, name, denied("origin", "I cannot verify where that file came from.", "Choose another source."))
        if result.get("origin") in ("granted_external_file", "imported_content"):
            c["tainted"] = True
            tmp = path + ".origin"
            with open(tmp, "w", encoding="utf-8") as f:
                json.dump(c, f)
            os.replace(tmp, path)
        return action(c, name, result)
    except (OSError, ValueError, r.Refused, r.Unsafe, subprocess.TimeoutExpired, TimeoutError) as e:
        return action(c, name, denied("refused", str(e)[:180], "Check the request and try again."))


def respond(value):
    sys.stdout.write(json.dumps(value, ensure_ascii=False) + "\n")
    sys.stdout.flush()


def main(path):
    pid_file = os.path.join(os.path.dirname(path), "argoni-tool-server.pid")
    with open(pid_file, "w", encoding="ascii") as f:
        f.write(str(os.getpid()))
    def time_out(*_):
        raise TimeoutError("this tool took too long")
    signal.signal(signal.SIGALRM, time_out)
    for line in sys.stdin:
        req = None
        try:
            req = json.loads(line)
            method, ident = req.get("method"), req.get("id")
            if method == "initialize":
                result = {"protocolVersion": "2024-11-05", "capabilities": {"tools": {}},
                          "serverInfo": {"name": "argoni", "version": "23"}}
            elif method == "tools/list":
                result = {"tools": [{"name": n, "description": DESCRIPTIONS[n], "inputSchema": schema(n)} for n in SCHEMAS]}
            elif method == "tools/call":
                p = req.get("params") or {}
                signal.setitimer(signal.ITIMER_REAL, 35)
                try:
                    outcome = dispatch(path, p.get("name"), p.get("arguments") or {})
                finally:
                    signal.setitimer(signal.ITIMER_REAL, 0)
                result = {"content": [{"type": "text", "text": json.dumps(outcome, ensure_ascii=False)}]}
            elif method == "ping":
                result = {}
            else:
                result = {}
            if ident is not None:
                respond({"jsonrpc": "2.0", "id": ident, "result": result})
        except (ValueError, TypeError, OSError, TimeoutError):
            if isinstance(req, dict) and req.get("id") is not None:
                respond({"jsonrpc": "2.0", "id": req["id"], "error": {"code": -32603, "message": "Argoni could not read that call"}})


if __name__ == "__main__":
    main(sys.argv[1])
