#!/usr/bin/env python3
# Copyright 2026 Stephen William Wiley
# This software comes with absolutely no warranty or implied warranty.
# You may modify and redistribute it provided this notice remains intact.
# By using this software you agree to the terms of this license.


import agent as _agent
import shlex


# Fresh source namespaces must not clean up another composite's windows.
_WINDOW_OWNER = object()



def schedcmd(cmd: str, length: int = 800, timeout: int = 100, attime: float = 0):
    """Run command after attime seconds and email output to this agent."""
    if not isinstance(attime, (int, float)) or isinstance(attime, bool) or not _agent.math.isfinite(attime) or attime < 0:
        return {"text": "error: attime must be finite and nonnegative"}
    if not isinstance(length, int) or isinstance(length, bool) or length < 0:
        return {"text": "error: length must be a nonnegative integer"}
    if not isinstance(timeout, (int, float)) or isinstance(timeout, bool) or not _agent.math.isfinite(timeout) or timeout <= 0:
        return {"text": "error: timeout must be finite and positive"}
    recipient = _agent.os.path.basename(_agent.os.path.normpath(_agent.AGENT_DIR))
    def run_later():
        try:
            _agent.time.sleep(attime)
            p = _agent.subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout, check=False)
            output = _agent.limit(p.stdout + p.stderr, {"maxlines": length})
        except Exception as e:
            output = f"error: {e}"
        try:
            _agent.load_tool_module("agent_mail")._send_mail(
                recipient, "Scheduled command output", output, sender="schedcmd")
        except Exception as e:
            print(f"schedcmd mail failure: {e}", file=_agent.sys.stderr)
    _agent.threading.Thread(target=run_later, daemon=True).start()
    return {"text": f"Scheduled command in {attime} seconds."}


def py(script: str, savefile: str, maxlines: int = 800):
    """run a python script, optionally saving it to a file. Ensure it terminates as there is no timeout. """
    if savefile is not None and savefile !="":
        with open(savefile,"w") as f: f.write(script)
    try:
        r=""
        with _agent.io.StringIO() as buf, _agent.redirect_stdout(buf):
            with _agent.interrupt_python("<agent-python>"):
                exec(compile(script, "<agent-python>", "exec"), vars(_agent), locals())
            r= buf.getvalue()
        return {"text": _agent.limit(str(r), locals())}
    except Exception as e: return {"text": f"error: {e}"}


def read(path: str, start: int = 0, length: int = 400):
    """Read file lines."""
    with open(path, encoding="utf-8", errors="replace") as f: lines = f.readlines()
    s, e = max(0, start), min(max(0, start) + length, len(lines))
    return {"text": f"{path} lines {s}-{e} of {len(lines)}:\n" + "".join(lines[s:e])}


def memory_save(text: str):
    """Append to persistent memory list."""
    m = _agent.load_memories()
    m.append(text)
    _agent.save_memories(m)
    return {"text": f"ok (index {len(m)-1})"}


def web_fetch(url: str, maxlines: int = 800):
    """Fetch page via elinks --dump."""
    p = _agent.tool_process(["elinks", "--dump", url])
    return {"text": _agent.limit(p.stdout, locals())}


def web_search(query: str, maxlines: int = 800):
    """Web search via DuckDuckGo + elinks."""
    url = "http://duckduckgo.com/?q=" + _agent.urllib.parse.quote_plus(query)
    p = _agent.tool_process(["elinks", "--dump", url])
    scope = getattr(_agent.execution, "cancellation", None)
    if scope: scope.pending.wait(3)
    else: _agent.time.sleep(3)
    _agent.check_interrupt()
    return {"text": _agent.limit(p.stdout, locals())}


def readpng(path: str):
    """Read PNG (needs multimodal model)."""
    with open(path, "rb") as f: return {"text": path, "data": f.read(), "mime": "image/png"}

# Explicit opt-in for depth-0 non-quick supervisors.
read.supervisor = True
readpng.supervisor = True
memory_save.supervisor = True


def cmd_quick(agent, arg, *, input=None, tk_root=None):
    """Toggle direct mode: all tools, optional delegation unless no_delegate. /quick on|off|toggle."""
    mode = arg.strip().lower()
    if mode not in ('', 'on', 'off', 'toggle'):
        print('Usage: /quick [on|off|toggle]')
        return
    agent._repair_quick_history(agent.history)
    agent.quick = not agent.quick if mode in ('', 'toggle') else mode == 'on'
    if agent.depth == 0:
        agent.save()
    print(f"Quick mode {('on' if agent.quick else 'off')}.")


def cmd_page(agent, arg, *, input=None, tk_root=None):
    """Page conversation history using the pydoc pager."""
    if arg.strip():
        print('Usage: /page')
        return
    lines = []
    for i, msg in enumerate(agent.history):
        role = msg.get('role', 'unknown')
        lines.append(f'[{i}] {role}' + (f" ({msg.get('tool_call_id')})" if msg.get('tool_call_id') else ''))
        content = msg.get('content')
        lines.append(content if isinstance(content, str) else _agent.json.dumps(content, indent=2, ensure_ascii=False))
        for tc in msg.get('tool_calls', []):
            fn = tc.get('function', {})
            lines.append(f"  TOOL CALL {fn.get('name', '')}: {fn.get('arguments', '')}")
        lines.append('')
    agent.resettty()
    text = '\n'.join(lines) or '(empty conversation)'
    if tk_root is not None and _agent.page_callback is not None:
        _agent.page_callback(text)
    elif input is not None and tk_root is None:
        _agent.pydoc.pager(text)
    else:
        print(text)


