#!/usr/bin/env python3
# summary: Open an AI helper or investigate a crash.
"""starchaser agent: open an AI helper or ask for help with a problem.

Common commands
  launch [prompt]                  open your chosen coding agent (Super+Shift+A)
  default [claude|codex|opencode|hermes]
                                   show or choose your coding agent
  troubleshoot --title T [--context FILE|-] [--via agent|claude|chatgpt|grok|ask]
                                   ask for help; use --context to include a file (- reads typed or piped text)
  slot <1|2|3>                     open an AI shortcut set in Settings > AI
  sessions [--all]                 list AI tasks as JSON; --all includes other computers in the fleet
  focus <session-id>               bring an AI task's terminal to the front

Use default --text to show the selected helper's full name and whether it is installed.

Choose how to get problem help in Settings > AI. Until you choose, Troubleshoot asks
whether to use Ask Starchaser, open browser help, use or install a coding agent, or copy the details.

Advanced
  slots                            list the three AI shortcuts and their choices as JSON
  set <setting> <value>            change a setting:
                                   agent: claude|codex|opencode|hermes
                                   troubleshoot: agent|claude|chatgpt|grok|ask
                                   dock: true|false (show or hide AI tasks)
                                   slot1|slot2|slot3: claude|codex|opencode|hermes|chat:claude|chat:chatgpt|chat:grok
  hooks on|off|status|sync         turn AI task tracking on or off, or check it (sync: an added account follows)
  hook                             record an AI task update (used by AI apps)
  crash <pid> [comm] [exe] [sig]   ask for help with a crashed app (used by crash notifications)
  watch-crashes                    watch for app crashes and offer help

Settings are saved in ~/.config/starchaser/ai.json.
"""
import json
import os
import re
import runpy
import shlex
import shutil
import subprocess
import sys
import threading
import time
import urllib.parse
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import starchaser_ai_config as ai_config
from starchaser_cli import takes_nothing_after, usage_error, safe_streams
from starchaser_system_defaults import tool_path  # noqa: E402
safe_streams()

HOME = Path.home()
CONF = HOME / ".config/starchaser/ai.json"
LEGACY_DEFAULT = HOME / ".config/agents/default"           # an older agent.sh kept the default here
STATE = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "starchaser-agents"
# Claude Code reads its settings from $CLAUDE_CONFIG_DIR when that is set (Ask and the usage check already follow it):
# hooks written to ~/.claude there never reached the dock
CLAUDE_SETTINGS = Path(os.environ.get("CLAUDE_CONFIG_DIR") or HOME / ".claude") / "settings.json"
SELF = tool_path("starchaser-agent")   # what the hooks run: /usr/lib/starchaser/bin, or a checkout's bin/
AGENTS = {"claude": "Claude Code", "codex": "Codex", "opencode": "OpenCode", "hermes": "Hermes"}
WEB = {"claude": ("Claude", "https://claude.ai/new?q="), "chatgpt": ("ChatGPT", "https://chatgpt.com/?q="),
       "grok": ("Grok", "https://grok.com/?q=")}
# the chat apps an AI slot can open: name (as its desktop app is called), its website, desktop app commands to try
CHATS = {"claude": ("Claude", "https://claude.ai/new", ["claude-desktop"]),
         "chatgpt": ("ChatGPT", "https://chatgpt.com/", ["chatgpt"]),
         "grok": ("Grok", "https://grok.com/", ["grok-desktop", "grok-bot", "grok"])}
SLOT_VALUES = (*(f"chat:{k}" for k in CHATS), *AGENTS)
SLOT_DEFAULTS = ["chat:claude", "chat:chatgpt", "chat:grok"]
SET_VALUES = {"agent": tuple(AGENTS), "troubleshoot": ("ask-starchaser", "agent", *WEB, "ask"), "dock": ("true", "false"),
              "slot1": SLOT_VALUES, "slot2": SLOT_VALUES, "slot3": SLOT_VALUES}
HOOK_EVENTS = ("SessionStart", "UserPromptSubmit", "Notification", "PostToolUse", "Stop", "StopFailure", "SessionEnd")
# Each agent reports through its own mechanism; `starchaser agent hook --agent <name>` turns its events into ours:
#   start | prompt | permission | resumed | done | idle | failed | end
EVENT_MAP = {
    # Claude Code (~/.claude/settings.json hooks). Notification is split by notification_type below.
    "claude": {"SessionStart": "start", "UserPromptSubmit": "prompt", "PostToolUse": "resumed", "Stop": "done",
               "StopFailure": "failed", "SessionEnd": "end"},
    # Codex (~/.codex/hooks.json; Claude-compatible names, plus PermissionRequest, no Notification)
    "codex": {"SessionStart": "start", "UserPromptSubmit": "prompt", "PermissionRequest": "permission",
              "PostToolUse": "resumed", "Stop": "done", "SessionEnd": "end"},
    # OpenCode (our plugin ~/.config/opencode/plugins/starchaser.js forwards its bus events by name)
    "opencode": {"session.created": "start", "session.busy": "prompt", "permission.asked": "permission",
                 "permission.replied": "resumed", "session.idle": "done", "session.error": "failed", "session.deleted": "end"},
    # Hermes (shell hooks in ~/.hermes/config.yaml). on_session_end fires at the end of each turn.
    "hermes": {"on_session_start": "start", "pre_llm_call": "prompt", "pre_approval_request": "permission",
               "post_approval_response": "resumed", "post_tool_call": "resumed", "on_session_end": "done",
               "on_session_finalize": "end"},
}
CODEX_HOOK_EVENTS = ("SessionStart", "UserPromptSubmit", "PermissionRequest", "PostToolUse", "Stop", "SessionEnd")
HERMES_HOOK_EVENTS = ("on_session_start", "pre_llm_call", "pre_approval_request", "post_approval_response",
                      "post_tool_call", "on_session_end", "on_session_finalize")
DONE_WAITS = 60          # finished this many seconds ago: it's waiting for you (yellow), for agents with no idle notice
# How much a session needs you (the dock's one icon is the worst of them: green / yellow / red):
#   ok       working, or finished normally
#   needs    wants you, nothing is broken: it finished and waits for your next message (Claude's idle_prompt)
#   stopped  can't go on until you act: it asks permission or a question (permission_prompt / elicitation_dialog),
#            or an error ended its turn (StopFailure)
LEVELS = ("ok", "needs", "stopped")


def sh(*cmd, timeout=10, env=None) -> subprocess.CompletedProcess:
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, env=env)
    except (OSError, subprocess.TimeoutExpired) as e:
        return subprocess.CompletedProcess(cmd, 1, "", str(e))


def conf() -> dict:
    c = ai_config.read(CONF)
    if "agent" not in c:
        try:
            c["agent"] = LEGACY_DEFAULT.read_text().strip() or "claude"
        except OSError:
            # nothing chosen yet: Claude Code, unless only other coding agents are installed: then the first of those
            # (Codex set up from Settings > AI made Super+A offer to install Claude Code, QA 2026-11-03)
            have = [a for a in AGENTS if shutil.which(a)]
            c["agent"] = "claude" if not have or "claude" in have else have[0]
    # not chosen until the person chooses (decided 2026-10-10): the first Troubleshoot asks (choose_troubleshoot)
    if c.get("troubleshoot") not in ("ask-starchaser", "agent", *WEB):
        c["troubleshoot"] = ""
    c.setdefault("dock", True)
    slots = c.get("slots") if isinstance(c.get("slots"), list) else []
    c["slots"] = [slots[i] if i < len(slots) and slots[i] in SLOT_VALUES else SLOT_DEFAULTS[i] for i in range(3)]
    return c


def update_conf(change) -> dict:
    """conf(), changed by change(c), written back: under the lock starchaser ask takes for the same file (an agent
    or slot save here and an Ask provider save there used to write back each other's old values, bringing back a
    provider just switched off), and through a temporary file, so a reader never sees half a file."""
    def apply_change(data):
        data.update(conf())
        change(data)
    try:
        return ai_config.update(CONF, apply_change)
    except OSError as error:
        sys.exit(f"starchaser agent: couldn't save your settings ({error.strerror}). Check that you can write to ~/.config.")


def spawn(cmd: list, **kw) -> None:
    """Start a program that outlives this call (a terminal, a browser), and reap it when it ends: the crash watcher
    runs for days, and children that are never waited for stay behind as zombies.
    It runs in a scope of its own: started from a service (the crash watcher), it would otherwise be killed with
    that service whenever an update or a new checkout restarts it, taking an open Troubleshoot session with it."""
    if os.environ.get("XDG_RUNTIME_DIR") and os.path.exists(os.path.join(os.environ["XDG_RUNTIME_DIR"], "bus")) \
            and shutil.which("systemd-run"):
        cmd = ["systemd-run", "--user", "--scope", "--quiet", "--collect", "--", *cmd]
    p = subprocess.Popen(cmd, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **kw)
    threading.Thread(target=p.wait, daemon=True).start()


# ---------------------------------------------------------------------------------------------- launching
def workdir() -> str:
    return str(HOME / "Work") if (HOME / "Work").is_dir() else str(HOME)


CATALOG_ID = {"claude": "claude-code", "codex": "codex", "opencode": "opencode", "hermes": "hermes"}
# Claude Code from Anthropic's installer is ~/.local/bin/claude. The session puts that folder on PATH, but a shortcut
# or the cockpit doesn't always inherit the session's PATH: the agent, and the terminal it opens in, find it either way
LOCAL_BIN = str(HOME / ".local/bin")
if LOCAL_BIN not in os.environ.get("PATH", "").split(os.pathsep):
    os.environ["PATH"] = os.pathsep.join(p for p in (os.environ.get("PATH", ""), LOCAL_BIN) if p)


