stackdoctor-cli 1.0.1__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 (40) hide show
  1. stackdoctor/__init__.py +15 -0
  2. stackdoctor/__main__.py +6 -0
  3. stackdoctor/agent/__init__.py +5 -0
  4. stackdoctor/agent/compaction.py +66 -0
  5. stackdoctor/agent/diagnosis.py +398 -0
  6. stackdoctor/agent/loop.py +801 -0
  7. stackdoctor/agent/prompts.py +85 -0
  8. stackdoctor/agent/providers/__init__.py +295 -0
  9. stackdoctor/agent/providers/base.py +210 -0
  10. stackdoctor/agent/providers/claude.py +285 -0
  11. stackdoctor/agent/providers/gemini.py +312 -0
  12. stackdoctor/agent/providers/openai_compat.py +537 -0
  13. stackdoctor/agent/providers/prices.py +90 -0
  14. stackdoctor/benchmark/__init__.py +11 -0
  15. stackdoctor/benchmark/__main__.py +198 -0
  16. stackdoctor/benchmark/holmes.py +386 -0
  17. stackdoctor/benchmark/report.py +362 -0
  18. stackdoctor/benchmark/runner.py +710 -0
  19. stackdoctor/benchmark/scenarios.py +153 -0
  20. stackdoctor/benchmark/scoring.py +184 -0
  21. stackdoctor/cli.py +882 -0
  22. stackdoctor/dependencies.py +221 -0
  23. stackdoctor/discovery.py +361 -0
  24. stackdoctor/evidence.py +134 -0
  25. stackdoctor/github.py +168 -0
  26. stackdoctor/live.py +808 -0
  27. stackdoctor/mcp_server.py +233 -0
  28. stackdoctor/models.py +275 -0
  29. stackdoctor/pglog.py +55 -0
  30. stackdoctor/postgres.py +294 -0
  31. stackdoctor/probes.py +172 -0
  32. stackdoctor/py.typed +0 -0
  33. stackdoctor/redaction.py +215 -0
  34. stackdoctor/rules.py +303 -0
  35. stackdoctor/validation.py +61 -0
  36. stackdoctor_cli-1.0.1.dist-info/METADATA +177 -0
  37. stackdoctor_cli-1.0.1.dist-info/RECORD +40 -0
  38. stackdoctor_cli-1.0.1.dist-info/WHEEL +4 -0
  39. stackdoctor_cli-1.0.1.dist-info/entry_points.txt +3 -0
  40. stackdoctor_cli-1.0.1.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,801 @@