def cmd_new(agent, arg, *, input=None, tk_root=None):
    """Delete conversation (You should use dream instead.)"""
    agent.new()
    agent.resettty('Conversation cleared.\n')
    if arg:
        agent.step(arg)


def cmd_edit(agent, arg, *, input=None, tk_root=None):
    """Open an editor to edit the prompt or confirm agent's work."""
    edited = _agent._command_editor(arg, input, tk_root)
    if edited is not None:
        agent.cmdline(edited, input is not None)


def _effective_config():
    return {key: vars(_agent)[name] for key, name in _agent.SET_GLOBALS.items()}



def _serialize_config(values):
    return "".join("/set " + key + " " + str(value).replace("\n", "\\\n") + "\n"
                   for key, value in values.items())



def _save_config(values):
    """Persist a final override block; retain other rc commands. No live apply."""
    converted = {}
    for key in _agent.SET_GLOBALS:
        value = str(values[key])
        if value[:1].isspace() or value.endswith("\\") or "\r" in value or "\0" in value:
            raise ValueError(key + ": leading whitespace, terminal backslash, CR and NUL are unsupported")
        try: converted[key] = _agent.config_value(key, value)
        except ValueError as e: raise ValueError(key + ": " + str(e)) from e
    block = _serialize_config(converted)
    begin, end = "# Configuration editor settings begin\n", "# Configuration editor settings end\n"
    try:
        with open(_agent.AGENTRC, encoding="utf8") as source: original = source.read()
    except FileNotFoundError: original = ""
    # Only replace our final block. Preserve arbitrary earlier commands verbatim.
    if original.endswith(end) and begin in original:
        original = original[:original.rindex(begin)]
    if original.rstrip("\n").endswith("\\"):
        raise ValueError("Existing rc ends with an unfinished continuation")
    text = original + ("\n" if original and not original.endswith("\n") else "") + begin + block + end
    directory = _agent.os.path.dirname(_agent.os.path.abspath(_agent.AGENTRC))
    _agent.os.makedirs(directory, exist_ok=True)
    path = None
    try:
        with _agent.tempfile.NamedTemporaryFile(mode="w", encoding="utf8", dir=directory, delete=False) as target:
            path = target.name
            target.write(text)
            target.flush()
            _agent.os.fsync(target.fileno())
        _agent.os.replace(path, _agent.AGENTRC)
    finally:
        if path and _agent.os.path.exists(path): _agent.os.unlink(path)



def cmd_showcfg(agent, arg, *, input=None, tk_root=None):
    """Show config parameters"""
    print(_serialize_config(_effective_config()), end='')


def cmd_status(agent, arg, *, input=None, tk_root=None):
    """Redisplay the currently used context."""
    agent.usage_report()


def cmd_system(agent, arg, *, input=None, tk_root=None):
    """View or modify the system prompt/agent role."""
    agent.resettty()
    if arg:
        agent.history[0] = {'role': 'system', 'content': arg}
        _agent.set_config('system' if agent.depth < 1 else 'subsystem', arg)
        agent.save()
    print(agent.history[0]['content'])


def cmd_compact(agent, arg, *, input=None, tk_root=None):
    """Use a special subagent to summarize the context."""
    agent.resettty()
    agent.compact()


def _load_tools_source():
    try:
        with open(_agent.TOOLS_PATH, encoding="utf8") as stream: return stream.read()
    except OSError:
        return ""



def _append_tools_source(src, label=""):
    _agent.os.makedirs(_agent.AGENT_DIR, exist_ok=True)
    header = f"\n# --- {label} ({_agent.stamp()}) ---\n" if label else "\n"
    with open(_agent.TOOLS_PATH, "a", encoding="utf8") as f:
        f.write(header + src.rstrip("\n") + "\n")



def cmd_import(agent, arg, *, input=None, tk_root=None):
    """Import a python module: plain functions become tools; cmd_* functions
        become user commands, called as cmd_foo(agent, arg) via /foo. Set a tool's
        supervisor attribute to True (boolean) to expose it to depth-0 non-quick
        supervisors. Quick mode and child agents expose all tools, with subagent
        excluded when no_delegate is set. Source is copied
        to TOOLS_DIR and reloaded in a private namespace. Optional top-level forget
        and forget_list are combined lists of memory strings to append. Composite
        exports preserve component namespaces and receive the current _agent backend.
        Import executes trusted Python; use /meld for consent and history/datafiles.
        """
    if not arg:
        print('Usage: /import <path>')
        return
    try:
        name, path = _agent.tool_module_source(arg)
        module = _agent.load_tool_module(path, name)
        forget = _agent.tool_forget_list(module)
        nt, nm, nc = _agent.build_tools(module)
        with open(path, encoding='utf8') as stream:
            source = stream.read()
        _agent.os.makedirs(_agent.TOOLS_DIR, exist_ok=True)
        destination = _agent.os.path.join(_agent.TOOLS_DIR, name + '.py')
        with open(destination + '.tmp', 'w', encoding='utf8') as stream:
            stream.write(source)
        _agent.os.replace(destination + '.tmp', destination)
        module.__file__ = destination
        agent._register_module(name, module, (nt, nm, nc), forget)
        agent.core_modules.discard(name)
        agent._append_systemcmd(run_command=False)
        msg = f'Imported {len(nt)} tools'
        if nc:
            msg += f", {len(nc)} commands ({', '.join(nc)})"
        print(msg + f' from {arg}')
    except Exception as e:
        print(f'Import failed: {e}')


