k0ntrol-cli 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 (80) hide show
  1. k0ntrol/__init__.py +1 -0
  2. k0ntrol/agents.py +998 -0
  3. k0ntrol/cli.py +190 -0
  4. k0ntrol/config.py +330 -0
  5. k0ntrol/credentials.py +78 -0
  6. k0ntrol/defaults/config.yaml +23 -0
  7. k0ntrol/events.py +838 -0
  8. k0ntrol/frontends/__init__.py +1 -0
  9. k0ntrol/frontends/ask.py +218 -0
  10. k0ntrol/frontends/badges.py +228 -0
  11. k0ntrol/frontends/banner.py +128 -0
  12. k0ntrol/frontends/diffview.py +174 -0
  13. k0ntrol/frontends/editor.py +701 -0
  14. k0ntrol/frontends/klog.html +740 -0
  15. k0ntrol/frontends/klog.py +403 -0
  16. k0ntrol/frontends/logo.py +12 -0
  17. k0ntrol/frontends/mentions.py +29 -0
  18. k0ntrol/frontends/prompt.py +340 -0
  19. k0ntrol/frontends/render.py +485 -0
  20. k0ntrol/frontends/session.py +717 -0
  21. k0ntrol/frontends/setup.py +442 -0
  22. k0ntrol/frontends/terminal.py +396 -0
  23. k0ntrol/frontends/theme.py +24 -0
  24. k0ntrol/helpers.py +108 -0
  25. k0ntrol/init_flow.py +362 -0
  26. k0ntrol/langfuse.py +173 -0
  27. k0ntrol/memory/__init__.py +0 -0
  28. k0ntrol/memory/index.py +235 -0
  29. k0ntrol/memory/layout.py +66 -0
  30. k0ntrol/memory/python_extract.py +189 -0
  31. k0ntrol/memory/reflect.py +366 -0
  32. k0ntrol/memory/refresh.py +21 -0
  33. k0ntrol/memory/scan.py +538 -0
  34. k0ntrol/memory/session.py +145 -0
  35. k0ntrol/otel.py +429 -0
  36. k0ntrol/pricing.py +29 -0
  37. k0ntrol/prompts/chatty.md +17 -0
  38. k0ntrol/prompts/implementer.md +14 -0
  39. k0ntrol/prompts/planner.md +42 -0
  40. k0ntrol/prompts/researcher.md +20 -0
  41. k0ntrol/prompts/reviewer.md +34 -0
  42. k0ntrol/providers.py +718 -0
  43. k0ntrol/search.py +133 -0
  44. k0ntrol/tools/__init__.py +0 -0
  45. k0ntrol/tools/bulk_read.py +93 -0
  46. k0ntrol/tools/errors.py +50 -0
  47. k0ntrol/tools/fetch_url.py +212 -0
  48. k0ntrol/tools/net.py +317 -0
  49. k0ntrol/tools/path_guard.py +45 -0
  50. k0ntrol/tools/read.py +174 -0
  51. k0ntrol/tools/run_tests.py +66 -0
  52. k0ntrol/tools/runner.py +177 -0
  53. k0ntrol/tools/search_memory.py +32 -0
  54. k0ntrol/tools/slice_guard.py +166 -0
  55. k0ntrol/tools/slice_journal.py +481 -0
  56. k0ntrol/tools/tracker.py +115 -0
  57. k0ntrol/tools/web_search.py +199 -0
  58. k0ntrol/tools/write.py +123 -0
  59. k0ntrol/tracker/__init__.py +31 -0
  60. k0ntrol/tracker/github.py +371 -0
  61. k0ntrol/tracker/local_files.py +241 -0
  62. k0ntrol/tracker/protocol.py +210 -0
  63. k0ntrol/workflow/__init__.py +29 -0
  64. k0ntrol/workflow/change.py +605 -0
  65. k0ntrol/workflow/ci_gate.py +96 -0
  66. k0ntrol/workflow/context.py +137 -0
  67. k0ntrol/workflow/implement.py +1150 -0
  68. k0ntrol/workflow/nodes.py +331 -0
  69. k0ntrol/workflow/plan.py +675 -0
  70. k0ntrol/workflow/qa.py +98 -0
  71. k0ntrol/workflow/research.py +533 -0
  72. k0ntrol/workflow/routers.py +273 -0
  73. k0ntrol/workflow/run.py +1165 -0
  74. k0ntrol/workflow/state.py +146 -0
  75. k0ntrol/workflow/triage.py +269 -0
  76. k0ntrol_cli-0.1.0.dist-info/METADATA +154 -0
  77. k0ntrol_cli-0.1.0.dist-info/RECORD +80 -0
  78. k0ntrol_cli-0.1.0.dist-info/WHEEL +4 -0
  79. k0ntrol_cli-0.1.0.dist-info/entry_points.txt +2 -0
  80. k0ntrol_cli-0.1.0.dist-info/licenses/LICENSE +201 -0
