|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Process Pi Coding Agent tool_result events into episodic memory entries. |
| 3 | +
|
| 4 | +Pi exposes a project-local extension system. The adapter installs |
| 5 | +`.pi/extensions/memory-hook.ts`, which forwards every `tool_result` event to |
| 6 | +this script via stdin. We normalize Pi's event shape into the same |
| 7 | +tool_input/tool_response structure used by the Claude Code hook so the |
| 8 | +importance scoring, reflection generation, and success classification stay |
| 9 | +consistent across harnesses. |
| 10 | +""" |
| 11 | +import json |
| 12 | +import os |
| 13 | +import sys |
| 14 | + |
| 15 | +HERE = os.path.dirname(os.path.abspath(__file__)) |
| 16 | +AGENT_ROOT = os.path.abspath(os.path.join(HERE, "..", "..")) |
| 17 | + |
| 18 | +sys.path.insert(0, os.path.join(AGENT_ROOT, "harness")) |
| 19 | +sys.path.insert(0, os.path.join(AGENT_ROOT, "tools")) |
| 20 | + |
| 21 | +from hooks.post_execution import log_execution # noqa: E402 |
| 22 | +from hooks.on_failure import on_failure # noqa: E402 |
| 23 | +import hooks.claude_code_post_tool as cc # noqa: E402 |
| 24 | + |
| 25 | + |
| 26 | +_PI_TO_CANONICAL = { |
| 27 | + "bash": "Bash", |
| 28 | + "edit": "Edit", |
| 29 | + "write": "Write", |
| 30 | + "read": "Read", |
| 31 | + "grep": "Grep", |
| 32 | + "find": "Find", |
| 33 | + "ls": "LS", |
| 34 | + "task": "Task", |
| 35 | + "todowrite": "TodoWrite", |
| 36 | + "webfetch": "WebFetch", |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +def _tool_name(name: str) -> str: |
| 41 | + if not isinstance(name, str): |
| 42 | + return "Unknown" |
| 43 | + lowered = name.strip().lower() |
| 44 | + return _PI_TO_CANONICAL.get(lowered, name[:1].upper() + name[1:]) |
| 45 | + |
| 46 | + |
| 47 | +def _extract_text(content) -> str: |
| 48 | + if isinstance(content, str): |
| 49 | + return content[:500] |
| 50 | + if not isinstance(content, list): |
| 51 | + return "" |
| 52 | + texts = [] |
| 53 | + for item in content: |
| 54 | + if isinstance(item, dict) and item.get("type") == "text": |
| 55 | + text = item.get("text") |
| 56 | + if isinstance(text, str) and text: |
| 57 | + texts.append(text) |
| 58 | + return " ".join(texts)[:500] |
| 59 | + |
| 60 | + |
| 61 | +def _normalize_response(event: dict) -> dict: |
| 62 | + """Map Pi tool_result shape to the Claude hook's response schema.""" |
| 63 | + resp: dict = {"is_error": bool(event.get("isError", False))} |
| 64 | + details = event.get("details") |
| 65 | + content = event.get("content") |
| 66 | + |
| 67 | + if isinstance(details, dict): |
| 68 | + if isinstance(details.get("output"), str): |
| 69 | + resp["output"] = details["output"][:500] |
| 70 | + if isinstance(details.get("stdout"), str): |
| 71 | + resp["stdout"] = details["stdout"][:500] |
| 72 | + if isinstance(details.get("stderr"), str): |
| 73 | + resp["stderr"] = details["stderr"][:300] |
| 74 | + if isinstance(details.get("error"), str): |
| 75 | + resp["error"] = details["error"][:300] |
| 76 | + if isinstance(details.get("text"), str): |
| 77 | + resp["text"] = details["text"][:500] |
| 78 | + if "exitCode" in details: |
| 79 | + resp["exit_code"] = details.get("exitCode") |
| 80 | + if "cancelled" in details: |
| 81 | + resp["interrupted"] = bool(details.get("cancelled")) |
| 82 | + if "truncated" in details: |
| 83 | + resp["truncated"] = bool(details.get("truncated")) |
| 84 | + resp["details"] = details |
| 85 | + |
| 86 | + text = _extract_text(content) |
| 87 | + if text: |
| 88 | + resp.setdefault("output", text) |
| 89 | + resp["content"] = [{"type": "text", "text": text}] |
| 90 | + |
| 91 | + if not any(k in resp for k in ("output", "stdout", "text", "content")): |
| 92 | + if isinstance(details, str): |
| 93 | + resp["output"] = details[:500] |
| 94 | + elif details is not None: |
| 95 | + resp["output"] = json.dumps(details, default=str)[:500] |
| 96 | + |
| 97 | + return resp |
| 98 | + |
| 99 | + |
| 100 | +def main() -> None: |
| 101 | + try: |
| 102 | + raw = sys.stdin.read() |
| 103 | + payload = json.loads(raw) if raw.strip() else {} |
| 104 | + except (json.JSONDecodeError, OSError): |
| 105 | + payload = {} |
| 106 | + |
| 107 | + tool_name = _tool_name(payload.get("tool_name") or "Unknown") |
| 108 | + tool_input = payload.get("tool_input") or {} |
| 109 | + if not isinstance(tool_input, dict): |
| 110 | + tool_input = {"raw": str(tool_input)} |
| 111 | + tool_response = _normalize_response(payload) |
| 112 | + |
| 113 | + success = cc._is_success(tool_name, tool_input, tool_response) |
| 114 | + importance = cc._importance(tool_name, json.dumps(tool_input)) |
| 115 | + action = cc._action_label(tool_name, tool_input) |
| 116 | + reflection = cc._reflection(tool_name, tool_input, tool_response, success) |
| 117 | + detail = cc._detail(tool_name, tool_input, tool_response, success) |
| 118 | + |
| 119 | + pscore = cc._pain_score(importance, success) |
| 120 | + if success: |
| 121 | + log_execution( |
| 122 | + skill_name="pi", |
| 123 | + action=action, |
| 124 | + result=detail, |
| 125 | + success=True, |
| 126 | + reflection=reflection, |
| 127 | + importance=importance, |
| 128 | + confidence=0.7, |
| 129 | + pain_score=pscore, |
| 130 | + ) |
| 131 | + else: |
| 132 | + on_failure( |
| 133 | + skill_name="pi", |
| 134 | + action=action, |
| 135 | + error=reflection, |
| 136 | + context=detail, |
| 137 | + confidence=0.7, |
| 138 | + importance=importance, |
| 139 | + pain_score=pscore, |
| 140 | + ) |
| 141 | + |
| 142 | + |
| 143 | +if __name__ == "__main__": |
| 144 | + main() |
0 commit comments