1
+ """StackDoctor's own agent: a hand-written, bounded tool-calling loop.
2
+
3
+ The agent is an MCP client of StackDoctor's own MCP server, so it uses exactly
4
+ the tools external agents (HolmesGPT, Claude, ...) see. In normal use the
5
+ server runs as a subprocess (`stackdoctor mcp`) over stdio; tests connect to
6
+ an in-process server instead.
7
+
8
+ One run:
9
+
10
+ 1. List the server's tools and offer the model the read-only ones it may use
11
+ (`inspect_compose_runtime` only with ``live``), plus the local
12
+ `submit_diagnosis` tool, which is how the model gives its final answer.
13
+ 2. Loop: send the model the next message, run the tool calls it asks for,
14
+ and send back their results, until it submits a diagnosis or a limit stops
15
+ the run.
16
+ 3. Resolve every citation in the submission against the evidence the tools
17
+ returned (`stackdoctor.agent.diagnosis`), and build the `Diagnosis`.
18
+
19
+ Bounds, all in `Limits`: a tool-call limit (after which the model is asked,
20
+ once, to submit), a wall-clock timeout over the whole run, a token budget, a
21
+ cost cap, and a bounded number of retries with exponential backoff for rate
22
+ limits and server errors. One repair turn is allowed for a malformed or
23
+ badly cited submission, a malformed tool call, or model output the provider
24
+ itself rejected; every provider reports those the same way. A wait longer
25
+ than the backoff cap is not retried. Every path through the loop ends.
26
+
27
+ Data handling: tool results are redacted by the engine before they leave the
28
+ server. Before anything is sent to the provider it is redacted again, also
29
+ replacing the values of secret-looking variables in this process's
30
+ environment (such as the provider's own API key). Tool results are wrapped
31
+ as ``{"untrusted_tool_output": ...}`` and the system prompt says they are data,
32
+ never instructions. The model never sees host paths: it does not choose the
33
+ project, the loop does.
34
+ """
35
+
36
+ import asyncio
37
+ import inspect
38
+ import json
39
+ import os
40
+ import random
41
+ import sys
42
+ import time
43
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
44
+ from dataclasses import dataclass, field
45
+ from pathlib import Path
46
+ from typing import Any, cast
47
+
48
+ from mcp import Client, StdioServerParameters
49
+ from mcp.server.mcpserver import MCPServer
50
+ from mcp.types import CallToolResult, TextContent, Tool
51
+ from pydantic import JsonValue, ValidationError
52
+
53
+ from stackdoctor.agent import compaction, providers
54
+ from stackdoctor.agent.diagnosis import (
55
+ SUBMIT_DESCRIPTION,
56
+ SUBMIT_PARAMETERS,
57
+ SUBMIT_TOOL,
58
+ AIFinding,
59
+ Attempt,
60
+ Diagnosis,
61
+ RootCause,
62
+ RunStats,
63
+ Status,
64
+ StopReason,
65
+ Submission,
66
+ UnsupportedClaim,
67
+ check_diagnosis,
68
+ parse_submission,
69
+ resolve_citations,
70
+ )
71
+ from stackdoctor.agent.prompts import (
72
+ INITIAL_MESSAGE,
73
+ LIMIT_REACHED,
74
+ SYSTEM_PROMPT,
75
+ TEXT_ONLY,
76
+ handover_message,
77
+ rejected_message,
78
+ repair_message,
79
+ )
80
+ from stackdoctor.agent.providers.base import (
81
+ ErrorKind,
82
+ LLMProvider,
83
+ ProviderError,
84
+ Session,
85
+ ToolCall,
86
+ ToolResult,
87
+ ToolSpec,
88
+ Turn,
89
+ Usage,
90
+ )
91
+ from stackdoctor.evidence import config_item
92
+ from stackdoctor.models import ComposeProject, EvidenceItem, EvidenceRef, ValidationReport
93
+ from stackdoctor.redaction import redact_json, redact_text, sensitive_environment_values
94
+
95
+ DISCOVER_TOOL = "discover_compose_project"
96
+ VALIDATE_TOOL = "validate_compose_project"
97
+ RUNTIME_TOOL = "inspect_compose_runtime"
98
+ STATIC_TOOLS = (DISCOVER_TOOL, VALIDATE_TOOL)
99
+
100
+ # One repair turn for a malformed or badly cited submission, or a text answer.
101
+ MAX_REPAIRS = 1
102
+ # Turns beyond the tool-call limit: the first message, the forced submission
103
+ # after the limit, and a repair. A safety net; the other limits stop first.
104
+ EXTRA_TURNS = 4
105
+
106
+ # Provider failures after which the next model in the chain is tried: overload,
107
+ # server errors and rate limits that retries did not clear, quotas, and
108
+ # requests too large for the provider. Invalid output (malformed_output) and
109
+ # fatal errors (a bad key, an unknown model, a refusal) never move on.
110
+ FALLBACK_KINDS: frozenset[ErrorKind] = frozenset({"transient", "exhausted", "too_large"})
111
+
112
+ ServerTarget = MCPServer | StdioServerParameters
113
+ Sleep = Callable[[float], Awaitable[None]]
114
+
115
+
116
+ class AgentConfigError(ValueError):
117
+ """The run cannot start with these settings (for example, a cost cap without a price)."""
118
+
119
+
120
+ @dataclass(frozen=True)
121
+ class Limits:
122
+ """Bounds on one agent run. The defaults suit a free-tier Flash model."""
123
+
124
+ max_tool_calls: int = 10
125
+ timeout_seconds: float = 120.0
126
+ max_tokens: int = 150_000
127
+ max_retries: int = 3
128
+ # None disables the cost cap.
129
+ max_cost_usd: float | None = 0.10
130
+ backoff_seconds: float = 1.0
131
+ max_backoff_seconds: float = 20.0
132
+
133
+ def __post_init__(self) -> None:
134
+ if self.max_tool_calls < 1:
135
+ raise AgentConfigError("max_tool_calls must be at least 1")
136
+ if self.timeout_seconds <= 0 or self.max_tokens < 1 or self.max_retries < 0:
137
+ raise AgentConfigError("timeout, token budget and retries must be positive")
138
+ if self.max_cost_usd is not None and self.max_cost_usd <= 0:
139
+ raise AgentConfigError("max_cost_usd must be positive, or None to disable it")
140
+
141
+
142
+ def server_parameters(
143
+ project_dir: Path,
144
+ *,
145
+ live: bool,
146
+ probe: bool = False,
147
+ timeout: float | None = None,
148
+ key_variables: Sequence[str] = (),
149
+ ) -> StdioServerParameters:
150
+ """How to start StackDoctor's MCP server for one agent run.
151
+
152
+ The only allowed root is the project directory. Without ``live`` the
153
+ server does not register the live tool at all (``--no-live-tools``). The
154
+ server gets this process's environment, which Compose may need for
155
+ interpolation, minus every API key variable StackDoctor knows of and
156
+ the extra ``key_variables`` (such as one named by ``--api-key-env``).
157
+ """
158
+ if probe and not live:
159
+ raise AgentConfigError("probe requires live")
160
+ # WARNING: the server's routine INFO logs would clutter the user's terminal.
161
+ args = ["-m", "stackdoctor", "mcp", "--root", str(project_dir), "--log-level", "WARNING"]
162
+ if timeout is not None:
163
+ args += ["--timeout", str(timeout)]
164
+ if not live:
165
+ args.append("--no-live-tools")
166
+ if probe:
167
+ args.append("--allow-probes")
168
+ removed = {*providers.key_variables(), *key_variables}
169
+ env = {key: value for key, value in os.environ.items() if key not in removed}
170
+ return StdioServerParameters(command=sys.executable, args=args, env=env)
171
+
172
+
173
+ async def run_agent(
174
+ provider: LLMProvider,
175
+ server: ServerTarget,
176
+ *,
177
+ fallbacks: Sequence[LLMProvider] = (),
178
+ project_dir: str,
179
+ compose_files: Sequence[str] = (),
180
+ live: bool = False,
181
+ limits: Limits | None = None,
182
+ known_secrets: Sequence[str] | None = None,
183
+ secret_variables: Sequence[str] = (),
184
+ sleep: Sleep = asyncio.sleep,
185
+ clock: Callable[[], float] = time.monotonic,
186
+ ) -> Diagnosis:
187
+ """Investigate one Compose project and return a diagnosis.
188
+
189
+ Args:
190
+ provider: The model to use.
191
+ fallbacks: Models to try next, in order, if a model fails with a
192
+ provider error in `FALLBACK_KINDS`. Every limit applies to the
193
+ whole run, not to each model.
194
+ server: StackDoctor's MCP server: `server_parameters(...)` to run it as
195
+ a subprocess, or an `MCPServer` instance (tests).
196
+ project_dir: The project directory as the server should see it.
197
+ compose_files: Compose files to use instead of Compose's own lookup,
198
+ inside the project directory. Passed to every tool call; the
199
+ model chooses neither the project nor the files.
200
+ live: Whether the model may use `inspect_compose_runtime`.
201
+ limits: Bounds on the run.
202
+ known_secrets: Values to remove from everything sent to the provider.
203
+ Defaults to the values of secret-looking variables in this
204
+ process's environment. The values of every known API key
205
+ variable, and of ``secret_variables``, are always added.
206
+ secret_variables: More environment variables whose values are
207
+ secret, whatever their names (such as one named by
208
+ ``--api-key-env``).
209
+ sleep, clock: Replaceable in tests.
210
+
211
+ Raises:
212
+ AgentConfigError: if a cost cap is set but the price of a model in
213
+ the chain is unknown.
214
+ """
215
+ limits = limits or Limits()
216
+ chain = (provider, *fallbacks)
217
+ for model in chain:
218
+ if limits.max_cost_usd is not None and model.price() is None:
219
+ raise AgentConfigError(
220
+ f"The price of model {model.model!r} is not known, so the cost cap cannot be "
221
+ "enforced. Give its price or disable the cost cap."
222
+ )
223
+ secrets = sensitive_environment_values() if known_secrets is None else list(known_secrets)
224
+ for variable in (*providers.key_variables(), *secret_variables):
225
+ if value := os.environ.get(variable):
226
+ secrets.append(value)
227
+ run = _Run(
228
+ chain=chain,
229
+ server=server,
230
+ project_dir=project_dir,
231
+ compose_files=tuple(compose_files),
232
+ live=live,
233
+ limits=limits,
234
+ secrets=secrets,
235
+ sleep=sleep,
236
+ )
237
+ started = clock()
238
+ outcome: _Answer | _Stopped
239
+ try:
240
+ async with asyncio.timeout(limits.timeout_seconds):
241
+ outcome = await run.investigate()
242
+ except TimeoutError:
243
+ outcome = _Stopped("timeout", f"stopped after {limits.timeout_seconds:g} seconds")
244
+ except OSError as error:
245
+ outcome = _server_error(error)
246
+ except ExceptionGroup as group:
247
+ # The MCP client runs in a task group, which wraps start-up failures.
248
+ failures, _ = group.split(OSError)
249
+ if failures is None:
250
+ raise
251
+ outcome = _server_error(_first_leaf(failures))
252
+ return run.finish(outcome, duration=clock() - started)
253
+
254
+
255
+ def _server_error(error: BaseException) -> "_Stopped":
256
+ return _Stopped("server_error", f"the MCP server could not be used: {error}")
257
+
258
+
259
+ def _first_leaf(group: BaseExceptionGroup[BaseException]) -> BaseException:
260
+ first = group.exceptions[0]
261
+ return _first_leaf(first) if isinstance(first, BaseExceptionGroup) else first
262
+
263
+
264
+ @dataclass
265
+ class _Answer:
266
+ """A submission the loop accepted, with its citations resolved."""
267
+
268
+ status: Status
269
+ root_cause: RootCause | None = None
270
+ findings: list[AIFinding] = field(default_factory=list)
271
+ unsupported: list[UnsupportedClaim] = field(default_factory=list)
272
+ suggested_fix: str | None = None
273
+
274
+ @property
275
+ def problems(self) -> list[str]:
276
+ return [problem for claim in self.unsupported for problem in claim.problems]
277
+
278
+
279
+ class _OutputRejected(Exception):
280
+ """The provider rejected the model's output again after the repair turn (redacted)."""
281
+
282
+
283
+ @dataclass
284
+ class _Stopped:
285
+ reason: StopReason
286
+ detail: str
287
+
288
+
289
+ @dataclass
290
+ class _Attempt:
291
+ """One model's share of the run."""
292
+
293
+ provider: LLMProvider
294
+ model_calls: int = 0
295
+ retries: int = 0
296
+ usage: Usage = field(default_factory=Usage)
297
+ stopped: "_Stopped | None" = None
298
+
299
+ def cost(self) -> float | None:
300
+ price = self.provider.price()
301
+ return price.cost(self.usage) if price is not None else None
302
+
303
+
304
+ @dataclass
305
+ class _Run:
306
+ chain: tuple[LLMProvider, ...]
307
+ server: ServerTarget
308
+ project_dir: str
309
+ compose_files: tuple[str, ...]
310
+ live: bool
311
+ limits: Limits
312
+ secrets: list[str]
313
+ sleep: Sleep
314
+ tool_calls: int = 0
315
+ repairs: int = 0
316
+ project: str | None = None
317
+ evidence: dict[str, EvidenceItem] = field(default_factory=dict)
318
+ attempts: list[_Attempt] = field(default_factory=list)
319
+ # Every tool result so far, as (tool name, wrapped output): handed to a
320
+ # fallback model so it does not start from nothing.
321
+ collected: list[tuple[str, dict[str, JsonValue]]] = field(default_factory=list)
322
+ # Estimated tokens in the current conversation, for providers with a
323
+ # request-size limit.
324
+ context_tokens: int = 0
325
+ # The tools offered to the model, named in the repair turn.
326
+ tool_names: tuple[str, ...] = ()
327
+
328
+ @property
329
+ def attempt(self) -> _Attempt:
330
+ return self.attempts[-1]
331
+
332
+ @property
333
+ def usage(self) -> Usage:
334
+ return Usage(
335
+ input_tokens=sum(a.usage.input_tokens for a in self.attempts),
336
+ output_tokens=sum(a.usage.output_tokens for a in self.attempts),
337
+ thinking_tokens=sum(a.usage.thinking_tokens for a in self.attempts),
338
+ )
339
+
340
+ # --- The loop ---------------------------------------------------------------
341
+
342
+ async def investigate(self) -> "_Answer | _Stopped":
343
+ async with Client(self.server) as client:
344
+ # Handled inside the client's context, which would otherwise wrap
345
+ # it in an exception group.
346
+ try:
347
+ return await self._converse(client)
348
+ except ProviderError as error:
349
+ return _Stopped("provider_error", str(error))
350
+ except _OutputRejected as error:
351
+ detail = f"the provider rejected the model's output: {error}"
352
+ return _Stopped("invalid_output", detail)
353
+
354
+ async def _converse(self, client: Client) -> "_Answer | _Stopped":
355
+ listed = await client.list_tools()
356
+ offered = self._offered(listed.tools)
357
+ specs = [
358
+ *(ToolSpec(tool.name, _summary(tool.description)) for tool in offered.values()),
359
+ ToolSpec(SUBMIT_TOOL, SUBMIT_DESCRIPTION, SUBMIT_PARAMETERS),
360
+ ]
361
+ self.tool_names = tuple(spec.name for spec in specs)
362
+ for index, provider in enumerate(self.chain):
363
+ self.attempts.append(_Attempt(provider))
364
+ try:
365
+ return await self._converse_with(client, provider, offered, specs)
366
+ except ProviderError as error:
367
+ if error.kind not in FALLBACK_KINDS or index + 1 == len(self.chain):
368
+ raise
369
+ # The message is already redacted (see _send).
370
+ self.attempt.stopped = _Stopped("provider_error", str(error))
371
+ raise AssertionError("unreachable") # pragma: no cover
372
+
373
+ async def _converse_with(
374
+ self,
375
+ client: Client,
376
+ provider: LLMProvider,
377
+ offered: Mapping[str, Tool],
378
+ specs: Sequence[ToolSpec],
379
+ ) -> "_Answer | _Stopped":
380
+ """One model's conversation; a fallback model starts with what was collected."""
381
+ session = provider.start(SYSTEM_PROMPT, specs)
382
+ self.context_tokens = compaction.estimate_tokens(
383
+ [SYSTEM_PROMPT, *(vars(spec) for spec in specs)]
384
+ )
385
+ message: str | list[ToolResult] = (
386
+ self._handover(provider) if self.collected else INITIAL_MESSAGE
387
+ )
388
+ force: str | None = None
389
+
390
+ for _ in range(self.limits.max_tool_calls + EXTRA_TURNS):
391
+ turn = await self._send(session, message, force)
392
+ submit = next((c for c in turn.tool_calls if c.name == SUBMIT_TOOL), None)
393
+
394
+ if submit is not None:
395
+ answer, problems = self._judge(submit)
396
+ out_of_repairs = self.repairs >= MAX_REPAIRS
397
+ stopped = self._over_budget()
398
+ if answer is not None and (not problems or out_of_repairs or stopped):
399
+ # Claims whose citations still do not all resolve stay
400
+ # in the answer, flagged as unsupported.
401
+ return answer
402
+ if out_of_repairs:
403
+ return _Stopped("invalid_output", "; ".join(problems[:3]))
404
+ if stopped:
405
+ return stopped
406
+ self.repairs += 1
407
+ message = [
408
+ ToolResult(call, self._note(repair_message(problems)))
409
+ if call is submit
410
+ else ToolResult(call, self._note("Not run: submit_diagnosis again."))
411
+ for call in turn.tool_calls
412
+ ]
413
+ force = SUBMIT_TOOL
414
+ continue
415
+
416
+ if stopped := self._over_budget():
417
+ return stopped
418
+
419
+ if not turn.tool_calls:
420
+ if self.repairs >= MAX_REPAIRS:
421
+ return _Stopped(
422
+ "invalid_output", "the model answered in text instead of submitting"
423
+ )
424
+ self.repairs += 1
425
+ message, force = TEXT_ONLY, SUBMIT_TOOL
426
+ continue
427
+
428
+ if force == SUBMIT_TOOL:
429
+ # The model was required to submit and called other tools.
430
+ if self.tool_calls >= self.limits.max_tool_calls:
431
+ return _Stopped(
432
+ "tool_call_limit",
433
+ f"no diagnosis after {self.tool_calls} tool calls",
434
+ )
435
+ return _Stopped("invalid_output", "the model did not submit when asked")
436
+
437
+ executed = [await self._execute(client, call, offered) for call in turn.tool_calls]
438
+ message = self._fit(provider, executed)
439
+ if self.tool_calls >= self.limits.max_tool_calls:
440
+ force = SUBMIT_TOOL
441
+
442
+ # Reached only by a model that keeps making calls that do not run
443
+ # (unknown tools, malformed arguments): those do not count as tool calls.
444
+ return _Stopped("turn_limit", "the model did not finish within the turn limit")
445
+
446
+ async def _send(
447
+ self, session: Session, message: str | list[ToolResult], force: str | None
448
+ ) -> Turn:
449
+ attempt = 0
450
+ while True:
451
+ try:
452
+ turn = await session.send(message, force_tool=force)
453
+ except ProviderError as error:
454
+ detail = self._redact(str(error))
455
+ if error.kind == "malformed_output":
456
+ # The provider rejected the model's own output, such as a
457
+ # call to a tool that does not exist. Nothing was run, and
458
+ # the session's history is unchanged, so the repair turn
459
+ # sends the same message again with what went wrong and
460
+ # the tool names. It is never retried with backoff.
461
+ if self.repairs >= MAX_REPAIRS:
462
+ raise _OutputRejected(detail) from None
463
+ self.repairs += 1
464
+ note = self._redact(rejected_message(detail, self.tool_names))
465
+ message = _with_note(message, note)
466
+ continue
467
+ kind = error.kind
468
+ too_long = (
469
+ error.retry_after is not None
470
+ and error.retry_after > self.limits.max_backoff_seconds
471
+ )
472
+ if kind == "transient" and too_long:
473
+ # Waiting longer than the backoff cap would not fit the
474
+ # run: treat it as a quota that will not recover.
475
+ kind = "exhausted"
476
+ if kind != "transient" or attempt >= self.limits.max_retries:
477
+ raise ProviderError(detail, kind=kind, status=error.status) from None
478
+ self.attempt.retries += 1
479
+ await self.sleep(self._backoff(attempt, error.retry_after))
480
+ attempt += 1
481
+ continue
482
+ used = self.attempt.usage
483
+ self.attempt.model_calls += 1
484
+ self.attempt.usage = Usage(
485
+ input_tokens=used.input_tokens + turn.usage.input_tokens,
486
+ output_tokens=used.output_tokens + turn.usage.output_tokens,
487
+ thinking_tokens=used.thinking_tokens + turn.usage.thinking_tokens,
488
+ )
489
+ self._track_context(message, turn)
490
+ return turn
491
+
492
+ def _track_context(self, message: str | list[ToolResult], turn: Turn) -> None:
493
+ """Update the conversation's size: the provider's count when it reports one."""
494
+ if turn.usage.input_tokens:
495
+ # The reply's text and calls are sent back, and on some providers
496
+ # its reasoning too (Groq, after a tool call): counted, to be safe.
497
+ usage = turn.usage
498
+ self.context_tokens = usage.input_tokens + usage.output_tokens + usage.thinking_tokens
499
+ return
500
+ sent = message if isinstance(message, str) else [dict(r.content) for r in message]
501
+ reply = [turn.text, *(dict(call.arguments) for call in turn.tool_calls)]
502
+ self.context_tokens += compaction.estimate_tokens(sent) + compaction.estimate_tokens(reply)
503
+
504
+ def _backoff(self, attempt: int, retry_after: float | None) -> float:
505
+ cap = self.limits.max_backoff_seconds
506
+ delay = min(cap, self.limits.backoff_seconds * 2.0**attempt) * random.uniform(0.5, 1.0)
507
+ if retry_after is not None:
508
+ delay = max(delay, min(retry_after, cap))
509
+ return delay
510
+
511
+ def _over_budget(self) -> _Stopped | None:
512
+ if self.usage.total > self.limits.max_tokens:
513
+ return _Stopped(
514
+ "token_budget",
515
+ f"{self.usage.total} tokens used, budget {self.limits.max_tokens}",
516
+ )
517
+ cost = self._cost()
518
+ cap = self.limits.max_cost_usd
519
+ if cap is not None and cost is not None and cost >= cap:
520
+ return _Stopped("cost_cap", f"estimated ${cost:.4f}, cap ${cap:g}")
521
+ return None
522
+
523
+ def _cost(self) -> float | None:
524
+ """The run's estimated cost, each model at its own price; None if any is unknown."""
525
+ costs = [attempt.cost() for attempt in self.attempts]
526
+ if any(cost is None for cost in costs):
527
+ return None
528
+ return sum(cost for cost in costs if cost is not None)
529
+
530
+ # --- Request size ---------------------------------------------------------------
531
+
532
+ def _budget(self, provider: LLMProvider) -> int | None:
533
+ limit = provider.max_request_tokens
534
+ return None if limit is None else limit - self.context_tokens
535
+
536
+ def _fit(self, provider: LLMProvider, results: list[ToolResult]) -> list[ToolResult]:
537
+ """Tool results, compacted if needed to fit the provider's request limit.
538
+
539
+ Raises:
540
+ ProviderError: ``too_large``, if they do not fit even compacted.
541
+ """
542
+ budget = self._budget(provider)
543
+ if budget is None:
544
+ return results
545
+ contents: list[JsonValue] = [dict(result.content) for result in results]
546
+ fitted = compaction.fit(contents, budget)
547
+ if fitted is None:
548
+ raise ProviderError(
549
+ f"the tool results do not fit the {provider.name} request limit of "
550
+ f"{provider.max_request_tokens} tokens, even shortened",
551
+ kind="too_large",
552
+ )
553
+ if fitted == contents:
554
+ return results
555
+ return [
556
+ ToolResult(
557
+ result.call, {**cast(dict[str, JsonValue], content), "note": compaction.NOTE}
558
+ )
559
+ for result, content in zip(results, fitted, strict=True)
560
+ ]
561
+
562
+ def _handover(self, provider: LLMProvider) -> str:
563
+ """The first message for a fallback model: the task and the results so far.
564
+
565
+ Each result keeps its ``untrusted_tool_output`` wrapper and is
566
+ redacted again. It is compacted, as tool results are, if the
567
+ provider has a request limit.
568
+
569
+ Raises:
570
+ ProviderError: ``too_large``, if the results do not fit even
571
+ compacted.
572
+ """
573
+ collected: list[JsonValue] = [
574
+ {"tool": name, **cast(dict[str, JsonValue], self._redact_json(content))}
575
+ for name, content in self.collected
576
+ ]
577
+ budget = self._budget(provider)
578
+ if budget is not None:
579
+ budget -= compaction.estimate_tokens(handover_message(""))
580
+ fitted = compaction.fit(collected, budget)
581
+ if fitted is None:
582
+ raise ProviderError(
583
+ f"the collected tool results do not fit the {provider.name} request "
584
+ f"limit of {provider.max_request_tokens} tokens, even shortened",
585
+ kind="too_large",
586
+ )
587
+ if fitted != collected:
588
+ collected = [*fitted, {"note": compaction.NOTE}]
589
+ return handover_message(json.dumps(collected, ensure_ascii=False))
590
+
591
+ # --- Tools --------------------------------------------------------------------
592
+
593
+ def _offered(self, tools: Sequence[Tool]) -> dict[str, Tool]:
594
+ # Defense in depth: even if the server listed the live tool, it is
595
+ # only offered with `live`.
596
+ allowed = (*STATIC_TOOLS, RUNTIME_TOOL) if self.live else STATIC_TOOLS
597
+ return {tool.name: tool for tool in tools if tool.name in allowed}
598
+
599
+ async def _execute(
600
+ self, client: Client, call: ToolCall, offered: Mapping[str, Tool]
601
+ ) -> ToolResult:
602
+ if self.tool_calls >= self.limits.max_tool_calls:
603
+ return ToolResult(call, self._note(LIMIT_REACHED))
604
+ # Only a call that runs counts as a tool call. One the model got wrong
605
+ # gets an error result; the turn limit still bounds the run.
606
+ if call.name not in offered:
607
+ name = _printable(call.name)[:100]
608
+ available = ", ".join([*offered, SUBMIT_TOOL])
609
+ return ToolResult(call, self._note(f"Unknown tool {name!r}. Available: {available}."))
610
+ if call.error is not None:
611
+ # The tools take no arguments from the model, but a call the
612
+ # provider could not decode is reported, not run: the model
613
+ # should learn that its output was malformed.
614
+ return ToolResult(call, self._note(f"Not run: {call.error}"))
615
+ # The model does not choose the project or the Compose files.
616
+ arguments: dict[str, Any] = {"project_dir": self.project_dir}
617
+ if self.compose_files:
618
+ arguments["compose_files"] = list(self.compose_files)
619
+ self.tool_calls += 1
620
+ result = await client.call_tool(call.name, arguments)
621
+ wrapped = self._wrap(result)
622
+ self.collected.append((call.name, wrapped))
623
+ return ToolResult(call, wrapped)
624
+
625
+ def _wrap(self, result: CallToolResult) -> dict[str, JsonValue]:
626
+ if result.is_error or result.structured_content is None:
627
+ text = "\n".join(c.text for c in result.content if isinstance(c, TextContent))
628
+ payload: JsonValue = {"error": text or "the tool failed"}
629
+ else:
630
+ payload = cast(JsonValue, result.structured_content)
631
+ self._collect(result.structured_content)
632
+ return {"untrusted_tool_output": self._redact_json(payload)}
633
+
634
+ def _collect(self, data: dict[str, Any]) -> None:
635
+ """Keep the evidence a tool returned, re-validated (and so re-redacted)."""
636
+ items: Sequence[EvidenceItem]
637
+ try:
638
+ if "evidence" in data:
639
+ report = ValidationReport.model_validate(data)
640
+ self.project, items = report.project, report.evidence
641
+ else:
642
+ project = ComposeProject.model_validate(data)
643
+ self.project, items = project.name, (config_item(project),)
644
+ except ValidationError:
645
+ return
646
+ for item in items:
647
+ self.evidence[item.id] = item
648
+
649
+ def _note(self, text: str) -> dict[str, JsonValue]:
650
+ # A message from the loop itself, not tool output.
651
+ return {"error": self._redact(text)}
652
+
653
+ # --- The answer ---------------------------------------------------------------
654
+
655
+ def _judge(self, submit: ToolCall) -> tuple[_Answer | None, list[str]]:
656
+ if submit.error is not None:
657
+ return None, [self._redact(submit.error)]
658
+ parsed = parse_submission(submit.arguments)
659
+ if isinstance(parsed, list):
660
+ return None, parsed
661
+ answer = self._resolve(parsed)
662
+ return answer, answer.problems
663
+
664
+ def _resolve(self, submission: Submission) -> _Answer:
665
+ fix = self._redact(submission.suggested_fix) if submission.suggested_fix else None
666
+ if submission.status == "no_problem_found":
667
+ return _Answer("no_problem_found", suggested_fix=fix)
668
+ answer = _Answer("unsupported", suggested_fix=fix)
669
+ cause = submission.root_cause
670
+ assert cause is not None # Submission requires it for problem_found
671
+ refs, problems = resolve_citations(cause.evidence, self.evidence)
672
+ summary = self._redact(cause.summary)
673
+ if problems:
674
+ answer.unsupported.append(
675
+ UnsupportedClaim(
676
+ kind="root_cause",
677
+ title="Root cause",
678
+ explanation=summary,
679
+ problems=tuple(problems),
680
+ )
681
+ )
682
+ else:
683
+ answer.root_cause = RootCause(summary=summary, evidence=tuple(refs))
684
+ answer.status = "diagnosed"
685
+ for finding in submission.findings:
686
+ refs, problems = resolve_citations(finding.evidence, self.evidence)
687
+ title, explanation = self._redact(finding.title), self._redact(finding.explanation)
688
+ if problems:
689
+ answer.unsupported.append(
690
+ UnsupportedClaim(
691
+ kind="finding",
692
+ title=title,
693
+ explanation=explanation,
694
+ problems=tuple(problems),
695
+ )
696
+ )
697
+ else:
698
+ answer.findings.append(
699
+ AIFinding(
700
+ title=title,
701
+ explanation=explanation,
702
+ service=self._redact(finding.service) if finding.service else None,
703
+ evidence=tuple(refs),
704
+ )
705
+ )
706
+ return answer
707
+
708
+ def finish(self, outcome: "_Answer | _Stopped", *, duration: float) -> Diagnosis:
709
+ if isinstance(outcome, _Stopped):
710
+ diagnosis = Diagnosis(
711
+ project=self.project,
712
+ status="incomplete",
713
+ run=self._stats(duration, outcome.reason, self._redact(outcome.detail)),
714
+ )
715
+ else:
716
+ refs: list[EvidenceRef] = [
717
+ *(outcome.root_cause.evidence if outcome.root_cause else ()),
718
+ *(ref for finding in outcome.findings for ref in finding.evidence),
719
+ ]
720
+ cited = list(dict.fromkeys(ref.item for ref in refs))
721
+ diagnosis = Diagnosis(
722
+ project=self.project,
723
+ status=outcome.status,
724
+ root_cause=outcome.root_cause,
725
+ findings=tuple(outcome.findings),
726
+ unsupported=tuple(outcome.unsupported),
727
+ suggested_fix=outcome.suggested_fix,
728
+ evidence=tuple(self.evidence[item] for item in cited),
729
+ run=self._stats(duration, "submitted", None),
730
+ )
731
+ check_diagnosis(diagnosis)
732
+ return diagnosis
733
+
734
+ def _stats(self, duration: float, reason: StopReason, detail: str | None) -> RunStats:
735
+ if self.attempts and self.attempt.stopped is None:
736
+ self.attempt.stopped = _Stopped(reason, detail or "")
737
+ # The model that answered, or the last one tried.
738
+ last = self.attempt.provider if self.attempts else self.chain[0]
739
+ return RunStats(
740
+ provider=last.name,
741
+ model=last.model,
742
+ settings=dict(last.settings),
743
+ live=self.live,
744
+ tool_calls=self.tool_calls,
745
+ model_calls=sum(attempt.model_calls for attempt in self.attempts),
746
+ retries=sum(attempt.retries for attempt in self.attempts),
747
+ repairs=self.repairs,
748
+ duration_seconds=round(duration, 3),
749
+ input_tokens=self.usage.input_tokens,
750
+ output_tokens=self.usage.output_tokens,
751
+ thinking_tokens=self.usage.thinking_tokens,
752
+ estimated_cost_usd=self._cost(),
753
+ stop_reason=reason,
754
+ stop_detail=detail,
755
+ attempts=tuple(_report(attempt) for attempt in self.attempts),
756
+ )
757
+
758
+ # --- Redaction ----------------------------------------------------------------
759
+
760
+ def _redact(self, text: str) -> str:
761
+ return redact_text(text, self.secrets)
762
+
763
+ def _redact_json(self, value: JsonValue) -> JsonValue:
764
+ redacted: JsonValue = redact_json(value, self.secrets)
765
+ return redacted
766
+
767
+
768
+ def _with_note(message: str | list[ToolResult], note: str) -> str | list[ToolResult]:
769
+ """The message with a note from StackDoctor added (outside any tool output)."""
770
+ if isinstance(message, str):
771
+ return f"{message}\n\n{note}"
772
+ *earlier, last = message
773
+ return [*earlier, ToolResult(last.call, {**last.content, "note": note})]
774
+
775
+
776
+ def _report(attempt: _Attempt) -> Attempt:
777
+ stopped = attempt.stopped
778
+ assert stopped is not None # set when the attempt ended
779
+ return Attempt(
780
+ provider=attempt.provider.name,
781
+ model=attempt.provider.model,
782
+ settings=dict(attempt.provider.settings),
783
+ model_calls=attempt.model_calls,
784
+ retries=attempt.retries,
785
+ input_tokens=attempt.usage.input_tokens,
786
+ output_tokens=attempt.usage.output_tokens,
787
+ thinking_tokens=attempt.usage.thinking_tokens,
788
+ estimated_cost_usd=attempt.cost(),
789
+ stop_reason=stopped.reason,
790
+ stop_detail=stopped.detail or None,
791
+ )
792
+
793
+
794
+ def _summary(description: str | None) -> str:
795
+ """A tool's description without its argument list: the model passes no arguments."""
796
+ text = inspect.cleandoc(description or "")
797
+ return text.split("\nArgs:")[0].strip()
798
+
799
+
800
+ def _printable(text: str) -> str:
801
+ return "".join(char if char.isprintable() else "?" for char in text)