def cmd_newtool(agent, arg, *, input=None, tk_root=None):
    """Open $EDITOR with an example tool definition, then add and persist it to tools.py."""
    template = 'def mytool(arg: str):\n    """One-line description of what this tool does; shown to the model."""\n    return {"text": "result"}\n'
    src = _agent._command_editor(template, input, tk_root)
    if src is None:
        return
    if not src.strip() or src.strip() == template.strip():
        print('No changes made; tool not added.')
        return
    tmp_path = f'{_agent.AGENT_DIR}/newtool_{_agent.time.time_ns()}.py'
    try:
        _agent.os.makedirs(_agent.AGENT_DIR, exist_ok=True)
        with open(tmp_path, 'w', encoding='utf8') as f:
            f.write(src)
        module = _agent.load_tool_module(tmp_path, 'tools')
        forget = _agent.tool_forget_list(module)
        nt, nm, nc = _agent.build_tools(module)
        if not nt and (not nc):
            print('No tools or commands found in edited file; not added.')
            return
        _agent.append_tool_memories(forget)
        agent._register_tools(nt, nm, nc, owner='tools')
        agent.tool_modules['tools'] = module
        _append_tools_source(src, 'added via /newtool')
        msg = f'Added {len(nt)} tool(s)'
        if nc:
            msg += f", {len(nc)} command(s) ({', '.join(nc)})"
        print(msg)
    except Exception as e:
        print(f'New tool failed: {e}')
    finally:
        try:
            _agent.os.remove(tmp_path)
        except OSError:
            pass


def cmd_delmodule(agent, arg, *, input=None, tk_root=None):
    """Delete a saved module and its currently owned tools and commands.

    An optional generation token rejects a module changed since GUI selection.
    """
    try:
        parts = shlex.split(arg or '')
    except ValueError as error:
        print('Delete failed: malformed quoting: ' + str(error))
        return
    if not parts or len(parts) > 2:
        names = sorted(module["name"] for module in agent.deletable_modules())
        print('Usage: /delmodule <name> [expected_token]; deletable: ' + (', '.join(names) or '(none)'))
        return
    name = parts[0]
    try:
        agent.delete_module(name, expected_token=parts[1] if len(parts) == 2 else None)
    except (OSError, ValueError) as error:
        print('Delete failed: ' + str(error))
        return
    print(f"Deleted module '{name}'.")


def _apply_config(agent, values):
    """Apply an editor snapshot through registered commands; detect context once."""
    loading = agent._rc_loading
    agent._rc_loading = True
    try:
        for key in _agent.SET_GLOBALS:
            if key != "context_size": agent.cmdline("/set " + key + " " + str(values[key]), False)
    finally:
        agent._rc_loading = loading
    agent.cmdline("/set context_size " + str(values["context_size"]), False)


def cmd_set(agent, arg, *, input=None, tk_root=None):
    """Set agent.py configuration option"""
    if not arg:
        print('Usage: /set <key> <value>; keys:', ', '.join(sorted(_agent.VALID_SET)))
        for k in sorted(_agent.VALID_SET):
            print(f'  {k} = {_agent.config.get(k)}')
        return
    parts = arg.split(None, 1)
    key, val = (parts[0], parts[1] if len(parts) > 1 else '')
    if key not in _agent.VALID_SET:
        print(f'Unknown: {key}')
        return
    try:
        val = _agent.set_config(key, val)
    except ValueError as e:
        print(f'Error: {e}')
        return
    if key in _agent.SET_ATTRS:
        setattr(agent, key, val)
    if key in ('system', 'subsystem') and key == ('system' if agent.depth < 1 else 'subsystem'):
        agent.history[0] = {'role': 'system', 'content': val}
    if not agent._rc_loading and (not agent.context_size or (key in ('model', 'api') and (not _agent.CONTEXT_SIZE))):
        n = agent._detect_ctx()
        if n:
            agent.context_size = n


def cmd_source(agent, arg, *, input=None, tk_root=None):
    """Load rc file (overrides env)."""
    path = (arg or '').strip()
    if not path or not _agent.os.path.isfile(path):
        print('Usage: /source <path>')
        return
    agent._load_rc(path, override_env=True)
    agent.model, agent.api, agent.api_key = (_agent.MODEL, _agent.API, _agent.API_KEY)
    agent.context_size = _agent.CONTEXT_SIZE or agent.context_size
    print(f'Sourced {path}')


