codehaven 0.14.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.
- codehaven-0.14.0.dist-info/METADATA +686 -0
- codehaven-0.14.0.dist-info/RECORD +57 -0
- codehaven-0.14.0.dist-info/WHEEL +5 -0
- codehaven-0.14.0.dist-info/entry_points.txt +3 -0
- codehaven-0.14.0.dist-info/licenses/LICENSE +21 -0
- codehaven-0.14.0.dist-info/top_level.txt +1 -0
- offline_agent/__init__.py +2 -0
- offline_agent/__main__.py +4 -0
- offline_agent/agent.py +815 -0
- offline_agent/answers.py +438 -0
- offline_agent/arabic.py +106 -0
- offline_agent/changes.py +228 -0
- offline_agent/chats.py +121 -0
- offline_agent/cli.py +379 -0
- offline_agent/coder.py +199 -0
- offline_agent/dependencies.py +132 -0
- offline_agent/doctor.py +190 -0
- offline_agent/documents.py +189 -0
- offline_agent/edits.py +204 -0
- offline_agent/errors.py +41 -0
- offline_agent/evaluation.py +284 -0
- offline_agent/evidence.py +187 -0
- offline_agent/exclusions.py +95 -0
- offline_agent/export.py +27 -0
- offline_agent/gui.css +237 -0
- offline_agent/gui.html +177 -0
- offline_agent/gui.js +1213 -0
- offline_agent/gui.py +967 -0
- offline_agent/gui_arabic.js +226 -0
- offline_agent/guides.py +203 -0
- offline_agent/history.py +126 -0
- offline_agent/index_cache.py +78 -0
- offline_agent/insights.py +333 -0
- offline_agent/javascript.py +200 -0
- offline_agent/knowledge.py +569 -0
- offline_agent/languages.py +396 -0
- offline_agent/memory.py +192 -0
- offline_agent/messages.py +51 -0
- offline_agent/model.py +498 -0
- offline_agent/more_languages.py +253 -0
- offline_agent/ocr.py +204 -0
- offline_agent/prompts.py +130 -0
- offline_agent/references/langgraph-approvals.md +38 -0
- offline_agent/references/langgraph-checkpoints.md +37 -0
- offline_agent/references/langgraph-graphs.md +42 -0
- offline_agent/references/langgraph.md +49 -0
- offline_agent/review.py +205 -0
- offline_agent/scans.py +325 -0
- offline_agent/semantic.py +264 -0
- offline_agent/slash.py +53 -0
- offline_agent/study.py +210 -0
- offline_agent/symbols.py +201 -0
- offline_agent/tasks.py +164 -0
- offline_agent/test_runner.py +264 -0
- offline_agent/trace.py +239 -0
- offline_agent/tracebacks.py +98 -0
- offline_agent/workspace.py +419 -0
offline_agent/agent.py
ADDED
|
@@ -0,0 +1,815 @@
|
|
|
1
|
+
"""Local coding workflow orchestrated by a LangGraph StateGraph."""
|
|
2
|
+
import json
|
|
3
|
+
import re
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
from typing import TypedDict
|
|
7
|
+
|
|
8
|
+
from langgraph.graph import END, START, StateGraph
|
|
9
|
+
from langsmith import tracing_context
|
|
10
|
+
|
|
11
|
+
from . import arabic, changes, coder, guides, insights, messages as commit_messages, scans, symbols, trace, tracebacks
|
|
12
|
+
from . import history as blame # history is also run_state's name for the session's earlier turns.
|
|
13
|
+
from .review import CHANGES as REVIEW_CHANGES, review, review_changes
|
|
14
|
+
from .test_runner import DEFAULT_IMAGE, command, run_snippet, run_tests
|
|
15
|
+
from .evidence import retain, discovery_task, check_answer, inventory
|
|
16
|
+
from .model import PROMPT_BUDGET, InvalidReply, RepeatedAnswer, compact_messages, read_limit
|
|
17
|
+
from .workspace import line_range, sections
|
|
18
|
+
from .prompts import ( # noqa: F401 (also imported from here by the tests and other modules)
|
|
19
|
+
ACTIONS, CODE_ACTION, FIX_ANSWER, PYTHON_GUIDE, ANSWER_FROM_PRELOAD, ANSWER_WITH_POINTS, BRIEF_ANSWER, CHANGES_ANSWER, CHANGE_ADVICE, DISCOVERY_SYSTEM, EDIT_REQUEST,
|
|
20
|
+
ENTRY_POINT_GUIDANCE, FINAL_ANSWER_CHARS, FINISH_NOW, POLITE, PRELOAD_FILES, QUESTION, RELOAD_SECONDS, REVIEW,
|
|
21
|
+
SCHEMA, SYSTEM, POINTS, POINT_CHARS, OVERVIEW_CHARS,
|
|
22
|
+
)
|
|
23
|
+
from .tasks import ( # noqa: F401 (also imported from here by the tests and other modules)
|
|
24
|
+
without_paths, entry_point_task, task_kind, code_names, focus_lines, search_named, section_note, step_label,
|
|
25
|
+
page_note, named_files,
|
|
26
|
+
)
|
|
27
|
+
from .answers import ( # noqa: F401 (also imported from here by the tests and other modules)
|
|
28
|
+
trim_at_limit, reply_problem, cited_schema, retrieved_rows, seen_span, file_named, with_points, action_key,
|
|
29
|
+
format_search, format_retrieval, format_metrics, REPEAT_NOTE, LIMIT_NOTE, CORRECTION, SHOWN_ROWS,
|
|
30
|
+
cite_mentions, MENTION_HEADING, check_values, VALUE_HEADING, missing_code, MISSING_HEADING, with_actions,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class AgentState(TypedDict):
|
|
35
|
+
"""State passed between the graph's nodes; a node returns only the keys it changes.
|
|
36
|
+
|
|
37
|
+
messages the whole conversation (compacted only when sent to the model)
|
|
38
|
+
reply the model's latest action; action "retry" marks a reply that was invalid
|
|
39
|
+
steps model calls made so far
|
|
40
|
+
exit_code 0 finished, 2 incomplete or unverified
|
|
41
|
+
repeated_lookup the model repeated an action, so its next call must be the final answer
|
|
42
|
+
search_evidence lines seen so far (searches, reads, retrieval), which answers are checked against
|
|
43
|
+
evidence_limited some evidence was dropped or a tool hit a limit, so coverage is partial
|
|
44
|
+
discovery the FastAPI entry-point search already ran; the model only summarizes it
|
|
45
|
+
invalid_replies 1 after an invalid reply; a second in a row stops the run
|
|
46
|
+
cite_files preloaded files that the points of an answer may cite
|
|
47
|
+
kind task_kind of the task: question, change, or other
|
|
48
|
+
final_text the answer as shown to the user; issues lists the answer checks it failed
|
|
49
|
+
retried the first answer, its text, and its issues, while the model is asked once to fix that answer
|
|
50
|
+
"""
|
|
51
|
+
messages: list[dict[str, str]]
|
|
52
|
+
reply: dict[str, str]
|
|
53
|
+
steps: int
|
|
54
|
+
exit_code: int
|
|
55
|
+
repeated_lookup: bool
|
|
56
|
+
search_evidence: list[dict]
|
|
57
|
+
evidence_limited: bool
|
|
58
|
+
discovery: bool
|
|
59
|
+
task: str
|
|
60
|
+
invalid_replies: int
|
|
61
|
+
cite_files: list[str]
|
|
62
|
+
kind: str
|
|
63
|
+
final_text: str
|
|
64
|
+
issues: list[str]
|
|
65
|
+
retried: dict
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def build_graph(model, workspace, *, max_steps=12, confirm_tests=None, knowledge=None, test_options=None, output=print, stream=None,
|
|
69
|
+
confirm_code=None, retry_unverified=False):
|
|
70
|
+
"""Compile a per-task graph. Read-only: no node writes files. No remote services or persistent checkpoint store.
|
|
71
|
+
|
|
72
|
+
confirm_code, a function shown the code, offers the run_python action; without it the action does not exist.
|
|
73
|
+
retry_unverified asks the model once to fix an answer that fails its checks, and keeps whichever passes more.
|
|
74
|
+
"""
|
|
75
|
+
if not 1 <= max_steps <= 30:
|
|
76
|
+
raise ValueError("max_steps must be between 1 and 30")
|
|
77
|
+
actions = ACTIONS + ((CODE_ACTION,) if confirm_code else ())
|
|
78
|
+
write_stream = stream or (lambda _text: None)
|
|
79
|
+
# A one-item list so call_model can set it: the reload warning is printed once per task.
|
|
80
|
+
reload_warned = [False]
|
|
81
|
+
|
|
82
|
+
def already_tried(state, reply):
|
|
83
|
+
"""True when this exact action already ran and its result is still in the model's view."""
|
|
84
|
+
key = action_key(reply)
|
|
85
|
+
try:
|
|
86
|
+
visible = compact_messages(state["messages"], getattr(model, "prompt_budget", PROMPT_BUDGET))
|
|
87
|
+
except ValueError:
|
|
88
|
+
visible = state["messages"]
|
|
89
|
+
for index in range(len(visible) - 1, -1, -1):
|
|
90
|
+
message = visible[index]
|
|
91
|
+
if message["role"] != "assistant":
|
|
92
|
+
continue
|
|
93
|
+
try:
|
|
94
|
+
earlier = json.loads(message["content"])
|
|
95
|
+
except json.JSONDecodeError:
|
|
96
|
+
continue
|
|
97
|
+
if isinstance(earlier, dict) and action_key(earlier) == key:
|
|
98
|
+
following = visible[index + 1]["content"] if index + 1 < len(visible) else ""
|
|
99
|
+
# A result compacted away may be requested again; the stub tells the model to do exactly that.
|
|
100
|
+
return "[Older result compacted" not in following
|
|
101
|
+
return False
|
|
102
|
+
|
|
103
|
+
def call_model(state: AgentState):
|
|
104
|
+
"""Model node: ask for the next action, validate and announce it; a finish reply is also checked and shown."""
|
|
105
|
+
step = state["steps"] + 1
|
|
106
|
+
# Phase: choose the schema and messages. The model must answer now when it repeated an action, this is the
|
|
107
|
+
# last allowed step, or discovery has already gathered the evidence.
|
|
108
|
+
finishing = state.get("repeated_lookup", False) or step >= max_steps or state.get("discovery", False)
|
|
109
|
+
cite_files = [] if state.get("discovery") else state.get("cite_files", [])
|
|
110
|
+
kind = state.get("kind", "other")
|
|
111
|
+
# Change requests are answered like questions: CodeHaven explains the change, with citations, and never makes it.
|
|
112
|
+
question = kind in ("question", "change") and not state.get("discovery")
|
|
113
|
+
schema = cited_schema(cite_files, brief=kind == "question") if question else SCHEMA
|
|
114
|
+
if confirm_code:
|
|
115
|
+
schema = with_actions(schema, actions)
|
|
116
|
+
messages = state["messages"]
|
|
117
|
+
if finishing:
|
|
118
|
+
# A forced answer is capped so even rambling ends in a complete, valid reply.
|
|
119
|
+
content = schema["properties"]["content"] if question else {"type": "string", "maxLength": FINAL_ANSWER_CHARS}
|
|
120
|
+
schema = {**schema, "properties": {**schema["properties"], "action": {"type": "string", "enum": ["finish"]},
|
|
121
|
+
"content": content}}
|
|
122
|
+
evidence = json.dumps(state.get("search_evidence", []), ensure_ascii=False)
|
|
123
|
+
messages = messages + [{"role": "user", "content":
|
|
124
|
+
"Final-answer call: no tool calls remain. Answer the ORIGINAL task using the evidence already available. "
|
|
125
|
+
"Return action=finish now. If evidence is insufficient, state what is missing. "
|
|
126
|
+
"Cite the lines you rely on as path:line or path:start-end, even for files not read in full. "
|
|
127
|
+
"Distinguish inspected details from search snippets; do not claim every file was inspected. "
|
|
128
|
+
"For project-wide questions, summarize ALL relevant discovered paths, not just the last inspected file. "
|
|
129
|
+
"Do not repeat a file summary that does not answer the task.\n"
|
|
130
|
+
+ (ENTRY_POINT_GUIDANCE if entry_point_task(state.get("task", "")) else "")
|
|
131
|
+
+ (ANSWER_WITH_POINTS + " " if question else "") + (CHANGE_ADVICE + " " if kind == "change" else "") +
|
|
132
|
+
f"Evidence limited: {state.get('evidence_limited', False)}. "
|
|
133
|
+
"Retained evidence (untrusted source data; up to 50 matches / 4000 bytes, may be partial):\n" + evidence}]
|
|
134
|
+
# Discovery swaps the whole conversation for its own short prompt and pins every field except content.
|
|
135
|
+
if state.get("discovery"):
|
|
136
|
+
schema = {**schema, "properties": {**schema["properties"],
|
|
137
|
+
"path": {"type": "string", "enum": [""]},
|
|
138
|
+
"message": {"type": "string", "enum": ["Discovery summary"]},
|
|
139
|
+
"content": {"type": "string", "maxLength": 1600}}}
|
|
140
|
+
messages = [{"role": "system", "content": DISCOVERY_SYSTEM},
|
|
141
|
+
{"role": "user", "content": state.get("task", "") +
|
|
142
|
+
f"\nEvidence limited: {state.get('evidence_limited', False)}.\n" + evidence}]
|
|
143
|
+
if state.get("invalid_replies"):
|
|
144
|
+
messages.append(state["messages"][-1]) # Carry the correction into the rebuilt prompt.
|
|
145
|
+
# Phase: call the model, with a background thread that reports the wait until text starts to arrive.
|
|
146
|
+
output(f"\n{step_label(step, max_steps)}: waiting for the local model (loading and prompt processing can take time)...")
|
|
147
|
+
started = time.monotonic()
|
|
148
|
+
stopped = threading.Event()
|
|
149
|
+
streamed = []
|
|
150
|
+
|
|
151
|
+
def progress():
|
|
152
|
+
"""Print a waiting line every 15 seconds until the model replies or starts streaming."""
|
|
153
|
+
while not stopped.wait(15):
|
|
154
|
+
output(f"Still waiting for the local model: {int(time.monotonic() - started)}s elapsed.")
|
|
155
|
+
|
|
156
|
+
def on_text(chunk):
|
|
157
|
+
"""Receive streamed answer text: print the heading before the first chunk, then pass each chunk on."""
|
|
158
|
+
if not streamed:
|
|
159
|
+
stopped.set() # Keep progress lines from interleaving with the answer.
|
|
160
|
+
output(f"\n{step_label(step, max_steps)}: final answer")
|
|
161
|
+
streamed.append(chunk)
|
|
162
|
+
write_stream(chunk)
|
|
163
|
+
|
|
164
|
+
# Discovery answers may be withheld after checks, so they are never shown before validation. A named-file
|
|
165
|
+
# overview is short and capped, so it is printed once complete: streamed text cannot be trimmed afterward.
|
|
166
|
+
# A corrected answer is printed once it is checked, so it does not run on into the first answer on screen.
|
|
167
|
+
live = (stream is not None and not state.get("discovery", False) and not (question and cite_files)
|
|
168
|
+
and not state.get("retried"))
|
|
169
|
+
reporter = threading.Thread(target=progress, daemon=True)
|
|
170
|
+
reporter.start()
|
|
171
|
+
# cut: the answer was stopped for repeating; missing: points that name nothing in their file;
|
|
172
|
+
# capped: the answer hit its length limit; overview: the answer text before points were folded in.
|
|
173
|
+
cut, missing, capped, overview = False, [], False, ""
|
|
174
|
+
try:
|
|
175
|
+
try:
|
|
176
|
+
reply = model.chat(messages, schema, on_text=on_text) if live else model.chat(messages, schema)
|
|
177
|
+
if isinstance(reply, dict) and reply.get("action") == "finish" and isinstance(reply.get("content"), str):
|
|
178
|
+
reply["content"], capped = trim_at_limit(reply["content"], schema["properties"]["content"].get("maxLength"))
|
|
179
|
+
overview = reply["content"]
|
|
180
|
+
if question:
|
|
181
|
+
reply, missing = with_points(reply, workspace, state.get("search_evidence", []))
|
|
182
|
+
problem = reply_problem(reply, actions)
|
|
183
|
+
except RepeatedAnswer as exc:
|
|
184
|
+
# Keep the useful text before the loop; a retry at temperature 0 tends to loop again.
|
|
185
|
+
reply, problem, cut = (dict(action="finish", path="", content=exc.answer, message="Answer stopped while repeating"),
|
|
186
|
+
None, True) if exc.answer else (None, str(exc), False)
|
|
187
|
+
except InvalidReply as exc:
|
|
188
|
+
reply, problem = None, str(exc)
|
|
189
|
+
finally:
|
|
190
|
+
stopped.set()
|
|
191
|
+
reporter.join()
|
|
192
|
+
if streamed:
|
|
193
|
+
write_stream("\n")
|
|
194
|
+
metrics = getattr(model, "last_metrics", None)
|
|
195
|
+
if isinstance(metrics, dict) and metrics:
|
|
196
|
+
output(format_metrics(metrics))
|
|
197
|
+
if step > 1 and not reload_warned[0] and (metrics.get("load_seconds") or 0) >= RELOAD_SECONDS:
|
|
198
|
+
reload_warned[0] = True
|
|
199
|
+
output(f"Warning: Ollama reloaded the model between steps ({metrics['load_seconds']:.0f}s). Something else is "
|
|
200
|
+
"probably using Ollama and competing for memory; check with `ollama ps`. Steps will stay slow until it stops.")
|
|
201
|
+
steps = state["steps"] + 1
|
|
202
|
+
# Phase: handle an unusable reply. The first one gets a correction and another try; a second in a row ends the run.
|
|
203
|
+
if problem:
|
|
204
|
+
if state.get("invalid_replies", 0):
|
|
205
|
+
raise ValueError(f"Model returned an invalid action twice in a row: {problem}")
|
|
206
|
+
output(f"\n{step_label(steps, max_steps)}: invalid model reply ({problem}); asking the model to correct it.")
|
|
207
|
+
return {"messages": state["messages"] + [{"role": "user", "content": CORRECTION.format(problem)}],
|
|
208
|
+
"reply": {"action": "retry", "path": "", "content": "", "message": ""},
|
|
209
|
+
"steps": steps, "invalid_replies": 1}
|
|
210
|
+
assert isinstance(reply, dict)
|
|
211
|
+
# A tool requested on a final-answer call is not run: exit code 2 makes route_action end the graph.
|
|
212
|
+
if finishing and reply["action"] != "finish":
|
|
213
|
+
output("Final-answer request failed: the model requested another tool. The task is incomplete; no further tool was executed.")
|
|
214
|
+
return {"reply": reply, "steps": steps, "exit_code": 2, "repeated_lookup": True, "invalid_replies": 0}
|
|
215
|
+
repeated = reply["action"] != "finish" and already_tried(state, reply)
|
|
216
|
+
# Phase: announce the action, describing its target in the action's own terms.
|
|
217
|
+
if reply["action"] == "search":
|
|
218
|
+
target = f"query={json.dumps(reply['content'])} scope={json.dumps(reply['path'] or '.') }"
|
|
219
|
+
elif reply["action"] == "read" and isinstance(span := action_key(reply)[2], tuple):
|
|
220
|
+
target = f"{reply['path']} lines {span[0]}-{span[1] or 'end'}"
|
|
221
|
+
else:
|
|
222
|
+
target = reply["path"] or (reply["content"][:100] if reply["action"] == "retrieve" else "")
|
|
223
|
+
shown = "".join(streamed)
|
|
224
|
+
if reply["action"] == "finish":
|
|
225
|
+
if not streamed:
|
|
226
|
+
output(f"\n{step_label(steps, max_steps)}: final answer")
|
|
227
|
+
else:
|
|
228
|
+
output(f"\n{step_label(steps, max_steps)}: {reply['action']} {target} ({reply['message']})")
|
|
229
|
+
if repeated:
|
|
230
|
+
output("Repeated action detected; skipping the duplicate tool call and requesting a final answer.")
|
|
231
|
+
# Phase: check a final answer against the evidence, and print whatever part of it was not already streamed.
|
|
232
|
+
final_text, issues = None, []
|
|
233
|
+
if reply["action"] == "finish":
|
|
234
|
+
invented = []
|
|
235
|
+
# Each literal value the answer reports is looked for in the code: on the cited lines, or else on a line the
|
|
236
|
+
# model was shown, which then gets a citation; a value on no shown line was not read from the code.
|
|
237
|
+
if question and reply.get("content") and not state.get("discovery"):
|
|
238
|
+
extra, invented = check_values(reply["content"], state.get("task", ""), workspace,
|
|
239
|
+
state.get("search_evidence", []))
|
|
240
|
+
if extra:
|
|
241
|
+
reply["content"] = "\n\n".join([reply["content"].rstrip(), VALUE_HEADING + "\n" + "\n".join(extra)])
|
|
242
|
+
output(f"CodeHaven cited {len(extra)} line(s) holding values the answer reports.")
|
|
243
|
+
issues = check_answer(reply["content"] or reply["message"], state.get("search_evidence", []),
|
|
244
|
+
discovery=state.get("discovery", False), require_citation=question)
|
|
245
|
+
# An answer that cites nothing gets citations for the code names it mentions, from lines the model saw.
|
|
246
|
+
if question and any(issue.startswith("Repository claims require") for issue in issues) and reply.get("content"):
|
|
247
|
+
sources = cite_mentions(reply["content"], workspace, state.get("search_evidence", []))
|
|
248
|
+
if sources:
|
|
249
|
+
reply["content"] = "\n\n".join([reply["content"].rstrip(), MENTION_HEADING + "\n" + "\n".join(sources)])
|
|
250
|
+
output(f"CodeHaven added {len(sources)} citation(s) for code names the answer mentions.")
|
|
251
|
+
issues = check_answer(reply["content"], state.get("search_evidence", []),
|
|
252
|
+
discovery=state.get("discovery", False), require_citation=question)
|
|
253
|
+
issues += [f"No part named {symbol!r} was found in {path}; that point is uncited." for path, symbol in missing]
|
|
254
|
+
issues += [f"The answer reports {value!r}, which is on no line the model was shown." for value in invented]
|
|
255
|
+
# Said after the checks, which it takes no part in: the cited code calls into code that is not here, so the
|
|
256
|
+
# reader knows the answer cannot show what that code does.
|
|
257
|
+
if question and reply.get("content") and not state.get("discovery"):
|
|
258
|
+
outside = missing_code(reply["content"], workspace, knowledge)
|
|
259
|
+
if outside:
|
|
260
|
+
reply["content"] = "\n\n".join([reply["content"].rstrip(), MISSING_HEADING + "\n" + "\n".join(outside)])
|
|
261
|
+
output(f"CodeHaven noted {len(outside)} import(s) of code that is not in this repository.")
|
|
262
|
+
if issues and state.get("discovery"):
|
|
263
|
+
output("Model summary withheld because answer checks failed.")
|
|
264
|
+
final_text = inventory(state.get("search_evidence", []), state.get("evidence_limited", False))
|
|
265
|
+
output(final_text)
|
|
266
|
+
else:
|
|
267
|
+
if cut:
|
|
268
|
+
output(REPEAT_NOTE)
|
|
269
|
+
# Print unless already streamed; a streamed loop is followed by the note, not a second copy.
|
|
270
|
+
answer = reply["content"] or reply["message"]
|
|
271
|
+
final_text = "\n".join([answer] + ([REPEAT_NOTE] if cut else []) + ([LIMIT_NOTE] if capped else []))
|
|
272
|
+
if capped and streamed:
|
|
273
|
+
# The unfinished sentence was already on screen; say it is dropped and show only the points after it.
|
|
274
|
+
output(LIMIT_NOTE)
|
|
275
|
+
if answer[len(overview):].strip():
|
|
276
|
+
output(answer[len(overview):].lstrip("\n"))
|
|
277
|
+
elif not (cut and streamed) and shown.strip() != answer.strip():
|
|
278
|
+
# Cited points follow a streamed overview, so print only what was not shown. The overview is
|
|
279
|
+
# stripped before the points are joined, so a trailing space must not make it look different.
|
|
280
|
+
base = shown.rstrip()
|
|
281
|
+
output(answer[len(base):].lstrip() if base and answer.startswith(base) else answer)
|
|
282
|
+
if capped and not streamed:
|
|
283
|
+
output(LIMIT_NOTE)
|
|
284
|
+
for issue in issues:
|
|
285
|
+
output("Answer check: " + issue)
|
|
286
|
+
if issues:
|
|
287
|
+
output("Answer is unverified; check the cited evidence before relying on it.")
|
|
288
|
+
result = {"messages": state["messages"] + [
|
|
289
|
+
{"role": "assistant", "content": json.dumps(reply)}],
|
|
290
|
+
"reply": reply, "steps": steps, "repeated_lookup": repeated, "invalid_replies": 0,
|
|
291
|
+
# The answer as shown and its check results, for callers such as the GUI that do not read output.
|
|
292
|
+
"final_text": final_text, "issues": issues,
|
|
293
|
+
"exit_code": 2 if reply["action"] == "finish" and issues else 0}
|
|
294
|
+
first = state.get("retried")
|
|
295
|
+
if reply["action"] == "finish" and first:
|
|
296
|
+
# The corrected answer: kept only if it fails fewer checks than the first one.
|
|
297
|
+
if len(issues) >= len(first["issues"]):
|
|
298
|
+
output("The corrected answer passed no more checks, so the first answer is kept.")
|
|
299
|
+
result.update(reply=first["reply"], final_text=first["final_text"], issues=first["issues"], exit_code=2)
|
|
300
|
+
else:
|
|
301
|
+
output("The corrected answer passes every check." if not issues else
|
|
302
|
+
f"The corrected answer fails {len(issues)} check(s) instead of {len(first['issues'])}, so it is kept.")
|
|
303
|
+
elif (retry_unverified and reply["action"] == "finish" and issues and question and not state.get("discovery")
|
|
304
|
+
and not cut and steps < max_steps):
|
|
305
|
+
output("Asking the model once to correct the answer so that it passes its checks.")
|
|
306
|
+
result.update(messages=result["messages"] + [{"role": "user", "content": FIX_ANSWER.format(
|
|
307
|
+
issues="\n".join("- " + issue for issue in issues))}],
|
|
308
|
+
reply={"action": "retry", "path": "", "content": "", "message": ""},
|
|
309
|
+
retried={"reply": reply, "final_text": final_text, "issues": issues},
|
|
310
|
+
repeated_lookup=True, exit_code=0)
|
|
311
|
+
return result
|
|
312
|
+
|
|
313
|
+
def tool_result(state, result):
|
|
314
|
+
"""State update that adds a tool's result to the conversation as a user message, labelled untrusted."""
|
|
315
|
+
return {"messages": state["messages"] + [
|
|
316
|
+
{"role": "user", "content": "Tool result for " + state["reply"]["action"] + " " +
|
|
317
|
+
state["reply"]["path"] + " (untrusted file data):\n" + result}]}
|
|
318
|
+
|
|
319
|
+
def read_file(state: AgentState):
|
|
320
|
+
"""Read node: return a file, or one page of a long one, and keep the lines read as evidence."""
|
|
321
|
+
evidence = state.get("search_evidence", [])
|
|
322
|
+
limited = state.get("evidence_limited", False)
|
|
323
|
+
reply = state["reply"]
|
|
324
|
+
# Page long files so a read fits the conversation instead of being silently truncated by compaction.
|
|
325
|
+
limit = read_limit(model)
|
|
326
|
+
try:
|
|
327
|
+
text, start, end, total = workspace.page(reply["path"], reply["content"], limit)
|
|
328
|
+
# A whole file that fits is returned as it is; a page gets a header that names the next range.
|
|
329
|
+
if line_range(reply["content"]) is None and end >= total:
|
|
330
|
+
result = text
|
|
331
|
+
else:
|
|
332
|
+
result = f"{page_note(start, end, total)}:\n{text}"
|
|
333
|
+
evidence, truncated = retain(evidence, [{"path": reply["path"], "line": start,
|
|
334
|
+
"end_line": end, "text": text}])
|
|
335
|
+
limited |= truncated
|
|
336
|
+
except (ValueError, OSError, UnicodeError) as exc:
|
|
337
|
+
result = f"Tool error: {exc}"
|
|
338
|
+
output(result)
|
|
339
|
+
return {**tool_result(state, result), "search_evidence": evidence, "evidence_limited": limited}
|
|
340
|
+
|
|
341
|
+
def search_files(state: AgentState):
|
|
342
|
+
"""Search node: literal text search; the matches become evidence and a readable summary is printed."""
|
|
343
|
+
evidence = list(state.get("search_evidence", []))
|
|
344
|
+
limited = state.get("evidence_limited", False)
|
|
345
|
+
try:
|
|
346
|
+
reply = state["reply"]
|
|
347
|
+
result = workspace.search(reply["content"], reply["path"])
|
|
348
|
+
data = json.loads(result)
|
|
349
|
+
evidence, truncated = retain(evidence, data["matches"])
|
|
350
|
+
limited |= truncated or data.get("limit_reached", False) or data.get("candidate_limit_reached", False)
|
|
351
|
+
output(format_search(data))
|
|
352
|
+
except (ValueError, OSError, UnicodeError) as exc:
|
|
353
|
+
result = f"Tool error: {exc}"
|
|
354
|
+
output(result)
|
|
355
|
+
return {**tool_result(state, result), "search_evidence": evidence, "evidence_limited": limited}
|
|
356
|
+
|
|
357
|
+
def retrieve_references(state: AgentState):
|
|
358
|
+
"""Retrieve node: query the knowledge base (indexed code, docs, user references) and keep the passages as evidence."""
|
|
359
|
+
reply = state["reply"]
|
|
360
|
+
evidence = state.get("search_evidence", [])
|
|
361
|
+
limited = state.get("evidence_limited", False)
|
|
362
|
+
try:
|
|
363
|
+
if reply["path"]:
|
|
364
|
+
raise ValueError("retrieve uses the configured knowledge base; path must be empty")
|
|
365
|
+
if knowledge is None:
|
|
366
|
+
raise ValueError("No knowledge base is configured")
|
|
367
|
+
result = knowledge.retrieve(reply["content"])
|
|
368
|
+
data = json.loads(result)
|
|
369
|
+
evidence, truncated = retain(evidence, retrieved_rows(data))
|
|
370
|
+
limited |= truncated or data.get("budget_limited", False) or data.get("results_limited", False)
|
|
371
|
+
output(format_retrieval(data))
|
|
372
|
+
except (ValueError, OSError, UnicodeError) as exc:
|
|
373
|
+
result = f"Tool error: {exc}"
|
|
374
|
+
output(result)
|
|
375
|
+
return {**tool_result(state, result), "search_evidence": evidence, "evidence_limited": limited}
|
|
376
|
+
|
|
377
|
+
def execute_tests(state: AgentState):
|
|
378
|
+
"""Test node: run the configured tests in Docker, only after the user approves the command shown."""
|
|
379
|
+
reply = state["reply"]
|
|
380
|
+
if reply["path"] or reply["content"]:
|
|
381
|
+
return tool_result(state, "Tool error: run_tests accepts no path, content, or custom command")
|
|
382
|
+
options = dict(test_options or {})
|
|
383
|
+
output("Requested test command: " + " ".join(command(options.get("runner", "unittest"))))
|
|
384
|
+
output("Isolation: Docker; network disabled; filtered project snapshot read-only. "
|
|
385
|
+
"Image: " + options.get("image", DEFAULT_IMAGE))
|
|
386
|
+
output(f"Working directory: {workspace.root}")
|
|
387
|
+
# With no way to ask the user, the run counts as denied.
|
|
388
|
+
if not confirm_tests or not confirm_tests():
|
|
389
|
+
return tool_result(state, "Tests were NOT run: execution was not approved.")
|
|
390
|
+
try:
|
|
391
|
+
result = run_tests(workspace, **options)
|
|
392
|
+
except (ValueError, OSError) as exc:
|
|
393
|
+
result = f"Test execution error: {exc}"
|
|
394
|
+
output(result)
|
|
395
|
+
return tool_result(state, result)
|
|
396
|
+
|
|
397
|
+
def execute_code(state: AgentState):
|
|
398
|
+
"""Code node: run the model's Python snippet in the test sandbox, only after the user approves the code shown."""
|
|
399
|
+
reply = state["reply"]
|
|
400
|
+
if reply["path"]:
|
|
401
|
+
return tool_result(state, "Tool error: run_python takes the code in content and an empty path")
|
|
402
|
+
code = reply["content"]
|
|
403
|
+
output("Requested Python snippet (runs in Docker with network disabled and a read-only copy of the project):\n"
|
|
404
|
+
+ code.rstrip())
|
|
405
|
+
if not confirm_code(code):
|
|
406
|
+
return tool_result(state, "The snippet was NOT run: the user did not approve it. Answer from the code instead.")
|
|
407
|
+
try:
|
|
408
|
+
result = run_snippet(workspace, code, **dict(test_options or {}))
|
|
409
|
+
except (ValueError, OSError) as exc:
|
|
410
|
+
result = f"Snippet error: {exc}"
|
|
411
|
+
output(result)
|
|
412
|
+
return tool_result(state, result)
|
|
413
|
+
|
|
414
|
+
def route_action(state: AgentState):
|
|
415
|
+
"""Edge after the model node: choose the next node from the reply."""
|
|
416
|
+
# An invalid reply was just sent back for correction: call the model again, unless the steps ran out.
|
|
417
|
+
if state["reply"]["action"] == "retry":
|
|
418
|
+
return after_tool(state)
|
|
419
|
+
if state["reply"]["action"] == "finish":
|
|
420
|
+
return "finish"
|
|
421
|
+
# The model asked for a tool on a final-answer call; stop without running it.
|
|
422
|
+
if state.get("exit_code") == 2:
|
|
423
|
+
return "finish"
|
|
424
|
+
if state.get("repeated_lookup"):
|
|
425
|
+
return "repeat"
|
|
426
|
+
return state["reply"]["action"]
|
|
427
|
+
|
|
428
|
+
def repeated_lookup(state: AgentState):
|
|
429
|
+
"""Repeat node: stands in for a duplicate tool call and tells the model to answer instead."""
|
|
430
|
+
return tool_result(state, "Duplicate action skipped: this exact request already ran and its result is above. "
|
|
431
|
+
"Answer the original task or explain the evidence gap.")
|
|
432
|
+
|
|
433
|
+
def after_tool(state: AgentState):
|
|
434
|
+
"""Edge after every tool node: back to the model, or to limit when the steps ran out."""
|
|
435
|
+
return "limit" if state["steps"] >= max_steps else "model"
|
|
436
|
+
|
|
437
|
+
def limit(state: AgentState):
|
|
438
|
+
"""Limit node: report that the steps ran out and mark the task incomplete."""
|
|
439
|
+
output("Step limit reached without a final answer. The task is incomplete; tool messages above are not a final answer.")
|
|
440
|
+
return {"exit_code": 2}
|
|
441
|
+
|
|
442
|
+
def discover(state: AgentState):
|
|
443
|
+
"""Discover node: run the fixed FastAPI( search up front, so the model only has to summarize the matches."""
|
|
444
|
+
output("Plan: search broadly for FastAPI constructors, classify candidates, then summarize with citations.")
|
|
445
|
+
data = json.loads(workspace.search("FastAPI("))
|
|
446
|
+
evidence, limited = retain([], data["matches"])
|
|
447
|
+
limited |= data["limit_reached"] or data["candidate_limit_reached"]
|
|
448
|
+
output(f"Discovery: {len(data['matches'])} matches across {data['files_searched']} files; limited={limited}.")
|
|
449
|
+
return {"search_evidence": evidence, "evidence_limited": limited, "discovery": True}
|
|
450
|
+
|
|
451
|
+
# Nodes: the model, one node per tool action, and three helpers (limit, repeat, discover).
|
|
452
|
+
graph = StateGraph(AgentState)
|
|
453
|
+
graph.add_node("model", call_model)
|
|
454
|
+
graph.add_node("read", read_file)
|
|
455
|
+
graph.add_node("search", search_files)
|
|
456
|
+
graph.add_node("retrieve", retrieve_references)
|
|
457
|
+
graph.add_node("run_tests", execute_tests)
|
|
458
|
+
graph.add_node(CODE_ACTION, execute_code)
|
|
459
|
+
graph.add_node("limit", limit)
|
|
460
|
+
graph.add_node("repeat", repeated_lookup)
|
|
461
|
+
graph.add_node("discover", discover)
|
|
462
|
+
# Entry: an explicit FastAPI entry-point task searches first; every other task starts at the model.
|
|
463
|
+
graph.add_conditional_edges(START, lambda state: "discover" if discovery_task(state.get("task", "")) else "model")
|
|
464
|
+
graph.add_edge("discover", "model")
|
|
465
|
+
# After the model: run the chosen tool, end on finish, or return to the model after a corrected reply.
|
|
466
|
+
graph.add_conditional_edges("model", route_action,
|
|
467
|
+
{"read": "read", "search": "search", "retrieve": "retrieve",
|
|
468
|
+
"run_tests": "run_tests", CODE_ACTION: CODE_ACTION, "repeat": "repeat", "finish": END,
|
|
469
|
+
"model": "model", "limit": "limit"})
|
|
470
|
+
# After a tool: its result goes back to the model, or to limit when no steps remain.
|
|
471
|
+
for tool in ("read", "search", "retrieve", "run_tests", CODE_ACTION, "repeat"):
|
|
472
|
+
graph.add_conditional_edges(tool, after_tool, {"model": "model", "limit": "limit"})
|
|
473
|
+
graph.add_edge("limit", END)
|
|
474
|
+
return graph.compile()
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def run(model, workspace, task, *, memory=None, **options):
|
|
478
|
+
"""Run one task and return its exit code: 0 finished, 2 incomplete or unverified.
|
|
479
|
+
|
|
480
|
+
With a Memory, saved answers from earlier sessions are recalled and a checked answer is saved.
|
|
481
|
+
"""
|
|
482
|
+
if memory is not None:
|
|
483
|
+
return Session(model, workspace, memory=memory, **options).ask(task)
|
|
484
|
+
return run_state(model, workspace, task, **options)["exit_code"]
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def run_state(model, workspace, task, *, max_steps=12, confirm_tests=None, knowledge=None,
|
|
488
|
+
test_options=None, output=print, stream=None, history="", carried_evidence=(), focus_file=None, notes="",
|
|
489
|
+
confirm_code=None, retry_unverified=False, editor=None):
|
|
490
|
+
"""Run one task and return the final graph state.
|
|
491
|
+
|
|
492
|
+
editor, a coder.Editor, turns on changing code: a change request is then made, after the user approves its diff. history and carried_evidence come from a Session.
|
|
493
|
+
|
|
494
|
+
notes are answers recalled from long-term memory, shown before the session's own history.
|
|
495
|
+
|
|
496
|
+
focus_file names the file every task is about, such as a file uploaded in the GUI: it is preloaded even
|
|
497
|
+
when the task does not name it.
|
|
498
|
+
"""
|
|
499
|
+
# Phase 1: the opening messages: the system prompt, then the task with the file paths most relevant to it.
|
|
500
|
+
files = workspace.files()
|
|
501
|
+
terms = set(re.findall(r"[a-z0-9]+", task.lower()))
|
|
502
|
+
def relevance(name):
|
|
503
|
+
"""Sort key: paths sharing the most words with the task first, then shallower paths, then by name."""
|
|
504
|
+
words = set(re.findall(r"[a-z0-9]+", name.lower()))
|
|
505
|
+
return (-len(terms & words), name.count("/"), name)
|
|
506
|
+
selected = []
|
|
507
|
+
size = 0
|
|
508
|
+
# At most 40 paths and 2000 bytes, so the listing never crowds the code out of the prompt.
|
|
509
|
+
for name in sorted(files, key=relevance):
|
|
510
|
+
if len(selected) >= 40 or size + len(name.encode()) + 1 > 2000:
|
|
511
|
+
break
|
|
512
|
+
selected.append(name)
|
|
513
|
+
size += len(name.encode()) + 1
|
|
514
|
+
earlier = ((f"Notes saved in earlier sessions about this repository (the files they cite have not changed since; "
|
|
515
|
+
f"use them only where they help with the current task):\n{notes}\n\n" if notes else "")
|
|
516
|
+
+ (f"Earlier in this session (answers may be outdated if files changed since):\n{history}\n\n" if history else ""))
|
|
517
|
+
earlier += "Current task: " if earlier else ""
|
|
518
|
+
messages = [{"role": "system", "content": SYSTEM + ("\n" + PYTHON_GUIDE if confirm_code else "")},
|
|
519
|
+
{"role": "user", "content": earlier + task + f"\nWorkspace path sample ({len(selected)} of {len(files)} listed files; use search/read/retrieve for more):\n" +
|
|
520
|
+
"\n".join(selected)}]
|
|
521
|
+
evidence, evidence_limited = [dict(row) for row in carried_evidence], False
|
|
522
|
+
# Phase 2: a task about git changes gets them read with git up front.
|
|
523
|
+
asked_changes = changes.requested(task)
|
|
524
|
+
report = found = None
|
|
525
|
+
if (written := commit_messages.requested(task)):
|
|
526
|
+
# "Write a commit message": the diff goes to the model with a prompt of its own, and nothing is committed.
|
|
527
|
+
found = commit_messages.write(model, workspace, task, written, read_limit(model) - 600, output)
|
|
528
|
+
elif asked_changes and REVIEW_CHANGES.search(task):
|
|
529
|
+
# "Review my changes": only the functions the diff touched are reviewed, one model call each.
|
|
530
|
+
try:
|
|
531
|
+
found = review_changes(model, workspace, asked_changes, spans=knowledge.dependencies.spans if knowledge else None,
|
|
532
|
+
output=output, in_arabic=arabic.written_in(task))
|
|
533
|
+
except changes.NoChanges as exc:
|
|
534
|
+
found = {"text": str(exc), "evidence": []}
|
|
535
|
+
except (ValueError, OSError) as exc:
|
|
536
|
+
found = {"text": f"Could not read the changes with git ({exc}).", "evidence": []}
|
|
537
|
+
elif asked_changes:
|
|
538
|
+
try:
|
|
539
|
+
report = changes.describe(workspace, asked_changes, read_limit(model) - len(CHANGES_ANSWER.encode()) - 200,
|
|
540
|
+
named_files(task, files))
|
|
541
|
+
except changes.NoChanges as exc:
|
|
542
|
+
# Nothing to explain is a fact git reports, so it is answered at once, without the model.
|
|
543
|
+
output(str(exc))
|
|
544
|
+
return {"messages": messages, "reply": {"action": "finish", "path": "", "content": str(exc), "message": ""},
|
|
545
|
+
"steps": 0, "exit_code": 0, "task": task, "search_evidence": evidence, "evidence_limited": False,
|
|
546
|
+
"final_text": str(exc), "issues": [], "kind": "question"}
|
|
547
|
+
except (ValueError, OSError) as exc:
|
|
548
|
+
output(f"Could not read the changes with git ({exc}); answering from the files instead.")
|
|
549
|
+
# Phase 3: shortcuts that return without running the graph: a file review, a call trace, test gaps, or a project tour.
|
|
550
|
+
# Some requests have a purpose-built answer that does not go through the general workflow.
|
|
551
|
+
reviewed = named_files(task, files)[:1] or ([focus_file] if focus_file in files else [])
|
|
552
|
+
wanted = insights.requested(task) if report is None and not asked_changes else None
|
|
553
|
+
in_arabic = arabic.written_in(task)
|
|
554
|
+
scan = scans.requested(task) if report is None and not asked_changes else None
|
|
555
|
+
why = report is None and not asked_changes and blame.requested(task)
|
|
556
|
+
edit = coder.requested(task) if editor is not None and report is None and found is None else None
|
|
557
|
+
if found is not None:
|
|
558
|
+
pass # The changes were reviewed above.
|
|
559
|
+
elif edit:
|
|
560
|
+
found = coder.run(edit, model, workspace, knowledge, task, editor, output)
|
|
561
|
+
elif scan:
|
|
562
|
+
found = scans.run(*scan, workspace, knowledge)
|
|
563
|
+
elif report is None and not asked_changes and (guide := guides.requested(task)):
|
|
564
|
+
found = guides.run(*guide, model, workspace, knowledge, output)
|
|
565
|
+
elif why and (explained := blame.explain(model, workspace, knowledge, task, output)) is not None:
|
|
566
|
+
found = explained
|
|
567
|
+
elif report is None and (REVIEW.search(task) or arabic.REVIEW.search(arabic.normalise(task))) and reviewed:
|
|
568
|
+
spans = knowledge.dependencies.spans.get(reviewed[0]) if knowledge is not None else None
|
|
569
|
+
try:
|
|
570
|
+
found = review(model, workspace, reviewed[0], spans=spans, output=output, in_arabic=in_arabic)
|
|
571
|
+
except (ValueError, OSError, UnicodeError) as exc:
|
|
572
|
+
found = {"text": f"{reviewed[0]} could not be reviewed: {exc}", "evidence": []}
|
|
573
|
+
elif report is None and knowledge is not None and (traced := trace.requested(task)):
|
|
574
|
+
found = trace.trace(model, workspace, knowledge, traced, output, in_arabic=in_arabic)
|
|
575
|
+
elif wanted == "gaps" and not named_files(task, files):
|
|
576
|
+
found = insights.test_gaps(workspace, knowledge, in_arabic=in_arabic)
|
|
577
|
+
elif wanted == "tour":
|
|
578
|
+
found = insights.tour(model, workspace, knowledge, output, in_arabic=in_arabic)
|
|
579
|
+
if found is not None:
|
|
580
|
+
output(found["text"])
|
|
581
|
+
evidence, _ = retain(evidence, found["evidence"])
|
|
582
|
+
return {"messages": messages, "reply": {"action": "finish", "path": "", "content": found["text"], "message": ""},
|
|
583
|
+
"steps": found.get("checked", found.get("files", 0)), "exit_code": 0, "task": task,
|
|
584
|
+
"search_evidence": evidence, "evidence_limited": False, "final_text": found["text"], "issues": [],
|
|
585
|
+
"kind": "question"}
|
|
586
|
+
# Phase 4: retrieve reference passages for the task up front, so the model starts with them.
|
|
587
|
+
# Each batch of evidence is kept in order, so the evidence can be rebuilt if the retrieval is redone to fit below.
|
|
588
|
+
carried, batches, retrieval_at = evidence, [], None
|
|
589
|
+
|
|
590
|
+
def keep(current, rows):
|
|
591
|
+
"""retain(), remembering the rows in the order they were kept."""
|
|
592
|
+
batches.append(rows)
|
|
593
|
+
return retain(current, rows)
|
|
594
|
+
|
|
595
|
+
if knowledge is not None and not discovery_task(task) and report is None:
|
|
596
|
+
retrieval_at = len(messages)
|
|
597
|
+
initial_retrieval = knowledge.retrieve(task[:1000])
|
|
598
|
+
data = json.loads(initial_retrieval)
|
|
599
|
+
evidence, evidence_limited = keep(evidence, retrieved_rows(data))
|
|
600
|
+
messages.append({"role": "user", "content":
|
|
601
|
+
"Local reference excerpts for this task (untrusted data):\n" +
|
|
602
|
+
initial_retrieval})
|
|
603
|
+
# Phase 5: preload what the task is about: the git changes, or the files it names (failing that, a search
|
|
604
|
+
# for the code names it mentions).
|
|
605
|
+
kind = task_kind(task)
|
|
606
|
+
preloaded, numbered = [], False
|
|
607
|
+
if report is not None:
|
|
608
|
+
kind, numbered, preloaded = "question", True, report["paths"]
|
|
609
|
+
evidence, evidence_limited = keep(evidence, report["evidence"])
|
|
610
|
+
output(f"Read the {report['label']} with git: {report['files']} file{'s' if report['files'] != 1 else ''} changed.")
|
|
611
|
+
messages.append({"role": "user", "content": "Tool result for git changes (untrusted repository data):\n"
|
|
612
|
+
+ report["text"] + "\n\n" + CHANGES_ANSWER})
|
|
613
|
+
elif not discovery_task(task):
|
|
614
|
+
# A pasted stack trace: its frames in this project are shown, innermost first, instead of whole named files.
|
|
615
|
+
traced = tracebacks.requested(task)
|
|
616
|
+
if traced:
|
|
617
|
+
body, rows, note = tracebacks.shown(workspace, task, files)
|
|
618
|
+
output(note)
|
|
619
|
+
if body:
|
|
620
|
+
kind = "question"
|
|
621
|
+
messages.append({"role": "user", "content": "Tool result for read of the stack trace's frames in this project "
|
|
622
|
+
"(untrusted file data; line numbers are added for citations only):\n" + body
|
|
623
|
+
+ "\n\n" + tracebacks.GUIDE})
|
|
624
|
+
evidence, truncated = keep(evidence, rows)
|
|
625
|
+
evidence_limited |= truncated
|
|
626
|
+
names = [] if traced else named_files(task, files)
|
|
627
|
+
reason = "the task names it"
|
|
628
|
+
if not names and focus_file in files:
|
|
629
|
+
names, reason = [focus_file], "it is the file this chat is about"
|
|
630
|
+
# "Explain this project": a map of the main code files and what they define, so the answer is about the code,
|
|
631
|
+
# not the README and packaging that a path listing and a retrieval for the words "this project" turn up.
|
|
632
|
+
if not names and not traced and insights.overview_requested(task):
|
|
633
|
+
body, rows = insights.project_map(workspace, knowledge)
|
|
634
|
+
if body:
|
|
635
|
+
output("Preloaded a map of the project's main code files because the task asks about the whole project.")
|
|
636
|
+
messages.append({"role": "user", "content": "Tool result for a map of the project (untrusted file data, "
|
|
637
|
+
"built by parsing the code):\n" + body + "\n\n" + insights.MAP_GUIDE})
|
|
638
|
+
evidence, truncated = keep(evidence, rows)
|
|
639
|
+
evidence_limited |= truncated
|
|
640
|
+
# The functions and classes the task names, looked up in the parsed code; within the named files when there are any.
|
|
641
|
+
named = symbols.find(task, knowledge, set(names) if names else None) if knowledge is not None and kind != "other" else []
|
|
642
|
+
# Searched even when the task names a file, within that file: "which functions in routing.py call X?" needs
|
|
643
|
+
# the matches and the functions they are in, which a preview of a long file does not show.
|
|
644
|
+
if kind != "other":
|
|
645
|
+
shown, found = search_named(workspace, task, scope=names)
|
|
646
|
+
if shown:
|
|
647
|
+
messages.append({"role": "user", "content": "Tool result for search of names in the task (untrusted file data):\n"
|
|
648
|
+
+ "\n".join(shown)})
|
|
649
|
+
evidence, truncated = keep(evidence, found)
|
|
650
|
+
evidence_limited |= truncated
|
|
651
|
+
# Their definitions are shown whole, with line numbers: left to search, the model answers without reading them.
|
|
652
|
+
body, rows, notes = symbols.shown(workspace, named, task, knowledge=knowledge)
|
|
653
|
+
if body:
|
|
654
|
+
for note in notes:
|
|
655
|
+
output(note)
|
|
656
|
+
messages.append({"role": "user", "content": "Tool result for read of the definitions the task names (untrusted file data; "
|
|
657
|
+
"line numbers are added for citations only; do not read these lines again):\n" + body})
|
|
658
|
+
evidence, truncated = keep(evidence, rows)
|
|
659
|
+
evidence_limited |= truncated
|
|
660
|
+
# Line numbers help citations; nothing is ever edited, so files need not stay byte-exact.
|
|
661
|
+
numbered = kind in ("question", "change")
|
|
662
|
+
guide = FINISH_NOW + ANSWER_FROM_PRELOAD
|
|
663
|
+
# The byte budget is shared between the named files, less the room the closing guide needs.
|
|
664
|
+
limit = (read_limit(model) - (len(guide.encode()) + 2 if numbered else 0)) // max(1, len(names))
|
|
665
|
+
for name in names:
|
|
666
|
+
try:
|
|
667
|
+
text = workspace.read(name)
|
|
668
|
+
except (ValueError, OSError, UnicodeError):
|
|
669
|
+
continue
|
|
670
|
+
lines = text.splitlines(keepends=True)
|
|
671
|
+
total = len(lines)
|
|
672
|
+
# A file too long for its share is shown in parts; 6 is the bytes each line-number prefix adds.
|
|
673
|
+
# A file too long to show whole keeps the lines of the parts the task names, not only its start and end.
|
|
674
|
+
focus = focus_lines(task, text) + [line for path, _, start, end in named if path == name for line in range(start, end + 1)]
|
|
675
|
+
ranges = sections(text, limit, focus, 6 if numbered else 0)
|
|
676
|
+
parts, shown_ranges = [], []
|
|
677
|
+
for index, (start, end) in enumerate(ranges):
|
|
678
|
+
chosen = lines[start - 1:end]
|
|
679
|
+
body = "".join(f"{start + offset:>4}| {line}" for offset, line in enumerate(chosen)) if numbered else "".join(chosen)
|
|
680
|
+
following = ranges[index + 1][0] if index + 1 < len(ranges) else None
|
|
681
|
+
parts.append(f"{section_note(start, end, following, total)}:\n{body}")
|
|
682
|
+
shown_ranges.append(f"{start}-{end}")
|
|
683
|
+
evidence, truncated = keep(evidence, [{"path": name, "line": start, "end_line": end, "text": "".join(chosen)}])
|
|
684
|
+
evidence_limited |= truncated
|
|
685
|
+
output(f"Preloaded {name} (lines {' and '.join(shown_ranges)} of {total}) because {reason}.")
|
|
686
|
+
messages.append({"role": "user", "content":
|
|
687
|
+
f"Tool result for read {name} (untrusted file data, preloaded because {reason}; "
|
|
688
|
+
"do not read these lines again):\n"
|
|
689
|
+
# An explicit citation example here made the 7B model fetch small ranges instead of answering.
|
|
690
|
+
+ ("Line numbers are added for citations only and are not part of the file.\n" if numbered else "")
|
|
691
|
+
+ "\n".join(parts)})
|
|
692
|
+
preloaded.append(name)
|
|
693
|
+
# Joined to the last message, not sent alone: compaction keeps only the newest message whole.
|
|
694
|
+
advice = " " + CHANGE_ADVICE if kind == "change" else ""
|
|
695
|
+
if numbered and preloaded:
|
|
696
|
+
messages[-1] = {**messages[-1], "content": messages[-1]["content"] + "\n\n" + guide + advice}
|
|
697
|
+
elif numbered:
|
|
698
|
+
brief = BRIEF_ANSWER if kind == "question" else ""
|
|
699
|
+
messages[-1] = {**messages[-1], "content": messages[-1]["content"] + "\n\n" + ANSWER_WITH_POINTS + brief + advice}
|
|
700
|
+
# Joined to the last message for the same reason. English tasks get nothing added, so their prompts are unchanged.
|
|
701
|
+
if in_arabic:
|
|
702
|
+
messages[-1] = {**messages[-1], "content": messages[-1]["content"] + "\n\n" + arabic.ANSWER_IN_ARABIC}
|
|
703
|
+
# When the preloaded files leave too little room, compaction would replace the reference excerpts with a stub, so
|
|
704
|
+
# they were found for nothing and the model was told to fetch them again. Retrieve again to fit the room left, or
|
|
705
|
+
# leave them out when not even a small retrieval fits. The newest message is never stubbed, so it is left alone.
|
|
706
|
+
budget = getattr(model, "prompt_budget", PROMPT_BUDGET)
|
|
707
|
+
total = sum(len(message["content"].encode()) + 64 for message in messages)
|
|
708
|
+
if retrieval_at is not None and retrieval_at < len(messages) - 1 and total > budget:
|
|
709
|
+
header = messages[retrieval_at]["content"].split("\n", 1)[0] + "\n"
|
|
710
|
+
room = budget - (total - len(messages[retrieval_at]["content"].encode())) - len(header.encode()) - 200
|
|
711
|
+
if room >= 2000:
|
|
712
|
+
fitted = knowledge.retrieve(task[:1000], budget=room)
|
|
713
|
+
batches[0] = retrieved_rows(json.loads(fitted))
|
|
714
|
+
messages[retrieval_at] = {**messages[retrieval_at], "content": header + fitted}
|
|
715
|
+
else:
|
|
716
|
+
batches[0] = []
|
|
717
|
+
del messages[retrieval_at]
|
|
718
|
+
# The model is shown only the new excerpts, so only those count as lines it has seen.
|
|
719
|
+
evidence, evidence_limited = carried, False
|
|
720
|
+
for rows in batches:
|
|
721
|
+
evidence, truncated = retain(evidence, rows)
|
|
722
|
+
evidence_limited |= truncated
|
|
723
|
+
# Phase 6: run the graph. A step is at most two graph hops (the model, then a tool), plus discover and limit,
|
|
724
|
+
# which gives the recursion limit below.
|
|
725
|
+
# Always offline: LangChain would otherwise start remote tracing from LANGSMITH_TRACING and similar env vars.
|
|
726
|
+
with tracing_context(enabled=False):
|
|
727
|
+
graph = build_graph(model, workspace, max_steps=max_steps, confirm_tests=confirm_tests,
|
|
728
|
+
knowledge=knowledge, test_options=test_options, output=output, stream=stream,
|
|
729
|
+
confirm_code=confirm_code, retry_unverified=retry_unverified)
|
|
730
|
+
return graph.invoke({"messages": messages, "reply": {}, "steps": 0, "exit_code": 0, "task": task,
|
|
731
|
+
"search_evidence": evidence, "evidence_limited": evidence_limited, "invalid_replies": 0,
|
|
732
|
+
"cite_files": preloaded if numbered else [], "kind": kind},
|
|
733
|
+
config={"recursion_limit": 2 * max_steps + 2, "callbacks": [],
|
|
734
|
+
"run_name": "CodeHaven"})
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
class Session:
|
|
738
|
+
"""Several tasks in a row with one workspace, index, and model.
|
|
739
|
+
|
|
740
|
+
Follow-ups see a bounded record of earlier questions and answers plus retained evidence,
|
|
741
|
+
not full tool transcripts, so prompts stay small and the system-prompt prefix stays cacheable.
|
|
742
|
+
|
|
743
|
+
Memory is tiered: the last RECENT answers are kept nearly whole, because follow-ups such as
|
|
744
|
+
"and what does it return?" refer to them, while older ones keep only their question and first
|
|
745
|
+
sentence. The whole record stays under HISTORY_BYTES, so it never crowds the code out of a
|
|
746
|
+
12 KB prompt; the oldest entries go first.
|
|
747
|
+
|
|
748
|
+
With a Memory (opt-in), answers that passed their checks are also saved to disk, and relevant ones whose
|
|
749
|
+
cited files are unchanged are shown again in later sessions. saved tells whether the last answer was kept.
|
|
750
|
+
"""
|
|
751
|
+
TURNS, RECENT = 8, 2
|
|
752
|
+
QUESTION_BYTES, ANSWER_BYTES = 300, 1000
|
|
753
|
+
OLDER_QUESTION_BYTES, OLDER_ANSWER_BYTES = 160, 200
|
|
754
|
+
HISTORY_BYTES = 3200
|
|
755
|
+
|
|
756
|
+
def __init__(self, model, workspace, *, knowledge=None, memory=None, **options):
|
|
757
|
+
"""options are passed on to run_state for every task (max_steps, output, stream, and so on)."""
|
|
758
|
+
self.model, self.workspace, self.knowledge, self.options = model, workspace, knowledge, options
|
|
759
|
+
self.memory, self.saved = memory, False
|
|
760
|
+
self.reset()
|
|
761
|
+
|
|
762
|
+
def reset(self):
|
|
763
|
+
"""Forget the conversation so far: its turns, its retained evidence, and the last graph state."""
|
|
764
|
+
self.turns, self.evidence, self.last_state = [], [], {}
|
|
765
|
+
|
|
766
|
+
@staticmethod
|
|
767
|
+
def first_sentence(answer):
|
|
768
|
+
"""The opening of an answer, without the cited points listed after it."""
|
|
769
|
+
line = next((line.strip() for line in answer.splitlines() if line.strip()), "")
|
|
770
|
+
match = re.match(r"(.+?[.!?؟])(?:\s|$)", line)
|
|
771
|
+
return match[1] if match else line
|
|
772
|
+
|
|
773
|
+
def history(self):
|
|
774
|
+
"""The bounded record of earlier turns that run_state puts before the next task."""
|
|
775
|
+
def clip(text, limit):
|
|
776
|
+
"""Shorten text to limit UTF-8 bytes without splitting a character."""
|
|
777
|
+
raw = text.encode()
|
|
778
|
+
return text if len(raw) <= limit else raw[:limit].decode("utf-8", "ignore") + " …"
|
|
779
|
+
entries = []
|
|
780
|
+
for index, (question, answer) in enumerate(self.turns):
|
|
781
|
+
if index >= len(self.turns) - self.RECENT:
|
|
782
|
+
entries.append(f"Q: {clip(question, self.QUESTION_BYTES)}\nA: {clip(answer, self.ANSWER_BYTES)}")
|
|
783
|
+
else:
|
|
784
|
+
entries.append(f"Q: {clip(question, self.OLDER_QUESTION_BYTES)}\n"
|
|
785
|
+
f"A (summary): {clip(self.first_sentence(answer), self.OLDER_ANSWER_BYTES)}")
|
|
786
|
+
# Over budget: drop the oldest entries, always keeping the latest one.
|
|
787
|
+
while len(entries) > 1 and len("\n".join(entries).encode()) > self.HISTORY_BYTES:
|
|
788
|
+
entries.pop(0)
|
|
789
|
+
return "\n".join(entries)
|
|
790
|
+
|
|
791
|
+
def ask(self, task):
|
|
792
|
+
"""Run one task with this session's history and evidence, record its answer, and return the exit code."""
|
|
793
|
+
if self.turns and self.knowledge is not None:
|
|
794
|
+
self.knowledge.refresh() # Pick up files changed between questions.
|
|
795
|
+
# "My last commit" means something else tomorrow, so answers about changes are neither recalled nor saved.
|
|
796
|
+
# Test gaps and tours are rebuilt from the whole project each time, which a saved copy would not notice changing.
|
|
797
|
+
memory = (None if changes.requested(task) or insights.requested(task) or commit_messages.requested(task)
|
|
798
|
+
or guides.requested(task) or scans.requested(task) or blame.requested(task)
|
|
799
|
+
or (self.options.get("editor") is not None and coder.requested(task)) else self.memory)
|
|
800
|
+
notes = memory.recall(task, skip=[question for question, _ in self.turns]) if memory else []
|
|
801
|
+
evidence = self.evidence
|
|
802
|
+
if notes:
|
|
803
|
+
self.options.get("output", print)(f"Recalled {len(notes)} saved answer{'s' if len(notes) != 1 else ''} "
|
|
804
|
+
"from earlier sessions; the files they cite have not changed.")
|
|
805
|
+
evidence, _ = retain(evidence, self.memory.evidence(notes))
|
|
806
|
+
state = run_state(self.model, self.workspace, task, knowledge=self.knowledge, history=self.history(),
|
|
807
|
+
carried_evidence=evidence, notes=self.memory.text(notes) if notes else "", **self.options)
|
|
808
|
+
reply = state.get("reply") or {}
|
|
809
|
+
answer = (reply.get("content") or reply.get("message") or "") if reply.get("action") == "finish" else ""
|
|
810
|
+
self.turns = (self.turns + [(task, answer or "(no final answer)")])[-self.TURNS:]
|
|
811
|
+
self.evidence = state.get("search_evidence", [])
|
|
812
|
+
self.last_state = state
|
|
813
|
+
# Only an answer that passed its checks is worth keeping for another day.
|
|
814
|
+
self.saved = bool(memory and answer and state["exit_code"] == 0 and memory.add(task, answer))
|
|
815
|
+
return state["exit_code"]
|