def offer(agent: str, why: str) -> None:
    """Offer to install an agent (the software center's "Would you like to install …?")."""
    subprocess.Popen(["starchaser", "software", "offer", "--remind", CATALOG_ID.get(agent, agent), why], start_new_session=True,
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def selected_account(agent: str) -> str:
    """Name the saved selection only when the caller hasn't supplied a different account home."""
    variable = {"claude": "CLAUDE_CONFIG_DIR", "codex": "CODEX_HOME", "hermes": "HERMES_HOME"}.get(agent)
    if not variable or variable in os.environ or "STARCHASER_AI_" + agent.upper() + "_HOME" in os.environ:
        return ""
    try:
        data = json.loads((HOME / ".local/share/starchaser/ai-accounts" / (agent + ".json")).read_text())
        name = next(a["name"] for a in data["accounts"] if a["home"] == data["active"] and a["ready"])
        return name if isinstance(name, str) and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9 _.-]{0,63}", name) else ""
    except (OSError, ValueError, KeyError, TypeError, StopIteration):
        return ""  # the account helper reports a broken registry; don't invent an identity


def launch(prompt: str = "", agent: str = "") -> None:
    from starchaser_ask_store import policy
    if policy() != "all":
        sys.exit("This account uses private AI only or has AI turned off. Ask Starchaser still offers built-in help.")
    agent = agent or conf()["agent"]
    if not shutil.which(agent):
        name = AGENTS.get(agent, agent)
        print(f"starchaser agent: {name} isn't installed yet. You can install it from Software.", file=sys.stderr)
        offer(agent, "Your coding agent isn't installed yet.")
        sys.exit(1)
    # starchaser ai account's link for this tool starts the account chosen with Use in Settings > AI; a shortcut or
    # the cockpit doesn't always inherit the session's PATH that puts it first, so ask for it by path
    shim = HOME / ".local/share/starchaser/ai-accounts/bin" / agent
    if agent in ("claude", "codex") and not (shim.is_symlink() and shim.exists()):
        # A tool installed since the last refresh has no link yet, and the bare tool would open its own browser
        # sign-in; the link is what picks the sign-in that works without a browser
        try:
            subprocess.run([tool_path("starchaser-ai-account"), "sync"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                           stderr=subprocess.DEVNULL, timeout=10, check=False)
        except (OSError, subprocess.SubprocessError):
            pass
    cmd = [str(shim) if shim.is_symlink() and shim.exists() else agent]
    account = selected_account(agent)
    if account:
        # Pin this window to the account in its title even if Use changes before the terminal starts.
        cmd = [tool_path("starchaser-ai-account"), "run", account, agent]
    if prompt and agent == "opencode":
        cmd += ["--prompt", prompt]
    elif prompt and agent == "hermes":
        # `hermes "text"` reads the text as a subcommand and exits; `chat -q` on a terminal starts a session with it
        cmd += ["chat", "-q", prompt]
    elif prompt:
        cmd += [prompt]
    title = AGENTS.get(agent, agent) + (" - " + account if account else "")
    # Like Settings > AI's terminals, the window stays open to show why a session ended badly (a sign-in that failed
    # offline closed it before anyone could read why); Ctrl+C (exit 130) and a normal exit close it.
    cmd = ["bash", "-c", '"$0" "$@"; case $? in 0|130) ;; *) read -rsn1 -p "Press a key to close" ;; esac', *cmd]
    spawn(["starchaser", "terminal", "--class", f"agent-{agent}", "--title", title, *cmd], cwd=workdir())


# ---------------------------------------------------------------------------------------------- AI slots
def webapp_module():
    """bin/starchaser-webapp, loaded as a module (it finds desktop apps and opens app windows)."""
    import importlib.machinery
    import importlib.util
    loader = importlib.machinery.SourceFileLoader("starchaser_webapp", str(Path(__file__).resolve().parent / "starchaser-webapp"))
    spec = importlib.util.spec_from_loader("starchaser_webapp", loader)
    mod = importlib.util.module_from_spec(spec)
    loader.exec_module(mod)
    return mod


def chat_app(chat: str, wa=None):
    """The installed desktop app for a chat ("claude" -> the Claude app), as a .desktop path or a command; None when
    there's none (then its website opens as an app window). A site the browser installed as an app counts too."""
    name, _, cmds = CHATS[chat]
    try:
        wa = wa or webapp_module()
        f = wa.find_app([name])
        if f:
            return f
    except (OSError, ImportError, SyntaxError, AttributeError):
        pass
    for c in cmds:
        if shutil.which(c):
            return c
    return None


def slot_opens(value: str, wa=None) -> str:
    """What a slot opens right now, in a few words (Settings > AI shows it under the choice)."""
    if value in AGENTS:
        return f"{AGENTS[value]} in a terminal" if shutil.which(value) else f"{AGENTS[value]} isn't installed yet: the key offers to install it"
    chat = value.split(":", 1)[1]
    app = chat_app(chat, wa)
    host = CHATS[chat][1].split("/")[2]
    if app:
        return f"The {CHATS[chat][0]} app"
    try:
        windowed = bool((wa or webapp_module()).browser()[1])
    except (OSError, ImportError, SyntaxError, AttributeError):
        windowed = False
    return f"{host} in an app window" if windowed else f"{host} in your web browser"


def open_slot(n: int) -> None:
    from starchaser_ask_store import policy
    if policy() != "all":
        sys.exit("AI app shortcuts are off for this account. Open Ask Starchaser for private help.")
    value = conf()["slots"][n - 1]
    if value in AGENTS:
        launch(agent=value)
        return
    chat = value.split(":", 1)[1]
    name, url, _ = CHATS[chat]
    app = chat_app(chat)
    if isinstance(app, Path):
        from starchaser_app_privacy import mediated_command
        if sh(*mediated_command(["gio", "launch", str(app)]), timeout=10).returncode == 0:
            return
    elif app:
        spawn([app])
        return
    if sh(str(Path(__file__).resolve().parent / "starchaser-webapp"), url, "--name", name, timeout=15).returncode:
        offer("brave-origin", f"{name} opens in a web browser, and none would start. Get a browser, then try the shortcut again.")


def slots_info() -> dict:
    c = conf()
    try:
        wa = webapp_module()
    except (OSError, ImportError, SyntaxError):
        wa = None
    # the keys in use now (a profile or your own change can move them), as people read them; "" = no key
    # written "Super + Shift + A" like every other key on screen (Settings' headings, the cheat sheet); splitting
    # and re-joining is safe whether the helper prints "Super+Shift+A" or already "Super + Shift + A"
    keys = []
    for i in range(3):
        try:
            k = subprocess.run(["starchaser", "shortcuts", "key", f"AI: AI slot {i + 1}"], capture_output=True,
                               text=True, timeout=5).stdout.strip()
        except (OSError, subprocess.TimeoutExpired):
            k = ""
        keys.append(" + ".join(p.strip() for p in k.split("+") if p.strip()) if k else "")
    choices = [{"value": f"chat:{k}", "label": v[0], "kind": "chat"} for k, v in CHATS.items()] + \
              [{"value": k, "label": v, "kind": "agent", "installed": bool(shutil.which(k))} for k, v in AGENTS.items()]
    return {"slots": [{"slot": i + 1, "key": keys[i], "value": c["slots"][i], "opens": slot_opens(c["slots"][i], wa)}
                      for i in range(3)], "choices": choices}


# ---------------------------------------------------------------------------------------------- troubleshooting
SYSTEM = ("I'm on Starchaser Linux: an Arch Linux based desktop (pacman, AUR via yay/paru, systemd, Hyprland on Wayland, "
          "Quickshell for the desktop shell).")


def troubleshoot_via() -> str:
    """Where Troubleshoot goes: the coding agent, the web chat the person picked in Settings > AI, or "" when nothing
    is chosen yet (the default, Derek 2026-10-10): then the first Troubleshoot asks (choose_troubleshoot). It never
    switches to a web chat by itself: that would put crash details (the program, its command line, its stack) in a
    website's address without the person ever choosing that (decisions-r7)."""
    return conf()["troubleshoot"]


def troubleshoot_who(via: str) -> str:
    """The name on the button: "Claude Code" (the agent), "Claude" (the web chat), or "" when nothing is chosen yet
    (the button then says just "Troubleshoot")."""
    if not via:
        return ""
    if via == "ask-starchaser": return "Ask Starchaser"
    return AGENTS.get(conf()["agent"], "the agent") if via == "agent" else WEB.get(via, ("AI",))[0]


def has_web_browser() -> bool:
    """Something opens web links. Only a clean empty answer means no browser (the failed install may have been the
    browser): a missing xdg-mime, an error or a timeout still counts as one, so help in the browser is still tried."""
    if not shutil.which("xdg-mime"):
        return True
    r = sh("xdg-mime", "query", "default", "x-scheme-handler/https", timeout=5)
    return r.returncode != 0 or bool(r.stdout.strip())


def choose_troubleshoot(title: str) -> str:
    """The first Troubleshoot, before a choice is made in Settings > AI: a question with three answers. "claude"
    (help in the browser) or "agent" (use the coding agent, or install one) is kept as the choice; "copy" (copy the
    details) is for this time only, so the next Troubleshoot asks again. "" when the question is closed unanswered.
    With no web browser on the computer, help in the browser isn't offered (it would do nothing), and the question
    says why."""
    from starchaser_ask_store import policy
    if policy() != "all":
        return "ask-starchaser"
    agent = conf()["agent"]
    use = f"Use {AGENTS.get(agent, agent)}" if shutil.which(agent) else "Install a coding agent"
    web = WEB["claude"][0]
    browser = has_web_browser()
    body = "Ask Starchaser shows you the details first. Nothing is sent until you press Ask. Built-in help works without AI."
    actions = ["-A", "ask-starchaser=Ask Starchaser", "-A", "copy=Copy the details"] + (["-A", "web=Get help in the browser"] if browser else []) + ["-A", f"agent={use}"]
    # always, even when stderr is not a terminal: this waits in the background, and a script or a remote shell
    # must not sit in silence for the hour the question is up
    print("Waiting for your answer in the notification: how should Troubleshoot help? "
          f"(or run with --via {'|'.join(SET_VALUES['troubleshoot'])})", file=sys.stderr)
    try:
        r = subprocess.run([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "dialog-question", "-w",
                            "-h", "string:x-starchaser-offer:troubleshoot",
                            *actions, f"{title}: how should Troubleshoot help?", body],
                           capture_output=True, text=True, timeout=3600)
        pick = r.stdout.strip()
    except (OSError, subprocess.TimeoutExpired):
        return ""
    if pick == "ask-starchaser":
        update_conf(lambda c: c.update(troubleshoot="ask-starchaser"))
        return pick
    if pick == "web":
        update_conf(lambda c: c.update(troubleshoot="claude"))
        return "claude"
    if pick == "agent":
        update_conf(lambda c: c.update(troubleshoot="agent"))
        return "agent"
    return "copy" if pick == "copy" else ""


def copy_details(title: str, context: str) -> bool:
    """Puts the problem on the clipboard, as the browser would have got it, and says so."""
    text = f"{SYSTEM} {title}." + (f"\n\nDetails:\n{context.strip()[-6000:]}" if context.strip() else "")
    try:
        ok = subprocess.run(["wl-copy"], input=text, text=True, timeout=10).returncode == 0
    except (OSError, subprocess.TimeoutExpired):
        ok = False
    if ok:
        sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "edit-copy", "Copied the details",
           "Paste them into any AI chat or a help forum. The next Troubleshoot asks again; to choose for good, use "
           "Settings > AI.")
    else:
        sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "dialog-warning", "Couldn't copy the details",
           "The clipboard isn't working right now. Try again in a moment.")
    return ok


