NPC Functions

DEFAULT_MD_AGENT_JINXES = ['sh', 'python', 'edit_file', 'load_file', 'file_search', 'web_search', 'ask_form', 'chat', 'stop'] module-attribute

JINX_SHEBANG = '#!/usr/bin/env npc-jinx' module-attribute

NPC_SHEBANG = '#!/usr/bin/env npc' module-attribute

_DEFAULT_AGENT_TOOLS = [_tool_sh, _tool_python, _tool_edit_file, _tool_load_file, _tool_web_search, _tool_file_search, _tool_stop, _tool_chat] module-attribute

Agent

Bases: NPC

NPC with a default tool set (sh, python, edit_file, load_file, web_search, file_search, stop, chat).

Can also load agent definitions from: - agents.md files (markdown with agent specs) - skills directories (each skill is a jinx) - MCP servers (external tool providers)

Source code in npcpy/npc_compiler.py
class Agent(NPC):
    """NPC with a default tool set (sh, python, edit_file, load_file, web_search, file_search, stop, chat).

    Can also load agent definitions from:
    - agents.md files (markdown with agent specs)
    - skills directories (each skill is a jinx)
    - MCP servers (external tool providers)
    """

    def __init__(
        self,
        name: str = "agent",
        primary_directive: str = "You are a helpful AI agent with access to tools.",
        model: str = None,
        provider: str = None,
        tools: list = None,
        extra_tools: list = None,
        agents_md: str = None,
        skills_dir: str = None,
        mcp_servers: list = None,
        safe_tools: bool = False,
        **kwargs,
    ):
        _EXEC_TOOLS = {_tool_sh, _tool_python}
        all_tools = [t for t in _DEFAULT_AGENT_TOOLS if not safe_tools or t not in _EXEC_TOOLS]
        if extra_tools:
            all_tools.extend(extra_tools)
        if tools is not None:
            all_tools = tools

        super().__init__(
            name=name,
            primary_directive=primary_directive,
            model=model,
            provider=provider,
            tools=all_tools,
            **kwargs,
        )

        if mcp_servers:
            self.mcp_servers = mcp_servers

        if agents_md:
            self._load_agents_md(agents_md)

        if skills_dir:
            self._load_skills_dir(skills_dir)

    def _load_agents_md(self, path: str):
        """Load agent definitions from an agents.md file.

        Format: markdown with H2 headings as agent names, body as directives.
        """
        path = os.path.expanduser(path)
        if not os.path.exists(path):
            return

        with open(path, 'r') as f:
            content = f.read()

        current_name = None
        current_body = []
        agents = {}

        for line in content.split('\n'):
            if line.startswith('## '):
                if current_name:
                    agents[current_name] = '\n'.join(current_body).strip()
                current_name = line[3:].strip()
                current_body = []
            elif current_name is not None:
                current_body.append(line)

        if current_name:
            agents[current_name] = '\n'.join(current_body).strip()

        self._sub_agents = agents

    def _load_skills_dir(self, path: str):
        """Load skills (jinxes) from a directory and add them as tools."""
        path = os.path.expanduser(path)
        if not os.path.isdir(path):
            return

        for fname in os.listdir(path):
            if fname.endswith('.jinx'):
                fpath = os.path.join(path, fname)
                try:
                    jinx = Jinx(jinx_path=fpath)
                    self.jinxes_dict[jinx.jinx_name] = jinx
                except Exception as e:
                    print(f"Warning: Failed to load skill {fname}: {e}")

    def run(
        self,
        input_text: str,
        max_iterations: int = 10,
        verbose: bool = False,
        require_permission: bool = True,
        allow_tools: list = None,
        **kwargs,
    ):
        """Run the agent in a tool-calling loop until it stops calling tools.

        Each iteration: call the model with tools; if it emits tool_calls, execute
        them and feed the results back; if it emits plain content, return it.

        Args:
            input_text: initial user prompt.
            max_iterations: hard cap on tool-calling turns.
            verbose: print each turn's tool calls and results.
            require_permission: if True (default), prompt the user before each
                tool call. Answer [y]es / [n]o / [a]ll (allow the rest of this
                run). Non-TTY environments auto-allow so scripts don't hang.
            allow_tools: optional list of tool names that bypass the prompt.
        """
        import sys
        import json as _json
        import uuid as _uuid
        from npcpy.llm_funcs import get_llm_response

        messages = list(kwargs.get("messages", []) or [])
        stream = kwargs.get("stream", False)
        prompt = input_text
        last_content = ""
        allow_tools = set(allow_tools or [])
        approve_all = [False]
        is_tty = sys.stdin.isatty()

        def _log(msg):
            if verbose:
                print(msg, flush=True)

        def _ask(tool_name, args):
            if not require_permission or tool_name in allow_tools or approve_all[0]:
                return True
            if not is_tty:
                _log(f"[agent:{self.name}] non-TTY: auto-allow {tool_name}")
                return True
            args_str = str(args)
            if len(args_str) > 300:
                args_str = args_str[:300] + "…"
            print(f"\n[agent:{self.name}] allow tool: {tool_name}({args_str})?", flush=True)
            resp = input("  [y]es / [n]o / [a]ll: ").strip().lower()
            if resp == "a":
                approve_all[0] = True
                return True
            return resp.startswith("y")

        def _extract_tc(tc):
            if isinstance(tc, dict):
                tc_id = tc.get("id") or str(_uuid.uuid4())
                fn = tc.get("function", {}) or {}
                name = fn.get("name", "")
                args_raw = fn.get("arguments", "{}")
            else:
                tc_id = getattr(tc, "id", None) or str(_uuid.uuid4())
                fn_obj = getattr(tc, "function", None)
                name = getattr(fn_obj, "name", "") if fn_obj else ""
                args_raw = getattr(fn_obj, "arguments", "{}") if fn_obj else "{}"
            if isinstance(args_raw, str):
                try:
                    args = _json.loads(args_raw)
                except (_json.JSONDecodeError, TypeError):
                    args = {"raw_arguments": args_raw}
            else:
                args = args_raw or {}
            return tc_id, name, args

        _log(f"[agent:{self.name}] run start | model={self.model} provider={self.provider} | prompt={input_text!r}")

        for iteration in range(max_iterations):
            _log(f"[agent:{self.name}] iter {iteration+1}/{max_iterations} → calling model")
            result = get_llm_response(
                prompt,
                npc=self,
                model=self.model,
                provider=self.provider,
                tools=self.tools,
                tool_map=self.tool_map,
                messages=messages,
                stream=stream,
            )
            if not isinstance(result, dict):
                return str(result)

            tool_calls = result.get("tool_calls")
            content = result.get("output", result.get("response", "")) or ""
            if content:
                last_content = content

            if not tool_calls:
                _log(f"[agent:{self.name}] no tool_calls → returning content ({len(last_content)} chars)")
                return last_content

            messages = result.get("messages", messages)
            # Drop the empty assistant turn get_ollama_response appends when the
            # model only emitted tool_calls — we'll add a proper one below.
            if (messages and messages[-1].get("role") == "assistant"
                    and not messages[-1].get("content")
                    and "tool_calls" not in messages[-1]):
                messages = messages[:-1]

            extracted = [_extract_tc(tc) for tc in tool_calls]
            _log(f"[agent:{self.name}] tool_calls: {[name for _, name, _ in extracted]}")

            messages.append({
                "role": "assistant",
                "content": None,
                "tool_calls": [
                    {
                        "id": tc_id,
                        "type": "function",
                        "function": {"name": name, "arguments": args},
                    }
                    for tc_id, name, args in extracted
                ],
            })

            for tc_id, name, args in extracted:
                if not _ask(name, args):
                    result_str = "[permission denied by user]"
                elif name in self.tool_map:
                    try:
                        tool_result = self.tool_map[name](**args)
                        result_str = _json.dumps(tool_result, default=str) if not isinstance(tool_result, str) else tool_result
                    except Exception as e:
                        result_str = f"Error executing {name}: {e}"
                else:
                    result_str = f"Unknown tool: {name}"

                messages.append({
                    "role": "tool",
                    "tool_call_id": tc_id,
                    "content": result_str,
                })

                disp_args = str(args)
                disp_res = result_str
                if len(disp_args) > 200:
                    disp_args = disp_args[:200] + "…"
                if len(disp_res) > 400:
                    disp_res = disp_res[:400] + "…"
                _log(f"[agent:{self.name}]   → {name}({disp_args}) = {disp_res}")

            prompt = None

        _log(f"[agent:{self.name}] hit max_iterations={max_iterations}")
        return last_content or "Max iterations reached without a final answer."

mcp_servers = mcp_servers instance-attribute

run(input_text, max_iterations=10, verbose=False, require_permission=True, allow_tools=None, **kwargs)

Run the agent in a tool-calling loop until it stops calling tools.

Each iteration: call the model with tools; if it emits tool_calls, execute them and feed the results back; if it emits plain content, return it.

Parameters:
  • input_text (str) –

    initial user prompt.

  • max_iterations (int, default: 10 ) –

    hard cap on tool-calling turns.

  • verbose (bool, default: False ) –

    print each turn's tool calls and results.

  • require_permission (bool, default: True ) –

    if True (default), prompt the user before each tool call. Answer [y]es / [n]o / [a]ll (allow the rest of this run). Non-TTY environments auto-allow so scripts don't hang.

  • allow_tools (list, default: None ) –

    optional list of tool names that bypass the prompt.

Source code in npcpy/npc_compiler.py
def run(
    self,
    input_text: str,
    max_iterations: int = 10,
    verbose: bool = False,
    require_permission: bool = True,
    allow_tools: list = None,
    **kwargs,
):
    """Run the agent in a tool-calling loop until it stops calling tools.

    Each iteration: call the model with tools; if it emits tool_calls, execute
    them and feed the results back; if it emits plain content, return it.

    Args:
        input_text: initial user prompt.
        max_iterations: hard cap on tool-calling turns.
        verbose: print each turn's tool calls and results.
        require_permission: if True (default), prompt the user before each
            tool call. Answer [y]es / [n]o / [a]ll (allow the rest of this
            run). Non-TTY environments auto-allow so scripts don't hang.
        allow_tools: optional list of tool names that bypass the prompt.
    """
    import sys
    import json as _json
    import uuid as _uuid
    from npcpy.llm_funcs import get_llm_response

    messages = list(kwargs.get("messages", []) or [])
    stream = kwargs.get("stream", False)
    prompt = input_text
    last_content = ""
    allow_tools = set(allow_tools or [])
    approve_all = [False]
    is_tty = sys.stdin.isatty()

    def _log(msg):
        if verbose:
            print(msg, flush=True)

    def _ask(tool_name, args):
        if not require_permission or tool_name in allow_tools or approve_all[0]:
            return True
        if not is_tty:
            _log(f"[agent:{self.name}] non-TTY: auto-allow {tool_name}")
            return True
        args_str = str(args)
        if len(args_str) > 300:
            args_str = args_str[:300] + "…"
        print(f"\n[agent:{self.name}] allow tool: {tool_name}({args_str})?", flush=True)
        resp = input("  [y]es / [n]o / [a]ll: ").strip().lower()
        if resp == "a":
            approve_all[0] = True
            return True
        return resp.startswith("y")

    def _extract_tc(tc):
        if isinstance(tc, dict):
            tc_id = tc.get("id") or str(_uuid.uuid4())
            fn = tc.get("function", {}) or {}
            name = fn.get("name", "")
            args_raw = fn.get("arguments", "{}")
        else:
            tc_id = getattr(tc, "id", None) or str(_uuid.uuid4())
            fn_obj = getattr(tc, "function", None)
            name = getattr(fn_obj, "name", "") if fn_obj else ""
            args_raw = getattr(fn_obj, "arguments", "{}") if fn_obj else "{}"
        if isinstance(args_raw, str):
            try:
                args = _json.loads(args_raw)
            except (_json.JSONDecodeError, TypeError):
                args = {"raw_arguments": args_raw}
        else:
            args = args_raw or {}
        return tc_id, name, args

    _log(f"[agent:{self.name}] run start | model={self.model} provider={self.provider} | prompt={input_text!r}")

    for iteration in range(max_iterations):
        _log(f"[agent:{self.name}] iter {iteration+1}/{max_iterations} → calling model")
        result = get_llm_response(
            prompt,
            npc=self,
            model=self.model,
            provider=self.provider,
            tools=self.tools,
            tool_map=self.tool_map,
            messages=messages,
            stream=stream,
        )
        if not isinstance(result, dict):
            return str(result)

        tool_calls = result.get("tool_calls")
        content = result.get("output", result.get("response", "")) or ""
        if content:
            last_content = content

        if not tool_calls:
            _log(f"[agent:{self.name}] no tool_calls → returning content ({len(last_content)} chars)")
            return last_content

        messages = result.get("messages", messages)
        # Drop the empty assistant turn get_ollama_response appends when the
        # model only emitted tool_calls — we'll add a proper one below.
        if (messages and messages[-1].get("role") == "assistant"
                and not messages[-1].get("content")
                and "tool_calls" not in messages[-1]):
            messages = messages[:-1]

        extracted = [_extract_tc(tc) for tc in tool_calls]
        _log(f"[agent:{self.name}] tool_calls: {[name for _, name, _ in extracted]}")

        messages.append({
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": tc_id,
                    "type": "function",
                    "function": {"name": name, "arguments": args},
                }
                for tc_id, name, args in extracted
            ],
        })

        for tc_id, name, args in extracted:
            if not _ask(name, args):
                result_str = "[permission denied by user]"
            elif name in self.tool_map:
                try:
                    tool_result = self.tool_map[name](**args)
                    result_str = _json.dumps(tool_result, default=str) if not isinstance(tool_result, str) else tool_result
                except Exception as e:
                    result_str = f"Error executing {name}: {e}"
            else:
                result_str = f"Unknown tool: {name}"

            messages.append({
                "role": "tool",
                "tool_call_id": tc_id,
                "content": result_str,
            })

            disp_args = str(args)
            disp_res = result_str
            if len(disp_args) > 200:
                disp_args = disp_args[:200] + "…"
            if len(disp_res) > 400:
                disp_res = disp_res[:400] + "…"
            _log(f"[agent:{self.name}]   → {name}({disp_args}) = {disp_res}")

        prompt = None

    _log(f"[agent:{self.name}] hit max_iterations={max_iterations}")
    return last_content or "Max iterations reached without a final answer."

CLIAgent

Bases: Agent

Agent that runs CLI tools (claude, opencode, kimi, kilo) as subprocesses.

Session context is managed by npcsh via temp files tied to conversation_id.

Source code in npcpy/npc_compiler.py
class CLIAgent(Agent):
    """Agent that runs CLI tools (claude, opencode, kimi, kilo) as subprocesses.

    Session context is managed by npcsh via temp files tied to conversation_id.
    """

    CLI_COMMANDS = {
        "claude_code": ["claude"],
        "claude": ["claude"],
        "opencode": ["opencode", "run"],
        "kimi_code": ["kimi"],
        "kimi": ["kimi"],
        "kilo_code": ["kilo", "run"],
        "kilo": ["kilo", "run"],
        "npcsh": ["npcsh"],
        "gemini": ["gemini"],
        "codex": ["codex"],
        "nanocoder": ["nanocoder"],
    }

    def __init__(
        self,
        cli_provider: str,
        name: str = "cli_agent",
        primary_directive: str = None,
        model: str = None,
        session_file: str = None,
        **kwargs,
    ):
        if primary_directive is None:
            primary_directive = f"CLI agent using {cli_provider} for code tasks."

        kwargs.pop("provider", None)
        super().__init__(
            name=name,
            primary_directive=primary_directive,
            model=model,
            provider=cli_provider,
            **kwargs,
        )

        self.cli_provider = cli_provider
        self.session_file = session_file

    def run(self, input_text: str, verbose: bool = False, session_context: str = None, **kwargs):
        from npcpy.gen.cli_agent import run_cli_agent

        full_prompt = f"{session_context}\n\n{input_text}" if session_context else input_text
        return run_cli_agent(
            provider=self.cli_provider,
            prompt=full_prompt,
            model=self.model,
            system_prompt=self.primary_directive,
            session_id=kwargs.get("session_id"),
            history=kwargs.get("messages"),
            images=kwargs.get("images"),
            think=kwargs.get("think"),
            n_samples=kwargs.get("n_samples", 1),
            verbose=verbose,
        )

cli_provider = cli_provider instance-attribute

session_file = session_file instance-attribute

run(input_text, verbose=False, session_context=None, **kwargs)

Source code in npcpy/npc_compiler.py
def run(self, input_text: str, verbose: bool = False, session_context: str = None, **kwargs):
    from npcpy.gen.cli_agent import run_cli_agent

    full_prompt = f"{session_context}\n\n{input_text}" if session_context else input_text
    return run_cli_agent(
        provider=self.cli_provider,
        prompt=full_prompt,
        model=self.model,
        system_prompt=self.primary_directive,
        session_id=kwargs.get("session_id"),
        history=kwargs.get("messages"),
        images=kwargs.get("images"),
        think=kwargs.get("think"),
        n_samples=kwargs.get("n_samples", 1),
        verbose=verbose,
    )

CodingAgent

Bases: Agent

Agent that auto-detects + executes code blocks in LLM responses.

Source code in npcpy/npc_compiler.py
class CodingAgent(Agent):
    """Agent that auto-detects + executes code blocks in LLM responses."""

    def __init__(
        self,
        name: str = "coding_agent",
        primary_directive: str = None,
        language: str = "python",
        auto_execute: bool = True,
        model: str = None,
        provider: str = None,
        **kwargs,
    ):
        if primary_directive is None:
            primary_directive = (
                f"You are a coding agent specialized in {language}. "
                f"Write {language} code in fenced code blocks (```{language}). "
                "The code will be automatically executed and the output fed back to you."
            )

        super().__init__(
            name=name,
            primary_directive=primary_directive,
            model=model,
            provider=provider,
            **kwargs,
        )

        self.language = language
        self.auto_execute = auto_execute

    def extract_code_blocks(self, text: str) -> list:
        """Extract code blocks matching this agent's language."""
        pattern = re.compile(r"```(\w+)?\s*\n(.*?)```", re.DOTALL)
        blocks = []
        for match in pattern.finditer(text):
            lang = (match.group(1) or "").lower()
            code = match.group(2).strip()
            if lang == self.language.lower() or (not lang and self.language == "python"):
                blocks.append(code)
        return blocks

    def execute_code(self, code: str) -> str:
        """Execute a code block and return the output."""
        lang = self.language.lower()
        if lang == "python":
            return _tool_python(code)
        elif lang in ("bash", "sh", "shell"):
            return _tool_sh(code)
        elif lang in ("javascript", "js", "node"):
            try:
                result = subprocess.run(
                    ["node", "-e", code], capture_output=True, text=True, timeout=120
                )
                out = result.stdout
                if result.returncode != 0 and result.stderr:
                    out += f"\nSTDERR:\n{result.stderr}"
                return out or "(no output)"
            except Exception as e:
                return f"Error: {e}"
        else:
            return f"Execution not supported for language: {lang}"

    def run(self, input_text: str, **kwargs):
        """Run with auto-execution of code blocks."""
        from npcpy.llm_funcs import get_llm_response

        messages = kwargs.get("messages", [])
        max_rounds = kwargs.get("max_rounds", 5)
        current_input = input_text
        response_text = ""

        for _ in range(max_rounds):
            result = get_llm_response(
                current_input,
                npc=self,
                model=self.model,
                provider=self.provider,
                tools=self.tools,
                tool_map=self.tool_map,
                messages=messages,
                stream=kwargs.get("stream", False),
            )

            if isinstance(result, dict):
                response_text = result.get("output", result.get("response", str(result)))
                messages = result.get("messages", messages)
            else:
                response_text = str(result)

            if not self.auto_execute:
                return response_text

            code_blocks = self.extract_code_blocks(response_text)
            if not code_blocks:
                return response_text

            execution_results = []
            for i, code in enumerate(code_blocks, 1):
                output = self.execute_code(code)
                execution_results.append(f"[Block {i} output]:\n{output}")

            current_input = "Code execution results:\n" + "\n\n".join(execution_results)

        return response_text

auto_execute = auto_execute instance-attribute

language = language instance-attribute

execute_code(code)

Execute a code block and return the output.

Source code in npcpy/npc_compiler.py
def execute_code(self, code: str) -> str:
    """Execute a code block and return the output."""
    lang = self.language.lower()
    if lang == "python":
        return _tool_python(code)
    elif lang in ("bash", "sh", "shell"):
        return _tool_sh(code)
    elif lang in ("javascript", "js", "node"):
        try:
            result = subprocess.run(
                ["node", "-e", code], capture_output=True, text=True, timeout=120
            )
            out = result.stdout
            if result.returncode != 0 and result.stderr:
                out += f"\nSTDERR:\n{result.stderr}"
            return out or "(no output)"
        except Exception as e:
            return f"Error: {e}"
    else:
        return f"Execution not supported for language: {lang}"

extract_code_blocks(text)

Extract code blocks matching this agent's language.

Source code in npcpy/npc_compiler.py
def extract_code_blocks(self, text: str) -> list:
    """Extract code blocks matching this agent's language."""
    pattern = re.compile(r"```(\w+)?\s*\n(.*?)```", re.DOTALL)
    blocks = []
    for match in pattern.finditer(text):
        lang = (match.group(1) or "").lower()
        code = match.group(2).strip()
        if lang == self.language.lower() or (not lang and self.language == "python"):
            blocks.append(code)
    return blocks

run(input_text, **kwargs)

Run with auto-execution of code blocks.

Source code in npcpy/npc_compiler.py
def run(self, input_text: str, **kwargs):
    """Run with auto-execution of code blocks."""
    from npcpy.llm_funcs import get_llm_response

    messages = kwargs.get("messages", [])
    max_rounds = kwargs.get("max_rounds", 5)
    current_input = input_text
    response_text = ""

    for _ in range(max_rounds):
        result = get_llm_response(
            current_input,
            npc=self,
            model=self.model,
            provider=self.provider,
            tools=self.tools,
            tool_map=self.tool_map,
            messages=messages,
            stream=kwargs.get("stream", False),
        )

        if isinstance(result, dict):
            response_text = result.get("output", result.get("response", str(result)))
            messages = result.get("messages", messages)
        else:
            response_text = str(result)

        if not self.auto_execute:
            return response_text

        code_blocks = self.extract_code_blocks(response_text)
        if not code_blocks:
            return response_text

        execution_results = []
        for i, code in enumerate(code_blocks, 1):
            output = self.execute_code(code)
            execution_results.append(f"[Block {i} output]:\n{output}")

        current_input = "Code execution results:\n" + "\n\n".join(execution_results)

    return response_text

Jinx

Jinx represents a workflow template with Jinja-rendered steps.

Loads YAML definition containing: - jinx_name: identifier - inputs: list of input parameters - description: what the jinx does - npc: optional NPC to execute with - steps: list of step definitions with code. This section can now be a Jinja template itself. - file_context: optional list of file patterns to include as context

Execution: - Renders Jinja templates in step code with input values - Executes resulting Python code - Returns context with outputs

