coder-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.
Files changed (163) hide show
  1. coder_agent-0.1.0.dist-info/METADATA +262 -0
  2. coder_agent-0.1.0.dist-info/RECORD +163 -0
  3. coder_agent-0.1.0.dist-info/WHEEL +5 -0
  4. coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
  5. coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  6. coder_agent-0.1.0.dist-info/top_level.txt +1 -0
  7. coderagent/__init__.py +20 -0
  8. coderagent/compat/__init__.py +27 -0
  9. coderagent/compat/cache_control.py +69 -0
  10. coderagent/compat/config_spec.py +60 -0
  11. coderagent/compat/exceptions.py +20 -0
  12. coderagent/compat/retry.py +27 -0
  13. coderagent/compat/serialize.py +31 -0
  14. coderagent/config/__init__.py +1 -0
  15. coderagent/config/defaults.yaml +103 -0
  16. coderagent/config/loader.py +264 -0
  17. coderagent/config/schema.py +548 -0
  18. coderagent/config/writer.py +218 -0
  19. coderagent/core/__init__.py +1 -0
  20. coderagent/core/budget.py +47 -0
  21. coderagent/core/capabilities.py +136 -0
  22. coderagent/core/checkpoint.py +164 -0
  23. coderagent/core/content.py +156 -0
  24. coderagent/core/context.py +618 -0
  25. coderagent/core/events.py +83 -0
  26. coderagent/core/history.py +56 -0
  27. coderagent/core/instructions.py +99 -0
  28. coderagent/core/loop.py +702 -0
  29. coderagent/core/memory.py +56 -0
  30. coderagent/core/mentions.py +81 -0
  31. coderagent/core/os_sandbox.py +191 -0
  32. coderagent/core/otel.py +214 -0
  33. coderagent/core/protocols.py +38 -0
  34. coderagent/core/redact.py +49 -0
  35. coderagent/core/sandbox.py +82 -0
  36. coderagent/core/schema.py +107 -0
  37. coderagent/core/session.py +344 -0
  38. coderagent/core/shell_env.py +74 -0
  39. coderagent/core/subagent.py +474 -0
  40. coderagent/core/summarize.py +312 -0
  41. coderagent/core/telemetry.py +209 -0
  42. coderagent/core/tokens.py +132 -0
  43. coderagent/core/trust.py +301 -0
  44. coderagent/environments/__init__.py +11 -0
  45. coderagent/environments/bubblewrap.py +150 -0
  46. coderagent/environments/contree.py +146 -0
  47. coderagent/environments/docker.py +160 -0
  48. coderagent/environments/local.py +110 -0
  49. coderagent/environments/singularity.py +138 -0
  50. coderagent/environments/swerex_docker.py +79 -0
  51. coderagent/environments/swerex_modal.py +123 -0
  52. coderagent/eval/__init__.py +1 -0
  53. coderagent/eval/compare.py +190 -0
  54. coderagent/eval/report.py +141 -0
  55. coderagent/eval/runner.py +368 -0
  56. coderagent/eval/task.py +194 -0
  57. coderagent/extensions/__init__.py +1 -0
  58. coderagent/extensions/hooks.py +121 -0
  59. coderagent/extensions/plugins.py +217 -0
  60. coderagent/extensions/reflect.py +342 -0
  61. coderagent/models/__init__.py +33 -0
  62. coderagent/models/backends.py +218 -0
  63. coderagent/models/call.py +18 -0
  64. coderagent/models/check.py +139 -0
  65. coderagent/models/gateway.py +60 -0
  66. coderagent/models/litellm_config.py +70 -0
  67. coderagent/models/provider.py +98 -0
  68. coderagent/models/reasoning.py +28 -0
  69. coderagent/models/router.py +136 -0
  70. coderagent/models/settings.py +172 -0
  71. coderagent/models/streaming.py +122 -0
  72. coderagent/models/verbosity.py +14 -0
  73. coderagent/paths.py +31 -0
  74. coderagent/run.py +454 -0
  75. coderagent/skills/__init__.py +119 -0
  76. coderagent/skills/errors.py +11 -0
  77. coderagent/skills/install.py +340 -0
  78. coderagent/skills/presets/code-review/SKILL.md +35 -0
  79. coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
  80. coderagent/skills/presets/data-analysis/SKILL.md +35 -0
  81. coderagent/skills/presets/deep-research/SKILL.md +38 -0
  82. coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
  83. coderagent/skills/presets/long-document/SKILL.md +37 -0
  84. coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
  85. coderagent/skills/presets/office-docx/SKILL.md +36 -0
  86. coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
  87. coderagent/skills/presets/office-pptx/SKILL.md +32 -0
  88. coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
  89. coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
  90. coderagent/skills/presets/writing/SKILL.md +31 -0
  91. coderagent/skills/sandbox.py +269 -0
  92. coderagent/skills/sites.py +177 -0
  93. coderagent/skills/source.py +404 -0
  94. coderagent/testing/__init__.py +5 -0
  95. coderagent/testing/factory.py +59 -0
  96. coderagent/testing/scripted_model.py +54 -0
  97. coderagent/tools/__init__.py +1 -0
  98. coderagent/tools/base.py +54 -0
  99. coderagent/tools/bash_policy.py +486 -0
  100. coderagent/tools/builtin/__init__.py +35 -0
  101. coderagent/tools/builtin/fs.py +283 -0
  102. coderagent/tools/builtin/patch.py +279 -0
  103. coderagent/tools/builtin/search.py +242 -0
  104. coderagent/tools/builtin/shell.py +336 -0
  105. coderagent/tools/builtin/skill.py +41 -0
  106. coderagent/tools/builtin/task.py +53 -0
  107. coderagent/tools/builtin/todo.py +63 -0
  108. coderagent/tools/executor.py +243 -0
  109. coderagent/tools/mcp.py +317 -0
  110. coderagent/tools/permissions.py +472 -0
  111. coderagent/tools/registry.py +83 -0
  112. coderagent/tools/rules.py +138 -0
  113. coderagent/ui/__init__.py +1 -0
  114. coderagent/ui/cli.py +498 -0
  115. coderagent/ui/commands/__init__.py +109 -0
  116. coderagent/ui/commands/builtin.py +778 -0
  117. coderagent/ui/commands/compact.py +12 -0
  118. coderagent/ui/commands/resume.py +26 -0
  119. coderagent/ui/commands/review.py +73 -0
  120. coderagent/ui/commands/rewind.py +28 -0
  121. coderagent/ui/custom_commands.py +179 -0
  122. coderagent/ui/notify.py +46 -0
  123. coderagent/ui/open_file.py +48 -0
  124. coderagent/ui/render.py +62 -0
  125. coderagent/ui/spinner.py +68 -0
  126. coderagent/ui/tui.py +610 -0
  127. coderagent/ui/widgets/__init__.py +29 -0
  128. coderagent/ui/widgets/approval_prompt.py +129 -0
  129. coderagent/ui/widgets/diff_view.py +97 -0
  130. coderagent/ui/widgets/file_tree.py +105 -0
  131. coderagent/ui/widgets/markdown_message.py +44 -0
  132. coderagent/ui/widgets/markup.py +10 -0
  133. coderagent/ui/widgets/message_block.py +61 -0
  134. coderagent/ui/widgets/path_suggester.py +66 -0
  135. coderagent/ui/widgets/session_picker.py +49 -0
  136. coderagent/ui/widgets/status_bar.py +44 -0
  137. coderagent/ui/widgets/todo_panel.py +40 -0
  138. coderagent/ui/widgets/tool_card.py +104 -0
  139. coderagent/ui/widgets/working_dots.py +26 -0
  140. coderagent/version.py +7 -0
  141. coderagent/web/__init__.py +5 -0
  142. coderagent/web/api.py +449 -0
  143. coderagent/web/app.py +113 -0
  144. coderagent/web/approver.py +73 -0
  145. coderagent/web/config_api.py +53 -0
  146. coderagent/web/events.py +159 -0
  147. coderagent/web/files.py +115 -0
  148. coderagent/web/i18n.py +346 -0
  149. coderagent/web/server.py +100 -0
  150. coderagent/web/sessions.py +404 -0
  151. coderagent/web/skills_api.py +376 -0
  152. coderagent/web/static/app.css +283 -0
  153. coderagent/web/static/app.js +1466 -0
  154. coderagent/web/templates/en/base.html +31 -0
  155. coderagent/web/templates/en/chat.html +60 -0
  156. coderagent/web/templates/en/macros.html +9 -0
  157. coderagent/web/templates/en/settings.html +80 -0
  158. coderagent/web/templates/en/skills.html +64 -0
  159. coderagent/web/templates/zh/base.html +31 -0
  160. coderagent/web/templates/zh/chat.html +60 -0
  161. coderagent/web/templates/zh/macros.html +9 -0
  162. coderagent/web/templates/zh/settings.html +77 -0
  163. coderagent/web/templates/zh/skills.html +61 -0