def troubleshoot(title: str, context: str = "", via: str = "") -> bool:
    from starchaser_ask_store import policy
    # Family policy applies to explicit and saved browser choices as well as coding agents.
    via = "ask-starchaser" if policy() != "all" else "" if via == "ask" else via or troubleshoot_via()
    context = context.strip()
    if via in WEB and not has_web_browser():
        # help in the browser was chosen, but there's no browser now: ask again, offering what works without one
        via = ""
    if not via:
        via = choose_troubleshoot(title)
        if via == "copy":
            return copy_details(title, context)
        if not via:
            return True                 # closed without an answer: nothing to do
    # The choice notification can stay open while an owner changes this account's policy.
    if policy() != "all":
        via = "ask-starchaser"
    if via == "ask-starchaser":
        r = subprocess.run(["starchaser", "ask", "context", "error"], input=title + "\n\n" + context, text=True)
        return r.returncode == 0
    if via in WEB:
        # the browser gets the problem in the address; keep it short enough for every site
        body = f"{SYSTEM} {title}." + (f"\n\nDetails:\n{context[-2500:]}" if context else "") + "\n\nWhat's wrong, and how do I fix it?"
        url = WEB[via][1] + urllib.parse.quote(body)
        if sh("xdg-open", url, timeout=10).returncode:
            # no web browser to open it in: say so, instead of a button that seems to do nothing
            sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "dialog-warning", "Couldn't open a web browser",
               f"Troubleshoot opens {WEB[via][0]} in a web browser, and none would start. Install one from the menu "
               "(Super + Space, then Install), then try again.")
            print(f"starchaser agent: couldn't open a web browser for {WEB[via][0]}", file=sys.stderr)
            return False
        return True
    # the coding agent can investigate this computer itself (read-only first, it asks before changing anything)
    prompt = (f"{SYSTEM} {title}. Investigate it on this computer: read logs and state first, change nothing without "
              f"asking me. Then tell me plainly what's wrong and how to fix it." + (f"\n\nWhat I have so far:\n{context[-6000:]}" if context else ""))
    launch(prompt)
    return True


def crash(pid: str, comm: str = "", exe: str = "", sig: str = "") -> None:
    title = f"The program {comm or exe or pid} crashed ({sig or 'signal unknown'}, PID {pid})"
    info = sh("coredumpctl", "info", "--no-pager", pid, timeout=20).stdout
    via = troubleshoot_via()            # the same choice the notice's button named
    if not via:                         # not chosen yet: ask (the browser and copy get the short form of the record)
        via = choose_troubleshoot(title)
        if via == "copy":
            copy_details(title, "\n".join(l for l in info.splitlines() if re.match(r"\s*(PID|Signal|Executable|Package|Command Line|Timestamp|Message|#\d)", l))[:2500])
            return
        if not via:
            return
    if via == "agent":
        troubleshoot(title + f". Use the diagnose-crash skill if you have it; `coredumpctl info {pid}` has the record",
                     info[:4000], via)
    else:
        troubleshoot(title, "\n".join(l for l in info.splitlines() if re.match(r"\s*(PID|Signal|Executable|Package|Command Line|Timestamp|Message|#\d)", l))[:2500], via)


def session_env() -> None:
    """The crash watcher is a user service: it can start before the desktop does, and then it has a bare PATH (no
    ~/.local/bin, where Starchaser's tools and Claude Code live) and no display, so a notification's Troubleshoot or
    Details button found neither the tools nor a screen to open a terminal on. Fill both in from this login's runtime
    folder, freshly for each button press (the desktop may have started after the service)."""
    path = os.environ.get("PATH", "").split(":")
    for d in (str(HOME / ".local/bin"), "/usr/local/bin", "/usr/bin"):
        if d not in path:
            path.insert(0, d) if d.startswith(str(HOME)) else path.append(d)
    os.environ["PATH"] = ":".join(p for p in path if p)
    run = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"))

    def newest(paths):
        paths = [p for p in paths if p.exists()]
        return max(paths, key=lambda p: p.stat().st_mtime) if paths else None
    try:
        if not os.environ.get("WAYLAND_DISPLAY") or not (run / os.environ["WAYLAND_DISPLAY"]).exists():
            sock = newest(p for p in run.glob("wayland-*") if re.fullmatch(r"wayland-\d+", p.name))
            if sock:
                os.environ["WAYLAND_DISPLAY"] = sock.name
        sig = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")
        if not sig or not (run / "hypr" / sig).is_dir():
            inst = newest(p for p in (run / "hypr").glob("*") if p.is_dir())
            if inst:
                os.environ["HYPRLAND_INSTANCE_SIGNATURE"] = inst.name
    except OSError:
        pass


# The names the main menu (keybinds/menu.py, its Apps page) gives the programs it launches: a crash notice says
# "Files closed unexpectedly", not "Flea" or "Thunar File Manager", for the app the menu calls Files. Keep the two in step.
MENU_NAMES = {"flea": "Files", "flea-gui": "Files", "thunar": "Files", "kitty": "Terminal", "zeditor": "Code editor (Zed)", "zed": "Code editor (Zed)",
              "remmina": "Remote desktop (Remmina)", "vesktop": "Discord (Vesktop)", "lite-xl": "Code editor", "mousepad": "Text editor",
              "brave-origin": "Web browser (Brave)", "yazi": "Files (in the terminal)",
              "fresh": "Text editor (in the terminal)", "spotify": "Spotify", "strawberry": "Strawberry"}


# The desktop's own parts are all one program (Quickshell), started with the folder of the part it runs
# (`qs -p ~/.config/quickshell/cockpit`): a crash notice names the part, never "quickshell".
QS_EXES = {"quickshell", "qs"}
QS_PARTS = {"cockpit": "The taskbar", "bar": "The taskbar", "keybinds": "The menu", "settings": "Settings",
            "welcome": "The welcome", "ask": "Ask Starchaser", "lock": "The lock screen", "greeter": "The login screen",
            "installer": "The installer"}
DESKTOP_NAMES = {"Hyprland": "The desktop", "hyprland": "The desktop", "hypridle": "The screen-off timer",
                 "hyprlock": "The lock screen", "hyprsunset": "Night light", "awww-daemon": "The wallpaper service", "awww": "The wallpaper service",
                 "xdg-desktop-portal-hyprland": "The screen-sharing service",
                 "xdg-desktop-portal-gtk": "The file-picker service", "xdg-desktop-portal": "The app permissions service"}
HELPER_NAMES = {"starchaser-fleet-settings": "Fleet settings"}


def qs_part(cmdline: str) -> str:
    m = re.search(r"(?:^|\s)(?:-p|--path)[ =](\S+)", cmdline or "")
    path = Path(m.group(1).rstrip("/")) if m else Path()
    part = path.parent.name if path.suffix == ".qml" else path.name      # -p may name the folder or its shell.qml
    return QS_PARTS.get(part, "The screenshot tool" if part == "freeze" else "Part of the desktop")


def app_name(exe: str, comm: str = "", cmdline: str = "") -> str:
    """What the person calls the program that crashed: the menu's name for it, else the Name of the app whose
    Exec / TryExec runs it, else the program's file name, else the kernel's (15-character) name for it."""
    base = Path(exe).name if exe else ""
    if base in HELPER_NAMES:
        return HELPER_NAMES[base]
    if re.fullmatch(r"python(?:\d+(?:\.\d+)*)?|sh|bash|dash|zsh|node|nodejs", base or comm):
        try:
            argv = shlex.split(cmdline)
        except ValueError:
            argv = []
        # Only recognize the script operand, never a later data argument or code passed to -c/-m/-e.
        # These Python switches take no value; stop at any other option rather than guess its meaning.
        args = iter(argv[1:])
        for arg in args:
            if (base or comm).startswith("python") and arg in {"-u", "-B", "-E", "-I", "-s", "-S"}:
                continue
            if arg == "--":
                arg = next(args, "")
            if arg and not arg.startswith("-") and Path(arg).name in HELPER_NAMES:
                return HELPER_NAMES[Path(arg).name]
            break
    if base in QS_EXES or (not base and comm in QS_EXES):
        return qs_part(cmdline)
    if base in DESKTOP_NAMES:
        return DESKTOP_NAMES[base]
    if base in MENU_NAMES:
        return MENU_NAMES[base]
    found = []
    if base:
        dirs = [Path("/usr/share/applications"), HOME / ".local/share/applications",
                Path("/var/lib/flatpak/exports/share/applications"), HOME / ".local/share/flatpak/exports/share/applications"]
        for d in dirs:
            for f in sorted(d.glob("*.desktop")) if d.is_dir() else []:
                try:
                    text = f.read_text(errors="replace")
                except OSError:
                    continue
                entry = text.split("\n[", 1)[0]                       # the [Desktop Entry] group only, not actions
                if re.search(r"(?m)^NoDisplay\s*=\s*true", entry):
                    continue
                ex = re.search(r"(?m)^Exec\s*=\s*(.+)$", entry)
                argv = ex.group(1).split() if ex else []
                runs = {Path(argv[0].strip('"')).name} if argv else set()
                te = re.search(r"(?m)^TryExec\s*=\s*(\S+)", entry)
                runs |= {Path(te.group(1).strip('"')).name} if te else set()
                name = re.search(r"(?m)^Name\s*=\s*(.+)$", entry)
                if base in runs and name:
                    # the app's own launcher (no arguments but %f-style codes) beats a helper like "thunar --bulk-rename"
                    plain = all(re.fullmatch(r"%\w", x) for x in argv[1:])
                    found.append((not plain, name.group(1).strip()))
    if found:
        return min(found)[1]
    return base or comm or "A program"


