makker 0.3.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.
Files changed (206) hide show
  1. makker/__init__.py +33 -0
  2. makker/__main__.py +23 -0
  3. makker/_version.py +24 -0
  4. makker/agent/__init__.py +0 -0
  5. makker/agent/added_dirs.py +117 -0
  6. makker/agent/approval.py +278 -0
  7. makker/agent/backend.py +160 -0
  8. makker/agent/builder.py +530 -0
  9. makker/agent/capabilities.py +355 -0
  10. makker/agent/context_editing.py +74 -0
  11. makker/agent/memory.py +267 -0
  12. makker/agent/openrouter.py +34 -0
  13. makker/agent/plot_julia.py +786 -0
  14. makker/agent/plot_julia_src.py +806 -0
  15. makker/agent/prompts.py +244 -0
  16. makker/agent/recovery.py +127 -0
  17. makker/agent/summarization.py +163 -0
  18. makker/agent/titling.py +60 -0
  19. makker/agent/tool_output.py +86 -0
  20. makker/agent/tools.py +358 -0
  21. makker/agent/turns.py +431 -0
  22. makker/agent/windows_paths.py +133 -0
  23. makker/approval_preview.py +270 -0
  24. makker/context_panel.py +239 -0
  25. makker/credentials.py +163 -0
  26. makker/display.py +188 -0
  27. makker/eval/__init__.py +22 -0
  28. makker/eval/_gemini_compat.py +65 -0
  29. makker/eval/report.py +475 -0
  30. makker/eval/runconfig.py +91 -0
  31. makker/eval/scorers.py +712 -0
  32. makker/eval/solver.py +295 -0
  33. makker/eval/tasks/__init__.py +1 -0
  34. makker/eval/tasks/_corpus/MiniRes/Project.toml +3 -0
  35. makker/eval/tasks/_corpus/MiniRes/README.md +4 -0
  36. makker/eval/tasks/_corpus/MiniRes/docs/api.md +7 -0
  37. makker/eval/tasks/_corpus/MiniRes/examples/advanced/sweep.jl +8 -0
  38. makker/eval/tasks/_corpus/MiniRes/examples/quickstart.jl +6 -0
  39. makker/eval/tasks/_corpus/MiniRes/src/MiniRes.jl +13 -0
  40. makker/eval/tasks/_corpus/MiniRes/src/grid.jl +8 -0
  41. makker/eval/tasks/_corpus/MiniRes/src/physics/darcy.jl +13 -0
  42. makker/eval/tasks/_corpus/MiniRes/src/physics/wells.jl +15 -0
  43. makker/eval/tasks/_corpus/MiniRes/src/solver/newton.jl +15 -0
  44. makker/eval/tasks/_corpus/__init__.py +54 -0
  45. makker/eval/tasks/api_discovery.py +122 -0
  46. makker/eval/tasks/battmo.py +88 -0
  47. makker/eval/tasks/calibration.py +82 -0
  48. makker/eval/tasks/canary.py +41 -0
  49. makker/eval/tasks/ensembles.py +209 -0
  50. makker/eval/tasks/filesystem.py +290 -0
  51. makker/eval/tasks/filesystem_source.py +80 -0
  52. makker/eval/tasks/fimbul.py +51 -0
  53. makker/eval/tasks/guardrails.py +47 -0
  54. makker/eval/tasks/jutuldarcy.py +139 -0
  55. makker/eval/tasks/mocca.py +90 -0
  56. makker/eval/tasks/plotting.py +111 -0
  57. makker/eval/tasks/search.py +211 -0
  58. makker/eval/tasks/search_source.py +71 -0
  59. makker/eval/tasks/usage.py +138 -0
  60. makker/interfaces/__init__.py +0 -0
  61. makker/interfaces/cli/__init__.py +10 -0
  62. makker/interfaces/cli/_helpers.py +197 -0
  63. makker/interfaces/cli/doctor.py +443 -0
  64. makker/interfaces/cli/eval.py +198 -0
  65. makker/interfaces/cli/init.py +274 -0
  66. makker/interfaces/cli/key.py +117 -0
  67. makker/interfaces/cli/main.py +207 -0
  68. makker/interfaces/cli/review.py +538 -0
  69. makker/interfaces/cli/run.py +412 -0
  70. makker/interfaces/cli/sessions.py +45 -0
  71. makker/interfaces/cli/sysimage.py +223 -0
  72. makker/interfaces/cli/transcript.py +102 -0
  73. makker/interfaces/cli/upgrade.py +369 -0
  74. makker/interfaces/cli/web.py +314 -0
  75. makker/interfaces/server/__init__.py +13 -0
  76. makker/interfaces/server/access.py +148 -0
  77. makker/interfaces/server/app.py +2443 -0
  78. makker/interfaces/server/manager.py +292 -0
  79. makker/interfaces/server/protocol.py +321 -0
  80. makker/interfaces/server/update_helper.py +199 -0
  81. makker/interfaces/server/updates.py +446 -0
  82. makker/interfaces/server/web_dist/assets/index-BcWXsrUW.js +54 -0
  83. makker/interfaces/server/web_dist/assets/index-Cbigi-bs.css +1 -0
  84. makker/interfaces/server/web_dist/index.html +17 -0
  85. makker/interfaces/tui/__init__.py +5 -0
  86. makker/interfaces/tui/app.py +1779 -0
  87. makker/interfaces/tui/approval_menu.py +227 -0
  88. makker/interfaces/tui/commands.py +143 -0
  89. makker/interfaces/tui/model_menu.py +416 -0
  90. makker/interfaces/tui/prompt.py +210 -0
  91. makker/interfaces/tui/tool_display.py +440 -0
  92. makker/interfaces/tui/widgets.py +991 -0
  93. makker/julia/__init__.py +0 -0
  94. makker/julia/precompile.py +120 -0
  95. makker/julia/requirements.py +101 -0
  96. makker/julia/session.py +49 -0
  97. makker/julia/threads.py +126 -0
  98. makker/julia_runtime/Makker/Project.toml +21 -0
  99. makker/julia_runtime/Makker/src/Makker.jl +99 -0
  100. makker/julia_runtime/Makker/src/ensemble.jl +104 -0
  101. makker/julia_runtime/Makker/src/plots.jl +292 -0
  102. makker/julia_runtime/Makker/src/web_views.jl +77 -0
  103. makker/juliakernel/__init__.py +19 -0
  104. makker/juliakernel/config.py +35 -0
  105. makker/juliakernel/connection.py +261 -0
  106. makker/juliakernel/kernel.py +509 -0
  107. makker/juliakernel/result.py +37 -0
  108. makker/juliakernel/server.jl +263 -0
  109. makker/juliakernel/text.py +211 -0
  110. makker/lab/__init__.py +19 -0
  111. makker/lab/fakes.py +744 -0
  112. makker/lab/live.py +225 -0
  113. makker/lab/profile_startup.py +144 -0
  114. makker/lab/profile_turn.py +70 -0
  115. makker/lab/rasterize.py +73 -0
  116. makker/lab/scenarios.py +255 -0
  117. makker/lab/tui.py +194 -0
  118. makker/legacy.py +298 -0
  119. makker/models.py +441 -0
  120. makker/ollama_client.py +177 -0
  121. makker/open_file.py +54 -0
  122. makker/paths.py +205 -0
  123. makker/preview.py +70 -0
  124. makker/py.typed +0 -0
  125. makker/recent_models.py +47 -0
  126. makker/review/__init__.py +40 -0
  127. makker/review/curate.py +135 -0
  128. makker/review/dashboard.py +216 -0
  129. makker/review/dashboard_template.html +384 -0
  130. makker/review/discovery.py +159 -0
  131. makker/review/eval_link.py +81 -0
  132. makker/review/export.py +74 -0
  133. makker/review/findings.py +176 -0
  134. makker/review/issues.py +190 -0
  135. makker/review/prompt.py +195 -0
  136. makker/review/reviewer.py +195 -0
  137. makker/review/server.py +109 -0
  138. makker/review/settings.py +28 -0
  139. makker/session.py +520 -0
  140. makker/session_host.py +706 -0
  141. makker/simulators/README.md +50 -0
  142. makker/simulators/__init__.py +0 -0
  143. makker/simulators/base.py +63 -0
  144. makker/simulators/battmo/__init__.py +3 -0
  145. makker/simulators/battmo/adapter.py +39 -0
  146. makker/simulators/battmo/julia_env/MakkerBattMo/Project.toml +21 -0
  147. makker/simulators/battmo/julia_env/MakkerBattMo/src/MakkerBattMo.jl +43 -0
  148. makker/simulators/battmo/julia_env/Project.toml +34 -0
  149. makker/simulators/battmo/skills/battmo-cycling/SKILL.md +33 -0
  150. makker/simulators/battmo/skills/battmo-overview/SKILL.md +55 -0
  151. makker/simulators/battmo/skills/battmo-plotting/SKILL.md +46 -0
  152. makker/simulators/env_setup.py +1070 -0
  153. makker/simulators/fimbul/__init__.py +3 -0
  154. makker/simulators/fimbul/adapter.py +43 -0
  155. makker/simulators/fimbul/julia_env/MakkerFimbul/Project.toml +23 -0
  156. makker/simulators/fimbul/julia_env/MakkerFimbul/src/MakkerFimbul.jl +89 -0
  157. makker/simulators/fimbul/julia_env/Project.toml +40 -0
  158. makker/simulators/fimbul/skills/fimbul-overview/SKILL.md +72 -0
  159. makker/simulators/fimbul/skills/fimbul-plotting/SKILL.md +69 -0
  160. makker/simulators/jutuldarcy/__init__.py +3 -0
  161. makker/simulators/jutuldarcy/adapter.py +41 -0
  162. makker/simulators/jutuldarcy/julia_env/MakkerJutulDarcy/Project.toml +24 -0
  163. makker/simulators/jutuldarcy/julia_env/MakkerJutulDarcy/src/MakkerJutulDarcy.jl +149 -0
  164. makker/simulators/jutuldarcy/julia_env/Project.toml +37 -0
  165. makker/simulators/jutuldarcy/skills/jutuldarcy-overview/SKILL.md +82 -0
  166. makker/simulators/jutuldarcy/skills/jutuldarcy-plotting/SKILL.md +74 -0
  167. makker/simulators/jutuldarcy/skills/jutuldarcy-wells/SKILL.md +67 -0
  168. makker/simulators/mocca/__init__.py +3 -0
  169. makker/simulators/mocca/adapter.py +40 -0
  170. makker/simulators/mocca/julia_env/MakkerMocca/Project.toml +22 -0
  171. makker/simulators/mocca/julia_env/MakkerMocca/src/MakkerMocca.jl +55 -0
  172. makker/simulators/mocca/julia_env/Project.toml +35 -0
  173. makker/simulators/mocca/skills/mocca-overview/SKILL.md +125 -0
  174. makker/simulators/registry.py +147 -0
  175. makker/simulators/shared_skills/ensembles/SKILL.md +94 -0
  176. makker/simulators/shared_skills/investigation-loop/SKILL.md +101 -0
  177. makker/simulators/shared_skills/julia-and-repl/SKILL.md +93 -0
  178. makker/simulators/shared_skills/plotting-basics/SKILL.md +138 -0
  179. makker/simulators/shared_skills/workspace-and-source/SKILL.md +110 -0
  180. makker/simulators/warmup.py +267 -0
  181. makker/sysimage.py +548 -0
  182. makker/sysimage_build.py +881 -0
  183. makker/tool_labels.py +35 -0
  184. makker/trace/__init__.py +10 -0
  185. makker/trace/log.py +155 -0
  186. makker/trace/messages.py +46 -0
  187. makker/trace/recorder.py +141 -0
  188. makker/trace/schema.py +129 -0
  189. makker/transcript/__init__.py +8 -0
  190. makker/transcript/attempts.py +67 -0
  191. makker/transcript/bundle.py +18 -0
  192. makker/transcript/embed.py +55 -0
  193. makker/transcript/events.py +77 -0
  194. makker/transcript/highlight.py +143 -0
  195. makker/transcript/html.py +1031 -0
  196. makker/transcript/markdown.py +176 -0
  197. makker/transcript/markdown_html.py +65 -0
  198. makker/transcript/report.py +1076 -0
  199. makker/update_check.py +329 -0
  200. makker/user_config.py +51 -0
  201. makker/workspace.py +1170 -0
  202. makker-0.3.0.dist-info/METADATA +157 -0
  203. makker-0.3.0.dist-info/RECORD +206 -0
  204. makker-0.3.0.dist-info/WHEEL +4 -0
  205. makker-0.3.0.dist-info/entry_points.txt +2 -0
  206. makker-0.3.0.dist-info/licenses/LICENSE +21 -0