k0ntrol/agents.py ADDED
@@ -0,0 +1,998 @@
1
+ """The one agent builder.
2
+
3
+ Every agent — CHATTY for ``/ask`` today, the workflow agents as their nodes
4
+ land — is built here from ``create_agent``: the agent's allowlist, k0's
5
+ closed middleware set (a run-scoped model-call limit with
6
+ ``exit_behavior="end"``, a retry of transient model errors, old tool
7
+ results cleared once the run's context grows, invalid tool names cleaned
8
+ from what the provider receives, and tool errors surfaced to the model), an
9
+ explicit recursion limit derived from the model-call limit, and a
10
+ fresh-context wrapper (``K0Agent``).
11
+
12
+ The allowlist is enforced in code, twice: ``agent_tools`` builds exactly
13
+ the tools on ``ALLOWLISTS[name]``, and ``build_agent`` refuses any tool set
14
+ that is not that allowlist — off-allowlist tools get
15
+ ``ToolError(denied="allowlist")``, the canonical refusal. Only ``BaseTool``
16
+ instances are accepted: dict tools (provider built-ins) would bypass the
17
+ allowlist check in the tool node — but for the one exception ADR 0017
18
+ carves out: a provider's own web search (``NATIVE_SEARCH_TOOLS``) may fill the ``web_search`` slot for
19
+ PLANNER and RESEARCHER.
20
+ """
21
+
22
+ import re
23
+ from collections.abc import Callable, Mapping, Sequence
24
+ from dataclasses import dataclass
25
+ from importlib.resources import files
26
+ from pathlib import Path
27
+ from typing import Any, Literal
28
+ from uuid import uuid4
29
+
30
+ from langchain.agents import create_agent
31
+ from langchain.agents.middleware import (
32
+ AgentMiddleware,
33
+ ContextEditingMiddleware,
34
+ ModelCallLimitMiddleware,
35
+ ModelRequest,
36
+ ModelResponse,
37
+ ModelRetryMiddleware,
38
+ ToolCallRequest,
39
+ )
40
+ from langchain.agents.structured_output import ToolStrategy
41
+ from langchain.chat_models import init_chat_model
42
+ from langchain_core.callbacks import dispatch_custom_event
43
+ from langchain_core.messages import (
44
+ AIMessage,
45
+ AIMessageChunk,
46
+ BaseMessage,
47
+ ToolMessage,
48
+ )
49
+ from langchain_core.tools import BaseTool
50
+ from langgraph.types import Command
51
+ from pydantic import BaseModel, Field, model_validator
52
+
53
+ from k0ntrol.events import META_AGENT, META_EFFORT, META_HELPER, WARNING_EVENT
54
+ from k0ntrol.memory.index import custom_rules_text, custom_topology_text
55
+ from k0ntrol.providers import build_chat_model
56
+ from k0ntrol.search import NATIVE_SEARCH_AGENTS, native_search_provider, uses_native_search
57
+ from k0ntrol.tools.bulk_read import make_bulk_read
58
+ from k0ntrol.tools.errors import ToolError
59
+ from k0ntrol.tools.fetch_url import make_fetch_url
60
+ from k0ntrol.tools.net import Resolver, Transport
61
+ from k0ntrol.tools.read import make_grep, make_list_files, make_read_file
62
+ from k0ntrol.tools.run_tests import make_run_tests
63
+ from k0ntrol.tools.search_memory import make_search_memory
64
+ from k0ntrol.tools.slice_guard import SliceGuard, SliceStart
65
+ from k0ntrol.tools.slice_journal import SliceJournal
66
+ from k0ntrol.tools.tracker import tracker_read_tools
67
+ from k0ntrol.tools.web_search import Fetch, make_web_search
68
+ from k0ntrol.tools.write import WritePolicy, make_edit_file, make_write_file
69
+
70
+ _PRIMARY_READ_TOOLS = ("read_file", "list_files", "grep")
71
+ _HELPER_READ_TOOLS = ("bulk_read", "search_memory")
72
+ _BASE_READ_TOOLS = _PRIMARY_READ_TOOLS + _HELPER_READ_TOOLS
73
+
74
+ # Reads that need a tracker; a run without a work item drops them.
75
+ _TRACKER_TOOLS = ("read_work_item", "read_change_diff")
76
+
77
+ _NETWORK_TOOLS = ("fetch_url", "web_search")
78
+
79
+ # The cap on provider searches per model call — a fixed k0 constant, not
80
+ # configurable (ADR 0017): OpenAI's ``max_tool_calls``, Anthropic's
81
+ # ``max_uses``.
82
+ NATIVE_SEARCH_MAX_CALLS = 5
83
+
84
+ # The provider built-ins PLANNER and RESEARCHER get instead of k0's
85
+ # ``web_search`` when ``uses_native_search`` says so (ADR 0017): constants
86
+ # k0 owns, the one exception to "tools are only ``BaseTool`` instances".
87
+ # Binding OpenAI's routes ``ChatOpenAI`` through the Responses API (#182);
88
+ # Anthropic's carries its own cap (#209).
89
+ # ponytail: Anthropic's basic web search runs each search directly — no
90
+ # code-execution caller, no container — so a paused turn replays intact
91
+ # through langchain-anthropic, which drops a search block's ``caller``.
92
+ # Dynamic filtering (``web_search_20260209``) needs that kept; switch once
93
+ # the adapter preserves ``caller`` and the continuation passes the container.
94
+ OPENAI_WEB_SEARCH: dict[str, Any] = {"type": "web_search"}
95
+ ANTHROPIC_WEB_SEARCH: dict[str, Any] = {
96
+ "type": "web_search_20250305",
97
+ "name": "web_search",
98
+ "max_uses": NATIVE_SEARCH_MAX_CALLS,
99
+ }
100
+ NATIVE_SEARCH_TOOLS: dict[str, dict[str, Any]] = {
101
+ "openai": OPENAI_WEB_SEARCH,
102
+ "anthropic": ANTHROPIC_WEB_SEARCH,
103
+ }
104
+
105
+ # The roster's tool allowlists (issue #12). `bulk_read` and `search_memory`
106
+ # are on the base reads (#40); CHATTY's `read_work_item` joins when the
107
+ # tracker lands (#43).
108
+ ALLOWLISTS: dict[str, tuple[str, ...]] = {
109
+ "planner": _BASE_READ_TOOLS + _TRACKER_TOOLS + _NETWORK_TOOLS,
110
+ "researcher": _PRIMARY_READ_TOOLS + _NETWORK_TOOLS,
111
+ "chatty": _BASE_READ_TOOLS,
112
+ "implementer": _BASE_READ_TOOLS
113
+ + ("write_file", "edit_file", "run_tests")
114
+ + _TRACKER_TOOLS,
115
+ "reviewer": _BASE_READ_TOOLS + ("read_work_item", "read_change_diff"),
116
+ }
117
+
118
+ # A model→tools round costs four super-steps in the compiled agent graph
119
+ # (before_model, model, after_model, tools), plus start/end bookkeeping.
120
+ # The recursion limit is a backstop: the model-call limit is the real bound
121
+ # and hitting a recursion limit means a k0 bug (#20).
122
+ _STEPS_PER_CALL = 4
123
+ _STEPS_SLACK = 8
124
+
125
+ # Tries after a transient provider error before the run stops (#85). The
126
+ # retries happen inside one model call, so they never count toward
127
+ # ``model_calls``; each try still emits its own ``model`` event.
128
+ _MODEL_RETRIES = 2
129
+
130
+ # Connection-level failures the provider SDKs raise without a status code:
131
+ # httpx's (ollama), the OpenAI/Anthropic clients' (timeouts included), and
132
+ # botocore's (Bedrock) — timeouts and transport breaks only, never the
133
+ # service's own ClientError/EventStreamError, so auth, config and quota
134
+ # failures still stop the run. A Converse read timeout raised while the
135
+ # event stream is being read escapes botocore's own retry layer (it only
136
+ # retries the request exchange), so k0's bounded retry is what covers it
137
+ # (#177).
138
+ _TRANSIENT_ERROR_TYPES = frozenset(
139
+ {
140
+ "TransportError",
141
+ "APIConnectionError",
142
+ "ReadTimeoutError",
143
+ "ConnectTimeoutError",
144
+ "EndpointConnectionError",
145
+ "ProxyConnectionError",
146
+ "ConnectionClosedError",
147
+ "ResponseStreamingError",
148
+ "IncompleteReadError",
149
+ }
150
+ )
151
+
152
+ # Inside one agent run every model call resends all earlier tool output.
153
+ # Past this many tokens, results the model has already read reach it as a
154
+ # placeholder (the run's own messages keep them). Half of Ollama's 64k
155
+ # window, so a local model never silently drops its prompt.
156
+ _CLEAR_TOOL_RESULTS_AT = 32_000
157
+ _CLEARED = "[cleared to save context; call the tool again if you need this]"
158
+
159
+ # The tool names a provider accepts in the history (Bedrock's rule, the
160
+ # strictest one k0 talks to).
161
+ _TOOL_NAME = re.compile(r"[a-zA-Z0-9_-]{1,64}")
162
+
163
+
164
+ class Review(BaseModel):
165
+ """REVIEWER's structured output: its verdict on the change.
166
+
167
+ ``status`` is the verdict — ``completed`` or ``refused`` — tracked per
168
+ axis separately from the text and findings: a refused or missing
169
+ review is not a completed review with zero findings (#175).
170
+ """
171
+
172
+ status: Literal["completed", "refused"]
173
+ summary: str
174
+ findings: list[str]
175
+ reason: str = ""
176
+
177
+ @model_validator(mode="after")
178
+ def _refusal_has_a_reason(self) -> "Review":
179
+ if self.status == "refused" and not self.reason.strip():
180
+ raise ValueError("a refused review needs a reason")
181
+ return self
182
+
183
+
184
+ class Question(BaseModel):
185
+ """One numbered PLANNER question with its recommended answer."""
186
+
187
+ number: int
188
+ question: str
189
+ recommendation: str
190
+ rationale: str = ""
191
+
192
+
193
+ class QuestionRound(BaseModel):
194
+ """PLANNER's structured output for one Q&A round."""
195
+
196
+ questions: list[Question]
197
+
198
+
199
+ class Spec(BaseModel):
200
+ """PLANNER's structured output: the spec draft for the spec gate."""
201
+
202
+ title: str
203
+ problem_statement: str
204
+ solution: str
205
+ user_stories: list[str]
206
+ implementation_decisions: list[str]
207
+ testing_decisions: list[str]
208
+ seams: list[str]
209
+ glossary_and_decisions: list[str]
210
+ not_yet_decided: list[str]
211
+ out_of_scope: list[str]
212
+
213
+
214
+ class Ticket(BaseModel):
215
+ """One child work item in PLANNER's ticket breakdown."""
216
+
217
+ title: str
218
+ what_to_build: str
219
+ seams: list[str]
220
+ acceptance_criteria: list[str]
221
+ blocked_by: list[int] = Field(default_factory=list)
222
+
223
+
224
+ def _earlier_ticket(index: int, blocker: int) -> bool:
225
+ return 0 <= blocker < index
226
+
227
+
228
+ class TicketList(BaseModel):
229
+ """PLANNER's structured output: the spec's tickets, blockers first."""
230
+
231
+ tickets: list[Ticket]
232
+
233
+ @model_validator(mode="after")
234
+ def _blockers_point_backwards(self) -> "TicketList":
235
+ for index, ticket in enumerate(self.tickets):
236
+ if any(not _earlier_ticket(index, blocker) for blocker in ticket.blocked_by):
237
+ raise ValueError("ticket blockers must be earlier ticket indexes")
238
+ return self
239
+
240
+
241
+ class DecisionTicket(BaseModel):
242
+ """One open question on a Map, typed by who answers it (#124)."""
243
+
244
+ question: str
245
+ type: Literal["research", "Q&A", "human"]
246
+ blocked_by: list[int] = Field(default_factory=list)
247
+
248
+
249
+ class ChartedMap(BaseModel):
250
+ """PLANNER's structured output: the map ``/research`` charts."""
251
+
252
+ title: str
253
+ destination: str
254
+ notes: str = ""
255
+ decisions: list[DecisionTicket]
256
+ not_yet_specified: list[str] = Field(default_factory=list)
257
+ out_of_scope: list[str] = Field(default_factory=list)
258
+
259
+ @model_validator(mode="after")
260
+ def _blockers_point_backwards(self) -> "ChartedMap":
261
+ for index, decision in enumerate(self.decisions):
262
+ if any(
263
+ not _earlier_ticket(index, blocker)
264
+ for blocker in decision.blocked_by
265
+ ):
266
+ raise ValueError(
267
+ "decision blockers must be earlier decision indexes"
268
+ )
269
+ return self
270
+
271
+
272
+ class DecisionProposal(BaseModel):
273
+ """PLANNER's structured output: the proposed decision on a Q&A
274
+ decision ticket (#125)."""
275
+
276
+ proposed_decision: str
277
+ rationale: str = ""
278
+
279
+
280
+ class TriageBrief(BaseModel):
281
+ """The agent brief a ``ready-for-*`` triage outcome posts (#128)."""
282
+
283
+ what_to_build: str
284
+ seams: list[str] = Field(default_factory=list)
285
+ acceptance_criteria: list[str] = Field(default_factory=list)
286
+ blocked_by: list[str] = Field(default_factory=list)
287
+ parent: str = ""
288
+
289
+
290
+ class TriageOutcome(BaseModel):
291
+ """PLANNER's triage proposal: one category, one state, the comment."""
292
+
293
+ category: Literal["bug", "enhancement"]
294
+ state: Literal[
295
+ "needs-triage",
296
+ "needs-info",
297
+ "ready-for-agent",
298
+ "ready-for-human",
299
+ "wontfix",
300
+ ]
301
+ comment: str = ""
302
+ brief: TriageBrief | None = None
303
+
304
+
305
+ class ResearchCitation(BaseModel):
306
+ """A primary source RESEARCHER cites."""
307
+
308
+ title: str
309
+ url: str
310
+
311
+
312
+ class ResearchFinding(BaseModel):
313
+ """RESEARCHER's structured output: cited findings and a proposed decision."""
314
+
315
+ findings: list[str] = Field(min_length=1)
316
+ proposed_decision: str = Field(min_length=1)
317
+ citations: list[ResearchCitation] = Field(min_length=1)
318
+
319
+
320
+ _PLANNER_OUTPUT = (
321
+ QuestionRound
322
+ | Spec
323
+ | TicketList
324
+ | ChartedMap
325
+ | DecisionProposal
326
+ | TriageOutcome
327
+ )
328
+
329
+ # Agents whose ``create_agent`` gets a structured ``response_format`` (spec
330
+ # #33): the schema becomes a tool the model calls; the validated value lands
331
+ # on ``AgentResult.structured_response``.
332
+ _RESPONSE_FORMATS: dict[str, Any] = {
333
+ "planner": ToolStrategy(_PLANNER_OUTPUT),
334
+ "researcher": ResearchFinding,
335
+ "reviewer": Review,
336
+ }
337
+
338
+
339
+ class MissingStructuredOutput(Exception):
340
+ """An agent with a ``response_format`` finished without one and no
341
+ limit hit.
342
+
343
+ Raised inside the agent invoke — the same resumable stop path as a
344
+ provider error: the checkpoint stays before the node, the error is
345
+ shown, and the run is never ``stuck`` (spec #33, #58)."""
346
+
347
+
348
+ _MISSING_OUTPUT = {
349
+ "planner": "PLANNER returned no structured output",
350
+ "researcher": "RESEARCHER returned no research finding",
351
+ "reviewer": "REVIEWER returned no review",
352
+ }
353
+
354
+
355
+ # The tools a proposal-only run never gets: no writes, no test runs —
356
+ # ``/implement``'s seam gate is a human decision, not a build (#116).
357
+ _SEAM_DROP = ("write_file", "edit_file", "run_tests")
358
+
359
+
360
+ def allowlist_for(name: str, *, tracker: bool, read_only: bool = False) -> tuple[str, ...]:
361
+ """Agent ``name``'s allowlist for this run.
362
+
363
+ Without a tracker (no work item), the tracker
364
+ reads drop off the allowlist; the agent can never see the tool.
365
+ ``read_only`` drops the mutating tools for proposal phases.
366
+ """
367
+ names = ALLOWLISTS[name]
368
+ if read_only:
369
+ names = _without(names, _SEAM_DROP)
370
+ if tracker:
371
+ return names
372
+ return _without(names, _TRACKER_TOOLS)
373
+
374
+
375
+ def _without(names: tuple[str, ...], dropped: tuple[str, ...]) -> tuple[str, ...]:
376
+ return tuple(n for n in names if n not in dropped)
377
+
378
+
379
+ def agent_tools(
380
+ name: str,
381
+ *,
382
+ root: Path,
383
+ cfg: dict | None = None,
384
+ tracker=None,
385
+ init: Callable = init_chat_model,
386
+ resolve: Resolver | None = None,
387
+ transport: Transport | None = None,
388
+ environ: Mapping[str, str] | None = None,
389
+ fetch: Fetch | None = None,
390
+ read_only: bool = False,
391
+ slice_start: SliceStart = "green",
392
+ journal: SliceJournal | None = None,
393
+ ) -> list[BaseTool | dict[str, Any]]:
394
+ """The tools on agent ``name``'s allowlist, bound to the run context.
395
+
396
+ ``cfg`` supplies ``test_cmd``/``test_timeout`` for ``run_tests``,
397
+ ``helpers.*`` for ``bulk_read`` and ``search.provider`` for
398
+ ``web_search`` — or ``search.native``, which puts the provider's own
399
+ search constant in the ``web_search`` slot instead (#182);
400
+ ``tracker`` feeds the tracker reads; ``init`` builds
401
+ helper models; ``resolve``/``transport``/``environ``/``fetch`` are the
402
+ network tools' injected seams. Each is needed only by tools that use
403
+ it, and only when the tool runs. With ``tracker=None`` the tracker
404
+ reads are left off entirely (a ``<task>`` run), matching
405
+ ``allowlist_for(name, tracker=False)``. ``read_only`` matches
406
+ ``allowlist_for(..., read_only=True)`` the same way. ``slice_start``
407
+ is IMPLEMENTER's guard's start state — ``refactor`` for a run started
408
+ from a review redo (#110).
409
+ """
410
+ try:
411
+ names = allowlist_for(
412
+ name, tracker=tracker is not None, read_only=read_only
413
+ )
414
+ except KeyError:
415
+ raise ValueError(f"unknown agent: {name!r}") from None
416
+ factories = _tool_factories(
417
+ name,
418
+ root=root,
419
+ cfg=cfg,
420
+ tracker=tracker,
421
+ init=init,
422
+ resolve=resolve,
423
+ transport=transport,
424
+ environ=environ,
425
+ fetch=fetch,
426
+ slice_start=slice_start,
427
+ journal=journal,
428
+ )
429
+ tools: list[BaseTool | dict[str, Any]] = []
430
+ for tool_name in names:
431
+ if tool_name == "web_search" and uses_native_search(cfg or {}, name):
432
+ tools.append(NATIVE_SEARCH_TOOLS[native_search_provider(cfg or {}, name)])
433
+ else:
434
+ tools.append(factories[tool_name]())
435
+ return tools
436
+
437
+
438
+ def build_agent(
439
+ name: str,
440
+ cfg: dict,
441
+ tools: Sequence[BaseTool | dict[str, Any]],
442
+ *,
443
+ root: Path,
444
+ init: Callable = init_chat_model,
445
+ allowlist: Sequence[str] | None = None,
446
+ ) -> "K0Agent":
447
+ """Build agent ``name`` behind the fresh-context wrapper.
448
+
449
+ ``tools`` must be exactly the agent's allowlist — ``allowlist``, or
450
+ ``ALLOWLISTS[name]`` when it is ``None`` (a ``<task>`` run passes the
451
+ tracker-less list). The model comes from the ``agents.<name>`` config
452
+ entry, and the prompt from ``prompts/<name>.md`` plus the project's
453
+ `Rules.md` and topology when someone has edited them.
454
+ """
455
+ entry = cfg["agents"][name]
456
+ checked = _check_allowlist(name, tools, allowlist)
457
+ model = build_chat_model(cfg, entry, init=init)
458
+ middleware: list[AgentMiddleware] = [
459
+ ModelCallLimitMiddleware( # type: ignore[list-item]
460
+ run_limit=entry["model_calls"], exit_behavior="end"
461
+ ),
462
+ ModelRetryMiddleware(
463
+ max_retries=_MODEL_RETRIES,
464
+ retry_on=is_transient,
465
+ on_failure="error",
466
+ ),
467
+ ContextEditingMiddleware(
468
+ edits=[ClearSeenToolResults(exclude_tools=("read_work_item",))], # type: ignore[list-item]
469
+ ),
470
+ ToolNameMiddleware(),
471
+ ToolErrorMiddleware(),
472
+ ]
473
+ if uses_native_search(cfg, name):
474
+ middleware.append(
475
+ NativeSearchMiddleware(
476
+ agent=name, model=entry["model"], provider=entry["provider"]
477
+ )
478
+ )
479
+ graph = create_agent(
480
+ model,
481
+ tools=checked,
482
+ system_prompt=_system_prompt(name, root),
483
+ response_format=_RESPONSE_FORMATS.get(name),
484
+ middleware=middleware,
485
+ name=name,
486
+ )
487
+ return K0Agent(
488
+ name,
489
+ graph,
490
+ checked,
491
+ model_calls=entry["model_calls"],
492
+ effort=entry.get("effort"),
493
+ )
494
+
495
+
496
+ def is_transient(error: Exception) -> bool:
497
+ """A model error worth another try: anything but a 4xx client error
498
+ (408 and 429 excepted), or a connection or timeout failure. Ollama
499
+ reports an error inside its response stream with status ``-1``."""
500
+ if isinstance(error, (ConnectionError, TimeoutError)):
501
+ return True
502
+ status = getattr(error, "status_code", None)
503
+ if isinstance(status, int):
504
+ return status in (408, 429) or not 400 <= status < 500
505
+ return any(
506
+ cls.__name__ in _TRANSIENT_ERROR_TYPES for cls in type(error).__mro__
507
+ )
508
+
509
+
510
+ @dataclass
511
+ class ClearSeenToolResults:
512
+ """A context edit: clear tool results the model has already read.
513
+
514
+ Only results from before the model's latest message qualify: it saw
515
+ them and answered. The results it is about to read, a whole parallel
516
+ batch included, always reach it whole; clearing those made the model
517
+ invent what the files said. The oldest go first, and only until the
518
+ context is back under the trigger.
519
+ """
520
+
521
+ trigger: int = _CLEAR_TOOL_RESULTS_AT
522
+ placeholder: str = _CLEARED
523
+ exclude_tools: tuple[str, ...] = ()
524
+
525
+ def apply(self, messages: list[BaseMessage], *, count_tokens: Callable) -> None:
526
+ for index in _seen_tool_results(messages, self.exclude_tools):
527
+ if count_tokens(messages) <= self.trigger:
528
+ return
529
+ messages[index] = messages[index].model_copy(update={"content": self.placeholder})
530
+
531
+
532
+ def _seen_tool_results(messages: list[BaseMessage], excluded: tuple[str, ...]) -> list[int]:
533
+ """Indexes of tool results before the latest AI message, oldest first."""
534
+ latest = max((i for i, m in enumerate(messages) if isinstance(m, AIMessage)), default=0)
535
+ return [
536
+ index
537
+ for index, message in enumerate(messages[:latest])
538
+ if isinstance(message, ToolMessage) and message.name not in excluded
539
+ ]
540
+
541
+
542
+ class ToolNameMiddleware(AgentMiddleware):
543
+ """Send the provider only valid tool names.
544
+
545
+ A model can call a tool named ``functions.edit_file``. The tool node
546
+ answers with a "not a valid tool" error the model sees, but the bad
547
+ name stays in the history, and Bedrock rejects every later request.
548
+ Only the request copy is cleaned: the agent's messages keep what the
549
+ model said.
550
+ """
551
+
552
+ def wrap_model_call(
553
+ self,
554
+ request: ModelRequest,
555
+ handler: Callable[[ModelRequest], ModelResponse],
556
+ ) -> ModelResponse:
557
+ messages = [_clean_tool_names(message) for message in request.messages]
558
+ return handler(request.override(messages=messages)) # type: ignore[arg-type]
559
+
560
+
561
+ def _clean_tool_names(message: BaseMessage) -> BaseMessage:
562
+ if not isinstance(message, AIMessage) or all(
563
+ _TOOL_NAME.fullmatch(call["name"]) for call in message.tool_calls
564
+ ):
565
+ return message
566
+ calls = [{**call, "name": _clean_name(call["name"])} for call in message.tool_calls]
567
+ return message.model_copy(update={"tool_calls": calls})
568
+
569
+
570
+ def _clean_name(name: str) -> str:
571
+ return re.sub(r"[^a-zA-Z0-9_-]", "_", name)[:64] or "invalid_tool"
572
+
573
+
574
+ class ToolErrorMiddleware(AgentMiddleware):
575
+ """Turn a ``ToolError`` into an error ``ToolMessage`` the model sees.
576
+
577
+ The tool node only handles argument errors by default and re-raises any
578
+ other ``ToolException``, which would end the run. The error has already
579
+ reached the event handler by the time it gets here, so the ``tool``
580
+ event keeps ``err`` and ``denied``. Any other exception propagates.
581
+ """
582
+
583
+ def wrap_tool_call(
584
+ self,
585
+ request: ToolCallRequest,
586
+ handler: Callable[[ToolCallRequest], ToolMessage | Command],
587
+ ) -> ToolMessage | Command:
588
+ try:
589
+ return handler(request)
590
+ except ToolError as error:
591
+ return ToolMessage(
592
+ content=str(error),
593
+ name=request.tool_call["name"],
594
+ tool_call_id=request.tool_call["id"],
595
+ status="error",
596
+ )
597
+
598
+
599
+ class NativeSearchMiddleware(AgentMiddleware):
600
+ """Bind the provider search's call cap; drop the tool if the model
601
+ cannot use it (ADR 0017).
602
+
603
+ On OpenAI every model call carries ``max_tool_calls`` so the
604
+ provider's searches stay capped; Anthropic's tool carries its own
605
+ ``max_uses`` and gets no extra setting. When the provider rejects the
606
+ tool — the configured model does not support web search, or the
607
+ organization has it switched off — the call is retried
608
+ once without it and the tool stays off for the rest of the agent
609
+ run. One ``warning`` event names the agent and model; k0 never falls
610
+ back to ``search.provider`` (Brave): a silent switch would hide a
611
+ misconfiguration and could bill a second account.
612
+ """
613
+
614
+ def __init__(self, *, agent: str, model: str, provider: str = "openai") -> None:
615
+ super().__init__()
616
+ self._agent = agent
617
+ self._model = model
618
+ self._cap = (
619
+ {"max_tool_calls": NATIVE_SEARCH_MAX_CALLS} if provider == "openai" else {}
620
+ )
621
+ self._search_dropped = False
622
+
623
+ def wrap_model_call(
624
+ self,
625
+ request: ModelRequest,
626
+ handler: Callable[[ModelRequest], ModelResponse],
627
+ ) -> ModelResponse:
628
+ request = request.override(
629
+ model_settings={**request.model_settings, **self._cap}
630
+ )
631
+ if self._search_dropped:
632
+ request = request.override(tools=_without_search(request.tools))
633
+ try:
634
+ return _resume_paused(request, handler)
635
+ except Exception as error:
636
+ if not _unsupported_search(error):
637
+ raise
638
+ self._search_dropped = True
639
+ dispatch_custom_event(
640
+ WARNING_EVENT,
641
+ {
642
+ "agent": self._agent,
643
+ "model": self._model,
644
+ "reason": "web search unsupported",
645
+ },
646
+ )
647
+ return handler(request.override(tools=_without_search(request.tools)))
648
+
649
+
650
+ def _without_search(tools: Sequence[Any]) -> list[Any]:
651
+ return [tool for tool in tools if tool not in NATIVE_SEARCH_TOOLS.values()]
652
+
653
+
654
+ # Anthropic may pause a long server-search turn (``pause_turn``): the turn
655
+ # is unfinished, not final. k0 sends the paused content back unchanged,
656
+ # with the same tools, at most this many times per model call; one more
657
+ # pause fails the call (#210 review). Every continuation is its own model
658
+ # invocation with its own ``model`` event; the continuations of one model
659
+ # call are bounded by this limit, not by the agent's ``model_calls``.
660
+ PAUSED_TURN_LIMIT = 3
661
+
662
+
663
+ def _resume_paused(
664
+ request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]
665
+ ) -> ModelResponse:
666
+ paused: list[AIMessage] = []
667
+ for _ in range(PAUSED_TURN_LIMIT + 1):
668
+ outcome = _call_once(request, handler)
669
+ if isinstance(outcome, ModelResponse):
670
+ return _with_paused(outcome, paused)
671
+ paused.append(outcome)
672
+ request = _continuation(request, outcome)
673
+ raise RuntimeError(
674
+ f"the provider paused the search turn {PAUSED_TURN_LIMIT + 1} times; "
675
+ "stopping this model call"
676
+ )
677
+
678
+
679
+ def _call_once(
680
+ request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]
681
+ ) -> ModelResponse | AIMessage:
682
+ """The response, or the paused message when the turn paused — also
683
+ when LangChain's provider structured output failed to parse it."""
684
+ try:
685
+ response = handler(request)
686
+ except Exception as error:
687
+ message = paused_turn(error)
688
+ if message is None:
689
+ raise
690
+ return message
691
+ return paused_turn(response) or response
692
+
693
+
694
+ def paused_turn(source: Any) -> AIMessage | None:
695
+ """The paused assistant message in a model response, or in the
696
+ structured-output error LangChain raises when it parses one."""
697
+ message = getattr(source, "ai_message", None)
698
+ if isinstance(source, ModelResponse):
699
+ message = source.result[-1] if source.result else None
700
+ return message if _is_paused(message) else None
701
+
702
+
703
+ def _is_paused(message: Any) -> bool:
704
+ return (
705
+ isinstance(message, AIMessage)
706
+ and message.response_metadata.get("stop_reason") == "pause_turn"
707
+ )
708
+
709
+
710
+ def _continuation(request: ModelRequest, message: AIMessage) -> ModelRequest:
711
+ """The same request, tools included, with the paused turn appended
712
+ unchanged."""
713
+ return request.override(messages=[*request.messages, message])
714
+
715
+
716
+ def _with_paused(response: ModelResponse, paused: list[AIMessage]) -> ModelResponse:
717
+ """Merge the paused turns' content ahead of the answer's, in order, in
718
+ one assistant message: the history keeps every search block, and one
719
+ model node still leaves one assistant message for the call count."""
720
+ if not paused:
721
+ return response
722
+ answer, *rest = response.result
723
+ content = [block for message in [*paused, answer] for block in _blocks(message)]
724
+ merged = answer.model_copy(update={"content": content})
725
+ return ModelResponse(
726
+ result=[merged, *rest], structured_response=response.structured_response
727
+ )
728
+
729
+
730
+ def _blocks(message: BaseMessage) -> list[Any]:
731
+ if isinstance(message.content, list):
732
+ return list(message.content)
733
+ return [{"type": "text", "text": message.content}] if message.content else []
734
+
735
+
736
+ _WEB_SEARCH = re.compile(r"web[ _]search", re.IGNORECASE)
737
+
738
+
739
+ def _unsupported_search(error: Exception) -> bool:
740
+ """A provider SDK's ``BadRequestError`` naming web search: the model
741
+ cannot use the tool (``web_search``, ``web_search_20260209``), or the
742
+ organization has it off ("Web search is not enabled"). Matched on the
743
+ class name — the provider extras may not be installed — like
744
+ ``_TRANSIENT_ERROR_TYPES``."""
745
+ return bool(_WEB_SEARCH.search(str(error))) and any(
746
+ cls.__name__ == "BadRequestError" for cls in type(error).__mro__
747
+ )
748
+
749
+
750
+ def _check_allowlist(
751
+ name: str,
752
+ tools: Sequence[BaseTool | dict[str, Any]],
753
+ allowlist: Sequence[str] | None = None,
754
+ ) -> list[BaseTool | dict[str, Any]]:
755
+ slots = [_tool_slot(name, item) for item in tools]
756
+ expected = set(allowlist if allowlist is not None else ALLOWLISTS[name])
757
+ if len(set(slots)) != len(slots) or set(slots) != expected:
758
+ raise ToolError(
759
+ f"agent {name!r} tools must be its allowlist {sorted(expected)}; "
760
+ f"got {sorted(slots)}",
761
+ denied="allowlist",
762
+ )
763
+ return list(tools)
764
+
765
+
766
+ def _tool_slot(agent: str, item: BaseTool | dict[str, Any]) -> str:
767
+ """The allowlist slot a tool occupies; dict tools are refused but for
768
+ the one provider built-in PLANNER and RESEARCHER may carry (ADR 0017)."""
769
+ if isinstance(item, BaseTool):
770
+ return item.name
771
+ if agent in NATIVE_SEARCH_AGENTS and item in NATIVE_SEARCH_TOOLS.values():
772
+ return "web_search"
773
+ raise TypeError(f"tools must be BaseTool instances, got {item!r}")
774
+
775
+
776
+ def _prompt(name: str) -> str:
777
+ return (files("k0ntrol") / "prompts" / f"{name}.md").read_text(
778
+ encoding="utf-8"
779
+ )
780
+
781
+
782
+ def _system_prompt(name: str, root: Path) -> str:
783
+ """The agent's prompt file plus edited memory: `Rules.md` and topology
784
+ go in when someone has changed them from the init template."""
785
+ parts = [_prompt(name)]
786
+ rules = custom_rules_text(root)
787
+ if rules:
788
+ parts.append(rules)
789
+ topology = custom_topology_text(root)
790
+ if topology:
791
+ parts.append(topology)
792
+ return "\n\n".join(parts)
793
+
794
+
795
+ def _tool_factories(
796
+ agent: str,
797
+ *,
798
+ root: Path,
799
+ cfg: dict | None,
800
+ tracker,
801
+ init: Callable,
802
+ resolve: Resolver | None,
803
+ transport: Transport | None,
804
+ environ: Mapping[str, str] | None,
805
+ fetch: Fetch | None,
806
+ slice_start: SliceStart = "green",
807
+ journal: SliceJournal | None = None,
808
+ ) -> dict[str, Callable[[], BaseTool]]:
809
+ guard = (
810
+ SliceGuard(start=slice_start, journal=journal)
811
+ if agent == "implementer"
812
+ else None
813
+ )
814
+ factories: dict[str, Callable[[], BaseTool]] = {
815
+ "read_file": lambda: make_read_file(root),
816
+ "list_files": lambda: make_list_files(root),
817
+ "grep": lambda: make_grep(root),
818
+ "bulk_read": lambda: make_bulk_read(root, cfg, init=init),
819
+ "search_memory": lambda: make_search_memory(root),
820
+ "fetch_url": lambda: make_fetch_url(resolve=resolve, transport=transport),
821
+ "web_search": lambda: make_web_search(
822
+ cfg or {}, environ=environ, fetch=fetch
823
+ ),
824
+ "run_tests": lambda: make_run_tests(root, _need_cfg(cfg), guard),
825
+ "read_work_item": lambda: _tracker_tool("read_work_item", tracker),
826
+ "read_change_diff": lambda: _tracker_tool("read_change_diff", tracker),
827
+ }
828
+ policy: WritePolicy | None = guard
829
+ if policy is not None:
830
+ factories["write_file"] = lambda: make_write_file(root, policy)
831
+ factories["edit_file"] = lambda: make_edit_file(root, policy)
832
+ return factories
833
+
834
+
835
+ def _need_cfg(cfg: dict | None) -> dict:
836
+ if cfg is None:
837
+ raise ValueError("run_tests needs the project config")
838
+ return cfg
839
+
840
+
841
+ def _tracker_tool(name: str, tracker) -> BaseTool:
842
+ if tracker is None:
843
+ raise ValueError(f"the {name} tool needs a tracker")
844
+ tools = {tool.name: tool for tool in tracker_read_tools(tracker)}
845
+ return tools[name]
846
+
847
+
848
+ def _recursion_limit(model_calls: int) -> int:
849
+ return model_calls * _STEPS_PER_CALL + _STEPS_SLACK
850
+
851
+
852
+ @dataclass
853
+ class AgentResult:
854
+ """What one agent run leaves: the messages and whether the model-call
855
+ limit ended it."""
856
+
857
+ messages: list[BaseMessage]
858
+ limit_hit: bool
859
+ structured_response: Any = None
860
+
861
+ @property
862
+ def text(self) -> str:
863
+ """The last real AI text; the injected limit message never counts."""
864
+ return _answer_text(self.messages)
865
+
866
+
867
+ def _answer_text(messages: list[BaseMessage]) -> str:
868
+ for message in reversed(messages):
869
+ if _is_answer(message):
870
+ return _content_text(message.content)
871
+ return ""
872
+
873
+
874
+ def _is_answer(message: BaseMessage) -> bool:
875
+ if not isinstance(message, AIMessage):
876
+ return False
877
+ text = _content_text(message.content)
878
+ return bool(text) and not _is_limit_marker(text)
879
+
880
+
881
+ def _content_text(content) -> str:
882
+ """A message's text, whether it is a plain string or content blocks."""
883
+ if isinstance(content, str):
884
+ return content
885
+ if isinstance(content, list):
886
+ return "".join(
887
+ block.get("text", "")
888
+ for block in content
889
+ if isinstance(block, dict) and block.get("type") == "text"
890
+ )
891
+ return ""
892
+
893
+
894
+ def _is_limit_marker(text: str) -> bool:
895
+ return text.startswith("Model call limits exceeded")
896
+
897
+
898
+ def _limit_hit(messages: list[BaseMessage], model_calls: int) -> bool:
899
+ # With exit_behavior="end" the middleware appends one extra AI message
900
+ # when the agent wants a call past the limit, so a limit hit shows as
901
+ # more AI messages than calls allowed.
902
+ calls = sum(1 for m in messages if isinstance(m, AIMessage))
903
+ return calls > model_calls
904
+
905
+
906
+ class K0Agent:
907
+ """An agent behind the fresh-context wrapper.
908
+
909
+ Every ``invoke``/``stream`` sends a brand-new ``{"messages": ...}`` into
910
+ the compiled ``create_agent`` graph — no checkpointer, no thread state —
911
+ so each run starts fresh (ADR 0002). The wrapper always sets the
912
+ derived ``recursion_limit`` and tags callback metadata with the agent
913
+ name and effort so the event handler can fill event fields.
914
+ """
915
+
916
+ def __init__(
917
+ self,
918
+ name: str,
919
+ graph,
920
+ tools: Sequence[BaseTool | dict[str, Any]],
921
+ *,
922
+ model_calls: int,
923
+ effort: str | None = None,
924
+ ) -> None:
925
+ self.name = name
926
+ self.tools = tuple(tools)
927
+ self.model_calls = model_calls
928
+ self.effort = effort
929
+ self.recursion_limit = _recursion_limit(model_calls)
930
+ self._graph = graph
931
+
932
+ def invoke(
933
+ self, messages: Sequence[BaseMessage], *, config: dict | None = None
934
+ ) -> AgentResult:
935
+ """Run the agent once on fresh context; return its messages."""
936
+ output = self._graph.invoke(
937
+ {"messages": list(messages)}, config=self._config(config)
938
+ )
939
+ return self._result(output)
940
+
941
+ def stream(
942
+ self,
943
+ messages: Sequence[BaseMessage],
944
+ *,
945
+ config: dict | None = None,
946
+ on_text: Callable[[str], None] | None = None,
947
+ ) -> AgentResult:
948
+ """Run the agent once, streaming answer text through ``on_text``."""
949
+ output = None
950
+ for mode, data in self._graph.stream(
951
+ {"messages": list(messages)},
952
+ config=self._config(config),
953
+ stream_mode=["messages", "values"],
954
+ ):
955
+ if mode == "values":
956
+ output = data
957
+ elif on_text is not None:
958
+ _emit_text(data, on_text)
959
+ return self._result(output)
960
+
961
+ def _config(self, config: dict | None) -> dict:
962
+ merged = dict(config or {})
963
+ merged["recursion_limit"] = self.recursion_limit
964
+ metadata = dict(merged.get("metadata") or {})
965
+ metadata[META_AGENT] = self.name
966
+ if self.effort:
967
+ metadata[META_EFFORT] = self.effort
968
+ merged["metadata"] = metadata
969
+ # The run graph's checkpointer leaks into this invoke through
970
+ # runnable config context: without a fresh namespace the inner run
971
+ # checkpoints under the node's task namespace and a retried node
972
+ # replays its stale output instead of re-running on fresh context
973
+ # (ADR 0002, #58).
974
+ configurable = dict(merged.get("configurable") or {})
975
+ configurable["checkpoint_ns"] = f"{self.name}-{uuid4().hex}"
976
+ merged["configurable"] = configurable
977
+ return merged
978
+
979
+ def _result(self, output: dict | None) -> AgentResult:
980
+ messages = list((output or {}).get("messages") or [])
981
+ limited = _limit_hit(messages, self.model_calls)
982
+ structured = (output or {}).get("structured_response")
983
+ if self.name in _MISSING_OUTPUT and not limited and structured is None:
984
+ raise MissingStructuredOutput(_MISSING_OUTPUT[self.name])
985
+ return AgentResult(
986
+ messages=messages,
987
+ limit_hit=limited,
988
+ structured_response=structured,
989
+ )
990
+
991
+
992
+ def _emit_text(data, on_text: Callable[[str], None]) -> None:
993
+ chunk, metadata = data
994
+ if not isinstance(chunk, AIMessageChunk) or metadata.get(META_HELPER):
995
+ return
996
+ text = _content_text(chunk.content)
997
+ if text:
998
+ on_text(text)