def _frontend_forget(*, tk_root, bridge, arg=""):
    """Display the last ready memory snapshot without reading or writing storage."""
    import tkinter as tk
    window = tk.Toplevel(tk_root)
    window.title("Forget")
    text = tk.Text(window, wrap="word", width=80, height=20)
    text.pack(fill="both", expand=True)
    memories = bridge.workspace.get("memories", [])
    text.insert("1.0", "\n".join(f"  {i}: {memory}" for i, memory in enumerate(memories))
                or "No memories.")
    text.configure(state="disabled")
    windows = tk_root.__dict__.setdefault(("_agent_forget_windows", _WINDOW_OWNER), [])
    windows.append(window)
    window.bind("<Escape>", lambda event: window.destroy())
    return window


def _close_forget(tk_root):
    for window in tk_root.__dict__.pop(("_agent_forget_windows", _WINDOW_OWNER), []):
        if window.winfo_exists():
            window.destroy()


def cmd_forget(agent, arg, *, input=None, tk_root=None):
    """List long term memories or forget given memory."""
    mem = _agent.load_memories()
    if not arg.strip():
        print('\n'.join(f"  {i}: {m.replace(chr(10), ' ')}" for i, m in enumerate(mem))
              or 'No memories.')
        return
    try:
        idxs = sorted({int(x) for x in arg.split()}, reverse=True)
    except ValueError:
        print('Usage: /forget <index...>')
        return
    for i in idxs:
        if 0 <= i < len(mem):
            print(f"Forgot [{i}]: {mem.pop(i).replace(chr(10), ' ')[:60]}")
        else:
            print(f'Bad index {i}')
    _agent.save_memories(mem)
    agent.inject_memories()
    agent.save()
    print(f'{len(mem)} remain.')


cmd_forget.ui = {"menu": "Core", "label": "Forget…", "direct": True,
                 "frontend": "_frontend_forget", "cleanup": "_close_forget", "empty_args_only": True,
                 "safe_during_inference": True}


def cmd_export(agent, arg, *, input=None, tk_root=None):
    """Export an importable composite .py: isolated user modules, effective aliases,
        prefixed docs and memory metadata. History and UTF-8 datafiles accompany /meld.
        Core modules and backend configuration/credentials are not exported. Source,
        history, memories and datafiles are user content; inspect before sharing.
        """
    if not arg:
        _s = _agent.stamp().replace(':', '').replace(' ', '_')
        arg = f'{_agent.AGENT_DIR}/export_{_s}.py'
    try:
        datafiles = {}
        directory = _agent.os.path.join(_agent.AGENT_DIR, 'datafiles')
        if _agent.os.path.lexists(directory):
            if _agent.os.path.islink(directory) or not _agent.os.path.isdir(directory):
                raise ValueError('Unsafe datafiles directory')
            for name in _agent.os.listdir(directory):
                path = _agent.os.path.join(directory, name)
                if not _agent.stat.S_ISREG(_agent.os.lstat(path).st_mode):
                    raise ValueError(f'Unsafe datafile: {name!r}')
                with open(path, encoding='utf8', newline='') as f:
                    datafiles[name] = f.read()
        components, docs, memories = ([], [], _agent.load_memories())
        for name, module in agent.tool_modules.items():
            if name in agent.core_modules:
                continue
            source = _load_tools_source() if name == 'tools' and module.__file__ != _agent.os.path.join(_agent.TOOLS_DIR, 'tools.py') else module._tool_source
            methods = [key for key, owner in agent.tool_owners.items() if owner == name]
            commands = [key for key, owner in agent.command_owners.items() if owner == name]
            components.append((name, source, methods, commands))
            if _agent.inspect.getdoc(module):
                docs.append(f'{name}:\n{_agent.inspect.getdoc(module)}')
            memories = list(dict.fromkeys(memories + _agent.tool_forget_list(module)))
        payload = {'history': list(agent.history), 'memories': _agent.load_memories(), 'datafiles': datafiles}
        source = repr('\n\n'.join(docs)) + '\n'
        source += 'forget = ' + repr(memories) + '\n'
        source += '_agent_meld = ' + repr(payload) + '\n'
        source += '_components = ' + repr(components) + '\n'
        source += '\ndef _load_components():\n    import types\n    namespaces, aliases = [], {}\n    for name, source, methods, commands in _components:\n        module = types.ModuleType(name)\n        module.__file__ = __file__\n        module.__dict__["__builtins__"] = __builtins__\n        if "_agent" in globals():\n            module._agent = _agent\n        exec(compile(source, __file__ + ":" + name, "exec"), vars(module))\n        namespaces.append(module)\n        for alias in methods:\n            aliases[alias] = vars(module)[alias]\n        for alias in commands:\n            aliases["cmd_" + alias] = vars(module)["cmd_" + alias]\n    globals().update(aliases)\n    return namespaces\n_component_modules = _load_components()\ndel _load_components\n'
        source += '\ndef _system_context():\n    return "\\n\\n".join(context for module in _component_modules\n                         if (hook := getattr(module, "_system_context", None))\n                         and (context := hook()))\n'
        compile(source, arg, 'exec')
        with open(arg, 'w', encoding='utf8') as f:
            f.write(source)
    except (OSError, ValueError, SyntaxError, AttributeError) as e:
        print(f'Export failed: {e}')
        return
    print(f'Exported composite Python module to {arg}')


