intern-agent 0.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.
- intern_agent/__init__.py +2 -0
- intern_agent/__main__.py +5 -0
- intern_agent/adapters/__init__.py +41 -0
- intern_agent/adapters/claude_code.py +22 -0
- intern_agent/adapters/codex.py +235 -0
- intern_agent/adapters/generic.py +57 -0
- intern_agent/agentenv.py +60 -0
- intern_agent/capture.py +165 -0
- intern_agent/cli.py +823 -0
- intern_agent/config.py +100 -0
- intern_agent/counters.py +136 -0
- intern_agent/detect.py +125 -0
- intern_agent/distill.py +540 -0
- intern_agent/doctor.py +180 -0
- intern_agent/entry.py +137 -0
- intern_agent/evaluate.py +283 -0
- intern_agent/events.py +88 -0
- intern_agent/export.py +119 -0
- intern_agent/frontmatter.py +53 -0
- intern_agent/fsutil.py +80 -0
- intern_agent/guard.py +609 -0
- intern_agent/hooks.py +218 -0
- intern_agent/implicit.py +433 -0
- intern_agent/integrity.py +122 -0
- intern_agent/lesson.py +159 -0
- intern_agent/lifecycle.py +226 -0
- intern_agent/llm.py +112 -0
- intern_agent/lock.py +42 -0
- intern_agent/migrate.py +165 -0
- intern_agent/prompts/distill.md +33 -0
- intern_agent/prompts/eval_arm.md +9 -0
- intern_agent/prompts/eval_judge.md +24 -0
- intern_agent/redact.py +98 -0
- intern_agent/report.py +178 -0
- intern_agent/retrieve.py +267 -0
- intern_agent/review.py +78 -0
- intern_agent/rules.py +468 -0
- intern_agent/store.py +110 -0
- intern_agent/textsim.py +60 -0
- intern_agent/toml_lite.py +186 -0
- intern_agent/toolcache.py +43 -0
- intern_agent/transcript.py +648 -0
- intern_agent/trust.py +50 -0
- intern_agent-0.1.0.dist-info/METADATA +242 -0
- intern_agent-0.1.0.dist-info/RECORD +49 -0
- intern_agent-0.1.0.dist-info/WHEEL +5 -0
- intern_agent-0.1.0.dist-info/entry_points.txt +2 -0
- intern_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
- intern_agent-0.1.0.dist-info/top_level.txt +1 -0
intern_agent/__init__.py
ADDED
intern_agent/__main__.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Agent adapters: the only code that knows a particular agent's hook format (spec K1).
|
|
2
|
+
|
|
3
|
+
The core (hooks.py, guard.py, capture.py, retrieve.py) works on one **canonical hook input**, a JSON
|
|
4
|
+
object with Claude Code's field names because that adapter came first:
|
|
5
|
+
|
|
6
|
+
{"session_id": str, "cwd": str, "prompt": str, # user-prompt
|
|
7
|
+
"tool_name": str, "tool_input": object, # pre-tool
|
|
8
|
+
"transcript_path": str | null, # read only by the claude-code adapter path
|
|
9
|
+
"agent_action": str, "outside": bool, "tool": str, "paths": [str]} # optional, from the adapter
|
|
10
|
+
|
|
11
|
+
and answers with canonical output: ``""`` for nothing, or Claude Code's ``hookSpecificOutput`` JSON
|
|
12
|
+
(``additionalContext`` for added context, ``permissionDecision`` ``ask``/``deny`` with a reason). Each
|
|
13
|
+
adapter has two pure functions:
|
|
14
|
+
|
|
15
|
+
- ``normalize(event, data) -> dict``: the agent's hook input to canonical input. It may read the agent's
|
|
16
|
+
own session file to fill ``agent_action``, ``outside``, ``tool`` and ``paths`` (what the agent did in the
|
|
17
|
+
turn the user is reacting to).
|
|
18
|
+
- ``render(event, out) -> str``: canonical output to what the agent's hook runner expects. An adapter
|
|
19
|
+
whose agent cannot "ask" turns ask into deny: a guard never fails open.
|
|
20
|
+
|
|
21
|
+
``intern hook <event> --agent claude-code|codex|generic`` picks one; claude-code is the default and its
|
|
22
|
+
adapter changes nothing, so existing installs behave exactly as before.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from types import ModuleType
|
|
27
|
+
|
|
28
|
+
AGENTS = ("claude-code", "codex", "generic")
|
|
29
|
+
DEFAULT = "claude-code"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def get(name: str) -> ModuleType:
|
|
33
|
+
if name == "claude-code":
|
|
34
|
+
from . import claude_code as module
|
|
35
|
+
elif name == "codex":
|
|
36
|
+
from . import codex as module
|
|
37
|
+
elif name == "generic":
|
|
38
|
+
from . import generic as module
|
|
39
|
+
else:
|
|
40
|
+
raise ValueError(f"unknown agent {name!r}; use one of {', '.join(AGENTS)}")
|
|
41
|
+
return module
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Claude Code: the canonical format is Claude Code's own, so input and output pass through unchanged.
|
|
2
|
+
|
|
3
|
+
What is Claude Code specific beyond the field names stays where it was and is used only on this path:
|
|
4
|
+
transcript.py reads ``~/.claude/projects/<cwd slug>/<session>.jsonl`` (the turn before a correction, the
|
|
5
|
+
human message that verifies it), implicit.py reads rejections, repeated failures and file edits from it
|
|
6
|
+
at Stop, and both trust a transcript only when ``CLAUDE_CODE_SESSION_ID`` (set by Claude Code in hook
|
|
7
|
+
processes) matches the hook's ``session_id``.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any, Dict
|
|
12
|
+
|
|
13
|
+
NAME = "claude-code"
|
|
14
|
+
READS_TRANSCRIPT = True
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def normalize(event: str, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
18
|
+
return data
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def render(event: str, out: str) -> str:
|
|
22
|
+
return out
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""Codex CLI: hooks from ``hooks.json`` (or ``[hooks]`` in ``config.toml``) and its rollout files.
|
|
2
|
+
|
|
3
|
+
Verified against the Codex hooks documentation (developers.openai.com/codex/hooks) and the generated
|
|
4
|
+
schemas in github.com/openai/codex (``codex-rs/hooks/schema/generated``), 2026-11-28:
|
|
5
|
+
|
|
6
|
+
- Every hook gets one JSON object on stdin with ``session_id``, ``transcript_path``, ``cwd``,
|
|
7
|
+
``hook_event_name``; ``UserPromptSubmit`` adds ``prompt``, ``PreToolUse`` adds ``tool_name`` and
|
|
8
|
+
``tool_input``. Shell calls (including unified exec) arrive as ``Bash``, file edits as ``apply_patch``,
|
|
9
|
+
both with ``tool_input.command``; MCP tools as ``mcp__server__tool``.
|
|
10
|
+
- Output uses the same ``hookSpecificOutput`` shape as Claude Code: ``additionalContext`` for
|
|
11
|
+
UserPromptSubmit and PreToolUse, ``permissionDecision: "deny"`` for PreToolUse. The schema lists
|
|
12
|
+
``ask`` too, but the documentation describes only deny (and allow with ``updatedInput``), so this
|
|
13
|
+
adapter turns every ask into a deny that says why: an unsupported answer must not let the call run.
|
|
14
|
+
- ``Stop`` expects JSON on stdout when it exits 0; this adapter prints ``{}`` when it has nothing to say.
|
|
15
|
+
- Hosted tools such as web search run no PreToolUse hook, and the docs call tool hooks "a useful
|
|
16
|
+
guardrail, not a complete enforcement boundary". The guard covers what reaches the hook, no more.
|
|
17
|
+
|
|
18
|
+
Rollout files (``$CODEX_HOME/sessions/YYYY/MM/DD/rollout-<time>-<session id>.jsonl``) are, per the docs,
|
|
19
|
+
"not a stable interface for hooks". This reader was written from the record shapes of Codex CLI 0.166
|
|
20
|
+
(observed, not documented): ``{"type": "response_item", "payload": {...}}`` where the payload is a
|
|
21
|
+
``message`` (``role`` user, assistant or developer; ``content`` items ``input_text`` / ``output_text``),
|
|
22
|
+
a ``function_call`` (``name``, ``arguments`` as a JSON string), a ``custom_tool_call`` (``name``,
|
|
23
|
+
``input`` as text), a ``local_shell_call`` (``action.command`` as a list) or a ``web_search_call``.
|
|
24
|
+
Codex also writes its own context into user messages (``<environment_context>``, the AGENTS.md text);
|
|
25
|
+
those are not the person. Anything it does not recognise counts as outside content (fail closed).
|
|
26
|
+
|
|
27
|
+
Trust: nothing in a Codex hook process ties the hook to its rollout file the way
|
|
28
|
+
``CLAUDE_CODE_SESSION_ID`` does for Claude Code, so a correction captured here is never ``verified``;
|
|
29
|
+
its lesson waits as untrusted until a person runs ``intern approve <id>``. The rollout is read only for
|
|
30
|
+
context (what the agent did, whether it read outside content), and only from under the sessions folder.
|
|
31
|
+
"""
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import json
|
|
35
|
+
import os
|
|
36
|
+
import re
|
|
37
|
+
import shlex
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
40
|
+
|
|
41
|
+
from .. import transcript
|
|
42
|
+
|
|
43
|
+
NAME = "codex"
|
|
44
|
+
READS_TRANSCRIPT = False
|
|
45
|
+
SHELL_TOOLS = {"shell", "exec_command", "local_shell", "container.exec", "shell_command", "Bash"}
|
|
46
|
+
INJECTED = ("<environment_context>", "<user_instructions>", "# AGENTS.md", "<subagent_notification>",
|
|
47
|
+
"<turn_aborted>", "<user_shell_command>")
|
|
48
|
+
ASK_AS_DENY = ("intern would ask a person before this call, and Codex hooks cannot ask, so it is denied. "
|
|
49
|
+
"If you mean it, run it yourself in your own terminal. Reason: ")
|
|
50
|
+
# Header lines the way apply_patch reads them: surrounding blanks and spacing do not matter.
|
|
51
|
+
_PATCH_PATH = re.compile(r"^\s*\*\*\*\s*(?:(?:Add|Update|Delete)\s+File|Move\s+to)\s*:\s*(.+?)\s*$", re.M | re.I)
|
|
52
|
+
_PATCH_HEADER = re.compile(r"^\s*\*\*\*", re.M)
|
|
53
|
+
_SESSION = re.compile(r"[A-Za-z0-9_.-]{1,128}")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def codex_home() -> Path:
|
|
57
|
+
return Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex").expanduser()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def patch_paths(text: str) -> List[str]:
|
|
61
|
+
"""The files an ``apply_patch`` patch adds, updates, deletes or moves to, in order, without repeats."""
|
|
62
|
+
out: List[str] = []
|
|
63
|
+
for path in _PATCH_PATH.findall(text or ""):
|
|
64
|
+
if path not in out:
|
|
65
|
+
out.append(path)
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _command(value: Any) -> str:
|
|
70
|
+
if isinstance(value, list):
|
|
71
|
+
return shlex.join(str(part) for part in value)
|
|
72
|
+
return str(value or "")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def canonical_tool(name: str, tool_input: Any) -> Tuple[str, Any]:
|
|
76
|
+
"""A Codex tool call as the core sees it: shell calls are ``Bash`` with a string ``command``, patches
|
|
77
|
+
are ``Edit`` with every file in ``paths`` (the first also as ``file_path``) and the patch as
|
|
78
|
+
``new_string``, so the guard checks every file and rules see the new text."""
|
|
79
|
+
data = tool_input if isinstance(tool_input, dict) else {}
|
|
80
|
+
if name == "apply_patch":
|
|
81
|
+
patch = str(data.get("command") or data.get("input") or data.get("patch") or
|
|
82
|
+
(tool_input if isinstance(tool_input, str) else ""))
|
|
83
|
+
paths = patch_paths(patch)
|
|
84
|
+
data_out = {"file_path": paths[0] if paths else "", "paths": paths, "new_string": patch}
|
|
85
|
+
if not paths and _PATCH_HEADER.search(patch):
|
|
86
|
+
data_out["unparsed"] = True # a patch whose files intern cannot name: the guard asks
|
|
87
|
+
return "Edit", data_out
|
|
88
|
+
if name in SHELL_TOOLS:
|
|
89
|
+
command = data.get("command") if "command" in data else data.get("cmd")
|
|
90
|
+
if command is None and isinstance(tool_input, (str, list)):
|
|
91
|
+
command = tool_input
|
|
92
|
+
text = _command(command)
|
|
93
|
+
if "apply_patch" in text and _PATCH_HEADER.search(text):
|
|
94
|
+
# apply_patch fed a heredoc through the shell writes files like the apply_patch tool does. The
|
|
95
|
+
# call stays a shell call (every shell check still runs); the guard also checks these paths.
|
|
96
|
+
paths = patch_paths(text)
|
|
97
|
+
return "Bash", {"command": text, "paths": paths, **({} if paths else {"unparsed": True}),
|
|
98
|
+
**({"workdir": data["workdir"]} if data.get("workdir") else {})}
|
|
99
|
+
return "Bash", {"command": _command(command), **({"workdir": data["workdir"]} if data.get("workdir") else {})}
|
|
100
|
+
return name, tool_input
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# ---- the rollout file -------------------------------------------------------------------------------
|
|
104
|
+
def safe_rollout(path: Any, session_id: Any) -> Optional[Path]:
|
|
105
|
+
"""``path`` resolved, when it is a ``rollout-*.jsonl`` file under ``$CODEX_HOME/sessions`` whose name
|
|
106
|
+
ends with this session's id; else None."""
|
|
107
|
+
if not isinstance(path, str) or not path or not isinstance(session_id, str) or not _SESSION.fullmatch(session_id):
|
|
108
|
+
return None
|
|
109
|
+
try:
|
|
110
|
+
resolved = Path(os.path.realpath(Path(path).expanduser()))
|
|
111
|
+
resolved.relative_to(Path(os.path.realpath(codex_home() / "sessions")))
|
|
112
|
+
except (OSError, ValueError):
|
|
113
|
+
return None
|
|
114
|
+
if not (resolved.name.startswith("rollout-") and resolved.name.endswith(f"{session_id}.jsonl")):
|
|
115
|
+
return None
|
|
116
|
+
return resolved if resolved.is_file() else None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _texts(payload: Dict[str, Any], kinds: Tuple[str, ...]) -> str:
|
|
120
|
+
content = payload.get("content")
|
|
121
|
+
if isinstance(content, str):
|
|
122
|
+
return content
|
|
123
|
+
if not isinstance(content, list):
|
|
124
|
+
return ""
|
|
125
|
+
return "\n".join(str(item.get("text") or "") for item in content
|
|
126
|
+
if isinstance(item, dict) and item.get("type") in kinds)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def is_human(payload: Dict[str, Any]) -> bool:
|
|
130
|
+
if payload.get("type") != "message" or payload.get("role") != "user":
|
|
131
|
+
return False
|
|
132
|
+
text = _texts(payload, ("input_text", "text")).lstrip()
|
|
133
|
+
return bool(text) and not text.startswith(INJECTED)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _call(payload: Dict[str, Any]) -> Optional[Tuple[str, Any]]:
|
|
137
|
+
kind = payload.get("type")
|
|
138
|
+
if kind == "function_call":
|
|
139
|
+
try:
|
|
140
|
+
arguments = json.loads(str(payload.get("arguments") or "{}"))
|
|
141
|
+
except ValueError:
|
|
142
|
+
arguments = {"raw": str(payload.get("arguments"))[:200]}
|
|
143
|
+
return canonical_tool(str(payload.get("name") or "?"), arguments)
|
|
144
|
+
if kind == "custom_tool_call":
|
|
145
|
+
name = str(payload.get("name") or "?")
|
|
146
|
+
text = str(payload.get("input") or "")
|
|
147
|
+
return canonical_tool(name, {"input": text} if name != "apply_patch" else {"command": text})
|
|
148
|
+
if kind == "local_shell_call":
|
|
149
|
+
action = payload.get("action") if isinstance(payload.get("action"), dict) else {}
|
|
150
|
+
return "Bash", {"command": _command(action.get("command"))}
|
|
151
|
+
if kind == "web_search_call":
|
|
152
|
+
return "WebSearch", {}
|
|
153
|
+
if kind in ("tool_search_call", "image_generation_call", "computer_call", "mcp_call"):
|
|
154
|
+
return kind, {}
|
|
155
|
+
return None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def last_turn(path: Path) -> transcript.AgentTurn:
|
|
159
|
+
"""The agent's last turn in a rollout file: tools, files, last words, and whether it read outside
|
|
160
|
+
content. A human message with nothing after it (the prompt being submitted) is skipped."""
|
|
161
|
+
turn = transcript.AgentTurn()
|
|
162
|
+
items: List[Tuple[str, Any]] = [] # ("call", (name, input)) or ("text", str), newest first
|
|
163
|
+
cwd: Optional[str] = None
|
|
164
|
+
for record in transcript._records_backwards(path):
|
|
165
|
+
payload = record.get("payload") if isinstance(record.get("payload"), dict) else {}
|
|
166
|
+
if record.get("type") in ("turn_context", "session_meta") and isinstance(payload.get("cwd"), str):
|
|
167
|
+
cwd = cwd or payload["cwd"]
|
|
168
|
+
if record.get("type") != "response_item":
|
|
169
|
+
continue
|
|
170
|
+
if is_human(payload):
|
|
171
|
+
if items:
|
|
172
|
+
break
|
|
173
|
+
continue
|
|
174
|
+
call = _call(payload)
|
|
175
|
+
if call is not None:
|
|
176
|
+
items.append(("call", call))
|
|
177
|
+
elif payload.get("type") == "message" and payload.get("role") == "assistant":
|
|
178
|
+
text = _texts(payload, ("output_text", "text"))
|
|
179
|
+
if text.strip():
|
|
180
|
+
items.append(("text", text))
|
|
181
|
+
for kind, value in reversed(items):
|
|
182
|
+
if kind == "text":
|
|
183
|
+
turn.last_text = transcript._short(value, 200)
|
|
184
|
+
continue
|
|
185
|
+
name, tool_input = value
|
|
186
|
+
if name not in turn.tools:
|
|
187
|
+
turn.tools.append(name)
|
|
188
|
+
turn.steps.append(transcript._describe(name, tool_input))
|
|
189
|
+
if isinstance(tool_input, dict):
|
|
190
|
+
for path_value in [tool_input.get("file_path"), *(tool_input.get("paths") or [])]:
|
|
191
|
+
if isinstance(path_value, str) and path_value and path_value not in turn.paths:
|
|
192
|
+
turn.paths.append(path_value)
|
|
193
|
+
turn.outside = turn.outside or transcript.is_outside(name, tool_input, cwd)
|
|
194
|
+
return turn
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def read_turn(path: Any, session_id: Any) -> Optional[transcript.AgentTurn]:
|
|
198
|
+
safe = safe_rollout(path, session_id)
|
|
199
|
+
if safe is None:
|
|
200
|
+
return None
|
|
201
|
+
try:
|
|
202
|
+
return last_turn(safe)
|
|
203
|
+
except OSError:
|
|
204
|
+
return None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# ---- the adapter --------------------------------------------------------------------------------------
|
|
208
|
+
def normalize(event: str, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
209
|
+
out = {key: data[key] for key in ("session_id", "cwd", "prompt") if key in data}
|
|
210
|
+
out["transcript_path"] = None # the Claude Code transcript checks never apply here
|
|
211
|
+
if event == "pre-tool":
|
|
212
|
+
out["tool_name"], out["tool_input"] = canonical_tool(str(data.get("tool_name") or ""), data.get("tool_input"))
|
|
213
|
+
elif event == "user-prompt":
|
|
214
|
+
turn = read_turn(data.get("transcript_path"), data.get("session_id"))
|
|
215
|
+
if turn is not None:
|
|
216
|
+
out.update(agent_action=turn.action, outside=turn.outside, paths=turn.paths[:10],
|
|
217
|
+
tool=turn.tools[-1] if turn.tools else None)
|
|
218
|
+
return out
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def render(event: str, out: str) -> str:
|
|
222
|
+
if event == "stop":
|
|
223
|
+
return out or "{}"
|
|
224
|
+
if not out:
|
|
225
|
+
return ""
|
|
226
|
+
try:
|
|
227
|
+
data = json.loads(out)
|
|
228
|
+
except ValueError:
|
|
229
|
+
return out
|
|
230
|
+
specific = data.get("hookSpecificOutput") if isinstance(data, dict) else None
|
|
231
|
+
if isinstance(specific, dict) and specific.get("permissionDecision") == "ask":
|
|
232
|
+
specific["permissionDecision"] = "deny"
|
|
233
|
+
specific["permissionDecisionReason"] = ASK_AS_DENY + str(specific.get("permissionDecisionReason") or "")
|
|
234
|
+
return json.dumps(data, ensure_ascii=False)
|
|
235
|
+
return out
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Any agent with a hook or plugin system that can run a command and read its stdout.
|
|
2
|
+
|
|
3
|
+
Input (stdin, one JSON object; every field optional):
|
|
4
|
+
|
|
5
|
+
{"session_id": "abc", "cwd": "/repo", "prompt": "no, use pnpm", # user-prompt
|
|
6
|
+
"tool_name": "Bash", "tool_input": {"command": "npm install"}, # pre-tool
|
|
7
|
+
"agent_action": "tools: Bash npm install", "outside": false} # what the agent just did
|
|
8
|
+
|
|
9
|
+
``session`` and ``tool`` are accepted for ``session_id`` and ``tool_name``. Name a shell tool ``Bash``
|
|
10
|
+
with ``tool_input.command`` and a file edit ``Edit``/``Write`` with ``tool_input.file_path`` to get the
|
|
11
|
+
guard's checks. No transcript is read: a correction from this path is never ``verified``, so its lesson
|
|
12
|
+
waits as untrusted until a person runs ``intern approve <id>``.
|
|
13
|
+
|
|
14
|
+
Output (stdout; nothing when there is nothing to say):
|
|
15
|
+
|
|
16
|
+
{"context": "<lessons to add to the model's context>"}
|
|
17
|
+
{"decision": "deny" | "ask", "reason": "..."}
|
|
18
|
+
|
|
19
|
+
The caller must treat a decision as binding and a crash or unreadable output as "stop": the guard is
|
|
20
|
+
fail-closed only if the caller is too.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
from typing import Any, Dict
|
|
26
|
+
|
|
27
|
+
NAME = "generic"
|
|
28
|
+
READS_TRANSCRIPT = False
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def normalize(event: str, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
32
|
+
out: Dict[str, Any] = {"transcript_path": None}
|
|
33
|
+
out["session_id"] = data.get("session_id", data.get("session"))
|
|
34
|
+
for key in ("cwd", "prompt", "tool_input", "agent_action", "paths"):
|
|
35
|
+
if key in data:
|
|
36
|
+
out[key] = data[key]
|
|
37
|
+
out["tool_name"] = data.get("tool_name", data.get("tool"))
|
|
38
|
+
out["outside"] = bool(data.get("outside"))
|
|
39
|
+
return {key: value for key, value in out.items() if value is not None or key == "transcript_path"}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def render(event: str, out: str) -> str:
|
|
43
|
+
if not out:
|
|
44
|
+
return ""
|
|
45
|
+
try:
|
|
46
|
+
data = json.loads(out)
|
|
47
|
+
except ValueError:
|
|
48
|
+
return out
|
|
49
|
+
specific = data.get("hookSpecificOutput") if isinstance(data, dict) else None
|
|
50
|
+
if not isinstance(specific, dict):
|
|
51
|
+
return out
|
|
52
|
+
if specific.get("permissionDecision"):
|
|
53
|
+
return json.dumps({"decision": specific["permissionDecision"],
|
|
54
|
+
"reason": specific.get("permissionDecisionReason") or ""}, ensure_ascii=False)
|
|
55
|
+
if specific.get("additionalContext"):
|
|
56
|
+
return json.dumps({"context": specific["additionalContext"]}, ensure_ascii=False)
|
|
57
|
+
return ""
|
intern_agent/agentenv.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Is this process running inside a coding agent's session, and is a person at the keyboard?
|
|
2
|
+
|
|
3
|
+
The agent runs ``intern`` through its shell tool as the same OS user, so intern alone cannot be a security
|
|
4
|
+
boundary against it. The boundary is Claude Code's own permission rules and sandbox (``intern doctor``
|
|
5
|
+
prints them). What this module adds is a speed bump: lessons written from an agent process are stored as
|
|
6
|
+
``untrusted``, and the commands that grant trust refuse to run from one and ask a person on
|
|
7
|
+
``/dev/tty`` to type the id back. Clearing these variables (``env -u``, ``env -i``) or faking a terminal
|
|
8
|
+
(``script``) gets past the check; the built-in guard rules deny those commands and the permission rules
|
|
9
|
+
are what stop the agent for real. An agent can also start ``intern approve`` under a pseudo-terminal it
|
|
10
|
+
controls (``pty.fork``, ``expect``) with a clean environment and type the id itself: an accepted risk,
|
|
11
|
+
written down in docs/security.md. The guard denies such commands when they call intern.
|
|
12
|
+
|
|
13
|
+
A variable counts when it is present at all, even empty:
|
|
14
|
+
|
|
15
|
+
- ``CLAUDE_CODE_SESSION_ID``: documented, set in Claude Code's Bash tool and hook subprocesses.
|
|
16
|
+
- ``CLAUDECODE``: set to ``1`` by Claude Code in its subprocesses (observed, not in the env var docs).
|
|
17
|
+
- ``CODEX_SANDBOX``, ``CODEX_SANDBOX_NETWORK_DISABLED``: set by Codex CLI in sandboxed commands.
|
|
18
|
+
- ``GEMINI_CLI``: set to ``1`` by Gemini CLI in its shell tool.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import os
|
|
23
|
+
from typing import IO, Callable, Mapping, Optional, Tuple
|
|
24
|
+
|
|
25
|
+
AGENT_ENV = ("CLAUDE_CODE_SESSION_ID", "CLAUDECODE", "CODEX_SANDBOX", "CODEX_SANDBOX_NETWORK_DISABLED",
|
|
26
|
+
"GEMINI_CLI")
|
|
27
|
+
REFUSAL = "run this yourself in a separate terminal: an agent session cannot grant trust"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def in_agent(env: Optional[Mapping[str, str]] = None) -> bool:
|
|
31
|
+
env = os.environ if env is None else env
|
|
32
|
+
return any(name in env for name in AGENT_ENV)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def open_tty() -> IO[str]:
|
|
36
|
+
"""The controlling terminal, never stdin: a pipe into stdin is not a person.
|
|
37
|
+
|
|
38
|
+
``open("/dev/tty", "r+")`` fails on macOS (a tty is not seekable, so the buffered read-write object
|
|
39
|
+
raises io.UnsupportedOperation); an unbuffered FileIO under a write-through text wrapper works on
|
|
40
|
+
macOS and Linux."""
|
|
41
|
+
import io
|
|
42
|
+
|
|
43
|
+
return io.TextIOWrapper(io.FileIO("/dev/tty", "r+"), encoding="utf-8", write_through=True)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def person_confirms(question: str, token: str, opener: Optional[Callable[[], IO[str]]] = None) -> Tuple[bool, str]:
|
|
47
|
+
"""(True, "") when a person typed ``token`` on the terminal, else (False, why not)."""
|
|
48
|
+
if in_agent():
|
|
49
|
+
return False, REFUSAL
|
|
50
|
+
try:
|
|
51
|
+
tty = (opener or open_tty)()
|
|
52
|
+
except OSError:
|
|
53
|
+
return False, "no terminal to ask; " + REFUSAL
|
|
54
|
+
with tty:
|
|
55
|
+
tty.write(f"{question}\nType {token} to confirm: ")
|
|
56
|
+
tty.flush()
|
|
57
|
+
answer = tty.readline().strip()
|
|
58
|
+
if answer != token:
|
|
59
|
+
return False, "not confirmed"
|
|
60
|
+
return True, ""
|
intern_agent/capture.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Turn a signal from a capture gate into an event.
|
|
2
|
+
|
|
3
|
+
Gates (spec 6): ``user-correction`` comes from the prompt hook, ``papercut`` from the agent itself (the
|
|
4
|
+
skill tells it when), ``manual`` from a person, ``review-finding`` from a reviewer's report (a review
|
|
5
|
+
agent's finding, through the command line or ``intern import-review``), ``deferred`` for a suggestion
|
|
6
|
+
written to a backlog instead of being done (counted in ``intern report``, never a lesson).
|
|
7
|
+
``implicit-correction`` and repeated-failure papercuts are written by the hooks only (implicit.py). Nothing here calls an LLM: capture must stay cheap enough
|
|
8
|
+
to run on every prompt. Events only record; the distill step decides what becomes a lesson.
|
|
9
|
+
|
|
10
|
+
Provenance (spec K7): the agent can run ``intern`` itself, so stdin is never proof of where a signal came
|
|
11
|
+
from. A user correction is ``verified`` only when its text is the last human message of the session's
|
|
12
|
+
own transcript (transcript.session_transcript checks the session id, the exact path and the config
|
|
13
|
+
folder). That is a defence layer: the agent runs as the same OS user and could write a transcript,
|
|
14
|
+
which the guard's built-in rules and the permission rules from ``intern doctor`` are there to stop. A
|
|
15
|
+
``papercut`` or ``manual`` event from a process inside an agent session (agentenv.py) is marked
|
|
16
|
+
``agent``; its lesson waits as untrusted for ``intern approve``.
|
|
17
|
+
On the command line the transcript is found from ``CLAUDE_CODE_SESSION_ID`` and the real working
|
|
18
|
+
directory only; ``transcript_path``, ``session`` and ``session_id`` in stdin are ignored.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any, Dict, List, Optional
|
|
26
|
+
|
|
27
|
+
from . import agentenv, config, detect, events, transcript
|
|
28
|
+
|
|
29
|
+
CAPTURE_GATES = ("user-correction", "papercut", "manual", "review-finding", "deferred")
|
|
30
|
+
PAPERCUT_KINDS = ("broken-flag", "wrong-doc", "silent-error", "instruction-conflict", "missing-step",
|
|
31
|
+
"env-dependency", "flaky", "slow-or-costly", "repeated-failure", "other")
|
|
32
|
+
SEVERITIES = ("critical", "high", "medium", "low", "info")
|
|
33
|
+
SEVERITY_ALIASES = {"kritik": "critical", "yüksek": "high", "yuksek": "high", "orta": "medium", "düşük": "low",
|
|
34
|
+
"dusuk": "low", "bilgi": "info", "major": "high", "minor": "low", "blocker": "critical",
|
|
35
|
+
"med": "medium", "nit": "low", "note": "info", "bloklayıcı": "critical", "bloklayici": "critical",
|
|
36
|
+
"düzeltilmeli": "medium", "duzeltilmeli": "medium", "öneri": "low", "oneri": "low"}
|
|
37
|
+
REVIEW_FIELDS = ("reviewer", "file", "severity", "finding", "fix")
|
|
38
|
+
DEFERRED_FIELDS = ("item", "reason", "by")
|
|
39
|
+
PAPERCUT_FIELDS = ("target", "kind", "tried", "expected", "happened", "fix", "workaround")
|
|
40
|
+
MANUAL_FIELDS = ("note", "title", "context", "did", "instead", "why", "do", "dont")
|
|
41
|
+
SCOPE_FIELDS = ("tools", "intents")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def project_name(cwd: Optional[str]) -> Optional[str]:
|
|
45
|
+
root = config.find_root(Path(cwd or "."))
|
|
46
|
+
return root.name if root else None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _strings(value: Any) -> List[str]:
|
|
50
|
+
if isinstance(value, str):
|
|
51
|
+
value = [part.strip() for part in value.split(",")]
|
|
52
|
+
return [str(item) for item in value or [] if str(item).strip()] if isinstance(value, list) else []
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _common(data: Dict[str, Any], session: Optional[str]) -> Dict[str, Any]:
|
|
56
|
+
return {"project": data.get("project") or project_name(data.get("cwd")), "session": session,
|
|
57
|
+
"tool": data.get("tool") or data.get("tool_name"), "paths": _strings(data.get("paths"))}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def severity(value: Any) -> str:
|
|
61
|
+
# "🔴 Kritik", "**high**", "[orta]": marks and emoji around the word are dropped
|
|
62
|
+
text = re.sub(r"^[^\w]+|[^\w]+$", "", str(value or "").strip().lower())
|
|
63
|
+
text = SEVERITY_ALIASES.get(text, text)
|
|
64
|
+
if text not in SEVERITIES:
|
|
65
|
+
raise ValueError(f"severity must be one of {', '.join(SEVERITIES)}")
|
|
66
|
+
return text
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def correction(path: Path, prompt: str, found: detect.Detection, data: Dict[str, Any],
|
|
70
|
+
from_hook: bool = True, settings: Optional[Dict[str, Dict[str, Any]]] = None,
|
|
71
|
+
gate: str = "user-correction", signal: Optional[List[str]] = None,
|
|
72
|
+
extra: Optional[Dict[str, Any]] = None, untrusted_reason: Optional[str] = None) -> Dict[str, Any]:
|
|
73
|
+
"""A ``user-correction`` event: the user's words and what the agent did just before them.
|
|
74
|
+
|
|
75
|
+
``from_hook`` is True only for the UserPromptSubmit hook; only that path can be ``verified``. The
|
|
76
|
+
prompt hook also uses this for ``implicit-correction`` (a file the agent changed, changed back), with
|
|
77
|
+
its own ``signal`` and ``extra`` fields; trust is decided the same way, from the prompt, unless
|
|
78
|
+
``untrusted_reason`` says why the event cannot be trusted at all (distill.untrusted honours it).
|
|
79
|
+
"""
|
|
80
|
+
session = data.get("session_id") if from_hook else os.environ.get("CLAUDE_CODE_SESSION_ID")
|
|
81
|
+
fields = _common(data, session)
|
|
82
|
+
declared = str(((settings or config.load()).get("claude") or {}).get("config_dir") or "") if from_hook else ""
|
|
83
|
+
source = transcript.session_transcript(data.get("transcript_path"), data.get("session_id"), data.get("cwd"),
|
|
84
|
+
declared) if from_hook else None
|
|
85
|
+
turn = transcript.read_turn(str(source)) if source else None
|
|
86
|
+
outside = bool(data.get("outside"))
|
|
87
|
+
if turn is not None:
|
|
88
|
+
fields["tool"] = fields["tool"] or (turn.tools[-1] if turn.tools else None)
|
|
89
|
+
fields["paths"] = fields["paths"] or turn.paths
|
|
90
|
+
outside = outside or turn.outside
|
|
91
|
+
provenance: Dict[str, Any] = {"outside": outside, "checked": turn is not None, "verified": False}
|
|
92
|
+
if source is not None:
|
|
93
|
+
last = transcript.human_messages(str(source), limit=1)
|
|
94
|
+
provenance["verified"] = bool(last) and last[0][0].strip() == prompt.strip()
|
|
95
|
+
if not provenance["verified"]:
|
|
96
|
+
provenance["transcript"] = str(source) # the prompt may not be written yet; distill checks again
|
|
97
|
+
if extra:
|
|
98
|
+
fields.update({k: v for k, v in extra.items() if v})
|
|
99
|
+
provenance["source"] = "files"
|
|
100
|
+
if untrusted_reason:
|
|
101
|
+
provenance["untrusted"] = untrusted_reason
|
|
102
|
+
return events.append(path, gate, signal=signal or found.matched,
|
|
103
|
+
score=found.score if gate == "user-correction" else None, excerpt=prompt,
|
|
104
|
+
agent_action=turn.action if turn else data.get("agent_action"),
|
|
105
|
+
provenance=provenance, **fields)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _agent_turn(session: Optional[str]) -> Optional[transcript.AgentTurn]:
|
|
109
|
+
"""What the agent did in this turn and the one before, from the running session's own transcript."""
|
|
110
|
+
return transcript.read_turn(transcript.find_transcript(session, os.getcwd()), turns=2)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def capture(path: Path, gate: str, data: Dict[str, Any], languages: List[str]) -> Dict[str, Any]:
|
|
114
|
+
"""Validate ``data`` for ``gate`` and append the event. Raises ValueError with a message for people.
|
|
115
|
+
|
|
116
|
+
This is the command line path: whoever runs it, its stdin is not trusted (see the module docstring).
|
|
117
|
+
"""
|
|
118
|
+
if gate not in CAPTURE_GATES:
|
|
119
|
+
raise ValueError(f"--gate must be one of {', '.join(CAPTURE_GATES)}")
|
|
120
|
+
data = {k: v for k, v in data.items() if k not in ("transcript_path", "session", "session_id")}
|
|
121
|
+
if gate == "user-correction":
|
|
122
|
+
prompt = str(data.get("prompt") or data.get("excerpt") or "")
|
|
123
|
+
if not prompt.strip():
|
|
124
|
+
raise ValueError("user-correction needs 'prompt'")
|
|
125
|
+
found = detect.detect(prompt, languages)
|
|
126
|
+
if data.get("signal"):
|
|
127
|
+
found.matched = _strings(data.get("signal"))
|
|
128
|
+
return correction(path, prompt, found, data, from_hook=False)
|
|
129
|
+
|
|
130
|
+
session = os.environ.get("CLAUDE_CODE_SESSION_ID")
|
|
131
|
+
fields = _common(data, session)
|
|
132
|
+
turn = _agent_turn(session)
|
|
133
|
+
outside = bool(data.get("outside")) or bool(turn and turn.outside)
|
|
134
|
+
if gate == "review-finding":
|
|
135
|
+
text = {name: str(data[name]) for name in REVIEW_FIELDS if data.get(name)}
|
|
136
|
+
if not text.get("finding", "").strip():
|
|
137
|
+
raise ValueError("review-finding needs 'finding'")
|
|
138
|
+
text["severity"] = severity(data.get("severity") or "info")
|
|
139
|
+
text.setdefault("reviewer", "review")
|
|
140
|
+
line = data.get("line")
|
|
141
|
+
if line not in (None, ""):
|
|
142
|
+
if not str(line).strip().isdigit():
|
|
143
|
+
raise ValueError("line must be a whole number")
|
|
144
|
+
text["line"] = str(int(str(line).strip()))
|
|
145
|
+
if text.get("file") and not fields["paths"]:
|
|
146
|
+
fields["paths"] = [text["file"]]
|
|
147
|
+
elif gate == "deferred":
|
|
148
|
+
text = {name: str(data[name]) for name in DEFERRED_FIELDS if data.get(name)}
|
|
149
|
+
if not text.get("item", "").strip():
|
|
150
|
+
raise ValueError("deferred needs 'item'")
|
|
151
|
+
elif gate == "papercut":
|
|
152
|
+
missing = [name for name in ("target", "kind", "happened") if not str(data.get(name) or "").strip()]
|
|
153
|
+
if missing:
|
|
154
|
+
raise ValueError(f"papercut needs {', '.join(missing)}")
|
|
155
|
+
if data["kind"] not in PAPERCUT_KINDS:
|
|
156
|
+
raise ValueError(f"kind must be one of {', '.join(PAPERCUT_KINDS)}")
|
|
157
|
+
text = {name: str(data[name]) for name in PAPERCUT_FIELDS if data.get(name)}
|
|
158
|
+
else:
|
|
159
|
+
text = {name: str(data[name]) for name in MANUAL_FIELDS if data.get(name)}
|
|
160
|
+
if not (text.get("note") or text.get("title")):
|
|
161
|
+
raise ValueError("manual needs 'note' or 'title'")
|
|
162
|
+
scope = {name: _strings(data.get(name)) for name in SCOPE_FIELDS}
|
|
163
|
+
provenance = {"outside": outside, "checked": turn is not None, "agent": agentenv.in_agent()}
|
|
164
|
+
return events.append(path, gate, provenance=provenance, agent_action=turn.action if turn else None,
|
|
165
|
+
**fields, **text, **{k: v for k, v in scope.items() if v})
|