Support tab (agents:support on a range with a question, instructions/support.md, its answer in labeling/auto/support/); the weather read from data/<STATION>/weather/ (pumped), no call to MeteoSwiss from the app; plots in mm (corr_x_mm, corr_y_mm); analyst instructions: the weather pumped, the targets in mm and their distance
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
60d10a282c
commit
161fb0212f
12 files changed
+414
-104
No files matched your search
@@ -0,0 +1,118 @@
|
||||
"""The Support tab of the Data page: the support of the agents repository (agents/, --agent agents:support), launched by
|
||||
`claude -p` on a range chosen in the page, with the user's question and its instructions (instructions/support.md). It
|
||||
answers as it judges best: itself, or through the analyst it launches on the range or a wider one. It writes in
|
||||
labeling/auto/support/<STATION>_<start>_<end>/ its answer (answer.md, its figures next to it); the labels of its analyst
|
||||
stay there, submitted nowhere. Then the user can write to it: the same session resumes (`claude -p --resume`).
|
||||
"""
|
||||
import json
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import analysis
|
||||
import station
|
||||
|
||||
FOLDER = station.LABELS / "auto" / "support"
|
||||
INSTRUCTIONS = station.ROOT / "instructions" / "support.md"
|
||||
REQUEST = """Station: data/{station}/. Range: {start} → {end} (UTC). Output folder: {out}/. INSTRUCTIONS: {instructions}.
|
||||
|
||||
Question: {question}"""
|
||||
TOOLS = "Read,Write,Edit,Bash,Glob,Grep"
|
||||
# the analyst it launches runs in the foreground, inside one of its commands: up to 3 h (claude -p ends with its turn)
|
||||
ENV = {"BASH_DEFAULT_TIMEOUT_MS": "10800000", "BASH_MAX_TIMEOUT_MS": "10800000"}
|
||||
|
||||
# name -> {"state": "running" | "done" | "error", "lines": [...], "request": {...}}
|
||||
supports = {}
|
||||
|
||||
|
||||
def launch(body):
|
||||
st, start, end = body.get("station"), body.get("start"), body.get("end")
|
||||
question = (body.get("question") or "").strip()
|
||||
station.checked_range(start, end)
|
||||
station.folder(st)
|
||||
if not question:
|
||||
raise station.Refusal("no question for the support")
|
||||
if not (analysis.AGENTS / "agents" / "support.md").exists():
|
||||
raise station.Refusal("no support in agents/ (the link: README.md)")
|
||||
name = f"{st}_{start[:16].replace(':', '')}_{end[:16].replace(':', '')}"
|
||||
with analysis.lock:
|
||||
if analysis._optimizing():
|
||||
raise station.Refusal(analysis.BUSY)
|
||||
out = FOLDER / name
|
||||
if out.exists(): # another question on the same range: the earlier one stays, next to it
|
||||
name += datetime.now(timezone.utc).strftime("_%H%M%S")
|
||||
out = FOLDER / name
|
||||
request = {"station": st, "start": start, "end": end, "question": question}
|
||||
supports[name] = {"state": "running", "lines": [], "request": request}
|
||||
(out / "work").mkdir(parents=True)
|
||||
(out / "request.json").write_text(json.dumps(request, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
prompt = REQUEST.format(station=st, start=start, end=end, out=out, instructions=INSTRUCTIONS, question=question)
|
||||
threading.Thread(target=work, args=(name, out, prompt), daemon=True).start()
|
||||
return {"name": name}
|
||||
|
||||
|
||||
def work(name, out, prompt, resume=None):
|
||||
"""A turn of the support: the request, or a message of the user in the same session (resume: its id)."""
|
||||
s = supports[name]
|
||||
try:
|
||||
analysis.run(s, out, prompt, resume, "support", TOOLS, ENV)
|
||||
s["state"] = "done"
|
||||
except Exception as e: # noqa: BLE001 — the error shows in the page, the server goes on
|
||||
s["lines"].append(f"Error: {e}")
|
||||
s["state"] = "error"
|
||||
|
||||
|
||||
def message(name, body):
|
||||
"""A message of the user to the support: the same session resumes (claude -p --resume)."""
|
||||
text, out = (body.get("text") or "").strip(), FOLDER / name
|
||||
state(name) # the name checked, the state read again after a restart
|
||||
s, session = supports[name], out / "work" / "session"
|
||||
if not text or not session.exists():
|
||||
raise station.Refusal("empty message, or the support has no session to resume")
|
||||
with analysis.lock:
|
||||
if analysis._optimizing():
|
||||
raise station.Refusal(analysis.BUSY)
|
||||
if s["state"] == "running":
|
||||
raise station.Refusal("the support is still working")
|
||||
s["state"] = "running"
|
||||
line = json.dumps({"type": "page", "text": text}, ensure_ascii=False) + "\n"
|
||||
with open(out / "work" / "log.jsonl", "a", encoding="utf-8") as log:
|
||||
log.write(line)
|
||||
s["lines"] += analysis.digest(line)
|
||||
prompt = f"{text}\n\n(If your answer changes, rewrite {out}/answer.md in full: the page shows it again.)"
|
||||
threading.Thread(target=work, args=(name, out, prompt, session.read_text()), daemon=True).start()
|
||||
return {}
|
||||
|
||||
|
||||
def _ended(out):
|
||||
"""The state of a request the server does not hold (after a restart): done with an answer, otherwise interrupted."""
|
||||
return "done" if (out / "answer.md").exists() else "interrupted"
|
||||
|
||||
|
||||
def state(name):
|
||||
out = FOLDER / name
|
||||
if "/" in name or name.startswith(".") or not (out / "request.json").is_file():
|
||||
raise station.Refusal("unknown support request")
|
||||
if name not in supports: # after a restart of the server, only the folder is left: the thread is read again in the log
|
||||
log = out / "work" / "log.jsonl"
|
||||
supports[name] = {"state": _ended(out), "request": json.loads((out / "request.json").read_text(encoding="utf-8")),
|
||||
"lines": [r for l in open(log, encoding="utf-8") for r in analysis.digest(l)] if log.exists() else []}
|
||||
s, r = supports[name], out / "answer.md"
|
||||
# report and submitted: the names of the Analysis panel, which the page reuses (no labels submitted here)
|
||||
return {"name": name, "state": s["state"], "lines": s["lines"], "submitted": None, "request": s["request"],
|
||||
"report": int(r.stat().st_mtime) if r.exists() else None, "dialogue": (out / "work" / "session").exists()}
|
||||
|
||||
|
||||
def list_supports():
|
||||
"""The history of the requests (the sidebar), the most recent first. Only those of the app: a folder of the support
|
||||
launched elsewhere has no request.json."""
|
||||
out = []
|
||||
for f in sorted(FOLDER.glob("*/request.json"), key=lambda f: f.parent.stat().st_mtime, reverse=True):
|
||||
name = f.parent.name
|
||||
s = supports.get(name) or {"state": _ended(f.parent), "request": json.loads(f.read_text(encoding="utf-8"))}
|
||||
out.append({"name": name, "state": s["state"]} | s["request"])
|
||||
return out
|
||||
|
||||
|
||||
def answer(name, dark):
|
||||
"""answer.md in HTML, served in the folder of the request: its relative images are found there."""
|
||||
return analysis._page(analysis.file(name, "answer.md", FOLDER).read_text(encoding="utf-8"), name, dark)
|
||||
Reference in new issue
Block a user