def when_words(t: float) -> str:
    """9:14 AM today, else Oct 6, 9:14 AM."""
    lt = time.localtime(t)
    return time.strftime("%-I:%M %p" if lt[:3] == time.localtime()[:3] else "%b %-d, %-I:%M %p", lt)


def crash_notice_proof(summary, body, actions, key):
    """Use the same signed payload as starchaser notify without losing D-Bus callbacks."""
    hints = {"x-starchaser-crash": key}
    try:
        token = (Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) /
                 "starchaser-notifications" / "token").read_text().strip()
        if len(token) != 64 or not all(c in "0123456789abcdef" for c in token):
            return hints
        args = ["-a", "Starchaser", "-h", "string:x-starchaser-crash:" + key]
        for i in range(0, len(actions), 2):
            args.extend(["-A", actions[i] + "=" + actions[i + 1]])
        args.extend([summary, body])
        signed = runpy.run_path(str(Path(__file__).resolve().with_name("starchaser-notify")))["proof_args"](args, token)
        for i, value in enumerate(signed[:-1]):
            if value == "-h":
                kind, name, text = signed[i + 1].split(":", 2)
                if kind == "string":
                    hints[name] = text
    except (OSError, ValueError):
        pass  # Without a session key, the notice remains an ordinary unverified notice.
    return hints


class CrashNotices:
    """The crash notifications, sent straight over D-Bus on one connection that stays open while the watcher runs.

    It used to be one `notify-send` per crash, killed after 120 s: a click after that reached nobody (the button did
    nothing at all), and clicking the notice itself only dismissed it. Now:
      - each notice stays answerable for as long as it is shown (the watcher keeps listening on this connection);
      - clicking the notice opens Details (its "default" action); it is resident, so it stays in the list after
        Details and Troubleshoot is still there;
      - a program that crashes again while its notice is still up gets that notice updated ("... 4 times") instead
        of a pile of new ones;
      - when the watcher stops (logout, or an update restarting it), it closes its notices, so the list never keeps
        buttons nobody is listening to."""
    BUS, PATH, IFACE = "org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications"
    QUIET = 2.0                         # a crash loop updates its notice at most this often

    def __init__(self):
        import gi
        gi.require_version("Gio", "2.0")
        from gi.repository import Gio, GLib
        self.Gio, self.GLib = Gio, GLib
        self.bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
        self.lock = threading.RLock()
        self.shown = {}                 # notification id -> crash record (see crashed())
        self.by_key = {}                # program -> notification id
        self.pending = {}               # program -> crash record whose first notice is still waiting for the service
        self.bus.signal_subscribe(None, self.IFACE, None, self.PATH, None, Gio.DBusSignalFlags.NONE, self.on_signal)
        # the notification service restarted (the cockpit reloaded): its ids start over, so the ones held here would
        # now name some other app's notification (an update would replace it, closing would close it)
        self.bus.signal_subscribe("org.freedesktop.DBus", "org.freedesktop.DBus", "NameOwnerChanged",
                                  "/org/freedesktop/DBus", self.BUS, Gio.DBusSignalFlags.NONE, self.on_owner)
        threading.Thread(target=GLib.MainLoop().run, daemon=True).start()

    # ---- sending
    def call(self, method: str, sig: str, args: tuple, reply: str | None = None):
        GLib = self.GLib
        r = self.bus.call_sync(self.BUS, self.PATH, self.IFACE, method, GLib.Variant(sig, args),
                               GLib.VariantType(reply) if reply else None, self.Gio.DBusCallFlags.NONE, 5000, None)
        return r.unpack() if r is not None else None

    def send(self, rec: dict, tries: int = 0) -> None:
        with self.lock:
            rec["timer"] = None
            if xwayland_session_ended(rec):
                if self.pending.get(rec["key"]) is rec:
                    del self.pending[rec["key"]]
                return
            name, n = rec["name"], rec["count"]
            summary = f"{name} closed unexpectedly" + (f" {n} times" if n > 1 else "")
            body = ("It crashed. " if n == 1 else f"It crashed {n} times since {when_words(rec['first'])}. ") + \
                "Troubleshoot can help find out why. Click for the details."
            if restored_this_boot():
                # system files went back under running programs (Settings > Recovery, Undo last update): crashes
                # before the restart Recovery asks for are expected, not a puzzle to troubleshoot (QA 2026-11-03,
                # hyprland-dialog crashed beside Recovery's Restart button)
                body = body.replace("Troubleshoot can help find out why.", "Going back to a snapshot changed system "
                                    "files under open apps, so they can crash until you restart. Restart to finish going "
                                    "back; if it still crashes after that, Troubleshoot can help.")
            if name in ("The taskbar", "The menu") and shutil.which("starchaser"):
                # starchaser shell keeper starts these two again within seconds: say so, or it reads as still gone
                body = ("It restarted by itself. " + body if restored_this_boot() else
                        "It restarted by itself. Troubleshoot can help find out why.")
            actions = ["default", "Details", "fix", f"Troubleshoot with {rec['who']}" if rec["who"] else "Troubleshoot",
                       "details", "Details"]
            hints = {"urgency": self.GLib.Variant("y", 1), "resident": self.GLib.Variant("b", True),
                     **{key: self.GLib.Variant("s", value) for key, value in
                        crash_notice_proof(summary, body, actions, rec["key"]).items()}}
            if "x-starchaser-proof" not in hints:
                return  # System notices need a valid session proof before delivery.
            old = rec.get("id", 0)
            try:
                nid = self.call("Notify", "(susssasa{sv}i)", ("Starchaser", old, "dialog-error", summary, body,
                                                               actions, hints, -1), "(u)")[0]
            except Exception:       # GLib.Error: the notification service isn't up yet (the desktop is starting)
                if tries < 10:
                    rec["timer"] = threading.Timer(3, self.send, (rec, tries + 1))
                    rec["timer"].daemon = True
                    rec["timer"].start()
                    if not old:     # more crashes of it meanwhile fold into this one (see crashed())
                        self.pending[rec["key"]] = rec
                elif self.pending.get(rec["key"]) is rec:
                    del self.pending[rec["key"]]
                return
            if self.pending.get(rec["key"]) is rec:
                del self.pending[rec["key"]]
            rec["id"], rec["sent"] = nid, time.time()
            if old and old != nid:  # the service restarted and gave it a new id
                self.shown.pop(old, None)
            self.shown[nid] = rec
            self.by_key[rec["key"]] = nid

    def crashed(self, pid: str, comm: str, exe: str, sig: str, who: str, name: str = "", session: str = "") -> None:
        name = name or app_name(exe, comm)
        # one notice per program; the desktop's own parts all run the same program, so they are told apart by name
        key = (exe or comm or pid) + ("\0" + name if Path(exe).name in QS_EXES else "")
        with self.lock:
            nid = self.by_key.get(key)
            rec = self.shown.get(nid) if nid else None
            waiting = self.pending.get(key)
            if waiting:             # its first notice is still waiting for the service: it will carry this count
                waiting.update(count=waiting["count"] + 1, pid=pid, comm=comm, sig=sig, who=who, session=session, last=time.time())
                return
            if rec:                 # still up: the same notice, one more crash
                rec.update(count=rec["count"] + 1, pid=pid, comm=comm, sig=sig, who=who, session=session, last=time.time())
                if rec.get("timer"):
                    return          # an update is already on its way; it will carry this count
                wait = self.QUIET - (time.time() - rec.get("sent", 0))
                if wait > 0:
                    rec["timer"] = threading.Timer(wait, self.send, (rec,))
                    rec["timer"].daemon = True
                    rec["timer"].start()
                    return
            else:
                rec = {"key": key, "name": name, "count": 1, "first": time.time(), "pid": pid,
                       "comm": comm, "exe": exe, "sig": sig, "who": who, "session": session}
        self.send(rec)

    def close(self, nid: int) -> None:
        try:
            self.call("CloseNotification", "(u)", (nid,))
        except Exception:
            pass

    def close_all(self) -> None:
        with self.lock:
            ids = list(self.shown)
        for nid in ids:
            self.close(nid)

    def on_owner(self, _conn, _sender, _path, _iface, _name, params):
        _bus, _old, _new = params.unpack()
        with self.lock:
            for rec in self.shown.values():
                if rec.get("timer"):
                    rec["timer"].cancel()
                    rec["timer"] = None
                rec["id"] = 0
            self.shown.clear()
            self.by_key.clear()

    # ---- answers (on the D-Bus thread: the work goes to a thread of its own, so a slow one never blocks the rest)
    def on_signal(self, _conn, _sender, _path, _iface, name, params):
        if name == "ActionInvoked":
            nid, action = params.unpack()
            with self.lock:
                rec = dict(self.shown.get(nid) or {})
            if rec:
                threading.Thread(target=self.answer, args=(nid, rec, action), daemon=True).start()
        elif name == "NotificationClosed":
            nid = params.unpack()[0]
            with self.lock:
                rec = self.shown.pop(nid, None)
                if rec and self.by_key.get(rec["key"]) == nid:
                    del self.by_key[rec["key"]]
                if rec and rec.get("timer"):
                    rec["timer"].cancel()

    def answer(self, nid: int, rec: dict, action: str) -> None:
        try:
            session_env()
            if action == "fix":
                self.close(nid)     # answered: it leaves the list (Details keeps it, so Troubleshoot is still there)
                crash(rec["pid"], rec["comm"], rec["exe"], rec["sig"])
            elif action in ("details", "default"):
                details(rec)
        except (OSError, SystemExit):       # e.g. the agent isn't installed (launch() offers it, then exits)
            pass