def cmd_meld(agent, arg, *, input=None, tk_root=None):
    """Merge a composite Python export or legacy JSON/history. Python requires
        explicit consent before any execution; trusted code is not sandboxed.
        Datafile names and all destinations are validated before writes.
        """
    if not arg:
        print('Usage: /meld <filename>')
        return
    if not _agent.os.path.isfile(arg):
        print(f'No such file: {arg}')
        return
    try:
        with open(arg, encoding='utf8') as f:
            source = f.read()
        python_module = None
        try:
            data = _agent.json.loads(source)
        except ValueError:
            answer = _agent._command_input('Python meld executes code (not sandboxed). Execute and meld? [y/N] ', input, tk_root).strip().lower()
            if answer not in ('y', 'yes'):
                print('Meld declined.')
                return
            python_module = _agent.load_tool_module(arg)
            data = getattr(python_module, '_agent_meld', {})
            if not isinstance(data, dict):
                raise ValueError('Python meld payload must be an object')
            forget = _agent.tool_forget_list(python_module)
            built = _agent.build_tools(python_module)
        memories = data.get('memories', []) if isinstance(data, dict) else []
        if not isinstance(memories, list) or any((not isinstance(item, str) for item in memories)):
            raise ValueError('Memories must be a list of strings')
        datafiles = data.get('datafiles', {}) if isinstance(data, dict) else {}
        if not isinstance(datafiles, dict):
            raise ValueError('Datafiles must be an object of filename: text')
        directory = _agent.os.path.join(_agent.AGENT_DIR, 'datafiles')
        for name, content in datafiles.items():
            if not isinstance(name, str) or name in ('', '.', '..') or _agent.os.path.isabs(name) or any((c in name for c in ('/', '\\', '\x00'))):
                raise ValueError(f'Unsafe datafile name: {name!r}')
            if not isinstance(content, str):
                raise ValueError(f'Datafile contents must be text: {name!r}')
            name.encode('utf8')
            content.encode('utf8')
        if datafiles:
            if _agent.os.path.lexists(directory) and (_agent.os.path.islink(directory) or not _agent.os.path.isdir(directory)):
                raise ValueError('Unsafe datafiles directory')
            for name in datafiles:
                path = _agent.os.path.join(directory, name)
                if _agent.os.path.lexists(path) and (not _agent.stat.S_ISREG(_agent.os.lstat(path).st_mode)):
                    raise ValueError(f'Unsafe datafile destination: {name!r}')
        if python_module is not None:
            name, _ = _agent.tool_module_source(arg)
            _agent.os.makedirs(_agent.TOOLS_DIR, exist_ok=True)
            destination = _agent.os.path.join(_agent.TOOLS_DIR, name + '.py')
            with open(destination + '.tmp', 'w', encoding='utf8') as stream:
                stream.write(source)
            _agent.os.replace(destination + '.tmp', destination)
            python_module.__file__ = destination
            agent._register_module(name, python_module, built, forget)
            agent.core_modules.discard(name)
            agent._append_systemcmd(run_command=False)
        if datafiles:
            _agent.os.makedirs(directory, exist_ok=True)
            for name, content in datafiles.items():
                with open(_agent.os.path.join(directory, name), 'w', encoding='utf8', newline='') as f:
                    f.write(content)
    except Exception as e:
        print(f'Merge failed: {e}')
        return
    imported = data.get('history', []) if isinstance(data, dict) else data
    if not isinstance(imported, list):
        print('No extra history.')
    else:
        for m in imported:
            agent.history.append(m)
    mems = data.get('memories', []) if isinstance(data, dict) else []
    if not isinstance(mems, list):
        print('No extra memories.')
    else:
        cur = _agent.load_memories()
        for m in mems:
            if m not in cur:
                cur.append(m)
        _agent.save_memories(cur)
        agent.inject_memories()
    tools_src = data.get('tools') if isinstance(data, dict) else None
    tools_msg = ''
    if isinstance(tools_src, str) and tools_src.strip():
        ans = _agent._command_input(f'Import file contains a tools.py ({len(tools_src.splitlines())} lines). Meld it in? [y/N] ', input, tk_root).strip().lower()
        if ans in ('y', 'yes'):
            tmp_path = f'{_agent.AGENT_DIR}/meld_tools_{_agent.time.time_ns()}.py'
            try:
                with open(tmp_path, 'w', encoding='utf8') as f:
                    f.write(tools_src)
                module = _agent.load_tool_module(tmp_path, 'tools')
                forget = _agent.tool_forget_list(module)
                nt, nm, nc = _agent.build_tools(module)
                _agent.append_tool_memories(forget)
                agent._register_tools(nt, nm, nc, owner='tools')
                agent.tool_modules['tools'] = module
                _append_tools_source(tools_src, f'melded from {arg}')
                tools_msg = f'; melded {len(nt)} tool(s)'
            except Exception as e:
                tools_msg = f'; tools meld failed: {e}'
            finally:
                try:
                    _agent.os.remove(tmp_path)
                except OSError:
                    pass
        else:
            tools_msg = '; discarded tools'
    agent.save()
    print(f'Merged {len(imported)} history messages and {len(mems)} memories{tools_msg}.')


