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:
maximeandClaude Opus 5.5 committed 2026-11-18 07:17:51 +01:00
1 parent 60d10a282c
commit 161fb0212f
12 files changed
+414 -104

No files matched your search

+25 -17
View File
@@ -81,23 +81,30 @@ def launch(body):
return {"name": name}
def run(a, out, prompt, resume, agent, tools, env=None):
"""A turn of an agent of the plugin by claude -p, from the root: its stream in work/log.jsonl and in a["lines"], its
session in work/session (resume: its id)."""
p = subprocess.Popen(["claude", "-p", prompt, "--plugin-dir", str(AGENTS), "--agent", f"agents:{agent}", *ISOLATED,
"--output-format", "stream-json", "--verbose",
"--allowedTools", tools, "--permission-mode", "acceptEdits", *station.links()]
+ (["--resume", resume] if resume else []),
cwd=station.ROOT, env=_env() | (env or {}), stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True)
with open(out / "work" / "log.jsonl", "a", encoding="utf-8") as log:
for line in p.stdout:
log.write(line)
a["lines"] += digest(line)
if '"subtype":"init"' in line: # the session, for the next messages
(out / "work" / "session").write_text(json.loads(line)["session_id"])
if p.wait():
raise RuntimeError(f"claude ended with code {p.returncode}")
def work(name, out, prompt, resume=None):
"""A turn of the analyst: the request, or a message of the user in the same session (resume: its id)."""
a = analyses[name]
try:
p = subprocess.Popen(["claude", "-p", prompt, "--plugin-dir", str(AGENTS), "--agent", "agents:analyst", *ISOLATED,
"--output-format", "stream-json", "--verbose",
"--allowedTools", "Read,Write,Bash", "--permission-mode", "acceptEdits", *station.links()]
+ (["--resume", resume] if resume else []),
cwd=station.ROOT, env=_env(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
with open(out / "work" / "log.jsonl", "a", encoding="utf-8") as log:
for line in p.stdout:
log.write(line)
a["lines"] += digest(line)
if '"subtype":"init"' in line: # the session, for the next messages
(out / "work" / "session").write_text(json.loads(line)["session_id"])
if p.wait():
raise RuntimeError(f"claude ended with code {p.returncode}")
run(a, out, prompt, resume, "analyst", "Read,Write,Bash")
a["submitted"] = submit(a["station"], name, out)
a["state"] = "done"
except Exception as e: # noqa: BLE001 — the error shows in the page, the server goes on
@@ -234,10 +241,11 @@ def list_analyses():
return out
def file(name, path):
"""A file of the folder of the analysis (the report, its figures), never outside."""
f = (FOLDER / name / path).resolve()
if not f.is_file() or not f.is_relative_to(FOLDER.resolve()):
def file(name, path, folder=None):
"""A file of the folder of the analysis (the report, its figures; or of a support request), never outside."""
folder = folder or FOLDER
f = (folder / name / path).resolve()
if not f.is_file() or not f.is_relative_to(folder.resolve()):
raise station.Refusal("unknown file")
return f
+70 -1
View File
@@ -46,6 +46,8 @@ def check_server():
assert call("/api/labels", {"station": "x"}, {"Content-Type": "text/plain"}) == 403
assert call("/api/stations") == 200
assert call("/api/analyses") == 200
assert call("/api/support") == 200
assert call("/api/support", {"station": "x"}) == 400
assert call("/api/analyses/UNKNOWN/optimize", {}) == 400
finally:
srv.should_exit = True
@@ -308,7 +310,74 @@ def check_validation():
analysis.analyses.clear()
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation]
def check_support():
# "Ask the support" then a message (support.launch, support.message), without claude: the support of the agents
# repository, its request (the question, its instructions, its absolute folder), the long commands it is given, the
# resumption of its session, its answer in the page; the state read again after a restart
import analysis
import support
launched = []
class FakeProcess:
returncode = 0
def __init__(self, args, *a, **k):
launched.append((args, k))
self.stdout = iter(['{"type":"system","subtype":"init","session_id":"s-1"}\n'])
def wait(self):
return 0
root = temp_folder()
before = support.FOLDER, analysis.subprocess.Popen, analysis.AGENTS
support.FOLDER, analysis.AGENTS, analysis.subprocess.Popen = root / "support", root / "agents", FakeProcess
key = os.environ.get("ANTHROPIC_API_KEY")
os.environ["ANTHROPIC_API_KEY"] = "test-key"
ask = {"station": "NORDEND", "start": "2026-11-05T06:00Z", "end": "2026-11-05T12:00Z", "question": "Why the jump?"}
try:
assert "agents/" in refuses(support.launch, ask)
(analysis.AGENTS / "agents").mkdir(parents=True)
(analysis.AGENTS / "agents" / "support.md").write_text("support")
assert "question" in refuses(support.launch, ask | {"question": " "})
name = support.launch(ask)["name"]
while support.supports[name]["state"] == "running":
time.sleep(0.05)
assert support.state(name)["state"] == "done" and support.state(name)["report"] is None, support.state(name)
args, k = launched[0]
assert args[args.index("--agent") + 1] == "agents:support" and "Edit" in args[args.index("--allowedTools") + 1], args
assert "ANTHROPIC_API_KEY" not in k["env"] and k["env"]["BASH_MAX_TIMEOUT_MS"] == "10800000", sorted(k["env"])
out = support.FOLDER / name
assert f"Output folder: {out}/." in args[2] and f"INSTRUCTIONS: {support.INSTRUCTIONS}." in args[2] \
and args[2].endswith("Question: Why the jump?") and support.INSTRUCTIONS.is_file(), args[2]
assert (out / "work" / "session").read_text() == "s-1"
assert support.launch(ask)["name"].startswith(name + "_") # another question on the same range, next to it
(out / "answer.md").write_text("# NORDEND: a jump\n\n![curves](fig.png)")
(out / "fig.png").write_bytes(b"png")
assert support.state(name)["report"] and "<h1>NORDEND: a jump</h1>" in support.answer(name, False)
assert analysis.file(name, "fig.png", support.FOLDER).is_file()
refuses(analysis.file, name, "../../agents/agents/support.md", support.FOLDER)
while any(s["state"] == "running" for s in support.supports.values()):
time.sleep(0.05)
support.message(name, {"text": "And the night before?"})
while support.supports[name]["state"] == "running":
time.sleep(0.05)
args = launched[-1][0]
assert args[args.index("--resume") + 1] == "s-1" and args[2].startswith("And the night before?"), args
support.supports.clear() # after a restart: the thread read again in the log, done with its answer
s = support.state(name)
assert s["state"] == "done" and s["lines"] == ["› And the night before?"], s
assert {x["name"]: x["state"] for x in support.list_supports()}[name] == "done" # the sidebar
refuses(support.state, "../analyses")
finally:
os.environ.pop("ANTHROPIC_API_KEY")
if key is not None:
os.environ["ANTHROPIC_API_KEY"] = key
shutil.rmtree(root)
support.FOLDER, analysis.subprocess.Popen, analysis.AGENTS = before
support.supports.clear()
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation, check_support]
if __name__ == "__main__":
name = sys.argv[1] if len(sys.argv) > 1 else None
+34 -1
View File
@@ -2,7 +2,7 @@
The FastAPI server serves the built React page (app/web/dist, `npm run build` in app/web) and the API under /api.
The Data page reads data/ and the labels of labeling/ (station.py); its Analysis tab launches the analyst, and the
optimization of the detectors (analysis.py).
optimization of the detectors (analysis.py); its Support tab, the support (support.py).
Settings: AIMSIGHT_DATA (data), AIMSIGHT_LABELS (labels), AIMSIGHT_PORT (port, 8770).
"""
import json
@@ -20,6 +20,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
import analysis
import station
import support
from fastapi.staticfiles import StaticFiles
APP = Path(__file__).resolve().parents[1]
@@ -167,6 +168,38 @@ def analysis_file(name: str, path: str):
return FileResponse(analysis.file(name, path))
# --- the Support tab of the Data page (support.py): the support launched by claude -p on a range, with a question
@app.post("/api/support")
def launch_support(body: dict):
return support.launch(body)
@app.get("/api/support")
def supports():
return support.list_supports()
@app.get("/api/support/{name}")
def support_state(name: str):
return support.state(name)
@app.post("/api/support/{name}/message")
def support_message(name: str, body: dict):
return support.message(name, body)
@app.get("/api/support/{name}/report.html")
def support_answer(name: str, dark: bool = False):
return HTMLResponse(support.answer(name, dark))
@app.get("/api/support/{name}/{path:path}")
def support_file(name: str, path: str):
return FileResponse(analysis.file(name, path, support.FOLDER))
if PAGE.is_dir():
app.mount("/", StaticFiles(directory=PAGE, html=True), name="page")
else:
+21 -30
View File
@@ -3,8 +3,8 @@
Data are read as the agents read them, tools/scripts/data.py (the tools repository, through the tools/ link); the detectors'
events are those of detectors/scripts/categories.py (window); the rules of the labels and what the client is told, those of
labeling/scripts (validate, ids, client). Read-only on data/, filled only by pump.sh; writes only in
labeling/auto/. What brings data in (the pumping, the list of the tracked stations, the weather) is in
~/aimsight-data, called as it is (extraction/pumping.py, weather/meteoswiss.py).
labeling/auto/. What brings data in (the pumping, the list of the tracked stations) is in ~/aimsight-data, called as it
is (extraction/pumping.py); the weather is pumped with the data, data/<STATION>/weather/ (data.load_weather).
"""
import bisect
import functools
@@ -18,15 +18,14 @@ from datetime import datetime, timedelta
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
# ~/aimsight-data, the repository of data/: the methods that bring data in (the pumping, the weather), called as they are
# ~/aimsight-data, the repository of data/: the method that brings data in (the pumping, the weather with it), called as it is
DATA_REPOSITORY = Path(os.environ.get("AIMSIGHT_DATA", ROOT / "data")).resolve().parent
sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "scripts"), str(ROOT / "labeling" / "scripts"),
str(DATA_REPOSITORY / "extraction"), str(DATA_REPOSITORY / "weather")]
str(DATA_REPOSITORY / "extraction")]
import categories # noqa: E402
import client # noqa: E402 (labeling: what the client is told of an event)
import data # noqa: E402
import ids # noqa: E402 (labeling: the stable id of the labels)
import meteoswiss # noqa: E402
import pumping # noqa: E402
import validate # noqa: E402 (labeling: the rules of a label)
@@ -49,6 +48,7 @@ POSE = (("pan", "#1a1a19"), ("tilt", "#8a8a85"), ("rotation", "#b5651d"))
PLOTS = (("error_value", "Error value"), ("x", "X [px]"), ("y", "Y [px]"),
("relative_x", "Relative Horizontal Shift"), ("relative_y", "Relative Vertical Shift"),
("corr_x", "Relative Corrected Horizontal Shift"), ("corr_y", "Relative Corrected Vertical Shift"),
("corr_x_mm", "Relative Corrected Horizontal Shift [mm]"), ("corr_y_mm", "Relative Corrected Vertical Shift [mm]"),
("reproj_err", "References (reproj. error)"))
QUALITY = (("peak", "Quality: Peak"), ("flux", "Quality: Flux"), ("sharpness", "Quality: Sharpness"),
("fwhm", "Quality: FWHM [px]"), ("dominance", "Quality: Dominance"), ("snr", "Quality: SNR"))
@@ -177,18 +177,17 @@ def curves(station, start, end):
if not out:
raise Refusal(f"no measurement of {station} in this range")
result = {"A": data.iso(a), "B": data.iso(b), "T": T, "plots": out}
if place := pumping.tracked().get(station): # the weather at the position of the station (stations.txt), if it has one
try:
label, times, plots = weather(place, a, b)
T.update(times)
out += plots
result["weather"] = label
except Refusal as e:
result["weather"] = f"unavailable ({e})"
if hours := [h for h in data.load_weather(d) if a <= h["t"] < b]: # the weather pumped with the data, if any
label, times, plots = weather(hours)
T.update(times)
out += plots
result["weather"] = label
elif pumping.tracked().get(station):
result["weather"] = "none pumped in this range (see the pumping log)"
return result
# --- the Data page, the weather at a place (weather/meteoswiss.py of ~/aimsight-data): plots "Weather: …" on the range of the curves
# --- the Data page, the weather pumped in data/<STATION>/weather/ (extraction/weather.py of ~/aimsight-data): plots "Weather: …"
WEATHER = (("Precipitation (mm/h)", "precipitation_mm"), ("Temperature (°C)", "temperature_c"), ("Humidity (%)", "humidity_pct"),
("Wind (km/h)", "wind_speed_kmh", "wind_gust_kmh"), ("Wind direction (deg)", "wind_direction_deg"),
@@ -196,29 +195,21 @@ WEATHER = (("Precipitation (mm/h)", "precipitation_mm"), ("Temperature (°C)", "
("Global radiation (W/m²)", "global_radiation_wm2"), ("Snow depth (cm)", "snow_depth_cm"))
def weather(place, a, b):
"""-> (label, T, plots) as curves(): the hourly values of the MeteoSwiss station nearest to the place ("lat,lon" or
a Swiss place name), over [a, b); their times under T["system:weather"], so that the target filters ignore them."""
try:
where, hours = meteoswiss.hourly(place, a, b)
except LookupError as e:
raise Refusal(str(e))
except OSError as e:
raise Refusal(f"MeteoSwiss unreachable: {e}")
times = list(hours)
def weather(hours):
"""[hour] of data.load_weather, not empty -> (label, T, plots) as curves(); their times under T["system:weather"], so
that the target filters ignore them; the label: where the last hour was measured."""
plots = []
for title, *columns in WEATHER:
traces = [{"name": c.rsplit("_", 1)[0].replace("_", " "), "t": "system:weather", "y": y,
"mode": "markers" if "direction" in c else "lines",
"line": {"width": 1.2, "color": COLORS[i], "shape": "hv" if c == "precipitation_mm" else "linear"}}
for i, (c, y) in enumerate((c, [hours[t][c] for t in times]) for c in columns) if any(v is not None for v in y)]
for i, (c, y) in enumerate((c, [h.get(c) for h in hours]) for c in columns) if any(v is not None for v in y)]
if traces:
plots.append({"title": "Weather: " + title, "traces": traces})
if not plots:
raise Refusal(f"no MeteoSwiss measurement at {where['name']} in this range")
return (f"{where['place']} → MeteoSwiss {where['station']} {where['name']}, {where['distance_km']:.1f} km, "
f"{where['height_m']:.0f} m",
{"system:weather": [t.strftime("%Y-%m-%d %H:%M") for t in times]}, plots)
w = hours[-1]
return (f"{w['place']} → MeteoSwiss {w['station']} {w['station_name']}, {w['distance_km']} km, {w['height_m']} m"
+ " (no measurement in this range)" * (not plots),
{"system:weather": [h["t"].strftime("%Y-%m-%d %H:%M") for h in hours]}, plots)
# --- the tracked stations and the pumping: extraction/pumping.py of ~/aimsight-data
+118
View File
@@ -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)