bannaha 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 (65) hide show
  1. bannaha/__init__.py +3 -0
  2. bannaha/backends.py +46 -0
  3. bannaha/cli/__init__.py +0 -0
  4. bannaha/cli/app.py +328 -0
  5. bannaha/cli/config.py +113 -0
  6. bannaha/cli/live.py +421 -0
  7. bannaha/cli/runner.py +136 -0
  8. bannaha/cli/themes.py +34 -0
  9. bannaha/cli/transcript.py +471 -0
  10. bannaha/consensus/__init__.py +1 -0
  11. bannaha/consensus/ballots.py +16 -0
  12. bannaha/consensus/clustering.py +138 -0
  13. bannaha/consensus/quorum.py +19 -0
  14. bannaha/core/__init__.py +0 -0
  15. bannaha/core/board.py +266 -0
  16. bannaha/core/errors.py +22 -0
  17. bannaha/core/events.py +65 -0
  18. bannaha/core/fleet.py +96 -0
  19. bannaha/core/limits.py +18 -0
  20. bannaha/core/outcome.py +20 -0
  21. bannaha/core/pricing.py +176 -0
  22. bannaha/core/registry.py +69 -0
  23. bannaha/core/runlog.py +55 -0
  24. bannaha/core/session.py +399 -0
  25. bannaha/core/text.py +80 -0
  26. bannaha/core/tools.py +57 -0
  27. bannaha/features/__init__.py +0 -0
  28. bannaha/features/base.py +33 -0
  29. bannaha/features/dropout.py +54 -0
  30. bannaha/features/peer_updates.py +38 -0
  31. bannaha/followup.py +328 -0
  32. bannaha/harnesses/__init__.py +0 -0
  33. bannaha/harnesses/adk.py +122 -0
  34. bannaha/harnesses/anthropic_sdk.py +76 -0
  35. bannaha/harnesses/banna.py +142 -0
  36. bannaha/harnesses/base.py +99 -0
  37. bannaha/harnesses/hermes.py +156 -0
  38. bannaha/harnesses/mock.py +100 -0
  39. bannaha/harnesses/openai_agents.py +140 -0
  40. bannaha/strategies/__init__.py +0 -0
  41. bannaha/strategies/base.py +75 -0
  42. bannaha/strategies/blackboard.py +199 -0
  43. bannaha/strategies/single.py +46 -0
  44. bannaha/strategies/vote.py +46 -0
  45. bannaha/tools/__init__.py +0 -0
  46. bannaha/tools/comms.py +229 -0
  47. bannaha/tools/documents.py +140 -0
  48. bannaha/tools/research.py +128 -0
  49. bannaha/tools/sandbox.py +102 -0
  50. bannaha/tools/toolbox.py +71 -0
  51. bannaha/tools/web_search.py +83 -0
  52. bannaha/tui/__init__.py +1 -0
  53. bannaha/tui/app.py +81 -0
  54. bannaha/tui/banner.py +238 -0
  55. bannaha/tui/fleet.py +169 -0
  56. bannaha/tui/keys.py +156 -0
  57. bannaha/tui/run.py +418 -0
  58. bannaha/tui/runs.py +166 -0
  59. bannaha/tui/setup.py +323 -0
  60. bannaha/tui/widgets.py +132 -0
  61. bannaha-0.1.0.dist-info/METADATA +351 -0
  62. bannaha-0.1.0.dist-info/RECORD +65 -0
  63. bannaha-0.1.0.dist-info/WHEEL +4 -0
  64. bannaha-0.1.0.dist-info/entry_points.txt +2 -0
  65. bannaha-0.1.0.dist-info/licenses/LICENSE +21 -0