def cmd_loop(agent, arg, *, input=None, tk_root=None):
    """/loop [seconds] [directive] - Load looprc; run, dream, sleep, repeat until complete."""
    parts = (arg or '').split(None, 1)
    try:
        seconds = int(parts[0])
    except (ValueError, IndexError):
        seconds = 60
    directive = parts[1] if len(parts) > 1 else ''
    agent._load_rc(_agent.LOOPRC, override_env=False)
    tty = input is not None
    if directive:
        agent.cmdline(directive, tty)
    while 'continue' in (cmd_dream(agent, '', input=input, tk_root=tk_root) or '').lower():
        if directive:
            agent.cmdline(directive, tty)
        _agent.time.sleep(max(1, seconds))


def cmd_dream(agent, arg, *, input=None, tk_root=None):
    """save a memory, summarize memories, start a new conversation."""
    agent.resettty()
    if len(agent.history) <= 2:
        print('Nothing to dream: empty conversation.')
        conv_summary = None
    else:
        print('Dreaming: summarizing conversation...')
        conv_summary = agent.compact(agent.history, summary_only=True)
        if not conv_summary:
            print('Conversation summary failed.')
        else:
            entry = f'Dream session ({_agent.stamp()}):\n{conv_summary}'
            m = _agent.load_memories()
            m.append(entry)
            _agent.save_memories(m)
            print(f'Appended conversation summary to memories (index {len(m) - 1}).')
    mem = _agent.load_memories()
    if not mem:
        print('No memories to summarize.')
        agent.inject_memories()
        agent.save()
        return
    print('Dreaming: summarizing memories...')
    body = '\n\n'.join((f'[{i}]\n{t}' for i, t in enumerate(mem)))
    h = [{'role': 'user', 'content': "Summarize these persistent memories. Merge duplicates. Keep facts, learnings, decisions,preferences, open tasks, dates. Clinical English. Complete but concise.Make careful note of the working directory and any important files.For each memory worth keeping going forward, call memory_save once with itssummarized text. Save each distinct idea as a separate memory.Keep track of times and event sequences if they are important.Your final status message should be a single line with the word of 'Continue' or 'Complete'.A status message of 'Continue' indicates the project is ongoingA status message of 'Complete' indicates that there is nothing left to do.\n\n" + body}]
    mem_tools = [t for t in agent.tools if t['function']['name'] == 'memory_save']
    msg = agent.api_call(h, tools=mem_tools, proactive=False, speak=False, show=_agent.DOT_PROGRESS)
    agent.updateusage(msg['_usage'], h)
    valid = []
    for tc in msg.get('tool_calls') or []:
        try:
            valid.append(_agent.json.loads(tc['function']['arguments'] or '{}'))
        except _agent.json.JSONDecodeError:
            continue
    status = (msg.get('content', '') or '').split('\n')[-1]
    print('Status', status)
    if not valid:
        print('Memory summary failed.')
    else:
        _agent.save_memories([])
        for args in valid:
            agent.run_tool('memory_save', args)
        print(f'--- Memory summary: kept {len(_agent.load_memories())} memories ---')
    agent.inject_memories()
    agent.save()
    cmd_new(agent, arg, input=input, tk_root=tk_root)
    return status


def cmd_help(agent, arg, *, input=None, tk_root=None):
    """List commands or show command/module documentation: /help [command|module]."""
    commands = {**_agent.Agent.COMMANDS, **agent.user_commands}
    name = arg.strip().removeprefix('/')
    if not name:
        for name, command in commands.items():
            print(f"{name}   {_agent.inspect.getdoc(command) or ''}")
        return
    command = commands.get(name)
    module = agent.tool_modules.get(name)
    if command is not None:
        print(_agent.inspect.getdoc(command) or '')
    elif module is not None:
        print(_agent.inspect.getdoc(module) or '')
        for alias, handler in commands.items():
            if agent.command_owners.get(alias) == name:
                print(f"{alias}   {_agent.inspect.getdoc(handler) or ''}")
    else:
        print('Unknown command or module', name)


