File size: 8,405 Bytes
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
"""TOML configuration with explicit validation and no stored API keys."""

from __future__ import annotations

from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from urllib.parse import urlparse

try:
    import tomllib
except ModuleNotFoundError:
    import tomli as tomllib


class ConfigError(ValueError):
    pass


@dataclass
class ProviderSettings:
    type: str = "openai"
    base_url: str = "https://api.openai.com/v1"
    model: str = "gpt-4.1-mini"
    api_key_env: str = "NANO_API_KEY"
    max_tokens: int = 8000
    temperature: float = 0.0


@dataclass
class AgentSettings:
    max_turns: int = 10
    max_tool_output_chars: int = 20000


@dataclass
class WorkspaceSettings:
    test_command: list[str] | None = None
    test_timeout_seconds: int = 120


@dataclass
class PromptSettings:
    system: list[str] = field(default_factory=lambda: ["system"])
    directories: list[str] = field(default_factory=list)


@dataclass
class SkillSettings:
    directories: list[str] = field(default_factory=list)


@dataclass
class TodoSettings:
    enabled: bool = False
    ledger_path: str = ".nano_agent/todo.json"
    contract_path: str = ".nano_agent/todo_contract.json"
    run_id: str = ""
    writer_session: str = "A"


@dataclass
class Settings:
    provider: ProviderSettings = field(default_factory=ProviderSettings)
    agent: AgentSettings = field(default_factory=AgentSettings)
    workspace: WorkspaceSettings = field(default_factory=WorkspaceSettings)
    prompts: PromptSettings = field(default_factory=PromptSettings)
    skills: SkillSettings = field(default_factory=SkillSettings)
    todo: TodoSettings = field(default_factory=TodoSettings)


def _table(data: dict[str, Any], key: str) -> dict[str, Any]:
    value = data.get(key, {})
    if not isinstance(value, dict):
        raise ConfigError(f"[{key}] must be a TOML table")
    return value


def _positive_int(value: Any, name: str) -> int:
    if isinstance(value, bool) or not isinstance(value, int) or value < 1:
        raise ConfigError(f"{name} must be a positive integer")
    return value


def _string(value: Any, name: str) -> str:
    if not isinstance(value, str) or not value.strip():
        raise ConfigError(f"{name} must be a non-empty string")
    return value.strip()


def _string_list(value: Any, name: str, *, allow_empty: bool) -> list[str]:
    if not isinstance(value, list) or (not allow_empty and not value):
        qualifier = "an array" if allow_empty else "a non-empty array"
        raise ConfigError(f"{name} must be {qualifier} of non-empty strings")
    result: list[str] = []
    for item in value:
        if not isinstance(item, str) or not item.strip():
            raise ConfigError(f"{name} must contain only non-empty strings")
        result.append(item.strip())
    return result


def _internal_todo_path(value: Any, name: str) -> str:
    result = _string(value, name)
    path = Path(result)
    if path.is_absolute() or ".." in path.parts or path.parts[:1] != (".nano_agent",):
        raise ConfigError(f"{name} must be a relative path inside .nano_agent")
    return result


