wells-agent 0.3.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 (86) hide show
  1. wells/AGENT.md +111 -0
  2. wells/__init__.py +25 -0
  3. wells/__main__.py +10 -0
  4. wells/_gitutils.py +63 -0
  5. wells/acp_server.py +390 -0
  6. wells/agents/__init__.py +0 -0
  7. wells/agents/architect.py +58 -0
  8. wells/agents/coder.py +253 -0
  9. wells/agents/planner.py +115 -0
  10. wells/agents/reviewer.py +113 -0
  11. wells/agents/tester.py +170 -0
  12. wells/background.py +668 -0
  13. wells/browser.py +435 -0
  14. wells/builtin_skills/benchmark-before-claiming/SKILL.md +16 -0
  15. wells/builtin_skills/dependency-audit/SKILL.md +23 -0
  16. wells/builtin_skills/incremental-refactor/SKILL.md +16 -0
  17. wells/builtin_skills/project-recon/SKILL.md +18 -0
  18. wells/builtin_skills/safe-migration/SKILL.md +17 -0
  19. wells/builtin_skills/verify-external-api/SKILL.md +15 -0
  20. wells/chat.py +196 -0
  21. wells/checkers.py +223 -0
  22. wells/cli.py +2789 -0
  23. wells/codeact.py +234 -0
  24. wells/codemode.py +243 -0
  25. wells/commands.py +103 -0
  26. wells/compress.py +92 -0
  27. wells/config.py +627 -0
  28. wells/context.py +128 -0
  29. wells/control.py +291 -0
  30. wells/embeddings.py +641 -0
  31. wells/evolve/__init__.py +65 -0
  32. wells/evolve/autoloop.py +280 -0
  33. wells/evolve/corpus.py +571 -0
  34. wells/evolve/mutate.py +526 -0
  35. wells/evolve/runner.py +799 -0
  36. wells/evolve/schema.py +168 -0
  37. wells/executor.py +3008 -0
  38. wells/finisher.py +232 -0
  39. wells/fleet.py +357 -0
  40. wells/gitops.py +375 -0
  41. wells/graph.py +167 -0
  42. wells/hooks.py +215 -0
  43. wells/index_tools.py +560 -0
  44. wells/index_watcher.py +164 -0
  45. wells/logger.py +107 -0
  46. wells/logo.py +24 -0
  47. wells/main.py +1702 -0
  48. wells/mcp_client.py +448 -0
  49. wells/mcp_server.py +826 -0
  50. wells/memory.py +296 -0
  51. wells/memory_bridge.py +195 -0
  52. wells/notify.py +142 -0
  53. wells/personas.py +454 -0
  54. wells/pricing.py +109 -0
  55. wells/principles.py +117 -0
  56. wells/providers.py +462 -0
  57. wells/recovery_hints.py +121 -0
  58. wells/reflections.py +552 -0
  59. wells/repomap.py +256 -0
  60. wells/rules.py +546 -0
  61. wells/runtime.py +86 -0
  62. wells/safety.py +244 -0
  63. wells/sandbox.py +235 -0
  64. wells/schedule.py +362 -0
  65. wells/sessions.py +210 -0
  66. wells/settings.py +845 -0
  67. wells/setup.py +322 -0
  68. wells/skill_authoring.py +479 -0
  69. wells/skills.py +537 -0
  70. wells/spend_guard.py +113 -0
  71. wells/state.py +60 -0
  72. wells/subagents.py +251 -0
  73. wells/summarize.py +89 -0
  74. wells/todo.py +118 -0
  75. wells/tokens.py +277 -0
  76. wells/tools.py +1248 -0
  77. wells/traces.py +465 -0
  78. wells/tui.py +4366 -0
  79. wells/user_memory.py +303 -0
  80. wells/vision.py +164 -0
  81. wells/web.py +249 -0
  82. wells/worktree.py +245 -0
  83. wells_agent-0.3.0.dist-info/METADATA +1776 -0
  84. wells_agent-0.3.0.dist-info/RECORD +86 -0
  85. wells_agent-0.3.0.dist-info/WHEEL +4 -0
  86. wells_agent-0.3.0.dist-info/entry_points.txt +4 -0