def details_cmd(rec: dict) -> list | None:
    """The terminal command for details(), or None when the record's PID isn't a plain number. Every value from the
    journal (PID, program path or name, the heading) goes to bash as an argument ("$1"...), never into the script
    text: journal fields can be written by other programs, and one spliced into `bash -c` would run as this user."""
    pid = str(rec.get("pid", ""))
    if not pid.isdigit():
        return None
    tech = 'coredumpctl info --no-pager -- "$1"'
    summary = f"{rec['name']} stopped at {when_words(rec.get('first', time.time()))}."
    if rec.get("count", 1) > 1:
        summary = f"{rec['name']} stopped {rec['count']} times, first at {when_words(rec.get('first', time.time()))}."
    # "running again" only when it can be known: the desktop's parts all run one program (QS_EXES), so another
    # part running says nothing about this one; otherwise a process with the same name that started after the crash
    comm = "" if Path(rec.get("exe") or "").name in QS_EXES or rec.get("comm") in QS_EXES else str(rec.get("comm", ""))
    crashed_at = rec.get("last", rec.get("first", time.time()))
    args = [pid, summary, comm, str(int(crashed_at))]
    if rec.get("count", 1) > 1:
        match = rec["exe"] if rec.get("exe") else f"COREDUMP_COMM={rec.get('comm', '')}"
        since = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(rec["first"] - 1))
        heading = f"Every crash of {rec['name']} since {when_words(rec['first'])}:"
        tech = ('printf \'%s\\n\' "$5"; coredumpctl list --no-pager --since="$6" -- "$7"; '
                f"echo; echo 'The newest one:'; {tech}")
        args += [heading, since, match]
    # plain summary first; the systemd record only when asked for (T)
    script = ('printf \'%s\\n\' "$2"; '
              # literal name match on /proc/*/comm (no pattern), newer than the crash
              'if [ -n "$3" ]; then again=; now=$(date +%s); for d in /proc/[0-9]*; do '
              'c=; read -r c < "$d/comm" 2>/dev/null; [ "$c" = "${3:0:15}" ] || continue; '
              'e=$(ps -o etimes= -p "${d#/proc/}" 2>/dev/null) || continue; [ -n "$e" ] || continue; '
              'if [ $((now - e)) -ge "$4" ]; then again=1; break; fi; done; '
              'if [ -n "$again" ]; then echo "It is running again."; else echo "It is not running now."; fi; fi; '
              + ('echo "It keeps stopping. The Troubleshoot button on the notice can look into it."; echo; '
                 if rec.get("count", 1) > 1 else 'echo "Nothing to do unless it happens again."; echo; ') +
              "read -rsn1 -p 'Press T for technical details, any other key to close ' k; echo; "
              f"case $k in t|T) {tech}; echo; read -rsn1 -p 'Press a key to close' || true;; esac")
    return ["starchaser", "terminal", "-o", "confirm_os_window_close=0", "--title", f"Crash: {rec['name']}", "bash", "-c",
            script, "bash", *args]


def details(rec: dict) -> None:
    """A terminal with systemd-coredump's record of the crash (the newest one, after a list of them all)."""
    cmd = details_cmd(rec)
    if cmd:
        spawn(cmd)


# systemd-coredump's "process dumped core" record. Matched by this id and the COREDUMP_ fields, not by who wrote it:
# its SYSLOG_IDENTIFIER changes between systemd versions ("systemd-coredump", "(coredump-worker)", ...), and a filter
# on the old name matched nothing at all (qa-8, round 11). The record lands in the crashed program's owner's journal
# (_UID is that user), so a user who isn't an admin sees their own crashes too (checked on qa-4: sh -c 'kill -SEGV $$').
COREDUMP_MESSAGE_ID = "fc2e22bc6ee647b6b90729ab34a250b1"


RECOVERY_LAST = HOME / ".local/state/starchaser/recovery-last.json"     # starchaser recovery's last go-back


def restored_this_boot() -> bool:
    """System files went back to a snapshot since this computer started, so it hasn't restarted to finish yet."""
    try:
        d = json.loads(RECOVERY_LAST.read_text())
        boot = Path("/proc/sys/kernel/random/boot_id").read_text().strip()
    except (OSError, ValueError):
        return False
    return (isinstance(d, dict) and d.get("kind") in ("restore", "undo") and d.get("outcome") in ("ok", "partial")
            and bool(boot) and d.get("boot_id") == boot)


def files_replaced_under_it(sig: str, lock: Path = Path("/var/lib/pacman/db.lck"),
                            log: Path = Path("/var/log/pacman.log")) -> bool:
    """A bus error (SIGBUS) while an install or update is running, or within a minute of one: pacman replaced a file
    the program had mapped (Python and its libraries, mid-update), which isn't a crash to troubleshoot (QA 2026-11-04,
    a Fleet settings check "crashed" while pacman -Syu replaced Python)."""
    if sig != "SIGBUS":
        return False
    try:
        return lock.exists() or time.time() - log.stat().st_mtime < 60
    except OSError:
        return False


def xwayland_session_ended(rec: dict) -> bool:
    """Xwayland teardown belongs to its old login, even if the crash notice is retried after the next sign-in."""
    session = rec.get("session", "")
    if Path(rec.get("exe", "")).name != "Xwayland" or not re.fullmatch(r"[a-zA-Z0-9]+", session):
        return False
    # A removed scope reads inactive; a logged-out session with lingering processes is abandoned but still active.
    # A failed query is unknown: keep the crash report in that case.
    state = sh("systemctl", "show", f"session-{session}.scope", "-p", "ActiveState", "-p", "SubState", timeout=2)
    fields = dict(line.split("=", 1) for line in state.stdout.splitlines() if "=" in line)
    return state.returncode == 0 and (fields.get("ActiveState") in ("inactive", "deactivating", "failed")
                                     or fields.get("SubState") == "abandoned")


def crash_record_ok(e: dict, uid: str) -> bool:
    """A coredump record worth a notice: this user's program (COREDUMP_UID), written by systemd-coredump on this
    user's behalf or by root (_UID, which journald sets itself, so it can't be faked: an admin's journalctl -f also
    reads other users' journals, where anyone can log a look-alike record), and a PID that is only digits."""
    return (str(e.get("COREDUMP_PID", "")).isdigit() and str(e.get("COREDUMP_UID", "")) == uid
            and str(e.get("_UID", "")) in ("0", uid))


def watch_crashes() -> None:
    """Follow systemd-coredump for this user; one notice per program (repeats fold into it), with Troubleshoot."""
    import signal
    session_env()
    notices = CrashNotices()
    seen = set()
    uid = str(os.getuid())
    p = subprocess.Popen(["journalctl", "-f", "-n0", "-o", "json", f"MESSAGE_ID={COREDUMP_MESSAGE_ID}"],
                         stdout=subprocess.PIPE, text=True)

    def stop(*_, code=0):
        notices.close_all()             # nobody will answer their buttons any more
        p.terminate()
        sys.exit(code)
    signal.signal(signal.SIGTERM, stop)
    signal.signal(signal.SIGINT, stop)
    for line in p.stdout:
        try:
            e = json.loads(line)
        except ValueError:
            continue
        if not crash_record_ok(e, uid):
            continue
        pid = str(e["COREDUMP_PID"])
        crash_id = (pid, e.get("COREDUMP_TIMESTAMP", ""))
        if crash_id in seen:
            continue
        if len(seen) > 500:
            seen.clear()
        seen.add(crash_id)
        comm, exe, sig = e.get("COREDUMP_COMM", ""), e.get("COREDUMP_EXE", ""), e.get("COREDUMP_SIGNAL_NAME", "")
        if files_replaced_under_it(sig):
            continue
        who = troubleshoot_who(troubleshoot_via())
        name = app_name(exe, comm, e.get("COREDUMP_CMDLINE", ""))
        notices.crashed(pid, comm, exe, sig, who, name, str(e.get("COREDUMP_SESSION", "")))
    stop(code=1)                        # journalctl ended: a failure, so the service starts the watcher again


# ---------------------------------------------------------------------------------------------- the dock: sessions
def proc_name(pid: int) -> str:
    try:
        return Path(f"/proc/{pid}/comm").read_text().strip()
    except OSError:
        return ""


def proc_parent(pid: int) -> int:
    try:
        return int(Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[1])
    except (OSError, ValueError, IndexError):
        return 0


def proc_tty(pid: int) -> int:
    """The process's controlling terminal (0: none, like Codex's `app-server --managed-daemon` left behind after it)."""
    try:
        return int(Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[4])
    except (OSError, ValueError, IndexError):
        return 0


def asks(d: Path) -> bool:
    """A command-line AI that Ask (starchaser ask) runs in the background to answer a question: not a session."""
    try:
        return b"\0STARCHASER_ASK=1\0" in b"\0" + (d / "environ").read_bytes()
    except OSError:
        return False