Source code in npcpy/npc_compiler.py
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
class Jinx:
    ''' 
    Jinx represents a workflow template with Jinja-rendered steps.

    Loads YAML definition containing:
    - jinx_name: identifier
    - inputs: list of input parameters
    - description: what the jinx does
    - npc: optional NPC to execute with
    - steps: list of step definitions with code. This section can now be a Jinja template itself.
    - file_context: optional list of file patterns to include as context

    Execution:
    - Renders Jinja templates in step code with input values
    - Executes resulting Python code
    - Returns context with outputs
    '''
    def __init__(self, jinx_data=None, jinx_path=None):
        if jinx_path:
            self._load_from_file(jinx_path)
        elif jinx_data:
            self._load_from_data(jinx_data)
        else:
            raise ValueError("Either jinx_data or jinx_path must be provided")

        self._raw_steps = list(self.steps)
        if self.steps and all(isinstance(s, dict) for s in self.steps):
            pass
        else:
            self.steps = []
        self.parsed_files = {}
        if self.file_context:
            self.parsed_files = self._parse_file_patterns(self.file_context)

    def _load_from_file(self, path):
        jinx_data = load_yaml_file(path)
        if not jinx_data:
            raise ValueError(f"Failed to load jinx from {path}")
        jinx_data['_source_path'] = path
        self._load_from_data(jinx_data)


    def _load_from_data(self, jinx_data):
        if not jinx_data or not isinstance(jinx_data, dict):
            raise ValueError("Invalid jinx data provided")

        if "jinx_name" not in jinx_data:
            raise KeyError("Missing 'jinx_name' in jinx definition")

        self.jinx_name = jinx_data.get("jinx_name")
        self.inputs = jinx_data.get("inputs", [])
        self.description = jinx_data.get("description", "")
        self.npc = jinx_data.get("npc")
        self.steps = jinx_data.get("steps", [])
        self.file_context = jinx_data.get("file_context", [])
        self._source_path = jinx_data.get("_source_path", None)

    def to_tool_def(self) -> Dict[str, Any]:
        """Convert this Jinx to an OpenAI-style tool definition."""
        properties = {}
        required = []
        for inp in self.inputs:
            if isinstance(inp, str):
                properties[inp] = {"type": "string", "description": f"Parameter: {inp}"}
                required.append(inp)
            elif isinstance(inp, dict):
                name = list(inp.keys())[0]
                default_val = inp.get(name, "")
                desc = f"Parameter: {name}"
                if default_val != "":
                    desc += f" (default: {default_val})"
                properties[name] = {"type": "string", "description": desc}
        return {
            "type": "function",
            "function": {
                "name": self.jinx_name,
                "description": self.description or f"Jinx: {self.jinx_name}",
                "parameters": {
                    "type": "object",
                    "properties": properties,
                    "required": required
                }
            }
        }

    def render_first_pass(
        self,
        jinja_env_for_macros: Environment,
        all_jinx_callables: Dict[str, Callable]
    ):
        """
        Performs the first-pass Jinja rendering on the Jinx's raw steps.
        This expands Jinja control flow (for, if) to generate step structures,
        then expands nested Jinx calls (e.g., {{ sh(...) }} or engine: jinx_name)
        and inline macros.
        """
        if self._raw_steps and isinstance(self._raw_steps[0], dict):
            structurally_expanded_steps = list(self._raw_steps)
        else:
            raw_steps_template_string = "\n".join(self._raw_steps)

            try:
                steps_template = jinja_env_for_macros.from_string(raw_steps_template_string)
                rendered_steps_yaml_string = steps_template.render(**jinja_env_for_macros.globals)
            except Exception as e:
                self.steps = list(self._raw_steps)
                return

            try:
                structurally_expanded_steps = yaml.safe_load(rendered_steps_yaml_string)
                if not isinstance(structurally_expanded_steps, list):
                    if structurally_expanded_steps is None:
                        structurally_expanded_steps = []
                    else:
                        raise ValueError(f"Rendered steps YAML did not result in a list: {type(structurally_expanded_steps)}")
            except Exception as e:
                self.steps = list(self._raw_steps)
                return

        final_rendered_steps = []
        for raw_step in structurally_expanded_steps:
            if not isinstance(raw_step, dict):
                final_rendered_steps.append(raw_step)
                continue

            engine_name = raw_step.get('engine')

            if engine_name and engine_name in all_jinx_callables:
                step_name = raw_step.get('name', f'call_{engine_name}')
                jinx_args = {
                    k: v for k, v in raw_step.items() 
                    if k not in ['engine', 'name']
                }

                jinx_callable = all_jinx_callables[engine_name]
                try:
                    expanded_yaml_string = jinx_callable(**jinx_args)
                    expanded_steps = yaml.safe_load(expanded_yaml_string)

                    if isinstance(expanded_steps, list):
                        final_rendered_steps.extend(expanded_steps)
                    elif expanded_steps is not None:
                        final_rendered_steps.append(expanded_steps)
                except Exception as e:
                    final_rendered_steps.append(raw_step)
            elif raw_step.get('engine') in ['python', 'bash']:
                processed_step = {}
                for key, value in raw_step.items():
                    if isinstance(value, str):
                        has_template_var = '{{' in value and '}}' in value
                        if has_template_var:
                            processed_step[key] = value
                        else:
                            try:
                                template = jinja_env_for_macros.from_string(value)
                                rendered_value = template.render({})
                                try:
                                    loaded_value = yaml.safe_load(rendered_value)
                                    processed_step[key] = loaded_value
                                except yaml.YAMLError:
                                    processed_step[key] = rendered_value
                            except Exception as e:
                                processed_step[key] = value
                    else:
                        processed_step[key] = value
                final_rendered_steps.append(processed_step)
            else:
                processed_step = {}
                for key, value in raw_step.items():
                    if isinstance(value, str):
                        try:
                            template = jinja_env_for_macros.from_string(value)
                            rendered_value = template.render({})
                            try:
                                loaded_value = yaml.safe_load(rendered_value)
                                processed_step[key] = loaded_value
                            except yaml.YAMLError:
                                processed_step[key] = rendered_value
                        except Exception as e:
                            processed_step[key] = value
                    else:
                        processed_step[key] = value
                final_rendered_steps.append(processed_step)

        self.steps = final_rendered_steps

    def execute(self,
                input_values: Dict[str, Any],
                npc: Optional[Any] = None,
                messages: Optional[List[Dict[str, str]]] = None,
                extra_globals: Optional[Dict[str, Any]] = None,
                jinja_env: Optional[Environment] = None):

        if jinja_env is None:
            jinja_env = SandboxedEnvironment(
                loader=DictLoader({}),
                undefined=SilentUndefined,
            )

        active_npc = self.npc if self.npc else npc

        # If npc is a list or NPCArray, run this jinx in parallel across all instances
        from npcpy.npc_array import NPCArray
        if isinstance(active_npc, (list, NPCArray)):
            arr = NPCArray.from_npcs(active_npc) if isinstance(active_npc, list) else active_npc
            return arr.jinx(self.jinx_name, inputs=input_values).collect()

        context = (
            active_npc.shared_context.copy() 
            if active_npc and hasattr(active_npc, 'shared_context') 
            else {}
        )
        context.update(input_values)
        context.update({
            "llm_response": None,
            "output": None,
            "messages": messages,
            "npc": active_npc
        })

        if self.parsed_files:
            context['file_context'] = self._format_parsed_files_context(self.parsed_files)
            context['files'] = self.parsed_files

        for i, step in enumerate(self.steps):
            context = self._execute_step(
                step,
                context,
                jinja_env,
                npc=active_npc,
                messages=messages,
                extra_globals=extra_globals
            )
            output_str = str(context.get("output", ""))
            if "error" in output_str.lower():
                break

        return context

    def _execute_step(self,
                  step: Dict[str, Any],
                  context: Dict[str, Any],
                  jinja_env: Environment,
                  npc: Optional[Any] = None,
                  messages: Optional[List[Dict[str, str]]] = None,
                  extra_globals: Optional[Dict[str, Any]] = None):

        step_name = step.get("name", "unnamed_step")
        step_npc = step.get("npc")
        active_npc = step_npc if step_npc else npc

        code_content = step.get("code") or ""

        try:
            template = jinja_env.from_string(code_content)
            rendered_code = template.render(**context)
        except Exception as e:
            error_msg = f"Error rendering template for step '{step_name}' (second pass): {type(e).__name__}: {e}"
            context['output'] = error_msg
            return context

        from npcpy.npc_array import NPCArray, infer_matrix, ensemble_vote

        exec_globals = {
            "__builtins__": __builtins__,
            "npc": active_npc,
            "context": context,
            "math": math,
            "random": random,
            "datetime": datetime,
            "Image": Image,
            "pd": pd,
            "plt": plt,
            "sys": sys,
            "subprocess": subprocess,
            "np": np,
            "os": os,
            're': re,
            "json": json,
            "Path": pathlib.Path,
            "fnmatch": fnmatch,
            "pathlib": pathlib,
            "subprocess": subprocess,
            "get_llm_response": npy.llm_funcs.get_llm_response,
            "print_and_process_stream_with_markdown": print_and_process_stream_with_markdown,
            "NPCArray": NPCArray,
            "infer_matrix": infer_matrix,
            "ensemble_vote": ensemble_vote,
        }

        if extra_globals:
            exec_globals.update(extra_globals)

        exec_globals.update(context)

        exec_locals = exec_globals

        try:
            exec(rendered_code, exec_globals, exec_locals)
        except SystemExit as e:
            error_msg = f"Error executing step '{step_name}' in jinx '{self.jinx_name}': code called sys.exit({e.code})"
            print(f"[JINX-ERROR] {error_msg}")
            context['output'] = error_msg
            return context
        except Exception as e:
            error_msg = f"Error executing step '{step_name}' in jinx '{self.jinx_name}': {type(e).__name__}: {e}"
            print(f"[JINX-ERROR] {error_msg}")
            context['output'] = error_msg
            return context

        context_output = context.get("output")
        context.update(exec_locals)

        if context_output is not None:
            context["output"] = context_output
            context[step_name] = context_output

        if "output" in exec_locals and exec_locals["output"] is not None:
            outp = exec_locals["output"]
            context["output"] = outp
            context[step_name] = outp

        final_output = context.get("output")
        if final_output and messages is not None:
            messages.append({
                'role':'assistant',
                'content': f'Jinx {self.jinx_name} step {step_name} executed: {final_output}'
            })
            context['messages'] = messages

        return context

    def _parse_file_patterns(self, patterns_config):
        """Parse file patterns configuration and load matching files into KV cache"""
        if not patterns_config:
            return {}

        file_cache = {}

        for pattern_entry in patterns_config:
            if isinstance(pattern_entry, str):
                pattern_entry = {"pattern": pattern_entry}

            pattern = pattern_entry.get("pattern", "")
            recursive = pattern_entry.get("recursive", False)
            base_path = pattern_entry.get("base_path", ".")

            if not pattern:
                continue

            if self._source_path:
                base_path = os.path.join(os.path.dirname(self._source_path), base_path)
            base_path = os.path.expanduser(base_path)

            if not os.path.isabs(base_path):
                base_path = os.path.join(os.getcwd(), base_path)

            matching_files = self._find_matching_files(pattern, base_path, recursive)

            for file_path in matching_files:
                file_content = self._load_file_content(file_path)
                if file_content:
                    relative_path = os.path.relpath(file_path, base_path)
                    file_cache[relative_path] = file_content

        return file_cache

    def _find_matching_files(self, pattern, base_path, recursive=False):
        """Find files matching the given pattern"""
        matching_files = []

        if not os.path.exists(base_path):
            return matching_files

        if recursive:
            for root, dirs, files in os.walk(base_path):
                for filename in files:
                    if fnmatch.fnmatch(filename, pattern):
                        matching_files.append(os.path.join(root, filename))
        else:
            try:
                for item in os.listdir(base_path):
                    item_path = os.path.join(base_path, item)
                    if os.path.isfile(item_path) and fnmatch.fnmatch(item, pattern):
                        matching_files.append(item_path)
            except PermissionError:
                print(f"Permission denied accessing {base_path}")

        return matching_files

    def _load_file_content(self, file_path):
        """Load content from a file with error handling"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return f.read()
        except Exception as e:
            print(f"Error reading {file_path}: {e}")
            return None

    def _format_parsed_files_context(self, parsed_files):
        """Format parsed files into context string"""
        if not parsed_files:
            return ""

        context_parts = ["Additional context from files:"]

        for file_path, content in parsed_files.items():
            context_parts.append(f"\n--- {file_path} ---")
            context_parts.append(content)
            context_parts.append("")

        return "\n".join(context_parts)

    def to_dict(self):
        result = {
            "jinx_name": self.jinx_name,
            "description": self.description,
            "inputs": self.inputs,
            "steps": self._raw_steps,
            "file_context": self.file_context
        }

        if self.npc:
            result["npc"] = self.npc

        return result

    def save(self, directory):
        jinx_path = os.path.join(directory, f"{self.jinx_name}.jinx")
        ensure_dirs_exist(os.path.dirname(jinx_path))
        return write_yaml_file(jinx_path, self.to_dict())

    @classmethod
    def from_mcp(cls, mcp_tool):
        try:
            import inspect

            doc = mcp_tool.__doc__ or ""
            name = mcp_tool.__name__
            signature = inspect.signature(mcp_tool)

            inputs = []
            for param_name, param in signature.parameters.items():
                if param_name != 'self':
                    param_type = (
                        param.annotation 
                        if param.annotation != inspect.Parameter.empty 
                        else None
                    )
                    param_default = (
                        None 
                        if param.default == inspect.Parameter.empty 
                        else param.default
                    )

                    inputs.append({
                        "name": param_name,
                        "type": str(param_type),
                        "default": param_default
                    })

            jinx_data = {
                "jinx_name": name,
                "description": doc.strip(),
                "inputs": inputs,
                "file_context": [],
                "steps": [
                    {
                        "name": "mcp_function_call",
                        "code": f"""
import {mcp_tool.__module__}
output = {mcp_tool.__module__}.{name}(
    {', '.join([
        f'{inp["name"]}=context.get("{inp["name"]}")' 
        for inp in inputs
    ])}
)
"""
                    }
                ]
            }

            return cls(jinx_data=jinx_data)

        except: 
            pass

parsed_files = {} instance-attribute

steps = [] instance-attribute

execute(input_values, npc=None, messages=None, extra_globals=None, jinja_env=None)

Source code in npcpy/npc_compiler.py
def execute(self,
            input_values: Dict[str, Any],
            npc: Optional[Any] = None,
            messages: Optional[List[Dict[str, str]]] = None,
            extra_globals: Optional[Dict[str, Any]] = None,
            jinja_env: Optional[Environment] = None):

    if jinja_env is None:
        jinja_env = SandboxedEnvironment(
            loader=DictLoader({}),
            undefined=SilentUndefined,
        )

    active_npc = self.npc if self.npc else npc

    # If npc is a list or NPCArray, run this jinx in parallel across all instances
    from npcpy.npc_array import NPCArray
    if isinstance(active_npc, (list, NPCArray)):
        arr = NPCArray.from_npcs(active_npc) if isinstance(active_npc, list) else active_npc
        return arr.jinx(self.jinx_name, inputs=input_values).collect()

    context = (
        active_npc.shared_context.copy() 
        if active_npc and hasattr(active_npc, 'shared_context') 
        else {}
    )
    context.update(input_values)
    context.update({
        "llm_response": None,
        "output": None,
        "messages": messages,
        "npc": active_npc
    })

    if self.parsed_files:
        context['file_context'] = self._format_parsed_files_context(self.parsed_files)
        context['files'] = self.parsed_files

    for i, step in enumerate(self.steps):
        context = self._execute_step(
            step,
            context,
            jinja_env,
            npc=active_npc,
            messages=messages,
            extra_globals=extra_globals
        )
        output_str = str(context.get("output", ""))
        if "error" in output_str.lower():
            break

    return context

from_mcp(mcp_tool) classmethod

Source code in npcpy/npc_compiler.py
    @classmethod
    def from_mcp(cls, mcp_tool):
        try:
            import inspect

            doc = mcp_tool.__doc__ or ""
            name = mcp_tool.__name__
            signature = inspect.signature(mcp_tool)

            inputs = []
            for param_name, param in signature.parameters.items():
                if param_name != 'self':
                    param_type = (
                        param.annotation 
                        if param.annotation != inspect.Parameter.empty 
                        else None
                    )
                    param_default = (
                        None 
                        if param.default == inspect.Parameter.empty 
                        else param.default
                    )

                    inputs.append({
                        "name": param_name,
                        "type": str(param_type),
                        "default": param_default
                    })

            jinx_data = {
                "jinx_name": name,
                "description": doc.strip(),
                "inputs": inputs,
                "file_context": [],
                "steps": [
                    {
                        "name": "mcp_function_call",
                        "code": f"""