bannaha/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """bannaha — a terminal sandbox for multi-agent coordination strategies."""
2
+
3
+ __version__ = "0.1.0"
bannaha/backends.py ADDED
@@ -0,0 +1,46 @@
1
+ """Shared backend details: endpoints, Bedrock credentials, optional packages.
2
+
3
+ Backends are not classes of their own: each harness knows how to reach a
4
+ model through the backends it supports. This module holds what they share.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import importlib.util
9
+ import os
10
+
11
+ OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
12
+ OPENAI_BASE_URL = "https://api.openai.com/v1"
13
+ BACKENDS = {
14
+ "direct": "the model vendor's own API",
15
+ "openrouter": "OpenRouter (one key, many vendors' models)",
16
+ "bedrock": "Amazon Bedrock (AWS credentials and region)",
17
+ "local": "runs locally, no network (mock harness)",
18
+ }
19
+
20
+
21
+ def aws_region() -> str | None:
22
+ return os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION")
23
+
24
+
25
+ def bedrock_problems() -> list[str]:
26
+ problems = []
27
+ if not aws_region():
28
+ problems.append("bedrock needs AWS_REGION (or AWS_DEFAULT_REGION)")
29
+ if importlib.util.find_spec("boto3") is None:
30
+ problems.append("bedrock needs boto3: install 'bannaha[bedrock]'")
31
+ return problems
32
+ import boto3
33
+
34
+ try:
35
+ if boto3.Session().get_credentials() is None:
36
+ problems.append("bedrock found no AWS credentials (set AWS_PROFILE, or AWS access keys, or log in "
37
+ "with `aws sso login`)")
38
+ except Exception as exc: # botocore raises many profile/config errors
39
+ problems.append(f"bedrock credentials could not be loaded: {exc}")
40
+ return problems
41
+
42
+
43
+ def litellm_problems(harness: str, backend: str) -> list[str]:
44
+ if importlib.util.find_spec("litellm") is None:
45
+ return [f"{harness}@{backend} goes through LiteLLM: install 'bannaha[litellm]'"]
46
+ return []
File without changes
bannaha/cli/app.py ADDED
@@ -0,0 +1,328 @@
1
+ """bannaha command line: `bannaha` opens the full-screen interface, `bannaha run` is the scriptable path."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import typer
9
+ from rich.console import Console
10
+ from rich.markup import escape
11
+ from rich.prompt import Prompt
12
+ from rich.table import Table
13
+
14
+ from .. import __version__
15
+ from ..core.errors import BannahaError
16
+ from ..core.fleet import parse_fleet
17
+ from ..core.outcome import Outcome
18
+ from ..core.pricing import PRICE_LINKS, load_openrouter, price_for, price_table_md
19
+ from ..core.registry import harnesses, strategies
20
+ from ..core.runlog import default_runs_dir
21
+ from ..core.text import clip, tilde
22
+ from ..tools.web_search import search_key_present
23
+ from .config import Settings, config_path, load_env_files, load_settings
24
+ from .live import run_live, run_plain
25
+ from .runner import RunArgs, prepare
26
+ from .themes import THEMES, get_theme
27
+ from .transcript import fleet_colors, run_stream
28
+
29
+ app = typer.Typer(
30
+ name="bannaha",
31
+ help="A terminal sandbox for multi-agent coordination strategies. Run with no arguments for the full-screen app.",
32
+ add_completion=False,
33
+ no_args_is_help=False,
34
+ rich_markup_mode="rich",
35
+ context_settings={"help_option_names": ["-h", "--help"]},
36
+ )
37
+
38
+
39
+ def execute(question: str, a: RunArgs, s: Settings, console: Console) -> Outcome | None:
40
+ theme = get_theme(a.theme or s.theme)
41
+ try:
42
+ prepared, problems = prepare(question, s, a)
43
+ except BannahaError as exc:
44
+ prepared, problems = None, [str(exc)]
45
+ if prepared is None:
46
+ console.print(f"[{theme.err}]cannot start:[/]")
47
+ for p in problems:
48
+ console.print(f" • {escape(p)}")
49
+ return None
50
+ captured: list = []
51
+ prepared.session.bus.subscribe(captured.append)
52
+ if a.plain or not console.is_terminal:
53
+ outcome = run_plain(prepared.session, console, theme, prepared.run_dir)
54
+ elif a.dashboard:
55
+ outcome = run_live(prepared.session, console, theme, prepared.run_dir)
56
+ else:
57
+ outcome = run_stream(prepared.session, console, theme, prepared.run_dir, full=a.full)
58
+ if a.json_out and outcome is not None:
59
+ run_dir = str(prepared.run_dir) if prepared.run_dir else None
60
+ console.print_json(json.dumps({"run_dir": run_dir, **outcome.to_dict()}, default=str))
61
+ elif a.followup and outcome is not None and console.is_terminal and sys.stdin.isatty() and not a.plain:
62
+ from ..followup import RunMemory
63
+
64
+ followup_loop(console, theme, s, RunMemory.from_events(captured, prepared.run_dir), a)
65
+ return outcome
66
+
67
+
68
+ def followup_loop(console: Console, theme, s: Settings, memory, a: RunArgs | None = None, *,
69
+ first: str | None = None, once: bool = False, agent: str | None = None) -> None:
70
+ """Questions about a finished run, with the run as memory; /new and /rerun start runs."""
71
+ from ..followup import FollowUp, RunMemory, help_renderable, parse_command, rerun_question
72
+ from ..tools.toolbox import ToolOptions
73
+ from .runner import limits_for
74
+
75
+ chat = FollowUp(memory, agent=agent)
76
+ opts = ToolOptions(web=s.web if (a is None or a.web is None) else a.web,
77
+ python=s.python if (a is None or a.python is None) else a.python,
78
+ sandbox=(a.sandbox if a and a.sandbox else s.sandbox), search_model=s.search_model)
79
+ if not once:
80
+ console.print(f"\n[{theme.muted}]Ask about the answer: follow-ups go to[/] [bold]{chat.agent_id()} "
81
+ f"{escape(chat.agent)}[/] [{theme.muted}](the strongest model in the fleet). /help for "
82
+ f"commands, ctrl-d to exit.[/]")
83
+ pending = first
84
+ while True:
85
+ if pending is None:
86
+ try:
87
+ text = console.input(f"[bold {theme.accent}]› [/]").strip()
88
+ except (EOFError, KeyboardInterrupt):
89
+ console.print()
90
+ return
91
+ else:
92
+ text, pending = pending, None
93
+ if not text:
94
+ continue
95
+ cmd, arg = parse_command(text)
96
+ if cmd in ("/exit", "/quit"):
97
+ return
98
+ if cmd == "/help":
99
+ console.print(help_renderable(theme))
100
+ elif cmd in ("/new", "/rerun"):
101
+ if not arg:
102
+ console.print(f"[{theme.warn}]usage: {cmd} <{'task' if cmd == '/new' else 'clarification'}>[/]")
103
+ continue
104
+ question = arg if cmd == "/new" else rerun_question(chat.memory, arg)
105
+ prepared, problems = prepare(question, s, RunArgs(followup=False))
106
+ if prepared is None:
107
+ for p in problems:
108
+ console.print(f" • {escape(p)}")
109
+ continue
110
+ captured: list = []
111
+ prepared.session.bus.subscribe(captured.append)
112
+ run_stream(prepared.session, console, theme, prepared.run_dir)
113
+ chat = FollowUp(RunMemory.from_events(captured, prepared.run_dir))
114
+ console.print(f"[{theme.muted}]follow-ups now go to[/] [bold]{chat.agent_id()} {escape(chat.agent)}[/]")
115
+ elif cmd == "/to":
116
+ try:
117
+ label = chat.set_agent(arg)
118
+ console.print(f"[{theme.muted}]follow-ups now go to[/] [bold]{chat.agent_id()} {escape(label)}[/]")
119
+ except BannahaError as exc:
120
+ console.print(f"[{theme.err}]{escape(str(exc))}[/]")
121
+ elif cmd == "/agents":
122
+ for x in chat.memory.fleet:
123
+ mark = " ← answers follow-ups" if x["label"] == chat.agent else ""
124
+ console.print(f" {x['id']} {escape(x['label'])}{mark}")
125
+ elif cmd == "/forget":
126
+ chat.forget()
127
+ console.print(f"[{theme.muted}]follow-up conversation cleared (the run's memory stays)[/]")
128
+ elif cmd is not None:
129
+ console.print(f"[{theme.warn}]unknown command {escape(cmd)}; /help lists them[/]")
130
+ else:
131
+ session = chat.session(text, opts, limits_for(s, a))
132
+ outcome = run_stream(session, console, theme, None, followup=True, colors=fleet_colors(chat.memory.fleet))
133
+ chat.record(text, outcome, session.total_cost())
134
+ if once:
135
+ return
136
+
137
+
138
+ def _open_tui(start: str) -> None:
139
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
140
+ Console(stderr=True).print("bannaha's full-screen app needs a terminal; use `bannaha run` in scripts "
141
+ "(see `bannaha --help`).")
142
+ raise typer.Exit(2)
143
+ from ..tui.app import run_tui
144
+
145
+ run_tui(start)
146
+
147
+
148
+ @app.callback(invoke_without_command=True)
149
+ def main(ctx: typer.Context,
150
+ version: bool = typer.Option(False, "--version", "-V", is_eager=True, help="Show version and exit.")) -> None:
151
+ if version:
152
+ typer.echo(f"bannaha {__version__}")
153
+ raise typer.Exit()
154
+ if ctx.invoked_subcommand is None:
155
+ _open_tui("setup")
156
+
157
+
158
+ @app.command()
159
+ def run(
160
+ question: str = typer.Argument(None, help="The question. Omit to be prompted."),
161
+ strategy: str = typer.Option(None, "--strategy", "-s", help="Coordination strategy (see `bannaha list`)."),
162
+ fleet: str = typer.Option(None, "--fleet", "-f", help="harness@backend:model*count, comma separated."),
163
+ web: bool = typer.Option(None, "--web/--no-web", help="Gemini web search and page fetch."),
164
+ python: bool = typer.Option(None, "--python/--no-python", help="The run_python tool."),
165
+ sandbox: str = typer.Option(None, "--sandbox", help="run_python isolation: process or docker."),
166
+ peer_updates: bool = typer.Option(None, "--peer-updates/--no-peer-updates",
167
+ help="Attach peers' new board activity to tool results."),
168
+ drop: float = typer.Option(None, "--drop", help="Fault injection: fraction (<1) or number of agents to drop."),
169
+ drop_after: int = typer.Option(None, "--drop-after", help="Dropped agents go dark after this many tool calls."),
170
+ seed: int = typer.Option(None, "--seed", help="Seed for choosing which agents drop."),
171
+ opt: list[str] = typer.Option([], "--opt", "-o", help="Strategy option key=value (repeatable)."),
172
+ max_wall: float = typer.Option(None, "--max-wall", help="Wall-time limit in seconds."),
173
+ max_calls: int = typer.Option(None, "--max-calls", help="Tool calls allowed per agent turn."),
174
+ max_tokens: int = typer.Option(None, "--max-tokens", help="Stop after this many tokens in total."),
175
+ max_cost: float = typer.Option(None, "--max-cost", help="Stop the run at this spend in USD (list prices)."),
176
+ max_agent_cost: float = typer.Option(None, "--max-agent-cost",
177
+ help="End an agent's work once it has spent this much in USD."),
178
+ search_model: str = typer.Option(None, "--search-model", help="Gemini model used for web search."),
179
+ theme: str = typer.Option(None, "--theme", help=f"Color theme: {', '.join(THEMES)}."),
180
+ plain: bool = typer.Option(False, "--plain", help="Print one line per event instead of the live view."),
181
+ dashboard: bool = typer.Option(False, "--dashboard", help="The boxed dashboard view instead of the transcript."),
182
+ full: bool = typer.Option(False, "--full", help="Show tool results in full in the transcript."),
183
+ json_out: bool = typer.Option(False, "--json", help="Print the outcome as JSON at the end."),
184
+ runs_dir: Path = typer.Option(None, "--runs-dir", help=f"Where runs are saved (default {default_runs_dir()})."),
185
+ no_save: bool = typer.Option(False, "--no-save", help="Do not write the run to disk."),
186
+ no_followup: bool = typer.Option(False, "--no-followup", help="Exit when the run ends instead of taking "
187
+ "follow-up questions."),
188
+ ) -> None:
189
+ """Run one question without the full-screen app (scripts, CI, quick checks)."""
190
+ settings, _ = load_settings()
191
+ console = Console()
192
+ if not question:
193
+ question = Prompt.ask("question")
194
+ args = RunArgs(strategy=strategy, fleet=fleet, web=web, python=python, sandbox=sandbox,
195
+ peer_updates=peer_updates, drop=drop, drop_after=drop_after, seed=seed, opts=list(opt),
196
+ max_wall=max_wall, max_calls=max_calls, max_tokens=max_tokens, max_cost=max_cost,
197
+ max_agent_cost=max_agent_cost, search_model=search_model,
198
+ theme=theme, plain=plain, json_out=json_out, runs_dir=runs_dir, save=not no_save,
199
+ dashboard=dashboard, full=full, followup=not no_followup)
200
+ outcome = execute(question, args, settings, console)
201
+ if outcome is None:
202
+ raise typer.Exit(2)
203
+ raise typer.Exit(0 if outcome.status == "committed" else 1)
204
+
205
+
206
+ @app.command()
207
+ def ask(
208
+ run_dir: str = typer.Argument("last", help="A run folder, or 'last' for the most recent run."),
209
+ question: str = typer.Argument(None, help="One question; omit it to keep asking."),
210
+ to: str = typer.Option(None, "--to", help="Who answers: a fleet id (a3) or harness@backend:model."),
211
+ ) -> None:
212
+ """Ask follow-up questions about a finished run, with that run as memory."""
213
+ from ..followup import RunMemory
214
+
215
+ settings, _ = load_settings()
216
+ console = Console()
217
+ theme = get_theme(settings.theme)
218
+ if run_dir == "last":
219
+ root = default_runs_dir()
220
+ runs = sorted((p for p in root.iterdir() if (p / "events.jsonl").is_file()), reverse=True) \
221
+ if root.is_dir() else []
222
+ if not runs:
223
+ console.print("no saved runs yet")
224
+ raise typer.Exit(2)
225
+ path = runs[0]
226
+ else:
227
+ path = Path(run_dir).expanduser()
228
+ memory = RunMemory.from_dir(path)
229
+ console.print(f"[{theme.muted}]run[/] {tilde(path)} · {escape(clip(memory.question, 120))} → "
230
+ f"[bold]{escape(str((memory.outcome or {}).get('answer')))}[/]")
231
+ agent = None
232
+ if to:
233
+ by_id = {a["id"]: a["label"] for a in memory.fleet}
234
+ agent = by_id.get(to, to)
235
+ followup_loop(console, theme, settings, memory, first=question, once=question is not None, agent=agent)
236
+
237
+
238
+ @app.command()
239
+ def setup() -> None:
240
+ """Open the full-screen app on the Setup page."""
241
+ _open_tui("setup")
242
+
243
+
244
+ @app.command("list")
245
+ def list_cmd(what: str = typer.Argument("all", help="strategies, harnesses, tools or all")) -> None:
246
+ """Show what is available."""
247
+ console = Console()
248
+ t = get_theme(load_settings()[0].theme)
249
+ if what in ("all", "strategies"):
250
+ table = Table(title="strategies", title_justify="left", box=None)
251
+ table.add_column("name", style=t.accent)
252
+ table.add_column("summary")
253
+ table.add_column("options", style=t.muted)
254
+ for name, cls in strategies().items():
255
+ opts = ", ".join(f"{k}={o.default}" for k, o in cls.options.items())
256
+ table.add_row(name, cls.summary, opts)
257
+ console.print(table)
258
+ if what in ("all", "harnesses"):
259
+ table = Table(title="harnesses", title_justify="left", box=None)
260
+ table.add_column("name", style=t.accent)
261
+ table.add_column("backends")
262
+ table.add_column("installed")
263
+ table.add_column("summary", style=t.muted)
264
+ for name, cls in harnesses().items():
265
+ installed = "yes" if cls.available() else escape(f"no: bannaha[{cls.extra}]")
266
+ table.add_row(name, ", ".join(cls.backends), installed, cls.summary)
267
+ console.print(table)
268
+ if what in ("all", "tools"):
269
+ console.print(f"[{t.title}]tools[/]")
270
+ console.print(" research web_search, fetch_page, search_documents (need --web), run_python")
271
+ console.print(" board read_board, post_claim, endorse_claim, challenge_claim, corroborate, send_message, "
272
+ "read_messages")
273
+ console.print(" finish final_answer, propose_answer, cast_vote, reply (follow-ups)")
274
+ console.print(f" web search key: {'found' if search_key_present() else 'missing (GEMINI_API_KEY)'}")
275
+
276
+
277
+ @app.command("prices")
278
+ def prices_cmd(
279
+ fleet: str = typer.Option(None, "--fleet", "-f", help="Fleet to price (default: your saved fleet)."),
280
+ find: str = typer.Option(None, "--find", help="List OpenRouter models whose id contains this text."),
281
+ md: Path = typer.Option(None, "--md", help="Also write the table, with the pricing links, to this .md file."),
282
+ refresh: bool = typer.Option(False, "--refresh", help="Re-download OpenRouter's price list."),
283
+ ) -> None:
284
+ """Per-token list prices used to settle runs (OpenRouter's public list, or your prices.toml)."""
285
+ s = load_settings()[0]
286
+ t = get_theme(s.theme)
287
+ console = Console()
288
+ table = load_openrouter(refresh=refresh)
289
+ if not table:
290
+ console.print(f"[{t.warn}]could not reach OpenRouter and nothing is cached; only prices.toml applies[/]")
291
+ if find:
292
+ ids = sorted({m["id"] for m in table.values() if find.lower() in m["id"].lower()})
293
+ rows = [(i, "openrouter", price_for("openrouter", i, table=table)) for i in ids]
294
+ else:
295
+ rows, seen = [], set()
296
+ for e in parse_fleet(fleet or s.fleet):
297
+ if e.label not in seen:
298
+ seen.add(e.label)
299
+ rows.append((e.label, e.backend, price_for(e.backend, e.model, table=table)))
300
+ if s.web:
301
+ rows.append((f"web search: {s.search_model}", "direct", price_for("direct", s.search_model, table=table)))
302
+ out = Table(box=None, title="list prices, USD per 1M tokens", title_justify="left")
303
+ for col in ("model", "backend", "input", "output", "source"):
304
+ out.add_column(col, style=t.accent if col == "model" else None,
305
+ justify="right" if col in ("input", "output") else "left")
306
+ for label, backend, p in rows:
307
+ if p is None:
308
+ out.add_row(escape(label), backend, "?", "?", f"[{t.warn}]not found; add it to prices.toml[/]")
309
+ else:
310
+ i, o = p.per_mtok()
311
+ out.add_row(escape(label), backend, f"{i:.3f}", f"{o:.3f}", escape(p.source))
312
+ console.print(out)
313
+ if md:
314
+ links = "\n".join(f"- {name}: {url}" for name, url in PRICE_LINKS.items())
315
+ md.write_text(f"# Model prices\n\n{price_table_md(rows)}\n\n## Where the prices come from\n\n{links}\n")
316
+ console.print(f"wrote {md}")
317
+
318
+
319
+ def run_cli() -> None:
320
+ load_env_files()
321
+ try:
322
+ app()
323
+ except BannahaError as exc:
324
+ Console(stderr=True).print(f"[bold red]error:[/] {exc}")
325
+ sys.exit(2)
326
+
327
+
328
+ __all__ = ["app", "config_path", "run_cli"]
bannaha/cli/config.py ADDED
@@ -0,0 +1,113 @@
1
+ """Saved defaults (~/.config/bannaha/config.toml) and .env loading."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import re
6
+ import tomllib
7
+ from dataclasses import asdict, dataclass, field, fields
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import tomli_w
12
+
13
+ from ..tools.web_search import DEFAULT_SEARCH_MODEL
14
+
15
+
16
+ def config_dir() -> Path:
17
+ base = os.environ.get("BANNAHA_CONFIG_DIR")
18
+ if base:
19
+ return Path(base).expanduser()
20
+ return Path(os.environ.get("XDG_CONFIG_HOME") or "~/.config").expanduser() / "bannaha"
21
+
22
+
23
+ def config_path() -> Path:
24
+ return config_dir() / "config.toml"
25
+
26
+
27
+ @dataclass
28
+ class Settings:
29
+ strategy: str = "blackboard"
30
+ fleet: str = "mock@local:42*3,mock@local:41*2"
31
+ web: bool = False
32
+ python: bool = True
33
+ sandbox: str = "process"
34
+ peer_updates: bool = True
35
+ search_model: str = DEFAULT_SEARCH_MODEL
36
+ theme: str = "ocean"
37
+ max_wall_s: float = 900.0
38
+ max_calls: int = 16
39
+ max_steps: int = 24
40
+ max_output_tokens: int = 16384
41
+ max_tokens: int = 0 # whole run; 0 = no limit
42
+ max_cost_usd: float = 0.0 # whole run, at list prices; 0 = no limit
43
+ max_agent_cost_usd: float = 0.0 # per agent; 0 = no limit
44
+ banner: bool = True
45
+ drop: float = 0.0
46
+ drop_after: int = 2
47
+ options: dict[str, dict[str, Any]] = field(default_factory=dict)
48
+
49
+
50
+ def load_settings() -> tuple[Settings, bool]:
51
+ path = config_path()
52
+ if not path.exists():
53
+ return Settings(), False
54
+ data = tomllib.loads(path.read_text())
55
+ known = {f.name for f in fields(Settings)}
56
+ return Settings(**{k: v for k, v in data.items() if k in known}), True
57
+
58
+
59
+ def save_settings(s: Settings) -> Path:
60
+ path = config_path()
61
+ path.parent.mkdir(parents=True, exist_ok=True)
62
+ path.write_text(tomli_w.dumps(asdict(s)))
63
+ return path
64
+
65
+
66
+ # Where each variable loaded by load_env_files came from (a file path); variables
67
+ # that were already in the environment are reported as "shell".
68
+ _ENV_SOURCES: dict[str, str] = {}
69
+
70
+
71
+ def env_files() -> list[Path]:
72
+ return [Path.cwd() / ".env", config_dir() / ".env"]
73
+
74
+
75
+ def load_env_files(reload: bool = False) -> list[Path]:
76
+ """Load KEY=VALUE pairs from ./.env and the config dir's .env without
77
+ overriding variables that are already set. With reload=True, values that
78
+ came from these files are re-read (so edits take effect); shell values stay."""
79
+ if reload:
80
+ for key, src in list(_ENV_SOURCES.items()):
81
+ if src != "shell":
82
+ os.environ.pop(key, None)
83
+ del _ENV_SOURCES[key]
84
+ loaded = []
85
+ for path in env_files():
86
+ if not path.is_file():
87
+ continue
88
+ for line in path.read_text().splitlines():
89
+ line = line.strip()
90
+ if not line or line.startswith("#") or "=" not in line:
91
+ continue
92
+ key, _, value = line.removeprefix("export ").partition("=")
93
+ key, value = key.strip(), value.strip()
94
+ if value[:1] in ("'", '"') and value[1:].find(value[0]) >= 0:
95
+ value = value[1:1 + value[1:].find(value[0])]
96
+ else:
97
+ value = re.split(r"\s+#", value, maxsplit=1)[0].strip()
98
+ if not key or not value:
99
+ continue
100
+ if os.environ.get(key):
101
+ _ENV_SOURCES.setdefault(key, "shell")
102
+ continue
103
+ os.environ[key] = value
104
+ _ENV_SOURCES[key] = str(path)
105
+ loaded.append(path)
106
+ return loaded
107
+
108
+
109
+ def env_source(key: str) -> str | None:
110
+ """'shell', the .env path it was loaded from, or None when not set."""
111
+ if not os.environ.get(key):
112
+ return None
113
+ return _ENV_SOURCES.get(key, "shell")