def _config_dialog(tk, root, values=None, bridge=None):
    from tkinter import messagebox
    import queue, threading
    result = None
    closed = False
    model_request = 0
    window = tk.Toplevel(root)
    _track_core_window(root, window)
    window.title("Configuration")
    window.transient(root)
    tk.Label(window, text="Effective values (including defaults). OK saves and applies settings now.\n"
             "Other rc commands are retained; these settings override earlier settings.\n"
             "Environment overrides still apply at startup.", justify="left").pack(fill="x")
    frame = tk.Frame(window)
    frame.pack(fill="both", expand=True)
    canvas = tk.Canvas(frame)
    scroll = tk.Scrollbar(frame, command=canvas.yview)
    canvas.configure(yscrollcommand=scroll.set)
    scroll.pack(side="right", fill="y")
    canvas.pack(side="left", fill="both", expand=True)
    table = tk.Frame(canvas)
    item = canvas.create_window((0, 0), window=table, anchor="nw")
    table.bind("<Configure>", lambda event: canvas.configure(scrollregion=canvas.bbox("all")))
    canvas.bind("<Configure>", lambda event: canvas.itemconfigure(item, width=event.width))
    table.columnconfigure(1, weight=1)
    tk.Label(table, text="Key").grid(row=0, column=0, sticky="w")
    tk.Label(table, text="Value").grid(row=0, column=1, sticky="w")
    fields = {}
    for row, (key, value) in enumerate((_effective_config() if values is None else values).items(), 1):
        tk.Label(table, text=key).grid(row=row, column=0, sticky="nw")
        if key == "model":
            from tkinter import ttk
            field = ttk.Combobox(table, width=60, values=(str(value), "Custom..."),
                                 postcommand=lambda: refresh_models())
            field.set(str(value))
            def custom_model(event):
                if fields["model"].get() == "Custom...":
                    fields["model"].set("")
                    fields["model"].focus_set()
            field.bind("<<ComboboxSelected>>", custom_model)
        else:
            field = tk.Text(table, height=3 if "\n" in str(value) else 1, width=60, wrap="word", undo=True)
            field.insert("1.0", str(value))
        field.grid(row=row, column=1, sticky="ew")
        fields[key] = field
        if "\n" not in str(value):
            field.bind("<Return>", lambda event: (save(), "break")[1])
    def field_value(key):
        return fields[key].get() if key == "model" else fields[key].get("1.0", "end-1c")

    def refresh_models():
        nonlocal model_request
        model_request += 1
        request = model_request
        endpoint = (field_value("api"), field_value("api_key"))
        replies = queue.Queue()
        model_status.configure(text="Loading models…")
        def query():
            try:
                models = [item["id"] for item in _agent.query_models(*endpoint)
                          if isinstance(item, dict) and isinstance(item.get("id"), str)]
                replies.put((models, False))
            except Exception:
                replies.put(([], True))
        def poll():
            if closed or not window.winfo_exists() or request != model_request:
                return
            if endpoint != (field_value("api"), field_value("api_key")):
                model_status.configure(text="Credentials changed; refresh models.")
                return
            try: models, failed = replies.get_nowait()
            except queue.Empty:
                window.after(100, poll)
                return
            current = field_value("model")
            choices = list(dict.fromkeys([current] + models))
            fields["model"].configure(values=[value for value in choices if value != "Custom..."] + ["Custom..."])
            model_status.configure(text="Model query failed; custom entry is available." if failed else "Models loaded; reopen dropdown to view.")
        if bridge is None:
            threading.Thread(target=query, daemon=True).start()
        else:
            bridge.submit(__name__, "_query_config_models",
                          {"api": endpoint[0], "api_key": endpoint[1]},
                          lambda result, error: replies.put((result or [], bool(error))))
        window.after(100, poll)

    def close():
        nonlocal closed
        closed = True
        window.destroy()

    def save():
        nonlocal result
        values = {key: field_value(key) for key in fields}
        try:
            if values.get("model") == "Custom...":
                raise ValueError("Enter a custom model name.")
            if bridge is None:
                _save_config(values)
            else:
                for key, value in values.items():
                    _agent.config_value(key, value)
                if not bridge.submit_command("/config " + _agent.json.dumps(values)):
                    raise ValueError("Worker unavailable")
        except (OSError, ValueError) as e:
            messagebox.showerror("Configuration not saved", str(e), parent=window)
            return
        result = values
        close()
    buttons = tk.Frame(window)
    buttons.pack(fill="x")
    tk.Button(buttons, text="OK", command=save).pack(side="right")
    tk.Button(buttons, text="Cancel", command=close).pack(side="right")
    if "model" in fields:
        tk.Button(buttons, text="Refresh models", command=refresh_models).pack(side="left")
        model_status = tk.Label(buttons, text="")
        model_status.pack(side="left")
    window.protocol("WM_DELETE_WINDOW", close)
    window.bind("<Escape>", lambda event: close())
    window.geometry("800x600")
    window.grab_set()
    root.wait_window(window)
    return result



def _query_config_models(api, api_key):
    return [item["id"] for item in _agent.query_models(api, api_key)
            if isinstance(item, dict) and isinstance(item.get("id"), str)]


def _track_core_window(root, window):
    windows = root.__dict__.setdefault(("_agent_core_windows", _WINDOW_OWNER), [])
    windows[:] = [item for item in windows if item.winfo_exists()]
    windows.append(window)


def _close_core_windows(tk_root):
    for window in tk_root.__dict__.pop(("_agent_core_windows", _WINDOW_OWNER), []):
        if window.winfo_exists():
            window.destroy()


def _frontend_config(*, tk_root, bridge, arg=""):
    import tkinter as tk
    return _config_dialog(tk, tk_root, bridge.workspace.get("config", {}), bridge=bridge)


def cmd_config(agent, arg, *, input=None, tk_root=None):
    """Save and apply a configuration editor snapshot."""
    if not arg.strip():
        print('Usage: /config <JSON settings>')
        return
    try:
        values = _agent.json.loads(arg)
        if not isinstance(values, dict) or set(values) != set(_agent.SET_GLOBALS):
            raise ValueError("Expected a complete configuration snapshot")
        _save_config(values)
    except (OSError, ValueError, TypeError) as error:
        print("Configuration not saved: " + str(error))
        return
    _apply_config(agent, values)


def _frontend_import(*, tk_root, bridge, arg=""):
    import tkinter as tk
    from tkinter import filedialog
    window = tk.Toplevel(tk_root)
    _track_core_window(tk_root, window)
    window.title("Import tools")
    window.transient(tk_root)
    tk.Label(window, text="Python module:").pack()
    module = tk.Entry(window)
    module.pack(fill="x")

    def finish(value):
        if window.winfo_exists() and value and bridge.submit_command("/import " + value):
            window.destroy()

    tk.Button(window, text="Import module", command=lambda: finish(module.get())).pack()
    tk.Button(window, text="Python file…", command=lambda: finish(filedialog.askopenfilename(
        parent=window, title="Import Python tools",
        filetypes=(("Python files", "*.py"), ("All files", "*"))))).pack()
    tk.Button(window, text="Cancel", command=window.destroy).pack()
    window.bind("<Escape>", lambda event: window.destroy())
    module.focus_set()
    return window