makker/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ """Makker: an AI agent for computational science."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+
8
+ def _resolve_version() -> str:
9
+ """Best-effort running version, robust across install shapes.
10
+
11
+ Preference order:
12
+ 1. Installed distribution metadata (wheel, ``uv tool install``, editable) —
13
+ the canonical source, derived from git tags by hatch-vcs at build time.
14
+ 2. The ``_version.py`` file hatch-vcs bakes into the wheel, in case metadata
15
+ is unavailable (e.g. running from a source tree that was built but not
16
+ installed).
17
+ 3. ``"0.0.0+unknown"`` when neither is present (a bare source checkout with no
18
+ build), so callers always get a string.
19
+ """
20
+
21
+ try:
22
+ return version("makker")
23
+ except PackageNotFoundError:
24
+ pass
25
+ try:
26
+ from makker._version import __version__ as baked # type: ignore[import-not-found]
27
+
28
+ return baked
29
+ except Exception:
30
+ return "0.0.0+unknown"
31
+
32
+
33
+ __version__ = _resolve_version()
makker/__main__.py ADDED
@@ -0,0 +1,23 @@
1
+ """Entry point for the Makker CLI.
2
+
3
+ Delegates to ``interfaces.cli.main`` so the CLI plumbing has one home.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import sys
9
+ import warnings
10
+
11
+ # The LangChain packages import pydantic.v1 so they can accept V1 models, and on
12
+ # Python 3.14+ that import alone warns at the start of every command. Makker
13
+ # never hands them a V1 model, so the warning says nothing about this program.
14
+ warnings.filterwarnings(
15
+ "ignore",
16
+ message="Core Pydantic V1 functionality isn't compatible with Python 3.14",
17
+ category=UserWarning,
18
+ )
19
+
20
+ from makker.interfaces.cli import main # noqa: E402
21
+
22
+ if __name__ == "__main__":
23
+ sys.exit(main())
makker/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.3.0'
22
+ __version_tuple__ = version_tuple = (0, 3, 0)
23
+
24
+ __commit_id__ = commit_id = None
File without changes
@@ -0,0 +1,117 @@
1
+ """Track additional working directories the user adds to the session.
2
+
3
+ The agent's filesystem uses real paths (see ``agent.builder.build_backend``), so
4
+ an added folder is already reachable at its absolute path by every tool:
5
+ ``read_file``, ``grep``, ``write_file``, ``execute``, and ``run_julia`` alike.
6
+ Adding a folder just validates the path and records it on the live backend so
7
+ the session can list what was added (via the ``--add-dir`` flag at launch or the
8
+ TUI ``/add-dir`` command). Records are session-scoped: they live until the
9
+ process exits and are not persisted.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ from makker.paths import workspace_root
19
+
20
+ # Collapse anything outside this set to a single dash for a readable short name.
21
+ _UNSAFE_NAME_CHARS = re.compile(r"[^A-Za-z0-9._-]+")
22
+
23
+
24
+ class AddDirError(ValueError):
25
+ """A folder could not be added (missing path, not a directory, ...)."""
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class AddedDir:
30
+ """A folder the user added to the session, used at its real ``path``."""
31
+
32
+ name: str
33
+ path: Path
34
+
35
+
36
+ def _slugify(path: Path) -> str:
37
+ """A safe, human-readable short name derived from the folder's basename."""
38
+
39
+ base = _UNSAFE_NAME_CHARS.sub("-", path.name).strip("-._")
40
+ return base or "dir"
41
+
42
+
43
+ def _unique_name(taken: set[str], desired: str) -> str:
44
+ """``desired`` if free, else ``desired-2``, ``desired-3``, ... so two
45
+ folders that share a basename get distinct names."""
46
+
47
+ if desired not in taken:
48
+ return desired
49
+ index = 2
50
+ while f"{desired}-{index}" in taken:
51
+ index += 1
52
+ return f"{desired}-{index}"
53
+
54
+
55
+ def resolve_dir(raw: str | Path, *, workspace: Path | None = None) -> Path:
56
+ """Resolve a user-supplied folder to an absolute, existing directory.
57
+
58
+ ``~`` and relative paths are resolved against the workspace root (the
59
+ user's launch directory), matching how they'd read the path at the prompt.
60
+ Raises ``AddDirError`` if the path is missing or not a directory.
61
+ """
62
+
63
+ base = (workspace or workspace_root()).resolve()
64
+ candidate = Path(raw).expanduser()
65
+ if not candidate.is_absolute():
66
+ candidate = base / candidate
67
+ candidate = candidate.resolve()
68
+ if not candidate.exists():
69
+ raise AddDirError(f"no such directory: {candidate}")
70
+ if not candidate.is_dir():
71
+ raise AddDirError(f"not a directory: {candidate}")
72
+ return candidate
73
+
74
+
75
+ def _registry(backend) -> list[AddedDir]:
76
+ """The mutable list of added folders, stored on the live backend."""
77
+ dirs = getattr(backend, "_added_dirs", None)
78
+ if dirs is None:
79
+ dirs = []
80
+ backend._added_dirs = dirs
81
+ return dirs
82
+
83
+
84
+ def added_dirs(backend) -> list[AddedDir]:
85
+ """The folders added to this session, sorted by name."""
86
+ return sorted(_registry(backend), key=lambda entry: entry.name)
87
+
88
+
89
+ def add_dir(
90
+ backend,
91
+ raw: str | Path,
92
+ *,
93
+ workspace: Path | None = None,
94
+ ) -> AddedDir:
95
+ """Validate ``raw`` and record it as an added folder; return its ``AddedDir``.
96
+
97
+ The real-path backend already reads and writes any real path, so the agent
98
+ uses the folder's absolute path directly; recording it just lets the session
99
+ list and track what was added. Idempotent (an already-added folder returns
100
+ its existing record). The workspace itself is rejected because it is already
101
+ the working directory. Raises ``AddDirError`` for a missing or non-directory path.
102
+ """
103
+
104
+ ws = (workspace or workspace_root()).resolve()
105
+ path = resolve_dir(raw, workspace=ws)
106
+ if path == ws:
107
+ raise AddDirError("the workspace is already the working directory, no need to add it")
108
+
109
+ registry = _registry(backend)
110
+ for entry in registry:
111
+ if entry.path == path:
112
+ return entry
113
+
114
+ name = _unique_name({entry.name for entry in registry}, _slugify(path))
115
+ entry = AddedDir(name=name, path=path)
116
+ registry.append(entry)
117
+ return entry
@@ -0,0 +1,278 @@
1
+ """Human-in-the-loop approval modes for workspace file and shell tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from copy import deepcopy
7
+ from enum import StrEnum
8
+ from typing import Any, Protocol
9
+
10
+ from langchain.agents.middleware import InterruptOnConfig
11
+
12
+ # Tools that require human approval. Action name → human-readable description
13
+ # shown in the approval card. All entries use approve/reject only.
14
+ _APPROVAL_TOOLS: dict[str, str] = {
15
+ "execute": "Run a shell command in the workspace.",
16
+ "write_file": "Write a file in the workspace.",
17
+ "edit_file": "Edit a file in the workspace.",
18
+ "delete": "Delete a file or directory (directories go recursively).",
19
+ }
20
+
21
+ # Deliberately excludes `delete`: these are the tools "accept edits" mode and the
22
+ # session allowlist wave through in bulk, and a recursive delete is not something
23
+ # a blanket "always allow file edits" should cover. It stays one prompt per call.
24
+ _WORKSPACE_EDIT_TOOLS = frozenset({"write_file", "edit_file"})
25
+ _SHELL_TOOLS = frozenset({"execute"})
26
+
27
+ # Session allowlist categories.
28
+ ALLOWLIST_FILE_EDITS = "file_edits"
29
+ ALLOWLIST_SHELL = "shell"
30
+
31
+
32
+ def interrupt_on_config() -> dict[str, InterruptOnConfig]:
33
+ """``interrupt_on`` map keyed by tool name (used by `create_deep_agent`)."""
34
+
35
+ return {
36
+ name: {"allowed_decisions": ["approve", "reject"], "description": description}
37
+ for name, description in _APPROVAL_TOOLS.items()
38
+ }
39
+
40
+
41
+ class ApprovalMode(StrEnum):
42
+ """How side-effecting Deep Agents tools are gated before execution."""
43
+
44
+ ASK = "ask"
45
+ """Prompt before every gated tool (default)."""
46
+
47
+ WORKSPACE = "workspace"
48
+ """Auto-allow workspace write_file and edit_file; still prompt for the rest."""
49
+
50
+ AUTO = "auto"
51
+ """Auto-allow all configured approval tools (non-interactive trust mode)."""
52
+
53
+ def display_label(self) -> str:
54
+ return {
55
+ ApprovalMode.ASK: "default",
56
+ ApprovalMode.WORKSPACE: "accept edits",
57
+ ApprovalMode.AUTO: "auto",
58
+ }[self]
59
+
60
+ def cycle_next(self) -> ApprovalMode:
61
+ order = (ApprovalMode.ASK, ApprovalMode.WORKSPACE, ApprovalMode.AUTO)
62
+ index = order.index(self)
63
+ return order[(index + 1) % len(order)]
64
+
65
+
66
+ class ToolAllowlist:
67
+ """Per-session categories the user chose to always allow."""
68
+
69
+ def __init__(self) -> None:
70
+ self._categories: set[str] = set()
71
+
72
+ def add(self, category: str) -> None:
73
+ self._categories.add(category)
74
+
75
+ def contains(self, category: str) -> bool:
76
+ return category in self._categories
77
+
78
+ def __bool__(self) -> bool:
79
+ return bool(self._categories)
80
+
81
+ def categories(self) -> frozenset[str]:
82
+ return frozenset(self._categories)
83
+
84
+
85
+ def tool_allowlist_category(tool_name: str) -> str | None:
86
+ if tool_name in _WORKSPACE_EDIT_TOOLS:
87
+ return ALLOWLIST_FILE_EDITS
88
+ if tool_name in _SHELL_TOOLS:
89
+ return ALLOWLIST_SHELL
90
+ return None
91
+
92
+
93
+ def categories_for_interrupt(value: Any) -> frozenset[str]:
94
+ if not isinstance(value, dict):
95
+ return frozenset()
96
+ action_requests = value.get("action_requests")
97
+ if not isinstance(action_requests, list):
98
+ return frozenset()
99
+ categories: set[str] = set()
100
+ for action in action_requests:
101
+ if not isinstance(action, dict):
102
+ continue
103
+ category = tool_allowlist_category(str(action.get("name") or ""))
104
+ if category:
105
+ categories.add(category)
106
+ return frozenset(categories)
107
+
108
+
109
+ def interrupt_matches_allowlist(value: Any, allowlist: ToolAllowlist) -> bool:
110
+ categories = categories_for_interrupt(value)
111
+ if not categories:
112
+ return False
113
+ return all(allowlist.contains(category) for category in categories)
114
+
115
+
116
+ def always_allow_categories(value: Any) -> frozenset[str]:
117
+ """Categories a front end may offer to 'always allow' for this interrupt.
118
+
119
+ Mirrors the TUI's policy so every interface behaves the same: shell approvals
120
+ are deliberately one-off (a blanket 'always allow shell' is too broad), so a
121
+ shell-only interrupt offers nothing; file edits and other categories do.
122
+ """
123
+ categories = categories_for_interrupt(value)
124
+ if not categories or categories == {ALLOWLIST_SHELL}:
125
+ return frozenset()
126
+ return categories
127
+
128
+
129
+ def parse_approval_mode(value: str | None) -> ApprovalMode:
130
+ if not value:
131
+ return ApprovalMode.ASK
132
+ normalized = value.strip().lower()
133
+ for mode in ApprovalMode:
134
+ if mode == normalized:
135
+ return mode
136
+ raise ValueError(
137
+ f"unknown approval mode {value!r}; expected one of: "
138
+ + ", ".join(m.value for m in ApprovalMode)
139
+ )
140
+
141
+
142
+ def interrupt_on_for_mode(mode: ApprovalMode) -> dict[str, InterruptOnConfig]:
143
+ """Map an approval mode to Deep Agents ``interrupt_on`` configuration."""
144
+
145
+ if mode == ApprovalMode.AUTO:
146
+ return {}
147
+ if mode == ApprovalMode.WORKSPACE:
148
+ # "Accept edits" auto-allows exactly the workspace edit tools; anything
149
+ # else that is gated at all stays gated, so a newly gated tool is not
150
+ # silently waved through by this mode.
151
+ full = interrupt_on_config()
152
+ return {name: cfg for name, cfg in full.items() if name not in _WORKSPACE_EDIT_TOOLS}
153
+ return interrupt_on_config()
154
+
155
+
156
+ def interrupt_is_workspace_edits_only(value: Any) -> bool:
157
+ """True when every action in an interrupt is write_file or edit_file."""
158
+
159
+ if not isinstance(value, dict):
160
+ return False
161
+ action_requests = value.get("action_requests")
162
+ if not isinstance(action_requests, list) or not action_requests:
163
+ return False
164
+ for action in action_requests:
165
+ if not isinstance(action, dict):
166
+ return False
167
+ if action.get("name") not in _WORKSPACE_EDIT_TOOLS:
168
+ return False
169
+ return True
170
+
171
+
172
+ def should_auto_approve_interrupt(
173
+ value: Any,
174
+ mode: ApprovalMode,
175
+ *,
176
+ allowlist: ToolAllowlist | None = None,
177
+ ) -> bool:
178
+ if allowlist is not None and interrupt_matches_allowlist(value, allowlist):
179
+ return True
180
+ if mode == ApprovalMode.AUTO:
181
+ return True
182
+ if mode == ApprovalMode.WORKSPACE:
183
+ return interrupt_is_workspace_edits_only(value)
184
+ return False
185
+
186
+
187
+ # ---------------------------------------------------------------------------
188
+ # Interrupt decisions and resume payloads.
189
+ #
190
+ # Shared across interfaces (TUI, server) so every front end resolves an
191
+ # approval interrupt the same way. An interrupt payload follows deepagents'
192
+ # contract: a dict with an ``action_requests`` list and a parallel
193
+ # ``review_configs`` list of allowed-decision policies.
194
+
195
+ # The decisions a front end can resolve an interrupt with.
196
+ SUPPORTED_APPROVAL_DECISIONS = frozenset({"approve", "reject", "respond"})
197
+
198
+
199
+ class SupportsInterrupt(Protocol):
200
+ """A pending interrupt: an id and its raw payload value."""
201
+
202
+ interrupt_id: str
203
+ value: Any
204
+
205
+
206
+ def review_config_map(review_configs: Any) -> dict[str, frozenset[str]]:
207
+ """Map each action name to its allowed decisions from a ``review_configs`` list."""
208
+
209
+ config_map: dict[str, frozenset[str]] = {}
210
+ if not isinstance(review_configs, list):
211
+ return config_map
212
+ for review in review_configs:
213
+ if not isinstance(review, dict):
214
+ continue
215
+ action_name = review.get("action_name")
216
+ allowed = review.get("allowed_decisions")
217
+ if isinstance(action_name, str) and isinstance(allowed, list):
218
+ config_map[action_name] = frozenset(str(item) for item in allowed)
219
+ return config_map
220
+
221
+
222
+ def allowed_decisions_for_interrupt(value: Any) -> frozenset[str]:
223
+ """Return the intersection of decisions allowed across an interrupt's actions.
224
+
225
+ An interrupt may bundle multiple ``action_requests``; each can declare its
226
+ own ``allowed_decisions`` in a sibling ``review_configs`` block. A front end
227
+ can only resume an interrupt with a decision every action accepts, so we
228
+ intersect. Empty / malformed payloads fall back to all supported decisions,
229
+ matching deepagents' default.
230
+ """
231
+
232
+ if not isinstance(value, dict):
233
+ return SUPPORTED_APPROVAL_DECISIONS
234
+
235
+ config_map = review_config_map(value.get("review_configs"))
236
+ action_requests = value.get("action_requests")
237
+ if not isinstance(action_requests, list):
238
+ return SUPPORTED_APPROVAL_DECISIONS
239
+
240
+ shared: frozenset[str] | None = None
241
+ for action in action_requests:
242
+ if not isinstance(action, dict):
243
+ continue
244
+ action_name = str(action.get("name") or "")
245
+ allowed = config_map.get(action_name, SUPPORTED_APPROVAL_DECISIONS)
246
+ shared = allowed if shared is None else shared & allowed
247
+ return shared if shared is not None else SUPPORTED_APPROVAL_DECISIONS
248
+
249
+
250
+ def pending_allowed_decisions(interrupts: Iterable[SupportsInterrupt]) -> frozenset[str]:
251
+ """Decisions every pending interrupt accepts, scoped to the supported set."""
252
+
253
+ shared: frozenset[str] | None = None
254
+ for interrupt in interrupts:
255
+ allowed = allowed_decisions_for_interrupt(interrupt.value)
256
+ shared = allowed if shared is None else shared & allowed
257
+ if shared is None:
258
+ return frozenset()
259
+ return shared & SUPPORTED_APPROVAL_DECISIONS
260
+
261
+
262
+ def build_resume_payload(
263
+ interrupts: Iterable[SupportsInterrupt],
264
+ decision: dict[str, str],
265
+ ) -> dict[str, dict[str, list[dict[str, str]]]]:
266
+ """Apply one decision to every action of every pending interrupt, for ``resume``.
267
+
268
+ The result is the ``Command(resume=...)`` payload deepagents expects: keyed
269
+ by interrupt id, each carrying one decision per ``action_request``.
270
+ """
271
+
272
+ payload: dict[str, dict[str, list[dict[str, str]]]] = {}
273
+ for interrupt in interrupts:
274
+ value = interrupt.value if isinstance(interrupt.value, dict) else {}
275
+ action_requests = value.get("action_requests")
276
+ count = len(action_requests) if isinstance(action_requests, list) else 1
277
+ payload[interrupt.interrupt_id] = {"decisions": [deepcopy(decision) for _ in range(count)]}
278
+ return payload
@@ -0,0 +1,160 @@
1
+ """Filesystem backend for the agent's workspace.
2
+
3
+ ``WorkspaceShellBackend`` is the real-path default: it reads and writes the real
4
+ filesystem from the workspace, refuses writes into read-only roots (installed
5
+ package source in the shared Julia depot), and blocks shell ``julia``.
6
+ ``WorkspaceCompositeBackend`` is the top-level composite, handling Windows
7
+ drive-absolute glob patterns.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+
14
+ from deepagents.backends import CompositeBackend, LocalShellBackend
15
+ from deepagents.backends.protocol import (
16
+ DeleteResult,
17
+ EditResult,
18
+ ExecuteResponse,
19
+ GlobResult,
20
+ WriteResult,
21
+ )
22
+
23
+ from makker.agent.windows_paths import split_windows_glob
24
+
25
+ _BLOCKED_INTERPRETERS = frozenset({"julia"})
26
+
27
+
28
+ def interpreter_invocation(command: str, names: frozenset[str] | tuple[str, ...]) -> str | None:
29
+ """Name of the interpreter a shell command launches, or ``None``.
30
+
31
+ Looks at the executable position of each pipeline/sequence segment, so
32
+ ``julia -e ...`` and ``echo x | julia`` match while an interpreter name
33
+ appearing as data (``ls ~/.julia/...``, ``grep julia src/``) does not.
34
+ Shared by the workspace backend's execute guard (which blocks only
35
+ ``julia``, the session kernel exists precisely for it) and the bench
36
+ scorers that audit recorded execute calls.
37
+ """
38
+ import re
39
+
40
+ for segment in re.split(r"[;|&]+|\$\(", command):
41
+ head = segment.strip().split()
42
+ if head and Path(head[0]).name in names:
43
+ return Path(head[0]).name
44
+ return None
45
+
46
+
47
+ _NO_JULIA_SHELL_MSG = (
48
+ "Error: spawning `julia` through the shell is disabled. Julia code runs in "
49
+ "the persistent session via `run_julia`: shared state, streamed output, no "
50
+ 'cold start. Use `run_julia` for code and `include("file.jl")` for scripts.'
51
+ )
52
+
53
+ _READ_ONLY_MSG = (
54
+ "Error: '{path}' is read-only installed package source in the shared Julia "
55
+ "depot. Read and grep it freely (it's reference material), but don't edit "
56
+ "it: the depot is shared across projects. Write your own code in the "
57
+ "workspace, or to change the package itself, `Pkg.develop` it "
58
+ "(makker init --source-path ...) and edit that checkout."
59
+ )
60
+
61
+
62
+ class WorkspaceCompositeBackend(CompositeBackend):
63
+ """Top-level composite that rewrites a Windows drive-absolute glob into a relative
64
+ pattern plus a base path (see :func:`split_windows_glob`): ``pathlib``'s
65
+ ``rglob`` rejects absolute patterns, so the absolute ``glob`` form the skills
66
+ use silently matches nothing on Windows otherwise. A no-op off Windows.
67
+ """
68
+
69
+ def glob(self, pattern: str, path: str | None = None) -> GlobResult:
70
+ pattern, path = split_windows_glob(pattern, path)
71
+ return super().glob(pattern, path=path)
72
+
73
+ async def aglob(self, pattern: str, path: str | None = None) -> GlobResult:
74
+ pattern, path = split_windows_glob(pattern, path)
75
+ return await super().aglob(pattern, path=path)
76
+
77
+
78
+ class WorkspaceShellBackend(LocalShellBackend):
79
+ """Workspace default backend: real paths, with a guard against shell ``julia``.
80
+
81
+ Constructed with ``virtual_mode=False`` so the file tools speak the real
82
+ filesystem: a relative path resolves against the workspace (the backend's
83
+ ``cwd``) and an absolute path as itself, the same way ``run_julia`` and
84
+ ``execute`` resolve paths from that working directory. One path string
85
+ therefore names one file in the file tools, the shell, and the REPL. Package
86
+ source, skills, memory, and added folders are all read and written at their
87
+ real paths through this one backend.
88
+
89
+ ``readonly_roots`` are real directories writes are refused under: the
90
+ shared Julia depot's installed package source. Reads and greps there are
91
+ fine (that's how the agent studies a package); ``write``, ``edit`` and
92
+ ``delete`` are blocked, so the agent can't corrupt the depot for other
93
+ projects. A ``Pkg.develop`` checkout lives outside the depot and stays
94
+ writable, so the registry-vs-dev distinction falls out of the path, with no
95
+ special-casing.
96
+
97
+ ``execute`` refuses to launch ``julia``: Julia belongs in the session
98
+ kernel, where state persists and output streams; a shell julia is a cold
99
+ process that shares nothing with the session. A prompt rule alone does not
100
+ reliably stop models from shelling out; the tool guaranteeing it does.
101
+ Other interpreters are deliberately not blocked: shell python and friends
102
+ are part of general competence, and scientific results are kept honest by
103
+ the bench's trace checks, not by a blanket ban.
104
+ """
105
+
106
+ def __init__(self, *args, readonly_roots: tuple[Path, ...] = (), **kwargs) -> None:
107
+ super().__init__(*args, **kwargs)
108
+ self._readonly_roots = tuple(Path(root).resolve() for root in readonly_roots)
109
+
110
+ def _readonly_reason(self, file_path: str) -> str | None:
111
+ """Corrective message if ``file_path`` lands inside a read-only root, else ``None``."""
112
+ if not self._readonly_roots:
113
+ return None
114
+ path = Path(file_path)
115
+ target = path if path.is_absolute() else self.cwd / path
116
+ try:
117
+ target = target.resolve()
118
+ except OSError:
119
+ return None
120
+ for root in self._readonly_roots:
121
+ if target == root or root in target.parents:
122
+ return _READ_ONLY_MSG.format(path=file_path)
123
+ return None
124
+
125
+ def write(self, file_path: str, content: str) -> WriteResult:
126
+ reason = self._readonly_reason(file_path)
127
+ if reason is not None:
128
+ return WriteResult(error=reason)
129
+ return super().write(file_path, content)
130
+
131
+ def edit(
132
+ self,
133
+ file_path: str,
134
+ old_string: str,
135
+ new_string: str,
136
+ replace_all: bool = False,
137
+ ) -> EditResult:
138
+ reason = self._readonly_reason(file_path)
139
+ if reason is not None:
140
+ return EditResult(error=reason)
141
+ return super().edit(file_path, old_string, new_string, replace_all=replace_all)
142
+
143
+ def delete(self, file_path: str) -> DeleteResult:
144
+ # Deleting a directory removes it recursively, so the depot guard matters
145
+ # here more than for write/edit: one call could take out a package's
146
+ # whole source tree.
147
+ reason = self._readonly_reason(file_path)
148
+ if reason is not None:
149
+ return DeleteResult(error=reason)
150
+ return super().delete(file_path)
151
+
152
+ def execute(self, command: str, *, timeout: int | None = None) -> ExecuteResponse:
153
+ if interpreter_invocation(command, _BLOCKED_INTERPRETERS) is not None:
154
+ return ExecuteResponse(output=_NO_JULIA_SHELL_MSG, exit_code=2)
155
+ return super().execute(command, timeout=timeout)
156
+
157
+ async def aexecute(self, command: str, *, timeout: int | None = None) -> ExecuteResponse:
158
+ if interpreter_invocation(command, _BLOCKED_INTERPRETERS) is not None:
159
+ return ExecuteResponse(output=_NO_JULIA_SHELL_MSG, exit_code=2)
160
+ return await super().aexecute(command, timeout=timeout)