pi-codemode-py 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .eggs/
5
+ dist/
6
+ build/
7
+ !tui/crates/build/
8
+ .pytest_cache/
9
+ .pytest-audit/
10
+ .mypy_cache/
11
+ .ruff_cache/
12
+ .venv/
13
+ .venv-*/
14
+ venv/
15
+ .env
16
+ # Rust TUI workspace (Apache-2.0 fork under tui/)
17
+ tui/target/
18
+ **/*.rs.bk
19
+
20
+ # Benchmark evaluation cache and trial artifacts
21
+ .cache/
22
+ .pi-eval/
23
+
24
+ # Temporary files, coverage and logs
25
+ *.log
26
+ *.tmp
27
+ *.bak
28
+ *.swp
29
+ *.orig
30
+ .coverage
31
+ .coverage.*
32
+ coverage.xml
33
+ htmlcov/
34
+
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.5
2
+ Name: pi-codemode-py
3
+ Version: 1.1.0
4
+ Summary: Programmatic tool orchestration and deferred tool discovery extension for pi-python
5
+ Project-URL: Homepage, https://github.com/zy1233/pi-python
6
+ Project-URL: Website, https://zycode.dev
7
+ Project-URL: Repository, https://github.com/zy1233/pi-python
8
+ Author-email: zy1233 <zy1233@users.noreply.github.com>
9
+ License-Expression: MIT
10
+ Keywords: agent,codemode,extension,mcp,pi,tool-search
11
+ Requires-Python: >=3.11
12
+ Requires-Dist: pi-agent-core-lc>=1.1.0
13
+ Requires-Dist: pydantic>=2.0
14
+ Description-Content-Type: text/markdown
15
+
16
+ # pi-codemode-py
17
+
18
+ Programmatic tool orchestration (`codemode`) and on-demand deferred tool discovery (`tool_search`)
19
+ for `pi-python` (`zycode`).
20
+
21
+ Design specification: `docs/specs/2026-11-24-code-mode-design.md`.
22
+
23
+ ## Features
24
+
25
+ - **`codemode` tool**: Executes async Python orchestration scripts in the shared
26
+ `pi_agent_core.sandbox` child process (`pi-sandbox-child`, protocol v2). Intermediate tool outputs
27
+ stay inside the sandbox; only explicit `text()` / `image()` calls, trailing return values, and
28
+ `<console_output>` (`print()`) return to the LLM context.
29
+ - **Runtime permission gating**: By default (`[codemode] require_approval = true`), starting an outer `codemode` script asks for permission in `ask` and `auto` modes just like `workflow` (users inside a container/VM/trusted setup can set `require_approval = false`). Every inner `await tools.<name>(...)` call evaluates its concrete arguments at runtime and passes through `AgentHarness.invoke_tool` (`check_tool_call`, `tool_result` hooks, Auto rules and model classifier, and ACP permission prompts) with `origin={"kind": "codemode", ...}` and writer-preferring serialization when mutating or under sequential tool policy.
30
+ - **`tool_search` & Deferred Tool Loading**: Discovers deferred tools (such as `pi-mcp` servers) via `ALL_TOOLS` / `search_tools()` inside scripts or promotes them directly with `tool_search`.
31
+ - **`/codemode` command**: Toggle or inspect runtime modes (`/codemode [status|on|hybrid|only|off]`).
32
+
33
+ ## Sandbox boundaries
34
+
35
+ Scripts run in a child process (`pi_agent_core.sandbox`) with a scrubbed environment, empty temporary working directory, stdlib-only allowlisted imports (`_safe_import`), PEP 578 audit hook (a speed bump, not a security boundary on its own), and OS-level resource limits (Linux `rlimit` / `PR_SET_NO_NEW_PRIVS` where `unlink`, same-user `/proc`, and sockets remain open; Windows Job Object `ActiveProcessLimit=1` and low integrity without `RLIMIT_FSIZE`). On macOS the kernel does not enforce `RLIMIT_AS` or `RLIMIT_NPROC` (repository decision 2026-10-31). Keep `[codemode] require_approval = true` (default) or run the agent inside `zypi --sandbox`, a container, or a VM for untrusted repositories.
@@ -0,0 +1,20 @@
1
+ # pi-codemode-py
2
+
3
+ Programmatic tool orchestration (`codemode`) and on-demand deferred tool discovery (`tool_search`)
4
+ for `pi-python` (`zycode`).
5
+
6
+ Design specification: `docs/specs/2026-11-24-code-mode-design.md`.
7
+
8
+ ## Features
9
+
10
+ - **`codemode` tool**: Executes async Python orchestration scripts in the shared
11
+ `pi_agent_core.sandbox` child process (`pi-sandbox-child`, protocol v2). Intermediate tool outputs
12
+ stay inside the sandbox; only explicit `text()` / `image()` calls, trailing return values, and
13
+ `<console_output>` (`print()`) return to the LLM context.
14
+ - **Runtime permission gating**: By default (`[codemode] require_approval = true`), starting an outer `codemode` script asks for permission in `ask` and `auto` modes just like `workflow` (users inside a container/VM/trusted setup can set `require_approval = false`). Every inner `await tools.<name>(...)` call evaluates its concrete arguments at runtime and passes through `AgentHarness.invoke_tool` (`check_tool_call`, `tool_result` hooks, Auto rules and model classifier, and ACP permission prompts) with `origin={"kind": "codemode", ...}` and writer-preferring serialization when mutating or under sequential tool policy.
15
+ - **`tool_search` & Deferred Tool Loading**: Discovers deferred tools (such as `pi-mcp` servers) via `ALL_TOOLS` / `search_tools()` inside scripts or promotes them directly with `tool_search`.
16
+ - **`/codemode` command**: Toggle or inspect runtime modes (`/codemode [status|on|hybrid|only|off]`).
17
+
18
+ ## Sandbox boundaries
19
+
20
+ Scripts run in a child process (`pi_agent_core.sandbox`) with a scrubbed environment, empty temporary working directory, stdlib-only allowlisted imports (`_safe_import`), PEP 578 audit hook (a speed bump, not a security boundary on its own), and OS-level resource limits (Linux `rlimit` / `PR_SET_NO_NEW_PRIVS` where `unlink`, same-user `/proc`, and sockets remain open; Windows Job Object `ActiveProcessLimit=1` and low integrity without `RLIMIT_FSIZE`). On macOS the kernel does not enforce `RLIMIT_AS` or `RLIMIT_NPROC` (repository decision 2026-10-31). Keep `[codemode] require_approval = true` (default) or run the agent inside `zypi --sandbox`, a container, or a VM for untrusted repositories.
@@ -0,0 +1,179 @@
1
+ """pi-codemode: programmatic tool orchestration and deferred tool discovery extension.
2
+
3
+ Design: ``docs/specs/2026-11-24-code-mode-design.md``.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ from typing import TYPE_CHECKING, Any, Literal
10
+
11
+ from pi_codemode.codemode_tool import build_codemode_description, create_codemode_tool
12
+ from pi_codemode.runtime import CodemodeRuntime
13
+ from pi_codemode.settings import CodemodeSettings
14
+ from pi_codemode.tool_search_tool import create_tool_search_tool
15
+
16
+ if TYPE_CHECKING:
17
+ from pi_agent_core.extensions import ExtensionAPI
18
+
19
+ __all__ = ["activate"]
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ MODE_ENTRY_TYPE = "pi.codemode_mode"
24
+ SessionMode = Literal["hybrid", "only", "off"]
25
+ _META_TOOLS = frozenset({"codemode", "tool_search"})
26
+
27
+
28
+ class _Controller:
29
+ def __init__(self, pi: ExtensionAPI, settings: CodemodeSettings) -> None:
30
+ self.pi = pi
31
+ self.settings = settings
32
+ self.mode: SessionMode = settings.mode if settings.enabled else "off"
33
+ self.tools_registered = False
34
+ self.saved_before_only: list[str] | None = None
35
+ self._deferred_by_only: set[str] = set()
36
+ self.runtime = CodemodeRuntime(pi, lambda: self.settings)
37
+
38
+ def _restore_hidden_tools(self) -> None:
39
+ if not self.saved_before_only:
40
+ self._deferred_by_only.clear()
41
+ return
42
+ known = {t.name for t in self.pi.get_all_tools()}
43
+ restore = [n for n in self.saved_before_only if n in known]
44
+ to_undefer = [n for n in restore if n in self._deferred_by_only]
45
+ others = [n for n in restore if n not in self._deferred_by_only]
46
+ if to_undefer:
47
+ self.pi.activate_tools(to_undefer, undefer=True)
48
+ if others:
49
+ self.pi.activate_tools(others)
50
+ self._deferred_by_only.clear()
51
+ self.saved_before_only = None
52
+
53
+ def ensure_tools_registered(self, *, refresh_description: bool = False) -> None:
54
+ if self.tools_registered and not refresh_description:
55
+ return
56
+ direct_names = frozenset(self.saved_before_only or ())
57
+ desc = (
58
+ build_codemode_description(self.pi, direct_names=direct_names)
59
+ if self.tools_registered
60
+ else None
61
+ )
62
+ if not self.tools_registered:
63
+ try:
64
+ desc = build_codemode_description(self.pi, direct_names=direct_names)
65
+ except Exception:
66
+ desc = None
67
+ self.pi.register_tool(
68
+ create_codemode_tool(
69
+ self.pi,
70
+ self.runtime,
71
+ lambda: self.settings,
72
+ description=desc,
73
+ )
74
+ )
75
+ if not self.tools_registered:
76
+ self.pi.register_tool(create_tool_search_tool(self.pi))
77
+ self.tools_registered = True
78
+
79
+ def apply_mode(self, new_mode: SessionMode, *, persist: bool) -> None:
80
+ previous = self.mode
81
+ self.mode = new_mode
82
+
83
+ if new_mode == "off":
84
+ if self.tools_registered:
85
+ self.pi.deactivate_tools(["codemode", "tool_search"])
86
+ self._restore_hidden_tools()
87
+ deferred = [t.name for t in self.pi.get_all_tools() if t.deferred and not t.active]
88
+ if deferred:
89
+ self.pi.activate_tools(deferred)
90
+ elif new_mode == "hybrid":
91
+ self.ensure_tools_registered(refresh_description=True)
92
+ self.pi.activate_tools(["codemode", "tool_search"])
93
+ self._restore_hidden_tools()
94
+ self.ensure_tools_registered(refresh_description=True)
95
+ elif new_mode == "only":
96
+ self.ensure_tools_registered(refresh_description=True)
97
+ self.pi.activate_tools(["codemode", "tool_search"])
98
+ all_by_name = {t.name: t for t in self.pi.get_all_tools()}
99
+ active = self.pi.get_active_tools()
100
+ to_hide = [name for name in active if name not in _META_TOOLS]
101
+ if to_hide:
102
+ if self.saved_before_only is None:
103
+ self.saved_before_only = to_hide
104
+ else:
105
+ existing = set(self.saved_before_only)
106
+ self.saved_before_only.extend(n for n in to_hide if n not in existing)
107
+ self._deferred_by_only.update(
108
+ n for n in to_hide if n in all_by_name and not all_by_name[n].deferred
109
+ )
110
+ self.pi.deactivate_tools(to_hide, defer=True)
111
+ self.ensure_tools_registered(refresh_description=True)
112
+
113
+ if persist and new_mode != previous:
114
+ self.pi.append_entry(MODE_ENTRY_TYPE, {"mode": new_mode})
115
+
116
+ def status_text(self) -> str:
117
+ all_tools = self.pi.get_all_tools()
118
+ active_count = sum(1 for t in all_tools if t.active)
119
+ deferred_count = sum(1 for t in all_tools if t.deferred and not t.active)
120
+ return (
121
+ f"Codemode is **{self.mode}** "
122
+ f"(active tools: {active_count}, deferred tools: {deferred_count}, "
123
+ f"require_approval: {self.settings.require_approval}, "
124
+ f"timeout: {self.settings.timeout_seconds:g}s, "
125
+ f"max_tool_calls: {self.settings.max_tool_calls})."
126
+ )
127
+
128
+ def handle_command(self, args: str) -> None:
129
+ tokens = args.strip().lower().split()
130
+ sub = tokens[0] if tokens else "status"
131
+ if sub in ("status", ""):
132
+ self.pi.send_message(self.status_text())
133
+ return
134
+ if sub in ("on", "hybrid"):
135
+ self.apply_mode("hybrid", persist=True)
136
+ self.pi.send_message(f"Codemode enabled (mode: hybrid). {self.status_text()}")
137
+ return
138
+ if sub == "only":
139
+ self.apply_mode("only", persist=True)
140
+ self.pi.send_message(f"Codemode set to only mode. {self.status_text()}")
141
+ return
142
+ if sub == "off":
143
+ self.apply_mode("off", persist=True)
144
+ self.pi.send_message(f"Codemode disabled for this session. {self.status_text()}")
145
+ return
146
+ self.pi.send_message("Usage: /codemode [status|on|hybrid|only|off]")
147
+
148
+
149
+ def activate(pi: ExtensionAPI) -> None:
150
+ """Extension entry point: register codemode, tool_search, and ``/codemode``."""
151
+ settings = CodemodeSettings.from_mapping(pi.get_settings())
152
+ controller = _Controller(pi, settings)
153
+
154
+ if settings.enabled:
155
+ pi.register_tool(create_codemode_tool(pi, controller.runtime, lambda: controller.settings))
156
+ pi.register_tool(create_tool_search_tool(pi))
157
+ controller.tools_registered = True
158
+
159
+ def on_session_start(_event: Any) -> None:
160
+ if not controller.settings.enabled:
161
+ return
162
+ restored: SessionMode | None = None
163
+ for entry in pi.get_custom_entries(MODE_ENTRY_TYPE):
164
+ data = getattr(entry, "data", None)
165
+ if isinstance(data, dict) and data.get("mode") in ("hybrid", "only", "off"):
166
+ restored = data["mode"]
167
+ if restored is not None:
168
+ controller.apply_mode(restored, persist=False)
169
+ elif controller.mode == "only":
170
+ controller.apply_mode("only", persist=False)
171
+ elif controller.mode == "hybrid" and controller.tools_registered:
172
+ controller.ensure_tools_registered(refresh_description=True)
173
+
174
+ pi.on("session_start", on_session_start)
175
+ pi.register_command(
176
+ "codemode",
177
+ description="Inspect or switch codemode (/codemode [status|on|hybrid|only|off])",
178
+ handler=controller.handle_command,
179
+ )
@@ -0,0 +1,95 @@
1
+ """The ``codemode`` tool definition and execution wrapper."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from pydantic import BaseModel, Field
9
+
10
+ from pi_agent_core.extensions.types import ToolDefinition
11
+ from pi_agent_core.types import AgentToolResult, ToolAnnotations
12
+ from pi_codemode.runtime import CodemodeRuntime
13
+ from pi_codemode.settings import CodemodeSettings
14
+ from pi_codemode.signatures import render_codemode_description
15
+
16
+ if TYPE_CHECKING:
17
+ from pi_agent_core.extensions import ExtensionAPI
18
+
19
+ CODEMODE_PROMPT_SNIPPET = (
20
+ "Execute an async Python script in a sandboxed child process (resource limits and audit hook) "
21
+ "to orchestrate multiple tool calls, filter outputs locally, and discover deferred tools"
22
+ )
23
+
24
+ CODEMODE_PROMPT_GUIDELINE = (
25
+ "Prefer `codemode` when an operation needs multiple read/search/edit/MCP steps or large "
26
+ "intermediate output filtering so only the final distilled result enters context; "
27
+ "always prefer `read`, `grep`, `find`, `ls` or `bash` directly for trivial single-step checks."
28
+ )
29
+
30
+
31
+ class CodemodeParams(BaseModel):
32
+ code: str = Field(
33
+ description=(
34
+ "Async Python script body (no markdown fences). Supports top-level `await`, "
35
+ "`return`, or a trailing expression. Call session tools via `await tools.<name>(...)` "
36
+ "or `await call_tool(name, ...)`, and inspect deferred tools with `search_tools(...)`."
37
+ )
38
+ )
39
+ timeout_ms: int | None = Field(
40
+ default=None,
41
+ ge=1000,
42
+ le=600_000,
43
+ description="Optional wall-clock timeout override in milliseconds.",
44
+ )
45
+
46
+
47
+ def create_codemode_tool(
48
+ pi: ExtensionAPI,
49
+ runtime: CodemodeRuntime,
50
+ get_settings: Callable[[], CodemodeSettings],
51
+ *,
52
+ description: str | None = None,
53
+ ) -> ToolDefinition:
54
+ """Create the ``codemode`` ``ToolDefinition``."""
55
+ settings = get_settings()
56
+ annotations: ToolAnnotations | None = (
57
+ None if settings.require_approval else {"destructiveHint": False, "openWorldHint": False}
58
+ )
59
+
60
+ async def execute(
61
+ tool_call_id: str,
62
+ params: CodemodeParams,
63
+ signal: Any | None = None,
64
+ on_update: Any | None = None,
65
+ ) -> AgentToolResult:
66
+ return await runtime.execute(
67
+ tool_call_id,
68
+ params.code,
69
+ timeout_ms=params.timeout_ms,
70
+ signal=signal,
71
+ on_update=on_update,
72
+ )
73
+
74
+ return ToolDefinition(
75
+ name="codemode",
76
+ description=description
77
+ or (
78
+ "Execute an async Python script in a sandboxed child process (resource limits and "
79
+ "audit hook) to orchestrate multiple tools (`await tools.<name>(...)`, `ALL_TOOLS`, "
80
+ "`search_tools()`, `describe_tool()`, `parallel()`, `text()`, `image()`, `print()`)."
81
+ ),
82
+ parameters=CodemodeParams,
83
+ execute=execute,
84
+ label="Codemode",
85
+ prompt_snippet=CODEMODE_PROMPT_SNIPPET,
86
+ prompt_guidelines=[CODEMODE_PROMPT_GUIDELINE],
87
+ annotations=annotations,
88
+ )
89
+
90
+
91
+ def build_codemode_description(
92
+ pi: ExtensionAPI, *, direct_names: frozenset[str] = frozenset()
93
+ ) -> str:
94
+ """Render live ``codemode`` description from the current harness tools."""
95
+ return render_codemode_description(pi.get_all_tools(), direct_names=direct_names)