def hook(agent: str = "claude") -> None:
    """An agent's lifecycle event, JSON on stdin (see EVENT_MAP): records the session's state and how much it needs you."""
    if os.environ.get("STARCHASER_ASK"):
        return                      # Ask's own background question (starchaser ask), not a session of yours
    # an agent run outside a login session (over SSH, from a service) has no runtime folder to keep sessions in, and
    # no taskbar to show them: nothing to record, and nothing printed into the agent
    if not STATE.parent.is_dir() or not os.access(STATE.parent, os.W_OK | os.X_OK):
        return
    try:
        ev = json.loads(sys.stdin.read() or "{}")
    except ValueError:
        return
    agent = agent if agent in EVENT_MAP else "claude"
    extra = ev.get("extra") if isinstance(ev.get("extra"), dict) else {}          # Hermes puts event details here
    sid = re.sub(r"[^\w-]", "", str(ev.get("session_id") or ev.get("sessionID") or extra.get("session_id") or ""))[:64]
    if not sid:
        return
    STATE.mkdir(parents=True, exist_ok=True)
    f = STATE / f"{agent}-{sid}.json" if agent != "claude" else STATE / f"{sid}.json"
    name = ev.get("hook_event_name", "")
    kind = EVENT_MAP[agent].get(name, "")
    if agent == "claude" and name == "Notification":
        nt = ev.get("notification_type") or ""
        if nt in ("permission_prompt", "elicitation_dialog"):
            kind = "permission"
        elif nt in ("idle_prompt", ""):             # "" = a Claude Code from before notification types: as before
            kind = "idle"
        else:
            return                                  # auth_success and other notices don't need you
    if agent == "hermes" and kind == "done" and (extra.get("failed") or ev.get("failed")):
        kind = "failed"
    if not kind:
        return
    if kind == "end":
        f.unlink(missing_ok=True)
        refresh_attention()
        return
    try:
        rec = json.loads(f.read_text())
    except (OSError, ValueError):
        rec = {"id": f.stem, "agent": agent, "started": int(time.time())}
    # the agent's own process (the hook's nearest ancestor whose command line names the agent), and its tmux pane
    pid = found = os.getppid()
    for _ in range(8):
        try:
            cmd = Path(f"/proc/{found}/cmdline").read_bytes().decode(errors="replace").lower()
        except OSError:
            break
        if agent in cmd and "starchaser-agent" not in cmd:       # not the shell that runs this hook
            pid = found
            break
        found = proc_parent(found)
        if found <= 1:
            break
    rec.update({"pid": pid, "cwd": ev.get("cwd") or rec.get("cwd", ""), "updated": int(time.time()),
                "tmux": os.environ.get("TMUX_PANE", "") and sh("tmux", "display", "-p", "-t", os.environ["TMUX_PANE"], "#S").stdout.strip()})
    if kind == "start":
        rec["state"], rec["level"] = "idle", "ok"
    elif kind == "prompt":
        text = ev.get("prompt") or extra.get("user_message") or ev.get("message") or rec.get("task", "")
        rec["state"], rec["level"], rec["message"] = "working", "ok", str(text)[:140]
        rec["task"] = rec["message"]
    elif kind == "permission":
        ti = ev.get("tool_input") if isinstance(ev.get("tool_input"), dict) else {}
        what = (ev.get("message") or ti.get("description") or extra.get("description") or extra.get("command")
                or (f"Wants to use {ev['tool_name']}" if ev.get("tool_name") else "") or "Needs your permission")
        rec["state"], rec["level"], rec["message"] = "waiting", "stopped", str(what)[:200]
    elif kind == "resumed":
        if rec.get("state") == "working" and rec.get("level") == "ok":
            return                                     # nothing changed: skip the write and the light
        rec["state"], rec["level"], rec["message"] = "working", "ok", rec.get("task", "")
    elif kind == "idle":
        rec["state"], rec["level"], rec["message"] = "waiting", "needs", str(ev.get("message") or "Waiting for you")[:200]
    elif kind == "done":
        rec["state"], rec["level"] = "done", "ok"
    elif kind == "failed":
        err = ev.get("error") or ev.get("reason") or extra.get("turn_exit_reason") or ev.get("message") or "an error"
        rec["state"], rec["level"], rec["message"] = "waiting", "stopped", f"Stopped: {str(err)[:180]}"
    with state_lock():                                  # a list poll saving 'Finished; waiting for you' can't cross this
        write_text(f, json.dumps(rec))
    refresh_attention()


def sessions(light: bool = True) -> list:
    """Every agent session on this computer. When a record is dropped (its agent is gone) or a finished session turns
    into 'waiting for you', the frame's attention light is updated too (light=False: the caller does that itself)."""
    out, changed = [], False
    if STATE.is_dir():
        for f in STATE.glob("*.json"):
            try:
                r = json.loads(f.read_text())
            except (OSError, ValueError, RecursionError):
                continue
            if not r.get("pid") or not Path(f"/proc/{r['pid']}").exists():
                f.unlink(missing_ok=True)                   # the agent is gone (closed without SessionEnd)
                changed = changed or r.get("level", "ok") != "ok"
                continue
            r["project"] = Path(r.get("cwd") or "~").name or "~"
            r.setdefault("level", "needs" if r.get("state") == "waiting" else "ok")   # records from before levels
            if r.get("state") == "done" and r["level"] == "ok" and time.time() - r.get("updated", 0) > DONE_WAITS:
                promoted = dict(r, state="waiting", level="needs", message="Finished; waiting for you")
                try:                                        # saved, so the light is set once, not on every poll
                    with state_lock():                      # the same lock as the hook's write: a newer hook wins
                        cur = json.loads(f.read_text())
                        if cur.get("updated") == r.get("updated") and cur.get("state") == "done":   # no newer hook
                            write_text(f, json.dumps({k: v for k, v in promoted.items() if k != "project"}))
                            r, changed = promoted, True
                        else:                               # a hook wrote meanwhile: list what it wrote, light untouched
                            r = dict(cur, project=r["project"])
                            r.setdefault("level", "needs" if r.get("state") == "waiting" else "ok")
                except (OSError, ValueError, RecursionError):
                    pass
            out.append(r)
    # agents without hooks (Codex, OpenCode, Claude before the hooks were added): running, state unknown
    known = {r["pid"] for r in out}
    for d in Path("/proc").iterdir():
        if not d.name.isdigit():
            continue
        try:
            if d.stat().st_uid != os.getuid():
                continue
            cmd = (d / "cmdline").read_bytes().split(b"\0")
        except OSError:
            continue
        exe = Path(cmd[0].decode(errors="replace")).name if cmd and cmd[0] else ""
        if exe in AGENTS and int(d.name) not in known and proc_name(int(d.name)) != "starchaser-agen" and not asks(d):
            # skip helper children of a known agent
            if proc_parent(int(d.name)) in known:
                continue
            # a background server with no terminal has no window to bring forward: not a session
            if not proc_tty(int(d.name)):
                continue
            try:
                cwd = os.readlink(d / "cwd")
            except OSError:
                cwd = ""
            out.append({"id": f"pid-{d.name}", "agent": exe, "pid": int(d.name), "cwd": cwd, "project": Path(cwd).name or "~",
                        "state": "running", "level": "ok", "updated": int(d.stat().st_mtime)})
    order = {"waiting": 0, "working": 1, "running": 2, "idle": 3, "done": 4}
    out.sort(key=lambda r: (-LEVELS.index(r.get("level", "ok")) if r.get("level") in LEVELS else 0,
                            order.get(r.get("state"), 9), -r.get("updated", 0)))
    if changed and light:
        refresh_attention(out, wait=False)
    return out


REMOTE = STATE.parent / "starchaser-agents-remote.json"


def remote_sessions() -> list:
    """Agent sessions on the other computers in the fleet, through each one's link. Cached; refreshed in the background so
    the dock never waits on the network."""
    try:
        cached = json.loads(REMOTE.read_text())
    except (OSError, ValueError, RecursionError):
        cached = {"time": 0, "sessions": []}
    if not isinstance(cached, dict):                # a damaged cache reads as empty, never a traceback
        cached = {"time": 0, "sessions": []}
    when = cached.get("time", 0)
    if not isinstance(when, (int, float)):
        when = 0
    if time.time() - when > 15 and os.fork() == 0:
        try:
            os.setsid()
            # off the caller's output: a `sessions` stream (the taskbar) waited for this child's copy of its stdout
            # to close, so one offline device held back even this computer's own session updates
            null = os.open(os.devnull, os.O_RDWR)
            for fd in (0, 1, 2):
                os.dup2(null, fd)
            REMOTE.write_text(json.dumps(dict(cached, time=time.time())))     # one refresh at a time
            import importlib.machinery
            import importlib.util
            ld = importlib.machinery.SourceFileLoader("sl", tool_path("starchaser-link"))
            sp = importlib.util.spec_from_loader("sl", ld)
            sl = importlib.util.module_from_spec(sp)
            ld.exec_module(sl)
            try:                                # the names chosen in the fleet list, and whether this account may sign in
                fleet = [e for e in sl.fleet().load()["machines"] if e.get("link")]
                names = {e["link"]["device"]: e["name"] for e in fleet}
                ready = {e["link"]["device"]: (e.get("manage") or {}).get("state") == "ready" for e in fleet}
            except Exception:                   # (the device's own name is fine; attaching is then just tried)
                names, ready = {}, {}

            def ask(peer):                      # every fleet computer at once: one that's off doesn't hold up the rest
                r = sl.ssh_to(dict(peer), "agents", timeout=6)
                try:
                    rows = json.loads(r.stdout or "{}").get("sessions", [])
                except (ValueError, AttributeError):
                    return []
                name = names.get(peer["id"]) or peer["name"]
                # canAttach: a terminal there needs this account's own sign-in (Mission Control's), which the
                # computer gives only once it lets the fleet manage it
                extra = {"canAttach": ready[peer["id"]]} if peer["id"] in ready else {}
                return [dict(x, machine=name, machineId=peer["id"], id=f"{peer['id']}:{x['id']}", **extra)
                        for x in rows if isinstance(x, dict) and "id" in x]
            from concurrent.futures import ThreadPoolExecutor
            with ThreadPoolExecutor(max_workers=8) as ex:
                out = [x for rows in ex.map(ask, sl.load_peers()) for x in rows]
            REMOTE.write_text(json.dumps({"time": time.time(), "sessions": out}))
        finally:
            os._exit(0)
    sessions = cached.get("sessions")
    return sessions if isinstance(sessions, list) else []