wells/AGENT.md ADDED
@@ -0,0 +1,111 @@
1
+ # AGENT.md
2
+
3
+ > A practical set of operating principles for AI coding agents, inspired
4
+ > by the public four-rule CLAUDE.md philosophy and expanded with modern
5
+ > agent engineering practices. This is **not** an official Karpathy
6
+ > document, but a community-informed synthesis.
7
+
8
+ ## 1. Think Before Coding
9
+
10
+ - State assumptions before implementation.
11
+ - Surface tradeoffs and constraints.
12
+ - Ask clarifying questions instead of guessing.
13
+ - Recommend a simpler approach when appropriate.
14
+
15
+ ## 2. Simplicity First
16
+
17
+ - Write the minimum code necessary.
18
+ - Avoid speculative abstractions.
19
+ - Do not future-proof unless requested.
20
+ - Prefer readability over cleverness.
21
+
22
+ ## 3. Surgical Changes
23
+
24
+ - Change only what the task requires.
25
+ - Avoid unrelated refactors or cleanup.
26
+ - Match the project's existing style and architecture.
27
+
28
+ ## 4. Goal-Driven Execution
29
+
30
+ - Define success before writing code.
31
+ - Verify that the requested outcome is achieved.
32
+ - Stop when the goal is complete.
33
+
34
+ ## 5. Deterministic First
35
+
36
+ Use traditional code whenever logic can be deterministic.
37
+
38
+ LLMs are best for: - Drafting - Summarization - Classification -
39
+ Extraction - Reasoning over unstructured information
40
+
41
+ Use deterministic code for: - Business rules - Routing - Validation -
42
+ Retries - Persistence - Authorization
43
+
44
+ ## 6. Budget Everything
45
+
46
+ Every agent has limits. - Maximum tokens - Maximum cost - Maximum
47
+ runtime - Maximum retries
48
+
49
+ Fail explicitly instead of running indefinitely.
50
+
51
+ ## 7. Verify Before Trust
52
+
53
+ Treat every model output as a hypothesis.
54
+
55
+ Before making impactful changes: - Run tests - Validate outputs -
56
+ Confirm assumptions - Prefer automated verification
57
+
58
+ ## 8. Fail Loud
59
+
60
+ Never silently continue after uncertainty.
61
+
62
+ If confidence is low: - Explain why - Present options - Ask for
63
+ clarification
64
+
65
+ Avoid confident but incorrect behavior.
66
+
67
+ ## 9. Isolate Side Effects
68
+
69
+ Separate reasoning from execution.
70
+
71
+ The harness gates high-risk side effects via its safety system (the
72
+ `HARNESS_SAFETY` setting). When the harness permits an action — including
73
+ deployments, publishing, and external API calls — the agent **must execute
74
+ it** using the available tools. Do not refuse or simulate an action that the
75
+ harness has allowed; that decision already happened upstream.
76
+
77
+ The harness is responsible for: - Blocking destructive commands - Requiring
78
+ approval for sensitive operations - Constraining the workspace
79
+
80
+ The agent is responsible for: - Reading the right files before acting -
81
+ Running commands and observing the actual output - Reporting results
82
+ accurately, including failures
83
+
84
+ ## 10. Check Before Declaring Done
85
+
86
+ Before finishing, confirm: - The request was fully addressed. - No
87
+ unnecessary complexity was introduced. - Only relevant code was
88
+ changed. - The solution was verified. - Remaining assumptions are
89
+ documented.
90
+
91
+ ## 11. Evidence Over Confidence
92
+
93
+ Always distinguish between:
94
+
95
+ - **Observed** --- verified directly.
96
+ - **Inferred** --- logically concluded.
97
+ - **Hypothesized** --- plausible but unverified.
98
+ - **Recommended** --- suggested next action.
99
+
100
+ Never claim to have: - Run tests you did not run. - Read files you did
101
+ not inspect. - Verified behavior you did not verify. - Reproduced bugs
102
+ you did not reproduce.
103
+
104
+ Trust is built through evidence, not confidence.
105
+
106
+ ------------------------------------------------------------------------
107
+
108
+ **Guiding Principle**
109
+
110
+ > Slow down. Think clearly. Change as little as necessary. Verify
111
+ > everything. Be explicit about uncertainty.
wells/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """Wells — model-agnostic agentic coding."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version as _pkg_version
4
+
5
+
6
+ def _detect_version() -> str:
7
+ """Single source of truth: the installed distribution metadata.
8
+
9
+ pyproject.toml's ``version`` is the only place a release number is
10
+ written. Reading it back here keeps ``wells --version``, the MCP server
11
+ handshake, and the PyPI artifact from ever disagreeing (they did: three
12
+ hardcoded copies drifted to 0.2.0 while the package was 0.3.0).
13
+
14
+ A frozen PyInstaller bundle has metadata too (the dist-info is collected
15
+ as a data file), but fall back to a marker rather than crashing if the
16
+ environment is exotic — a wrong-but-present version string is never worth
17
+ a failed startup.
18
+ """
19
+ try:
20
+ return _pkg_version("wells-agent")
21
+ except PackageNotFoundError:
22
+ return "0.0.0+unknown"
23
+
24
+
25
+ __version__ = _detect_version()
wells/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Entry point for ``python -m wells`` — starts the MCP server.
2
+
3
+ This makes ``python -m wells`` behave identically to
4
+ ``wells-mcp``, which is convenient for MCP client configurations
5
+ that accept a ``python -m`` module path.
6
+ """
7
+
8
+ from wells.mcp_server import main
9
+
10
+ main()
wells/_gitutils.py ADDED
@@ -0,0 +1,63 @@
1
+ """Shared git plumbing for internal harness operations.
2
+
3
+ Three modules (fleet, worktree, gitops) each had their own ``_git`` /
4
+ ``is_git_repo`` / ``current_branch`` — three near-identical copies. This
5
+ module is the canonical home; the others re-export from here so external
6
+ callers (and tests that monkey-patch ``fleet._git`` etc.) keep working.
7
+
8
+ All operations use ``git`` directly via argv (no shell) so they bypass the
9
+ agent safety gate — these are internal harness operations, mirroring the
10
+ pattern in :mod:`gitops` snapshot/restore.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import subprocess
16
+
17
+
18
+ def git(
19
+ cwd: str,
20
+ *args: str,
21
+ timeout: float = 120.0,
22
+ env_extra: dict | None = None,
23
+ ) -> tuple[bool, str]:
24
+ """Run ``git`` directly (argv, no shell) in ``cwd``. Returns (ok, output).
25
+
26
+ ``output`` is stdout + stderr concatenated and stripped. On exception,
27
+ returns ``(False, "<ExceptionType>: <message>")`` so callers get a
28
+ useful error string instead of just the exception message.
29
+
30
+ ``env_extra`` is merged over ``os.environ`` (used by gitops' temp-index
31
+ snapshot trick, which sets ``GIT_INDEX_FILE``).
32
+ """
33
+ import os
34
+
35
+ env = {**os.environ, **(env_extra or {})}
36
+ try:
37
+ proc = subprocess.run(
38
+ ["git", *args], cwd=cwd, capture_output=True, text=True,
39
+ timeout=timeout, env=env,
40
+ # Explicit UTF-8: on Windows text=True alone decodes with the
41
+ # locale codec (cp1252), which crashes the reader thread on any
42
+ # non-ASCII commit subject (em-dashes, CJK…) — git outputs UTF-8.
43
+ encoding="utf-8", errors="replace",
44
+ )
45
+ except Exception as e:
46
+ return False, f"{type(e).__name__}: {e}"
47
+ out = (proc.stdout or "") + (proc.stderr or "")
48
+ return proc.returncode == 0, out.strip()
49
+
50
+
51
+ def is_git_repo(path: str) -> bool:
52
+ ok, out = git(path, "rev-parse", "--is-inside-work-tree")
53
+ return ok and "true" in out.lower()
54
+
55
+
56
+ def current_branch(path: str) -> str:
57
+ ok, out = git(path, "rev-parse", "--abbrev-ref", "HEAD")
58
+ return out.strip() if ok else ""
59
+
60
+
61
+ def head_sha(path: str) -> str:
62
+ ok, out = git(path, "rev-parse", "HEAD")
63
+ return out.strip() if ok else ""
wells/acp_server.py ADDED
@@ -0,0 +1,390 @@
1
+ """Agent Client Protocol (ACP) server for the Wells coding-agent harness.
2
+
3
+ Lets editor integrations (Zed, JetBrains, anything speaking ACP) drive Wells
4
+ over stdio JSON-RPC 2.0 with LSP-style ``Content-Length`` framing.
5
+
6
+ Start the server:
7
+
8
+ wells-acp # console script (wired by the parent session)
9
+ python -m wells.acp_server
10
+
11
+ Protocol surface (agentclientprotocol.com, protocol version 1):
12
+
13
+ initialize -> agent capabilities
14
+ initialize/:id -> notification, ignored
15
+ session/new -> Session (primary/default mode)
16
+ session/prompt -> runs the task, streams session/update
17
+ notifications, replies with a stop reason
18
+ session/cancel -> cooperatively cancels the running prompt
19
+ fs/read_text_file -> unsupported (returns a JSON-RPC error)
20
+
21
+ The ACP layer is deliberately thin: the prompt path delegates to
22
+ :func:`wells.main._run_goal` — the exact function behind ``wells -p
23
+ --output-format json`` — so editors get the same pipeline, hooks, session
24
+ persistence, and JSON outcome the headless CLI produces.
25
+
26
+ Only the standard library is used (json, sys, threading, contextlib).
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import contextlib
32
+ import io
33
+ import json
34
+ import sys
35
+ import threading
36
+ import uuid
37
+ from typing import Any, BinaryIO, Callable, TextIO
38
+
39
+ PROTOCOL_VERSION = 1
40
+
41
+ # JSON-RPC error codes
42
+ PARSE_ERROR = -32700
43
+ INVALID_REQUEST = -32600
44
+ METHOD_NOT_FOUND = -32601
45
+ INTERNAL_ERROR = -32603
46
+
47
+ # Header separator for LSP-style framing (always \r\n per the framing spec).
48
+ HEADER_SEP = b"\r\n\r\n"
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Framing
53
+ # ---------------------------------------------------------------------------
54
+
55
+
56
+ def read_message(stream: BinaryIO) -> dict | None:
57
+ """Read one Content-Length-framed JSON message from a binary stream.
58
+
59
+ Returns None on EOF. Raises ValueError on a malformed frame.
60
+ """
61
+ header = b""
62
+ while HEADER_SEP not in header:
63
+ chunk = stream.read(1)
64
+ if not chunk:
65
+ return None
66
+ header += chunk
67
+ # Sanity cap to avoid unbounded memory on garbage input.
68
+ if len(header) > 64 * 1024:
69
+ raise ValueError("frame header too large")
70
+ header_text = header.decode("ascii", errors="replace")
71
+ content_length = None
72
+ for line in header_text.split("\r\n"):
73
+ if ":" not in line:
74
+ continue
75
+ name, _, value = line.partition(":")
76
+ if name.strip().lower() == "content-length":
77
+ content_length = int(value.strip())
78
+ if content_length is None:
79
+ raise ValueError("missing Content-Length header")
80
+ body = stream.read(content_length)
81
+ if len(body) < content_length:
82
+ raise ValueError("truncated frame body")
83
+ return json.loads(body.decode("utf-8"))
84
+
85
+
86
+ def write_message(stream: BinaryIO, message: dict) -> None:
87
+ """Write one Content-Length-framed JSON message to a binary stream."""
88
+ data = json.dumps(message, ensure_ascii=False).encode("utf-8")
89
+ frame = f"Content-Length: {len(data)}\r\n\r\n".encode("ascii") + data
90
+ stream.write(frame)
91
+ stream.flush()
92
+
93
+
94
+ # ---------------------------------------------------------------------------
95
+ # Task runner (the seam tests monkeypatch)
96
+ # ---------------------------------------------------------------------------
97
+
98
+
99
+ def run_task(goal: str, cwd: str | None = None) -> dict:
100
+ """Run one Wells task via the headless one-shot code path.
101
+
102
+ Delegates to :func:`wells.main._run_goal` with ``output_format="json"``
103
+ (the ``wells -p --output-format json`` plumbing) and captures the single
104
+ JSON payload it prints to stdout. ``_run_goal`` signals completion via
105
+ ``sys.exit``; that is intercepted here so the server loop keeps running.
106
+ """
107
+ import contextlib
108
+ import io as _io
109
+
110
+ from wells import config
111
+ from wells.main import _run_goal
112
+
113
+ previous_root = config.WORKSPACE_ROOT
114
+ if cwd:
115
+ config.WORKSPACE_ROOT = cwd
116
+ buffer = _io.StringIO()
117
+ try:
118
+ with contextlib.redirect_stdout(buffer):
119
+ _run_goal(goal, output_format="json")
120
+ except SystemExit:
121
+ pass
122
+ finally:
123
+ config.WORKSPACE_ROOT = previous_root
124
+
125
+ text = buffer.getvalue().strip()
126
+ if not text:
127
+ return {"status": "error", "error": "no output from task runner"}
128
+ try:
129
+ # Exactly one JSON object is expected; tolerate stray lines.
130
+ for line in reversed(text.splitlines()):
131
+ line = line.strip()
132
+ if line.startswith("{"):
133
+ return json.loads(line)
134
+ return json.loads(text.splitlines()[-1])
135
+ except json.JSONDecodeError:
136
+ return {"status": "error", "error": f"unparseable output: {text[:400]}"}
137
+
138
+
139
+ # ---------------------------------------------------------------------------
140
+ # Server
141
+ # ---------------------------------------------------------------------------
142
+
143
+
144
+ class AcpServer:
145
+ """ACP JSON-RPC dispatcher.
146
+
147
+ ``send`` is called with each outgoing message (responses and
148
+ notifications); the stdio loop wires it to framed writes, tests wire it
149
+ to an in-memory list. Thread-safe: prompt handling runs on a worker
150
+ thread so the read loop stays live for ``session/cancel``.
151
+ """
152
+
153
+ def __init__(self, send: Callable[[dict], None] | None = None,
154
+ task_runner: Callable[[str, str | None], dict] = run_task):
155
+ self._send_fn = send
156
+ self._task_runner = task_runner
157
+ self._lock = threading.Lock()
158
+ # sessionId -> {"thread": Thread, "done": Event, "cancelled": bool}
159
+ self._running: dict[str, dict] = {}
160
+ self.sessions: dict[str, str] = {} # sessionId -> cwd
161
+ self._update_counter = 0
162
+
163
+ # -- outgoing ----------------------------------------------------------
164
+
165
+ def _send(self, message: dict) -> None:
166
+ if self._send_fn is not None:
167
+ with self._lock:
168
+ self._send_fn(message)
169
+
170
+ def _notify(self, method: str, params: dict) -> None:
171
+ self._send({"jsonrpc": "2.0", "method": method, "params": params})
172
+
173
+ def _respond(self, request_id: Any, result: dict) -> None:
174
+ self._send({"jsonrpc": "2.0", "id": request_id, "result": result})
175
+
176
+ def _respond_error(self, request_id: Any, code: int, message: str,
177
+ data: Any = None) -> None:
178
+ error: dict[str, Any] = {"code": code, "message": message}
179
+ if data is not None:
180
+ error["data"] = data
181
+ self._send({"jsonrpc": "2.0", "id": request_id, "error": error})
182
+
183
+ def _session_update(self, session_id: str, update: dict) -> None:
184
+ with self._lock:
185
+ self._update_counter += 1
186
+ update_id = self._update_counter
187
+ self._notify("session/update", {
188
+ "sessionId": session_id,
189
+ "update": {"updateId": update_id, **update},
190
+ })
191
+
192
+ # -- incoming ----------------------------------------------------------
193
+
194
+ def handle_message(self, message: dict) -> None:
195
+ """Process one decoded JSON-RPC message (request or notification)."""
196
+ if not isinstance(message, dict) or message.get("jsonrpc") != "2.0":
197
+ self._respond_error(None, INVALID_REQUEST, "not a JSON-RPC 2.0 message")
198
+ return
199
+ method = message.get("method")
200
+ request_id = message.get("id") # None => notification
201
+ params = message.get("params") or {}
202
+
203
+ if request_id is None:
204
+ # Notifications: initialize/:id is the only one we know; unknown
205
+ # notifications are silently dropped per JSON-RPC.
206
+ return
207
+
208
+ try:
209
+ handler = {
210
+ "initialize": self._on_initialize,
211
+ "session/new": self._on_session_new,
212
+ "session/prompt": self._on_session_prompt,
213
+ "session/cancel": self._on_session_cancel,
214
+ "fs/read_text_file": self._on_read_text_file,
215
+ }.get(method)
216
+ if handler is None:
217
+ self._respond_error(request_id, METHOD_NOT_FOUND,
218
+ f"method not found: {method}")
219
+ return
220
+ handler(request_id, params)
221
+ except Exception as exc: # never crash the loop
222
+ self._respond_error(request_id, INTERNAL_ERROR,
223
+ f"{type(exc).__name__}: {exc}")
224
+
225
+ # -- method handlers ---------------------------------------------------
226
+
227
+ def _on_initialize(self, request_id: Any, params: dict) -> None:
228
+ self._respond(request_id, {
229
+ "protocolVersion": PROTOCOL_VERSION,
230
+ "agentCapabilities": {"loadSession": False},
231
+ "authMethods": [],
232
+ })
233
+
234
+ def _on_session_new(self, request_id: Any, params: dict) -> None:
235
+ cwd = params.get("cwd") or ""
236
+ session_id = str(uuid.uuid4())
237
+ self.sessions[session_id] = cwd
238
+ self._respond(request_id, {
239
+ "sessionId": session_id,
240
+ "mode": {"kind": "primary", "name": "default"},
241
+ "mcpServers": [],
242
+ })
243
+
244
+ def _on_session_prompt(self, request_id: Any, params: dict) -> None:
245
+ session_id = params.get("sessionId") or ""
246
+ if session_id not in self.sessions:
247
+ self._respond_error(request_id, INVALID_REQUEST,
248
+ f"unknown session: {session_id!r}")
249
+ return
250
+ prompt = params.get("prompt") or {}
251
+ goal = self._prompt_text(prompt)
252
+ cwd = self.sessions.get(session_id) or None
253
+
254
+ entry: dict = {"done": threading.Event(), "cancelled": False}
255
+ self._running[session_id] = entry
256
+
257
+ def _work() -> None:
258
+ from wells.control import CONTROL
259
+
260
+ try:
261
+ CONTROL.reset()
262
+ self._session_update(session_id, {"sessionUpdate": "turn",
263
+ "state": "start"})
264
+ try:
265
+ result = self._task_runner(goal, cwd)
266
+ except SystemExit:
267
+ result = {"status": "error", "error": "task runner exited"}
268
+ if CONTROL.cancelled() or entry["cancelled"]:
269
+ entry["cancelled"] = True
270
+ text = self._result_text(result)
271
+ if text:
272
+ self._session_update(session_id, {
273
+ "sessionUpdate": "agent_message",
274
+ "content": [{"type": "text", "text": text}],
275
+ })
276
+ stop_reason = "cancelled" if entry["cancelled"] else "end_turn"
277
+ self._session_update(session_id, {"sessionUpdate": "turn",
278
+ "state": "complete",
279
+ "stopReason": stop_reason})
280
+ self._respond(request_id, {"stopReason": stop_reason})
281
+ except Exception as exc:
282
+ self._session_update(session_id, {"sessionUpdate": "turn",
283
+ "state": "complete",
284
+ "stopReason": "end_turn"})
285
+ self._respond_error(request_id, INTERNAL_ERROR,
286
+ f"{type(exc).__name__}: {exc}")
287
+ finally:
288
+ entry["done"].set()
289
+ with self._lock:
290
+ self._running.pop(session_id, None)
291
+
292
+ threading.Thread(target=_work, name=f"acp-prompt-{session_id[:8]}",
293
+ daemon=True).start()
294
+
295
+ def _on_session_cancel(self, request_id: Any, params: dict) -> None:
296
+ session_id = params.get("sessionId") or ""
297
+ entry = self._running.get(session_id)
298
+ if entry is not None:
299
+ entry["cancelled"] = True
300
+ try:
301
+ from wells.control import CONTROL
302
+
303
+ CONTROL.cancel()
304
+ except Exception:
305
+ pass # control bus unavailable; entry flag still stops the turn
306
+ self._respond(request_id, {})
307
+
308
+ def _on_read_text_file(self, request_id: Any, params: dict) -> None:
309
+ self._respond_error(request_id, METHOD_NOT_FOUND,
310
+ "fs/read_text_file is not supported")
311
+
312
+ # -- helpers -----------------------------------------------------------
313
+
314
+ @staticmethod
315
+ def _prompt_text(prompt: dict) -> str:
316
+ """Flatten an ACP Prompt (content blocks) into plain text."""
317
+ blocks = prompt.get("content") or []
318
+ parts = []
319
+ for block in blocks:
320
+ if isinstance(block, dict) and block.get("type") == "text":
321
+ parts.append(block.get("text", ""))
322
+ return "\n".join(p for p in parts if p).strip()
323
+
324
+ @staticmethod
325
+ def _result_text(result: dict) -> str:
326
+ """Human-facing text for the final agent message of a turn."""
327
+ if not isinstance(result, dict):
328
+ return str(result)
329
+ parts = []
330
+ for key in ("summary", "review_result", "git_summary"):
331
+ value = (result.get(key) or "").strip() if isinstance(result.get(key), str) else ""
332
+ if value:
333
+ parts.append(value)
334
+ if result.get("status") == "error" and result.get("error"):
335
+ parts.append(f"error: {result['error']}")
336
+ return "\n\n".join(parts)
337
+
338
+ def wait_for_prompts(self, timeout: float = 10.0) -> None:
339
+ """Block until every in-flight prompt worker finishes (test helper)."""
340
+ import time as _time
341
+
342
+ end = _time.monotonic() + timeout
343
+ while _time.monotonic() < end:
344
+ with self._lock:
345
+ entries = [e["done"] for e in self._running.values()]
346
+ if not entries or all(e.is_set() for e in entries):
347
+ return
348
+ _time.sleep(0.01)
349
+
350
+
351
+ # ---------------------------------------------------------------------------
352
+ # Stdio entry point
353
+ # ---------------------------------------------------------------------------
354
+
355
+
356
+ def serve(stdin: BinaryIO | None = None, stdout: BinaryIO | None = None) -> None:
357
+ """Run the ACP server loop over Content-Length-framed stdio."""
358
+ in_stream = stdin if stdin is not None else sys.stdin.buffer
359
+ out_stream = stdout if stdout is not None else sys.stdout.buffer
360
+
361
+ def _write(message: dict) -> None:
362
+ try:
363
+ write_message(out_stream, message)
364
+ except (OSError, ValueError):
365
+ pass # client went away; loop exits on next read
366
+
367
+ server = AcpServer(send=_write)
368
+ while True:
369
+ try:
370
+ message = read_message(in_stream)
371
+ except (ValueError, json.JSONDecodeError, UnicodeDecodeError) as exc:
372
+ server._respond_error(None, PARSE_ERROR, f"bad frame: {exc}")
373
+ continue
374
+ except OSError:
375
+ break
376
+ if message is None:
377
+ break # EOF — client closed the pipe
378
+ try:
379
+ server.handle_message(message)
380
+ except Exception:
381
+ # handle_message already guards itself; this is belt-and-braces.
382
+ continue
383
+
384
+
385
+ def main() -> None:
386
+ serve()
387
+
388
+
389
+ if __name__ == "__main__":
390
+ main()
File without changes
@@ -0,0 +1,58 @@
1
+ """Architect: validates and extends the planner's concrete plan.
2
+
3
+ For simple tasks (button, rename, small fix) the planner's output is already
4
+ sufficient — the architect just passes it through with minor additions.
5
+ For complex tasks (new module, API change, schema migration) the architect adds
6
+ design guidance: patterns, interfaces, migration strategy.
7
+
8
+ The architect does NOT use tools — it reasons over the planner's already-grounded
9
+ output. Adding another agentic loop here would be redundant since the planner
10
+ already read the relevant code.
11
+ """
12
+
13
+ from wells.runtime import run_step
14
+
15
+ _ARCHITECT_SYSTEM = """\
16
+ You are a senior software architect reviewing a concrete implementation plan.
17
+ The plan was produced by an agent that already read the codebase.
18
+
19
+ Your job:
20
+ 1. Validate the plan is technically correct and complete.
21
+ 2. For complex changes (new modules, APIs, data models, migrations): add a brief
22
+ design note covering patterns, interfaces, or migration strategy.
23
+ 3. For simple changes (add button, rename, small fix): just confirm the plan is
24
+ correct and add any single non-obvious gotcha you see.
25
+ 4. Do NOT pad the output. If the plan is already correct and complete, say so
26
+ in one sentence and stop.
27
+
28
+ Output format:
29
+
30
+ ## Design validation
31
+ APPROVED / NEEDS REVISION + one-sentence reason.
32
+
33
+ ## Design notes (omit section if simple task)
34
+ Brief additions for complex tasks only.
35
+
36
+ ## Confirmed plan
37
+ Repeat the planner's Implementation steps verbatim if approved, or corrected
38
+ steps if you revised them.
39
+ """
40
+
41
+
42
+ def architect(state: dict) -> dict:
43
+ from wells.control import CONTROL
44
+ CONTROL.set_activity("architect · validating plan")
45
+ print("[architect] validating plan ...")
46
+
47
+ chunks = {
48
+ "user_request": f"Goal:\n{state.get('goal', '')}",
49
+ "retrieved_code": f"Planner's concrete implementation plan:\n{state.get('development_plan', '')}",
50
+ }
51
+ architecture, _ = run_step(
52
+ step="architect",
53
+ task_type="architecture",
54
+ system=_ARCHITECT_SYSTEM,
55
+ chunks=chunks,
56
+ workspace=state.get("workspace_root"),
57
+ )
58
+ return {"architecture": architecture}