import {mcp_tool.__module__}
output = {mcp_tool.__module__}.{name}(
    {', '.join([
        f'{inp["name"]}=context.get("{inp["name"]}")' 
        for inp in inputs
    ])}
)
"""
                    }
                ]
            }

            return cls(jinx_data=jinx_data)

        except: 
            pass

render_first_pass(jinja_env_for_macros, all_jinx_callables)

Performs the first-pass Jinja rendering on the Jinx's raw steps. This expands Jinja control flow (for, if) to generate step structures, then expands nested Jinx calls (e.g., {{ sh(...) }} or engine: jinx_name) and inline macros.

Source code in npcpy/npc_compiler.py
def render_first_pass(
    self,
    jinja_env_for_macros: Environment,
    all_jinx_callables: Dict[str, Callable]
):
    """
    Performs the first-pass Jinja rendering on the Jinx's raw steps.
    This expands Jinja control flow (for, if) to generate step structures,
    then expands nested Jinx calls (e.g., {{ sh(...) }} or engine: jinx_name)
    and inline macros.
    """
    if self._raw_steps and isinstance(self._raw_steps[0], dict):
        structurally_expanded_steps = list(self._raw_steps)
    else:
        raw_steps_template_string = "\n".join(self._raw_steps)

        try:
            steps_template = jinja_env_for_macros.from_string(raw_steps_template_string)
            rendered_steps_yaml_string = steps_template.render(**jinja_env_for_macros.globals)
        except Exception as e:
            self.steps = list(self._raw_steps)
            return

        try:
            structurally_expanded_steps = yaml.safe_load(rendered_steps_yaml_string)
            if not isinstance(structurally_expanded_steps, list):
                if structurally_expanded_steps is None:
                    structurally_expanded_steps = []
                else:
                    raise ValueError(f"Rendered steps YAML did not result in a list: {type(structurally_expanded_steps)}")
        except Exception as e:
            self.steps = list(self._raw_steps)
            return

    final_rendered_steps = []
    for raw_step in structurally_expanded_steps:
        if not isinstance(raw_step, dict):
            final_rendered_steps.append(raw_step)
            continue

        engine_name = raw_step.get('engine')

        if engine_name and engine_name in all_jinx_callables:
            step_name = raw_step.get('name', f'call_{engine_name}')
            jinx_args = {
                k: v for k, v in raw_step.items() 
                if k not in ['engine', 'name']
            }

            jinx_callable = all_jinx_callables[engine_name]
            try:
                expanded_yaml_string = jinx_callable(**jinx_args)
                expanded_steps = yaml.safe_load(expanded_yaml_string)

                if isinstance(expanded_steps, list):
                    final_rendered_steps.extend(expanded_steps)
                elif expanded_steps is not None:
                    final_rendered_steps.append(expanded_steps)
            except Exception as e:
                final_rendered_steps.append(raw_step)
        elif raw_step.get('engine') in ['python', 'bash']:
            processed_step = {}
            for key, value in raw_step.items():
                if isinstance(value, str):
                    has_template_var = '{{' in value and '}}' in value
                    if has_template_var:
                        processed_step[key] = value
                    else:
                        try:
                            template = jinja_env_for_macros.from_string(value)
                            rendered_value = template.render({})
                            try:
                                loaded_value = yaml.safe_load(rendered_value)
                                processed_step[key] = loaded_value
                            except yaml.YAMLError:
                                processed_step[key] = rendered_value
                        except Exception as e:
                            processed_step[key] = value
                else:
                    processed_step[key] = value
            final_rendered_steps.append(processed_step)
        else:
            processed_step = {}
            for key, value in raw_step.items():
                if isinstance(value, str):
                    try:
                        template = jinja_env_for_macros.from_string(value)
                        rendered_value = template.render({})
                        try:
                            loaded_value = yaml.safe_load(rendered_value)
                            processed_step[key] = loaded_value
                        except yaml.YAMLError:
                            processed_step[key] = rendered_value
                    except Exception as e:
                        processed_step[key] = value
                else:
                    processed_step[key] = value
            final_rendered_steps.append(processed_step)

    self.steps = final_rendered_steps

save(directory)

Source code in npcpy/npc_compiler.py
def save(self, directory):
    jinx_path = os.path.join(directory, f"{self.jinx_name}.jinx")
    ensure_dirs_exist(os.path.dirname(jinx_path))
    return write_yaml_file(jinx_path, self.to_dict())

to_dict()

Source code in npcpy/npc_compiler.py
def to_dict(self):
    result = {
        "jinx_name": self.jinx_name,
        "description": self.description,
        "inputs": self.inputs,
        "steps": self._raw_steps,
        "file_context": self.file_context
    }

    if self.npc:
        result["npc"] = self.npc

    return result

to_tool_def()

Convert this Jinx to an OpenAI-style tool definition.

Source code in npcpy/npc_compiler.py
def to_tool_def(self) -> Dict[str, Any]:
    """Convert this Jinx to an OpenAI-style tool definition."""
    properties = {}
    required = []
    for inp in self.inputs:
        if isinstance(inp, str):
            properties[inp] = {"type": "string", "description": f"Parameter: {inp}"}
            required.append(inp)
        elif isinstance(inp, dict):
            name = list(inp.keys())[0]
            default_val = inp.get(name, "")
            desc = f"Parameter: {name}"
            if default_val != "":
                desc += f" (default: {default_val})"
            properties[name] = {"type": "string", "description": desc}
    return {
        "type": "function",
        "function": {
            "name": self.jinx_name,
            "description": self.description or f"Jinx: {self.jinx_name}",
            "parameters": {
                "type": "object",
                "properties": properties,
                "required": required
            }
        }
    }

NPC

Source code in npcpy/npc_compiler.py
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
class NPC:
    def __init__(
        self,
        file: str = None,
        name: str = None,
        primary_directive: str = None,
        plain_system_message: bool = False,
        team = None,
        jinxes: list = None,
        tools: list = None,
        model: str = None,
        provider: str = None,
        api_url: str = None,
        api_key: str = None,
        db_conn=None,
        use_global_jinxes=False,
        memory = False,
        **kwargs
    ):
        """
        Initialize an NPC from a file path or with explicit parameters

        Args:
            file: Path to .npc file or name for the NPC
            primary_directive: System prompt/directive for the NPC
            jinxes: List of jinxes available to the NPC or "*" to load all jinxes
            model: LLM model to use
            provider: LLM provider to use
            api_url: API URL for LLM
            api_key: API key for LLM
            db_conn: Database connection
        """
        if not file and not name and not primary_directive:
            raise ValueError("Either 'file' or 'name' and 'primary_directive' must be provided")

        self.team = team

        if file:
            if file.endswith(".npc"):
                self._load_from_file(file)
            file_parent = os.path.dirname(file)
            self.jinxes_directory = os.path.join(file_parent, "jinxes")
            self.npc_directory = file_parent
        else:
            self.name = name            
            self.primary_directive = primary_directive
            self.model = model
            self.provider = provider
            self.api_url = api_url
            self.api_key = api_key

            if use_global_jinxes:
                self.jinxes_directory = os.path.expanduser('~/.npcsh/npc_team/jinxes/')
            else: 
                self.jinxes_directory = None
            self.npc_directory = None

        if not hasattr(self, 'jinxes_spec') or jinxes is not None:
            self.jinxes_spec = jinxes or []

        if tools is not None:
            tools_schema, tool_map = auto_tools(tools)
            self.tools = tools_schema  
            self.tool_map = tool_map   
            self.tools_schema = tools_schema  
        else:
            self.tools = []
            self.tool_map = {}
            self.tools_schema = []
        self.plain_system_message = plain_system_message
        self.use_global_jinxes = use_global_jinxes
        self.jinx_tool_catalog: Dict[str, Dict[str, Any]] = {}
        self.mcp_servers = []

        self.memory_length = 20
        self.memory_strategy = 'recent'
        dirs = []
        if self.npc_directory:
            dirs.append(self.npc_directory)
        if self.jinxes_directory:
            dirs.append(self.jinxes_directory)

        self.jinja_env = SandboxedEnvironment(
            loader=FileSystemLoader([
                os.path.expanduser(d) for d in dirs
            ]),
            undefined=SilentUndefined,
        )

        self.db_conn = db_conn
        self.kg_data = None
        self.tables = None
        self.memory = None

        if self.db_conn:
            self._setup_db()

        self.jinxes_dict = {}
        if jinxes and jinxes != "*": 
            for jinx_item in jinxes:
                if isinstance(jinx_item, Jinx):
                    self.jinxes_dict[jinx_item.jinx_name] = jinx_item
                elif isinstance(jinx_item, dict):
                    jinx_obj = Jinx(jinx_data=jinx_item)
                    self.jinxes_dict[jinx_obj.jinx_name] = jinx_obj
                elif isinstance(jinx_item, str):
                    jinx_path = find_file_path(jinx_item, [self.npc_jinxes_directory], suffix=".jinx")
                    if jinx_path:
                        jinx_obj = Jinx(jinx_path=jinx_path)
                        self.jinxes_dict[jinx_obj.jinx_name] = jinx_obj
                    else:
                        print(f"Warning: Jinx '{jinx_item}' not found for NPC '{self.name}' during initial load.")

        self.shared_context = {
            "dataframes": {},
            "current_data": None,
            "computation_results": [],
            "locals": {},

            "memories": {},

            "mcp_client": None,
            "mcp_tools": [],
            "mcp_tool_map": {},

            "session_input_tokens": 0,
            "session_output_tokens": 0,
            "session_cost_usd": 0.0,
            "turn_count": 0,

            "current_mode": "agent",
            "attachments": [],
        }

        for key, value in kwargs.items():
            setattr(self, key, value)

        if db_conn is not None:
            init_db_tables()

    def initialize_jinxes(self, team_raw_jinxes: Optional[List['Jinx']] = None):
        """
        Loads and performs first-pass Jinja rendering for NPC-specific jinxes,
        now that the NPC's team context is fully established.
        """
        npc_jinxes_raw_list = []

        if self.jinxes_spec == "*":
            if self.team and hasattr(self.team, 'jinxes_dict') and self.team.jinxes_dict:
                self.jinxes_dict.update(self.team.jinxes_dict)
        else:
            if self.team and hasattr(self.team, 'jinxes_dict') and self.team.jinxes_dict:
                jinxes_base_dir = None
                if hasattr(self.team, 'team_path') and self.team.team_path:
                    jinxes_base_dir = os.path.join(self.team.team_path, 'jinxes')

                path_map = getattr(self.team, '_jinx_path_map', None)
                for jinx_spec in self.jinxes_spec:
                    if jinxes_base_dir:
                        matched_names = match_jinx_spec_to_names(jinx_spec, self.team.jinxes_dict, jinxes_base_dir, jinx_path_map=path_map)
                    else:
                        matched_names = [jinx_spec] if jinx_spec in self.team.jinxes_dict else []

                    if not matched_names:
                        # Warn-and-skip instead of crashing the whole process. A missing
                        # external/foreign jinx (offline, wrong repo, rename) shouldn't
                        # take the MCP server down with it — the NPC just has fewer tools.
                        print(
                            f"Warning: NPC '{self.name}' references jinx '{jinx_spec}' but no matching jinx was found. "
                            f"Skipping. Available jinxes (first 20): {list(self.team.jinxes_dict.keys())[:20]}",
                            file=sys.stderr,
                        )
                        continue

                    for jinx_name in matched_names:
                        if jinx_name in self.team.jinxes_dict:
                            self.jinxes_dict[jinx_name] = self.team.jinxes_dict[jinx_name]

        # Additively merge team-level jinxes (from team .ctx `jinxes:`) on top of
        # whatever this NPC resolved from its own spec. This eliminates the need
        # to list universal jinxes (chat, stop, ask_form) in every .npc file.
        team_jinxes_spec = getattr(self.team, 'team_jinxes_spec', None) if self.team else None
        if team_jinxes_spec and hasattr(self.team, 'jinxes_dict') and self.team.jinxes_dict:
            jinxes_base_dir = None
            if hasattr(self.team, 'team_path') and self.team.team_path:
                jinxes_base_dir = os.path.join(self.team.team_path, 'jinxes')
            path_map = getattr(self.team, '_jinx_path_map', None)
            for jinx_spec in team_jinxes_spec:
                if jinxes_base_dir:
                    matched_names = match_jinx_spec_to_names(jinx_spec, self.team.jinxes_dict, jinxes_base_dir, jinx_path_map=path_map)
                else:
                    matched_names = [jinx_spec] if jinx_spec in self.team.jinxes_dict else []
                for jinx_name in matched_names:
                    if jinx_name in self.team.jinxes_dict and jinx_name not in self.jinxes_dict:
                        self.jinxes_dict[jinx_name] = self.team.jinxes_dict[jinx_name]

        should_load_from_directory = False
        if hasattr(self, 'npc_jinxes_directory') and self.npc_jinxes_directory and os.path.exists(self.npc_jinxes_directory):
            if not self.team:
                should_load_from_directory = True
            elif hasattr(self.team, 'team_path') and self.team.team_path:
                team_jinxes_dir = os.path.join(self.team.team_path, 'jinxes')
                if os.path.normpath(self.npc_jinxes_directory) != os.path.normpath(team_jinxes_dir):
                    should_load_from_directory = True

        if should_load_from_directory:
            for jinx_obj in load_jinxes_from_directory(self.npc_jinxes_directory):
                if jinx_obj.jinx_name not in self.jinxes_dict:
                    npc_jinxes_raw_list.append(jinx_obj)

        if npc_jinxes_raw_list or team_raw_jinxes:
            all_available_raw_jinxes = list(team_raw_jinxes or [])
            all_available_raw_jinxes.extend(npc_jinxes_raw_list)

            combined_raw_jinxes_dict = {j.jinx_name: j for j in all_available_raw_jinxes}

            npc_first_pass_jinja_env = SandboxedEnvironment(undefined=SilentUndefined)

            jinx_macro_globals = {}
            for raw_jinx in combined_raw_jinxes_dict.values():
                def create_jinx_callable(jinx_obj_in_closure):
                    def callable_jinx(**kwargs):
                        temp_jinja_env = SandboxedEnvironment(undefined=SilentUndefined)
                        rendered_target_steps = []
                        for target_step in jinx_obj_in_closure._raw_steps:
                            temp_rendered_step = {}
                            for k, v in target_step.items():
                                if isinstance(v, str):
                                    try:
                                        temp_rendered_step[k] = temp_jinja_env.from_string(v).render(**kwargs)
                                    except Exception as e:
                                        print(f"Warning: Error in Jinx macro '{jinx_obj_in_closure.jinx_name}' rendering step field '{k}' (NPC first pass): {e}")
                                        temp_rendered_step[k] = v
                                else:
                                    temp_rendered_step[k] = v
                            rendered_target_steps.append(temp_rendered_step)
                        return yaml.dump(rendered_target_steps, default_flow_style=False)
                    return callable_jinx

                jinx_macro_globals[raw_jinx.jinx_name] = create_jinx_callable(raw_jinx)

            npc_first_pass_jinja_env.globals.update(jinx_macro_globals)

            for raw_npc_jinx in npc_jinxes_raw_list:
                try:
                    raw_npc_jinx.render_first_pass(npc_first_pass_jinja_env, jinx_macro_globals)
                    self.jinxes_dict[raw_npc_jinx.jinx_name] = raw_npc_jinx
                except Exception as e:
                    print(f"Error performing first-pass rendering for NPC Jinx '{raw_npc_jinx.jinx_name}': {e}")

        self.jinx_tool_catalog = build_jinx_tool_catalog(self.jinxes_dict)
        print(f"NPC {self.name} loaded {len(self.jinxes_dict)} jinxes and built catalog with {len(self.jinx_tool_catalog)} tools.", file=sys.stderr)


    def get_memory_context(self):
        """Get formatted memory context for system prompt"""
        if not self.kg_data:
            return ""

        context_parts = []

        recent_facts = self.kg_data.get('facts', [])[-10:]
        if recent_facts:
            context_parts.append("Recent memories:")
            for fact in recent_facts:
                context_parts.append(f"- {fact['statement']}")

        concepts = self.kg_data.get('concepts', [])
        if concepts:
            concept_names = [c['name'] for c in concepts[:5]]
            context_parts.append(f"Key concepts: {', '.join(concept_names)}")

        return "\n".join(context_parts)

    def enter_tool_use_loop(
        self, 
        prompt: str, 
        tools: list = None, 
        tool_map: dict = None, 
        max_iterations: int = 5,
        stream: bool = False
    ):
        """Enter interactive tool use loop for complex tasks"""
        if not tools:
            tools = self.tools
        if not tool_map:
            tool_map = self.tool_map

        messages = self.memory.copy() if self.memory else []
        messages.append({"role": "user", "content": prompt})

        for iteration in range(max_iterations):
            response = get_llm_response(
                prompt="",
                model=self.model,
                provider=self.provider,
                npc=self,
                messages=messages,
                tools=tools,
                tool_map=tool_map,
                auto_process_tool_calls=True,
                stream=stream
            )

            messages = response.get('messages', messages)

            if not response.get('tool_calls'):
                return {
                    "final_response": response.get('response'),
                    "messages": messages,
                    "iterations": iteration + 1
                }

        return {
            "final_response": "Max iterations reached",
            "messages": messages,
            "iterations": max_iterations
        }

    def get_code_response(
        self, 
        prompt: str, 
        language: str = "python", 
        execute: bool = False, 
        locals_dict: dict = None
    ):
        """Generate and optionally execute code responses"""
        code_prompt = f"""Generate {language} code for: {prompt}

        Provide ONLY executable {language} code without explanations.
        Do not include markdown formatting or code blocks.
        Begin directly with the code."""

        response = get_llm_response(
            prompt=code_prompt,
            model=self.model,
            provider=self.provider,
            npc=self,
            stream=False
        )

        generated_code = response.get('response', '')

        result = {
            "code": generated_code,
            "executed": False,
            "output": None,
            "error": None
        }

        if execute and language == "python":
            if locals_dict is None:
                locals_dict = {}

            exec_globals = {"__builtins__": __builtins__}
            exec_globals.update(locals_dict)

            exec_locals = {}
            try:
                exec(generated_code, exec_globals, exec_locals)
            except SystemExit as e:
                result["error"] = f"Code called sys.exit({e.code})"
                return result

            locals_dict.update(exec_locals)
            result["executed"] = True
            result["output"] = exec_locals.get("output", "Code executed successfully")

        return result

    def _load_from_file(self, file):
        """Load NPC configuration from file"""
        if "~" in file:
            file = os.path.expanduser(file)
        if not os.path.isabs(file):
            file = os.path.abspath(file)

        # If team has jinx path context, pass it so {{ jinx_name }} resolves
        jinja_ctx = None
        if self.team and hasattr(self.team, '_npc_jinja_context'):
            jinja_ctx = self.team._npc_jinja_context

        npc_data = load_yaml_file(file, jinja_context=jinja_ctx)
        if not npc_data:
            raise ValueError(f"Failed to load NPC from {file}")

        self.name = npc_data.get("name")
        if not self.name:
            self.name = os.path.splitext(os.path.basename(file))[0]

        self.primary_directive = npc_data.get("primary_directive")

        jinxes_spec = npc_data.get("jinxes", [])

        if jinxes_spec == "*":
            self.jinxes_spec = "*"
        else:
            self.jinxes_spec = jinxes_spec

        self.model = npc_data.get("model")
        self.provider = npc_data.get("provider")
        self.api_url = npc_data.get("api_url")
        self.api_key = npc_data.get("api_key")
        self.mcp_servers = npc_data.get("mcp_servers", [])

        if self.team:
            if not self.model and hasattr(self.team, 'model'):
                self.model = self.team.model
            if not self.provider and hasattr(self.team, 'provider'):
                self.provider = self.team.provider
            if not self.api_url and hasattr(self.team, 'api_url'):
                self.api_url = self.team.api_url
            if not self.api_key and hasattr(self.team, 'api_key'):
                self.api_key = self.team.api_key


        self.name = npc_data.get("name", self.name)

        self.npc_path = file
        self.npc_jinxes_directory = os.path.join(os.path.dirname(file), "jinxes")

    def resolve_tools(self, mcp_clients_cache: dict = None) -> tuple:
        """
        Returns (tools_for_llm, tool_executors) where:
          - tools_for_llm: list of OpenAI-style tool defs for the LLM
          - tool_executors: dict mapping tool_name -> {"type": ..., ...} for execution

        Assembles from: jinx_tool_catalog + mcp_servers + python tools
        """
        from npcpy.serve import MCPClientNPC

        tools_for_llm = []
        tool_executors = {}
        seen = set()

        # 1. Jinx tools
        catalog = self.jinx_tool_catalog or build_jinx_tool_catalog(self.jinxes_dict)
        for name, tool_def in catalog.items():
            if name not in seen:
                tools_for_llm.append(tool_def)
                tool_executors[name] = {"type": "jinx", "jinx": self.jinxes_dict.get(name)}
                seen.add(name)

        # 2. MCP server tools
        if mcp_clients_cache is None:
            mcp_clients_cache = {}

        connectable_specs = []
        nameonly_tools = []
        for server_spec in (self.mcp_servers or []):
            if isinstance(server_spec, str):
                connectable_specs.append({"path": server_spec})
            elif isinstance(server_spec, dict):
                if "path" in server_spec or "command" in server_spec or "url" in server_spec:
                    connectable_specs.append(server_spec)
                elif "tools" in server_spec:
                    nameonly_tools.extend(server_spec["tools"])

        def spec_cache_key(spec):
            if isinstance(spec, str):
                return os.path.expanduser(spec)
            if "path" in spec:
                return os.path.expanduser(spec["path"])
            if "url" in spec:
                return spec["url"]
            if "command" in spec:
                return f"{spec['command']}:{' '.join(spec.get('args', []))}"
            return str(spec)

        for spec in connectable_specs:
            key = spec_cache_key(spec)
            whitelist = spec.get("tools")
            client = mcp_clients_cache.get(key)
            if not client:
                client = MCPClientNPC()
                if client.connect_sync(spec):
                    mcp_clients_cache[key] = client
                else:
                    continue
            for tool_def in client.available_tools_llm:
                name = tool_def["function"]["name"]
                if name in seen:
                    continue
                if whitelist and name not in whitelist:
                    continue
                tools_for_llm.append(tool_def)
                tool_executors[name] = {
                    "type": "mcp",
                    "client": client,
                    "tool_func": client.tool_map.get(name),
                }
                seen.add(name)

        # Resolve tool-name-only specs by searching team MCP servers
        if nameonly_tools and self.team and hasattr(self.team, "mcp_servers"):
            for team_server in (self.team.mcp_servers or []):
                ts = team_server if isinstance(team_server, dict) else {"path": team_server}
                key = spec_cache_key(ts)
                client = mcp_clients_cache.get(key)
                if not client:
                    client = MCPClientNPC()
                    if client.connect_sync(ts):
                        mcp_clients_cache[key] = client
                    else:
                        continue
                for tool_def in client.available_tools_llm:
                    name = tool_def["function"]["name"]
                    if name in nameonly_tools and name not in seen:
                        tools_for_llm.append(tool_def)
                        tool_executors[name] = {
                            "type": "mcp",
                            "client": client,
                            "tool_func": client.tool_map.get(name),
                        }
                        seen.add(name)

        # 3. Python tools (from auto_tools)
        for tool_def in (self.tools_schema or []):
            name = tool_def["function"]["name"]
            if name not in seen:
                tools_for_llm.append(tool_def)
                tool_executors[name] = {"type": "python", "func": self.tool_map.get(name)}
                seen.add(name)

        return tools_for_llm, tool_executors

    def get_system_prompt(self, simple=False, tool_capable=False):
        """Get system prompt for the NPC"""
        if simple or self.plain_system_message:
            return self.primary_directive
        else:
            return get_system_message(self, team=self.team, tool_capable=tool_capable)

    def _setup_db(self):
        """Set up database tables and determine type"""
        dialect = self.db_conn.dialect.name

        with self.db_conn.connect() as conn:
            if dialect == "postgresql":
                result = conn.execute(text("""
                    SELECT table_name, obj_description((quote_ident(table_name))::regclass, 'pg_class')
                    FROM information_schema.tables
                    WHERE table_schema='public';
                """))
                self.tables = result.fetchall()
                self.db_type = "postgres"

            elif dialect == "sqlite":
                result = conn.execute(text(
                    "SELECT name, sql FROM sqlite_master WHERE type='table';"
                ))
                self.tables = result.fetchall()
                self.db_type = "sqlite"

            else:
                print(f"Unsupported DB dialect: {dialect}")
                self.tables = None
                self.db_type = None

    def get_llm_response(self, 
                        request,
                        jinxes=None,
                        tools: Optional[list] = None,
                        tool_map: Optional[dict] = None,
                        tool_choice=None, 
                        messages=None,
                        auto_process_tool_calls=True,
                        use_core_tools: bool = False,
                        **kwargs):
        all_candidate_functions = []

        if tools is not None and tool_map is not None:
            all_candidate_functions.extend([func for func in tool_map.values() if callable(func)])
        elif hasattr(self, 'tool_map') and self.tool_map:
            all_candidate_functions.extend([func for func in self.tool_map.values() if callable(func)])

        if use_core_tools:
            dynamic_core_tools_list = [
                self.think_step_by_step,
                self.write_code,
            ]

            if self.db_conn:
                dynamic_core_tools_list.append(self.query_database)

            all_candidate_functions.extend(dynamic_core_tools_list)

        unique_functions = []
        seen_names = set()
        for func in all_candidate_functions:
            if func.__name__ not in seen_names:
                unique_functions.append(func)
                seen_names.add(func.__name__)

        final_tools_schema = None
        final_tool_map_dict = None

        if unique_functions:
            final_tools_schema, final_tool_map_dict = auto_tools(unique_functions)

        if tool_choice is None:
            if final_tools_schema:
                tool_choice = "auto"
            else:
                tool_choice = None

        response = npy.llm_funcs.get_llm_response(
            request, 
            npc=self, 
            jinxes=jinxes,
            tools=final_tools_schema,
            tool_map=final_tool_map_dict,
            tool_choice=tool_choice,           
            auto_process_tool_calls=auto_process_tool_calls,
            messages=self.memory if messages is None else messages,
            **kwargs
        )        

        return response


    def search_my_memories(self, query: str, limit: int = 10) -> str:
        """Search through this NPC's knowledge graph memories for relevant facts and concepts"""
        if not self.kg_data:
            return "No memories available"

        query_lower = query.lower()
        relevant_facts = []
        relevant_concepts = []

        for fact in self.kg_data.get('facts', []):
            if query_lower in fact.get('statement', '').lower():
                relevant_facts.append(fact['statement'])

        for concept in self.kg_data.get('concepts', []):
            if query_lower in concept.get('name', '').lower():
                relevant_concepts.append(concept['name'])

        result_parts = []
        if relevant_facts:
            result_parts.append(f"Relevant memories: {'; '.join(relevant_facts[:limit])}")
        if relevant_concepts:
            result_parts.append(f"Related concepts: {', '.join(relevant_concepts[:limit])}")

        return "\n".join(result_parts) if result_parts else f"No memories found matching '{query}'"

    def query_database(self, sql_query: str) -> str:
        """Execute a SQL query against the available database"""
        if not self.db_conn:
            return "No database connection available"

        try:
            with self.db_conn.connect() as conn:
                result = conn.execute(text(sql_query))
                rows = result.fetchall()

                if not rows:
                    return "Query executed successfully but returned no results"

                columns = result.keys()
                formatted_rows = []
                for row in rows[:20]:  
                    row_dict = dict(zip(columns, row))
                    formatted_rows.append(str(row_dict))

                return f"Query results ({len(rows)} total rows, showing first 20):\n" + "\n".join(formatted_rows)

        except Exception as e:
            return f"Database query error: {str(e)}"

    def think_step_by_step(self, problem: str) -> str:
        """Think through a problem step by step using chain of thought reasoning"""
        thinking_prompt = f"""Think through this problem step by step:

    {problem}

    Break down your reasoning into clear steps:
    1. First, I need to understand...
    2. Then, I should consider...
    3. Next, I need to...
    4. Finally, I can conclude...

    Provide your step-by-step analysis.
    Do not under any circumstances ask for feedback from a user. These thoughts are part of an agentic tool that is letting the agent
    break down a problem by thinking it through. they will review the results and use them accordingly. 


    """

        response = self.get_llm_response(thinking_prompt, tool_choice = False)
        return response.get('response', 'Unable to process thinking request')

    def write_code(self, task: str, language: str = "python") -> str:
        """Write code to accomplish a task.

        Args:
            task: Description of what the code should do
            language: Programming language to use (default: python)

        Returns:
            The generated code as a string
        """
        code_prompt = f"""Write {language} code to accomplish the following task:

{task}

Requirements:
- Write clean, well-commented code
- Include error handling where appropriate
- Make sure the code is complete and runnable
- Only output the code, no explanations before or after

```{language}
"""

        response = self.get_llm_response(code_prompt, tool_choice=False)
        code = response.get('response', '')

        if f'```{language}' in code:
            code = code.split(f'```{language}')[-1]
        if '```' in code:
            code = code.split('```')[0]

        return code.strip()

    def create_planning_state(self, goal: str) -> Dict[str, Any]:
        """Create initial planning state for a goal"""
        return {
            "goal": goal,
            "todos": [],
            "constraints": [],
            "facts": [],
            "mistakes": [],
            "successes": [],
            "current_todo_index": 0,
            "current_subtodo_index": 0,
            "context_summary": ""
        }

    def generate_todos(self, user_goal: str, planning_state: Dict[str, Any], additional_context: str = "") -> List[Dict[str, Any]]:
        """Generate high-level todos for a goal"""
        prompt = f"""
        You are a high-level project planner. Structure tasks logically:
        1. Understand current state
        2. Make required changes 
        3. Verify changes work

        User goal: {user_goal}
        {additional_context}

        Generate 3-5 todos to accomplish this goal. Use specific actionable language.
        Each todo should be independent where possible and focused on a single component.

        Return JSON:
        {{
            "todos": [
                {{"description": "todo description", "estimated_complexity": "simple|medium|complex"}},
                ...
            ]
        }}
        """

        response = self.get_llm_response(prompt, format="json", tool_choice=False)
        todos_data = response.get("response", {}).get("todos", [])
        return todos_data

    def should_break_down_todo(self, todo: Dict[str, Any]) -> bool:
        """Ask LLM if a todo needs breakdown"""
        prompt = f"""
        Todo: {todo['description']}
        Complexity: {todo.get('estimated_complexity', 'unknown')}

        Should this be broken into smaller steps? Consider:
        - Is it complex enough to warrant breakdown?
        - Would breakdown make execution clearer?
        - Are there multiple distinct steps?

        Return JSON: {{"should_break_down": true/false, "reason": "explanation"}}
        """

        response = self.get_llm_response(prompt, format="json", tool_choice=False)
        result = response.get("response", {})
        return result.get("should_break_down", False)

    def generate_subtodos(self, todo: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Generate atomic subtodos for a complex todo"""
        prompt = f"""
        Parent todo: {todo['description']}

        Break this into atomic, executable subtodos. Each should be:
        - A single, concrete action
        - Executable in one step
        - Clear and unambiguous

        Return JSON:
        {{
            "subtodos": [
                {{"description": "subtodo description", "type": "action|verification|analysis"}},
                ...
            ]
        }}
        """

        response = self.get_llm_response(prompt, format="json")
        return response.get("response", {}).get("subtodos", [])

    def execute_planning_item(self, item: Dict[str, Any], planning_state: Dict[str, Any], context: str = "") -> Dict[str, Any]:
        """Execute a single planning item (todo or subtodo)"""
        context_summary = self.get_planning_context_summary(planning_state)

        command = f"""
        Current context:
        {context_summary}
        {context}

        Execute this task: {item['description']}

        Constraints to follow:
        {chr(10).join([f"- {c}" for c in planning_state.get('constraints', [])])}
        """

        result = self.check_llm_command(
            command,
            context=self.shared_context,
            stream=False
        )

        return result

    def get_planning_context_summary(self, planning_state: Dict[str, Any]) -> str:
        """Get lightweight context for planning prompts"""
        context = []
        facts = planning_state.get('facts', [])
        mistakes = planning_state.get('mistakes', [])
        successes = planning_state.get('successes', [])

        if facts:
            context.append(f"Facts: {'; '.join(facts[:5])}")
        if mistakes:
            context.append(f"Recent mistakes: {'; '.join(mistakes[-3:])}")
        if successes:
            context.append(f"Recent successes: {'; '.join(successes[-3:])}")
        return "\n".join(context)

    def compress_planning_state(self, messages):
        if isinstance(messages, list):
            from npcpy.llm_funcs import breathe, get_facts

            conversation_summary = breathe(messages=messages, npc=self)
            summary_data = conversation_summary.get('output', '')

            conversation_text = "\n".join([msg['content'] for msg in messages])
            extracted_facts = get_facts(conversation_text, model=self.model, provider=self.provider, npc=self)

            user_inputs = [msg['content'] for msg in messages if msg.get('role') == 'user']
            assistant_outputs = [msg['content'] for msg in messages if msg.get('role') == 'assistant']

            planning_state = {
                "goal": summary_data,
                "facts": [fact['statement'] if isinstance(fact, dict) else str(fact) for fact in extracted_facts[-10:]],
                "successes": [output[:100] for output in assistant_outputs[-5:]],
                "mistakes": [],
                "todos": user_inputs[-3:],
                "constraints": []
            }
        else:
            planning_state = messages

        todos = planning_state.get('todos', [])
        current_index = planning_state.get('current_todo_index', 0)

        if todos and current_index < len(todos):
            current_focus = todos[current_index].get('description', todos[current_index]) if isinstance(todos[current_index], dict) else str(todos[current_index])
        else:
            current_focus = 'No current task'

        compressed = {
            "goal": planning_state.get("goal", ""),
            "progress": f"{len(planning_state.get('successes', []))}/{len(todos)} todos completed",
            "context": self.get_planning_context_summary(planning_state),
            "current_focus": current_focus
        }
        return json.dumps(compressed, indent=2)

    def decompress_planning_state(self, compressed_state: str) -> Dict[str, Any]:
        """Restore planning state from compressed string"""
        try:
            data = json.loads(compressed_state)
            return {
                "goal": data.get("goal", ""),
                "todos": [],
                "constraints": [],
                "facts": [],
                "mistakes": [],
                "successes": [],
                "current_todo_index": 0,
                "current_subtodo_index": 0,
                "compressed_context": data.get("context", "")
            }
        except json.JSONDecodeError:
            return self.create_planning_state("")

    def run_planning_loop(self, user_goal: str, interactive: bool = True) -> Dict[str, Any]:
        """Run the full planning loop for a goal"""
        planning_state = self.create_planning_state(user_goal)

        todos = self.generate_todos(user_goal, planning_state)
        planning_state["todos"] = todos

        for i, todo in enumerate(todos):
            planning_state["current_todo_index"] = i

            if self.should_break_down_todo(todo):
                subtodos = self.generate_subtodos(todo)

                for j, subtodo in enumerate(subtodos):
                    planning_state["current_subtodo_index"] = j
                    result = self.execute_planning_item(subtodo, planning_state)

                    if result.get("output"):
                        planning_state["successes"].append(f"Completed: {subtodo['description']}")
                    else:
                        planning_state["mistakes"].append(f"Failed: {subtodo['description']}")
            else:
                result = self.execute_planning_item(todo, planning_state)

                if result.get("output"):
                    planning_state["successes"].append(f"Completed: {todo['description']}")
                else:
                    planning_state["mistakes"].append(f"Failed: {todo['description']}")

        return {
            "planning_state": planning_state,
            "compressed_state": self.compress_planning_state(planning_state),
            "summary": f"Completed {len(planning_state['successes'])} tasks for goal: {user_goal}"
        }

    def execute_jinx(
        self,
        jinx_name,
        inputs,
        conversation_id=None,
        message_id=None,
        team_name=None,
        extra_globals=None
    ):
        if jinx_name in self.jinxes_dict:
            jinx = self.jinxes_dict[jinx_name]
        else:
            return {"error": f"jinx '{jinx_name}' not found"}

        import time as _time
        _start = _time.monotonic()
        _status = "success"
        _error = None

        try:
            result = jinx.execute(
                input_values=inputs,
                npc=self,
                extra_globals=extra_globals,
                jinja_env=self.jinja_env
            )
        except Exception as e:
            _status = "error"
            _error = str(e)
            result = {"error": str(e)}

        _duration_ms = int((_time.monotonic() - _start) * 1000)
        return result
    def check_llm_command(self,
                            command,
                            messages=None,
                            context=None,
                            team=None,
                            stream=False,
                            jinxes=None,
                            use_jinxes=True,
                            **kwargs):
        """Check if a command is for the LLM"""
        if context is None:
            context = self.shared_context

        if team:
            self._current_team = team
        if jinxes is None and use_jinxes:
            jinxes_to_use = self.jinxes_dict
        elif jinxes is not None and use_jinxes:
            jinxes_to_use = jinxes

        return npy.llm_funcs.check_llm_command(
            command,
            model=self.model,
            provider=self.provider,
            npc=self,
            team=team,
            messages=self.memory if messages is None else messages,
            context=context,
            stream=stream,
            jinxes=jinxes_to_use,
            **kwargs,
        )

    def run(self, input_text: str, **kwargs):
        return self.check_llm_command(input_text, **kwargs)

    def handle_agent_pass(self, 
                            npc_to_pass,
                            command, 
                            messages=None, 
                            context=None, 
                            shared_context=None, 
                            stream=False,
                            team=None):  
        """Pass a command to another NPC"""
        print('handling agent pass')
        if isinstance(npc_to_pass, NPC):
            target_npc = npc_to_pass
        else:
            return {"error": "Invalid NPC to pass command to"}

        if shared_context is not None:
            self.shared_context.update(shared_context)
            target_npc.shared_context.update(shared_context)

        updated_command = (
            command
            + "\n\n"
            + f"NOTE: THIS COMMAND HAS BEEN PASSED FROM {self.name} TO YOU, {target_npc.name}.\n"
            + "PLEASE CHOOSE ONE OF THE OTHER OPTIONS WHEN RESPONDING."
        )

        result = target_npc.check_llm_command(
            updated_command,
            messages=messages,
            context=target_npc.shared_context,
            team=team, 
            stream=stream
        )
        if isinstance(result, dict):
            result['npc_name'] = target_npc.name
            result['passed_from'] = self.name

        return result    

    def to_dict(self):
        """Convert NPC to dictionary representation"""
        jinx_rep = []
        if self.jinxes_dict:
            jinx_rep = [ jinx.to_dict() for jinx in self.jinxes_dict.values()]
        source_path = getattr(self, 'npc_path', None) or getattr(self, 'source_path', None) or ''
        source_ext = ''
        if source_path:
            lower = source_path.lower()
            if lower.endswith('.npc'):
                source_ext = '.npc'
            elif lower.endswith('.md'):
                source_ext = '.md'
        return {
            "name": self.name,
            "primary_directive": self.primary_directive,
            "model": self.model,
            "provider": self.provider,
            "api_url": self.api_url,
            "api_key": self.api_key,
            "jinxes": self.jinxes_spec,
            "use_global_jinxes": self.use_global_jinxes,
            "source_path": source_path,
            "source_ext": source_ext,
        }

    def save(self, directory=None):
        """Save NPC to file"""
        if directory is None:
            directory = self.npc_directory

        ensure_dirs_exist(directory)
        npc_path = os.path.join(directory, f"{self.name}.npc")

        return write_yaml_file(npc_path, self.to_dict())

    def __str__(self):
        """String representation of NPC"""
        str_rep = f"NPC: {self.name}\nDirective: {self.primary_directive}\nModel: {self.model}\nProvider: {self.provider}\nAPI URL: {self.api_url}\n"
        if self.jinxes_dict:
            str_rep += "Jinxs:\n"
            for jinx_name in self.jinxes_dict.keys():
                str_rep += f"  - {jinx_name}\n"
        else:
            str_rep += "No jinxes available.\n"
        return str_rep

    def execute_jinx_command(self, 
        jinx: Jinx,
        args: List[str],
        messages=None,
    ) -> Dict[str, Any]:
        """
        Execute a jinx command with the given arguments.
        """

        input_values = extract_jinx_inputs(args, jinx)

        jinx_output = jinx.execute(
            input_values,
            npc=self,
            messages=messages,
            jinja_env=self.jinja_env
        )

        return {"messages": messages, "output": jinx_output}

api_key = api_key instance-attribute

api_url = api_url instance-attribute

db_conn = db_conn instance-attribute

jinja_env = SandboxedEnvironment(loader=(FileSystemLoader([(os.path.expanduser(d)) for d in dirs])), undefined=SilentUndefined) instance-attribute

jinx_tool_catalog = {} instance-attribute

jinxes_dict = {} instance-attribute

jinxes_directory = os.path.join(file_parent, 'jinxes') instance-attribute

jinxes_spec = jinxes or [] instance-attribute

kg_data = None instance-attribute

mcp_servers = [] instance-attribute

memory = None instance-attribute

memory_length = 20 instance-attribute

memory_strategy = 'recent' instance-attribute

model = model instance-attribute

name = name instance-attribute

npc_directory = file_parent instance-attribute

plain_system_message = plain_system_message instance-attribute

primary_directive = primary_directive instance-attribute

provider = provider instance-attribute

shared_context = {'dataframes': {}, 'current_data': None, 'computation_results': [], 'locals': {}, 'memories': {}, 'mcp_client': None, 'mcp_tools': [], 'mcp_tool_map': {}, 'session_input_tokens': 0, 'session_output_tokens': 0, 'session_cost_usd': 0.0, 'turn_count': 0, 'current_mode': 'agent', 'attachments': []} instance-attribute

tables = None instance-attribute

team = team instance-attribute

tool_map = tool_map instance-attribute

tools = tools_schema instance-attribute

tools_schema = tools_schema instance-attribute

use_global_jinxes = use_global_jinxes instance-attribute

check_llm_command(command, messages=None, context=None, team=None, stream=False, jinxes=None, use_jinxes=True, **kwargs)

Check if a command is for the LLM

Source code in npcpy/npc_compiler.py
def check_llm_command(self,
                        command,
                        messages=None,
                        context=None,
                        team=None,
                        stream=False,
                        jinxes=None,
                        use_jinxes=True,
                        **kwargs):
    """Check if a command is for the LLM"""
    if context is None:
        context = self.shared_context

    if team:
        self._current_team = team
    if jinxes is None and use_jinxes:
        jinxes_to_use = self.jinxes_dict
    elif jinxes is not None and use_jinxes:
        jinxes_to_use = jinxes

    return npy.llm_funcs.check_llm_command(
        command,
        model=self.model,
        provider=self.provider,
        npc=self,
        team=team,
        messages=self.memory if messages is None else messages,
        context=context,
        stream=stream,
        jinxes=jinxes_to_use,
        **kwargs,
    )

compress_planning_state(messages)

Source code in npcpy/npc_compiler.py
def compress_planning_state(self, messages):
    if isinstance(messages, list):
        from npcpy.llm_funcs import breathe, get_facts

        conversation_summary = breathe(messages=messages, npc=self)
        summary_data = conversation_summary.get('output', '')

        conversation_text = "\n".join([msg['content'] for msg in messages])
        extracted_facts = get_facts(conversation_text, model=self.model, provider=self.provider, npc=self)

        user_inputs = [msg['content'] for msg in messages if msg.get('role') == 'user']
        assistant_outputs = [msg['content'] for msg in messages if msg.get('role') == 'assistant']

        planning_state = {
            "goal": summary_data,
            "facts": [fact['statement'] if isinstance(fact, dict) else str(fact) for fact in extracted_facts[-10:]],
            "successes": [output[:100] for output in assistant_outputs[-5:]],
            "mistakes": [],
            "todos": user_inputs[-3:],
            "constraints": []
        }
    else:
        planning_state = messages

    todos = planning_state.get('todos', [])
    current_index = planning_state.get('current_todo_index', 0)

    if todos and current_index < len(todos):
        current_focus = todos[current_index].get('description', todos[current_index]) if isinstance(todos[current_index], dict) else str(todos[current_index])
    else:
        current_focus = 'No current task'

    compressed = {
        "goal": planning_state.get("goal", ""),
        "progress": f"{len(planning_state.get('successes', []))}/{len(todos)} todos completed",
        "context": self.get_planning_context_summary(planning_state),
        "current_focus": current_focus
    }
    return json.dumps(compressed, indent=2)

create_planning_state(goal)

Create initial planning state for a goal

Source code in npcpy/npc_compiler.py
def create_planning_state(self, goal: str) -> Dict[str, Any]:
    """Create initial planning state for a goal"""
    return {
        "goal": goal,
        "todos": [],
        "constraints": [],
        "facts": [],
        "mistakes": [],
        "successes": [],
        "current_todo_index": 0,
        "current_subtodo_index": 0,
        "context_summary": ""
    }

decompress_planning_state(compressed_state)

Restore planning state from compressed string

Source code in npcpy/npc_compiler.py
def decompress_planning_state(self, compressed_state: str) -> Dict[str, Any]:
    """Restore planning state from compressed string"""
    try:
        data = json.loads(compressed_state)
        return {
            "goal": data.get("goal", ""),
            "todos": [],
            "constraints": [],
            "facts": [],
            "mistakes": [],
            "successes": [],
            "current_todo_index": 0,
            "current_subtodo_index": 0,
            "compressed_context": data.get("context", "")
        }
    except json.JSONDecodeError:
        return self.create_planning_state("")

enter_tool_use_loop(prompt, tools=None, tool_map=None, max_iterations=5, stream=False)

Enter interactive tool use loop for complex tasks

Source code in npcpy/npc_compiler.py
def enter_tool_use_loop(
    self, 
    prompt: str, 
    tools: list = None, 
    tool_map: dict = None, 
    max_iterations: int = 5,
    stream: bool = False
):
    """Enter interactive tool use loop for complex tasks"""
    if not tools:
        tools = self.tools
    if not tool_map:
        tool_map = self.tool_map

    messages = self.memory.copy() if self.memory else []
    messages.append({"role": "user", "content": prompt})

    for iteration in range(max_iterations):
        response = get_llm_response(
            prompt="",
            model=self.model,
            provider=self.provider,
            npc=self,
            messages=messages,
            tools=tools,
            tool_map=tool_map,
            auto_process_tool_calls=True,
            stream=stream
        )

        messages = response.get('messages', messages)

        if not response.get('tool_calls'):
            return {
                "final_response": response.get('response'),
                "messages": messages,
                "iterations": iteration + 1
            }

    return {
        "final_response": "Max iterations reached",
        "messages": messages,
        "iterations": max_iterations
    }

execute_jinx(jinx_name, inputs, conversation_id=None, message_id=None, team_name=None, extra_globals=None)

Source code in npcpy/npc_compiler.py
def execute_jinx(
    self,
    jinx_name,
    inputs,
    conversation_id=None,
    message_id=None,
    team_name=None,
    extra_globals=None
):
    if jinx_name in self.jinxes_dict:
        jinx = self.jinxes_dict[jinx_name]
    else:
        return {"error": f"jinx '{jinx_name}' not found"}

    import time as _time
    _start = _time.monotonic()
    _status = "success"
    _error = None

    try:
        result = jinx.execute(
            input_values=inputs,
            npc=self,
            extra_globals=extra_globals,
            jinja_env=self.jinja_env
        )
    except Exception as e:
        _status = "error"
        _error = str(e)
        result = {"error": str(e)}

    _duration_ms = int((_time.monotonic() - _start) * 1000)
    return result

execute_jinx_command(jinx, args, messages=None)

Execute a jinx command with the given arguments.

Source code in npcpy/npc_compiler.py
def execute_jinx_command(self, 
    jinx: Jinx,
    args: List[str],
    messages=None,
) -> Dict[str, Any]:
    """
    Execute a jinx command with the given arguments.
    """

    input_values = extract_jinx_inputs(args, jinx)

    jinx_output = jinx.execute(
        input_values,
        npc=self,
        messages=messages,
        jinja_env=self.jinja_env
    )

    return {"messages": messages, "output": jinx_output}

execute_planning_item(item, planning_state, context='')

Execute a single planning item (todo or subtodo)

Source code in npcpy/npc_compiler.py
def execute_planning_item(self, item: Dict[str, Any], planning_state: Dict[str, Any], context: str = "") -> Dict[str, Any]:
    """Execute a single planning item (todo or subtodo)"""
    context_summary = self.get_planning_context_summary(planning_state)

    command = f"""
    Current context:
    {context_summary}
    {context}

    Execute this task: {item['description']}

    Constraints to follow:
    {chr(10).join([f"- {c}" for c in planning_state.get('constraints', [])])}
    """

    result = self.check_llm_command(
        command,
        context=self.shared_context,
        stream=False
    )

    return result

generate_subtodos(todo)

Generate atomic subtodos for a complex todo

Source code in npcpy/npc_compiler.py
def generate_subtodos(self, todo: Dict[str, Any]) -> List[Dict[str, Any]]:
    """Generate atomic subtodos for a complex todo"""
    prompt = f"""
    Parent todo: {todo['description']}

    Break this into atomic, executable subtodos. Each should be:
    - A single, concrete action
    - Executable in one step
    - Clear and unambiguous

    Return JSON:
    {{
        "subtodos": [
            {{"description": "subtodo description", "type": "action|verification|analysis"}},
            ...
        ]
    }}
    """

    response = self.get_llm_response(prompt, format="json")
    return response.get("response", {}).get("subtodos", [])

generate_todos(user_goal, planning_state, additional_context='')

Generate high-level todos for a goal

Source code in npcpy/npc_compiler.py
def generate_todos(self, user_goal: str, planning_state: Dict[str, Any], additional_context: str = "") -> List[Dict[str, Any]]:
    """Generate high-level todos for a goal"""
    prompt = f"""
    You are a high-level project planner. Structure tasks logically:
    1. Understand current state
    2. Make required changes 
    3. Verify changes work

    User goal: {user_goal}
    {additional_context}

    Generate 3-5 todos to accomplish this goal. Use specific actionable language.
    Each todo should be independent where possible and focused on a single component.

    Return JSON:
    {{
        "todos": [
            {{"description": "todo description", "estimated_complexity": "simple|medium|complex"}},
            ...
        ]
    }}
    """

    response = self.get_llm_response(prompt, format="json", tool_choice=False)
    todos_data = response.get("response", {}).get("todos", [])
    return todos_data

get_code_response(prompt, language='python', execute=False, locals_dict=None)

Generate and optionally execute code responses

Source code in npcpy/npc_compiler.py
def get_code_response(
    self, 
    prompt: str, 
    language: str = "python", 
    execute: bool = False, 
    locals_dict: dict = None
):
    """Generate and optionally execute code responses"""
    code_prompt = f"""Generate {language} code for: {prompt}

    Provide ONLY executable {language} code without explanations.
    Do not include markdown formatting or code blocks.
    Begin directly with the code."""

    response = get_llm_response(
        prompt=code_prompt,
        model=self.model,
        provider=self.provider,
        npc=self,
        stream=False
    )

    generated_code = response.get('response', '')

    result = {
        "code": generated_code,
        "executed": False,
        "output": None,
        "error": None
    }

    if execute and language == "python":
        if locals_dict is None:
            locals_dict = {}

        exec_globals = {"__builtins__": __builtins__}
        exec_globals.update(locals_dict)

        exec_locals = {}
        try:
            exec(generated_code, exec_globals, exec_locals)
        except SystemExit as e:
            result["error"] = f"Code called sys.exit({e.code})"
            return result

        locals_dict.update(exec_locals)
        result["executed"] = True
        result["output"] = exec_locals.get("output", "Code executed successfully")

    return result

get_llm_response(request, jinxes=None, tools=None, tool_map=None, tool_choice=None, messages=None, auto_process_tool_calls=True, use_core_tools=False, **kwargs)

Source code in npcpy/npc_compiler.py
def get_llm_response(self, 
                    request,
                    jinxes=None,
                    tools: Optional[list] = None,
                    tool_map: Optional[dict] = None,
                    tool_choice=None, 
                    messages=None,
                    auto_process_tool_calls=True,
                    use_core_tools: bool = False,
                    **kwargs):
    all_candidate_functions = []

    if tools is not None and tool_map is not None:
        all_candidate_functions.extend([func for func in tool_map.values() if callable(func)])
    elif hasattr(self, 'tool_map') and self.tool_map:
        all_candidate_functions.extend([func for func in self.tool_map.values() if callable(func)])

    if use_core_tools:
        dynamic_core_tools_list = [
            self.think_step_by_step,
            self.write_code,
        ]

        if self.db_conn:
            dynamic_core_tools_list.append(self.query_database)

        all_candidate_functions.extend(dynamic_core_tools_list)

    unique_functions = []
    seen_names = set()
    for func in all_candidate_functions:
        if func.__name__ not in seen_names:
            unique_functions.append(func)
            seen_names.add(func.__name__)

    final_tools_schema = None
    final_tool_map_dict = None

    if unique_functions:
        final_tools_schema, final_tool_map_dict = auto_tools(unique_functions)

    if tool_choice is None:
        if final_tools_schema:
            tool_choice = "auto"
        else:
            tool_choice = None

    response = npy.llm_funcs.get_llm_response(
        request, 
        npc=self, 
        jinxes=jinxes,
        tools=final_tools_schema,
        tool_map=final_tool_map_dict,
        tool_choice=tool_choice,           
        auto_process_tool_calls=auto_process_tool_calls,
        messages=self.memory if messages is None else messages,
        **kwargs
    )        

    return response

get_memory_context()

Get formatted memory context for system prompt

Source code in npcpy/npc_compiler.py
def get_memory_context(self):
    """Get formatted memory context for system prompt"""
    if not self.kg_data:
        return ""

    context_parts = []

    recent_facts = self.kg_data.get('facts', [])[-10:]
    if recent_facts:
        context_parts.append("Recent memories:")
        for fact in recent_facts:
            context_parts.append(f"- {fact['statement']}")

    concepts = self.kg_data.get('concepts', [])
    if concepts:
        concept_names = [c['name'] for c in concepts[:5]]
        context_parts.append(f"Key concepts: {', '.join(concept_names)}")

    return "\n".join(context_parts)

get_planning_context_summary(planning_state)

Get lightweight context for planning prompts

Source code in npcpy/npc_compiler.py
def get_planning_context_summary(self, planning_state: Dict[str, Any]) -> str:
    """Get lightweight context for planning prompts"""
    context = []
    facts = planning_state.get('facts', [])
    mistakes = planning_state.get('mistakes', [])
    successes = planning_state.get('successes', [])

    if facts:
        context.append(f"Facts: {'; '.join(facts[:5])}")
    if mistakes:
        context.append(f"Recent mistakes: {'; '.join(mistakes[-3:])}")
    if successes:
        context.append(f"Recent successes: {'; '.join(successes[-3:])}")
    return "\n".join(context)

get_system_prompt(simple=False, tool_capable=False)

Get system prompt for the NPC

Source code in npcpy/npc_compiler.py
def get_system_prompt(self, simple=False, tool_capable=False):
    """Get system prompt for the NPC"""
    if simple or self.plain_system_message:
        return self.primary_directive
    else:
        return get_system_message(self, team=self.team, tool_capable=tool_capable)

handle_agent_pass(npc_to_pass, command, messages=None, context=None, shared_context=None, stream=False, team=None)

Pass a command to another NPC

Source code in npcpy/npc_compiler.py
def handle_agent_pass(self, 
                        npc_to_pass,
                        command, 
                        messages=None, 
                        context=None, 
                        shared_context=None, 
                        stream=False,
                        team=None):  
    """Pass a command to another NPC"""
    print('handling agent pass')
    if isinstance(npc_to_pass, NPC):
        target_npc = npc_to_pass
    else:
        return {"error": "Invalid NPC to pass command to"}

    if shared_context is not None:
        self.shared_context.update(shared_context)
        target_npc.shared_context.update(shared_context)

    updated_command = (
        command
        + "\n\n"
        + f"NOTE: THIS COMMAND HAS BEEN PASSED FROM {self.name} TO YOU, {target_npc.name}.\n"
        + "PLEASE CHOOSE ONE OF THE OTHER OPTIONS WHEN RESPONDING."
    )

    result = target_npc.check_llm_command(
        updated_command,
        messages=messages,
        context=target_npc.shared_context,
        team=team, 
        stream=stream
    )
    if isinstance(result, dict):
        result['npc_name'] = target_npc.name
        result['passed_from'] = self.name

    return result    

initialize_jinxes(team_raw_jinxes=None)

Loads and performs first-pass Jinja rendering for NPC-specific jinxes, now that the NPC's team context is fully established.

Source code in npcpy/npc_compiler.py
def initialize_jinxes(self, team_raw_jinxes: Optional[List['Jinx']] = None):
    """
    Loads and performs first-pass Jinja rendering for NPC-specific jinxes,
    now that the NPC's team context is fully established.
    """
    npc_jinxes_raw_list = []

    if self.jinxes_spec == "*":
        if self.team and hasattr(self.team, 'jinxes_dict') and self.team.jinxes_dict:
            self.jinxes_dict.update(self.team.jinxes_dict)
    else:
        if self.team and hasattr(self.team, 'jinxes_dict') and self.team.jinxes_dict:
            jinxes_base_dir = None
            if hasattr(self.team, 'team_path') and self.team.team_path:
                jinxes_base_dir = os.path.join(self.team.team_path, 'jinxes')

            path_map = getattr(self.team, '_jinx_path_map', None)
            for jinx_spec in self.jinxes_spec:
                if jinxes_base_dir:
                    matched_names = match_jinx_spec_to_names(jinx_spec, self.team.jinxes_dict, jinxes_base_dir, jinx_path_map=path_map)
                else:
                    matched_names = [jinx_spec] if jinx_spec in self.team.jinxes_dict else []

                if not matched_names:
                    # Warn-and-skip instead of crashing the whole process. A missing
                    # external/foreign jinx (offline, wrong repo, rename) shouldn't
                    # take the MCP server down with it — the NPC just has fewer tools.
                    print(
                        f"Warning: NPC '{self.name}' references jinx '{jinx_spec}' but no matching jinx was found. "
                        f"Skipping. Available jinxes (first 20): {list(self.team.jinxes_dict.keys())[:20]}",
                        file=sys.stderr,
                    )
                    continue

                for jinx_name in matched_names:
                    if jinx_name in self.team.jinxes_dict:
                        self.jinxes_dict[jinx_name] = self.team.jinxes_dict[jinx_name]

    # Additively merge team-level jinxes (from team .ctx `jinxes:`) on top of
    # whatever this NPC resolved from its own spec. This eliminates the need
    # to list universal jinxes (chat, stop, ask_form) in every .npc file.
    team_jinxes_spec = getattr(self.team, 'team_jinxes_spec', None) if self.team else None
    if team_jinxes_spec and hasattr(self.team, 'jinxes_dict') and self.team.jinxes_dict:
        jinxes_base_dir = None
        if hasattr(self.team, 'team_path') and self.team.team_path:
            jinxes_base_dir = os.path.join(self.team.team_path, 'jinxes')
        path_map = getattr(self.team, '_jinx_path_map', None)
        for jinx_spec in team_jinxes_spec:
            if jinxes_base_dir:
                matched_names = match_jinx_spec_to_names(jinx_spec, self.team.jinxes_dict, jinxes_base_dir, jinx_path_map=path_map)
            else:
                matched_names = [jinx_spec] if jinx_spec in self.team.jinxes_dict else []
            for jinx_name in matched_names:
                if jinx_name in self.team.jinxes_dict and jinx_name not in self.jinxes_dict:
                    self.jinxes_dict[jinx_name] = self.team.jinxes_dict[jinx_name]

    should_load_from_directory = False
    if hasattr(self, 'npc_jinxes_directory') and self.npc_jinxes_directory and os.path.exists(self.npc_jinxes_directory):
        if not self.team:
            should_load_from_directory = True
        elif hasattr(self.team, 'team_path') and self.team.team_path:
            team_jinxes_dir = os.path.join(self.team.team_path, 'jinxes')
            if os.path.normpath(self.npc_jinxes_directory) != os.path.normpath(team_jinxes_dir):
                should_load_from_directory = True

    if should_load_from_directory:
        for jinx_obj in load_jinxes_from_directory(self.npc_jinxes_directory):
            if jinx_obj.jinx_name not in self.jinxes_dict:
                npc_jinxes_raw_list.append(jinx_obj)

    if npc_jinxes_raw_list or team_raw_jinxes:
        all_available_raw_jinxes = list(team_raw_jinxes or [])
        all_available_raw_jinxes.extend(npc_jinxes_raw_list)

        combined_raw_jinxes_dict = {j.jinx_name: j for j in all_available_raw_jinxes}

        npc_first_pass_jinja_env = SandboxedEnvironment(undefined=SilentUndefined)

        jinx_macro_globals = {}
        for raw_jinx in combined_raw_jinxes_dict.values():
            def create_jinx_callable(jinx_obj_in_closure):
                def callable_jinx(**kwargs):
                    temp_jinja_env = SandboxedEnvironment(undefined=SilentUndefined)
                    rendered_target_steps = []
                    for target_step in jinx_obj_in_closure._raw_steps:
                        temp_rendered_step = {}
                        for k, v in target_step.items():
                            if isinstance(v, str):
                                try:
                                    temp_rendered_step[k] = temp_jinja_env.from_string(v).render(**kwargs)
                                except Exception as e:
                                    print(f"Warning: Error in Jinx macro '{jinx_obj_in_closure.jinx_name}' rendering step field '{k}' (NPC first pass): {e}")
                                    temp_rendered_step[k] = v
                            else:
                                temp_rendered_step[k] = v
                        rendered_target_steps.append(temp_rendered_step)
                    return yaml.dump(rendered_target_steps, default_flow_style=False)
                return callable_jinx

            jinx_macro_globals[raw_jinx.jinx_name] = create_jinx_callable(raw_jinx)

        npc_first_pass_jinja_env.globals.update(jinx_macro_globals)

        for raw_npc_jinx in npc_jinxes_raw_list:
            try:
                raw_npc_jinx.render_first_pass(npc_first_pass_jinja_env, jinx_macro_globals)
                self.jinxes_dict[raw_npc_jinx.jinx_name] = raw_npc_jinx
            except Exception as e:
                print(f"Error performing first-pass rendering for NPC Jinx '{raw_npc_jinx.jinx_name}': {e}")

    self.jinx_tool_catalog = build_jinx_tool_catalog(self.jinxes_dict)
    print(f"NPC {self.name} loaded {len(self.jinxes_dict)} jinxes and built catalog with {len(self.jinx_tool_catalog)} tools.", file=sys.stderr)

query_database(sql_query)

Execute a SQL query against the available database

Source code in npcpy/npc_compiler.py
def query_database(self, sql_query: str) -> str:
    """Execute a SQL query against the available database"""
    if not self.db_conn:
        return "No database connection available"

    try:
        with self.db_conn.connect() as conn:
            result = conn.execute(text(sql_query))
            rows = result.fetchall()

            if not rows:
                return "Query executed successfully but returned no results"

            columns = result.keys()
            formatted_rows = []
            for row in rows[:20]:  
                row_dict = dict(zip(columns, row))
                formatted_rows.append(str(row_dict))

            return f"Query results ({len(rows)} total rows, showing first 20):\n" + "\n".join(formatted_rows)

    except Exception as e:
        return f"Database query error: {str(e)}"

resolve_tools(mcp_clients_cache=None)

Returns (tools_for_llm, tool_executors) where: - tools_for_llm: list of OpenAI-style tool defs for the LLM - tool_executors: dict mapping tool_name -> {"type": ..., ...} for execution

Assembles from: jinx_tool_catalog + mcp_servers + python tools

Source code in npcpy/npc_compiler.py
def resolve_tools(self, mcp_clients_cache: dict = None) -> tuple:
    """
    Returns (tools_for_llm, tool_executors) where:
      - tools_for_llm: list of OpenAI-style tool defs for the LLM
      - tool_executors: dict mapping tool_name -> {"type": ..., ...} for execution

    Assembles from: jinx_tool_catalog + mcp_servers + python tools
    """
    from npcpy.serve import MCPClientNPC

    tools_for_llm = []
    tool_executors = {}
    seen = set()

    # 1. Jinx tools
    catalog = self.jinx_tool_catalog or build_jinx_tool_catalog(self.jinxes_dict)
    for name, tool_def in catalog.items():
        if name not in seen:
            tools_for_llm.append(tool_def)
            tool_executors[name] = {"type": "jinx", "jinx": self.jinxes_dict.get(name)}
            seen.add(name)

    # 2. MCP server tools
    if mcp_clients_cache is None:
        mcp_clients_cache = {}

    connectable_specs = []
    nameonly_tools = []
    for server_spec in (self.mcp_servers or []):
        if isinstance(server_spec, str):
            connectable_specs.append({"path": server_spec})
        elif isinstance(server_spec, dict):
            if "path" in server_spec or "command" in server_spec or "url" in server_spec:
                connectable_specs.append(server_spec)
            elif "tools" in server_spec:
                nameonly_tools.extend(server_spec["tools"])

    def spec_cache_key(spec):
        if isinstance(spec, str):
            return os.path.expanduser(spec)
        if "path" in spec:
            return os.path.expanduser(spec["path"])
        if "url" in spec:
            return spec["url"]
        if "command" in spec:
            return f"{spec['command']}:{' '.join(spec.get('args', []))}"
        return str(spec)

    for spec in connectable_specs:
        key = spec_cache_key(spec)
        whitelist = spec.get("tools")
        client = mcp_clients_cache.get(key)
        if not client:
            client = MCPClientNPC()
            if client.connect_sync(spec):
                mcp_clients_cache[key] = client
            else:
                continue
        for tool_def in client.available_tools_llm:
            name = tool_def["function"]["name"]
            if name in seen:
                continue
            if whitelist and name not in whitelist:
                continue
            tools_for_llm.append(tool_def)
            tool_executors[name] = {
                "type": "mcp",
                "client": client,
                "tool_func": client.tool_map.get(name),
            }
            seen.add(name)

    # Resolve tool-name-only specs by searching team MCP servers
    if nameonly_tools and self.team and hasattr(self.team, "mcp_servers"):
        for team_server in (self.team.mcp_servers or []):
            ts = team_server if isinstance(team_server, dict) else {"path": team_server}
            key = spec_cache_key(ts)
            client = mcp_clients_cache.get(key)
            if not client:
                client = MCPClientNPC()
                if client.connect_sync(ts):
                    mcp_clients_cache[key] = client
                else:
                    continue
            for tool_def in client.available_tools_llm:
                name = tool_def["function"]["name"]
                if name in nameonly_tools and name not in seen:
                    tools_for_llm.append(tool_def)
                    tool_executors[name] = {
                        "type": "mcp",
                        "client": client,
                        "tool_func": client.tool_map.get(name),
                    }
                    seen.add(name)

    # 3. Python tools (from auto_tools)
    for tool_def in (self.tools_schema or []):
        name = tool_def["function"]["name"]
        if name not in seen:
            tools_for_llm.append(tool_def)
            tool_executors[name] = {"type": "python", "func": self.tool_map.get(name)}
            seen.add(name)

    return tools_for_llm, tool_executors

run(input_text, **kwargs)

Source code in npcpy/npc_compiler.py
def run(self, input_text: str, **kwargs):
    return self.check_llm_command(input_text, **kwargs)

run_planning_loop(user_goal, interactive=True)

Run the full planning loop for a goal

Source code in npcpy/npc_compiler.py
def run_planning_loop(self, user_goal: str, interactive: bool = True) -> Dict[str, Any]:
    """Run the full planning loop for a goal"""
    planning_state = self.create_planning_state(user_goal)

    todos = self.generate_todos(user_goal, planning_state)
    planning_state["todos"] = todos

    for i, todo in enumerate(todos):
        planning_state["current_todo_index"] = i

        if self.should_break_down_todo(todo):
            subtodos = self.generate_subtodos(todo)

            for j, subtodo in enumerate(subtodos):
                planning_state["current_subtodo_index"] = j
                result = self.execute_planning_item(subtodo, planning_state)

                if result.get("output"):
                    planning_state["successes"].append(f"Completed: {subtodo['description']}")
                else:
                    planning_state["mistakes"].append(f"Failed: {subtodo['description']}")
        else:
            result = self.execute_planning_item(todo, planning_state)

            if result.get("output"):
                planning_state["successes"].append(f"Completed: {todo['description']}")
            else:
                planning_state["mistakes"].append(f"Failed: {todo['description']}")

    return {
        "planning_state": planning_state,
        "compressed_state": self.compress_planning_state(planning_state),
        "summary": f"Completed {len(planning_state['successes'])} tasks for goal: {user_goal}"
    }

save(directory=None)

Save NPC to file

Source code in npcpy/npc_compiler.py
def save(self, directory=None):
    """Save NPC to file"""
    if directory is None:
        directory = self.npc_directory

    ensure_dirs_exist(directory)
    npc_path = os.path.join(directory, f"{self.name}.npc")

    return write_yaml_file(npc_path, self.to_dict())

search_my_memories(query, limit=10)

Search through this NPC's knowledge graph memories for relevant facts and concepts

Source code in npcpy/npc_compiler.py
def search_my_memories(self, query: str, limit: int = 10) -> str:
    """Search through this NPC's knowledge graph memories for relevant facts and concepts"""
    if not self.kg_data:
        return "No memories available"

    query_lower = query.lower()
    relevant_facts = []
    relevant_concepts = []

    for fact in self.kg_data.get('facts', []):
        if query_lower in fact.get('statement', '').lower():
            relevant_facts.append(fact['statement'])

    for concept in self.kg_data.get('concepts', []):
        if query_lower in concept.get('name', '').lower():
            relevant_concepts.append(concept['name'])

    result_parts = []
    if relevant_facts:
        result_parts.append(f"Relevant memories: {'; '.join(relevant_facts[:limit])}")
    if relevant_concepts:
        result_parts.append(f"Related concepts: {', '.join(relevant_concepts[:limit])}")

    return "\n".join(result_parts) if result_parts else f"No memories found matching '{query}'"

should_break_down_todo(todo)

Ask LLM if a todo needs breakdown

Source code in npcpy/npc_compiler.py
def should_break_down_todo(self, todo: Dict[str, Any]) -> bool:
    """Ask LLM if a todo needs breakdown"""
    prompt = f"""
    Todo: {todo['description']}
    Complexity: {todo.get('estimated_complexity', 'unknown')}

    Should this be broken into smaller steps? Consider:
    - Is it complex enough to warrant breakdown?
    - Would breakdown make execution clearer?
    - Are there multiple distinct steps?

    Return JSON: {{"should_break_down": true/false, "reason": "explanation"}}
    """

    response = self.get_llm_response(prompt, format="json", tool_choice=False)
    result = response.get("response", {})
    return result.get("should_break_down", False)

think_step_by_step(problem)

Think through a problem step by step using chain of thought reasoning

Source code in npcpy/npc_compiler.py
def think_step_by_step(self, problem: str) -> str:
    """Think through a problem step by step using chain of thought reasoning"""
    thinking_prompt = f"""Think through this problem step by step:

{problem}

Break down your reasoning into clear steps:
1. First, I need to understand...
2. Then, I should consider...
3. Next, I need to...
4. Finally, I can conclude...

Provide your step-by-step analysis.
Do not under any circumstances ask for feedback from a user. These thoughts are part of an agentic tool that is letting the agent
break down a problem by thinking it through. they will review the results and use them accordingly. 


"""

    response = self.get_llm_response(thinking_prompt, tool_choice = False)
    return response.get('response', 'Unable to process thinking request')

to_dict()

Convert NPC to dictionary representation

Source code in npcpy/npc_compiler.py
def to_dict(self):
    """Convert NPC to dictionary representation"""
    jinx_rep = []
    if self.jinxes_dict:
        jinx_rep = [ jinx.to_dict() for jinx in self.jinxes_dict.values()]
    source_path = getattr(self, 'npc_path', None) or getattr(self, 'source_path', None) or ''
    source_ext = ''
    if source_path:
        lower = source_path.lower()
        if lower.endswith('.npc'):
            source_ext = '.npc'
        elif lower.endswith('.md'):
            source_ext = '.md'
    return {
        "name": self.name,
        "primary_directive": self.primary_directive,
        "model": self.model,
        "provider": self.provider,
        "api_url": self.api_url,
        "api_key": self.api_key,
        "jinxes": self.jinxes_spec,
        "use_global_jinxes": self.use_global_jinxes,
        "source_path": source_path,
        "source_ext": source_ext,
    }

write_code(task, language='python')

Write code to accomplish a task.

Parameters:
  • task (str) –

    Description of what the code should do

  • language (str, default: 'python' ) –

    Programming language to use (default: python)

Returns:
  • str

    The generated code as a string

Source code in npcpy/npc_compiler.py
    def write_code(self, task: str, language: str = "python") -> str:
        """Write code to accomplish a task.

        Args:
            task: Description of what the code should do
            language: Programming language to use (default: python)

        Returns:
            The generated code as a string
        """
        code_prompt = f"""Write {language} code to accomplish the following task:

{task}

Requirements:
- Write clean, well-commented code
- Include error handling where appropriate
- Make sure the code is complete and runnable
- Only output the code, no explanations before or after

```{language}
"""

        response = self.get_llm_response(code_prompt, tool_choice=False)
        code = response.get('response', '')

        if f'```{language}' in code:
            code = code.split(f'```{language}')[-1]
        if '```' in code:
            code = code.split('```')[0]

        return code.strip()

PreserveUndefined

Bases: ChainableUndefined

Undefined that preserves the original {{ variable }} syntax

Source code in npcpy/npc_compiler.py
class PreserveUndefined(ChainableUndefined):
    """Undefined that preserves the original {{ variable }} syntax"""
    def __str__(self):
        return f"{{{{ {self._undefined_name} }}}}"

SilentUndefined

Bases: Undefined

Undefined that silently returns empty string instead of raising errors

Source code in npcpy/npc_compiler.py
class SilentUndefined(Undefined):
    """Undefined that silently returns empty string instead of raising errors"""
    def _fail_with_undefined_error(self, *args, **kwargs):
        return ""

    def __str__(self):
        return ""

    def __repr__(self):
        return ""

    def __bool__(self):
        return False

    def __eq__(self, other):
        return other == "" or other is None or isinstance(other, Undefined)

    def __ne__(self, other):
        return not self.__eq__(other)

    def __iter__(self):
        return iter([])

    def __len__(self):
        return 0

Team

Source code in npcpy/npc_compiler.py
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
class Team:
    def __init__(self,
                    team_path=None,
                    npcs: Optional[List['NPC']] = None,
                    forenpc: Optional[Union[str, 'NPC']] = None,
                    jinxes: Optional[List[Union['Jinx', Dict[str, Any]]]] = None,
                    db_conn=None,
                    model = None,
                    provider = None,
                    api_url = None,
                    api_key = None,
                    team_jinxes: Optional[List['Jinx']] = None):
        """
        Initialize an NPC team from directory or list of NPCs

        Args:
            team_path: Path to team directory
            npcs: List of NPC objects
            db_conn: Database connection
            team_jinxes: Pre-loaded jinxes (sub-teams use the same jinxes as the team)
        """
        self._team_jinxes = team_jinxes
        self.model = model
        self.provider = provider
        self.api_url = api_url
        self.api_key = api_key

        self.npcs: Dict[str, 'NPC'] = {}
        self.sub_teams: Dict[str, 'Team'] = {}
        self.jinxes_dict: Dict[str, 'Jinx'] = {}
        self._raw_jinxes_list: List['Jinx'] = []
        self.jinx_tool_catalog: Dict[str, Dict[str, Any]] = {}

        self.jinja_env_for_first_pass = SandboxedEnvironment(undefined=SilentUndefined)

        self.db_conn = db_conn
        self.team_path = os.path.expanduser(team_path) if team_path else None
        self.databases = []
        self.mcp_servers = []

        self.forenpc: Optional['NPC'] = None
        self.forenpc_name: Optional[str] = None
        self.skills_directory: Optional[str] = None
        self.external_jinx_teams: List[str] = []

        if team_path:
            self.name = os.path.basename(os.path.abspath(team_path))
            self._load_from_directory_and_initialize_forenpc() 
        elif npcs:
            self.name = "custom_team"
            for npc_obj in npcs:
                self.npcs[npc_obj.name] = npc_obj
                npc_obj.team = self

            if jinxes:
                for jinx_item in jinxes:
                    if isinstance(jinx_item, Jinx):
                        self._raw_jinxes_list.append(jinx_item)
                    elif isinstance(jinx_item, dict):
                        self._raw_jinxes_list.append(Jinx(jinx_data=jinx_item))

            self._determine_forenpc_from_provided_npcs(npcs, forenpc)

        else:
            self.name = "custom_team"
            self._create_default_forenpc()

        self.context = ''
        self.shared_context = {
            "intermediate_results": {},
            "dataframes": {},
            "memories": {},          
            "execution_history": [],   
            "context":''       
            }

        if team_path:
            self._load_team_context_into_shared_context()
        elif self.forenpc:
            if not self.context:
                self.context = f"Team '{self.name}' with forenpc '{self.forenpc.name}'"
                self.shared_context['context'] = self.context

        self._perform_first_pass_jinx_rendering()
        self.jinx_tool_catalog = build_jinx_tool_catalog(self.jinxes_dict)
        print(f"[TEAM] Built Jinx tool catalog with {len(self.jinx_tool_catalog)} entries for team {self.name}", file=sys.stderr)

        for npc_obj in self.npcs.values():
            npc_obj.initialize_jinxes(team_raw_jinxes=self._raw_jinxes_list) 

        if db_conn is not None:
            init_db_tables()

    def _load_from_directory_and_initialize_forenpc(self):
        """
        Consolidated method to load NPCs, team context, and resolve the forenpc.
        Ensures self.npcs is populated and self.forenpc is an NPC object.

        Load order: context → jinxes → NPCs (so NPC files can use {{ jinx_name }}
        Jinja references that resolve to the jinx's relative path).
        """
        if not os.path.exists(self.team_path):
            raise ValueError(f"Team directory not found: {self.team_path}")

        self._load_team_context_file()

        # Load jinxes FIRST so we can build the name→path map for NPC Jinja context.
        # Sub-teams use the same jinxes as the team — they're just organizational groupings.
        if self._team_jinxes:
            self._raw_jinxes_list.extend(self._team_jinxes)

        jinxes_dir = os.path.join(self.team_path, "jinxes")
        if os.path.exists(jinxes_dir):
            for jinx_obj in load_jinxes_from_directory(jinxes_dir):
                self._raw_jinxes_list.append(jinx_obj)

        # Merge jinxes from external teams listed in team.ctx (external_jinx_teams).
        # Own-team jinxes take precedence — external ones only fill in gaps by name.
        if getattr(self, 'external_jinx_teams', None):
            existing_names = {j.jinx_name for j in self._raw_jinxes_list}
            for ext_team_root in self.external_jinx_teams:
                ext_jinxes_dir = os.path.join(ext_team_root, "jinxes")
                if not os.path.isdir(ext_jinxes_dir):
                    print(f"[TEAM] external_jinx_teams: skipping missing {ext_jinxes_dir}", file=sys.stderr)
                    continue
                for jinx_obj in load_jinxes_from_directory(ext_jinxes_dir):
                    if jinx_obj.jinx_name in existing_names:
                        continue
                    self._raw_jinxes_list.append(jinx_obj)
                    existing_names.add(jinx_obj.jinx_name)

        if hasattr(self, 'skills_directory') and self.skills_directory:
            skills_path = os.path.expanduser(self.skills_directory)
            if not os.path.isabs(skills_path):
                skills_path = os.path.join(self.team_path, skills_path)
            if os.path.exists(skills_path):
                for jinx_obj in load_jinxes_from_directory(skills_path):
                    self._raw_jinxes_list.append(jinx_obj)
                print(f"[TEAM] Loaded skills from SKILLS_DIRECTORY: {skills_path}")
            else:
                print(f"[TEAM] Warning: SKILLS_DIRECTORY not found: {skills_path}")

        # Build jinx name→relative_path map for Jinja context.
        # e.g. { "edit_file": "lib/core/files/edit_file", "sh": "lib/core/sh", ... }
        self._jinx_path_map = {}
        for jinx_obj in self._raw_jinxes_list:
            if jinx_obj.jinx_name in self._jinx_path_map:
                continue
            source = getattr(jinx_obj, '_source_path', None)
            if source:
                # Derive the jinxes/ base dir from the source path
                base_dir = None
                parts = source.split(os.sep)
                for i, p in enumerate(parts):
                    if p == 'jinxes':
                        base_dir = os.sep.join(parts[:i+1])
                if not base_dir:
                    continue
                try:
                    rel = os.path.relpath(source, base_dir)
                    if rel.endswith('.jinx'):
                        rel = rel[:-5]
                    self._jinx_path_map[jinx_obj.jinx_name] = rel
                except ValueError:
                    pass

        # --- Unified Jinja template functions (dbt-style) ---

        def _Jinx(name, path=None, *, repo=None, ref=None):
            """Resolve a jinx by name, optionally from a foreign team.

            Usage:
              {{ Jinx('edit_file') }}                                 — own team (or already-loaded external)
              {{ Jinx('kg_search_keyword', '/abs/team/root') }}       — positional path to foreign team
              {{ Jinx('kg_search_keyword', path='/abs/team/root') }}  — same, keyword
              {{ Jinx('kg_search_keyword', repo='npc-worldwide/npcsh') }}
                  — foreign team in a GitHub repo; cached to
                    ~/.npcsh/jinx_cache/<owner>_<repo>[@<ref>]/ on first use
              {{ Jinx('x', repo='owner/repo', ref='v1.2.0') }}        — pin a branch/tag

            Foreign jinxes are loaded into this team's pool on first resolve,
            so subsequent renders hit the normal in-memory path.
            """
            # Already known (own-team or previously-hydrated external).
            if name in self._jinx_path_map and not (repo or path):
                return self._jinx_path_map[name]

            # External source requested — resolve to a team root, then load.
            if repo or path:
                try:
                    team_root = _resolve_external_team_root(repo=repo, path=path, ref=ref)
                except Exception as _e:
                    print(f"Warning: Jinx('{name}', repo={repo!r}, path={path!r}) failed: {_e}", file=sys.stderr)
                    return name

                if team_root:
                    _hydrate_jinx_from_team(team_root, name)

                if name in self._jinx_path_map:
                    return self._jinx_path_map[name]

            # Warnings MUST go to stderr — npc_compiler runs inside the MCP server
            # process, which uses stdout for JSON-RPC. A stray print on stdout
            # corrupts the protocol and kills the connection.
            print(f"Warning: Jinx('{name}') not found. Available: {list(self._jinx_path_map.keys())[:15]}...", file=sys.stderr)
            return name

        def _resolve_external_team_root(repo=None, path=None, ref=None):
            """Return a local filesystem path to a team root (directory containing
            a jinxes/ folder), fetching from GitHub if needed. Caches under
            ~/.npcsh/jinx_cache/. Looks recursively for a directory named
            npc_team inside the cloned repo."""
            if path:
                expanded = os.path.expanduser(path)
                return expanded if os.path.isdir(expanded) else None

            if not repo:
                return None

            cache_root = os.path.expanduser('~/.npcsh/jinx_cache')
            os.makedirs(cache_root, exist_ok=True)
            slug = repo.replace('/', '_')
            if ref:
                slug = f"{slug}@{ref}"
            clone_dir = os.path.join(cache_root, slug)

            if not os.path.isdir(clone_dir):
                import subprocess as _sp
                url = f"https://github.com/{repo}.git"
                cmd = ['git', 'clone', '--depth', '1']
                if ref:
                    cmd += ['--branch', ref]
                cmd += [url, clone_dir]
                _sp.run(cmd, check=True, capture_output=True)

            # Find a directory named npc_team (the first one wins).
            for root, dirs, _ in os.walk(clone_dir):
                # Skip .git and node_modules to keep this fast.
                dirs[:] = [d for d in dirs if d not in ('.git', 'node_modules', '.venv', 'venv', 'dist')]
                if os.path.basename(root) == 'npc_team':
                    return root
            # Fallback: repo root itself if it has jinxes/ at top level.
            if os.path.isdir(os.path.join(clone_dir, 'jinxes')):
                return clone_dir
            return None

        def _hydrate_jinx_from_team(team_root, jinx_name):
            """Load a single named jinx from a foreign team root into this team's
            pool, mutating _raw_jinxes_list and _jinx_path_map in place."""
            jinxes_dir = os.path.join(team_root, 'jinxes')
            if not os.path.isdir(jinxes_dir):
                return
            # Walk to find <jinx_name>.jinx at any depth.
            for root, _, files in os.walk(jinxes_dir):
                target = f"{jinx_name}.jinx"
                if target in files:
                    jinx_path = os.path.join(root, target)
                    try:
                        jinx_obj = Jinx(jinx_path=jinx_path)
                    except Exception as _e:
                        print(f"Warning: failed to load foreign jinx {jinx_path}: {_e}", file=sys.stderr)
                        return
                    # De-dupe by name — own team already wins above.
                    for existing in self._raw_jinxes_list:
                        if existing.jinx_name == jinx_obj.jinx_name:
                            return
                    self._raw_jinxes_list.append(jinx_obj)
                    rel = os.path.relpath(jinx_path, jinxes_dir)
                    if rel.endswith('.jinx'):
                        rel = rel[:-5]
                    self._jinx_path_map[jinx_obj.jinx_name] = rel
                    return

        def _NPC(name):
            """Reference an NPC by name.
            Usage: {{ NPC('corca') }} → 'corca'
            Returns the name for use in directives and jinx configs.
            Validation happens at runtime, not compile time.
            """
            return name

        def _ref(model_name):
            """Reference a SQL model by name (dbt-style).
            Usage: FROM {{ ref('customer_feedback') }}
            At compile time in SQL models, resolves to the actual table name.
            In non-SQL contexts, returns the model name as-is.
            """
            return model_name

        def _jinxes_list(pattern):
            """Glob-expand a jinx path pattern to a list of paths.
            Usage: {% for j in jinxes_list('lib/browser/*') %}
              - {{ j }}
            {% endfor %}
            """
            import fnmatch as _fn
            matched = []
            for name, rel_path in self._jinx_path_map.items():
                spec_pattern = pattern
                if not spec_pattern.endswith('.jinx') and not spec_pattern.endswith('*'):
                    spec_pattern += '.jinx'
                rel_with_ext = rel_path + '.jinx'
                if _fn.fnmatch(rel_with_ext, spec_pattern):
                    matched.append(rel_path)
            return matched

        # Context dict used for NPC file loading and first-pass jinx rendering.
        # Provides both explicit functions and bare name shortcuts.
        self._npc_jinja_context = {
            # Explicit functions (preferred)
            'Jinx': _Jinx,
            'NPC': _NPC,
            'ref': _ref,
            'jinxes_list': _jinxes_list,
            # Bare jinx names as shortcuts (backward compat)
            **self._jinx_path_map,
        }

        # Resolve team-level `jinxes:` from the .ctx (Jinja-rendered) now that
        # the Jinx() macro is available. Every NPC on this team merges these
        # into its own jinxes_dict during initialize_jinxes.
        self._resolve_team_jinxes_spec()

        # Now load NPCs with jinx path context available
        for filename in os.listdir(self.team_path):
            if filename.endswith(".npc"):
                npc_path = os.path.join(self.team_path, filename)
                npc = NPC(npc_path, db_conn=self.db_conn, team=self)
                if _is_cli_provider(npc.provider):
                    npc = CLIAgent(
                        cli_provider=npc.provider,
                        name=npc.name,
                        primary_directive=npc.primary_directive,
                        model=npc.model,
                        provider=npc.provider,
                        api_url=npc.api_url,
                        api_key=npc.api_key,
                        db_conn=self.db_conn,
                        team=self,
                    )
                self.npcs[npc.name] = npc

        # Load markdown agents from the project root (parent of npc_team/).
        # Accepts agents.md, AGENTS.md, CLAUDE.md, and an agents/ directory.
        project_root = os.path.dirname(os.path.abspath(self.team_path))
        for md_name in ("agents.md", "AGENTS.md", "CLAUDE.md"):
            md_path = os.path.join(project_root, md_name)
            if os.path.exists(md_path):
                self._load_agents_from_md(md_path)

        agents_dir = os.path.join(project_root, "agents")
        if os.path.isdir(agents_dir):
            self._load_agents_from_dir(agents_dir)

        if self.forenpc_name and self.forenpc_name in self.npcs:
            self.forenpc = self.npcs[self.forenpc_name]
        elif self.npcs:
            self.forenpc = list(self.npcs.values())[0]
            self.forenpc_name = self.forenpc.name
        else:
            self._create_default_forenpc()

        self._load_sub_teams()

    def _load_team_context_file(self) -> Dict[str, Any]:
        """Loads team context from .ctx file and updates team attributes.

        Runs before the full Jinja context (Jinx()/NPC()/jinxes_list()) is built,
        so we pass an empty context with SilentUndefined — any `{{ Jinx('x') }}`
        inside jinxes: renders to empty on this pass. The real resolution happens
        in _resolve_team_jinxes_spec after jinx discovery.
        """
        ctx_data = {}
        for fname in os.listdir(self.team_path):
            if fname.endswith('.ctx'):
                ctx_data = load_yaml_file(os.path.join(self.team_path, fname), jinja_context={})
                if ctx_data is not None:
                    self.model = ctx_data.get('model', self.model)
                    self.provider = ctx_data.get('provider', self.provider)
                    self.api_url = ctx_data.get('api_url', self.api_url)
                    self.env = ctx_data.get('env', self.env if hasattr(self, 'env') else None)
                    self.mcp_servers = ctx_data.get('mcp_servers', [])
                    self.databases = ctx_data.get('databases', [])
                    self.forenpc_name = ctx_data.get('forenpc', self.forenpc_name)
                    self.skills_directory = ctx_data.get('SKILLS_DIRECTORY', None)
                    # external_jinx_teams: list of other team root dirs whose jinxes/
                    # directory should also be loaded into this team. Enables jinx
                    # reuse across teams (e.g. an app-specific team pulling in the
                    # global npcsh lib/) without copying files.
                    _ext = ctx_data.get('external_jinx_teams') or ctx_data.get('EXTERNAL_JINX_TEAMS') or []
                    if isinstance(_ext, str):
                        _ext = [_ext]
                    self.external_jinx_teams = [os.path.expanduser(str(p)) for p in _ext if p]
                return ctx_data
        return {}

    def _load_team_context_into_shared_context(self):
        """Loads team context into shared_context after forenpc is determined."""
        ctx_data = {}
        jinja_ctx = getattr(self, '_npc_jinja_context', None)
        for fname in os.listdir(self.team_path):
            if fname.endswith('.ctx'):
                ctx_data = load_yaml_file(os.path.join(self.team_path, fname), jinja_context=jinja_ctx if jinja_ctx is not None else {})
                if ctx_data is not None:
                    self.context = ctx_data.get('context', '')
                    self.shared_context['context'] = self.context
                    if 'file_patterns' in ctx_data:
                        file_cache = self._parse_file_patterns(ctx_data['file_patterns'])
                        self.shared_context['files'] = file_cache
                    for key, item in ctx_data.items():
                        if key not in ['name', 'mcp_servers', 'databases', 'context', 'file_patterns', 'forenpc', 'model', 'provider', 'api_url', 'env', 'SKILLS_DIRECTORY']:
                            self.shared_context[key] = item
                return

    def _determine_forenpc_from_provided_npcs(self, npcs_list: List['NPC'], forenpc_arg: Optional[Union[str, 'NPC']]):
        """Determines self.forenpc when NPCs are provided directly to Team.__init__."""
        if forenpc_arg:
            if isinstance(forenpc_arg, NPC):
                self.forenpc = forenpc_arg
                self.forenpc_name = forenpc_arg.name
            elif isinstance(forenpc_arg, str) and forenpc_arg in self.npcs:
                self.forenpc = self.npcs[forenpc_arg]
                self.forenpc_name = forenpc_arg
            else:
                print(f"Warning: Specified forenpc '{forenpc_arg}' not found among provided NPCs. Falling back to first NPC.")
                if npcs_list:
                    self.forenpc = npcs_list[0]
                    self.forenpc_name = npcs_list[0].name
                else:
                    self._create_default_forenpc()
        elif npcs_list:
            self.forenpc = npcs_list[0]
            self.forenpc_name = npcs_list[0].name
        else:
            self._create_default_forenpc()

    def _create_default_forenpc(self):
        """Creates a default forenpc if none can be determined."""
        forenpc_model = self.model
        forenpc_provider = self.provider or 'ollama'
        if not forenpc_model:
            raise ValueError("No model specified for default forenpc.")
        forenpc_api_key = self.api_key
        forenpc_api_url = self.api_url

        default_forenpc = NPC(name='forenpc', 
                                primary_directive="""You are the forenpc of the team, coordinating activities 
                                                    between NPCs on the team, verifying that results from 
                                                    NPCs are high quality and can help to adequately answer 
                                                    user requests.""", 
                                model=forenpc_model,
                                provider=forenpc_provider,
                                api_key=forenpc_api_key,
                                api_url=forenpc_api_url,                            
                                team=self
                                                    )
        self.forenpc = default_forenpc
        self.forenpc_name = default_forenpc.name
        self.npcs[default_forenpc.name] = default_forenpc

    def _perform_first_pass_jinx_rendering(self):
        """
        Performs the first-pass Jinja rendering on all loaded raw Jinxs.
        This expands nested Jinx calls but preserves runtime variables.

        Also injects team-level Jinja helpers into the rendering context:
        - NPC('name') — validates an NPC exists and returns its name
        - jinx name variables — e.g., {{ edit_file }} resolves to 'lib/core/files/edit_file'
        - jinxes_list('pattern') — glob-expands a jinx path pattern to a list
        """
        jinx_macro_globals = {}
        for raw_jinx in self._raw_jinxes_list:
            def create_jinx_callable(jinx_obj_in_closure):
                def callable_jinx(**kwargs):
                    temp_jinja_env = SandboxedEnvironment(undefined=SilentUndefined)

                    rendered_target_steps = []
                    for target_step in jinx_obj_in_closure._raw_steps:
                        temp_rendered_step = {}
                        for k, v in target_step.items():
                            if isinstance(v, str):
                                try:
                                    temp_rendered_step[k] = temp_jinja_env.from_string(v).render(**kwargs)
                                except Exception as e:
                                    print(f"Warning: Error in Jinx macro '{jinx_obj_in_closure.jinx_name}' rendering step field '{k}' (Team first pass): {e}")
                                    temp_rendered_step[k] = v
                            else:
                                temp_rendered_step[k] = v
                        rendered_target_steps.append(temp_rendered_step)

                    return yaml.dump(rendered_target_steps, default_flow_style=False)
                return callable_jinx

            jinx_macro_globals[raw_jinx.jinx_name] = create_jinx_callable(raw_jinx)

        # Inject unified Jinja context + jinx macros + ctx into first-pass globals
        self.jinja_env_for_first_pass.globals['jinxes'] = jinx_macro_globals
        # ctx — exposes team context variables: {{ ctx.forenpc }}, {{ ctx.preferences }}, etc.
        self.jinja_env_for_first_pass.globals['ctx'] = self.shared_context
        if hasattr(self, '_npc_jinja_context'):
            # Adds: Jinx(), NPC(), ref(), jinxes_list(), and bare jinx name shortcuts
            self.jinja_env_for_first_pass.globals.update(self._npc_jinja_context)
        self.jinja_env_for_first_pass.globals.update(jinx_macro_globals)

        for raw_jinx in self._raw_jinxes_list:
            try:
                # Re-resolve top-level 'npc' field if it contains Jinja
                if hasattr(raw_jinx, 'npc') and isinstance(raw_jinx.npc, str):
                    if '{{' in raw_jinx.npc and '}}' in raw_jinx.npc:
                        try:
                            template = self.jinja_env_for_first_pass.from_string(raw_jinx.npc)
                            raw_jinx.npc = template.render(**self.jinja_env_for_first_pass.globals)
                        except Exception as e:
                            print(f"Warning: Error rendering npc field for jinx '{raw_jinx.jinx_name}': {e}")

                raw_jinx.render_first_pass(self.jinja_env_for_first_pass, jinx_macro_globals)
                self.jinxes_dict[raw_jinx.jinx_name] = raw_jinx
            except Exception as e:
                print(f"Error performing first-pass rendering for Jinx '{raw_jinx.jinx_name}': {e}")

    def update_context(self, messages: list):
        """Update team context based on recent conversation patterns"""
        if len(messages) < 10:
            return

        summary = breathe(
            messages=messages[-10:], 
            npc=self.forenpc
        )
        characterization = summary.get('output')

        if characterization:
            team_ctx_path = os.path.join(self.team_path, "team.ctx")

            if os.path.exists(team_ctx_path):
                with open(team_ctx_path, 'r', encoding="utf-8") as f:
                    ctx_data = yaml.safe_load(f) or {}
            else:
                ctx_data = {}

            current_context = ctx_data.get('context', '')

            prompt = f"""Based on this characterization: {characterization},
            suggest changes to the team's context.
            Current Context: "{current_context}".
            Respond with JSON: {{"suggestion": "Your sentence."}}"""

            response = get_llm_response(
                prompt=prompt,
                npc=self.forenpc,
                format="json"
            )
            suggestion = response.get("response", {}).get("suggestion")

            if suggestion:
                new_context = (current_context + " " + suggestion).strip()
                user_approval = input(f"Update context to: {new_context}? [y/N]: ").strip().lower()
                if user_approval == 'y':
                    ctx_data['context'] = new_context
                    self.context = new_context
                    with open(team_ctx_path, 'w', encoding="utf-8") as f:
                        yaml.dump(ctx_data, f)

    def _load_sub_teams(self):
        """Load sub-teams from subdirectories.

        A subdirectory becomes a sub-team if it contains either:
          - one or more .npc files (npcsh-native team), or
          - agents.md / AGENTS.md / CLAUDE.md / an agents/ directory
            (markdown-declared team — inherits this team's jinxes).

        Also scans an agents/ directory inside the team root for sub-teams
        (supports mixed markdown + npc_team style nesting).
        """
        candidates = []

        # Normal subdirectories of the team path
        for item in os.listdir(self.team_path):
            item_path = os.path.join(self.team_path, item)
            if os.path.isdir(item_path) and not item.startswith('.') and item != "jinxes":
                candidates.append((item, item_path))

        # Also scan agents/ for subdirectories that look like teams
        agents_dir = os.path.join(self.team_path, "agents")
        if os.path.isdir(agents_dir):
            for item in os.listdir(agents_dir):
                item_path = os.path.join(agents_dir, item)
                if os.path.isdir(item_path) and not item.startswith('.'):
                    candidates.append((item, item_path))

        for item, item_path in candidates:
            entries = os.listdir(item_path)
            has_npc = any(f.endswith(".npc") for f in entries
                          if os.path.isfile(os.path.join(item_path, f)))
            has_md_team = (
                any(f in ("agents.md", "AGENTS.md", "CLAUDE.md") for f in entries) or
                os.path.isdir(os.path.join(item_path, "agents"))
            )
            if has_npc or has_md_team:
                sub_team = Team(team_path=item_path, db_conn=self.db_conn, team_jinxes=self._raw_jinxes_list)
                self.sub_teams[item] = sub_team

    def _resolve_team_jinxes_spec(self):
        """Jinja-render the `jinxes:` field from the team .ctx file.

        The first pass of .ctx parsing runs before the Jinx()/NPC()/jinxes_list()
        macros exist, so jinxes: can't be resolved there. This second pass reads
        the .ctx again with the full npc_jinja_context and stores the resolved
        spec on self.team_jinxes_spec — a list of rendered strings (jinx names or
        relative paths) that every NPC on the team will pick up via
        initialize_jinxes.
        """
        self.team_jinxes_spec = []
        if not hasattr(self, 'team_path') or not self.team_path:
            return
        try:
            for fname in os.listdir(self.team_path):
                if not fname.endswith('.ctx'):
                    continue
                ctx_path = os.path.join(self.team_path, fname)
                rendered = load_yaml_file(ctx_path, jinja_context=self._npc_jinja_context)
                if isinstance(rendered, dict):
                    spec = rendered.get('jinxes', [])
                    if isinstance(spec, list):
                        self.team_jinxes_spec = [s for s in spec if s]
                return
        except Exception as e:
            print(f"Warning: failed to resolve team-level jinxes from .ctx: {e}")

    def _load_agents_from_md(self, path: str):
        """Load agents from an agents.md / AGENTS.md / CLAUDE.md file.

        Format:
            ## agent_name
            directive body text...

        Each H2 heading becomes an NPC with that name and the body as its directive.
        Agents loaded this way pick up the team's .ctx jinxes; if none are defined
        they fall back to DEFAULT_MD_AGENT_JINXES.
        """
        with open(path, 'r') as f:
            content = f.read()

        current_name = None
        current_body = []

        for line in content.split('\n'):
            if line.startswith('## '):
                if current_name:
                    self._register_or_prompt_agent(current_name, '\n'.join(current_body).strip(), path)
                current_name = line[3:].strip()
                current_body = []
            elif current_name is not None:
                current_body.append(line)

        if current_name:
            self._register_or_prompt_agent(current_name, '\n'.join(current_body).strip(), path)

    def _load_agents_from_dir(self, agents_dir: str):
        """Load agents from an agents/ directory.

        Each .md file defines an agent:
        - Filename (without extension) = agent name
        - File content = directive (optionally with YAML frontmatter for
          model/provider/name and a jinxes: or tools: list for per-agent tool spec)
        """
        for fname in os.listdir(agents_dir):
            if not fname.endswith('.md'):
                continue
            name = fname[:-3]  # strip .md
            if name in self.npcs:
                continue
            fpath = os.path.join(agents_dir, fname)
            with open(fpath, 'r') as f:
                content = f.read()

            # Check for YAML frontmatter
            model = self.model
            provider = self.provider
            jinxes_spec = None
            directive = content
            if content.startswith('---'):
                parts = content.split('---', 2)
                if len(parts) >= 3:
                    try:
                        fm = yaml.safe_load(parts[1])
                        if isinstance(fm, dict):
                            model = fm.get('model', model)
                            provider = fm.get('provider', provider)
                            name = fm.get('name', name)
                            # Accept either `jinxes:` (npcsh native) or `tools:`
                            # (Claude-Code / Agents-md convention).
                            fm_jinxes = fm.get('jinxes', fm.get('tools'))
                            if isinstance(fm_jinxes, list):
                                jinxes_spec = [str(s) for s in fm_jinxes if s]
                        directive = parts[2].strip()
                    except Exception:
                        directive = content

            self._register_md_agent(name, directive, model=model, provider=provider, jinxes_spec=jinxes_spec, source_path=fpath)

    def _register_or_prompt_agent(self, name: str, directive: str, source_path: str):
        """Register a markdown-declared agent, skipping names that collide with an
        existing .npc-declared NPC so curated definitions always win.

        ``source_path`` is accepted for logging/traceability; agents.md / AGENTS.md /
        CLAUDE.md all feed through here.
        """
        if not name or name in self.npcs:
            return
        self._register_md_agent(name, directive, source_path=source_path)

    def _register_md_agent(self, name: str, directive: str, model=None, provider=None, jinxes_spec=None, source_path: str = None):
        """Create an NPC from a markdown agent definition and add to team.

        Markdown agents don't have a strict .npc jinxes: spec. Resolution order:
          1. Explicit frontmatter `jinxes:`/`tools:` list, if provided.
          2. Team-level `jinxes:` from .ctx, if any.
          3. DEFAULT_MD_AGENT_JINXES fallback — a generic agent toolkit.
        Team-level jinxes are then additively merged on top in initialize_jinxes.
        """
        if jinxes_spec is None:
            if getattr(self, 'team_jinxes_spec', None):
                jinxes_spec = list(self.team_jinxes_spec)
            else:
                jinxes_spec = [
                    name for name in DEFAULT_MD_AGENT_JINXES
                    if name in self.jinxes_dict
                ]
        npc = NPC(
            name=name,
            primary_directive=directive,
            model=model or self.model,
            provider=provider or self.provider,
            jinxes=jinxes_spec,
            db_conn=self.db_conn,
        )
        npc.team = self
        if source_path:
            npc.source_path = source_path
        self.npcs[name] = npc
        # Markdown agents never get initialize_jinxes called via the .npc load path,
        # so call it here so their jinxes_dict is actually populated.
        try:
            npc.initialize_jinxes(team_raw_jinxes=self._raw_jinxes_list)
        except Exception as e:
            print(f"Warning: failed to initialize jinxes for markdown agent '{name}': {e}")

    def get_forenpc(self) -> Optional['NPC']:
        """
        Returns the forenpc (coordinator) for this team.
        This method is now primarily for external access, as self.forenpc is set in __init__.
        """
        return self.forenpc

    def get_npc(self, npc_ref: Union[str, 'NPC']) -> Optional['NPC']:
        """Get NPC by name or reference with hierarchical lookup capability"""
        if isinstance(npc_ref, NPC):
            return npc_ref
        elif isinstance(npc_ref, str):
            if npc_ref in self.npcs:
                return self.npcs[npc_ref]

            for sub_team_name, sub_team in self.sub_teams.items():
                if npc_ref in sub_team.npcs:
                    return sub_team.npcs[npc_ref]

                result = sub_team.get_npc(npc_ref)
                if result:
                    return result

            return None
        else:
            return None

    def orchestrate(self, request, max_iterations=3):
        """Orchestrate a request through the team"""
        import re
        from termcolor import colored

        forenpc = self.get_forenpc()
        if not forenpc:
            return {"error": "No forenpc available to coordinate the team"}

        print(colored(f"[orchestrate] Starting with forenpc={forenpc.name}, team={self.name}", "cyan"))
        print(colored(f"[orchestrate] Request: {request[:100]}...", "cyan"))

        jinxes_for_orchestration = {k: v for k, v in forenpc.jinxes_dict.items() if k != 'orchestrate'}

        try:
            result = forenpc.check_llm_command(
                request,
                context=getattr(self, 'context', {}),
                team=self,
                jinxes=jinxes_for_orchestration,
            )
            print(colored(f"[orchestrate] Initial result type={type(result)}", "cyan"))
            if isinstance(result, dict):
                print(colored(f"[orchestrate] Result keys={list(result.keys())}", "cyan"))
                if 'error' in result:
                    print(colored(f"[orchestrate] Error in result: {result['error']}", "red"))
                    return result
        except Exception as e:
            print(colored(f"[orchestrate] Exception in check_llm_command: {e}", "red"))
            return {"error": str(e), "output": f"Orchestration failed: {e}"}

        output = ""
        if isinstance(result, dict):
            output = result.get('output') or result.get('response') or ""

        print(colored(f"[orchestrate] Output preview: {output[:200] if output else 'EMPTY'}...", "cyan"))

        if output and self.npcs:
            at_pattern = r'@(\w+)'
            mentions = re.findall(at_pattern, output)

            if not mentions:
                for npc_name in self.npcs.keys():
                    if npc_name.lower() != forenpc.name.lower():
                        if npc_name.lower() in output.lower():
                            mentions.append(npc_name)
                            break

            print(colored(f"[orchestrate] Found mentions: {mentions}", "cyan"))

            for mentioned in mentions:
                mentioned_lower = mentioned.lower()
                if mentioned_lower in self.npcs and mentioned_lower != forenpc.name:
                    target_npc = self.npcs[mentioned_lower]
                    print(colored(f"[orchestrate] Delegating to @{mentioned_lower}", "yellow"))

                    try:
                        target_jinxes = {k: v for k, v in target_npc.jinxes_dict.items() if k != 'orchestrate'}
                        delegate_result = target_npc.check_llm_command(
                            request,
                            context=getattr(self, 'context', {}),
                            team=self,
                            jinxes=target_jinxes,
                        )

                        if isinstance(delegate_result, dict):
                            delegate_output = delegate_result.get('output') or delegate_result.get('response') or ""
                            if delegate_output:
                                output = f"[{mentioned_lower}]: {delegate_output}"
                                result = delegate_result
                                print(colored(f"[orchestrate] Got response from {mentioned_lower}", "green"))
                    except Exception as e:
                        print(colored(f"[orchestrate] Delegation to {mentioned_lower} failed: {e}", "red"))

                    break

        if isinstance(result, dict):
            final_output = output if output else str(result)
            return {
                "output": final_output,
                "result": result,
            }
        else:
            return {
                "output": str(result),
                "result": result,
            }

    def to_dict(self):
        """Convert team to dictionary representation"""
        return {
            "name": self.name,
            "npcs": {name: npc.to_dict() for name, npc in self.npcs.items()},
            "sub_teams": {name: team.to_dict() for name, team in self.sub_teams.items()},
            "jinxes": {name: jinx.to_dict() for name, jinx in self.jinxes_dict.items()},
            "context": getattr(self, 'context', {})
        }

    def save(self, directory=None):
        """Save team to directory"""
        if directory is None:
            directory = self.team_path

        if not directory:
            raise ValueError("No directory specified for saving team")

        ensure_dirs_exist(directory)

        if hasattr(self, 'context') and self.context:
            ctx_path = os.path.join(directory, "team.ctx")
            write_yaml_file(ctx_path, self.context)

        for npc in self.npcs.values():
            npc.save(directory)

        jinxes_dir = os.path.join(directory, "jinxes")
        ensure_dirs_exist(jinxes_dir)

        for jinx in self.jinxes_dict.values():
            jinx.save(jinxes_dir)

        for team_name, team in self.sub_teams.items():
            team_dir = os.path.join(directory, team_name)
            team.save(team_dir)

        return True
    def _parse_file_patterns(self, patterns_config):
        """Parse file patterns configuration and load matching files into KV cache"""
        if not patterns_config:
            return {}

        file_cache = {}

        for pattern_entry in patterns_config:
            if isinstance(pattern_entry, str):
                pattern_entry = {"pattern": pattern_entry}

            pattern = pattern_entry.get("pattern", "")
            recursive = pattern_entry.get("recursive", False)
            base_path = pattern_entry.get("base_path", ".")

            if not pattern:
                continue

            base_path = os.path.expanduser(base_path)
            if not os.path.isabs(base_path):
                base_path = os.path.join(self.team_path or os.getcwd(), base_path)

            matching_files = self._find_matching_files(pattern, base_path, recursive)

            for file_path in matching_files:
                file_content = self._load_file_content(file_path)
                if file_content:
                    relative_path = os.path.relpath(file_path, base_path)
                    file_cache[relative_path] = file_content

        return file_cache

    def _find_matching_files(self, pattern, base_path, recursive=False):
        """Find files matching the given pattern"""
        matching_files = []

        if not os.path.exists(base_path):
            return matching_files

        if recursive:
            for root, dirs, files in os.walk(base_path):
                for filename in files:
                    if fnmatch.fnmatch(filename, pattern):
                        matching_files.append(os.path.join(root, filename))
        else:
            try:
                for item in os.listdir(base_path):
                    item_path = os.path.join(base_path, item)
                    if os.path.isfile(item_path) and fnmatch.fnmatch(item, pattern):
                        matching_files.append(item_path)
            except PermissionError:
                print(f"Permission denied accessing {base_path}")

        return matching_files

    def _load_file_content(self, file_path):
        """Load content from a file with error handling"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return f.read()
        except Exception as e:
            print(f"Error reading {file_path}: {e}")
            return None

    def _format_parsed_files_context(self, parsed_files):
        """Format parsed files into context string"""
        if not parsed_files:
            return ""

        context_parts = ["Additional context from files:"]

        for file_path, content in parsed_files.items():
            context_parts.append(f"\n--- {file_path} ---")
            context_parts.append(content)
            context_parts.append("")

        return "\n".join(context_parts)

api_key = api_key instance-attribute

api_url = api_url instance-attribute

context = '' instance-attribute

databases = [] instance-attribute

db_conn = db_conn instance-attribute

external_jinx_teams = [] instance-attribute

forenpc = None instance-attribute

forenpc_name = None instance-attribute

jinja_env_for_first_pass = SandboxedEnvironment(undefined=SilentUndefined) instance-attribute

jinx_tool_catalog = build_jinx_tool_catalog(self.jinxes_dict) instance-attribute

jinxes_dict = {} instance-attribute

mcp_servers = [] instance-attribute

model = model instance-attribute

name = os.path.basename(os.path.abspath(team_path)) instance-attribute

npcs = {} instance-attribute

provider = provider instance-attribute

shared_context = {'intermediate_results': {}, 'dataframes': {}, 'memories': {}, 'execution_history': [], 'context': ''} instance-attribute

skills_directory = None instance-attribute

sub_teams = {} instance-attribute

team_path = os.path.expanduser(team_path) if team_path else None instance-attribute

get_forenpc()

Returns the forenpc (coordinator) for this team. This method is now primarily for external access, as self.forenpc is set in init.

Source code in npcpy/npc_compiler.py
def get_forenpc(self) -> Optional['NPC']:
    """
    Returns the forenpc (coordinator) for this team.
    This method is now primarily for external access, as self.forenpc is set in __init__.
    """
    return self.forenpc

get_npc(npc_ref)

Get NPC by name or reference with hierarchical lookup capability

Source code in npcpy/npc_compiler.py
def get_npc(self, npc_ref: Union[str, 'NPC']) -> Optional['NPC']:
    """Get NPC by name or reference with hierarchical lookup capability"""
    if isinstance(npc_ref, NPC):
        return npc_ref
    elif isinstance(npc_ref, str):
        if npc_ref in self.npcs:
            return self.npcs[npc_ref]

        for sub_team_name, sub_team in self.sub_teams.items():
            if npc_ref in sub_team.npcs:
                return sub_team.npcs[npc_ref]

            result = sub_team.get_npc(npc_ref)
            if result:
                return result

        return None
    else:
        return None

orchestrate(request, max_iterations=3)

Orchestrate a request through the team

Source code in npcpy/npc_compiler.py
def orchestrate(self, request, max_iterations=3):
    """Orchestrate a request through the team"""
    import re
    from termcolor import colored

    forenpc = self.get_forenpc()
    if not forenpc:
        return {"error": "No forenpc available to coordinate the team"}

    print(colored(f"[orchestrate] Starting with forenpc={forenpc.name}, team={self.name}", "cyan"))
    print(colored(f"[orchestrate] Request: {request[:100]}...", "cyan"))

    jinxes_for_orchestration = {k: v for k, v in forenpc.jinxes_dict.items() if k != 'orchestrate'}

    try:
        result = forenpc.check_llm_command(
            request,
            context=getattr(self, 'context', {}),
            team=self,
            jinxes=jinxes_for_orchestration,
        )
        print(colored(f"[orchestrate] Initial result type={type(result)}", "cyan"))
        if isinstance(result, dict):
            print(colored(f"[orchestrate] Result keys={list(result.keys())}", "cyan"))
            if 'error' in result:
                print(colored(f"[orchestrate] Error in result: {result['error']}", "red"))
                return result
    except Exception as e:
        print(colored(f"[orchestrate] Exception in check_llm_command: {e}", "red"))
        return {"error": str(e), "output": f"Orchestration failed: {e}"}

    output = ""
    if isinstance(result, dict):
        output = result.get('output') or result.get('response') or ""

    print(colored(f"[orchestrate] Output preview: {output[:200] if output else 'EMPTY'}...", "cyan"))

    if output and self.npcs:
        at_pattern = r'@(\w+)'
        mentions = re.findall(at_pattern, output)

        if not mentions:
            for npc_name in self.npcs.keys():
                if npc_name.lower() != forenpc.name.lower():
                    if npc_name.lower() in output.lower():
                        mentions.append(npc_name)
                        break

        print(colored(f"[orchestrate] Found mentions: {mentions}", "cyan"))

        for mentioned in mentions:
            mentioned_lower = mentioned.lower()
            if mentioned_lower in self.npcs and mentioned_lower != forenpc.name:
                target_npc = self.npcs[mentioned_lower]
                print(colored(f"[orchestrate] Delegating to @{mentioned_lower}", "yellow"))

                try:
                    target_jinxes = {k: v for k, v in target_npc.jinxes_dict.items() if k != 'orchestrate'}
                    delegate_result = target_npc.check_llm_command(
                        request,
                        context=getattr(self, 'context', {}),
                        team=self,
                        jinxes=target_jinxes,
                    )

                    if isinstance(delegate_result, dict):
                        delegate_output = delegate_result.get('output') or delegate_result.get('response') or ""
                        if delegate_output:
                            output = f"[{mentioned_lower}]: {delegate_output}"
                            result = delegate_result
                            print(colored(f"[orchestrate] Got response from {mentioned_lower}", "green"))
                except Exception as e:
                    print(colored(f"[orchestrate] Delegation to {mentioned_lower} failed: {e}", "red"))

                break

    if isinstance(result, dict):
        final_output = output if output else str(result)
        return {
            "output": final_output,
            "result": result,
        }
    else:
        return {
            "output": str(result),
            "result": result,
        }

save(directory=None)

Save team to directory

Source code in npcpy/npc_compiler.py
def save(self, directory=None):
    """Save team to directory"""
    if directory is None:
        directory = self.team_path

    if not directory:
        raise ValueError("No directory specified for saving team")

    ensure_dirs_exist(directory)

    if hasattr(self, 'context') and self.context:
        ctx_path = os.path.join(directory, "team.ctx")
        write_yaml_file(ctx_path, self.context)

    for npc in self.npcs.values():
        npc.save(directory)

    jinxes_dir = os.path.join(directory, "jinxes")
    ensure_dirs_exist(jinxes_dir)

    for jinx in self.jinxes_dict.values():
        jinx.save(jinxes_dir)

    for team_name, team in self.sub_teams.items():
        team_dir = os.path.join(directory, team_name)
        team.save(team_dir)

    return True

to_dict()

Convert team to dictionary representation

Source code in npcpy/npc_compiler.py
def to_dict(self):
    """Convert team to dictionary representation"""
    return {
        "name": self.name,
        "npcs": {name: npc.to_dict() for name, npc in self.npcs.items()},
        "sub_teams": {name: team.to_dict() for name, team in self.sub_teams.items()},
        "jinxes": {name: jinx.to_dict() for name, jinx in self.jinxes_dict.items()},
        "context": getattr(self, 'context', {})
    }

update_context(messages)

Update team context based on recent conversation patterns

Source code in npcpy/npc_compiler.py
def update_context(self, messages: list):
    """Update team context based on recent conversation patterns"""
    if len(messages) < 10:
        return

    summary = breathe(
        messages=messages[-10:], 
        npc=self.forenpc
    )
    characterization = summary.get('output')

    if characterization:
        team_ctx_path = os.path.join(self.team_path, "team.ctx")

        if os.path.exists(team_ctx_path):
            with open(team_ctx_path, 'r', encoding="utf-8") as f:
                ctx_data = yaml.safe_load(f) or {}
        else:
            ctx_data = {}

        current_context = ctx_data.get('context', '')

        prompt = f"""Based on this characterization: {characterization},
        suggest changes to the team's context.
        Current Context: "{current_context}".
        Respond with JSON: {{"suggestion": "Your sentence."}}"""

        response = get_llm_response(
            prompt=prompt,
            npc=self.forenpc,
            format="json"
        )
        suggestion = response.get("response", {}).get("suggestion")

        if suggestion:
            new_context = (current_context + " " + suggestion).strip()
            user_approval = input(f"Update context to: {new_context}? [y/N]: ").strip().lower()
            if user_approval == 'y':
                ctx_data['context'] = new_context
                self.context = new_context
                with open(team_ctx_path, 'w', encoding="utf-8") as f:
                    yaml.dump(ctx_data, f)

ToolAgent

Bases: Agent

Agent with user-provided tool functions and/or MCP servers.

Source code in npcpy/npc_compiler.py
class ToolAgent(Agent):
    """Agent with user-provided tool functions and/or MCP servers."""

    def __init__(
        self,
        name: str = "tool_agent",
        primary_directive: str = "You are an AI agent with specialized tools.",
        tools: list = None,
        mcp_servers: list = None,
        include_defaults: bool = True,
        model: str = None,
        provider: str = None,
        **kwargs,
    ):
        all_tools = []
        if include_defaults:
            all_tools.extend(_DEFAULT_AGENT_TOOLS)
        if tools:
            all_tools.extend(tools)

        super().__init__(
            name=name,
            primary_directive=primary_directive,
            model=model,
            provider=provider,
            tools=all_tools,
            mcp_servers=mcp_servers,
            **kwargs,
        )

_compile_skill_to_jinx(skill_data, source_path=None)

Compile skill data into a Jinx whose step is engine: skill.

Everything about the skill — name, description, sections, scripts, references, assets — is passed as structured data into skill.jinx. The sub-jinx owns the full representation; the compiler just parses the source format and hands it off.

Sections content is base64-encoded to survive the two-pass Jinja pipeline without mangling. Metadata lists (scripts, references, assets) are passed as JSON strings.

Source code in npcpy/npc_compiler.py
def _compile_skill_to_jinx(skill_data, source_path=None):
    """Compile skill data into a Jinx whose step is ``engine: skill``.

    Everything about the skill — name, description, sections, scripts,
    references, assets — is passed as structured data into ``skill.jinx``.
    The sub-jinx owns the full representation; the compiler just parses the
    source format and hands it off.

    Sections content is base64-encoded to survive the two-pass Jinja pipeline
    without mangling.  Metadata lists (scripts, references, assets) are passed
    as JSON strings.
    """
    name = skill_data.get('jinx_name', skill_data.get('name', ''))
    description = skill_data.get('description', '')
    sections = skill_data.get('sections', {})

    sections_json = json.dumps(sections, ensure_ascii=False)
    content_b64 = base64.b64encode(sections_json.encode('utf-8')).decode('ascii')

    section_names = list(sections.keys())
    desc_suffix = f" [Sections: {', '.join(section_names)}]" if section_names else ""

    scripts_list = []
    references_list = []
    assets_list = []

    file_context = list(skill_data.get('file_context', []))
    for subdir, collector in (('scripts', scripts_list),
                               ('references', references_list),
                               ('assets', assets_list)):
        entries = skill_data.get(subdir)
        if isinstance(entries, list):
            collector.extend(entries)
            for entry in entries:
                if isinstance(entry, str):
                    file_context.append({
                        'pattern': entry,
                        'base_path': os.path.join('.', subdir) if source_path else '.',
                    })
                elif isinstance(entry, dict):
                    file_context.append(entry)
        elif entries is None and source_path:
            skill_dir = os.path.dirname(source_path)
            subdir_path = os.path.join(skill_dir, subdir)
            if os.path.isdir(subdir_path):
                for r, _d, fnames in os.walk(subdir_path):
                    for fn in fnames:
                        rel = os.path.relpath(os.path.join(r, fn), skill_dir)
                        collector.append(rel)
                file_context.append({
                    'pattern': '*',
                    'base_path': subdir,
                    'recursive': True,
                })

    jinx_data = {
        'jinx_name': name,
        'description': (description + desc_suffix) if description else f"Skill: {name}{desc_suffix}",
        'inputs': [{'section': 'all'}],
        'steps': [{
            'engine': 'skill',
            'skill_name': name,
            'skill_description': description,
            'sections': content_b64,
            'scripts_json': json.dumps(scripts_list),
            'references_json': json.dumps(references_list),
            'assets_json': json.dumps(assets_list),
            'section': '{{section}}'
        }],
        'file_context': file_context,
        '_source_path': source_path
    }

    return Jinx(jinx_data=jinx_data)

_is_cli_provider(provider)

Check if provider is a CLI-based agent.

Source code in npcpy/npc_compiler.py
def _is_cli_provider(provider: str) -> bool:
    """Check if provider is a CLI-based agent."""
    return provider in ("claude_code", "claude", "opencode", "kimi_code", "kimi", "kilo_code", "kilo", "gemini", "codex", "nanocoder", "aider", "amp")

_json_dumps_with_undefined(obj, **kwargs)

Custom JSON dumps that handles SilentUndefined objects

Source code in npcpy/npc_compiler.py
def _json_dumps_with_undefined(obj, **kwargs):
    """Custom JSON dumps that handles SilentUndefined objects"""
    def default_handler(o):
        if isinstance(o, Undefined):
            return ""
        raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
    return json.dumps(obj, default=default_handler, **kwargs)

_load_skill_from_md(path)

Load a skill from a SKILL.md file with YAML frontmatter and ## sections.

The skill name defaults to the parent folder name (matching the Anthropic skill-folder convention), falling back to the frontmatter name field.

Sibling directories (scripts/, references/, assets/) are auto-discovered and attached as file_context.

Source code in npcpy/npc_compiler.py
def _load_skill_from_md(path):
    """Load a skill from a SKILL.md file with YAML frontmatter and ## sections.

    The skill name defaults to the parent folder name (matching the Anthropic
    skill-folder convention), falling back to the frontmatter ``name`` field.

    Sibling directories (``scripts/``, ``references/``, ``assets/``) are
    auto-discovered and attached as ``file_context``.
    """
    parsed = _parse_skill_md(path)
    if not parsed or not parsed.get('sections'):
        return None

    parent_dir = os.path.basename(os.path.dirname(path))
    name = parsed['name'] or parent_dir

    skill_data = {
        'jinx_name': name,
        'description': parsed['description'],
        'sections': parsed['sections'],
    }

    fm = parsed.get('frontmatter', {})
    for key in ('scripts', 'references', 'assets', 'file_context'):
        if key in fm:
            skill_data[key] = fm[key]

    return _compile_skill_to_jinx(skill_data, source_path=path)

_parse_skill_md(path)

Parse a skill markdown file with YAML frontmatter and ## sections.

Expected format

name: skill-name description: What it does. Use when ...


Skill Title

section-one

Content for section one...

section-two

Content for section two...

Returns dict with name, description, sections, frontmatter or None on failure.

Source code in npcpy/npc_compiler.py
def _parse_skill_md(path):
    """Parse a skill markdown file with YAML frontmatter and ## sections.

    Expected format:
        ---
        name: skill-name
        description: What it does. Use when ...
        ---
        # Skill Title

        ## section-one
        Content for section one...

        ## section-two
        Content for section two...

    Returns dict with name, description, sections, frontmatter or None on failure.
    """
    with open(path, 'r', encoding='utf-8') as f:
        content = f.read()

    if not content.startswith('---'):
        return None

    parts = content.split('---', 2)
    if len(parts) < 3:
        return None

    frontmatter = yaml.safe_load(parts[1])
    if not frontmatter or not isinstance(frontmatter, dict):
        return None

    body = parts[2].strip()

    sections = {}
    current_section = None
    current_content = []

    for line in body.split('\n'):
        if line.startswith('## '):
            if current_section:
                sections[current_section] = '\n'.join(current_content).strip()
            current_section = line[3:].strip()
            current_content = []
        elif current_section is not None:
            current_content.append(line)

    if current_section:
        sections[current_section] = '\n'.join(current_content).strip()

    basename = os.path.splitext(os.path.basename(path))[0]
    if basename.upper() == 'SKILL':
        default_name = os.path.basename(os.path.dirname(path))
    else:
        default_name = basename

    return {
        'name': frontmatter.get('name', default_name),
        'description': frontmatter.get('description', ''),
        'sections': sections,
        'frontmatter': frontmatter
    }

_tool_chat(message)

Respond directly to the user without taking any action.

Parameters:
  • message (str) –

    The message to send.

Source code in npcpy/npc_compiler.py
def _tool_chat(message: str) -> str:
    """Respond directly to the user without taking any action.

    Args:
        message: The message to send.
    """
    return message

_tool_edit_file(path, action='create', new_text='', old_text='')

Edit a file. Actions: create/write, append, replace.

Parameters:
  • path (str) –

    File path to edit.

  • action (str, default: 'create' ) –

    One of 'create', 'write', 'append', 'replace'.

  • new_text (str, default: '' ) –

    Text to write/append, or replacement text.

  • old_text (str, default: '' ) –

    Text to find (for replace action).

Source code in npcpy/npc_compiler.py
def _tool_edit_file(path: str, action: str = "create", new_text: str = "", old_text: str = "") -> str:
    """Edit a file. Actions: create/write, append, replace.

    Args:
        path: File path to edit.
        action: One of 'create', 'write', 'append', 'replace'.
        new_text: Text to write/append, or replacement text.
        old_text: Text to find (for replace action).
    """
    path = os.path.expanduser(path)
    try:
        if action in ("create", "write"):
            os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
            with open(path, "w") as f:
                f.write(new_text)
            return f"Created/wrote {path} ({len(new_text)} bytes)"
        elif action == "append":
            with open(path, "a") as f:
                f.write(new_text)
            return f"Appended to {path}"
        elif action == "replace":
            with open(path, "r") as f:
                content = f.read()
            updated = content.replace(old_text, new_text)
            with open(path, "w") as f:
                f.write(updated)
            return f"Replaced text in {path}"
        else:
            return f"Unknown action: {action}"
    except Exception as e:
        return f"Error: {e}"

Search for files containing a query string.

Parameters:
  • query (str) –

    Text pattern to search for.

  • path (str, default: '.' ) –

    Directory to search in.

Source code in npcpy/npc_compiler.py
def _tool_file_search(query: str, path: str = ".") -> str:
    """Search for files containing a query string.

    Args:
        query: Text pattern to search for.
        path: Directory to search in.
    """
    path = os.path.expanduser(path)
    try:
        result = subprocess.run(
            ["grep", "-rn",
             "--include=*.py", "--include=*.rs", "--include=*.js", "--include=*.ts",
             "--include=*.md", "--include=*.txt", "--include=*.yaml", "--include=*.yml",
             "--include=*.toml", "--include=*.json", "--include=*.sh",
             "-l", query, path],
            capture_output=True, text=True, timeout=30)
        output = "\n".join(result.stdout.splitlines()[:20])
        return output or f"No files found matching '{query}' in {path}"
    except Exception as e:
        return f"Search error: {e}"

_tool_load_file(path)

Read and return the contents of a file.

Parameters:
  • path (str) –

    File path to read.

Source code in npcpy/npc_compiler.py
def _tool_load_file(path: str) -> str:
    """Read and return the contents of a file.

    Args:
        path: File path to read.
    """
    path = os.path.expanduser(path)
    try:
        with open(path, "r") as f:
            content = f.read()
        lines = content.count("\n") + 1
        if len(content) > 10000:
            return f"File: {path} ({lines} lines, {len(content)} bytes)\n---\n{content[:10000]}...\n[truncated]"
        return f"File: {path} ({lines} lines, {len(content)} bytes)\n---\n{content}"
    except Exception as e:
        return f"Error reading {path}: {e}"

_tool_python(code)

Execute Python code and return stdout+stderr.

Source code in npcpy/npc_compiler.py
def _tool_python(code: str) -> str:
    """Execute Python code and return stdout+stderr."""
    try:
        result = subprocess.run(
            ["python3", "-c", code], capture_output=True, text=True, timeout=120
        )
        out = result.stdout
        if result.returncode != 0 and result.stderr:
            out += f"\nSTDERR:\n{result.stderr}"
        return out or "(no output)"
    except subprocess.TimeoutExpired:
        return "Code execution timed out after 120s"
    except Exception as e:
        return f"Error: {e}"

_tool_sh(bash_command)

Execute a bash/shell command and return stdout+stderr.

Source code in npcpy/npc_compiler.py
def _tool_sh(bash_command: str) -> str:
    """Execute a bash/shell command and return stdout+stderr."""
    try:
        result = subprocess.run(
            bash_command, shell=True, capture_output=True, text=True, timeout=120
        )
        out = result.stdout
        if result.returncode != 0 and result.stderr:
            out += f"\nSTDERR:\n{result.stderr}"
        return out or "(no output)"
    except subprocess.TimeoutExpired:
        return "Command timed out after 120s"
    except Exception as e:
        return f"Error: {e}"

_tool_stop(reason='')

Signal that the task is complete.

Parameters:
  • reason (str, default: '' ) –

    Optional reason for stopping.

Source code in npcpy/npc_compiler.py
def _tool_stop(reason: str = "") -> str:
    """Signal that the task is complete.

    Args:
        reason: Optional reason for stopping.
    """
    return f"STOP: {reason}" if reason else "STOP"

Search the web using DuckDuckGo and return results.

Parameters:
  • query (str) –

    Search query string.

Source code in npcpy/npc_compiler.py
def _tool_web_search(query: str) -> str:
    """Search the web using DuckDuckGo and return results.

    Args:
        query: Search query string.
    """
    try:
        from npcpy.data.web import search_web
        results = search_web(query)
        if isinstance(results, list):
            return "\n".join(str(r) for r in results[:5])
        return str(results)
    except ImportError:
        url = f"https://lite.duckduckgo.com/lite/?q={urllib.parse.quote_plus(query)}"
        try:
            result = subprocess.run(["curl", "-sL", url], capture_output=True, text=True, timeout=15)
            output = "\n".join(result.stdout.splitlines()[:100])
            return output or "No results"
        except Exception as e:
            return f"Search failed: {e}"

agent_pass_handler(command, extracted_data, **kwargs)

Handler for agent pass action

Source code in npcpy/npc_compiler.py
def agent_pass_handler(command, extracted_data, **kwargs):
    """Handler for agent pass action"""
    npc = kwargs.get('npc')
    team = kwargs.get('team')    
    if not team and npc and hasattr(npc, '_current_team'):
        team = npc._current_team


    if not npc or not team:
        return {"messages": kwargs.get('messages', []), "output": f"Error: No NPC ({npc.name if npc else 'None'}) or team ({team.name if team else 'None'}) available for agent pass"}

    target_npc_name = extracted_data.get('target_npc')
    if not target_npc_name:
        return {"messages": kwargs.get('messages', []), "output": "Error: No target NPC specified"}

    messages = kwargs.get('messages', [])


    pass_count = 0
    recent_passes = []

    for msg in messages[-10:]:  
        if 'NOTE: THIS COMMAND HAS BEEN PASSED FROM' in msg.get('content', ''):
            pass_count += 1

            if 'PASSED FROM' in msg.get('content', ''):
                content = msg.get('content', '')
                if 'PASSED FROM' in content and 'TO YOU' in content:
                    parts = content.split('PASSED FROM')[1].split('TO YOU')[0].strip()
                    recent_passes.append(parts)



    target_npc = team.get_npc(target_npc_name)
    if not target_npc:
        available_npcs = list(team.npcs.keys()) if hasattr(team, 'npcs') else []
        return {"messages": kwargs.get('messages', []), 
                "output": f"Error: NPC '{target_npc_name}' not found in team. Available: {available_npcs}"}



    result = npc.handle_agent_pass(
        target_npc,
        command,
        messages=kwargs.get('messages'),
        context=kwargs.get('context'),
        shared_context=getattr(team, 'shared_context', None),
        stream=kwargs.get('stream', False),
        team=team
    )

    return result

auto_tools(functions)

Automatically create both tool schema and tool map from functions.

Parameters:
  • functions (List[Callable]) –

    List of Python functions to convert to tools

Returns:
  • tuple[List[Dict[str, Any]], Dict[str, Callable]]

    Tuple of (tools_schema, tool_map)

Example
def get_weather(location: str) -> str:
    '''Get weather information for a location'''
    return f"The weather in {location} is sunny and 75°F"

def calculate_math(expression: str) -> str:
    '''Calculate a mathematical expression'''
    try:
        result = eval(expression)
        return f"The result of {expression} is {result}"
    except Exception:
        return "Invalid mathematical expression"


tools_schema, tool_map = auto_tools([get_weather, calculate_math])


response = get_llm_response(
    "What's the weather in Paris and what's 15 * 23?",
    model='gpt-4o-mini',
    provider='openai',
    tools=tools_schema,
    tool_map=tool_map
)
Source code in npcpy/tools.py
def auto_tools(functions: List[Callable]) -> tuple[List[Dict[str, Any]], Dict[str, Callable]]:
    """
    Automatically create both tool schema and tool map from functions.

    Args:
        functions: List of Python functions to convert to tools

    Returns:
        Tuple of (tools_schema, tool_map)

    Example:
        ```python
        def get_weather(location: str) -> str:
            '''Get weather information for a location'''
            return f"The weather in {location} is sunny and 75°F"

        def calculate_math(expression: str) -> str:
            '''Calculate a mathematical expression'''
            try:
                result = eval(expression)
                return f"The result of {expression} is {result}"
            except Exception:
                return "Invalid mathematical expression"


        tools_schema, tool_map = auto_tools([get_weather, calculate_math])


        response = get_llm_response(
            "What's the weather in Paris and what's 15 * 23?",
            model='gpt-4o-mini',
            provider='openai',
            tools=tools_schema,
            tool_map=tool_map
        )
        ```
    """
    schema = create_tool_schema(functions)
    tool_map = create_tool_map(functions)
    return schema, tool_map

breathe(messages, model=None, provider=None, npc=None, context=None, **kwargs)

Condense the conversation context into a small set of key extractions.

Source code in npcpy/llm_funcs.py
def breathe(
    messages: List[Dict[str, str]],
    model: str = None,
    provider: str = None, 
    npc =  None,
    context: str = None,
    **kwargs: Any
) -> Dict[str, Any]:
    """Condense the conversation context into a small set of key extractions."""
    if not messages:
        return {"output": {}, "messages": []}

    if 'stream' in kwargs:
        kwargs['stream'] = False
    conversation_text = "\n".join([f"{m['role']}: {m['content']}" for m in messages])

    prompt = f'''
    Read the following conversation:

    {conversation_text}

    ''' +'''

    Now identify the following items:

    1. The high level objective
    2. The most recent task
    3. The accomplishments thus far
    4. The failures thus far

    Return a JSON like so:

    {
        "high_level_objective": "the overall goal so far for the user", 
        "most_recent_task": "The currently ongoing task", 
        "accomplishments": ["accomplishment1", "accomplishment2"], 
        "failures": ["falures1", "failures2"], 
    }

    '''


    result = get_llm_response(prompt, 
                           model=model, 
                           provider=provider, 
                           npc=npc, 
                           context=context, 
                           format='json', 
                           **kwargs)

    res = result.get('response', {})
    if isinstance(res, str):
        raise Exception
    format_output = f"""Here is a summary of the previous session. 
    The high level objective was: {res.get('high_level_objective')} \n The accomplishments were: {res.get('accomplishments')}, 
    the failures were: {res.get('failures')} and the most recent task was: {res.get('most_recent_task')}   """
    return {'output': format_output,
            'summary': res,
            'messages': [
                         {
                           'content': format_output,
                           'role': 'assistant'}
                           ]
                          }

build_jinx_tool_catalog(jinxes)

Helper to build a name->tool_def catalog from a dict of Jinx objects.

Source code in npcpy/npc_compiler.py
def build_jinx_tool_catalog(jinxes: Dict[str, 'Jinx']) -> Dict[str, Dict[str, Any]]:
    """Helper to build a name->tool_def catalog from a dict of Jinx objects."""
    return {name: jinx_to_tool_def(jinx_obj) for name, jinx_obj in jinxes.items()}

create_or_replace_table(db_path, table_name, data)

Creates or replaces a table in the SQLite database

Source code in npcpy/npc_compiler.py
def create_or_replace_table(db_path, table_name, data):
    """Creates or replaces a table in the SQLite database"""
    conn = sqlite3.connect(os.path.expanduser(db_path))
    try:
        data.to_sql(table_name, conn, if_exists="replace", index=False)
        print(f"Table '{table_name}' created/replaced successfully.")
        return True
    except Exception as e:
        print(f"Error creating/replacing table '{table_name}': {e}")
        return False
    finally:
        conn.close()

ensure_dirs_exist(*dirs)

Ensure all specified directories exist

Source code in npcpy/npc_sysenv.py
def ensure_dirs_exist(*dirs):
    """Ensure all specified directories exist"""
    for dir_path in dirs:
        os.makedirs(os.path.expanduser(dir_path), exist_ok=True)

ensure_shebang(file_path, shebang=None)

Add a shebang to a .npc/.jinx file so it can run as an executable.

Returns the file path.

Source code in npcpy/npc_compiler.py
def ensure_shebang(file_path: str, shebang: str = None) -> str:
    """Add a shebang to a .npc/.jinx file so it can run as an executable.

    Returns the file path.
    """
    if shebang is None:
        if file_path.endswith('.npc'):
            shebang = NPC_SHEBANG
        elif file_path.endswith('.jinx'):
            shebang = JINX_SHEBANG
        else:
            return file_path

    with open(file_path, 'r') as f:
        content = f.read()

    if content.startswith('#!'):
        return file_path

    with open(file_path, 'w') as f:
        f.write(shebang + '\n' + content)

    current = os.stat(file_path).st_mode
    os.chmod(file_path, current | 0o111)
    return file_path

extract_jinx_inputs(args, jinx)

Source code in npcpy/npc_compiler.py
def extract_jinx_inputs(args: List[str], jinx: Jinx) -> Dict[str, Any]:
    inputs = {}

    flag_mapping = {}
    for input_ in jinx.inputs:
        if isinstance(input_, str):
            flag_mapping[f"-{input_[0]}"] = input_
            flag_mapping[f"--{input_}"] = input_
        elif isinstance(input_, dict):
            key = list(input_.keys())[0]
            flag_mapping[f"-{key[0]}"] = key
            flag_mapping[f"--{key}"] = key

    if len(jinx.inputs) > 1:
        used_args = set()
        for i, arg in enumerate(args):
            if '=' in arg and arg != '=' and not arg.startswith('-'):
                key, value = arg.split('=', 1)
                key = key.strip().strip("'\"")
                value = value.strip().strip("'\"")
                inputs[key] = value
                used_args.add(i)
    else:
        used_args = set()

    for i, arg in enumerate(args):
        if i in used_args:
            continue

        if arg in flag_mapping:
            if i + 1 < len(args) and not args[i + 1].startswith('-'):
                input_name = flag_mapping[arg]
                inputs[input_name] = args[i + 1]
                used_args.add(i)
                used_args.add(i + 1)
            else:
                input_name = flag_mapping[arg]
                inputs[input_name] = True
                used_args.add(i)

    unused_args = [arg for i, arg in enumerate(args) if i not in used_args]

    first_required = None
    for input_ in jinx.inputs:
        if isinstance(input_, str):
            first_required = input_
            break

    if first_required and unused_args:
        inputs[first_required] = ' '.join(unused_args).strip()
    else:
        jinx_input_names = []
        for input_ in jinx.inputs:
            if isinstance(input_, str):
                jinx_input_names.append(input_)
            elif isinstance(input_, dict):
                jinx_input_names.append(list(input_.keys())[0])

        if len(jinx_input_names) == 1 and unused_args:
            inputs[jinx_input_names[0]] = ' '.join(unused_args).strip()
        else:
            for i, arg in enumerate(unused_args):
                if i < len(jinx_input_names):
                    input_name = jinx_input_names[i]
                    if input_name not in inputs: 
                        inputs[input_name] = arg

    for input_ in jinx.inputs:
        if isinstance(input_, str):
            if input_ not in inputs:
                raise ValueError(f"Missing required input: {input_}")
        elif isinstance(input_, dict):
            key = list(input_.keys())[0]
            default_value = input_[key]
            if key not in inputs:
                inputs[key] = default_value

    return inputs

find_file_path(filename, search_dirs, suffix=None)

Find a file in multiple directories

Source code in npcpy/npc_compiler.py
def find_file_path(filename, search_dirs, suffix=None):
    """Find a file in multiple directories"""
    if suffix and not filename.endswith(suffix):
        filename += suffix

    for dir_path in search_dirs:
        file_path = os.path.join(os.path.expanduser(dir_path), filename)
        if os.path.exists(file_path):
            return file_path

    return None

get_llm_response(prompt, model=None, provider=None, images=None, npc=None, team=None, messages=None, api_url=None, api_key=None, context=None, stream=False, attachments=None, include_usage=False, n_samples=1, matrix=None, **kwargs)

Generate a response using the specified provider and model.

Source code in npcpy/llm_funcs.py
def get_llm_response(
    prompt: str,
    model: str = None,
    provider: str = None,
    images: List[str] = None,
    npc: Any = None,
    team: Any = None,
    messages: List[Dict[str, str]] = None,
    api_url: str = None,
    api_key: str = None,
    context=None,
    stream: bool = False,
    attachments: List[str] = None,
    include_usage: bool = False,
    n_samples: int = 1,
    matrix: Optional[Dict[str, List[Any]]] = None,
    **kwargs,
):
    """Generate a response using the specified provider and model."""
    logger.debug(
        f"[get_llm_response] {len(messages) if messages else 0} messages, "
        f"prompt_len={len(prompt) if prompt else 0}, "
        f"context={'yes' if context else 'no'}"
    )

    base_model, base_provider, base_api_url, base_api_key = resolve_model_provider(
        npc=npc, team=team, model=model, provider=provider,
        api_url=api_url, api_key=api_key, images=images, attachments=attachments,
    )
    if api_key is None:
        api_key = base_api_key

    use_matrix = matrix is not None and len(matrix) > 0
    multi_sample = n_samples and n_samples > 1

    if not use_matrix and not multi_sample:
        # Simple single-call path
        run_model, run_provider, run_api_url, run_api_key = resolve_model_provider(
            npc=npc, team=team, model=base_model, provider=base_provider,
            api_url=api_url, api_key=api_key, images=images, attachments=attachments,
        )
        tool_capable = bool(kwargs.get("tools"))
        system_message = get_system_message(npc, team, tool_capable=tool_capable) if npc is not None else "You are a helpful assistant."

        # Build messages
        run_messages = copy.deepcopy(messages) if messages else []
        if not run_messages:
            run_messages = [{"role": "system", "content": system_message}]

        # Build full text from prompt and/or context
        full_text = ""
        if prompt and context:
            full_text = f"{prompt}\n\n\nUser Provided Context: {context}"
        elif prompt:
            full_text = prompt
        elif context:
            full_text = f"User Provided Context: {context}"

        if full_text:
            if run_messages[-1]["role"] == "user" and isinstance(run_messages[-1]["content"], str):
                run_messages[-1]["content"] += "\n" + full_text
            else:
                run_messages.append({"role": "user", "content": full_text})

        if not run_model:
            raise ValueError("No model specified. Please set a model in your NPC configuration or team settings.")
        return get_litellm_response(
            full_text or None,
            messages=run_messages,
            model=run_model,
            provider=run_provider,
            api_url=run_api_url,
            api_key=api_key,
            images=images,
            attachments=attachments,
            stream=stream,
            include_usage=include_usage,
            **kwargs,
        )

    # Matrix / multi-sample path
    combos = []
    if use_matrix:
        keys = list(matrix.keys())
        values = []
        for key in keys:
            val = matrix[key]
            if isinstance(val, (list, tuple, set)):
                values.append(list(val))
            else:
                values.append([val])
        for combo_values in itertools.product(*values):
            combos.append(dict(zip(keys, combo_values)))
    else:
        combos.append({})

    runs = []
    for combo in combos:
        run_npc = combo.get("npc", npc)
        run_team = combo.get("team", team)
        run_context = combo.get("context", context)
        extra_kwargs = dict(kwargs)
        for k, v in combo.items():
            if k not in {"model", "provider", "npc", "context", "team"}:
                extra_kwargs[k] = v

        run_model, run_provider, run_api_url, run_api_key = resolve_model_provider(
            npc=run_npc, team=run_team,
            model=combo.get("model", base_model),
            provider=combo.get("provider", base_provider),
            api_url=api_url, api_key=api_key, images=images, attachments=attachments,
        )

        tool_capable = bool(extra_kwargs.get("tools"))
        system_message = get_system_message(run_npc, run_team, tool_capable=tool_capable) if run_npc is not None else "You are a helpful assistant."

        run_messages = copy.deepcopy(messages) if messages else []
        if not run_messages:
            run_messages = [{"role": "system", "content": system_message}]

        full_text = ""
        if prompt and run_context:
            full_text = f"{prompt}\n\n\nUser Provided Context: {run_context}"
        elif prompt:
            full_text = prompt
        elif run_context:
            full_text = f"User Provided Context: {run_context}"

        if full_text:
            if run_messages[-1]["role"] == "user" and isinstance(run_messages[-1]["content"], str):
                run_messages[-1]["content"] += "\n" + full_text
            else:
                run_messages.append({"role": "user", "content": full_text})

        for sample_idx in range(max(1, n_samples or 1)):
            resp = get_litellm_response(
                full_text or None,
                messages=run_messages,
                model=run_model,
                provider=run_provider,
                api_url=run_api_url,
                api_key=api_key,
                images=images,
                attachments=attachments,
                stream=stream,
                include_usage=include_usage,
                **extra_kwargs,
            )
            runs.append({
                "response": resp.get("response") if isinstance(resp, dict) else resp,
                "raw": resp,
                "combo": combo,
                "sample_index": sample_idx,
            })

    aggregated = {
        "response": runs[0]["response"] if runs else None,
        "runs": runs,
    }
    if runs and isinstance(runs[0]["raw"], dict) and "messages" in runs[0]["raw"]:
        aggregated["messages"] = runs[0]["raw"].get("messages")
    return aggregated

get_log_entries(entity_id, entry_type=None, limit=10, db_path='~/npcsh_history.db')

Get log entries for an NPC or team

Source code in npcpy/npc_compiler.py
def get_log_entries(entity_id, entry_type=None, limit=10, db_path="~/npcsh_history.db"):
    """Get log entries for an NPC or team"""
    db_path = os.path.expanduser(db_path)
    with sqlite3.connect(db_path) as conn:
        query = "SELECT entry_type, content, metadata, timestamp FROM npc_log WHERE entity_id = ?"
        params = [entity_id]

        if entry_type:
            query += " AND entry_type = ?"
            params.append(entry_type)

        query += " ORDER BY timestamp DESC LIMIT ?"
        params.append(limit)

        results = conn.execute(query, params).fetchall()

        return [
            {
                "entry_type": r[0],
                "content": json.loads(r[1]),
                "metadata": json.loads(r[2]) if r[2] else None,
                "timestamp": r[3]
            }
            for r in results
        ]

get_system_message(npc, team=None, tool_capable=False)

Source code in npcpy/npc_sysenv.py
def get_system_message(npc, team=None, tool_capable=False) -> str:

    if npc is None:
        return "You are a helpful assistant"
    if npc.plain_system_message:
        return npc.primary_directive

    system_message = f"""
.
..
...
....
.....
......
.......
........
.........
..........
Hello!
Welcome to the team.
You are the {npc.name} NPC with the following primary directive: {npc.primary_directive}.
Users may refer to you by your assistant name, {npc.name} and you should
consider this to be your core identity.
The current working directory is {os.getcwd()}.
The current date and time are : {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
"""

    if hasattr(npc, 'kg_data') and npc.kg_data:
        memory_context = npc.get_memory_context()
        if memory_context:
            system_message += f"\n\nMemory Context:\n{memory_context}\n"

    if npc.db_conn is not None:
        db_path = None
        if hasattr(npc.db_conn, "url") and npc.db_conn.url:
            db_path = npc.db_conn.url.database
        elif hasattr(npc.db_conn, "database"):
            db_path = npc.db_conn.database
        system_message += """What follows is information about the database connection. If you are asked to execute queries with tools, use this information. 
        If you are asked for help with debugging queries, use this information. 
        Do not unnecessarily reference that you possess this information unless it is
        specifically relevant to the request.

        DB Connection Information:        
        """
        if db_path:
            system_message += f"\nDatabase path: {db_path}\n"
        if npc.tables is not None:
            system_message += f"\nDatabase tables: {npc.tables}\n"

    if team is not None and npc.name == getattr(team, 'forenpc_name', 'sibiji'):
        team_context = team.context if hasattr(team, "context") and team.context else ""
        team_preferences = team.shared_context.get('preferences', '') if hasattr(team, "shared_context") else ""
        system_message += f"\nTeam context: {team_context}\n"
        if team_preferences:
            system_message += f"Team preferences: {team_preferences}\n"

        if hasattr(team, 'npcs') and team.npcs:
            members = []
            for name, member in team.npcs.items():
                if name != npc.name:
                    directive = getattr(member, 'primary_directive', '')
                    desc = directive[:50].strip() if directive else ''
                    members.append(f"  - @{name}: {desc}")
            if members:
                system_message += "\nTeam members available for delegation:\n" + "\n".join(members) + "\n"

    if hasattr(npc, 'jinxes_dict') and npc.jinxes_dict:
        tool_lines = []
        for jname, jinx in npc.jinxes_dict.items():
            desc = getattr(jinx, 'description', '') or ''
            tool_lines.append(f"  - {jname}: {desc.strip()}")
        if tool_lines:
            system_message += "\nYou have access to the following jinxes:\n"
            system_message += "\n".join(tool_lines) + "\n"
            if tool_capable:
                system_message += "\nUse the provided function calling interface to invoke tools when they are relevant to the request. For multi-step tasks, call one tool at a time and use its result to inform the next step.\n"
            else:
                jinx_names_str = ", ".join(npc.jinxes_dict.keys())
                jinx_instructions = f"""
                if you are in the [ReAct loop] and you are asked to use jinxes, refer to these guidelines:
              [BEGIN GUIDELINES FOR JINX EXECUTION]
                  Use jinxes when appropriate. For example:

                    - If you are asked about something up-to-date or dynamic (e.g., latest exchange rates)
                    - If the user asks you to read or edit a file
                    - If the user asks for code that should be executed
                    - If the user requests to open, search, download or scrape, which involve actual system or web actions
                    - If they request a screenshot, audio, or image manipulation
                    - Situations requiring file parsing (e.g., CSV or JSON loading)
                    - Scripted workflows or pipelines, e.g., generate a chart, fetch data, summarize from source, etc.

                    You MUST use a jinx if the request directly refers to a tool the AI cannot handle directly (e.g., 'run', 'open', 'search', etc).

                    You do not need to use a jinx if:

                    - the user asks a simple question like 'what is 2+2' or 'who invented linux', essentially any question which only requires general knowledge.
                    - The user asks you to write them a story (unless they separately specify saving it to a file, then you should directly write the story to be output through a jinx to said file.)
                    To invoke a jinx, return the action 'invoke_jinx' along with the jinx specific name.
                    An example for a jinx-specific return would be:
                    """ +"""
                    {
                        "action": "invoke_jinx",
                        "jinx_name": "file_reader",
                        "explanation": "Read the contents of <full_filename_path_from_user_request> and <detailed explanation of how to accomplish the problem outlined in the request>."
                    }


                    Do not use the jinx names as the action keys. You must use the action 'invoke_jinx' to invoke a jinx!
                    Do not invent jinx names. Use only those provided.


                Respond with a single JSON object only.
                To use a jinx, set action to jinx, jinx_name to one of [{jinx_names_str}], and inputs with the required parameters.

              [END GUIDELINES FOR JINX EXECUTION]


"""
                system_message += jinx_instructions




    return system_message

init_db_tables(db_path='~/npcsh_history.db')

Initialize necessary database tables

Source code in npcpy/npc_sysenv.py
def init_db_tables(db_path="~/npcsh_history.db"):
    """Initialize necessary database tables"""
    db_path = os.path.expanduser(db_path)
    with sqlite3.connect(db_path) as conn:

        conn.execute("""
            CREATE TABLE IF NOT EXISTS npc_log (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                entity_id TEXT,  
                entry_type TEXT,
                content TEXT,
                metadata TEXT,
                timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        """)


        conn.execute("""
            CREATE TABLE IF NOT EXISTS pipeline_runs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                pipeline_name TEXT,
                step_name TEXT,
                output TEXT,
                timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        """)


        conn.execute("""
            CREATE TABLE IF NOT EXISTS compiled_npcs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT UNIQUE,
                source_path TEXT,
                compiled_content TEXT,
                timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        """)

        conn.commit()

initialize_npc_project(directory=None, templates=None, context=None, model=None, provider=None, include_jinx_groups=None)

Initialize an NPC project.

Parameters:
  • include_jinx_groups

    List of jinx subdir paths to copy from the global team (e.g. ['lib/core', 'lib/utils', 'modes']). None = skip.

Source code in npcpy/npc_compiler.py
def initialize_npc_project(
    directory=None,
    templates=None,
    context=None,
    model=None,
    provider=None,
    include_jinx_groups=None,
) -> str:
    """Initialize an NPC project.

    Args:
        include_jinx_groups: List of jinx subdir paths to copy from the global
            team (e.g. ['lib/core', 'lib/utils', 'modes']).  None = skip.
    """
    if directory is None:
        directory = os.getcwd()
    directory = os.path.expanduser(os.fspath(directory))

    npc_team_dir = os.path.join(directory, "npc_team")
    os.makedirs(npc_team_dir, exist_ok=True)

    for subdir in ["jinxes",
                   "jinxes/skills",
                   "assembly_lines",
                   "sql_models",
                   "jobs",
                   "triggers",
                   "tools",
                   "images",
                   "models",
                   "attachments",
                   "mcp_servers"]:
        os.makedirs(os.path.join(npc_team_dir, subdir), exist_ok=True)

    # Copy selected jinx groups from the global npcsh team
    if include_jinx_groups:
        global_jinxes = os.path.expanduser("~/.npcsh/npc_team/jinxes")
        if not os.path.isdir(global_jinxes):
            pkg_jinxes = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                     '..', 'npcsh', 'npcsh', 'npc_team', 'jinxes')
            if os.path.isdir(pkg_jinxes):
                global_jinxes = pkg_jinxes
        if os.path.isdir(global_jinxes):
            dest_jinxes = os.path.join(npc_team_dir, "jinxes")
            for group in include_jinx_groups:
                src_group = os.path.join(global_jinxes, group)
                if not os.path.isdir(src_group):
                    continue
                for dirpath, dirnames, filenames in os.walk(src_group):
                    rel = os.path.relpath(dirpath, global_jinxes)
                    dest_dir = os.path.join(dest_jinxes, rel)
                    os.makedirs(dest_dir, exist_ok=True)
                    for fname in filenames:
                        if fname.endswith('.jinx'):
                            src = os.path.join(dirpath, fname)
                            dst = os.path.join(dest_dir, fname)
                            if not os.path.exists(dst):
                                shutil.copy2(src, dst)

    forenpc_path = os.path.join(npc_team_dir, "forenpc.npc")



    if not os.path.exists(forenpc_path):

        default_npc = {
            "name": "forenpc",
            "primary_directive": "You are the forenpc of an NPC team",
        }
        if model:
            default_npc["model"] = model
        if provider:
            default_npc["provider"] = provider
        with open(forenpc_path, "w", encoding="utf-8") as f:
            yaml.dump(default_npc, f)
    parsed_templates: List[str] = []
    if templates:
        if isinstance(templates, str):
            parsed_templates = [
                t.strip() for t in re.split(r"[,\s]+", templates) if t.strip()
            ]
        elif isinstance(templates, (list, tuple, set)):
            parsed_templates = [str(t).strip() for t in templates if str(t).strip()]
        else:
            parsed_templates = [str(templates).strip()]

    ctx_destination: Optional[str] = None
    preexisting_ctx = [
        os.path.join(npc_team_dir, f)
        for f in os.listdir(npc_team_dir)
        if f.endswith(".ctx")
    ]
    if preexisting_ctx:
        ctx_destination = preexisting_ctx[0]
        if len(preexisting_ctx) > 1:
            print(
                "Warning: Multiple .ctx files already present; using first and ignoring the rest."
            )

    def _resolve_template_path(template_name: str) -> Optional[str]:
        expanded = os.path.expanduser(template_name)
        if os.path.exists(expanded):
            return expanded

        embedded_templates = {
            "slean": """name: slean
primary_directive: You are slean, the marketing innovator AI. Your responsibility is to create marketing campaigns and manage them effectively, while also thinking creatively to solve marketing challenges. Guide the strategy that drives customer engagement and brand awareness.
""",
            "turnic": """name: turnic
primary_directive: Assist with sales challenges and questions. Opt for straightforward solutions that help sales professionals achieve quick results.
""",
            "budgeto": """name: budgeto
primary_directive: You manage marketing budgets, ensuring resources are allocated efficiently and spend is optimized.
""",
            "relatio": """name: relatio
primary_directive: You manage customer relationships and ensure satisfaction throughout the sales process. Focus on nurturing clients and maintaining long-term connections.
""",
            "funnel": """name: funnel
primary_directive: You oversee the sales pipeline, track progress, and optimize conversion rates to move leads efficiently.
""",
        }

        base_dirs = [
            os.path.expanduser("~/.npcsh/npc_team/templates"),
            os.path.expanduser("~/.npcpy/npc_team/templates"),
            os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tests", "template_tests", "npc_team")),
            os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "examples", "npc_team")),
            os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "example_npc_project", "npc_team")),
        ]
        base_dirs = [d for d in base_dirs if os.path.isdir(d)]

        for base in base_dirs:
            direct = os.path.join(base, template_name)
            if os.path.exists(direct):
                return direct
            if not direct.endswith(".npc") and os.path.exists(direct + ".npc"):
                return direct + ".npc"
            for root, _, files in os.walk(base):
                for fname in files:
                    stem, ext = os.path.splitext(fname)
                    if ext == ".npc" and stem == template_name:
                        return os.path.join(root, fname)

        if template_name in embedded_templates:
            embedded_dir = os.path.join(npc_team_dir, "_embedded_templates", template_name)
            os.makedirs(embedded_dir, exist_ok=True)
            npc_file = os.path.join(embedded_dir, f"{template_name}.npc")
            if not os.path.exists(npc_file):
                with open(npc_file, "w", encoding="utf-8") as f:
                    f.write(embedded_templates[template_name])
            return embedded_dir
        return None

    def _copy_template(src_path: str) -> List[str]:
        nonlocal ctx_destination
        copied: List[str] = []
        src_path = os.path.expanduser(src_path)

        allowed_exts = {".npc", ".tool", ".pipe", ".sql", ".job", ".ctx", ".yaml", ".yml"}

        if os.path.isfile(src_path):
            if os.path.splitext(src_path)[1] in allowed_exts:
                if os.path.splitext(src_path)[1] == ".ctx":
                    if ctx_destination:
                        print(
                            f"Warning: Skipping extra context file '{src_path}' because one already exists."
                        )
                        return copied
                    dest_path = os.path.join(npc_team_dir, os.path.basename(src_path))
                    ctx_destination = dest_path
                else:
                    dest_path = os.path.join(npc_team_dir, os.path.basename(src_path))
                if not os.path.exists(dest_path):
                    shutil.copy2(src_path, dest_path)
                copied.append(dest_path)
            return copied

        for root, _, files in os.walk(src_path):
            rel_dir = os.path.relpath(root, src_path)
            dest_dir = npc_team_dir if rel_dir == "." else os.path.join(npc_team_dir, rel_dir)
            os.makedirs(dest_dir, exist_ok=True)
            for fname in files:
                if os.path.splitext(fname)[1] not in allowed_exts:
                    continue
                if os.path.splitext(fname)[1] == ".ctx":
                    if ctx_destination:
                        print(
                            f"Warning: Skipping extra context file '{os.path.join(root, fname)}' because one already exists."
                        )
                        continue
                    dest_path = os.path.join(npc_team_dir, fname)
                    ctx_destination = dest_path
                else:
                    dest_path = os.path.join(dest_dir, fname)
                if not os.path.exists(dest_path):
                    shutil.copy2(os.path.join(root, fname), dest_path)
                copied.append(dest_path)
        return copied

    applied_templates: List[str] = []
    if parsed_templates:
        for template_name in parsed_templates:
            template_path = _resolve_template_path(template_name)
            if not template_path:
                print(f"Warning: Template '{template_name}' not found in known template directories.")
                continue
            copied = _copy_template(template_path)
            if copied:
                applied_templates.append(template_name)

    if applied_templates:
        applied_templates = sorted(set(applied_templates))
    if not ctx_destination:
        default_ctx_path = os.path.join(npc_team_dir, "team.ctx")
        default_ctx = {
            'name': '',
            'context' : context or '', 
            'preferences': '', 
            'mcp_servers': '', 
            'databases':'', 
            'use_global_jinxes': True,
            'forenpc': 'forenpc'
        }
        if model:
            default_ctx['model'] = model
        if provider:
            default_ctx['provider'] = provider
        if parsed_templates:
            default_ctx['templates'] = parsed_templates
        with open(default_ctx_path, "w", encoding="utf-8") as f:
            yaml.dump(default_ctx, f)
        ctx_destination = default_ctx_path

    if applied_templates:
        return f"NPC project initialized in {npc_team_dir} using templates: {', '.join(applied_templates)}"
    return f"NPC project initialized in {npc_team_dir}"

jinx_to_tool_def(jinx_obj)

Convert a Jinx instance into an MCP/LLM-compatible tool schema definition.

Source code in npcpy/npc_compiler.py
def jinx_to_tool_def(jinx_obj: 'Jinx') -> Dict[str, Any]:
    """Convert a Jinx instance into an MCP/LLM-compatible tool schema definition."""
    return jinx_obj.to_tool_def()

kg_dream_process(existing_kg, model=None, provider=None, npc=None, context='', num_seeds=3)

Source code in npcpy/memory/knowledge_graph.py
def kg_dream_process(existing_kg,
                     model=None,
                     provider=None,
                     npc=None,
                     context='',
                     num_seeds=3):
    current_gen = existing_kg.get('generation', 0)
    next_gen = current_gen + 1
    logger.info(f"DREAMING (Creative Synthesis): Gen {current_gen} -> Gen {next_gen}")
    concepts = existing_kg.get('concepts', [])
    if len(concepts) < num_seeds:
        logger.info(f"Not enough concepts ({len(concepts)}) for dream. Skipping.")
        return existing_kg, {}
    seed_concepts = random.sample(concepts, k=num_seeds)
    seed_names = [c['name'] for c in seed_concepts]
    logger.info(f"Dream seeded with: {seed_names}")
    prompt = f"""
    Write a short, speculative paragraph (a 'dream') that plausibly connects the concepts of {json.dumps(seed_names)}.
    Invent a brief narrative or a hypothetical situation.
    Respond with JSON: {{"dream_text": "A short paragraph..."}}
    """
    response = get_llm_response(prompt,
                                model=model,
                                provider=provider, npc=npc,
                                format="json", context=context)
    dream_text = response['response'].get('dream_text')
    if not dream_text:
        logger.info("Failed to generate a dream narrative. Skipping.")
        return existing_kg, {}
    logger.info(f"Generated Dream: '{dream_text[:150]}...'")

    dream_kg, _ = kg_evolve_incremental(existing_kg, new_content_text=dream_text,
                                         model=model, provider=provider, npc=npc, context=context)

    original_fact_stmts = {f['statement'] for f in existing_kg['facts']}
    for fact in dream_kg['facts']:
        if fact['statement'] not in original_fact_stmts:
            fact['origin'] = 'dream'
    original_concept_names = {c['name'] for c in existing_kg['concepts']}
    for concept in dream_kg['concepts']:
        if concept['name'] not in original_concept_names:
            concept['origin'] = 'dream'
    logger.info("Dream analysis complete. New knowledge integrated.")
    return dream_kg, {}

kg_evolve_incremental(existing_kg, new_content_text=None, new_facts=None, model=None, provider=None, npc=None, context='', get_concepts=False, link_concepts_facts=False, link_concepts_concepts=False, link_facts_facts=False, embedding_model=None, embedding_provider=None)

Source code in npcpy/memory/knowledge_graph.py
def kg_evolve_incremental(existing_kg,
                          new_content_text=None,
                          new_facts=None,
                          model=None,
                          provider=None,
                          npc=None,
                          context='',
                          get_concepts=False,
                          link_concepts_facts=False,
                          link_concepts_concepts=False,
                          link_facts_facts=False,
                          embedding_model=None,
                          embedding_provider=None):

    current_gen = existing_kg.get('generation', 0)
    next_gen = current_gen + 1

    newly_added_concepts = []
    concept_links = list(existing_kg.get('concept_links', []))
    fact_to_concept_links = defaultdict(list,
                                        existing_kg.get('fact_to_concept_links', {}))
    fact_to_fact_links = list(existing_kg.get('fact_to_fact_links', []))

    existing_facts = existing_kg.get('facts', [])
    existing_concepts = existing_kg.get('concepts', [])
    existing_concept_names = {c['name'] for c in existing_concepts}
    existing_fact_statements = [f['statement'] for f in existing_facts]
    all_concept_names = list(existing_concept_names)

    all_new_facts = []

    if new_facts:
        all_new_facts = new_facts
        logger.info(f'Using pre-approved facts: {len(all_new_facts)}')
    elif new_content_text:
        logger.info('Extracting facts from content...')
        if len(new_content_text) > 10000:
            for n in range(len(new_content_text) // 10000):
                content_to_sample = new_content_text[n * 10000:(n + 1) * 10000]
                facts = get_facts(content_to_sample,
                                model=model,
                                provider=provider,
                                npc=npc,
                                context=context)
                all_new_facts.extend(facts)
        else:
            all_new_facts = get_facts(new_content_text,
                                model=model,
                                provider=provider,
                                npc=npc,
                                context=context)
    else:
        logger.info("No new content or facts provided")
        return existing_kg, {}

    existing_stmts = {f['statement'] for f in existing_facts}
    for fact in all_new_facts:
        fact['generation'] = next_gen

    final_facts = existing_facts + [f for f in all_new_facts if f['statement'] not in existing_stmts]

    if get_concepts:
        logger.info('Generating groups...')
        candidate_concepts = generate_groups(all_new_facts,
                                            model=model,
                                            provider=provider,
                                            npc=npc,
                                            context=context)
        for cand_concept in candidate_concepts:
            cand_name = cand_concept['name']
            if cand_name in existing_concept_names:
                continue
            cand_concept['generation'] = next_gen
            newly_added_concepts.append(cand_concept)
            if link_concepts_concepts:
                related_concepts = get_related_concepts_multi(cand_name,
                                                            "concept",
                                                            all_concept_names,
                                                            model,
                                                            provider,
                                                            npc,
                                                            context)
                for related_name in related_concepts:
                    if related_name != cand_name:
                        concept_links.append((cand_name, related_name))
            all_concept_names.append(cand_name)

        final_concepts = existing_concepts + newly_added_concepts

        if link_concepts_facts:
            for fact in all_new_facts:
                fact_to_concept_links[fact['statement']] = get_related_concepts_multi(
                    fact['statement'], "fact", all_concept_names,
                    model=model, provider=provider, npc=npc, context=context)
    else:
        final_concepts = existing_concepts

    if link_facts_facts and existing_fact_statements:
        e_model = embedding_model or 'nomic-embed-text'
        e_provider = embedding_provider or 'ollama'

        for new_fact in all_new_facts:
            # Pre-filter existing facts by embedding similarity
            candidates = _get_similar_by_embedding(
                new_fact['statement'], existing_fact_statements,
                e_model, e_provider, top_k=20)
            if candidates:
                related_fact_stmts = get_related_facts_llm(new_fact['statement'],
                                                           candidates,
                                                           model=model,
                                                           provider=provider,
                                                           npc=npc,
                                                           context=context)
                for related_stmt in related_fact_stmts:
                    fact_to_fact_links.append((new_fact['statement'], related_stmt))

    final_kg = {
        "generation": next_gen,
        "facts": final_facts,
        "concepts": final_concepts,
        "concept_links": concept_links,
        "fact_to_concept_links": dict(fact_to_concept_links),
        "fact_to_fact_links": fact_to_fact_links
    }
    return final_kg, {}

kg_initial(content, model=None, provider=None, npc=None, context='', facts=None, generation=None, verbose=True, embedding_model=None, embedding_provider=None, zoom_in_enabled=True)

Source code in npcpy/memory/knowledge_graph.py
def kg_initial(content,
               model=None,
               provider=None,
               npc=None,
               context='',
               facts=None,
               generation=None,
               verbose=True,
               embedding_model=None,
               embedding_provider=None,
               zoom_in_enabled=True):

    if generation is None:
        CURRENT_GENERATION = 0
    else:
        CURRENT_GENERATION = generation

    logger.info(f"Running KG Structuring Process (Generation: {CURRENT_GENERATION})")

    if facts is None:
        if not content:
            raise ValueError("kg_initial requires either content_text or a list of facts.")
        logger.info("Mode: Deriving new facts from text content...")
        all_facts = []
        if len(content) > 10000:
            for n in range(len(content) // 10000):
                content_to_sample = content[n * 10000:(n + 1) * 10000]
                extracted = get_facts(content_to_sample,
                                model=model,
                                provider=provider,
                                npc=npc,
                                context=context)
                if verbose:
                    logger.debug(f"Extracted {len(extracted)} facts from segment {n+1}")
                all_facts.extend(extracted)
        else:
            all_facts = get_facts(content,
                                  model=model,
                                  provider=provider,
                                  npc=npc,
                                  context=context)
            if verbose:
                logger.debug(f"Extracted {len(all_facts)} facts from content")
        for fact in all_facts:
            fact['generation'] = CURRENT_GENERATION
    else:
        logger.info(f"Mode: Building structure from {len(facts)} pre-existing facts...")
        all_facts = list(facts)

    all_implied_facts = []
    if zoom_in_enabled:
        logger.info("Inferring implied facts (zooming in)...")
        if len(all_facts) > 20:
            sampled_facts = random.sample(all_facts, k=20)
            for n in range(len(all_facts) // 20):
                implied_facts = zoom_in(sampled_facts,
                                        model=model,
                                        provider=provider,
                                        npc=npc,
                                        context=context)
                all_implied_facts.extend(implied_facts)
                if verbose:
                    logger.debug(f"Inferred {len(implied_facts)} implied facts from sample {n+1}")
        else:
            implied_facts = zoom_in(all_facts,
                                    model=model,
                                    provider=provider,
                                    npc=npc,
                                    context=context)
            all_implied_facts.extend(implied_facts)
            if verbose:
                logger.debug(f"Inferred {len(implied_facts)} implied facts from all facts")

        for fact in all_implied_facts:
            fact['generation'] = CURRENT_GENERATION
    else:
        logger.info("Skipping zoom-in (zoom_in_enabled=False)")

    all_facts = all_facts + all_implied_facts

    logger.info("Generating concepts from all facts...")
    concepts = generate_groups(all_facts,
                               model=model,
                               provider=provider,
                               npc=npc,
                               context=context)
    for concept in concepts:
        concept['generation'] = CURRENT_GENERATION

    if verbose:
        logger.debug(f"Generated {len(concepts)} concepts")

    logger.info("Linking facts to concepts...")
    fact_to_concept_links = defaultdict(list)
    concept_names = [c['name'] for c in concepts if c and 'name' in c]
    for fact in all_facts:
        fact_to_concept_links[fact['statement']] = get_related_concepts_multi(
            fact['statement'], "fact", concept_names, model, provider, npc, context)

    logger.info("Linking facts to other facts...")
    fact_to_fact_links = []
    fact_statements = [f['statement'] for f in all_facts]

    e_model = embedding_model or 'nomic-embed-text'
    e_provider = embedding_provider or 'ollama'

    for i, fact in enumerate(all_facts):
        other_fact_statements = [s for s in fact_statements if s != fact['statement']]
        if not other_fact_statements:
            continue
        try:
            # Pre-filter by embedding similarity to avoid passing too many to LLM
            candidates = _get_similar_by_embedding(
                fact['statement'], other_fact_statements, e_model, e_provider, top_k=20)
            if candidates:
                related_fact_stmts = get_related_facts_llm(fact['statement'],
                                                           candidates,
                                                           model=model,
                                                           provider=provider,
                                                           npc=npc,
                                                           context=context)
                for related_stmt in related_fact_stmts:
                    fact_to_fact_links.append((fact['statement'], related_stmt))
        except Exception as e:
            logger.warning(f"Failed to link fact {i+1}/{len(all_facts)}: {e}")
            continue

    return {
        "generation": CURRENT_GENERATION,
        "facts": all_facts,
        "concepts": concepts,
        "concept_links": [],
        "fact_to_concept_links": dict(fact_to_concept_links),
        "fact_to_fact_links": fact_to_fact_links
    }

kg_sleep_process(existing_kg, model=None, provider=None, npc=None, context='', operations_config=None, embedding_model=None, embedding_provider=None)

Source code in npcpy/memory/knowledge_graph.py
def kg_sleep_process(existing_kg,
                     model=None,
                     provider=None,
                     npc=None,
                     context='',
                     operations_config=None,
                     embedding_model=None,
                     embedding_provider=None):
    current_gen = existing_kg.get('generation', 0)
    next_gen = current_gen + 1
    logger.info(f"SLEEPING (Evolving Knowledge): Gen {current_gen} -> Gen {next_gen}")

    facts_map = {f['statement']: f for f in existing_kg.get('facts', [])}
    concepts_map = {c['name']: c for c in existing_kg.get('concepts', [])}
    fact_links = defaultdict(list, {k: list(v) for k, v in existing_kg.get('fact_to_concept_links', {}).items()})
    concept_links = set(tuple(sorted(link)) for link in existing_kg.get('concept_links', []))
    fact_to_fact_links = set(tuple(sorted(link)) for link in existing_kg.get('fact_to_fact_links', []))

    # Phase 1: Check for unstructured facts
    logger.info("Phase 1: Checking for unstructured facts...")
    facts_with_concepts = set(fact_links.keys())
    orphaned_fact_statements = list(set(facts_map.keys()) - facts_with_concepts)

    if len(orphaned_fact_statements) > 20:
        logger.info(f"Found {len(orphaned_fact_statements)} orphaned facts. Applying full KG structuring process...")
        orphaned_facts_as_dicts = [facts_map[s] for s in orphaned_fact_statements]

        new_structure = kg_initial(
            content=None,
            facts=orphaned_facts_as_dicts,
            model=model,
            provider=provider,
            npc=npc,
            context=context,
            generation=next_gen,
            embedding_model=embedding_model,
            embedding_provider=embedding_provider
        )

        logger.info("Merging new structure into main KG...")
        for concept in new_structure.get("concepts", []):
            if concept['name'] not in concepts_map:
                concepts_map[concept['name']] = concept

        for fact_stmt, new_links in new_structure.get("fact_to_concept_links", {}).items():
            existing_links = set(fact_links.get(fact_stmt, []))
            existing_links.update(new_links)
            fact_links[fact_stmt] = list(existing_links)

        for f1, f2 in new_structure.get("fact_to_fact_links", []):
            fact_to_fact_links.add(tuple(sorted((f1, f2))))
    else:
        logger.info("Knowledge graph is sufficiently structured. Proceeding to refinement.")

    # Phase 2: Refinement operations
    if operations_config is None:
        possible_ops = ['prune', 'deepen']
        ops_to_run = random.sample(possible_ops, k=random.randint(1, 2))
    else:
        ops_to_run = operations_config

    logger.info(f"Phase 2: Executing refinement operations: {ops_to_run}")

    for op in ops_to_run:
        if op == 'prune' and (len(facts_map) > 10 or len(concepts_map) > 5):
            logger.info("Running 'prune' operation...")
            fact_to_check = random.choice(list(facts_map.values()))
            other_facts = [f for f in facts_map.values() if f['statement'] != fact_to_check['statement']]
            consolidation_result = consolidate_facts_llm(fact_to_check, other_facts, model, provider, npc, context)
            if consolidation_result.get('decision') == 'redundant':
                logger.info(f"Pruning redundant fact: '{fact_to_check['statement'][:80]}...'")
                del facts_map[fact_to_check['statement']]

        elif op == 'deepen' and facts_map:
            logger.info("Running 'deepen' operation...")
            fact_to_deepen = random.choice(list(facts_map.values()))
            implied_facts = zoom_in([fact_to_deepen], model, provider, npc, context)
            new_fact_count = 0
            for fact in implied_facts:
                if fact['statement'] not in facts_map:
                    fact.update({'generation': next_gen, 'origin': 'deepen'})
                    facts_map[fact['statement']] = fact
                    new_fact_count += 1
            if new_fact_count > 0:
                logger.info(f"Inferred {new_fact_count} new fact(s).")

        else:
            logger.debug(f"SKIPPED: Operation '{op}' did not run (conditions not met).")

    new_kg = {
        "generation": next_gen,
        "facts": list(facts_map.values()),
        "concepts": list(concepts_map.values()),
        "concept_links": [list(link) for link in concept_links],
        "fact_to_concept_links": dict(fact_links),
        "fact_to_fact_links": [list(link) for link in fact_to_fact_links]
    }
    return new_kg, {}

load_jinxes_from_directory(directory)

Load all jinxes from a directory recursively.

Handles two file types:

  1. .jinx — regular jinxes loaded as-is. Skill-type jinxes are just regular .jinx files whose steps use engine: skill with the full structured args (sections, scripts, references, assets).
  2. SKILL.md inside a skill folder — Anthropic-style skill folders::

    jinxes/skills/code-review/SKILL.md jinxes/skills/code-review/scripts/ jinxes/skills/code-review/references/

The folder name becomes the skill name. The SKILL.md must have YAML frontmatter (--- delimiters) and ## section headers. These are compiled into jinxes with engine: skill steps.

Source code in npcpy/npc_compiler.py
def load_jinxes_from_directory(directory):
    """Load all jinxes from a directory recursively.

    Handles two file types:

    1. **.jinx** — regular jinxes loaded as-is.  Skill-type jinxes are just
       regular ``.jinx`` files whose steps use ``engine: skill`` with the
       full structured args (sections, scripts, references, assets).
    2. **SKILL.md inside a skill folder** — Anthropic-style skill folders::

           jinxes/skills/code-review/SKILL.md
           jinxes/skills/code-review/scripts/
           jinxes/skills/code-review/references/

       The folder name becomes the skill name.  The SKILL.md must have YAML
       frontmatter (``---`` delimiters) and ``##`` section headers.
       These are compiled into jinxes with ``engine: skill`` steps.
    """
    jinxes = []
    directory = os.path.expanduser(directory)

    if not os.path.exists(directory):
        return jinxes

    for root, dirs, files in os.walk(directory):
        for filename in files:
            if filename.endswith(".jinx"):
                try:
                    jinx_path = os.path.join(root, filename)
                    jinx = Jinx(jinx_path=jinx_path)
                    jinxes.append(jinx)
                except Exception as e:
                    print(f"Error loading jinx {filename}: {e}")
            elif filename == "SKILL.md":
                try:
                    md_path = os.path.join(root, filename)
                    jinx = _load_skill_from_md(md_path)
                    if jinx:
                        jinxes.append(jinx)
                except Exception as e:
                    skill_folder = os.path.basename(root)
                    print(f"Error loading skill from {skill_folder}/SKILL.md: {e}")

    return jinxes

load_yaml_file(file_path, jinja_context=None)

Load a YAML file with error handling, rendering Jinja2 first.

Parameters:
  • file_path

    Path to the YAML file

  • jinja_context

    Optional dict of variables to pass to Jinja2 rendering. Used by Team to inject jinx name->path mappings so NPC files can use {{ jinx_name }} to resolve to the correct relative path.

Source code in npcpy/npc_compiler.py
def load_yaml_file(file_path, jinja_context=None):
    """Load a YAML file with error handling, rendering Jinja2 first.

    Args:
        file_path: Path to the YAML file
        jinja_context: Optional dict of variables to pass to Jinja2 rendering.
            Used by Team to inject jinx name->path mappings so NPC files can
            use {{ jinx_name }} to resolve to the correct relative path.
    """
    try:
        with open(os.path.expanduser(file_path), 'r', encoding="utf-8") as f:
            content = f.read()

        # Only trigger Jinja on {{ }} if jinja_context is provided (NPC and team
        # .ctx files). Callers signal "render Jinja" by passing ANY jinja_context,
        # including {}, so first-pass .ctx loads can use SilentUndefined without
        # supplying the full macro set. Jinx files use {{ }} for runtime templating
        # and should NOT be rendered at load time, so they pass None.
        has_jinja = '{%' in content or (jinja_context is not None and '{{' in content and '}}' in content)
        if not has_jinja:
            return yaml.safe_load(content)

        jinja_env = SandboxedEnvironment(undefined=SilentUndefined)
        jinja_env.policies['json.dumps_function'] = _json_dumps_with_undefined
        template = jinja_env.from_string(content)
        rendered_content = template.render(jinja_context or {})

        return yaml.safe_load(rendered_content)
    except Exception as e:
        print(f"Error loading YAML file {file_path}: {e}")
        return None

log_entry(entity_id, entry_type, content, metadata=None, db_path='~/npcsh_history.db')

Log an entry for an NPC or team

Source code in npcpy/npc_compiler.py
def log_entry(entity_id, entry_type, content, metadata=None, db_path="~/npcsh_history.db"):
    """Log an entry for an NPC or team"""
    db_path = os.path.expanduser(db_path)
    with sqlite3.connect(db_path) as conn:
        conn.execute(
            "INSERT INTO npc_log (entity_id, entry_type, content, metadata) VALUES (?, ?, ?, ?)",
            (entity_id, entry_type, json.dumps(content), json.dumps(metadata) if metadata else None)
        )
        conn.commit()

match_jinx_spec_to_names(jinx_spec, team_jinxes_dict, jinxes_base_dir, jinx_path_map=None)

Match a jinx spec to actual jinx names from the team's jinxes_dict.

Specs can be: - A direct jinx name: 'edit_file', 'sh', 'python' - A relative path (resolved via {{ Jinx() }} in .npc files): 'lib/core/files/edit_file' - A glob pattern for bulk loading: 'lib/browser/*'

Parameters:
  • jinx_spec (str) –

    The spec string

  • team_jinxes_dict (Dict[str, Jinx]) –

    Dict mapping jinx_name -> Jinx object

  • jinxes_base_dir (str) –

    Base directory where team jinxes are stored

  • jinx_path_map (dict, default: None ) –

    Optional dict mapping jinx_name -> relative path (for reverse lookup)

Returns:
  • List[str]

    List of jinx names that match the spec

Source code in npcpy/npc_compiler.py
def match_jinx_spec_to_names(jinx_spec: str, team_jinxes_dict: Dict[str, 'Jinx'], jinxes_base_dir: str, jinx_path_map: dict = None) -> List[str]:
    """
    Match a jinx spec to actual jinx names from the team's jinxes_dict.

    Specs can be:
    - A direct jinx name: 'edit_file', 'sh', 'python'
    - A relative path (resolved via {{ Jinx() }} in .npc files): 'lib/core/files/edit_file'
    - A glob pattern for bulk loading: 'lib/browser/*'

    Args:
        jinx_spec: The spec string
        team_jinxes_dict: Dict mapping jinx_name -> Jinx object
        jinxes_base_dir: Base directory where team jinxes are stored
        jinx_path_map: Optional dict mapping jinx_name -> relative path (for reverse lookup)

    Returns:
        List of jinx names that match the spec
    """
    # 1) Direct name match
    if jinx_spec in team_jinxes_dict:
        return [jinx_spec]

    # 1.5) Reverse path lookup - resolved paths like 'lib/core/sql' map back to names
    if jinx_path_map:
        for name, path in jinx_path_map.items():
            if jinx_spec == path and name in team_jinxes_dict:
                return [name]

    # 2) Path/glob match against source_path relative to jinxes_base_dir
    spec_pattern = jinx_spec
    if not spec_pattern.endswith('.jinx') and not spec_pattern.endswith('*'):
        spec_pattern += '.jinx'

    matched_names = []
    for jinx_name, jinx_obj in team_jinxes_dict.items():
        source_path = getattr(jinx_obj, '_source_path', None)
        if not source_path:
            continue

        try:
            rel_path = os.path.relpath(source_path, jinxes_base_dir)
        except ValueError:
            continue

        if fnmatch.fnmatch(rel_path, spec_pattern):
            matched_names.append(jinx_name)

    return matched_names

print_and_process_stream_with_markdown(response, model, provider, show=False, rerender=True)

Source code in npcpy/npc_sysenv.py
def print_and_process_stream_with_markdown(response, model, provider, show=False, rerender=True):
    import sys

    str_output = ""
    dot_count = 0
    tool_call_data = {"id": None, "function_name": None, "arguments": ""}
    interrupted = False

    if isinstance(response, str):
        render_markdown(response)
        print('\n') 
        return response 


    if rerender:
        sys.stdout.write('\033[s')
        sys.stdout.flush()

    try:
        for chunk in response:

            if provider == "ollama":

                if "message" in chunk and "tool_calls" in chunk["message"]:
                    for tool_call in chunk["message"]["tool_calls"]:
                        if "id" in tool_call:
                            tool_call_data["id"] = tool_call["id"]
                        if "function" in tool_call:
                            if "name" in tool_call["function"]:
                                tool_call_data["function_name"] = tool_call["function"]["name"]
                            if "arguments" in tool_call["function"]:
                                if isinstance(tool_call["function"]["arguments"], dict):
                                    tool_call_data["arguments"] += json.dumps(tool_call["function"]["arguments"])
                                else:
                                    tool_call_data["arguments"] += tool_call["function"]["arguments"]
                chunk_content = chunk["message"]["content"] if "message" in chunk and "content" in chunk["message"] else ""
                reasoning_content = chunk['message'].get('thinking', '') if "message" in chunk and "thinking" in chunk['message'] else ""
                if show:
                    if len(reasoning_content) > 0:
                        print(reasoning_content, end="", flush=True)
                    if chunk_content != "":
                        print(chunk_content, end="", flush=True)
                else:
                    print('.', end="", flush=True)
                    dot_count += 1

            else:
                for c in chunk.choices:
                    if hasattr(c.delta, "tool_calls") and c.delta.tool_calls:
                        for tool_call in c.delta.tool_calls:
                            if tool_call.id:
                                tool_call_data["id"] = tool_call.id
                            if tool_call.function:
                                if hasattr(tool_call.function, "name") and tool_call.function.name:
                                    tool_call_data["function_name"] = tool_call.function.name
                                if hasattr(tool_call.function, "arguments") and tool_call.function.arguments:
                                    tool_call_data["arguments"] += tool_call.function.arguments

                chunk_content = ''
                reasoning_content = ''
                for c in chunk.choices:
                    if hasattr(c.delta, "reasoning_content"):
                        reasoning_content += c.delta.reasoning_content

                chunk_content += "".join(
                    c.delta.content for c in chunk.choices if c.delta.content
                )
                if show:
                    if reasoning_content is not None:
                        print(reasoning_content, end="", flush=True)
                    if chunk_content != "":
                        print(chunk_content, end="", flush=True)
                else:
                    print('.', end="", flush=True)
                    dot_count += 1

            if not chunk_content:
                continue
            str_output += chunk_content

    except KeyboardInterrupt:
        interrupted = True
        print('\n⚠️ Stream interrupted by user')

    if tool_call_data["id"] or tool_call_data["function_name"] or tool_call_data["arguments"]:
        str_output += "\n\n"
        if tool_call_data["id"]:
            str_output += f"**ID:** {tool_call_data['id']}\n\n"
        if tool_call_data["function_name"]:
            str_output += f"**Function:** {tool_call_data['function_name']}\n\n"
        if tool_call_data["arguments"]:
            try:
                args_parsed = json.loads(tool_call_data["arguments"])
                str_output += f"**Arguments:**\n```json\n{json.dumps(args_parsed, indent=2)}\n```"
            except Exception:
                str_output += f"**Arguments:** `{tool_call_data['arguments']}`"

    if interrupted:
        str_output += "\n\n[⚠️ Response interrupted by user]"


    if rerender:
        sys.stdout.write('\033[u')
        sys.stdout.write('\033[J')
        sys.stdout.flush()
        render_markdown(str_output)
    print('\n')

    return str_output

strip_shebang(content)

Strip shebang line from file content before YAML parsing.

Source code in npcpy/npc_compiler.py
def strip_shebang(content: str) -> str:
    """Strip shebang line from file content before YAML parsing."""
    if content.startswith('#!'):
        newline = content.find('\n')
        if newline >= 0:
            return content[newline + 1:]
    return content

write_yaml_file(file_path, data)

Write data to a YAML file

Source code in npcpy/npc_compiler.py
def write_yaml_file(file_path, data):
    """Write data to a YAML file"""
    try:
        with open(os.path.expanduser(file_path), 'w', encoding="utf-8") as f:
            yaml.dump(data, f)
        return True
    except Exception as e:
        print(f"Error writing YAML file {file_path}: {e}")
        return False