pi-codemode-py 1.1.0__py3-none-any.whl
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.
- pi_codemode/__init__.py +179 -0
- pi_codemode/codemode_tool.py +95 -0
- pi_codemode/runtime.py +409 -0
- pi_codemode/settings.py +81 -0
- pi_codemode/signatures.py +194 -0
- pi_codemode/tool_search_tool.py +132 -0
- pi_codemode_py-1.1.0.dist-info/METADATA +35 -0
- pi_codemode_py-1.1.0.dist-info/RECORD +10 -0
- pi_codemode_py-1.1.0.dist-info/WHEEL +4 -0
- pi_codemode_py-1.1.0.dist-info/entry_points.txt +2 -0
pi_codemode/__init__.py
ADDED
|
@@ -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)
|
pi_codemode/runtime.py
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"""Codemode script runtime: RW/sequential gate lock, inner tool invocation, and formatting."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import time
|
|
10
|
+
import uuid
|
|
11
|
+
from collections.abc import AsyncIterator, Callable, Sequence
|
|
12
|
+
from typing import TYPE_CHECKING, Any
|
|
13
|
+
|
|
14
|
+
from pydantic import ValidationError
|
|
15
|
+
|
|
16
|
+
from pi_agent_core.sandbox import (
|
|
17
|
+
CodemodeScriptError,
|
|
18
|
+
SandboxError,
|
|
19
|
+
SandboxLimits,
|
|
20
|
+
ScriptSandbox,
|
|
21
|
+
)
|
|
22
|
+
from pi_agent_core.types import AgentToolResult
|
|
23
|
+
from pi_codemode.settings import CodemodeSettings
|
|
24
|
+
from pi_codemode.signatures import (
|
|
25
|
+
FORBIDDEN_INNER_TOOLS,
|
|
26
|
+
build_tools_catalog,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from pi_agent_core.extensions import ExtensionAPI
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
_PROGRESS_INTERVAL_S = 0.15
|
|
35
|
+
_MAX_PROGRESS_LINES = 20
|
|
36
|
+
_MAX_IMAGES_PER_RESULT = 8
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ToolError(RuntimeError):
|
|
40
|
+
"""Raised in host so the sandbox wire carries ``etype='ToolError'`` and ``tool_name``."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, message: str, *, tool_name: str = "") -> None:
|
|
43
|
+
super().__init__(message)
|
|
44
|
+
self.tool_name = tool_name
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ToolPermissionError(ToolError):
|
|
48
|
+
"""Raised in host when permission or policy blocks an inner tool call."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class _GateLock:
|
|
52
|
+
"""Writer-preferring RW lock for inner tool gating under parallel vs sequential policies."""
|
|
53
|
+
|
|
54
|
+
def __init__(self) -> None:
|
|
55
|
+
self._cond = asyncio.Condition()
|
|
56
|
+
self._readers = 0
|
|
57
|
+
self._writer = False
|
|
58
|
+
self._waiting_writers = 0
|
|
59
|
+
|
|
60
|
+
@contextlib.asynccontextmanager
|
|
61
|
+
async def reader(self) -> AsyncIterator[None]:
|
|
62
|
+
async with self._cond:
|
|
63
|
+
while self._writer or self._waiting_writers > 0:
|
|
64
|
+
await self._cond.wait()
|
|
65
|
+
self._readers += 1
|
|
66
|
+
try:
|
|
67
|
+
yield
|
|
68
|
+
finally:
|
|
69
|
+
async with self._cond:
|
|
70
|
+
self._readers -= 1
|
|
71
|
+
if self._readers == 0:
|
|
72
|
+
self._cond.notify_all()
|
|
73
|
+
|
|
74
|
+
@contextlib.asynccontextmanager
|
|
75
|
+
async def writer(self) -> AsyncIterator[None]:
|
|
76
|
+
async with self._cond:
|
|
77
|
+
self._waiting_writers += 1
|
|
78
|
+
acquired = False
|
|
79
|
+
try:
|
|
80
|
+
while self._writer or self._readers > 0:
|
|
81
|
+
await self._cond.wait()
|
|
82
|
+
self._writer = True
|
|
83
|
+
acquired = True
|
|
84
|
+
finally:
|
|
85
|
+
self._waiting_writers -= 1
|
|
86
|
+
if not acquired:
|
|
87
|
+
self._cond.notify_all()
|
|
88
|
+
try:
|
|
89
|
+
yield
|
|
90
|
+
finally:
|
|
91
|
+
async with self._cond:
|
|
92
|
+
self._writer = False
|
|
93
|
+
self._cond.notify_all()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _extract_result_parts(
|
|
97
|
+
result: AgentToolResult,
|
|
98
|
+
) -> tuple[str, dict[str, Any], list[dict[str, str]]]:
|
|
99
|
+
texts: list[str] = []
|
|
100
|
+
images: list[dict[str, str]] = []
|
|
101
|
+
for block in getattr(result, "content", None) or []:
|
|
102
|
+
if isinstance(block, dict):
|
|
103
|
+
btype = block.get("type")
|
|
104
|
+
if btype == "text":
|
|
105
|
+
texts.append(str(block.get("text") or ""))
|
|
106
|
+
elif btype == "image" and len(images) < _MAX_IMAGES_PER_RESULT:
|
|
107
|
+
data = block.get("data")
|
|
108
|
+
mime = block.get("mimeType") or "image/png"
|
|
109
|
+
if isinstance(data, str) and data:
|
|
110
|
+
images.append({"data": data, "mimeType": str(mime)})
|
|
111
|
+
raw_details = getattr(result, "details", None)
|
|
112
|
+
details: dict[str, Any] = {}
|
|
113
|
+
if raw_details is not None:
|
|
114
|
+
try:
|
|
115
|
+
encoded = json.loads(json.dumps(raw_details, default=str))
|
|
116
|
+
if isinstance(encoded, dict):
|
|
117
|
+
details = encoded
|
|
118
|
+
except Exception:
|
|
119
|
+
details = {}
|
|
120
|
+
return "\n".join(texts), details, images
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _summarize_args(args: dict[str, Any]) -> str:
|
|
124
|
+
if "path" in args:
|
|
125
|
+
return str(args["path"])
|
|
126
|
+
if "command" in args:
|
|
127
|
+
cmd = " ".join(str(args["command"]).split())
|
|
128
|
+
return cmd[:60] + ("..." if len(cmd) > 60 else "")
|
|
129
|
+
if "pattern" in args:
|
|
130
|
+
return str(args["pattern"])
|
|
131
|
+
if "query" in args:
|
|
132
|
+
return str(args["query"])
|
|
133
|
+
return ""
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _truncate_utf8(text: str, max_bytes: int) -> tuple[str, bool]:
|
|
137
|
+
encoded = text.encode("utf-8")
|
|
138
|
+
if len(encoded) <= max_bytes:
|
|
139
|
+
return text, False
|
|
140
|
+
return encoded[:max_bytes].decode("utf-8", errors="ignore"), True
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class _CodemodeHost:
|
|
144
|
+
def __init__(
|
|
145
|
+
self,
|
|
146
|
+
*,
|
|
147
|
+
pi: ExtensionAPI,
|
|
148
|
+
catalog: dict[str, dict[str, Any]],
|
|
149
|
+
outer_call_id: str,
|
|
150
|
+
run_id: str,
|
|
151
|
+
cwd: str,
|
|
152
|
+
signal: Any | None,
|
|
153
|
+
on_update: Callable[[AgentToolResult], Any] | None,
|
|
154
|
+
) -> None:
|
|
155
|
+
self._pi = pi
|
|
156
|
+
self._catalog = catalog
|
|
157
|
+
self._outer_call_id = outer_call_id
|
|
158
|
+
self._run_id = run_id
|
|
159
|
+
self._cwd = cwd
|
|
160
|
+
self._signal = signal
|
|
161
|
+
self._on_update = on_update
|
|
162
|
+
self._gate_lock = _GateLock()
|
|
163
|
+
self._seq = 0
|
|
164
|
+
self._progress_lines: list[str] = []
|
|
165
|
+
self._last_emit = 0.0
|
|
166
|
+
self.tool_call_count = 0
|
|
167
|
+
|
|
168
|
+
def _emit_progress(self, line: str, *, force: bool = False) -> None:
|
|
169
|
+
self._progress_lines.append(line)
|
|
170
|
+
if len(self._progress_lines) > _MAX_PROGRESS_LINES:
|
|
171
|
+
self._progress_lines = self._progress_lines[-_MAX_PROGRESS_LINES:]
|
|
172
|
+
if self._on_update is None:
|
|
173
|
+
return
|
|
174
|
+
now = time.monotonic()
|
|
175
|
+
if not force and (now - self._last_emit) < _PROGRESS_INTERVAL_S:
|
|
176
|
+
return
|
|
177
|
+
self._last_emit = now
|
|
178
|
+
with contextlib.suppress(Exception):
|
|
179
|
+
self._on_update(
|
|
180
|
+
AgentToolResult(
|
|
181
|
+
content=[{"type": "text", "text": "\n".join(self._progress_lines)}],
|
|
182
|
+
details={"codemode_progress": True},
|
|
183
|
+
)
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
async def call_tool(self, tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
|
|
187
|
+
if tool_name in FORBIDDEN_INNER_TOOLS:
|
|
188
|
+
raise ToolPermissionError(
|
|
189
|
+
f"Tool {tool_name!r} cannot be called from inside codemode",
|
|
190
|
+
tool_name=tool_name,
|
|
191
|
+
)
|
|
192
|
+
entry = self._catalog.get(tool_name)
|
|
193
|
+
if entry is None:
|
|
194
|
+
raise ToolError(f"Unknown tool {tool_name!r}", tool_name=tool_name)
|
|
195
|
+
if not isinstance(args, dict):
|
|
196
|
+
raise ToolError(
|
|
197
|
+
f"{tool_name}: arguments must be a dict\nExpected signature: {entry['signature']}",
|
|
198
|
+
tool_name=tool_name,
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
self._seq += 1
|
|
202
|
+
self.tool_call_count += 1
|
|
203
|
+
call_id = f"codemode-{self._run_id}:{self._seq}"
|
|
204
|
+
origin = {
|
|
205
|
+
"kind": "codemode",
|
|
206
|
+
"cwd": self._cwd,
|
|
207
|
+
"parent_call_id": self._outer_call_id,
|
|
208
|
+
}
|
|
209
|
+
harmless = bool(entry.get("read_only"))
|
|
210
|
+
need_exclusive = (not harmless) or self._pi.is_sequential_tool_policy
|
|
211
|
+
|
|
212
|
+
arg_preview = _summarize_args(args)
|
|
213
|
+
label = f"{tool_name} {arg_preview}".strip()
|
|
214
|
+
self._emit_progress(f"▸ {label}")
|
|
215
|
+
started = time.monotonic()
|
|
216
|
+
|
|
217
|
+
ctx_mgr = self._gate_lock.writer() if need_exclusive else self._gate_lock.reader()
|
|
218
|
+
try:
|
|
219
|
+
async with ctx_mgr:
|
|
220
|
+
result = await self._pi.invoke_tool(
|
|
221
|
+
call_id,
|
|
222
|
+
tool_name,
|
|
223
|
+
args,
|
|
224
|
+
origin=origin,
|
|
225
|
+
signal=self._signal,
|
|
226
|
+
)
|
|
227
|
+
except PermissionError as exc:
|
|
228
|
+
elapsed = time.monotonic() - started
|
|
229
|
+
self._emit_progress(f"✗ {label} ({elapsed:.2f}s)", force=True)
|
|
230
|
+
raise ToolPermissionError(f"{tool_name}: {exc}", tool_name=tool_name) from exc
|
|
231
|
+
except (ValidationError, ValueError, TypeError, KeyError) as exc:
|
|
232
|
+
elapsed = time.monotonic() - started
|
|
233
|
+
self._emit_progress(f"✗ {label} ({elapsed:.2f}s)", force=True)
|
|
234
|
+
raise ToolError(
|
|
235
|
+
f"{tool_name}: {exc}\nExpected signature: {entry['signature']}",
|
|
236
|
+
tool_name=tool_name,
|
|
237
|
+
) from exc
|
|
238
|
+
except Exception as exc:
|
|
239
|
+
elapsed = time.monotonic() - started
|
|
240
|
+
self._emit_progress(f"✗ {label} ({elapsed:.2f}s)", force=True)
|
|
241
|
+
raise ToolError(f"{tool_name}: {exc}", tool_name=tool_name) from exc
|
|
242
|
+
|
|
243
|
+
elapsed = time.monotonic() - started
|
|
244
|
+
text, details, images = _extract_result_parts(result)
|
|
245
|
+
if details.get("isError") is True or details.get("is_error") is True:
|
|
246
|
+
self._emit_progress(f"✗ {label} ({elapsed:.2f}s)", force=True)
|
|
247
|
+
raise ToolError(text or f"{tool_name} returned an error", tool_name=tool_name)
|
|
248
|
+
|
|
249
|
+
self._emit_progress(f"✓ {label} ({elapsed:.2f}s)")
|
|
250
|
+
return {"text": text, "details": details, "images": images}
|
|
251
|
+
|
|
252
|
+
def log(self, message: str) -> None:
|
|
253
|
+
return None
|
|
254
|
+
|
|
255
|
+
def output(self, kind: str, data: Any) -> None:
|
|
256
|
+
return None
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _format_outcome(
|
|
260
|
+
*,
|
|
261
|
+
outputs: Sequence[tuple[str, Any]],
|
|
262
|
+
result: Any,
|
|
263
|
+
logs: Sequence[str],
|
|
264
|
+
tool_call_count: int,
|
|
265
|
+
max_output_kb: int,
|
|
266
|
+
layers: tuple[str, ...],
|
|
267
|
+
) -> AgentToolResult:
|
|
268
|
+
text_parts: list[str] = [str(data) for kind, data in outputs if kind == "text" and str(data)]
|
|
269
|
+
images: list[dict[str, str]] = [
|
|
270
|
+
{"type": "image", "data": data["data"], "mimeType": data["mimeType"]}
|
|
271
|
+
for kind, data in outputs
|
|
272
|
+
if kind == "image" and isinstance(data, dict)
|
|
273
|
+
]
|
|
274
|
+
|
|
275
|
+
if result is not None:
|
|
276
|
+
if isinstance(result, str):
|
|
277
|
+
text_parts.append(result)
|
|
278
|
+
else:
|
|
279
|
+
text_parts.append(json.dumps(result, ensure_ascii=False, indent=2, default=str))
|
|
280
|
+
|
|
281
|
+
if logs:
|
|
282
|
+
console = "\n".join(logs)
|
|
283
|
+
text_parts.append(f"<console_output>\n{console}\n</console_output>")
|
|
284
|
+
|
|
285
|
+
combined = "\n\n".join(text_parts)
|
|
286
|
+
if not combined and not images:
|
|
287
|
+
combined = "(codemode finished with no output)"
|
|
288
|
+
|
|
289
|
+
max_bytes = max(1, max_output_kb) * 1024
|
|
290
|
+
combined, truncated = _truncate_utf8(combined, max_bytes)
|
|
291
|
+
if truncated:
|
|
292
|
+
combined += (
|
|
293
|
+
f"\n\n[Output truncated to {max_output_kb} KiB; filter or summarize inside the "
|
|
294
|
+
"codemode script before returning.]"
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
content: list[Any] = [{"type": "text", "text": combined}]
|
|
298
|
+
content.extend(images)
|
|
299
|
+
return AgentToolResult(
|
|
300
|
+
content=content,
|
|
301
|
+
details={
|
|
302
|
+
"tool_calls": tool_call_count,
|
|
303
|
+
"truncated": truncated,
|
|
304
|
+
"layers": list(layers),
|
|
305
|
+
},
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
class CodemodeRuntime:
|
|
310
|
+
"""Executes codemode scripts inside the shared ``ScriptSandbox``."""
|
|
311
|
+
|
|
312
|
+
def __init__(
|
|
313
|
+
self,
|
|
314
|
+
pi: ExtensionAPI,
|
|
315
|
+
get_settings: Callable[[], CodemodeSettings],
|
|
316
|
+
*,
|
|
317
|
+
audit_hook: bool = True,
|
|
318
|
+
) -> None:
|
|
319
|
+
self._pi = pi
|
|
320
|
+
self._get_settings = get_settings
|
|
321
|
+
self._audit_hook = audit_hook
|
|
322
|
+
|
|
323
|
+
async def execute(
|
|
324
|
+
self,
|
|
325
|
+
tool_call_id: str,
|
|
326
|
+
script: str,
|
|
327
|
+
*,
|
|
328
|
+
timeout_ms: int | None = None,
|
|
329
|
+
signal: Any | None = None,
|
|
330
|
+
on_update: Callable[[AgentToolResult], Any] | None = None,
|
|
331
|
+
) -> AgentToolResult:
|
|
332
|
+
if signal and getattr(signal, "aborted", False):
|
|
333
|
+
raise RuntimeError("Codemode execution aborted")
|
|
334
|
+
|
|
335
|
+
settings = self._get_settings()
|
|
336
|
+
wall_seconds = settings.timeout_seconds
|
|
337
|
+
if timeout_ms is not None:
|
|
338
|
+
wall_seconds = min(settings.timeout_seconds, max(1.0, float(timeout_ms) / 1000.0))
|
|
339
|
+
|
|
340
|
+
try:
|
|
341
|
+
cwd = self._pi.cwd
|
|
342
|
+
except RuntimeError:
|
|
343
|
+
cwd = "."
|
|
344
|
+
|
|
345
|
+
tools_info = self._pi.get_all_tools()
|
|
346
|
+
catalog = build_tools_catalog(tools_info)
|
|
347
|
+
run_id = uuid.uuid4().hex[:10]
|
|
348
|
+
host = _CodemodeHost(
|
|
349
|
+
pi=self._pi,
|
|
350
|
+
catalog=catalog,
|
|
351
|
+
outer_call_id=tool_call_id,
|
|
352
|
+
run_id=run_id,
|
|
353
|
+
cwd=cwd,
|
|
354
|
+
signal=signal,
|
|
355
|
+
on_update=on_update,
|
|
356
|
+
)
|
|
357
|
+
limits = SandboxLimits(
|
|
358
|
+
memory_bytes=256 * 1024 * 1024,
|
|
359
|
+
cpu_seconds=30,
|
|
360
|
+
wall_seconds=wall_seconds,
|
|
361
|
+
open_files=64,
|
|
362
|
+
max_message_bytes=4 * 1024 * 1024,
|
|
363
|
+
max_inflight_calls=16,
|
|
364
|
+
max_log_lines=2000,
|
|
365
|
+
max_log_chars=256 * 1024,
|
|
366
|
+
)
|
|
367
|
+
sandbox = ScriptSandbox(limits, audit_hook=self._audit_hook)
|
|
368
|
+
|
|
369
|
+
run_task = asyncio.ensure_future(
|
|
370
|
+
sandbox.run_codemode(
|
|
371
|
+
script,
|
|
372
|
+
tools_meta=catalog,
|
|
373
|
+
host=host,
|
|
374
|
+
max_tool_calls=settings.max_tool_calls,
|
|
375
|
+
)
|
|
376
|
+
)
|
|
377
|
+
abort_task: asyncio.Task[None] | None = None
|
|
378
|
+
if signal is not None and hasattr(signal, "wait_aborted"):
|
|
379
|
+
|
|
380
|
+
async def _watch_abort() -> None:
|
|
381
|
+
await signal.wait_aborted()
|
|
382
|
+
if not run_task.done():
|
|
383
|
+
run_task.cancel()
|
|
384
|
+
|
|
385
|
+
abort_task = asyncio.ensure_future(_watch_abort())
|
|
386
|
+
|
|
387
|
+
try:
|
|
388
|
+
outcome = await run_task
|
|
389
|
+
except asyncio.CancelledError as exc:
|
|
390
|
+
raise RuntimeError("Codemode execution aborted") from exc
|
|
391
|
+
except CodemodeScriptError as exc:
|
|
392
|
+
loc = f" (line {exc.line})" if exc.line is not None else ""
|
|
393
|
+
raise RuntimeError(f"Codemode failed{loc}: {exc.error_type}: {exc}") from exc
|
|
394
|
+
except SandboxError as exc:
|
|
395
|
+
raise RuntimeError(f"Codemode failed: {exc}") from exc
|
|
396
|
+
finally:
|
|
397
|
+
if abort_task is not None:
|
|
398
|
+
abort_task.cancel()
|
|
399
|
+
with contextlib.suppress(BaseException):
|
|
400
|
+
await abort_task
|
|
401
|
+
|
|
402
|
+
return _format_outcome(
|
|
403
|
+
outputs=outcome.outputs,
|
|
404
|
+
result=outcome.result,
|
|
405
|
+
logs=outcome.logs,
|
|
406
|
+
tool_call_count=host.tool_call_count,
|
|
407
|
+
max_output_kb=settings.max_output_kb,
|
|
408
|
+
layers=outcome.layers,
|
|
409
|
+
)
|
pi_codemode/settings.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Settings for ``pi-codemode`` (passed via ``AgentHarness.set_extension_settings``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any, Literal
|
|
8
|
+
|
|
9
|
+
CodemodeMode = Literal["hybrid", "only"]
|
|
10
|
+
|
|
11
|
+
DEFAULT_TIMEOUT_SECONDS = 120.0
|
|
12
|
+
MIN_TIMEOUT_SECONDS = 1.0
|
|
13
|
+
MAX_TIMEOUT_SECONDS = 600.0
|
|
14
|
+
DEFAULT_MAX_TOOL_CALLS = 100
|
|
15
|
+
MIN_MAX_TOOL_CALLS = 1
|
|
16
|
+
MAX_MAX_TOOL_CALLS = 500
|
|
17
|
+
DEFAULT_MAX_OUTPUT_KB = 64
|
|
18
|
+
MIN_MAX_OUTPUT_KB = 4
|
|
19
|
+
MAX_MAX_OUTPUT_KB = 512
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class CodemodeSettings:
|
|
24
|
+
enabled: bool = True
|
|
25
|
+
mode: CodemodeMode = "hybrid"
|
|
26
|
+
defer_mcp: bool = True
|
|
27
|
+
require_approval: bool = True
|
|
28
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS
|
|
29
|
+
max_tool_calls: int = DEFAULT_MAX_TOOL_CALLS
|
|
30
|
+
max_output_kb: int = DEFAULT_MAX_OUTPUT_KB
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def from_mapping(cls, raw: Mapping[str, Any] | None) -> CodemodeSettings:
|
|
34
|
+
if not isinstance(raw, Mapping):
|
|
35
|
+
return cls()
|
|
36
|
+
enabled = raw["enabled"] if isinstance(raw.get("enabled"), bool) else True
|
|
37
|
+
mode_raw = raw.get("mode")
|
|
38
|
+
mode: CodemodeMode = mode_raw if mode_raw in ("hybrid", "only") else "hybrid"
|
|
39
|
+
defer_mcp = raw["defer_mcp"] if isinstance(raw.get("defer_mcp"), bool) else True
|
|
40
|
+
require_approval = (
|
|
41
|
+
raw["require_approval"] if isinstance(raw.get("require_approval"), bool) else True
|
|
42
|
+
)
|
|
43
|
+
timeout_raw = raw.get("timeout_seconds", DEFAULT_TIMEOUT_SECONDS)
|
|
44
|
+
if (
|
|
45
|
+
isinstance(timeout_raw, (int, float))
|
|
46
|
+
and not isinstance(timeout_raw, bool)
|
|
47
|
+
and MIN_TIMEOUT_SECONDS <= float(timeout_raw) <= MAX_TIMEOUT_SECONDS
|
|
48
|
+
):
|
|
49
|
+
timeout_seconds = float(timeout_raw)
|
|
50
|
+
else:
|
|
51
|
+
timeout_seconds = DEFAULT_TIMEOUT_SECONDS
|
|
52
|
+
|
|
53
|
+
calls_raw = raw.get("max_tool_calls", DEFAULT_MAX_TOOL_CALLS)
|
|
54
|
+
if (
|
|
55
|
+
isinstance(calls_raw, int)
|
|
56
|
+
and not isinstance(calls_raw, bool)
|
|
57
|
+
and MIN_MAX_TOOL_CALLS <= calls_raw <= MAX_MAX_TOOL_CALLS
|
|
58
|
+
):
|
|
59
|
+
max_tool_calls = calls_raw
|
|
60
|
+
else:
|
|
61
|
+
max_tool_calls = DEFAULT_MAX_TOOL_CALLS
|
|
62
|
+
|
|
63
|
+
kb_raw = raw.get("max_output_kb", DEFAULT_MAX_OUTPUT_KB)
|
|
64
|
+
if (
|
|
65
|
+
isinstance(kb_raw, int)
|
|
66
|
+
and not isinstance(kb_raw, bool)
|
|
67
|
+
and MIN_MAX_OUTPUT_KB <= kb_raw <= MAX_MAX_OUTPUT_KB
|
|
68
|
+
):
|
|
69
|
+
max_output_kb = kb_raw
|
|
70
|
+
else:
|
|
71
|
+
max_output_kb = DEFAULT_MAX_OUTPUT_KB
|
|
72
|
+
|
|
73
|
+
return cls(
|
|
74
|
+
enabled=enabled,
|
|
75
|
+
mode=mode,
|
|
76
|
+
defer_mcp=defer_mcp,
|
|
77
|
+
require_approval=require_approval,
|
|
78
|
+
timeout_seconds=timeout_seconds,
|
|
79
|
+
max_tool_calls=max_tool_calls,
|
|
80
|
+
max_output_kb=max_output_kb,
|
|
81
|
+
)
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Tool identifier normalization, Python signature stubs, and deferred namespace grouping."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import keyword
|
|
6
|
+
import re
|
|
7
|
+
from collections import Counter
|
|
8
|
+
from collections.abc import Mapping, Sequence
|
|
9
|
+
from collections.abc import Set as AbstractSet
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from pi_agent_core.extensions.types import ToolInfo
|
|
14
|
+
|
|
15
|
+
FORBIDDEN_INNER_TOOLS: frozenset[str] = frozenset({"codemode", "workflow", "tool_search"})
|
|
16
|
+
_NON_IDENT_RE = re.compile(r"[^a-zA-Z0-9_]")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def is_harmless_annotations(annotations: Mapping[str, Any] | None) -> bool:
|
|
20
|
+
"""True when MCP-style annotations declare read-only or local non-destructive notes."""
|
|
21
|
+
if not isinstance(annotations, Mapping):
|
|
22
|
+
return False
|
|
23
|
+
if annotations.get("readOnlyHint") is True:
|
|
24
|
+
return True
|
|
25
|
+
return annotations.get("destructiveHint") is False and annotations.get("openWorldHint") is False
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def normalize_tool_identifier(name: str, taken: set[str]) -> str:
|
|
29
|
+
"""Turn *name* into a unique valid Python identifier for ``tools.<ident>``."""
|
|
30
|
+
base = _NON_IDENT_RE.sub("_", name)
|
|
31
|
+
if not base or base[0].isdigit():
|
|
32
|
+
base = f"_{base}"
|
|
33
|
+
if keyword.iskeyword(base):
|
|
34
|
+
base = f"{base}_"
|
|
35
|
+
candidate = base
|
|
36
|
+
suffix = 2
|
|
37
|
+
while candidate in taken:
|
|
38
|
+
candidate = f"{base}_{suffix}"
|
|
39
|
+
suffix += 1
|
|
40
|
+
taken.add(candidate)
|
|
41
|
+
return candidate
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _schema_type(schema: Mapping[str, Any]) -> str:
|
|
45
|
+
if not isinstance(schema, Mapping):
|
|
46
|
+
return "Any"
|
|
47
|
+
if "enum" in schema and isinstance(schema["enum"], list) and schema["enum"]:
|
|
48
|
+
vals = ", ".join(repr(v) for v in schema["enum"][:5])
|
|
49
|
+
if len(schema["enum"]) > 5:
|
|
50
|
+
vals += ", ..."
|
|
51
|
+
return f"Literal[{vals}]"
|
|
52
|
+
if "anyOf" in schema and isinstance(schema["anyOf"], list):
|
|
53
|
+
parts: list[str] = []
|
|
54
|
+
for sub in schema["anyOf"]:
|
|
55
|
+
if isinstance(sub, Mapping):
|
|
56
|
+
if sub.get("type") == "null":
|
|
57
|
+
if "None" not in parts:
|
|
58
|
+
parts.append("None")
|
|
59
|
+
else:
|
|
60
|
+
t = _schema_type(sub)
|
|
61
|
+
if t not in parts:
|
|
62
|
+
parts.append(t)
|
|
63
|
+
return " | ".join(parts) if parts else "Any"
|
|
64
|
+
raw_type = schema.get("type")
|
|
65
|
+
if isinstance(raw_type, list):
|
|
66
|
+
mapped = [_schema_type({"type": item}) if item != "null" else "None" for item in raw_type]
|
|
67
|
+
return " | ".join(dict.fromkeys(mapped)) or "Any"
|
|
68
|
+
mapping = {
|
|
69
|
+
"string": "str",
|
|
70
|
+
"integer": "int",
|
|
71
|
+
"number": "float",
|
|
72
|
+
"boolean": "bool",
|
|
73
|
+
"object": "dict[str, Any]",
|
|
74
|
+
"null": "None",
|
|
75
|
+
}
|
|
76
|
+
if raw_type == "array":
|
|
77
|
+
items = schema.get("items")
|
|
78
|
+
inner = _schema_type(items) if isinstance(items, Mapping) else "Any"
|
|
79
|
+
return f"list[{inner}]"
|
|
80
|
+
if isinstance(raw_type, str):
|
|
81
|
+
return mapping.get(raw_type, "Any")
|
|
82
|
+
return "Any"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def render_python_signature(
|
|
86
|
+
call_name: str, parameters: Mapping[str, Any] | None, *, read_only: bool = False
|
|
87
|
+
) -> str:
|
|
88
|
+
"""Render a compact one-line async Python signature stub from a JSON Schema."""
|
|
89
|
+
props = parameters.get("properties") if isinstance(parameters, Mapping) else None
|
|
90
|
+
required_raw = parameters.get("required") if isinstance(parameters, Mapping) else None
|
|
91
|
+
required = set(required_raw) if isinstance(required_raw, list) else set()
|
|
92
|
+
params_parts: list[str] = []
|
|
93
|
+
if isinstance(props, Mapping) and props:
|
|
94
|
+
ordered = [k for k in props if k in required] + [k for k in props if k not in required]
|
|
95
|
+
for key in ordered:
|
|
96
|
+
prop_schema = props[key]
|
|
97
|
+
ptype = _schema_type(prop_schema if isinstance(prop_schema, Mapping) else {})
|
|
98
|
+
if key in required:
|
|
99
|
+
params_parts.append(f"{key}: {ptype}")
|
|
100
|
+
else:
|
|
101
|
+
if "None" not in ptype.split(" | "):
|
|
102
|
+
ptype = f"{ptype} | None"
|
|
103
|
+
params_parts.append(f"{key}: {ptype} = None")
|
|
104
|
+
sig_args = f"*, {', '.join(params_parts)}" if params_parts else ""
|
|
105
|
+
tag = " [readOnly]" if read_only else ""
|
|
106
|
+
return f"async def {call_name}({sig_args}) -> ToolText{tag}"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def build_tools_catalog(tools: Sequence[ToolInfo]) -> dict[str, dict[str, Any]]:
|
|
110
|
+
"""Build the ``ALL_TOOLS`` metadata dictionary exposed to codemode scripts."""
|
|
111
|
+
taken: set[str] = set(FORBIDDEN_INNER_TOOLS)
|
|
112
|
+
catalog: dict[str, dict[str, Any]] = {}
|
|
113
|
+
for info in tools:
|
|
114
|
+
if info.name in FORBIDDEN_INNER_TOOLS:
|
|
115
|
+
continue
|
|
116
|
+
if not info.active and not info.deferred:
|
|
117
|
+
continue
|
|
118
|
+
call_name = normalize_tool_identifier(info.name, taken)
|
|
119
|
+
read_only = is_harmless_annotations(info.annotations)
|
|
120
|
+
params = dict(info.parameters) if isinstance(info.parameters, Mapping) else {}
|
|
121
|
+
sig = render_python_signature(call_name, params, read_only=read_only)
|
|
122
|
+
desc = " ".join((info.description or "").split())
|
|
123
|
+
if len(desc) > 280:
|
|
124
|
+
desc = desc[:277].rstrip() + "..."
|
|
125
|
+
catalog[info.name] = {
|
|
126
|
+
"call_name": call_name,
|
|
127
|
+
"description": desc,
|
|
128
|
+
"signature": sig,
|
|
129
|
+
"parameters": params,
|
|
130
|
+
"deferred": bool(info.deferred),
|
|
131
|
+
"active": bool(info.active),
|
|
132
|
+
"read_only": read_only,
|
|
133
|
+
}
|
|
134
|
+
return catalog
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def namespace_for_tool(name: str) -> str:
|
|
138
|
+
"""Group deferred tool names (e.g. ``mcp__github__list_issues`` -> ``mcp__github``)."""
|
|
139
|
+
if name.startswith("mcp__"):
|
|
140
|
+
parts = name.split("__", 2)
|
|
141
|
+
if len(parts) >= 2 and parts[1]:
|
|
142
|
+
return f"mcp__{parts[1]}"
|
|
143
|
+
if "__" in name:
|
|
144
|
+
prefix = name.split("__", 1)[0]
|
|
145
|
+
if prefix:
|
|
146
|
+
return prefix
|
|
147
|
+
return "other"
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def group_deferred_namespaces(names: Sequence[str]) -> list[tuple[str, int]]:
|
|
151
|
+
"""Count deferred tools by namespace in stable sorted order."""
|
|
152
|
+
counts = Counter(namespace_for_tool(name) for name in names)
|
|
153
|
+
return sorted(counts.items())
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def render_codemode_description(
|
|
157
|
+
tools: Sequence[ToolInfo], *, direct_names: AbstractSet[str] = frozenset()
|
|
158
|
+
) -> str:
|
|
159
|
+
"""Build a concise ``codemode`` tool description with direct stubs & deferred counts."""
|
|
160
|
+
catalog = build_tools_catalog(tools)
|
|
161
|
+
direct_lines: list[str] = []
|
|
162
|
+
deferred_names: list[str] = []
|
|
163
|
+
for name, entry in catalog.items():
|
|
164
|
+
if entry["deferred"] and not entry["active"] and name not in direct_names:
|
|
165
|
+
deferred_names.append(name)
|
|
166
|
+
else:
|
|
167
|
+
direct_lines.append(f"- {entry['signature']}")
|
|
168
|
+
|
|
169
|
+
lines = [
|
|
170
|
+
"Execute an async Python script in a sandboxed child process (resource limits and "
|
|
171
|
+
"audit hook) to orchestrate multiple tools, filter large outputs locally, and return "
|
|
172
|
+
"only the distilled result.",
|
|
173
|
+
"Pass raw Python code without markdown fences (supports top-level `await`, `return`, "
|
|
174
|
+
"or a trailing expression).",
|
|
175
|
+
"",
|
|
176
|
+
"Sandbox globals:",
|
|
177
|
+
"- `await tools.<name>(**kwargs)` or `await tools.<name>(args_dict)` — call a tool",
|
|
178
|
+
"- `await call_tool(raw_name, args_dict=None, **kwargs)` — call by exact tool name",
|
|
179
|
+
"- `ALL_TOOLS`, `search_tools(query, limit=20)`, `describe_tool(name)` — inspect tools",
|
|
180
|
+
"- `await parallel(*coros, concurrency=8)` — bounded concurrent execution",
|
|
181
|
+
"- `text(...)`, `image(...)`, `print(...)` — emit text, images, or <console_output>",
|
|
182
|
+
"- Tool errors raise `ToolError` / `ToolPermissionError` (catchable in script)",
|
|
183
|
+
]
|
|
184
|
+
if direct_lines:
|
|
185
|
+
lines.extend(["", "Direct tools on `tools`:", *direct_lines])
|
|
186
|
+
if deferred_names:
|
|
187
|
+
groups = group_deferred_namespaces(deferred_names)
|
|
188
|
+
lines.append("")
|
|
189
|
+
lines.append("Deferred tools (inspect via `search_tools(query)` / `describe_tool(name)`):")
|
|
190
|
+
for ns, count in groups:
|
|
191
|
+
noun = "tool" if count == 1 else "tools"
|
|
192
|
+
prefix = f"{ns}__*" if ns != "other" else "other"
|
|
193
|
+
lines.append(f"- {prefix} ({count} {noun})")
|
|
194
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""The ``tool_search`` tool definition for discovering and activating deferred tools."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
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
|
|
12
|
+
from pi_codemode.signatures import FORBIDDEN_INNER_TOOLS, render_python_signature
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from pi_agent_core.extensions import ExtensionAPI
|
|
16
|
+
|
|
17
|
+
TOOL_SEARCH_PROMPT_SNIPPET = (
|
|
18
|
+
"Search deferred or registered tools by keyword or /regex/ and optionally load them "
|
|
19
|
+
"into the active tool list"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ToolSearchParams(BaseModel):
|
|
24
|
+
query: str = Field(
|
|
25
|
+
default="*",
|
|
26
|
+
description=(
|
|
27
|
+
"Search query: space-separated keywords (AND match), `/regex/`, or `*` to list all "
|
|
28
|
+
"deferred tools."
|
|
29
|
+
),
|
|
30
|
+
)
|
|
31
|
+
limit: int = Field(
|
|
32
|
+
default=10,
|
|
33
|
+
ge=1,
|
|
34
|
+
le=50,
|
|
35
|
+
description="Maximum number of matching tools to return.",
|
|
36
|
+
)
|
|
37
|
+
activate: bool = Field(
|
|
38
|
+
default=True,
|
|
39
|
+
description=(
|
|
40
|
+
"When true, promote matching deferred tools into the session's active tools so they "
|
|
41
|
+
"can be called directly on subsequent turns."
|
|
42
|
+
),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def create_tool_search_tool(pi: ExtensionAPI) -> ToolDefinition:
|
|
47
|
+
"""Create the ``tool_search`` ``ToolDefinition``."""
|
|
48
|
+
|
|
49
|
+
async def execute(
|
|
50
|
+
tool_call_id: str,
|
|
51
|
+
params: ToolSearchParams,
|
|
52
|
+
signal: Any | None = None,
|
|
53
|
+
on_update: Any | None = None,
|
|
54
|
+
) -> AgentToolResult:
|
|
55
|
+
tools = [
|
|
56
|
+
t
|
|
57
|
+
for t in pi.get_all_tools()
|
|
58
|
+
if t.name not in FORBIDDEN_INNER_TOOLS and (t.active or t.deferred)
|
|
59
|
+
]
|
|
60
|
+
q = params.query.strip()
|
|
61
|
+
pattern: re.Pattern[str] | None = None
|
|
62
|
+
if len(q) >= 2 and q.startswith("/") and q.endswith("/"):
|
|
63
|
+
try:
|
|
64
|
+
pattern = re.compile(q[1:-1], re.IGNORECASE)
|
|
65
|
+
except re.error as exc:
|
|
66
|
+
raise ValueError(f"Invalid regular expression {q!r}: {exc}") from exc
|
|
67
|
+
tokens = [] if (not q or q == "*" or pattern is not None) else q.lower().split()
|
|
68
|
+
|
|
69
|
+
matches = []
|
|
70
|
+
for info in tools:
|
|
71
|
+
haystack = f"{info.name} {info.description or ''}"
|
|
72
|
+
if not q or q == "*":
|
|
73
|
+
ok = bool(info.deferred)
|
|
74
|
+
elif pattern is not None:
|
|
75
|
+
ok = bool(pattern.search(haystack))
|
|
76
|
+
else:
|
|
77
|
+
low = haystack.lower()
|
|
78
|
+
ok = all(tok in low for tok in tokens)
|
|
79
|
+
if ok:
|
|
80
|
+
matches.append(info)
|
|
81
|
+
if len(matches) >= params.limit:
|
|
82
|
+
break
|
|
83
|
+
|
|
84
|
+
activated: list[str] = []
|
|
85
|
+
if params.activate and matches:
|
|
86
|
+
to_activate = [m.name for m in matches if not m.active]
|
|
87
|
+
if to_activate:
|
|
88
|
+
activated = pi.activate_tools(to_activate)
|
|
89
|
+
|
|
90
|
+
if not matches:
|
|
91
|
+
text = f"No tools matched query {params.query!r}."
|
|
92
|
+
else:
|
|
93
|
+
lines = [f"Matched {len(matches)} tool(s):"]
|
|
94
|
+
for m in matches:
|
|
95
|
+
sig = render_python_signature(
|
|
96
|
+
m.name,
|
|
97
|
+
m.parameters,
|
|
98
|
+
read_only=bool(m.annotations and m.annotations.get("readOnlyHint") is True),
|
|
99
|
+
)
|
|
100
|
+
status = "active" if (m.active or m.name in activated) else "deferred"
|
|
101
|
+
desc = " ".join((m.description or "").split())
|
|
102
|
+
if len(desc) > 140:
|
|
103
|
+
desc = desc[:137].rstrip() + "..."
|
|
104
|
+
lines.append(f"- `{m.name}` [{status}]: {sig} — {desc}")
|
|
105
|
+
if activated:
|
|
106
|
+
lines.append(f"\nActivated for direct calling: {', '.join(activated)}")
|
|
107
|
+
text = "\n".join(lines)
|
|
108
|
+
|
|
109
|
+
return AgentToolResult(
|
|
110
|
+
content=[{"type": "text", "text": text}],
|
|
111
|
+
details={
|
|
112
|
+
"matched": [m.name for m in matches],
|
|
113
|
+
"activated": activated,
|
|
114
|
+
},
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
return ToolDefinition(
|
|
118
|
+
name="tool_search",
|
|
119
|
+
description=(
|
|
120
|
+
"Discover deferred or registered tools (such as MCP tools) by keyword or /regex/, "
|
|
121
|
+
"optionally activating them for direct tool calling."
|
|
122
|
+
),
|
|
123
|
+
parameters=ToolSearchParams,
|
|
124
|
+
execute=execute,
|
|
125
|
+
label="Tool Search",
|
|
126
|
+
prompt_snippet=TOOL_SEARCH_PROMPT_SNIPPET,
|
|
127
|
+
annotations={
|
|
128
|
+
"readOnlyHint": True,
|
|
129
|
+
"destructiveHint": False,
|
|
130
|
+
"openWorldHint": False,
|
|
131
|
+
},
|
|
132
|
+
)
|
|
@@ -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,10 @@
|
|
|
1
|
+
pi_codemode/__init__.py,sha256=QXIhKb54IXVFJBpe00Poxt9IcmC1yRGob25X5R5tM4k,7493
|
|
2
|
+
pi_codemode/codemode_tool.py,sha256=7GG1hPlwUi1ZTJLX8AVB_N9Bnkd5GtyChjkbO7lr6mY,3390
|
|
3
|
+
pi_codemode/runtime.py,sha256=vNZfgSCuSujmzxf-vtd3FF_GIcidgT0hb0zp0hpzGgE,13825
|
|
4
|
+
pi_codemode/settings.py,sha256=uYSIA56xhJidtpIpufKy-aSSNpwfL8ozOffKhCixYtA,2795
|
|
5
|
+
pi_codemode/signatures.py,sha256=zg6qw-rNA46qRnKqnGItr5swqlS_HJkK8eN4C9-3Mik,8088
|
|
6
|
+
pi_codemode/tool_search_tool.py,sha256=8by6IQoQqXiyWtQSfXr2wmgxFXq39Cxie9H5ZUouIe0,4564
|
|
7
|
+
pi_codemode_py-1.1.0.dist-info/METADATA,sha256=MSlN0PM6rRswvk_0UvgxADnx45EFhhv2r6bdOl9R_Cs,2788
|
|
8
|
+
pi_codemode_py-1.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
pi_codemode_py-1.1.0.dist-info/entry_points.txt,sha256=3gQcCNjQwIG6IIMQmCORGLS5UaTW35BpTTu9yk5L9q0,57
|
|
10
|
+
pi_codemode_py-1.1.0.dist-info/RECORD,,
|