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/cli.py ADDED
@@ -0,0 +1,190 @@
1
+ import argparse
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ from langchain.chat_models import init_chat_model
6
+
7
+ from k0ntrol import __version__
8
+ from k0ntrol.config import ConfigError, load_config
9
+ from k0ntrol.credentials import load_credentials
10
+ from k0ntrol.events import (
11
+ EventWriter,
12
+ K0EventHandler,
13
+ ProgressRenderer,
14
+ events_path,
15
+ new_run_id,
16
+ )
17
+ from k0ntrol.frontends.banner import color_enabled
18
+ from k0ntrol.frontends.session import run_session
19
+ from k0ntrol.frontends.terminal import Terminal, needs_project_setup, needs_provider_setup
20
+ from k0ntrol.helpers import helper_invoker
21
+ from k0ntrol.init_flow import run_init
22
+ from k0ntrol.memory.refresh import refresh_memory
23
+ from k0ntrol.otel import build_run_trace, trace_callbacks
24
+ from k0ntrol.providers import free_checks, has_errors, live_checks, report_lines
25
+ from k0ntrol.workflow.change import current_branch
26
+
27
+
28
+ def main(argv: list[str] | None = None, *, init=init_chat_model) -> int:
29
+ parser = argparse.ArgumentParser(
30
+ prog="k0",
31
+ description="Local harness for coding agents.",
32
+ )
33
+ parser.add_argument(
34
+ "--version",
35
+ action="version",
36
+ version=f"k0 {__version__}",
37
+ )
38
+ subparsers = parser.add_subparsers(dest="command")
39
+ doctor_parser = subparsers.add_parser(
40
+ "doctor",
41
+ help="check the provider setup without spending tokens",
42
+ )
43
+ doctor_parser.add_argument(
44
+ "--live",
45
+ action="store_true",
46
+ help="make one tiny tool-call round trip per configured model",
47
+ )
48
+ init_parser = subparsers.add_parser(
49
+ "init",
50
+ help="create the project memory layout",
51
+ )
52
+ init_parser.add_argument("directory")
53
+ init_parser.add_argument(
54
+ "--tracker",
55
+ help="work-item tracker for the project (github; others not in 0.1.0)",
56
+ )
57
+ init_parser.add_argument(
58
+ "--provider",
59
+ help="one provider for every agent and helper (user config)",
60
+ )
61
+ subparsers.add_parser("scan", help="write the code graph")
62
+ args = parser.parse_args(argv)
63
+ # Keys saved by the setup screen; variables already set always win.
64
+ load_credentials(Path.home())
65
+
66
+ if args.command == "doctor":
67
+ return _run_doctor(live=args.live)
68
+ if args.command == "init":
69
+ return _run_init(args.directory, tracker=args.tracker, provider=args.provider)
70
+ if args.command == "scan":
71
+ return _run_scan(init=init)
72
+ if args.command is None:
73
+ return _run_session(init=init)
74
+ return 0
75
+
76
+
77
+ def _run_init(
78
+ directory: str, *, tracker: str | None = None, provider: str | None = None
79
+ ) -> int:
80
+ return run_init(Path(directory), tracker=tracker, provider=provider)
81
+
82
+
83
+ def _run_doctor(live: bool) -> int:
84
+ try:
85
+ cfg = load_config(Path.cwd())
86
+ except ConfigError as error:
87
+ print(f"config error: {error}", file=sys.stderr)
88
+ return 1
89
+ if needs_provider_setup(Path.home()):
90
+ print("no user config yet: run k0 to set up")
91
+ return 1
92
+
93
+ checks = free_checks(cfg, root=Path.cwd())
94
+ if live:
95
+ checks += live_checks(cfg)
96
+ print("\n".join(report_lines(checks)))
97
+ return 1 if has_errors(checks) else 0
98
+
99
+
100
+ def _run_session(*, init=init_chat_model) -> int:
101
+ root = Path.cwd()
102
+ ui = _terminal_ui()
103
+ if ui is not None and not _first_run(ui, root):
104
+ return 1
105
+ try:
106
+ config = load_config(root)
107
+ except ConfigError as error:
108
+ print(f"config error: {error}", file=sys.stderr)
109
+ return 1
110
+ return run_session(
111
+ lambda: input("› "),
112
+ print,
113
+ root=root,
114
+ config=config,
115
+ color=color_enabled(sys.stdout),
116
+ echo_input=False,
117
+ init=init,
118
+ stream=lambda text: print(text, end="", flush=True),
119
+ ui=ui,
120
+ )
121
+
122
+
123
+ def _first_run(ui: Terminal, root: Path) -> bool:
124
+ """The setup screens on a new repo or machine; False when cancelled."""
125
+ if needs_project_setup(root) or needs_provider_setup(Path.home()):
126
+ ui.welcome(version=__version__, provider=None, cwd=str(root))
127
+ try:
128
+ ui.first_run(root, Path.home())
129
+ except (KeyboardInterrupt, EOFError):
130
+ print("\nsetup cancelled; run k0 again to finish it")
131
+ return False
132
+ return True
133
+
134
+
135
+ def _terminal_ui() -> Terminal | None:
136
+ """The Claude Code-style front in a real terminal; plain lines otherwise."""
137
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
138
+ return None
139
+ return Terminal.open(history=Path.home() / ".k0ntrol" / "history")
140
+
141
+
142
+ def _run_scan(*, init=init_chat_model, tracing=build_run_trace) -> int:
143
+ """Rescan in place: changed files get notes from the bulk_read helper,
144
+ then the FTS index is rebuilt — run-scoped events as it works.
145
+
146
+ The scan is its own Langfuse/OTel trace (id = its run id, kind ``scan``).
147
+ """
148
+ root = Path.cwd()
149
+ run_id = new_run_id()
150
+ trace = tracing(run_id)
151
+ code = _scan(root, init, run_id, trace)
152
+ trace.finish(
153
+ kind="scan",
154
+ outcome="done" if code == 0 else "failed",
155
+ metadata=_scan_metadata(root),
156
+ )
157
+ return code
158
+
159
+
160
+ def _scan(root: Path, init, run_id: str, trace) -> int:
161
+ try:
162
+ config = load_config(root)
163
+ callbacks = [_scan_handler(root, run_id), *trace_callbacks(trace)]
164
+ invoke = helper_invoker(
165
+ config, "bulk_read", init=init, config={"callbacks": callbacks}
166
+ )
167
+ refresh_memory(root, config=config, invoke=invoke)
168
+ except ConfigError as error:
169
+ print(f"config error: {error}", file=sys.stderr)
170
+ return 1
171
+ except Exception as error:
172
+ print(f"scan error: {error}", file=sys.stderr)
173
+ return 1
174
+ return 0
175
+
176
+
177
+ def _scan_metadata(root: Path) -> dict:
178
+ """The scan trace's metadata: branch and k0 version."""
179
+ metadata = {"k0_version": __version__}
180
+ branch = current_branch(root)
181
+ if branch:
182
+ metadata["branch"] = branch
183
+ return metadata
184
+
185
+
186
+ def _scan_handler(root: Path, run_id: str) -> K0EventHandler:
187
+ path = events_path(root)
188
+ path.parent.mkdir(parents=True, exist_ok=True)
189
+ writer = EventWriter(path, run=run_id, progress=ProgressRenderer(print))
190
+ return K0EventHandler(writer)
k0ntrol/config.py ADDED
@@ -0,0 +1,330 @@
1
+ from collections.abc import Mapping
2
+ from importlib.resources import files
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ import yaml
7
+
8
+
9
+ class ConfigError(Exception):
10
+ """Raised when configuration cannot be read or is invalid."""
11
+
12
+
13
+ AGENTS = ("planner", "researcher", "implementer", "reviewer", "chatty")
14
+ HELPERS = ("bulk_read", "reflect")
15
+
16
+ _AGENT_KEYS = {"provider", "model", "effort", "params", "model_calls"}
17
+ _HELPER_KEYS = {"provider", "model", "effort", "params"}
18
+ _EFFORT_LEVELS = {"low", "medium", "high"}
19
+ _TICKET_SIZES = ("small", "medium", "large")
20
+
21
+ # Which issue trackers make sense for each code host (vcs); a missing vcs is github.
22
+ VCS_TRACKERS = {
23
+ "github": ("github", "linear", "jira"),
24
+ "gitlab": ("gitlab", "linear", "jira"),
25
+ "bitbucket": ("jira", "linear"),
26
+ }
27
+
28
+ # 0.0.x keys that are gone in 0.1.0, mapped to their replacement.
29
+ _RETIRED_KEYS = {
30
+ "backend": "set provider on each agents:/helpers: entry",
31
+ "max_retries": "max_attempts",
32
+ "retrieval_top_k": "the search_memory tool's limit argument",
33
+ "reflect_every": "nothing; reflect runs after each run",
34
+ "validator": "VALIDATOR is a deterministic code gate now; use test_cmd and gates",
35
+ "retrieval_gate": "the search_memory tool",
36
+ "bulk_reader": "helpers.bulk_read",
37
+ }
38
+
39
+ _RETIRED_AGENT_KEYS = {
40
+ "agents.spec": "use agents.planner",
41
+ "agents.tester": "use agents.implementer",
42
+ "agents.coder": "use agents.implementer",
43
+ }
44
+
45
+ # Keys that must never appear in config: secrets belong in vendor env vars.
46
+ _SECRET_MARKERS = ("api_key", "token", "secret", "password")
47
+
48
+ # Keys that would inject tool definitions through params.
49
+ _TOOL_MARKERS = ("tool", "function")
50
+
51
+
52
+ def deep_merge(base: dict, override: dict) -> dict:
53
+ result = dict(base)
54
+ for key, value in override.items():
55
+ if isinstance(value, dict) and isinstance(result.get(key), dict):
56
+ result[key] = deep_merge(result[key], value)
57
+ else:
58
+ result[key] = value
59
+ return result
60
+
61
+
62
+ def load_config(project_dir: Path, home_dir: Path | None = None) -> dict:
63
+ effective = _read_config(files("k0ntrol") / "defaults" / "config.yaml")
64
+ home = home_dir or Path.home()
65
+ for path in (home / ".k0ntrol/config.yaml", project_dir / ".k0-mem/config.yaml"):
66
+ if path.exists():
67
+ effective = deep_merge(effective, _read_config(path))
68
+ validate_config(effective)
69
+ return effective
70
+
71
+
72
+ def validate_config(cfg: dict) -> None:
73
+ errors = _validate_top_level(cfg)
74
+ if errors:
75
+ raise ConfigError("; ".join(errors))
76
+
77
+
78
+ def resolved_params(cfg: dict, entry: dict) -> dict:
79
+ """Merge an agent or helper's params over its provider's params."""
80
+ providers = cfg.get("providers") or {}
81
+ provider = providers.get(entry.get("provider")) or {}
82
+ return deep_merge(provider.get("params") or {}, entry.get("params") or {})
83
+
84
+
85
+ def _validate_top_level(cfg: dict) -> list[str]:
86
+ errors = _check_keys(cfg)
87
+ errors.extend(_validate_integer("threshold_lines", cfg.get("threshold_lines"), 1))
88
+ errors.extend(_validate_text("test_cmd", cfg.get("test_cmd")))
89
+ errors.extend(_validate_gates(cfg.get("gates")))
90
+ errors.extend(_validate_optional_text("vcs", cfg.get("vcs")))
91
+ errors.extend(_validate_optional_text("tracker", cfg.get("tracker")))
92
+ errors.extend(_validate_vcs_tracker(cfg.get("vcs"), cfg.get("tracker")))
93
+ errors.extend(_validate_trusted_authors(cfg.get("trusted_authors")))
94
+ errors.extend(_validate_optional_text("base_branch", cfg.get("base_branch")))
95
+ errors.extend(_validate_integer("max_attempts", cfg.get("max_attempts"), 1))
96
+ errors.extend(_validate_integer("test_timeout", cfg.get("test_timeout"), 1))
97
+ errors.extend(_validate_integer("max_questions", cfg.get("max_questions"), 1))
98
+ errors.extend(_validate_integer("max_round_questions", cfg.get("max_round_questions"), 1))
99
+ errors.extend(_validate_choice("ticket_size", cfg.get("ticket_size"), _TICKET_SIZES))
100
+ errors.extend(_validate_roster("agents", cfg.get("agents")))
101
+ errors.extend(_validate_roster("helpers", cfg.get("helpers")))
102
+ errors.extend(_validate_providers(cfg.get("providers")))
103
+ errors.extend(_validate_search(cfg.get("search")))
104
+ return errors
105
+
106
+
107
+ # ``search`` keys: ``provider`` names k0's ``web_search`` backend; ``native``
108
+ # is the switch for provider-native search (#182, ADR 0017).
109
+ _SEARCH_KEYS = {"provider", "native"}
110
+
111
+
112
+ def _validate_search(value: object) -> list[str]:
113
+ if value is None:
114
+ return []
115
+ if not isinstance(value, Mapping):
116
+ return ["search: must be a mapping"]
117
+ errors = [f"search.{key}: unknown key" for key in value if key not in _SEARCH_KEYS]
118
+ if "native" in value and not isinstance(value["native"], bool):
119
+ errors.append("search.native: must be a boolean")
120
+ return errors
121
+
122
+
123
+ def _validate_trusted_authors(value: object) -> list[str]:
124
+ """``trusted_authors``: a list of GitHub App logins (``name[bot]``),
125
+ the expressly trusted App identities of #176 (ADR 0016)."""
126
+ if value is None:
127
+ return []
128
+ if not isinstance(value, list):
129
+ return ["trusted_authors: must be a list"]
130
+ errors = []
131
+ for index, login in enumerate(value):
132
+ errors.extend(_trusted_author_error(index, login))
133
+ return errors
134
+
135
+
136
+ def _trusted_author_error(index: int, login: object) -> list[str]:
137
+ if not isinstance(login, str) or not login.strip():
138
+ return [f"trusted_authors[{index}]: must be a non-empty string"]
139
+ if login != login.strip():
140
+ return [f"trusted_authors[{index}]: must not have surrounding whitespace"]
141
+ if not login.endswith("[bot]"):
142
+ return [f"trusted_authors[{index}]: only App logins, ending in '[bot]'"]
143
+ return []
144
+
145
+
146
+ def _validate_vcs_tracker(vcs: object, tracker: object) -> list[str]:
147
+ if not isinstance(vcs, str) or not isinstance(tracker, str):
148
+ return []
149
+ if vcs not in VCS_TRACKERS:
150
+ return [f"vcs: must be one of {', '.join(VCS_TRACKERS)}"]
151
+ if tracker not in VCS_TRACKERS[vcs]:
152
+ return [f"tracker: '{tracker}' does not fit a repo hosted on {vcs}"]
153
+ return []
154
+
155
+
156
+ def _validate_providers(value: object) -> list[str]:
157
+ if value is None:
158
+ return []
159
+ if not isinstance(value, Mapping):
160
+ return ["providers: must be a mapping"]
161
+ errors = []
162
+ for name, entry in value.items():
163
+ errors.extend(_validate_provider(f"providers.{name}", entry))
164
+ return errors
165
+
166
+
167
+ def _validate_provider(path: str, value: object) -> list[str]:
168
+ if not isinstance(value, Mapping):
169
+ return [f"{path}: must be a mapping"]
170
+ errors = []
171
+ if "base_url" in value:
172
+ errors.extend(_validate_text(f"{path}.base_url", value["base_url"]))
173
+ errors.extend(_validate_params(f"{path}.params", value.get("params")))
174
+ errors.extend(
175
+ f"{path}.{key}: unknown key" for key in value if key not in {"base_url", "params"}
176
+ )
177
+ return errors
178
+
179
+
180
+ def _validate_roster(kind: str, value: object) -> list[str]:
181
+ names = AGENTS if kind == "agents" else HELPERS
182
+ if not isinstance(value, Mapping):
183
+ return [f"{kind}: must be a mapping"]
184
+ errors = _unknown_roster_names(kind, names, value)
185
+ for name in names:
186
+ errors.extend(_validate_entry(f"{kind}.{name}", value.get(name), kind))
187
+ return errors
188
+
189
+
190
+ def _unknown_roster_names(kind: str, names: tuple, value: Mapping) -> list[str]:
191
+ return [
192
+ f"{kind}.{name}: unknown {kind} entry"
193
+ for name in value
194
+ if name not in names and _retired_key_hint(str(name), f"{kind}.{name}") is None
195
+ ]
196
+
197
+
198
+ def _retired_key_hint(key: str, path: str) -> str | None:
199
+ return _RETIRED_KEYS.get(key.lower()) or _RETIRED_AGENT_KEYS.get(path.lower())
200
+
201
+
202
+ def _check_keys(node: object, path: str = "", in_params: bool = False) -> list[str]:
203
+ if isinstance(node, Mapping):
204
+ return _check_mapping_keys(node, path, in_params)
205
+ if isinstance(node, list):
206
+ return _check_list_keys(node, path, in_params)
207
+ return []
208
+
209
+
210
+ def _check_mapping_keys(node: Mapping, path: str, in_params: bool) -> list[str]:
211
+ errors = []
212
+ for key, value in node.items():
213
+ key_path = f"{path}.{key}" if path else str(key)
214
+ errors.extend(_check_key(key, key_path, in_params))
215
+ errors.extend(
216
+ _check_keys(value, key_path, in_params or str(key).lower() == "params")
217
+ )
218
+ return errors
219
+
220
+
221
+ def _check_list_keys(node: list, path: str, in_params: bool) -> list[str]:
222
+ errors = []
223
+ for index, item in enumerate(node):
224
+ errors.extend(_check_keys(item, f"{path}[{index}]", in_params))
225
+ return errors
226
+
227
+
228
+ def _check_key(key: object, path: str, in_params: bool) -> list[str]:
229
+ if not isinstance(key, str):
230
+ return [f"{path}: keys must be strings"]
231
+ lowered = key.lower()
232
+ if hint := _retired_key_hint(key, path):
233
+ return [f"{path}: retired in 0.1.0; {hint}"]
234
+ secret_match = any(
235
+ marker in lowered for marker in _SECRET_MARKERS if marker != "token"
236
+ ) or lowered == "token" or lowered.endswith("token")
237
+ if secret_match:
238
+ return [f"{path}: secrets are not allowed in config; use the provider's env vars"]
239
+ if in_params and any(marker in lowered for marker in _TOOL_MARKERS):
240
+ return [f"{path}: tool definitions are not allowed in params"]
241
+ return []
242
+
243
+
244
+ def _validate_entry(path: str, value: object, kind: str) -> list[str]:
245
+ if not isinstance(value, Mapping):
246
+ return [f"{path}: must be a mapping"]
247
+ errors = _validate_text(f"{path}.provider", value.get("provider"))
248
+ errors.extend(_validate_text(f"{path}.model", value.get("model")))
249
+ errors.extend(_validate_effort(f"{path}.effort", value.get("effort")))
250
+ errors.extend(_validate_params(f"{path}.params", value.get("params")))
251
+ errors.extend(_unknown_entry_keys(path, value, kind))
252
+ if kind == "agents":
253
+ errors.extend(_validate_integer(f"{path}.model_calls", value.get("model_calls"), 1))
254
+ return errors
255
+
256
+
257
+ def _unknown_entry_keys(path: str, entry: Mapping, kind: str) -> list[str]:
258
+ allowed = _AGENT_KEYS if kind == "agents" else _HELPER_KEYS
259
+ return [f"{path}.{key}: unknown key" for key in entry if key not in allowed]
260
+
261
+
262
+ def _validate_effort(name: str, value: object) -> list[str]:
263
+ if value is None:
264
+ return []
265
+ if value not in _EFFORT_LEVELS:
266
+ return [f"{name}: must be one of low, medium, high"]
267
+ return []
268
+
269
+
270
+ def _validate_params(name: str, value: object) -> list[str]:
271
+ if value is None:
272
+ return []
273
+ if not isinstance(value, Mapping):
274
+ return [f"{name}: must be a mapping"]
275
+ return []
276
+
277
+
278
+ def _validate_gates(value: object) -> list[str]:
279
+ if value is None:
280
+ return []
281
+ if not isinstance(value, list):
282
+ return ["gates: must be a list"]
283
+ errors = []
284
+ for index, gate in enumerate(value):
285
+ errors.extend(_validate_gate(index, gate))
286
+ return errors
287
+
288
+
289
+ def _validate_gate(index: int, gate: object) -> list[str]:
290
+ if not isinstance(gate, Mapping):
291
+ return [f"gates[{index}]: must be a mapping"]
292
+ errors = _validate_text(f"gates[{index}].name", gate.get("name"))
293
+ errors.extend(_validate_text(f"gates[{index}].cmd", gate.get("cmd")))
294
+ return errors
295
+
296
+
297
+ def _validate_integer(name: str, value: object, minimum: int) -> list[str]:
298
+ if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
299
+ return [f"{name}: must be an integer >= {minimum}"]
300
+ return []
301
+
302
+
303
+ def _validate_choice(name: str, value: object, choices: tuple) -> list[str]:
304
+ if value not in choices:
305
+ return [f"{name}: must be one of {', '.join(choices)}"]
306
+ return []
307
+
308
+
309
+ def _validate_text(name: str, value: object) -> list[str]:
310
+ if not isinstance(value, str) or not value.strip():
311
+ return [f"{name}: must be a non-empty string"]
312
+ return []
313
+
314
+
315
+ def _validate_optional_text(name: str, value: object) -> list[str]:
316
+ if value is None:
317
+ return []
318
+ return _validate_text(name, value)
319
+
320
+
321
+ def _read_config(path: Any) -> dict:
322
+ try:
323
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
324
+ except yaml.YAMLError as error:
325
+ raise ConfigError(f"{path}: invalid YAML: {error}") from error
326
+ if data is None:
327
+ return {}
328
+ if not isinstance(data, Mapping):
329
+ raise ConfigError(f"{path}: top level must be a mapping")
330
+ return dict(data)
k0ntrol/credentials.py ADDED
@@ -0,0 +1,78 @@
1
+ """API keys k0 saves for the user: ``~/.k0ntrol/credentials``, mode 0600.
2
+
3
+ The file holds ``KEY=VALUE`` lines. :func:`load_credentials` copies the keys
4
+ that name a known credential — a provider's or a search API's — into the
5
+ environment, never over a variable the user already set. Secrets never go
6
+ in ``config.yaml``.
7
+ """
8
+
9
+ import os
10
+ import re
11
+ from collections.abc import MutableMapping
12
+ from pathlib import Path
13
+
14
+ from k0ntrol.providers import REGISTRY
15
+ from k0ntrol.search import SEARCH_PROVIDERS
16
+
17
+ _NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
18
+ _FILE_MODE = 0o600
19
+
20
+
21
+ def credentials_path(home: Path) -> Path:
22
+ return home / ".k0ntrol" / "credentials"
23
+
24
+
25
+ def known_credential_names() -> frozenset[str]:
26
+ names = {name for spec in REGISTRY.values() for name in spec.credentials}
27
+ names.update(provider.key_env for provider in SEARCH_PROVIDERS.values())
28
+ return frozenset(names)
29
+
30
+
31
+ def save_credential(home: Path, name: str, value: str) -> None:
32
+ """Write ``name=value``, replacing an existing ``name`` line."""
33
+ if not _NAME.fullmatch(name):
34
+ raise ValueError(f"invalid credential name: {name!r}")
35
+ if "\n" in value or "\r" in value:
36
+ raise ValueError("a credential value cannot span lines")
37
+ path = credentials_path(home)
38
+ path.parent.mkdir(parents=True, exist_ok=True)
39
+ kept = [line for line in _read_lines(path) if _line_key(line) != name]
40
+ _write_private(path, "\n".join([*kept, f"{name}={value}"]) + "\n")
41
+
42
+
43
+ def load_credentials(
44
+ home: Path, environ: MutableMapping[str, str] = os.environ
45
+ ) -> list[str]:
46
+ """Export saved keys not already set; return the names set, not values."""
47
+ known = known_credential_names()
48
+ loaded = []
49
+ for line in _read_lines(credentials_path(home)):
50
+ name = _line_key(line)
51
+ if name in known and not environ.get(name):
52
+ environ[name] = line.partition("=")[2].strip()
53
+ loaded.append(name)
54
+ return loaded
55
+
56
+
57
+ def _read_lines(path: Path) -> list[str]:
58
+ try:
59
+ text = path.read_text(encoding="utf-8")
60
+ except FileNotFoundError:
61
+ return []
62
+ return [line for line in text.splitlines() if _line_key(line) is not None]
63
+
64
+
65
+ def _line_key(line: str) -> str | None:
66
+ """The key of a ``KEY=VALUE`` line; None for comments and blanks."""
67
+ stripped = line.strip()
68
+ if not stripped or stripped.startswith("#") or "=" not in stripped:
69
+ return None
70
+ return stripped.partition("=")[0].strip()
71
+
72
+
73
+ def _write_private(path: Path, text: str) -> None:
74
+ """Create the file as 0600 before any secret reaches it."""
75
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, _FILE_MODE)
76
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
77
+ os.fchmod(handle.fileno(), _FILE_MODE)
78
+ handle.write(text)
@@ -0,0 +1,23 @@
1
+ # k0ntrol defaults. Override in ~/.k0ntrol/config.yaml, then .k0-mem/config.yaml.
2
+ threshold_lines: 350
3
+ test_cmd: "pytest -q" # full suite, never only the new tests
4
+ gates: []
5
+ max_attempts: 2
6
+ test_timeout: 600
7
+ max_questions: 25
8
+ max_round_questions: 7
9
+ ticket_size: small
10
+ # search: # web search for PLANNER and RESEARCHER
11
+ # provider: brave # k0's web_search backend (BRAVE_SEARCH_API_KEY)
12
+ # native: false # true: agents on openai or anthropic use that provider's own
13
+ # # web search instead, billed per search on top of tokens
14
+ # OpenAI is the default provider: the one the 0.1.0 release check verified live.
15
+ agents:
16
+ planner: {provider: openai, model: gpt-6.1-terra, effort: high, model_calls: 25}
17
+ researcher: {provider: openai, model: gpt-6.1-terra, effort: high, model_calls: 40}
18
+ implementer: {provider: openai, model: gpt-6-luna, effort: medium, model_calls: 100}
19
+ reviewer: {provider: openai, model: gpt-6.1-terra, effort: high, model_calls: 25}
20
+ chatty: {provider: openai, model: gpt-6-luna, model_calls: 15}
21
+ helpers:
22
+ bulk_read: {provider: openai, model: gpt-6-luna}
23
+ reflect: {provider: openai, model: gpt-6-luna}