def refresh_attention(rows: list | None = None, wait: bool = True) -> None:
    """The cockpit's attention light (the frame) is on while any agent needs you (yellow or red)."""
    waiting = any(r.get("level", "ok") != "ok" for r in (sessions(light=False) if rows is None else rows))
    # `qs ipc` only finds instances on the current display, and agents often run in tmux without WAYLAND_DISPLAY
    cmd = ["qs", "-p", str(HOME / ".config/quickshell/cockpit"), "ipc", "call", "cockpit", "attention",
           "true" if waiting else "false"]
    if wait:
        sh(*cmd, timeout=5, env=desktop_env())
        return
    try:                                                    # from a list poll: don't hold up the list
        subprocess.Popen(cmd, env=desktop_env(), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                         stderr=subprocess.DEVNULL, start_new_session=True)
    except OSError:
        pass


def desktop_env() -> dict:
    run = Path(f"/run/user/{os.getuid()}")
    way = next((p.name for p in sorted(run.glob("wayland-*")) if not p.name.endswith(".lock")), "wayland-1")
    return dict(hypr_env(), XDG_RUNTIME_DIR=str(run), WAYLAND_DISPLAY=os.environ.get("WAYLAND_DISPLAY") or way)


def hypr_env() -> dict:
    run = Path(f"/run/user/{os.getuid()}/hypr")
    sigs = sorted(run.glob("*/.socket.sock"), key=lambda x: x.stat().st_mtime, reverse=True) if run.exists() else []
    return dict(os.environ, HYPRLAND_INSTANCE_SIGNATURE=sigs[0].parent.name) if sigs else dict(os.environ)


def focus(sid: str) -> None:
    """Bring the session's terminal to the front: the window whose process is the agent's ancestor (or the terminal
    attached to its tmux session)."""
    r = next((x for x in sessions() if x["id"] == sid), None)
    if not r:
        print(f"starchaser agent: no AI task with id {sid!r} (see: starchaser agent sessions)", file=sys.stderr)
        sys.exit(1)
    env = hypr_env()
    try:
        wins = {c["pid"]: c["address"] for c in json.loads(sh("hyprctl", "clients", "-j", env=env).stdout or "[]")}
    except ValueError:
        wins = {}
    starts = [r["pid"]]
    if r.get("tmux"):
        starts += [int(x) for x in sh("tmux", "list-clients", "-t", r["tmux"], "-F", "#{client_pid}").stdout.split() if x.isdigit()]
    for start in starts:
        pid = start
        for _ in range(12):
            if pid in wins:
                sh("hyprctl", "eval", f'hl.dispatch(hl.dsp.focus({{ window = "address:{wins[pid]}" }}))', env=env)
                return
            pid = proc_parent(pid)
            if pid <= 1:
                break
    # not in any window (a detached tmux session): open a terminal attached to it
    if r.get("tmux"):
        subprocess.Popen(["starchaser", "terminal", "tmux", "attach", "-t", r["tmux"]], start_new_session=True)


# ---------------------------------------------------------------------------------------------- agent hooks
# Every agent that's installed gets wired to `starchaser agent hook --agent <name>`; other people's hooks and
# settings are left alone, and each file is backed up before the first change.
CODEX_HOOKS = HOME / ".codex/hooks.json"
OPENCODE_PLUGIN = HOME / ".config/opencode/plugins/starchaser.js"
HERMES_CONFIG = HOME / ".hermes/config.yaml"
HERMES_ALLOW = HOME / ".hermes/shell-hooks-allowlist.json"
ACCOUNTS = HOME / ".local/share/starchaser/ai-accounts"    # starchaser ai account's added accounts, one folder each
OPENCODE_JS = """// Starchaser Linux (managed by starchaser-agent; `starchaser-agent hooks off` removes it): tells the cockpit's agent
// icon what this OpenCode session is doing: working, waiting for permission, finished, or stopped by an error.
export const StarchaserAgent = async ({ $, directory }) => {
  const send = async (name, sid, message = "") => {
    if (!sid) return
    const payload = JSON.stringify({ hook_event_name: name, session_id: sid, cwd: directory, message })
    try { await $`%s hook --agent opencode < ${new Response(payload)}`.quiet() } catch (e) {}
  }
  return {
    event: async ({ event }) => {
      const p = event.properties || {}
      const sid = p.sessionID || (p.info && p.info.id) || p.id
      if (event.type === "session.status") {
        const t = p.status && p.status.type
        if (t === "busy") await send("session.busy", sid)
        else if (t === "idle") await send("session.idle", sid)
      } else if (["session.created", "session.idle", "session.error", "session.deleted", "permission.asked", "permission.replied"].includes(event.type)) {
        const err = p.error && ((p.error.data && p.error.data.message) || p.error.name)
        await send(event.type, sid, p.title || p.message || err || "")
      }
    },
  }
}
""" % SELF


def backup_once(path: Path) -> None:
    b = path.with_name(path.name + ".bak-starchaser")
    if path.exists() and not b.exists():
        shutil.copy(path, b)


class state_lock:
    """One writer at a time in STATE (the hooks and a list poll promoting a finished session)."""
    def __enter__(self):
        import fcntl
        STATE.mkdir(parents=True, exist_ok=True)
        self.fd = os.open(STATE / ".lock", os.O_CREAT | os.O_RDWR, 0o600)
        fcntl.flock(self.fd, fcntl.LOCK_EX)
        return self

    def __exit__(self, *exc):
        os.close(self.fd)                               # closing releases the lock


