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.
- coder_agent-0.1.0.dist-info/METADATA +262 -0
- coder_agent-0.1.0.dist-info/RECORD +163 -0
- coder_agent-0.1.0.dist-info/WHEEL +5 -0
- coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
- coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
- coder_agent-0.1.0.dist-info/top_level.txt +1 -0
- coderagent/__init__.py +20 -0
- coderagent/compat/__init__.py +27 -0
- coderagent/compat/cache_control.py +69 -0
- coderagent/compat/config_spec.py +60 -0
- coderagent/compat/exceptions.py +20 -0
- coderagent/compat/retry.py +27 -0
- coderagent/compat/serialize.py +31 -0
- coderagent/config/__init__.py +1 -0
- coderagent/config/defaults.yaml +103 -0
- coderagent/config/loader.py +264 -0
- coderagent/config/schema.py +548 -0
- coderagent/config/writer.py +218 -0
- coderagent/core/__init__.py +1 -0
- coderagent/core/budget.py +47 -0
- coderagent/core/capabilities.py +136 -0
- coderagent/core/checkpoint.py +164 -0
- coderagent/core/content.py +156 -0
- coderagent/core/context.py +618 -0
- coderagent/core/events.py +83 -0
- coderagent/core/history.py +56 -0
- coderagent/core/instructions.py +99 -0
- coderagent/core/loop.py +702 -0
- coderagent/core/memory.py +56 -0
- coderagent/core/mentions.py +81 -0
- coderagent/core/os_sandbox.py +191 -0
- coderagent/core/otel.py +214 -0
- coderagent/core/protocols.py +38 -0
- coderagent/core/redact.py +49 -0
- coderagent/core/sandbox.py +82 -0
- coderagent/core/schema.py +107 -0
- coderagent/core/session.py +344 -0
- coderagent/core/shell_env.py +74 -0
- coderagent/core/subagent.py +474 -0
- coderagent/core/summarize.py +312 -0
- coderagent/core/telemetry.py +209 -0
- coderagent/core/tokens.py +132 -0
- coderagent/core/trust.py +301 -0
- coderagent/environments/__init__.py +11 -0
- coderagent/environments/bubblewrap.py +150 -0
- coderagent/environments/contree.py +146 -0
- coderagent/environments/docker.py +160 -0
- coderagent/environments/local.py +110 -0
- coderagent/environments/singularity.py +138 -0
- coderagent/environments/swerex_docker.py +79 -0
- coderagent/environments/swerex_modal.py +123 -0
- coderagent/eval/__init__.py +1 -0
- coderagent/eval/compare.py +190 -0
- coderagent/eval/report.py +141 -0
- coderagent/eval/runner.py +368 -0
- coderagent/eval/task.py +194 -0
- coderagent/extensions/__init__.py +1 -0
- coderagent/extensions/hooks.py +121 -0
- coderagent/extensions/plugins.py +217 -0
- coderagent/extensions/reflect.py +342 -0
- coderagent/models/__init__.py +33 -0
- coderagent/models/backends.py +218 -0
- coderagent/models/call.py +18 -0
- coderagent/models/check.py +139 -0
- coderagent/models/gateway.py +60 -0
- coderagent/models/litellm_config.py +70 -0
- coderagent/models/provider.py +98 -0
- coderagent/models/reasoning.py +28 -0
- coderagent/models/router.py +136 -0
- coderagent/models/settings.py +172 -0
- coderagent/models/streaming.py +122 -0
- coderagent/models/verbosity.py +14 -0
- coderagent/paths.py +31 -0
- coderagent/run.py +454 -0
- coderagent/skills/__init__.py +119 -0
- coderagent/skills/errors.py +11 -0
- coderagent/skills/install.py +340 -0
- coderagent/skills/presets/code-review/SKILL.md +35 -0
- coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
- coderagent/skills/presets/data-analysis/SKILL.md +35 -0
- coderagent/skills/presets/deep-research/SKILL.md +38 -0
- coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
- coderagent/skills/presets/long-document/SKILL.md +37 -0
- coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
- coderagent/skills/presets/office-docx/SKILL.md +36 -0
- coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
- coderagent/skills/presets/office-pptx/SKILL.md +32 -0
- coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
- coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
- coderagent/skills/presets/writing/SKILL.md +31 -0
- coderagent/skills/sandbox.py +269 -0
- coderagent/skills/sites.py +177 -0
- coderagent/skills/source.py +404 -0
- coderagent/testing/__init__.py +5 -0
- coderagent/testing/factory.py +59 -0
- coderagent/testing/scripted_model.py +54 -0
- coderagent/tools/__init__.py +1 -0
- coderagent/tools/base.py +54 -0
- coderagent/tools/bash_policy.py +486 -0
- coderagent/tools/builtin/__init__.py +35 -0
- coderagent/tools/builtin/fs.py +283 -0
- coderagent/tools/builtin/patch.py +279 -0
- coderagent/tools/builtin/search.py +242 -0
- coderagent/tools/builtin/shell.py +336 -0
- coderagent/tools/builtin/skill.py +41 -0
- coderagent/tools/builtin/task.py +53 -0
- coderagent/tools/builtin/todo.py +63 -0
- coderagent/tools/executor.py +243 -0
- coderagent/tools/mcp.py +317 -0
- coderagent/tools/permissions.py +472 -0
- coderagent/tools/registry.py +83 -0
- coderagent/tools/rules.py +138 -0
- coderagent/ui/__init__.py +1 -0
- coderagent/ui/cli.py +498 -0
- coderagent/ui/commands/__init__.py +109 -0
- coderagent/ui/commands/builtin.py +778 -0
- coderagent/ui/commands/compact.py +12 -0
- coderagent/ui/commands/resume.py +26 -0
- coderagent/ui/commands/review.py +73 -0
- coderagent/ui/commands/rewind.py +28 -0
- coderagent/ui/custom_commands.py +179 -0
- coderagent/ui/notify.py +46 -0
- coderagent/ui/open_file.py +48 -0
- coderagent/ui/render.py +62 -0
- coderagent/ui/spinner.py +68 -0
- coderagent/ui/tui.py +610 -0
- coderagent/ui/widgets/__init__.py +29 -0
- coderagent/ui/widgets/approval_prompt.py +129 -0
- coderagent/ui/widgets/diff_view.py +97 -0
- coderagent/ui/widgets/file_tree.py +105 -0
- coderagent/ui/widgets/markdown_message.py +44 -0
- coderagent/ui/widgets/markup.py +10 -0
- coderagent/ui/widgets/message_block.py +61 -0
- coderagent/ui/widgets/path_suggester.py +66 -0
- coderagent/ui/widgets/session_picker.py +49 -0
- coderagent/ui/widgets/status_bar.py +44 -0
- coderagent/ui/widgets/todo_panel.py +40 -0
- coderagent/ui/widgets/tool_card.py +104 -0
- coderagent/ui/widgets/working_dots.py +26 -0
- coderagent/version.py +7 -0
- coderagent/web/__init__.py +5 -0
- coderagent/web/api.py +449 -0
- coderagent/web/app.py +113 -0
- coderagent/web/approver.py +73 -0
- coderagent/web/config_api.py +53 -0
- coderagent/web/events.py +159 -0
- coderagent/web/files.py +115 -0
- coderagent/web/i18n.py +346 -0
- coderagent/web/server.py +100 -0
- coderagent/web/sessions.py +404 -0
- coderagent/web/skills_api.py +376 -0
- coderagent/web/static/app.css +283 -0
- coderagent/web/static/app.js +1466 -0
- coderagent/web/templates/en/base.html +31 -0
- coderagent/web/templates/en/chat.html +60 -0
- coderagent/web/templates/en/macros.html +9 -0
- coderagent/web/templates/en/settings.html +80 -0
- coderagent/web/templates/en/skills.html +64 -0
- coderagent/web/templates/zh/base.html +31 -0
- coderagent/web/templates/zh/chat.html +60 -0
- coderagent/web/templates/zh/macros.html +9 -0
- coderagent/web/templates/zh/settings.html +77 -0
- coderagent/web/templates/zh/skills.html +61 -0
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Model routing: which model answers which purpose.
|
|
2
|
+
|
|
3
|
+
The routing has four dimensions:
|
|
4
|
+
|
|
5
|
+
- `purpose`: a fixed mapping of purpose to model (`main`, `cheap`, `summarize`, `reflect`).
|
|
6
|
+
- `complexity`: a big job gets a stronger model.
|
|
7
|
+
- `budget`: when the money is nearly gone, a cheaper model takes over.
|
|
8
|
+
- `user_override`: the model the user picked with `/model` wins over everything.
|
|
9
|
+
|
|
10
|
+
The rules are small expressions on the state of the session, like `tokens > 50000`.
|
|
11
|
+
They are parsed, not evaluated, so a configuration file cannot run code.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
|
|
16
|
+
from coderagent.config.schema import COMPARISONS, ModelConfig, parse_condition
|
|
17
|
+
from coderagent.models.backends import LiteLLMBackend
|
|
18
|
+
|
|
19
|
+
STRONG_PURPOSE = "strong"
|
|
20
|
+
"""The purpose of a model that is stronger than the main one."""
|
|
21
|
+
CHEAP_PURPOSE = "cheap"
|
|
22
|
+
"""The purpose of a model that is cheaper than the main one."""
|
|
23
|
+
|
|
24
|
+
STRONG_TOKENS = 50000
|
|
25
|
+
STRONG_TURNS = 30
|
|
26
|
+
BUDGET_SHARE = 0.8
|
|
27
|
+
"""The share of the budget at which the agent moves to a cheaper model."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class RoutingRule:
|
|
32
|
+
"""A condition on the state of the session and the purpose it leads to."""
|
|
33
|
+
|
|
34
|
+
when: str
|
|
35
|
+
purpose: str
|
|
36
|
+
|
|
37
|
+
def matches(self, context: dict) -> bool:
|
|
38
|
+
"""True when the condition holds for this context. Only numbers are compared."""
|
|
39
|
+
parts = parse_condition(self.when)
|
|
40
|
+
if parts is None:
|
|
41
|
+
return False
|
|
42
|
+
key, operator, right = parts
|
|
43
|
+
if key not in context:
|
|
44
|
+
return False
|
|
45
|
+
left = context[key]
|
|
46
|
+
if isinstance(left, bool) or not isinstance(left, (int, float)):
|
|
47
|
+
return False
|
|
48
|
+
try:
|
|
49
|
+
return COMPARISONS[operator](left, right)
|
|
50
|
+
except TypeError:
|
|
51
|
+
return False
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ModelRouter:
|
|
55
|
+
"""Picks the model of a turn."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, config: ModelConfig, gateway=None) -> None:
|
|
58
|
+
self.config = config
|
|
59
|
+
self.gateway = gateway
|
|
60
|
+
self.override = ""
|
|
61
|
+
"""The model the user picked. It wins over every rule."""
|
|
62
|
+
self.main_model = config.model_name
|
|
63
|
+
"""The model of the main loop. The one the agent falls back to."""
|
|
64
|
+
|
|
65
|
+
def resolve(self, purpose: str, context: dict | None = None) -> str:
|
|
66
|
+
"""The name of the model to use for this purpose. Empty means: keep the current one."""
|
|
67
|
+
context = context or {}
|
|
68
|
+
if self.override:
|
|
69
|
+
return self.override
|
|
70
|
+
target = self._purpose(purpose, context)
|
|
71
|
+
name = self.config.routing.get(target, "")
|
|
72
|
+
if not name and target == "main":
|
|
73
|
+
return self.main_model
|
|
74
|
+
if not name and target == "review":
|
|
75
|
+
"""The review may run on a model of its own."""
|
|
76
|
+
return self.config.review_model
|
|
77
|
+
return name
|
|
78
|
+
|
|
79
|
+
def explain(self, context: dict) -> str:
|
|
80
|
+
"""Why the main loop would use another model."""
|
|
81
|
+
if context.get("budget") and float(context.get("cost") or 0.0) >= context["budget"] * BUDGET_SHARE:
|
|
82
|
+
return "the budget is nearly used up"
|
|
83
|
+
if _token_budget_tight(context):
|
|
84
|
+
return "the token budget is nearly used up"
|
|
85
|
+
if float(context.get("tokens") or 0) > STRONG_TOKENS:
|
|
86
|
+
return "the context has grown"
|
|
87
|
+
if int(context.get("turns") or 0) > STRONG_TURNS:
|
|
88
|
+
return "the session has many turns"
|
|
89
|
+
for rule in self.config.routing_rules:
|
|
90
|
+
if RoutingRule(rule.when, rule.purpose).matches(context):
|
|
91
|
+
return f"the rule '{rule.when}' holds"
|
|
92
|
+
return "the rules of the routing say so"
|
|
93
|
+
|
|
94
|
+
def backend_for(self, name: str):
|
|
95
|
+
"""The backend of a model name."""
|
|
96
|
+
return LiteLLMBackend(
|
|
97
|
+
name,
|
|
98
|
+
model_kwargs=self.config.model_kwargs,
|
|
99
|
+
litellm_config=self.config.litellm_config,
|
|
100
|
+
reasoning_effort=self.config.reasoning_effort,
|
|
101
|
+
max_retries=self.config.max_retries,
|
|
102
|
+
api_key=self.config.api_key,
|
|
103
|
+
api_base=self.config.api_base,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
def _purpose(self, purpose: str, context: dict) -> str:
|
|
107
|
+
"""The purpose tier this call belongs to."""
|
|
108
|
+
for rule in self.config.routing_rules:
|
|
109
|
+
if RoutingRule(rule.when, rule.purpose).matches(context):
|
|
110
|
+
return rule.purpose
|
|
111
|
+
if purpose != "main":
|
|
112
|
+
return purpose
|
|
113
|
+
return self._default_purpose(context)
|
|
114
|
+
|
|
115
|
+
def _default_purpose(self, context: dict) -> str:
|
|
116
|
+
"""The policy of the main loop: cheaper when the budget is tight, stronger when it is big."""
|
|
117
|
+
budget = float(context.get("budget") or 0.0)
|
|
118
|
+
if budget and float(context.get("cost") or 0.0) >= budget * BUDGET_SHARE:
|
|
119
|
+
return CHEAP_PURPOSE
|
|
120
|
+
if _token_budget_tight(context):
|
|
121
|
+
"""A model without a price spends no money, so the token budget is the budget."""
|
|
122
|
+
return CHEAP_PURPOSE
|
|
123
|
+
if float(context.get("tokens") or 0) > STRONG_TOKENS:
|
|
124
|
+
return STRONG_PURPOSE
|
|
125
|
+
if int(context.get("turns") or 0) > STRONG_TURNS:
|
|
126
|
+
return STRONG_PURPOSE
|
|
127
|
+
return "main"
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _token_budget_tight(context: dict) -> bool:
|
|
131
|
+
"""True when the tokens of the session are close to the token budget."""
|
|
132
|
+
budget = float(context.get("token_budget") or 0.0)
|
|
133
|
+
return bool(budget) and float(context.get("tokens_used") or 0.0) >= budget * BUDGET_SHARE
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
__all__ = ["CHEAP_PURPOSE", "RoutingRule", "STRONG_PURPOSE", "ModelRouter"]
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""The settings of the model: the layers merged, the secrets taken out.
|
|
2
|
+
|
|
3
|
+
The terminal, the terminal interface and the browser all show the same eight
|
|
4
|
+
things: the name of the model, the provider, the address, whether a key is
|
|
5
|
+
set, where the key comes from and how many times a call is tried at most.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from coderagent.config.loader import load_config
|
|
13
|
+
from coderagent.config.schema import ModelConfig
|
|
14
|
+
from coderagent.models.litellm_config import resolve as resolve_alias
|
|
15
|
+
from coderagent.models.provider import env_key, env_var, normalize
|
|
16
|
+
from coderagent.models.provider import provider_of as provider_of_model
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def hint(secret: str) -> str:
|
|
20
|
+
"""A hint of a secret: enough to recognize it, too little to use it."""
|
|
21
|
+
if not secret:
|
|
22
|
+
return ""
|
|
23
|
+
return f"********{secret[-4:]}" if len(secret) > 4 else "********"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def api_base_of(endpoint: str) -> str:
|
|
27
|
+
"""The base of an endpoint: litellm adds the path of the chat completions itself.
|
|
28
|
+
|
|
29
|
+
The providers hand out the full address
|
|
30
|
+
(`https://api.example.com/v1/chat/completions`), the base stops at `/v1`.
|
|
31
|
+
"""
|
|
32
|
+
base = endpoint.strip().rstrip("/")
|
|
33
|
+
for suffix in ("/chat/completions", "/completions"):
|
|
34
|
+
if base.endswith(suffix):
|
|
35
|
+
return base[: -len(suffix)]
|
|
36
|
+
return base
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def provider_of(model_name: str, api_base: str = "") -> str:
|
|
40
|
+
"""The provider of a model: the name says it, the endpoint does, the family does."""
|
|
41
|
+
return provider_of_model(model_name, api_base)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def env_api_key(model_name: str, api_base: str = "") -> str:
|
|
45
|
+
"""The key the environment has for the provider of the model."""
|
|
46
|
+
return env_key(model_name, api_base)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def key_source(own_key: str, provider: str) -> str:
|
|
50
|
+
"""Where the key comes from: the settings, or the environment of the provider."""
|
|
51
|
+
if own_key:
|
|
52
|
+
return "settings"
|
|
53
|
+
return "env" if os.getenv(env_var(provider), "") else ""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def key_of(effective: dict) -> str:
|
|
57
|
+
"""The key of a run: the one of the settings or the one of the environment."""
|
|
58
|
+
kwargs = effective["model_kwargs"]
|
|
59
|
+
return str(kwargs.get("api_key") or env_api_key(effective["model_name"], str(kwargs.get("api_base") or "")))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def effective_of(model: ModelConfig, overrides: dict) -> dict:
|
|
63
|
+
"""The model to talk to and the kwargs to talk with, with the overrides applied.
|
|
64
|
+
|
|
65
|
+
An alias of a litellm config file is resolved here: the name becomes the
|
|
66
|
+
model of the provider and the parameters of the alias are the kwargs.
|
|
67
|
+
"""
|
|
68
|
+
kwargs = dict(model.model_kwargs)
|
|
69
|
+
if model.api_key:
|
|
70
|
+
kwargs["api_key"] = model.api_key
|
|
71
|
+
"""The field of its own wins over the old place of `model_kwargs`."""
|
|
72
|
+
if model.api_base:
|
|
73
|
+
kwargs["api_base"] = model.api_base
|
|
74
|
+
name = model.model_name
|
|
75
|
+
aliases = model.litellm_config
|
|
76
|
+
if isinstance(overrides.get("model_name"), str) and overrides["model_name"].strip():
|
|
77
|
+
name = overrides["model_name"].strip()
|
|
78
|
+
if isinstance(overrides.get("litellm_config"), str) and overrides["litellm_config"].strip():
|
|
79
|
+
aliases = overrides["litellm_config"].strip()
|
|
80
|
+
for key in ("api_base", "api_key"):
|
|
81
|
+
value = overrides.get(key)
|
|
82
|
+
if isinstance(value, str):
|
|
83
|
+
if value.strip():
|
|
84
|
+
kwargs[key] = api_base_of(value) if key == "api_base" else value.strip()
|
|
85
|
+
else:
|
|
86
|
+
kwargs.pop(key, None)
|
|
87
|
+
extra = overrides.get("model_kwargs")
|
|
88
|
+
if isinstance(extra, dict):
|
|
89
|
+
kwargs.update({key: value for key, value in extra.items() if key not in ("api_key", "api_base")})
|
|
90
|
+
resolved, params = resolve_alias(aliases, name)
|
|
91
|
+
merged = params | kwargs
|
|
92
|
+
base = str(merged.get("api_base") or "")
|
|
93
|
+
return {
|
|
94
|
+
"model_name": normalize(resolved, base),
|
|
95
|
+
"requested": name,
|
|
96
|
+
"alias": name if resolved != name else "",
|
|
97
|
+
"provider": provider_of(resolved, base),
|
|
98
|
+
"litellm_config": aliases,
|
|
99
|
+
"model_kwargs": merged,
|
|
100
|
+
"reasoning_effort": model.reasoning_effort,
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def effective_model(cwd: Path, overrides: dict) -> dict:
|
|
105
|
+
"""The model of a run: the layers merged, with the overrides applied."""
|
|
106
|
+
return effective_of(load_config([], cwd=cwd).model, overrides)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def effective_api_key(cwd: Path) -> str:
|
|
110
|
+
"""The key the agent would use: the one of the settings, the one of the alias or the one of the environment."""
|
|
111
|
+
config = load_config([], cwd=cwd)
|
|
112
|
+
name, params = resolve_alias(config.model.litellm_config, config.model.model_name)
|
|
113
|
+
base = str(config.model.api_base or config.model.model_kwargs.get("api_base") or params.get("api_base") or "")
|
|
114
|
+
key = (
|
|
115
|
+
config.model.api_key
|
|
116
|
+
or config.model.model_kwargs.get("api_key")
|
|
117
|
+
or params.get("api_key")
|
|
118
|
+
or env_api_key(name, base)
|
|
119
|
+
)
|
|
120
|
+
return str(key or "")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def model_view_of(model: ModelConfig) -> dict[str, Any]:
|
|
124
|
+
"""The settings of a model, with the secrets taken out.
|
|
125
|
+
|
|
126
|
+
Only the settings the settings page shows are here: the rest of the model
|
|
127
|
+
lives in the configuration file, and the file is the only place it is read
|
|
128
|
+
from.
|
|
129
|
+
"""
|
|
130
|
+
kwargs = dict(model.model_kwargs)
|
|
131
|
+
resolved, alias = resolve_alias(model.litellm_config, model.model_name)
|
|
132
|
+
base = str(model.api_base or kwargs.get("api_base") or alias.get("api_base") or "")
|
|
133
|
+
provider = provider_of(resolved, base)
|
|
134
|
+
own_key = model.api_key or kwargs.get("api_key") or alias.get("api_key")
|
|
135
|
+
key = own_key or env_api_key(resolved, base)
|
|
136
|
+
return {
|
|
137
|
+
"model_name": model.model_name,
|
|
138
|
+
"provider": provider,
|
|
139
|
+
"api_base": str(model.api_base or kwargs.get("api_base") or ""),
|
|
140
|
+
"api_key_set": bool(key),
|
|
141
|
+
"api_key_hint": hint(key),
|
|
142
|
+
"key_source": key_source(own_key, provider),
|
|
143
|
+
"key_env": env_var(provider),
|
|
144
|
+
"max_retries": model.max_retries,
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def model_view(cwd: Path) -> dict[str, Any]:
|
|
149
|
+
"""The settings of the model of a directory, with the secrets taken out."""
|
|
150
|
+
return model_view_of(load_config([], cwd=cwd).model)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def key_text(view: dict) -> str:
|
|
154
|
+
"""The key of a view, in a line: whether it is set and where it comes from."""
|
|
155
|
+
if not view.get("api_key_set"):
|
|
156
|
+
return "not set"
|
|
157
|
+
source = "the settings" if view.get("key_source") == "settings" else f"the environment ({view.get('key_env', '')})"
|
|
158
|
+
return f"set ({view.get('api_key_hint', '')}) from {source}"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def view_text(view: dict, path: str = "") -> str:
|
|
162
|
+
"""The settings of the model, as the terminal and the interface show them."""
|
|
163
|
+
lines = [
|
|
164
|
+
f"model: {view.get('model_name', '')}",
|
|
165
|
+
f"provider: {view.get('provider', '') or '(none)'}",
|
|
166
|
+
f"api base: {view.get('api_base', '') or '(none)'}",
|
|
167
|
+
f"api key: {key_text(view)}",
|
|
168
|
+
f"max retries: {view.get('max_retries', 0)}",
|
|
169
|
+
]
|
|
170
|
+
if path:
|
|
171
|
+
lines.append(f"file: {path}")
|
|
172
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Streaming model events.
|
|
2
|
+
|
|
3
|
+
A streamed answer arrives in pieces: text, reasoning and the fragments of a tool
|
|
4
|
+
call. `ModelEvent` is the common currency between the backends and the UI, and
|
|
5
|
+
`message_from_events` folds the pieces back into one assistant message.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from coderagent.compat import FormatError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class ModelEvent:
|
|
17
|
+
type: str
|
|
18
|
+
"""One of `text`, `reasoning`, `tool_call_delta`, `tool_call_done`, `usage`, `error`."""
|
|
19
|
+
content: str = ""
|
|
20
|
+
tool_call: dict | None = None
|
|
21
|
+
cost: float = 0.0
|
|
22
|
+
raw: dict = field(default_factory=dict)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _format_error(message: str) -> FormatError:
|
|
26
|
+
"""The FormatError keeps the details in `messages`, not in the text."""
|
|
27
|
+
error = FormatError({"error": message})
|
|
28
|
+
error.args = (message,)
|
|
29
|
+
return error
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ToolCallAccumulator:
|
|
33
|
+
"""Collects the pieces of the tool calls that arrive in pieces.
|
|
34
|
+
|
|
35
|
+
Providers differ: some send the function name once, some repeat it in every
|
|
36
|
+
fragment, some split it. The arguments always arrive as JSON fragments.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(self) -> None:
|
|
40
|
+
self._calls: dict[int, dict] = {}
|
|
41
|
+
|
|
42
|
+
def feed(self, delta: dict) -> None:
|
|
43
|
+
index = delta.get("index", 0)
|
|
44
|
+
call = self._calls.setdefault(index, {"id": "", "name": "", "arguments": ""})
|
|
45
|
+
if delta.get("id"):
|
|
46
|
+
call["id"] = delta["id"]
|
|
47
|
+
function = delta.get("function") or {}
|
|
48
|
+
call["name"] = self._merge_name(call["name"], function.get("name") or "")
|
|
49
|
+
call["arguments"] += function.get("arguments") or ""
|
|
50
|
+
|
|
51
|
+
@staticmethod
|
|
52
|
+
def _merge_name(current: str, fragment: str) -> str:
|
|
53
|
+
"""Add a name fragment, without repeating what we already have."""
|
|
54
|
+
if not fragment or fragment == current:
|
|
55
|
+
return current
|
|
56
|
+
if not current:
|
|
57
|
+
return fragment
|
|
58
|
+
if fragment.startswith(current):
|
|
59
|
+
return fragment
|
|
60
|
+
if current.startswith(fragment):
|
|
61
|
+
return current
|
|
62
|
+
return current + fragment
|
|
63
|
+
|
|
64
|
+
def finish(self) -> list[dict]:
|
|
65
|
+
"""The parsed tool calls. Raises FormatError when the arguments are not JSON."""
|
|
66
|
+
calls = []
|
|
67
|
+
for index in sorted(self._calls):
|
|
68
|
+
call = self._calls[index]
|
|
69
|
+
try:
|
|
70
|
+
json.loads(call["arguments"] or "{}")
|
|
71
|
+
except json.JSONDecodeError as error:
|
|
72
|
+
raise _format_error(f"could not parse the arguments of '{call['name']}' as JSON: {error}") from error
|
|
73
|
+
calls.append(
|
|
74
|
+
{
|
|
75
|
+
"id": call["id"],
|
|
76
|
+
"type": "function",
|
|
77
|
+
"function": {"name": call["name"], "arguments": call["arguments"] or "{}"},
|
|
78
|
+
}
|
|
79
|
+
)
|
|
80
|
+
return calls
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def message_from_events(events) -> dict:
|
|
84
|
+
"""Fold a stream of events back into one assistant message."""
|
|
85
|
+
content: list[str] = []
|
|
86
|
+
reasoning: list[str] = []
|
|
87
|
+
tool_calls: list[dict] = []
|
|
88
|
+
cost = 0.0
|
|
89
|
+
tokens_in = 0
|
|
90
|
+
tokens_out = 0
|
|
91
|
+
for event in events:
|
|
92
|
+
if event.type == "text":
|
|
93
|
+
content.append(event.content)
|
|
94
|
+
elif event.type == "reasoning":
|
|
95
|
+
reasoning.append(event.content)
|
|
96
|
+
elif event.type == "tool_call_done" and event.tool_call:
|
|
97
|
+
tool_calls.append(event.tool_call)
|
|
98
|
+
elif event.type == "usage":
|
|
99
|
+
cost += event.cost
|
|
100
|
+
prompt, completion = usage_tokens(event.raw.get("usage"))
|
|
101
|
+
tokens_in += prompt
|
|
102
|
+
tokens_out += completion
|
|
103
|
+
message: dict[str, Any] = {
|
|
104
|
+
"role": "assistant",
|
|
105
|
+
"content": "".join(content),
|
|
106
|
+
"extra": {"cost": cost, "tokens_in": tokens_in, "tokens_out": tokens_out},
|
|
107
|
+
}
|
|
108
|
+
if reasoning:
|
|
109
|
+
message["extra"]["reasoning"] = "".join(reasoning)
|
|
110
|
+
# An empty tool_calls array is rejected by some providers, so it is left out.
|
|
111
|
+
if tool_calls:
|
|
112
|
+
message["tool_calls"] = tool_calls
|
|
113
|
+
return message
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def usage_tokens(usage) -> tuple[int, int]:
|
|
117
|
+
"""The tokens of a usage object, which is a dict or a model."""
|
|
118
|
+
if usage is None:
|
|
119
|
+
return 0, 0
|
|
120
|
+
if isinstance(usage, dict):
|
|
121
|
+
return int(usage.get("prompt_tokens") or 0), int(usage.get("completion_tokens") or 0)
|
|
122
|
+
return int(getattr(usage, "prompt_tokens", 0) or 0), int(getattr(usage, "completion_tokens", 0) or 0)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""How much the model says. Provider agnostic: it is an instruction, not a parameter."""
|
|
2
|
+
|
|
3
|
+
VERBOSITIES = ("low", "medium", "high")
|
|
4
|
+
|
|
5
|
+
NOTES = {
|
|
6
|
+
"low": "Answer briefly: the result and what changed, without the reasoning behind it.",
|
|
7
|
+
"medium": "Answer with the result and the reasoning that matters, without padding.",
|
|
8
|
+
"high": "Answer in detail: the result, the reasoning, and the caveats.",
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def note(level: str) -> str:
|
|
13
|
+
"""The line that goes into the system prompt. Empty for the habit of the model."""
|
|
14
|
+
return NOTES.get(level, "")
|
coderagent/paths.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Where the coding agent keeps its configuration and session data."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def config_home() -> Path:
|
|
8
|
+
"""Root of the coder agent's user-level data. Overridable via `MSWEA_CODER_HOME`."""
|
|
9
|
+
home = os.getenv("MSWEA_CODER_HOME")
|
|
10
|
+
return Path(home) if home else Path.home() / ".coderagent"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def global_env_file() -> Path:
|
|
14
|
+
"""The file with the keys of the models. The same one mini-swe-agent uses."""
|
|
15
|
+
from platformdirs import user_config_dir
|
|
16
|
+
|
|
17
|
+
return Path(os.getenv("MSWEA_GLOBAL_CONFIG_DIR") or user_config_dir("mini-swe-agent")) / ".env"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def load_global_env() -> None:
|
|
21
|
+
"""Load the keys of the models into the environment.
|
|
22
|
+
|
|
23
|
+
Two files are read: the one of the coding agent and the one that
|
|
24
|
+
mini-swe-agent used. The keys that are already in the environment win, and
|
|
25
|
+
the file of the coding agent wins over the one of mini-swe-agent.
|
|
26
|
+
"""
|
|
27
|
+
from dotenv import load_dotenv
|
|
28
|
+
|
|
29
|
+
for path in (config_home() / ".env", global_env_file()):
|
|
30
|
+
if path.is_file():
|
|
31
|
+
load_dotenv(dotenv_path=path, override=False)
|