@@ -0,0 +1,20 @@
1
+ """The environment that runs the commands of the agent on this machine."""
2
+
3
+
4
+ class InterruptAgentFlow(Exception):
5
+ """Raised to interrupt the agent flow and add messages."""
6
+
7
+ def __init__(self, *messages: dict):
8
+ self.messages = messages
9
+ super().__init__()
10
+
11
+
12
+ class Submitted(InterruptAgentFlow):
13
+ """Raised when the agent has completed its task."""
14
+
15
+
16
+ class FormatError(InterruptAgentFlow):
17
+ """Raised when the LM's output is not in the expected format.
18
+
19
+ The details are in `messages`, not in the text of the exception.
20
+ """
@@ -0,0 +1,27 @@
1
+ """The retries of the calls to the model."""
2
+
3
+ import logging
4
+ import os
5
+
6
+ from tenacity import Retrying, before_sleep_log, retry_if_not_exception_type, stop_after_attempt, wait_exponential
7
+
8
+
9
+ def retry(*, logger: logging.Logger, abort_exceptions: list[type[Exception]], attempts: int = 0) -> Retrying:
10
+ """The retries of a call to the model.
11
+
12
+ Args:
13
+ logger: Logger to use for reporting retries
14
+ abort_exceptions: Exceptions to abort on.
15
+ attempts: How many times a call is tried at most. 0 takes the environment
16
+ variable `MSWEA_MODEL_RETRY_STOP_AFTER_ATTEMPT`, or ten.
17
+
18
+ Returns:
19
+ A tenacity.Retrying object.
20
+ """
21
+ return Retrying(
22
+ reraise=True,
23
+ stop=stop_after_attempt(int(os.getenv("MSWEA_MODEL_RETRY_STOP_AFTER_ATTEMPT", attempts or 10))),
24
+ wait=wait_exponential(multiplier=1, min=4, max=60),
25
+ before_sleep=before_sleep_log(logger, logging.WARNING),
26
+ retry=retry_if_not_exception_type(tuple(abort_exceptions)),
27
+ )
@@ -0,0 +1,31 @@
1
+ """Merging of the dictionaries of the configuration."""
2
+
3
+ from typing import Any
4
+
5
+ UNSET = object()
6
+
7
+
8
+ def recursive_merge(*dictionaries: dict | None) -> dict:
9
+ """Merge multiple dictionaries recursively.
10
+
11
+ Later dictionaries take precedence over earlier ones.
12
+ Nested dictionaries are merged recursively.
13
+ UNSET values are skipped.
14
+ """
15
+ if not dictionaries:
16
+ return {}
17
+ result: dict[str, Any] = {}
18
+ for d in dictionaries:
19
+ if d is None:
20
+ continue
21
+ for key, value in d.items():
22
+ if value is UNSET:
23
+ continue
24
+ if key in result and isinstance(result[key], dict) and isinstance(value, dict):
25
+ result[key] = recursive_merge(result[key], value)
26
+ elif isinstance(value, dict):
27
+ # Recursively merge dict values to filter out nested UNSET values
28
+ result[key] = recursive_merge(value)
29
+ else:
30
+ result[key] = value
31
+ return result
@@ -0,0 +1 @@
1
+ """Configuration schema and loading."""
@@ -0,0 +1,103 @@
1
+ model:
2
+ model_kwargs: {}
3
+ max_retries: 3
4
+ litellm_config: ""
5
+ routing: {}
6
+ routing_rules: []
7
+ set_cache_control: null
8
+ reasoning_effort: ""
9
+ verbosity: ""
10
+ review_model: ""
11
+ capabilities: {}
12
+
13
+ agent:
14
+ system_prompt: "You are a coding agent working in a code repository. Prefer the dedicated tools over shell commands: `read` to look at a file, `glob`/`grep`/`ls` to find code, `edit`/`multi_edit`/`apply_patch` to change files, and `bash` for builds, tests and pipelines. Call every tool with the argument names of its schema, exactly as they are written there (`path`), never a translated or renamed variant. Complete the task the user describes and summarize what you changed."
15
+ max_turns: 100
16
+ cost_limit: 0.0
17
+ token_limit: 0
18
+ subagent_max_turns: 0
19
+ subagent_max_parallel: 2
20
+
21
+ tools:
22
+ enabled: [read, write, edit, multi_edit, apply_patch, glob, grep, ls, bash, bash_output, bash_kill, todo_write, task, skill]
23
+ disabled: []
24
+ bash_timeout: 120
25
+ max_output_tokens: 8000
26
+ schema_budget_tokens: 0
27
+
28
+ permissions:
29
+ mode: default
30
+ rules: []
31
+ deny_paths: []
32
+ include_dirs: []
33
+ network: allow
34
+
35
+ shell_environment:
36
+ inherit: all
37
+ exclude: []
38
+ include: []
39
+ set: {}
40
+
41
+ context:
42
+ reserved_output: 8000
43
+ compact_threshold: 0.8
44
+ keep_recent_turns: 20
45
+ keep_recent_token_ratio: 0.4
46
+ compact_every_turns: 40
47
+ auto_compact: true
48
+ summarize_model: ""
49
+ summary_chunk_tokens: 0
50
+ project_doc_max_bytes: 32768
51
+
52
+ memory:
53
+ project_path: ".coderagent/memory"
54
+ user_path: "~/.coderagent/CLAUDE.md"
55
+ enabled: true
56
+
57
+ checkpoint:
58
+ enabled: true
59
+ keep: 50
60
+
61
+ mcp:
62
+ servers: []
63
+ timeout: 30
64
+
65
+ hooks:
66
+ events: {}
67
+
68
+ ui:
69
+ approval_timeout: 0
70
+ notifications: true
71
+ notify_command: ""
72
+ file_opener: ""
73
+ markdown: true
74
+
75
+ history:
76
+ persistence: save-all
77
+ max_bytes: 0
78
+
79
+ sandbox:
80
+ type: local
81
+ mode: full-access
82
+
83
+ verify:
84
+ commands: []
85
+ max_rounds: 3
86
+ timeout: 300
87
+
88
+ telemetry:
89
+ otel_endpoint: ""
90
+ otel_headers: {}
91
+ otel_timeout: 5.0
92
+
93
+ skills:
94
+ enabled: true
95
+ max_bytes: 8388608
96
+ max_file_bytes: 1048576
97
+ max_files: 2000
98
+ max_depth: 16
99
+ timeout: 30
100
+ registries: []
101
+ github_token: ""
102
+ allow_insecure: false
103
+ allowed_hosts: []
@@ -0,0 +1,264 @@
1
+ """Configuration loading: built-in defaults, project file, user file, CLI overrides."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ import yaml
7
+ from pydantic import BaseModel, ValidationError
8
+
9
+ from coderagent.compat import get_config_from_spec, recursive_merge
10
+ from coderagent.config.schema import Config
11
+ from coderagent.core.os_sandbox import FULL_ACCESS, MODES
12
+ from coderagent.core.trust import tightened, waiting, without_untrusted
13
+ from coderagent.paths import config_home
14
+
15
+ DEFAULTS_PATH = Path(__file__).parent / "defaults.yaml"
16
+ PROJECT_CONFIG = Path(".coderagent") / "config.yaml"
17
+ DEFAULT_MODEL_NAME = "anthropic/claude-sonnet-4-5"
18
+ ADDED_LISTS = (
19
+ ("permissions", "rules"),
20
+ ("permissions", "deny_paths"),
21
+ ("tools", "disabled"),
22
+ ("shell_environment", "exclude"),
23
+ )
24
+ """The lists that every layer adds to, instead of replacing."""
25
+
26
+ LIMIT_KEYS = (
27
+ ("agent", "max_turns"),
28
+ ("agent", "cost_limit"),
29
+ ("agent", "token_limit"),
30
+ ("agent", "subagent_max_turns"),
31
+ ("agent", "subagent_max_parallel"),
32
+ ("tools", "bash_timeout"),
33
+ ("tools", "max_output_tokens"),
34
+ )
35
+ """The ceilings of a session. A project may lower them, never raise them."""
36
+
37
+ UNLIMITED = {"max_turns", "cost_limit", "token_limit", "subagent_max_turns", "subagent_max_parallel"}
38
+ """The ceilings where zero means: no ceiling at all."""
39
+
40
+
41
+ def config_layers(cwd: Path | None = None) -> list[tuple[str, dict]]:
42
+ """The configuration layers, from the lowest to the highest priority.
43
+
44
+ The project layer is the one of the repository the agent works in. The code
45
+ it defines runs without asking the user, so it waits for a decision of the
46
+ user and is not in the layer until it is trusted. What it may not do is
47
+ loosen the permissions: it may take tools away, never give them.
48
+ """
49
+ directory = Path(cwd) if cwd else Path.cwd()
50
+ layers = [("defaults", _read(DEFAULTS_PATH))]
51
+ project = _project_config_path(directory)
52
+ if project.exists():
53
+ layers.append(("project", _sanitized(tightened(without_untrusted(_read(project), directory)))))
54
+ user = config_home() / "config.yaml"
55
+ if user.exists():
56
+ layers.append(("user", _read(user)))
57
+ return layers
58
+
59
+
60
+ def pending_code(cwd: Path | None = None, user_home: Path | None = None) -> dict[str, str]:
61
+ """The code of the project that waits for a decision of the user."""
62
+ directory = Path(cwd) if cwd else Path.cwd()
63
+ project = _project_config_path(directory)
64
+ if not project.exists():
65
+ return {}
66
+ return waiting(_read(project), directory, user_home)
67
+
68
+
69
+ def load_config(specs: list[str] | None = None, cwd: Path | None = None) -> Config:
70
+ """Merge the four configuration layers, later layers win.
71
+
72
+ The project may only take tools away: the rules and the paths it denies
73
+ are added to the ones of the user, and the tools it names may only remove
74
+ from the tools of the others.
75
+
76
+ """
77
+ layers = config_layers(cwd)
78
+ spec_layers = [get_config_from_spec(spec) for spec in specs or []]
79
+ project = next((data for name, data in layers if name == "project"), None)
80
+ defaults = next((data for name, data in layers if name == "defaults"), {})
81
+ user = next((data for name, data in layers if name == "user"), {})
82
+ profile = _profile(recursive_merge(*[data for _, data in layers], *spec_layers))
83
+ base = recursive_merge(*[data for name, data in layers if name != "project"], profile, *spec_layers)
84
+ merged = recursive_merge(*[data for _, data in layers], profile, *spec_layers)
85
+ if project is not None:
86
+ for path in ADDED_LISTS:
87
+ _put(merged, path, [*_items(project, path), *_items(base, path)])
88
+ if isinstance(project.get("tools"), dict) and "enabled" in project["tools"]:
89
+ enabled = _items(project, ("tools", "enabled"))
90
+ _put(merged, ("tools", "enabled"), [tool for tool in _items(base, ("tools", "enabled")) if tool in enabled])
91
+ project_permissions = project.get("permissions")
92
+ if isinstance(project_permissions, dict) and project_permissions.get("network") == "deny":
93
+ """A project may close the network: the user does not open it again."""
94
+ merged.setdefault("permissions", {})["network"] = "deny"
95
+ _tighten_sandbox(merged, project)
96
+ _tighten_telemetry(merged, project)
97
+ _tighten_limits(merged, defaults, user, recursive_merge(profile, *spec_layers), project)
98
+ merged.setdefault("model", {})["capabilities"] = base.get("model", {}).get("capabilities", {})
99
+ """A project does not say what the model of the user takes."""
100
+ model = merged.setdefault("model", {})
101
+ model["model_name"] = model.get("model_name") or os.getenv("MSWEA_MODEL_NAME") or DEFAULT_MODEL_NAME
102
+ return Config(**merged)
103
+
104
+
105
+ def problems(error: ValidationError) -> str:
106
+ """What is wrong with the configuration, one thing per problem.
107
+
108
+ The error of pydantic is meant for a program: this is meant for a person.
109
+ """
110
+ return "; ".join(
111
+ f"{'.'.join(str(part) for part in entry['loc'])}: {entry['msg'].removeprefix('Value error, ')}"
112
+ for entry in error.errors()
113
+ )
114
+
115
+
116
+ def _sanitized(project: dict) -> dict:
117
+ """The project without the values that the schema would refuse.
118
+
119
+ A project may not break the session of the user: a value that is not
120
+ understood is left out, and the rest of the project is kept. The mistake
121
+ of a project is a warning, not the end of the session.
122
+ """
123
+ result = {}
124
+ for key, value in project.items():
125
+ model = _model_of(key)
126
+ if model is not None and isinstance(value, dict):
127
+ value = _accepted(model, value)
128
+ result[key] = value
129
+ return _accepted(Config, result)
130
+
131
+
132
+ def _model_of(key: str) -> type[BaseModel] | None:
133
+ """The model of a section of the configuration, when it has one."""
134
+ field = Config.model_fields.get(key)
135
+ annotation = field.annotation if field else None
136
+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):
137
+ return annotation
138
+ return None
139
+
140
+
141
+ def _accepted(model: type[BaseModel], values: dict) -> dict:
142
+ """The values of a mapping that the model accepts.
143
+
144
+ A value that the model would refuse is left out, one key at a time: the
145
+ rest of the section is still worth something.
146
+ """
147
+ kept = dict(values)
148
+ while kept:
149
+ try:
150
+ model(**kept)
151
+ return kept
152
+ except ValidationError as error:
153
+ keys = {str(entry["loc"][0]) for entry in error.errors() if entry.get("loc")}
154
+ if not keys:
155
+ return {}
156
+ for key in keys:
157
+ kept.pop(key, None)
158
+ return {}
159
+
160
+
161
+ def _tighten_telemetry(merged: dict, project: dict) -> None:
162
+ """A project may close the trace, and the user does not open it again.
163
+
164
+ The trace of a session holds what the agent read. Where it goes is the
165
+ decision of the user: a project may say "do not send it", never "send it
166
+ to me".
167
+ """
168
+ telemetry = project.get("telemetry")
169
+ if isinstance(telemetry, dict) and "otel_endpoint" in telemetry:
170
+ merged.setdefault("telemetry", {})["otel_endpoint"] = ""
171
+
172
+
173
+ def _profile(merged: dict) -> dict:
174
+ """The configuration of the profile that is in effect.
175
+
176
+ The name of the profile comes from the user or from the command line: a
177
+ project may neither define a profile nor choose one, because choosing a set
178
+ of permissions is the decision of the user.
179
+ """
180
+ tables = merged.get("profiles")
181
+ tables = tables if isinstance(tables, dict) else {}
182
+ name = str(merged.get("profile") or "")
183
+ if not name:
184
+ return {}
185
+ chosen = tables.get(name)
186
+ if not isinstance(chosen, dict):
187
+ raise ValueError(f"unknown profile '{name}'. Use one of: {', '.join(sorted(tables)) or 'none'}.")
188
+ return chosen
189
+
190
+
191
+ def _tighten_limits(merged: dict, defaults: dict, user: dict, explicit: dict, project: dict) -> None:
192
+ """The ceilings of a session belong to the user: a project may lower them.
193
+
194
+ A ceiling that the user names — in the file of the user, in a profile or on
195
+ the command line — is the last word. A project that asks for a higher one
196
+ than the default is given the default instead.
197
+ """
198
+ for section, key in LIMIT_KEYS:
199
+ value = _number(project, section, key)
200
+ if value is None:
201
+ continue
202
+ if _number(user, section, key) is not None or _number(explicit, section, key) is not None:
203
+ continue
204
+ reference = _number(defaults, section, key)
205
+ if reference is None:
206
+ continue
207
+ merged.setdefault(section, {})[key] = value if _lower(value, reference, key) else reference
208
+
209
+
210
+ def _number(layer: dict, section: str, key: str) -> float | None:
211
+ """The number at a path of a layer, when there is one there."""
212
+ value = (layer.get(section) or {}).get(key)
213
+ return value if isinstance(value, (int, float)) and not isinstance(value, bool) else None
214
+
215
+
216
+ def _lower(value: float, reference: float, key: str) -> bool:
217
+ """Whether the ceiling of the project is the lower one."""
218
+ if key in UNLIMITED:
219
+ if value == 0:
220
+ """No ceiling at all is not a lower ceiling."""
221
+ return False
222
+ if reference == 0:
223
+ return True
224
+ return value < reference
225
+
226
+
227
+ def _tighten_sandbox(merged: dict, project: dict) -> None:
228
+ """A project may close the sandbox, and the user does not open it again.
229
+
230
+ The tightest of the two wins: a project that says `read-only` keeps the
231
+ agent from writing, whatever the user level says.
232
+ """
233
+ mode = str((project.get("sandbox") or {}).get("mode") or "")
234
+ current = str((merged.get("sandbox") or {}).get("mode") or FULL_ACCESS)
235
+ if current not in MODES:
236
+ current = FULL_ACCESS
237
+ if mode in MODES and MODES.index(mode) < MODES.index(current):
238
+ merged.setdefault("sandbox", {})["mode"] = mode
239
+
240
+
241
+ def _items(layer: dict, path: tuple[str, ...]) -> list:
242
+ """The list at a path of a layer. A path that is not there is empty."""
243
+ value: object = layer
244
+ for key in path:
245
+ value = value.get(key) if isinstance(value, dict) else None
246
+ return value if isinstance(value, list) else []
247
+
248
+
249
+ def _put(merged: dict, path: tuple[str, ...], value: list) -> None:
250
+ """Write a list into a path of the merged configuration."""
251
+ target = merged
252
+ for key in path[:-1]:
253
+ target = target.setdefault(key, {})
254
+ target[path[-1]] = value
255
+
256
+
257
+ def _read(path: Path) -> dict:
258
+ """A configuration file as a mapping. A file that is not there is empty."""
259
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
260
+ return data if isinstance(data, dict) else {}
261
+
262
+
263
+ def _project_config_path(cwd: Path | None = None) -> Path:
264
+ return (Path(cwd) if cwd else Path.cwd()) / PROJECT_CONFIG