def write_text(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(path.name + ".tmp")
    tmp.write_text(text)
    tmp.replace(path)


def claude_like(path: Path, events: tuple, cmd: str, action: str) -> bool | None:
    """Claude Code / Codex style {"hooks": {Event: [{"hooks": [{"type": "command", "command": ...}]}]}}.
    Returns whether ours is in place (after `action`); None = the file isn't valid JSON, "unreadable" = it
    couldn't be opened at all (permissions). Either way it is left untouched."""
    try:
        text = path.read_text() if path.exists() else ""
    except OSError:
        return "unreadable"
    try:
        cfg = json.loads(text) if text.strip() else {}
    except ValueError:
        return None
    hk = cfg.setdefault("hooks", {})
    mine = lambda h: h.get("command") == cmd
    have = all(any(mine(h) for g in hk.get(e, []) for h in g.get("hooks", [])) for e in events)
    if action == "status" or (action == "on" and have):
        return have
    if action == "on":
        for e in events:
            groups = hk.setdefault(e, [])
            if not any(mine(h) for g in groups for h in g.get("hooks", [])):
                groups.append({"hooks": [{"type": "command", "command": cmd, "timeout": 5}]})
    else:
        if not any(mine(h) for e in hk for g in hk[e] for h in g.get("hooks", [])):
            return False
        for e in list(hk):
            for g in hk[e]:
                g["hooks"] = [h for h in g.get("hooks", []) if not mine(h)]
            hk[e] = [g for g in hk[e] if g.get("hooks")]
            if not hk[e]:
                del hk[e]
    backup_once(path)
    write_text(path, json.dumps(cfg, indent=2) + "\n")
    return action == "on"


def hermes_hooks(action: str) -> tuple:
    """Hermes shell hooks: a `hooks:` block in ~/.hermes/config.yaml plus its consent allowlist. The YAML is edited
    as text (its comments stay), only when it has no hooks block of its own yet."""
    cmd = f"{SELF} hook --agent hermes"
    text = HERMES_CONFIG.read_text() if HERMES_CONFIG.exists() else ""
    begin, end = "# >>> starchaser-agent (managed)", "# <<< starchaser-agent"
    have = begin in text
    own = "Hermes already has hooks of its own, so Starchaser's weren't added. Its other settings were left alone."
    if action == "status" or (action == "on" and have):
        return have, (own if not have and re.search(r"(?m)^hooks:", text) else "")
    if action == "on":
        if re.search(r"(?m)^hooks:", text):
            return False, own
        block = [begin, "hooks:"] + [f"  {e}:\n    - command: \"{cmd}\"\n      timeout: 5" for e in HERMES_HOOK_EVENTS] + [end]
        backup_once(HERMES_CONFIG)
        write_text(HERMES_CONFIG, text.rstrip("\n") + ("\n\n" if text.strip() else "") + "\n".join(block) + "\n")
        try:
            allow = json.loads(HERMES_ALLOW.read_text()) if HERMES_ALLOW.exists() else {}
        except (OSError, ValueError):
            allow = {}
        ap = allow.setdefault("approvals", [])
        for e in HERMES_HOOK_EVENTS:            # you turned this on in Settings > AI: that is the consent
            if not any(x.get("event") == e and x.get("command") == cmd for x in ap):
                ap.append({"event": e, "command": cmd})
        write_text(HERMES_ALLOW, json.dumps(allow, indent=2) + "\n")
        return True, ""
    if not have:
        return False, ""
    write_text(HERMES_CONFIG, re.sub(rf"\n*{re.escape(begin)}.*?{re.escape(end)}\n?", "\n", text, flags=re.S))
    if HERMES_ALLOW.exists():
        try:
            allow = json.loads(HERMES_ALLOW.read_text())
            allow["approvals"] = [x for x in allow.get("approvals", []) if x.get("command") != cmd]
            write_text(HERMES_ALLOW, json.dumps(allow, indent=2) + "\n")
        except (OSError, ValueError):
            pass
    return False, ""


def account_files(agent: str, default: Path) -> list:
    """The agent's own settings file and the same file in each added account's folder (Settings > AI > Add an
    account): a session started as an added account reads its hooks from there, never from the default."""
    files = [default]
    try:
        for d in sorted((ACCOUNTS / agent).iterdir()):
            if d.is_dir() and not d.is_symlink() and (d / default.name).resolve() != default.resolve():
                files.append(d / default.name)
    except OSError:
        pass
    return files


def wire_all(files: list, events: tuple, cmd: str, action: str):
    """claude_like for every account's file: wired only when all are; the first file left alone, if any.
    sync wires the added accounts only when the agent's own file is wired (the switch is on)."""
    if action == "sync":
        action = "on" if claude_like(files[0], events, cmd, "status") is True else "status"
    results = [(f, claude_like(f, events, cmd, action)) for f in files]
    return all(w is True for _, w in results), next(((f, w) for f, w in results if not isinstance(w, bool)), None)


def hooks(action: str) -> dict:
    """Wire (on), unwire (off) or report (status) every installed agent, in every added account (sync: the added
    accounts follow the agent's own setting)."""
    out, problems = {}, []
    def broken(name, path, wired):          # the file was never overwritten: say why the switch stays off
        where = str(path).replace(str(HOME), "~")
        if wired is None:
            return (f"{name}'s settings file ({where}) has a mistake in it, so it was left alone. Fix the mistake, "
                    "or rename the file so a fresh one is made, then try again.")
        return (f"{name}'s settings file ({where}) can't be opened (its permissions don't let you read it), "
                "so it was left alone.")
    if shutil.which("claude") or CLAUDE_SETTINGS.exists():
        wired, bad = wire_all(account_files("claude", CLAUDE_SETTINGS), HOOK_EVENTS, f"{SELF} hook", action)
        out["claude"] = {"wired": wired}
        if bad:
            out["claude"]["note"] = broken("Claude Code", *bad)
            problems.append(out["claude"]["note"])
    if shutil.which("codex") or CODEX_HOOKS.exists():
        wired, bad = wire_all(account_files("codex", CODEX_HOOKS), CODEX_HOOK_EVENTS, f"{SELF} hook --agent codex", action)
        out["codex"] = {"wired": wired,
                        "note": broken("Codex", *bad) if bad else
                        "Codex asks you to trust new hooks once: run /hooks in Codex and trust Starchaser's."}
        if bad:
            problems.append(out["codex"]["note"])
    if action == "sync":                    # the other agents have no added accounts
        return {"agents": out, "problem": " ".join(problems)}
    if shutil.which("opencode") or OPENCODE_PLUGIN.exists():
        have = OPENCODE_PLUGIN.exists() and "starchaser-agent" in OPENCODE_PLUGIN.read_text()
        if action == "on" and not (have and OPENCODE_PLUGIN.read_text() == OPENCODE_JS):
            write_text(OPENCODE_PLUGIN, OPENCODE_JS)
            have = True
        elif action == "off" and have:
            OPENCODE_PLUGIN.unlink()
            have = False
        out["opencode"] = {"wired": have}
    if shutil.which("hermes") or HERMES_CONFIG.exists():
        wired, note = hermes_hooks(action)
        out["hermes"] = {"wired": wired, **({"note": note} if note else {})}
        if note and action != "off":
            problems.append(note)
    installed = bool(out) and all(v["wired"] for v in out.values())
    return {"installed": installed, "claude": bool(shutil.which("claude")), "agents": out,
            "problem": " ".join(problems)}


def opt(argv, name, default=""):
    return argv[argv.index(name) + 1] if name in argv and argv.index(name) + 1 < len(argv) else default


if __name__ == "__main__":
    a = sys.argv[1:]
    if a == ["help"] or any(x in ("-h", "--help") for x in a):
        print(__doc__.strip())
        sys.exit(0)
    cmd = a[0] if a else "launch"
    if cmd == "sessions" and a[1:] not in ([], ["--all"]):
        sys.exit(usage_error("starchaser agent", "sessions accepts only --all", "sessions [--all]"))
    if cmd in ("slots", "watch-crashes") and len(a) > 1:
        sys.exit(takes_nothing_after("starchaser agent", cmd, a))
    if cmd == "launch":
        launch(" ".join(a[1:]))
    elif cmd == "default" and a[1:] == ["--text"]:
        agent = conf()["agent"]
        name = AGENTS.get(agent, agent)
        if shutil.which(agent):
            print(f"{name} is selected and installed.")
        else:
            print(f"{name} is selected but is not installed. Open Settings > AI to set it up.")
    elif cmd == "default":
        if len(a) > 2:
            sys.exit(usage_error("starchaser agent", f"default takes one agent name (got {a[2]!r} as well)", "default [" + "|".join(AGENTS) + "]"))
        if len(a) > 1 and a[1] not in AGENTS:
            print(f"starchaser agent: unknown helper {a[1]!r} (one of: {', '.join(AGENTS)})", file=sys.stderr)
            sys.exit(2)
        if len(a) > 1:
            update_conf(lambda c: c.update(agent=a[1]))
            if not shutil.which(a[1]):
                offer(a[1], f"You picked {AGENTS[a[1]]} as your coding agent.")
        print(conf()["agent"])
    elif cmd == "troubleshoot":
        if any(x in ("-h", "--help") for x in a[1:]):
            print(__doc__.strip())
            sys.exit(0)
        # strict: each option once, each followed by its own value (so `--title --via claude` isn't a title of "--via")
        topts, bad, i = {}, "", 1
        while i < len(a) and not bad:
            name = a[i]
            if name not in ("--title", "--context", "--via"):
                bad = f"troubleshoot: unknown option {name!r} (options: --title, --context, --via)"
            elif name in topts:
                bad = f"troubleshoot: {name} is given twice"
            elif i + 1 >= len(a) or a[i + 1].startswith("--"):
                bad = f"troubleshoot: {name} needs a value after it"
            else:
                topts[name] = a[i + 1]
                i += 2
        if not bad and not topts.get("--title", "").strip():
            bad = "troubleshoot needs --title <text>, like: troubleshoot --title 'Wi-Fi keeps dropping'"
        if not bad and "--via" in topts and topts["--via"] not in SET_VALUES["troubleshoot"]:
            bad = f"troubleshoot: unknown --via {topts['--via']!r} (one of: {', '.join(SET_VALUES['troubleshoot'])})"
        if bad:
            print(f"starchaser agent: {bad}", file=sys.stderr)
            sys.exit(2)
        ctx, text = topts.get("--context", ""), ""
        if ctx == "-":
            text = sys.stdin.read()
        elif ctx:
            # Settings passes a log file that may be gone by now (cleared after a restart): go on without it, but say so
            try:
                text = Path(ctx).read_text(errors="replace")
            except OSError:
                print(f"starchaser agent: troubleshoot: couldn't read --context {ctx!r}; going on without it", file=sys.stderr)
        if not troubleshoot(topts["--title"].strip(), text, topts.get("--via", "")):
            sys.exit(1)
    elif cmd == "crash" and len(a) >= 2:
        crash(*a[1:5])
    elif cmd == "watch-crashes":
        watch_crashes()
    elif cmd == "sessions":
        local = sessions()
        # installed: the coding agents on this computer, so the taskbar's AI panel says to install one before
        # sending anyone to add an account
        print(json.dumps({"sessions": local + (remote_sessions() if "--all" in a else []), "conf": conf(),
                          "installed": [k for k in AGENTS if shutil.which(k)]}))
    elif cmd == "focus" and len(a) == 2:
        focus(a[1])
    elif cmd == "hook":
        try:
            hook(opt(a, "--agent", "claude"))
        except OSError:
            pass                    # the runtime folder went away or filled up: the agent goes on, the light catches up
    elif cmd == "hooks" and len(a) == 2 and a[1] in ("on", "off", "status", "sync"):
        print(json.dumps(hooks(a[1])))
    elif cmd == "slot" and len(a) == 2 and a[1] in ("1", "2", "3"):
        open_slot(int(a[1]))
    elif cmd == "slots":
        print(json.dumps(slots_info()))
    elif cmd == "set" and len(a) == 3 and a[1].startswith("slot") and a[2] in SET_VALUES.get(a[1], ()):
        print(json.dumps(update_conf(lambda c: c["slots"].__setitem__(int(a[1][4]) - 1, a[2]))))
    elif cmd == "set" and len(a) == 3 and a[2] in SET_VALUES.get(a[1], ()):
        val = (a[2] == "true") if a[1] == "dock" else "" if (a[1], a[2]) == ("troubleshoot", "ask") else a[2]
        print(json.dumps(update_conf(lambda c: c.update({a[1]: val}))))
    elif cmd in ("-h", "--help", "help"):
        print(__doc__.strip())
    else:
        # a known command used wrongly says what it needs; anything else is short, like the other helpers
        needs = {"crash": "crash needs a process id (and optionally its name, path and signal)",
                 "focus": "focus needs one session id (see: starchaser agent sessions)",
                 "slot": "slot needs 1, 2 or 3 (Super+Ctrl+Alt+A, Super+Alt+A, Super+Ctrl+A)",
                 "hooks": "hooks needs one of: on, off, status",
                 "set": "set needs a setting and a value, like: set troubleshoot claude (settings: agent, troubleshoot, dock, slot1, slot2, slot3)"}
        if cmd == "set" and len(a) == 3 and a[1] in SET_VALUES:
            needs["set"] = f"set {a[1]}: unknown value {a[2]!r} (one of: {', '.join(SET_VALUES[a[1]])})"
        elif cmd == "set" and len(a) >= 2 and a[1] not in SET_VALUES:
            needs["set"] = f"set: unknown setting {a[1]!r} (one of: {', '.join(SET_VALUES)})"
        print(f"starchaser agent: {needs[cmd]}" if cmd in needs
              else f"starchaser agent: unknown command {cmd!r}. Run 'starchaser agent --help' for more help.", file=sys.stderr)
        sys.exit(2)