def _frontend_delmodule(*, tk_root, bridge, arg=""):
    import tkinter as tk
    window = tk.Toplevel(tk_root)
    _track_core_window(tk_root, window)
    window.title("Delete Module")
    window.transient(tk_root)
    tk.Label(window, text="Results and errors appear in the transcript.").pack()
    frame = tk.Frame(window)
    frame.pack(fill="both", expand=True)
    canvas = tk.Canvas(frame)
    scroll = tk.Scrollbar(frame, command=canvas.yview)
    canvas.configure(yscrollcommand=scroll.set)
    scroll.pack(side="right", fill="y")
    canvas.pack(side="left", fill="both", expand=True)
    table = tk.Frame(canvas)
    item = canvas.create_window((0, 0), window=table, anchor="nw")
    table.bind("<Configure>", lambda event: canvas.configure(scrollregion=canvas.bbox("all")))
    canvas.bind("<Configure>", lambda event: canvas.itemconfigure(item, width=event.width))

    def refresh(event=None):
        if not window.winfo_exists():
            return
        for child in table.winfo_children():
            child.destroy()
        modules = bridge.workspace.get("deletable_modules", [])
        if not modules:
            tk.Label(table, text="No deletable modules.").pack()
        for module in modules:
            name, token = module["name"], module["token"]
            row = tk.Frame(table)
            row.pack(fill="x")
            tk.Button(row, text="Delete", state="normal" if bridge.available() else "disabled",
                      command=lambda name=name, token=token: bridge.submit_command(
                          "/delmodule " + shlex.quote(name) + " " + shlex.quote(token))).pack(side="right")
            tk.Label(row, text=name, anchor="w").pack(side="left", fill="x", expand=True)

    binding = tk_root.bind("<<AgentStateChanged>>", refresh, add="+")

    def destroyed(event):
        if event.widget is window:
            tk_root.unbind("<<AgentStateChanged>>", binding)

    window.bind("<Destroy>", destroyed)
    window.bind("<Escape>", lambda event: window.destroy())
    tk.Button(window, text="Close", command=window.destroy).pack()
    refresh()
    return window


# Core owns command presentation. The host consumes these declarations generically.
cmd_quick.ui = {"menu": "Core", "label": "Quick mode", "direct": True}
cmd_page.ui = {"menu": "Core", "label": "Page conversation", "direct": True}
cmd_new.ui = {"menu": "File", "label": "New conversation", "direct": True,
              "bindings": ["<Control-Shift-N>"]}
cmd_edit.ui = {"menu": "Core", "label": "Edit…", "direct": True}
cmd_showcfg.ui = {"menu": "Core", "label": "Show configuration", "direct": True}
cmd_status.ui = {"menu": "Core", "label": "Status", "direct": True}
cmd_system.ui = {"menu": "Core", "label": "System prompt…", "argument": {"type": "text"}}
cmd_compact.ui = {"menu": "Core", "label": "Compact conversation", "direct": True}
cmd_import.ui = {"menu": "File", "label": "Import tools…", "direct": True,
                 "frontend": "_frontend_import", "cleanup": "_close_core_windows", "empty_args_only": True}
cmd_newtool.ui = {"menu": "Core", "label": "New tool…", "direct": True}
cmd_delmodule.ui = {"menu": "Core", "label": "Delete Module…", "direct": True,
                   "frontend": "_frontend_delmodule", "cleanup": "_close_core_windows", "empty_args_only": True}
cmd_set.ui = {"menu": "Core", "label": "Edit configuration…", "direct": True,
              "frontend": "_frontend_config", "cleanup": "_close_core_windows", "empty_args_only": True}
cmd_config.ui = {"menu": "Core", "label": "Edit configuration…", "direct": True, "hidden": True,
                 "frontend": "_frontend_config", "cleanup": "_close_core_windows", "empty_args_only": True}
cmd_source.ui = {"menu": "File", "label": "Source configuration…",
                 "argument": {"type": "open", "title": "Source configuration"}}
cmd_export.ui = {"menu": "File", "label": "Export history and memories…", "bindings": ["<Control-s>"],
                 "argument": {"type": "save", "title": "Export history and memories", "defaultextension": ".py",
                              "filetypes": (("Python files", "*.py"), ("All files", "*"))}}
cmd_meld.ui = {"menu": "File", "label": "Merge exported history…", "bindings": ["<Control-Shift-O>"],
               "argument": {"type": "open", "title": "Merge exported history"}}
cmd_loop.ui = {"menu": "Core", "label": "Loop…",
               "argument": {"type": "integer", "title": "Command /loop", "prompt": "Interval in seconds:",
                            "initialvalue": 60, "minvalue": 1}}
cmd_dream.ui = {"menu": "Core", "label": "Dream", "direct": True}
cmd_help.ui = {"menu": "Core", "label": "Help", "direct": True}