def load_config(workspace_root: Path) -> Settings:
    settings = Settings()
    path = workspace_root / "nano_agent.toml"
    if not path.is_file():
        return settings

    with path.open("rb") as stream:
        data = tomllib.load(stream)
    if not isinstance(data, dict):
        raise ConfigError("nano_agent.toml must contain TOML tables")

    provider = _table(data, "provider")
    agent = _table(data, "agent")
    workspace = _table(data, "workspace")

    if "api_key" in provider:
        raise ConfigError("provider.api_key is forbidden; use provider.api_key_env")

    settings.provider.type = _string(provider.get("type", settings.provider.type), "provider.type")
    if settings.provider.type != "openai":
        raise ConfigError("provider.type must be 'openai'")
    settings.provider.base_url = _string(
        provider.get("base_url", settings.provider.base_url), "provider.base_url"
    )
    parsed_base_url = urlparse(settings.provider.base_url)
    if parsed_base_url.scheme not in {"http", "https"} or not parsed_base_url.netloc:
        raise ConfigError("provider.base_url must be an absolute HTTP(S) URL")
    settings.provider.model = _string(provider.get("model", settings.provider.model), "provider.model")
    settings.provider.api_key_env = _string(
        provider.get("api_key_env", settings.provider.api_key_env), "provider.api_key_env"
    )
    settings.provider.max_tokens = _positive_int(
        provider.get("max_tokens", settings.provider.max_tokens), "provider.max_tokens"
    )
    temperature = provider.get("temperature", settings.provider.temperature)
    if isinstance(temperature, bool) or not isinstance(temperature, (int, float)):
        raise ConfigError("provider.temperature must be a number")
    if not 0.0 <= float(temperature) <= 2.0:
        raise ConfigError("provider.temperature must be between 0 and 2")
    settings.provider.temperature = float(temperature)

    settings.agent.max_turns = _positive_int(
        agent.get("max_turns", settings.agent.max_turns), "agent.max_turns"
    )
    settings.agent.max_tool_output_chars = _positive_int(
        agent.get("max_tool_output_chars", settings.agent.max_tool_output_chars),
        "agent.max_tool_output_chars",
    )

    command = workspace.get("test_command")
    if command is not None:
        if (
            not isinstance(command, list)
            or not command
            or not all(isinstance(item, str) and item for item in command)
        ):
            raise ConfigError("workspace.test_command must be a non-empty array of strings")
        settings.workspace.test_command = list(command)
    settings.workspace.test_timeout_seconds = _positive_int(
        workspace.get("test_timeout_seconds", settings.workspace.test_timeout_seconds),
        "workspace.test_timeout_seconds",
    )

    prompts = _table(data, "prompts")
    if "system" in prompts:
        settings.prompts.system = _string_list(
            prompts["system"], "prompts.system", allow_empty=False
        )
    if "directories" in prompts:
        settings.prompts.directories = _string_list(
            prompts["directories"], "prompts.directories", allow_empty=True
        )
    unknown_prompt_keys = set(prompts) - {"system", "directories"}
    if unknown_prompt_keys:
        raise ConfigError(f"unknown keys in [prompts]: {sorted(unknown_prompt_keys)}")

    skills = _table(data, "skills")
    if "directories" in skills:
        settings.skills.directories = _string_list(
            skills["directories"], "skills.directories", allow_empty=True
        )
    unknown_skill_keys = set(skills) - {"directories"}
    if unknown_skill_keys:
        raise ConfigError(f"unknown keys in [skills]: {sorted(unknown_skill_keys)}")

    todo = _table(data, "todo")
    unknown_todo_keys = set(todo) - {"enabled", "ledger_path", "contract_path", "run_id", "writer_session"}
    if unknown_todo_keys:
        raise ConfigError(f"unknown keys in [todo]: {sorted(unknown_todo_keys)}")
    enabled = todo.get("enabled", False)
    if not isinstance(enabled, bool):
        raise ConfigError("todo.enabled must be a boolean")
    settings.todo.enabled = enabled
    settings.todo.ledger_path = _internal_todo_path(
        todo.get("ledger_path", settings.todo.ledger_path), "todo.ledger_path"
    )
    settings.todo.contract_path = _internal_todo_path(
        todo.get("contract_path", settings.todo.contract_path), "todo.contract_path"
    )
    if "run_id" in todo:
        settings.todo.run_id = _string(todo["run_id"], "todo.run_id")
    if "writer_session" in todo:
        settings.todo.writer_session = _string(todo["writer_session"], "todo.writer_session")
    if len(settings.todo.writer_session) > 64 or any(char.isspace() for char in settings.todo.writer_session):
        raise ConfigError("todo.writer_session must be a bounded token")
    if settings.todo.enabled and not settings.todo.run_id:
        raise ConfigError("todo.run_id is required when todo.enabled is true")

    if "api_key_env" in provider:
        import re
        if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", settings.provider.api_key_env):
            raise ConfigError("provider.api_key_env must be an environment-variable name")

    return settings