@lmmslab/harness 0.0.0-stage → 0.81.0
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.
- package/LICENSE +21 -0
- package/README.md +124 -2
- package/bin/harness.js +71 -0
- package/package.json +34 -4
- package/python/harness/README.md +72 -0
- package/python/harness/__init__.py +8 -0
- package/python/harness/__main__.py +3 -0
- package/python/harness/bench.py +124 -0
- package/python/harness/builtin/benches/README.md +5 -0
- package/python/harness/builtin/benches/none/bench.toml +6 -0
- package/python/harness/builtin/configs/README.md +26 -0
- package/python/harness/builtin/configs/assistant.toml +11 -0
- package/python/harness/builtin/configs/default.toml +33 -0
- package/python/harness/builtin/configs/deploy/example-api.toml +10 -0
- package/python/harness/builtin/configs/models/deepseek-api.toml +21 -0
- package/python/harness/builtin/configs/models/deepseek-flash.toml +12 -0
- package/python/harness/builtin/configs/models/grok-low.toml +8 -0
- package/python/harness/builtin/configs/models/grok-medium.toml +43 -0
- package/python/harness/builtin/configs/models/opus-5.5.toml +11 -0
- package/python/harness/builtin/environment/README.md +53 -0
- package/python/harness/builtin/environment/constraints.txt +31 -0
- package/python/harness/builtin/model-settings.js +143 -0
- package/python/harness/builtin/prompts/conversation/core.md +5 -0
- package/python/harness/builtin/prompts/conversation/pack.toml +12 -0
- package/python/harness/builtin/prompts/core/core.md +88 -0
- package/python/harness/builtin/prompts/core/pack.toml +9 -0
- package/python/harness/builtin/prompts/reflect/core.md +45 -0
- package/python/harness/builtin/prompts/reflect/pack.toml +7 -0
- package/python/harness/builtin/prompts/shared/agent-skills.md +5 -0
- package/python/harness/builtin/prompts/shared/agents.md +14 -0
- package/python/harness/builtin/prompts/shared/checklist.md +21 -0
- package/python/harness/builtin/prompts/shared/entries.md +86 -0
- package/python/harness/builtin/prompts/shared/environments.md +21 -0
- package/python/harness/builtin/prompts/shared/learning-goal.md +31 -0
- package/python/harness/builtin/prompts/shared/learning.md +27 -0
- package/python/harness/builtin/prompts/shared/mcp.md +9 -0
- package/python/harness/builtin/prompts/shared/world.md +1 -0
- package/python/harness/builtin/skills/README.md +10 -0
- package/python/harness/builtin/skills/agents/__init__.py +88 -0
- package/python/harness/builtin/skills/agents/skill.toml +11 -0
- package/python/harness/builtin/skills/checklist/__init__.py +32 -0
- package/python/harness/builtin/skills/checklist/skill.toml +9 -0
- package/python/harness/builtin/skills/conversation/__init__.py +23 -0
- package/python/harness/builtin/skills/conversation/skill.toml +8 -0
- package/python/harness/builtin/skills/entries/__init__.py +62 -0
- package/python/harness/builtin/skills/entries/skill.toml +8 -0
- package/python/harness/builtin/skills/environments/__init__.py +69 -0
- package/python/harness/builtin/skills/environments/skill.toml +9 -0
- package/python/harness/builtin/skills/experience/__init__.py +27 -0
- package/python/harness/builtin/skills/experience/skill.toml +9 -0
- package/python/harness/builtin/skills/instructions/__init__.py +29 -0
- package/python/harness/builtin/skills/instructions/skill.toml +9 -0
- package/python/harness/builtin/skills/learning/__init__.py +189 -0
- package/python/harness/builtin/skills/learning/skill.toml +7 -0
- package/python/harness/builtin/skills/mcp/__init__.py +54 -0
- package/python/harness/builtin/skills/mcp/skill.toml +10 -0
- package/python/harness/builtin/skills/memory/__init__.py +130 -0
- package/python/harness/builtin/skills/memory/skill.toml +13 -0
- package/python/harness/builtin/skills/verify/__init__.py +31 -0
- package/python/harness/builtin/skills/verify/skill.toml +7 -0
- package/python/harness/builtin/third_party/sources.toml +40 -0
- package/python/harness/cli.py +1182 -0
- package/python/harness/config/__init__.py +224 -0
- package/python/harness/config/agent.py +777 -0
- package/python/harness/core/__init__.py +52 -0
- package/python/harness/core/artifacts.py +46 -0
- package/python/harness/core/codec.py +160 -0
- package/python/harness/core/contracts.py +75 -0
- package/python/harness/core/episodes.py +150 -0
- package/python/harness/core/format.py +51 -0
- package/python/harness/core/http.py +124 -0
- package/python/harness/core/lanes.py +324 -0
- package/python/harness/core/linux_sandbox.py +55 -0
- package/python/harness/core/media.py +96 -0
- package/python/harness/core/memory.py +147 -0
- package/python/harness/core/ports.py +63 -0
- package/python/harness/core/procs.py +227 -0
- package/python/harness/core/remote.py +102 -0
- package/python/harness/core/spans.py +166 -0
- package/python/harness/core/trace.py +139 -0
- package/python/harness/core/wait.py +12 -0
- package/python/harness/core/worker.py +388 -0
- package/python/harness/core/worker_pipe.py +119 -0
- package/python/harness/embodiments.py +217 -0
- package/python/harness/extensions.py +112 -0
- package/python/harness/host/__init__.py +397 -0
- package/python/harness/host/client.py +201 -0
- package/python/harness/host/http.py +720 -0
- package/python/harness/host/listing.py +68 -0
- package/python/harness/host/server.py +189 -0
- package/python/harness/host/sessions.py +406 -0
- package/python/harness/host/tasks.py +1308 -0
- package/python/harness/host/workers.py +257 -0
- package/python/harness/host/workspaces.py +256 -0
- package/python/harness/model_list.py +117 -0
- package/python/harness/packages/__init__.py +73 -0
- package/python/harness/packages/addons.py +121 -0
- package/python/harness/packages/archive.py +122 -0
- package/python/harness/packages/describe.py +46 -0
- package/python/harness/packages/environments.py +448 -0
- package/python/harness/packages/fetch.py +57 -0
- package/python/harness/packages/manager.py +587 -0
- package/python/harness/packages/manifest.py +221 -0
- package/python/harness/packages/migrate.py +68 -0
- package/python/harness/packages/provision.py +38 -0
- package/python/harness/packages/registry.py +275 -0
- package/python/harness/packages/resolve.py +89 -0
- package/python/harness/packages/sources.py +141 -0
- package/python/harness/packages/state.py +213 -0
- package/python/harness/packages/versions.py +112 -0
- package/python/harness/paths.py +218 -0
- package/python/harness/providers.py +303 -0
- package/python/harness/runtime/__init__.py +8 -0
- package/python/harness/runtime/decision/__init__.py +1 -0
- package/python/harness/runtime/decision/loop.py +198 -0
- package/python/harness/runtime/decision/messages.py +271 -0
- package/python/harness/runtime/decision/model.py +424 -0
- package/python/harness/runtime/decision/prompts.py +248 -0
- package/python/harness/runtime/decision/protocol.py +169 -0
- package/python/harness/runtime/decision/thoughts.py +199 -0
- package/python/harness/runtime/events.py +213 -0
- package/python/harness/runtime/execution/__init__.py +1 -0
- package/python/harness/runtime/execution/attached.py +96 -0
- package/python/harness/runtime/execution/control.py +211 -0
- package/python/harness/runtime/execution/entries.py +665 -0
- package/python/harness/runtime/execution/kernel.py +811 -0
- package/python/harness/runtime/execution/noenv.py +84 -0
- package/python/harness/runtime/execution/results.py +40 -0
- package/python/harness/runtime/execution/session.py +871 -0
- package/python/harness/runtime/execution/skills.py +436 -0
- package/python/harness/runtime/learning/__init__.py +1 -0
- package/python/harness/runtime/learning/active.py +314 -0
- package/python/harness/runtime/learning/experience.py +48 -0
- package/python/harness/runtime/learning/fixtures.py +167 -0
- package/python/harness/runtime/learning/learner.py +651 -0
- package/python/harness/runtime/learning/library.py +504 -0
- package/python/harness/runtime/learning/reflect.py +151 -0
- package/python/harness/runtime/learning/usage.py +30 -0
- package/python/harness/runtime/learning/views.py +89 -0
- package/python/harness/runtime/reactive/__init__.py +1 -0
- package/python/harness/runtime/reactive/rules.py +549 -0
- package/python/harness/runtime/safety/__init__.py +1 -0
- package/python/harness/runtime/safety/approval.py +131 -0
- package/python/harness/runtime/safety/input.py +62 -0
- package/python/harness/runtime/safety/isolation.py +419 -0
- package/python/harness/runtime/safety/shield.py +129 -0
- package/python/harness/runtime/status.py +23 -0
- package/python/harness/runtime/task/__init__.py +7 -0
- package/python/harness/runtime/task/context.py +431 -0
- package/python/harness/runtime/task/delegation.py +468 -0
- package/python/harness/runtime/task/environments.py +268 -0
- package/python/harness/runtime/task/run.py +2878 -0
- package/python/harness/runtime/tick.py +909 -0
- package/python/harness/sdk/__init__.py +281 -0
- package/python/harness/services/__init__.py +6 -0
- package/python/harness/services/broker.py +35 -0
- package/python/harness/services/connectors.py +88 -0
- package/python/harness/services/mcp.py +298 -0
- package/python/harness/services/mcp_stdio.py +131 -0
- package/python/harness/services/placement.py +82 -0
- package/python/harness/services/registry.py +156 -0
- package/python/harness/settings.py +536 -0
- package/python/harness/terminal.py +79 -0
- package/python/harness/transcript.py +297 -0
- package/python/harness/tui/__init__.py +68 -0
- package/python/harness/tui/chat.py +1181 -0
- package/python/harness/tui/pty.py +81 -0
- package/python/harness/tui/renderer.py +45 -0
- package/python/harness/tui/timeline_rows.py +58 -0
- package/python/harness/tui/views.py +434 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""The shared conversation list for the app and taptab."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from ..core import episodes as runs
|
|
7
|
+
from . import sessions
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def conversations(server) -> list[dict]:
|
|
11
|
+
"""The app's conversations, and the other sessions the server runs: each with its session's
|
|
12
|
+
id, what started it (`frontend`), what it waits for, what it spent (`usage`) and its agents;
|
|
13
|
+
the app's own with their meta.json (title, pin)."""
|
|
14
|
+
app, listed = server.app, {row["run"]: row for row in server.conversations.sessions()}
|
|
15
|
+
index = server.conversations.index
|
|
16
|
+
history = {row["run"]: row for row in sessions.history(index)} if index else {}
|
|
17
|
+
rows = []
|
|
18
|
+
for episode in runs.list_episodes(app.conversations_dir, limit=500):
|
|
19
|
+
directory = app.conversations_dir / episode["run"]
|
|
20
|
+
try:
|
|
21
|
+
meta = json.loads((directory / "meta.json").read_text(encoding="utf-8"))
|
|
22
|
+
except (OSError, ValueError):
|
|
23
|
+
meta = {}
|
|
24
|
+
run = directory.relative_to(server.root).as_posix()
|
|
25
|
+
conversation, session = server.conversations.get(run), listed.get(run)
|
|
26
|
+
identity = session or history.get(run) or {}
|
|
27
|
+
status = (conversation.status if conversation else
|
|
28
|
+
sessions.ended_status(directory) if not episode["live"] else None)
|
|
29
|
+
rows.append({"run": run, "title": meta.get("title") or episode["run"], "text": meta.get("text"),
|
|
30
|
+
"created": meta.get("created"), "pinned": bool(meta.get("pinned")),
|
|
31
|
+
"model": meta.get("model"), "model_entry": meta.get("model_entry"), "reasoning_effort": meta.get("reasoning_effort"),
|
|
32
|
+
"profile": meta.get("profile"), "modified": episode["modified"],
|
|
33
|
+
"status": status, "controllable": (conversation is not None and sessions.live(status)
|
|
34
|
+
and not identity.get("metadata", {}).get("observed")),
|
|
35
|
+
"starting": app.starting.get(run), "frontend": identity.get("frontend", "app"),
|
|
36
|
+
"workspace": _workspace(app, run, meta), "session": identity.get("id"),
|
|
37
|
+
"kind": identity.get("kind", "harness"), "project": identity.get("project"),
|
|
38
|
+
"metadata": identity.get("metadata", {}), "capabilities": identity.get("capabilities"),
|
|
39
|
+
"waiting": session["waiting"] if session else None,
|
|
40
|
+
"usage": session["usage"] if session else None,
|
|
41
|
+
"agents": session["agents"] if session else []})
|
|
42
|
+
mine = app.conversations_dir.resolve()
|
|
43
|
+
for session in listed.values():
|
|
44
|
+
directory = Path(session["directory"]) if session["directory"] else None
|
|
45
|
+
if directory is None or directory == mine or mine in directory.parents:
|
|
46
|
+
continue
|
|
47
|
+
trace = directory / "events.jsonl"
|
|
48
|
+
status = next((agent["status"] for agent in session["agents"] if agent["depth"] == 0), None)
|
|
49
|
+
rows.append({"run": session["run"], "title": session["title"] or session["id"], "text": None,
|
|
50
|
+
"created": session["created"], "pinned": False, "model": None, "reasoning_effort": None,
|
|
51
|
+
"profile": None, "modified": trace.stat().st_mtime if trace.is_file() else session["created"],
|
|
52
|
+
"status": status, "controllable": status is not None and sessions.live(status),
|
|
53
|
+
"starting": None, "frontend": session["frontend"], "workspace": None, "session": session["id"],
|
|
54
|
+
"kind": session["kind"], "project": session["project"],
|
|
55
|
+
"metadata": session["metadata"], "capabilities": session["capabilities"],
|
|
56
|
+
"waiting": session["waiting"], "usage": session["usage"], "agents": session["agents"]})
|
|
57
|
+
# Pinned ones first; each group newest first.
|
|
58
|
+
return sorted(rows, key=lambda row: (not row["pinned"], -(row["modified"] or 0)))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _workspace(app, run, meta) -> dict | None:
|
|
62
|
+
"""A conversation's workspace: its kind, and the worker serving it while one does."""
|
|
63
|
+
kind = app._kinds.get(run) or meta.get("workspace")
|
|
64
|
+
if kind is None:
|
|
65
|
+
return None
|
|
66
|
+
workspaces = app.available_workspaces()
|
|
67
|
+
worker = workspaces.of(run) if workspaces is not None else None
|
|
68
|
+
return {"kind": kind, **({"id": worker.id, "status": worker.status} if worker is not None else {})}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""The session host's process (`python -m harness.host.server [--port N]`): the assistant's server over
|
|
2
|
+
DATA, with the sessions of every frontend as a tree, an index of them, and an end once
|
|
3
|
+
nothing is open and nobody asks (see host/__init__.py)."""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import signal
|
|
9
|
+
import sys
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
from .tasks import TaskHost, TaskHandler, TaskServer
|
|
14
|
+
from ..core.episodes import new_name
|
|
15
|
+
from ..core.ports import free_port
|
|
16
|
+
from ..core import atomic_write
|
|
17
|
+
from ..core.wait import wait_until
|
|
18
|
+
from ..paths import data
|
|
19
|
+
from . import PORT, PORT_ENV, address_file, identity, idle_seconds, index_file, read_address, _reachable
|
|
20
|
+
from .sessions import Sessions, history, live
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class HostHandler(TaskHandler):
|
|
24
|
+
def get_host(self, query):
|
|
25
|
+
self._json(self.server.state())
|
|
26
|
+
|
|
27
|
+
def post_host_stop(self, body):
|
|
28
|
+
self.server.stop(force=bool(body.get("force")))
|
|
29
|
+
self._json({"ok": True})
|
|
30
|
+
|
|
31
|
+
def get_sessions(self, query):
|
|
32
|
+
rows = self.server.conversations.sessions()
|
|
33
|
+
if (query.get("all") or ["0"])[0] in ("1", "true"):
|
|
34
|
+
rows += history(self.server.conversations.index, skip={row["id"] for row in rows})
|
|
35
|
+
limit = int((query.get("limit") or ["50"])[0])
|
|
36
|
+
self._json({"host": self.server.state(), "sessions": rows[:limit] if limit > 0 else rows})
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class HostServer(TaskServer):
|
|
40
|
+
"""The app's server as the session host: sessions started by any client, idle
|
|
41
|
+
tracking (touch(), the watchdog) and stop()."""
|
|
42
|
+
|
|
43
|
+
handler_class = HostHandler
|
|
44
|
+
|
|
45
|
+
def __init__(self, address, app: TaskHost, token: str | None = None, idle: float | None = None):
|
|
46
|
+
super().__init__(address, app, token=token)
|
|
47
|
+
self.conversations = Sessions(index=index_file(app.directory), default_frontend="app")
|
|
48
|
+
self.conversations.notes = lambda run: app.starting.get(run)
|
|
49
|
+
self.idle = idle_seconds() if idle is None else idle
|
|
50
|
+
self.started = time.time()
|
|
51
|
+
self._last = time.monotonic()
|
|
52
|
+
self.background = {}
|
|
53
|
+
|
|
54
|
+
def start_background(self):
|
|
55
|
+
from ..extensions import hosts
|
|
56
|
+
|
|
57
|
+
self.conversations.registered = self._registered
|
|
58
|
+
for package, module in hosts():
|
|
59
|
+
factory = getattr(module, "background", None)
|
|
60
|
+
if factory is not None:
|
|
61
|
+
service = factory(self)
|
|
62
|
+
self.background[package.name] = service
|
|
63
|
+
service.start()
|
|
64
|
+
|
|
65
|
+
def _registered(self, run, conversation):
|
|
66
|
+
for service in self.background.values():
|
|
67
|
+
registered = getattr(service, "registered", None)
|
|
68
|
+
if registered is not None:
|
|
69
|
+
registered(run, conversation)
|
|
70
|
+
|
|
71
|
+
def info(self) -> dict:
|
|
72
|
+
return {**super().info(), "host": True}
|
|
73
|
+
|
|
74
|
+
def touch(self) -> None:
|
|
75
|
+
self._last = time.monotonic()
|
|
76
|
+
|
|
77
|
+
def running(self) -> bool:
|
|
78
|
+
"""Whether a session is open (or one is being prepared)."""
|
|
79
|
+
return self.conversations.running() or any(not str(note).startswith("error")
|
|
80
|
+
for note in self.app.starting.values())
|
|
81
|
+
|
|
82
|
+
def state(self) -> dict:
|
|
83
|
+
host, port = self.server_address[:2]
|
|
84
|
+
return {**identity(), "pid": os.getpid(), "url": f"http://127.0.0.1:{port}", "started": self.started,
|
|
85
|
+
"idle_seconds": round(time.monotonic() - self._last, 1), "idle_limit": self.idle,
|
|
86
|
+
"running": self.running(), "open": sum(1 for row in self.conversations.sessions() if row["live"])}
|
|
87
|
+
|
|
88
|
+
def session_directory(self, request: dict, config, seed: int):
|
|
89
|
+
"""Where the client asked (an absolute path: its own `--output`), else
|
|
90
|
+
DATA/sessions/<time>-<task>/seed-<seed>; the run is the session's id."""
|
|
91
|
+
given = request.get("directory")
|
|
92
|
+
if given:
|
|
93
|
+
directory = Path(given)
|
|
94
|
+
if not directory.is_absolute():
|
|
95
|
+
raise ValueError("directory must be an absolute path")
|
|
96
|
+
else:
|
|
97
|
+
directory = self.root / "sessions" / new_name(config.task) / f"seed-{seed}"
|
|
98
|
+
return directory, None
|
|
99
|
+
|
|
100
|
+
def start_conversation(self, request: dict) -> str:
|
|
101
|
+
# The client's model keys the host lacks (a key exported in the client's shell only).
|
|
102
|
+
for name, value in (request.get("environment") or {}).items():
|
|
103
|
+
if str(name).endswith("_API_KEY") and value and not os.environ.get(name):
|
|
104
|
+
os.environ[name] = str(value)
|
|
105
|
+
return super().start_conversation(request)
|
|
106
|
+
|
|
107
|
+
def stop(self, force: bool = False) -> None:
|
|
108
|
+
"""Exit (after the answer to the request that asked): refused while a session is
|
|
109
|
+
open, unless `force`, which ends them first."""
|
|
110
|
+
if self.running():
|
|
111
|
+
if not force:
|
|
112
|
+
raise ValueError("sessions are open: end them first (/sessions and /end in harness), or force")
|
|
113
|
+
for conversation in list(self.conversations.values()):
|
|
114
|
+
if live(conversation.status):
|
|
115
|
+
conversation.close()
|
|
116
|
+
threading.Thread(target=self.shutdown, name="host-stop", daemon=True).start()
|
|
117
|
+
|
|
118
|
+
def watch(self) -> None:
|
|
119
|
+
"""Exit once no session is open and no client asked for anything for `idle` seconds."""
|
|
120
|
+
step = max(0.2, min(30.0, self.idle / 4))
|
|
121
|
+
while True:
|
|
122
|
+
time.sleep(step)
|
|
123
|
+
if self.running() or any(service.keep_alive() for service in self.background.values()):
|
|
124
|
+
self.touch()
|
|
125
|
+
elif time.monotonic() - self._last > self.idle:
|
|
126
|
+
print(json.dumps({"host": "idle", "seconds": self.idle}), flush=True)
|
|
127
|
+
self.shutdown()
|
|
128
|
+
return
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def serve(port: int | None = None, idle: float | None = None) -> int:
|
|
132
|
+
"""Run the host until it is idle or stopped; refused while another host answers."""
|
|
133
|
+
from ..extensions import focus
|
|
134
|
+
|
|
135
|
+
other = _reachable(read_address())
|
|
136
|
+
if other is not None:
|
|
137
|
+
raise RuntimeError(f"a session host already runs at {other.url} (process {other.pid})")
|
|
138
|
+
if port is None:
|
|
139
|
+
port = int(os.environ.get(PORT_ENV) or PORT)
|
|
140
|
+
app = TaskHost(data())
|
|
141
|
+
try:
|
|
142
|
+
server = HostServer(("127.0.0.1", port), app, idle=idle)
|
|
143
|
+
except OSError:
|
|
144
|
+
server = HostServer(("127.0.0.1", free_port()), app, idle=idle)
|
|
145
|
+
path = address_file(app.directory)
|
|
146
|
+
atomic_write(path, json.dumps({**server.state(), "token": server.token}), private=True)
|
|
147
|
+
app.focus_chat = focus
|
|
148
|
+
if hasattr(signal, "SIGTERM"):
|
|
149
|
+
signal.signal(signal.SIGTERM, lambda *_: threading.Thread(target=server.shutdown, daemon=True).start())
|
|
150
|
+
print(json.dumps({"host": server.state()["url"], "pid": os.getpid(), "data": str(app.directory)}), flush=True)
|
|
151
|
+
try:
|
|
152
|
+
with server:
|
|
153
|
+
server.start_background()
|
|
154
|
+
threading.Thread(target=server.watch, name="host-idle", daemon=True).start()
|
|
155
|
+
server.serve_forever()
|
|
156
|
+
except KeyboardInterrupt:
|
|
157
|
+
print("stopped", file=sys.stderr)
|
|
158
|
+
finally:
|
|
159
|
+
for service in reversed(list(server.background.values())):
|
|
160
|
+
service.close()
|
|
161
|
+
mine = read_address(app.directory)
|
|
162
|
+
if mine and mine.get("pid") == os.getpid():
|
|
163
|
+
try:
|
|
164
|
+
path.unlink()
|
|
165
|
+
except OSError:
|
|
166
|
+
pass
|
|
167
|
+
open_ = [conversation for conversation in server.conversations.values()
|
|
168
|
+
if live(conversation.status)]
|
|
169
|
+
for conversation in open_:
|
|
170
|
+
conversation.close()
|
|
171
|
+
# Their episodes end (and write their summaries) before the process does.
|
|
172
|
+
wait_until(lambda: not any(live(item.status) for item in open_), 30)
|
|
173
|
+
app.close()
|
|
174
|
+
return 0
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def main(argv=None):
|
|
178
|
+
import argparse
|
|
179
|
+
|
|
180
|
+
parsed = argparse.ArgumentParser(prog="python -m harness.host.server")
|
|
181
|
+
parsed.add_argument("--port", type=int, help="port to take (default $HARNESS_HOST_PORT or 8780, else a free one)")
|
|
182
|
+
parsed.add_argument("--idle", type=float, help="seconds with nothing open and no client before it exits "
|
|
183
|
+
"(default $HARNESS_HOST_IDLE or 1800)")
|
|
184
|
+
given = parsed.parse_args(argv)
|
|
185
|
+
return serve(port=given.port, idle=given.idle)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
if __name__ == "__main__":
|
|
189
|
+
sys.exit(main())
|
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
"""The sessions a server runs, as a tree: session -> agent -> sub-agent.
|
|
2
|
+
|
|
3
|
+
A session is what a user started from a frontend (the app, the terminal chat, harness run, the Python
|
|
4
|
+
API): its main agent is a conversation (runtime/conversation.py), and an agent may start
|
|
5
|
+
agents of its own (sub-agents, runtime/task/delegation.py: each a conversation of its own with its
|
|
6
|
+
own trace, under its parent's directory, its spending charged up the tree). Every
|
|
7
|
+
agent has a run, the key it is driven by (POST /api/conversations/... {run}); the main
|
|
8
|
+
agent's run is also its session's id, and a sub-agent's is "<session>/<agent>".
|
|
9
|
+
|
|
10
|
+
Sessions is the dict {run: conversation} a GUI server has always kept (host/http.py),
|
|
11
|
+
so code that registers a conversation by its run still works: a conversation registered
|
|
12
|
+
that way becomes a session of its own. With an `index` (the session host's), every
|
|
13
|
+
session is also appended to a JSON-lines file, so the sessions that ended are still
|
|
14
|
+
listed after the host exits (history()).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
import secrets
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
|
|
23
|
+
from ..core import episodes, format as formats
|
|
24
|
+
from ..runtime.status import ENDED as ENDED, LIVE as LIVE, live as live
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
MAIN = "main"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def session_metadata(conversation) -> dict:
|
|
31
|
+
"""Public identity of a session. A provider only returns fields safe to expose."""
|
|
32
|
+
return {"kind": "harness", "project": None, "source": "harness",
|
|
33
|
+
**getattr(conversation, "session_metadata", {})}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def word(status) -> str: # a status in every frontend's words: "waiting for confirmation"
|
|
37
|
+
return str(status or "").lower().replace("_", " ")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def title(text, limit: int = 80) -> str:
|
|
41
|
+
"""`text`'s words on one line, at most `limit` characters."""
|
|
42
|
+
return formats.clip(" ".join(str(text or "").split()), limit)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def waiting(status, note=None) -> str | None:
|
|
46
|
+
"""What an agent in `status` waits for: an approval, the user's message, a pause to
|
|
47
|
+
end, the computer to be prepared or the input lock (`note`); None while it works or
|
|
48
|
+
once it ended."""
|
|
49
|
+
if note and not str(note).startswith("error"):
|
|
50
|
+
return str(note)
|
|
51
|
+
return {"WAITING_FOR_CONFIRMATION": "approval", "WAITING_FOR_INPUT": "agent question",
|
|
52
|
+
"IDLE": "message", "PAUSED": "resume"}.get(status)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def ended_status(directory: Path) -> str:
|
|
56
|
+
"""The status of an agent nothing runs any more, from how its episode ended (none: interrupted)."""
|
|
57
|
+
return {"error": "ERROR", "interrupted": "INTERRUPTED", None: "INTERRUPTED"}.get(episodes.ending(episodes.summary(directory)), "FINISHED")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _usage(conversation) -> dict:
|
|
61
|
+
"""What an agent spent itself (its sub-agents' spending is theirs): model calls and dollars."""
|
|
62
|
+
return episodes.usage(getattr(conversation, "summary", None) or {})
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def spent(usage: dict | None) -> str:
|
|
66
|
+
"""Usage as a cell: "12 calls $0.034"."""
|
|
67
|
+
usage = usage or {}
|
|
68
|
+
calls = usage.get("model_calls") or 0
|
|
69
|
+
return f"{calls} call{'s' if calls != 1 else ''} {formats.cost(usage.get('cost_usd') or 0)}" if usage else ""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _title(conversation) -> str:
|
|
73
|
+
return title(conversation.instruction or getattr(conversation.config, "task", None) or "")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Sessions(dict):
|
|
77
|
+
"""{run: conversation} with the session tree over them (see the module docstring).
|
|
78
|
+
`default_frontend` names what started a conversation registered by its run alone;
|
|
79
|
+
`notes(run)` may say what an agent waits for before it starts (the app: preparing
|
|
80
|
+
this computer)."""
|
|
81
|
+
|
|
82
|
+
def __init__(self, index: Path | None = None, default_frontend: str = "ui"):
|
|
83
|
+
super().__init__()
|
|
84
|
+
self.index = Path(index) if index else None
|
|
85
|
+
self.default_frontend = default_frontend
|
|
86
|
+
self.notes = lambda run: None
|
|
87
|
+
self.registered = lambda run, conversation: None
|
|
88
|
+
# Session id -> {id, title, frontend, created, agents: {agent: {run, parent, created, title}}}.
|
|
89
|
+
self._sessions = {}
|
|
90
|
+
# Run -> (session id, agent id).
|
|
91
|
+
self._runs = {}
|
|
92
|
+
self._lock = threading.RLock()
|
|
93
|
+
|
|
94
|
+
# The dict, as servers use it.
|
|
95
|
+
|
|
96
|
+
def __setitem__(self, run, conversation):
|
|
97
|
+
with self._lock:
|
|
98
|
+
super().__setitem__(run, conversation)
|
|
99
|
+
if run not in self._runs:
|
|
100
|
+
self._add(run, conversation, title=None, frontend=None, session=self._new_id(), new=True)
|
|
101
|
+
|
|
102
|
+
def pop(self, run, *default):
|
|
103
|
+
with self._lock:
|
|
104
|
+
found = self._runs.pop(run, None)
|
|
105
|
+
if found is not None:
|
|
106
|
+
session, agent = found
|
|
107
|
+
entry = self._sessions.get(session)
|
|
108
|
+
if entry is not None:
|
|
109
|
+
entry["agents"].pop(agent, None)
|
|
110
|
+
if agent == MAIN:
|
|
111
|
+
for other in entry["agents"].values():
|
|
112
|
+
self._runs.pop(other["run"], None)
|
|
113
|
+
super().pop(other["run"], None)
|
|
114
|
+
self._sessions.pop(session, None)
|
|
115
|
+
return super().pop(run, *default)
|
|
116
|
+
|
|
117
|
+
# Registering.
|
|
118
|
+
|
|
119
|
+
def _new_id(self) -> str:
|
|
120
|
+
while True:
|
|
121
|
+
identifier = secrets.token_hex(3)
|
|
122
|
+
if identifier not in self._sessions and identifier not in self:
|
|
123
|
+
return identifier
|
|
124
|
+
|
|
125
|
+
def _add(self, run, conversation, *, title, frontend, session, new=False, agent=None, parent=None, created=None):
|
|
126
|
+
now = created if created is not None else time.time()
|
|
127
|
+
if new:
|
|
128
|
+
entry = {"id": session, "title": title or _title(conversation),
|
|
129
|
+
"frontend": frontend or self.default_frontend, "created": now, "agents": {}}
|
|
130
|
+
self._sessions[session] = entry
|
|
131
|
+
agent, parent = MAIN, None
|
|
132
|
+
else:
|
|
133
|
+
entry = self._sessions[session]
|
|
134
|
+
entry["agents"][agent] = {"run": run, "parent": parent, "created": now,
|
|
135
|
+
"title": title or _title(conversation)}
|
|
136
|
+
self._runs[run] = (session, agent)
|
|
137
|
+
try:
|
|
138
|
+
# Whose steps its worker sends (the physical-input policy, the input lock).
|
|
139
|
+
conversation.identity = {"session": session, "agent": agent}
|
|
140
|
+
except AttributeError:
|
|
141
|
+
pass
|
|
142
|
+
self.save_metadata(run)
|
|
143
|
+
self.registered(run, conversation)
|
|
144
|
+
return session
|
|
145
|
+
|
|
146
|
+
def add(self, run, conversation, *, title=None, frontend=None) -> str:
|
|
147
|
+
"""Register `conversation` under `run` (None: the new session's id) as a new
|
|
148
|
+
session's main agent; returns the session's id."""
|
|
149
|
+
with self._lock:
|
|
150
|
+
session = self._new_id()
|
|
151
|
+
run = run or session
|
|
152
|
+
dict.__setitem__(self, run, conversation)
|
|
153
|
+
return self._add(run, conversation, title=title, frontend=frontend, session=session, new=True)
|
|
154
|
+
|
|
155
|
+
def reconnect(self, row, conversation):
|
|
156
|
+
with self._lock:
|
|
157
|
+
run, session = row["run"], row["id"]
|
|
158
|
+
active = self.get(run)
|
|
159
|
+
if active is not None and live(active.status):
|
|
160
|
+
raise ValueError("the session already has a live controller")
|
|
161
|
+
if active is not None:
|
|
162
|
+
self.pop(run)
|
|
163
|
+
dict.__setitem__(self, run, conversation)
|
|
164
|
+
self._add(run, conversation, title=row["title"], frontend=row["frontend"], session=session,
|
|
165
|
+
new=True, created=row.get("created"))
|
|
166
|
+
|
|
167
|
+
def add_agent(self, session: str, conversation, *, agent: str | None = None, parent: str = MAIN,
|
|
168
|
+
title: str | None = None) -> str:
|
|
169
|
+
"""Register `conversation` as an agent of `session` started by its agent `parent`;
|
|
170
|
+
returns its run ("<session>/<agent>")."""
|
|
171
|
+
with self._lock:
|
|
172
|
+
entry = self._sessions.get(session)
|
|
173
|
+
if entry is None:
|
|
174
|
+
raise ValueError(f"no session {session}")
|
|
175
|
+
if parent not in entry["agents"]:
|
|
176
|
+
raise ValueError(f"session {session} has no agent {parent}")
|
|
177
|
+
if agent is None:
|
|
178
|
+
agent = f"a{len(entry['agents'])}"
|
|
179
|
+
while agent in entry["agents"]:
|
|
180
|
+
agent += "x"
|
|
181
|
+
if agent in entry["agents"] or "/" in agent:
|
|
182
|
+
raise ValueError(f"agent {agent} is taken (or has a /)")
|
|
183
|
+
run = f"{session}/{agent}"
|
|
184
|
+
dict.__setitem__(self, run, conversation)
|
|
185
|
+
self._add(run, conversation, title=title, frontend=None, session=session, agent=agent, parent=parent)
|
|
186
|
+
return run
|
|
187
|
+
|
|
188
|
+
def rename(self, run, text) -> str:
|
|
189
|
+
"""The title `text` for the agent of `run` (its main agent's: the session's), as kept."""
|
|
190
|
+
name = title(text, 120)
|
|
191
|
+
if not name:
|
|
192
|
+
raise ValueError("give it a title")
|
|
193
|
+
with self._lock:
|
|
194
|
+
if run in self._runs: # else the caller's to keep
|
|
195
|
+
session, agent = self._runs[run]
|
|
196
|
+
entry = self._sessions[session]
|
|
197
|
+
item = entry["agents"][agent]
|
|
198
|
+
item["title"] = name
|
|
199
|
+
if agent == MAIN:
|
|
200
|
+
entry["title"] = name
|
|
201
|
+
self.save_metadata(run)
|
|
202
|
+
return name
|
|
203
|
+
|
|
204
|
+
def _write(self, line: dict) -> None:
|
|
205
|
+
if self.index is None:
|
|
206
|
+
return
|
|
207
|
+
self.index.parent.mkdir(parents=True, exist_ok=True)
|
|
208
|
+
with self.index.open("a", encoding="utf-8") as handle:
|
|
209
|
+
handle.write(json.dumps(line, ensure_ascii=False) + "\n")
|
|
210
|
+
|
|
211
|
+
# Finding.
|
|
212
|
+
|
|
213
|
+
def resolve(self, name) -> str | None:
|
|
214
|
+
"""The run `name` stands for: a run, a session id (its main agent), "<session>/<agent>",
|
|
215
|
+
or the unique start of a session id (at least 3 characters); None when none."""
|
|
216
|
+
name = str(name or "").strip()
|
|
217
|
+
with self._lock:
|
|
218
|
+
if name in self:
|
|
219
|
+
return name
|
|
220
|
+
session, _, agent = name.partition("/")
|
|
221
|
+
if session not in self._sessions and len(session) >= 3:
|
|
222
|
+
found = [identifier for identifier in self._sessions if identifier.startswith(session)]
|
|
223
|
+
session = found[0] if len(found) == 1 else session
|
|
224
|
+
entry = self._sessions.get(session)
|
|
225
|
+
if entry is None:
|
|
226
|
+
return None
|
|
227
|
+
item = entry["agents"].get(agent or MAIN)
|
|
228
|
+
return item["run"] if item else None
|
|
229
|
+
|
|
230
|
+
def session_of(self, run) -> tuple[str, str] | None:
|
|
231
|
+
"""(session id, agent id) of a run."""
|
|
232
|
+
return self._runs.get(run)
|
|
233
|
+
|
|
234
|
+
def save_metadata(self, run: str) -> None:
|
|
235
|
+
"""Persist the public identity once a provider has returned its external ID."""
|
|
236
|
+
with self._lock:
|
|
237
|
+
session, agent = self._runs[run]
|
|
238
|
+
entry = self._sessions[session]
|
|
239
|
+
item = entry["agents"][agent]
|
|
240
|
+
conversation = self[run]
|
|
241
|
+
self._write({"id": session, "agent": agent, "parent": item["parent"], "run": run,
|
|
242
|
+
"directory": str(Path(conversation.directory).resolve()), "title": item["title"],
|
|
243
|
+
"frontend": entry["frontend"], "created": item["created"],
|
|
244
|
+
"metadata": session_metadata(conversation)})
|
|
245
|
+
|
|
246
|
+
# Describing.
|
|
247
|
+
|
|
248
|
+
def _agent(self, item: dict, agent: str) -> dict:
|
|
249
|
+
# Its model and reasoning effort are those of its next call (Conversation.set_model).
|
|
250
|
+
conversation = dict.get(self, item["run"])
|
|
251
|
+
status = conversation.status if conversation is not None else None
|
|
252
|
+
approval_id = getattr(conversation, "approval_id", None)
|
|
253
|
+
note = getattr(conversation, "waiting_for", None) or self.notes(item["run"])
|
|
254
|
+
if approval_id != getattr(conversation, "approval_id", None):
|
|
255
|
+
# Do not associate a changed request with the previous request's description.
|
|
256
|
+
approval_id = None
|
|
257
|
+
if not note and status == "RUNNING":
|
|
258
|
+
session = self._runs.get(item["run"], (None,))[0]
|
|
259
|
+
note = _waiting({"session": session, "agent": agent}) if session else None
|
|
260
|
+
main = getattr(getattr(conversation, "config", None), "main", None)
|
|
261
|
+
main = main if isinstance(main, dict) else {}
|
|
262
|
+
return {"id": agent, "parent": item["parent"], "run": item["run"], "title": item["title"],
|
|
263
|
+
"status": status, "waiting": waiting(status, note) if live(status) else None,
|
|
264
|
+
"approval_id": approval_id,
|
|
265
|
+
"metadata": session_metadata(conversation),
|
|
266
|
+
"capabilities": getattr(conversation, "capabilities", None),
|
|
267
|
+
"model": main.get("model"), "reasoning_effort": main.get("reasoning_effort"),
|
|
268
|
+
"workspace": getattr(conversation, "workspace_kind", None),
|
|
269
|
+
"directory": str(Path(conversation.directory).resolve()) if conversation is not None else None,
|
|
270
|
+
"created": item["created"], "usage": _usage(conversation) if conversation is not None else None}
|
|
271
|
+
|
|
272
|
+
def describe(self, session: str) -> dict | None:
|
|
273
|
+
"""One session as it is listed: its id, title, the frontend that started it, its
|
|
274
|
+
status (its main agent's, or WAITING_FOR_CONFIRMATION while any agent waits for an
|
|
275
|
+
approval), what it waits for, what all its agents spent (usage), and its agents in
|
|
276
|
+
tree order (each with its depth and what it spent itself)."""
|
|
277
|
+
with self._lock:
|
|
278
|
+
entry = self._sessions.get(session)
|
|
279
|
+
if entry is None:
|
|
280
|
+
return None
|
|
281
|
+
agents = {name: self._agent(item, name) for name, item in entry["agents"].items()}
|
|
282
|
+
return _session_row(entry, agents)
|
|
283
|
+
|
|
284
|
+
def sessions(self) -> list[dict]:
|
|
285
|
+
"""Every session registered, newest first."""
|
|
286
|
+
with self._lock:
|
|
287
|
+
identifiers = sorted(self._sessions, key=lambda key: self._sessions[key]["created"], reverse=True)
|
|
288
|
+
return [row for row in map(self.describe, identifiers) if row is not None]
|
|
289
|
+
|
|
290
|
+
def running(self) -> bool:
|
|
291
|
+
"""Whether any agent still runs (or waits for someone)."""
|
|
292
|
+
with self._lock:
|
|
293
|
+
conversations = list(self.values())
|
|
294
|
+
return any(live(conversation.status) for conversation in conversations)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _tree(agents: dict) -> list[dict]:
|
|
298
|
+
"""The agents in tree order (each after its parent), each with its depth."""
|
|
299
|
+
children = {}
|
|
300
|
+
for name, agent in agents.items():
|
|
301
|
+
children.setdefault(agent["parent"], []).append(name)
|
|
302
|
+
ordered = []
|
|
303
|
+
|
|
304
|
+
def visit(name, depth):
|
|
305
|
+
ordered.append({**agents[name], "depth": depth})
|
|
306
|
+
for child in sorted(children.get(name, []), key=lambda key: agents[key]["created"]):
|
|
307
|
+
visit(child, depth + 1)
|
|
308
|
+
|
|
309
|
+
for root in sorted(children.get(None, []), key=lambda key: agents[key]["created"]):
|
|
310
|
+
visit(root, 0)
|
|
311
|
+
# Agents whose parent is not known (left out of a history line) come last.
|
|
312
|
+
seen = {agent["id"] for agent in ordered}
|
|
313
|
+
ordered += [{**agent, "depth": 1} for name, agent in agents.items() if name not in seen]
|
|
314
|
+
return ordered
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _session_row(entry: dict, agents: dict) -> dict:
|
|
318
|
+
main = agents.get(MAIN) or {}
|
|
319
|
+
tree = _tree(agents)
|
|
320
|
+
approvals = [agent["id"] for agent in tree if agent["status"] == "WAITING_FOR_CONFIRMATION"]
|
|
321
|
+
status = "WAITING_FOR_CONFIRMATION" if approvals else main.get("status")
|
|
322
|
+
usage = [agent["usage"] for agent in tree if agent.get("usage")]
|
|
323
|
+
total = ({"model_calls": sum(item["model_calls"] for item in usage),
|
|
324
|
+
"cost_usd": round(sum(item["cost_usd"] for item in usage), 6)} if usage else None)
|
|
325
|
+
return {"id": entry["id"], "title": entry["title"], "frontend": entry["frontend"], "created": entry["created"],
|
|
326
|
+
"run": main.get("run", entry["id"]), "directory": main.get("directory"), "status": status,
|
|
327
|
+
"live": any(live(agent["status"]) for agent in tree),
|
|
328
|
+
"waiting": ("approval" if approvals else main.get("waiting")), "approvals": approvals, "usage": total,
|
|
329
|
+
"kind": main.get("metadata", {}).get("kind", "harness"),
|
|
330
|
+
"project": main.get("metadata", {}).get("project"),
|
|
331
|
+
"metadata": main.get("metadata", {}), "capabilities": main.get("capabilities"),
|
|
332
|
+
"agents": tree}
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
# The columns of a list of sessions (the terminal chat's /sessions).
|
|
336
|
+
COLUMNS = ("session", "agent", "kind", "project", "status", "waiting", "spent", "from", "started", "title")
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def table_rows(sessions: list[dict]) -> list[dict]:
|
|
340
|
+
"""Sessions as listed (rows) as the lines of a table: each agent under its session,
|
|
341
|
+
indented by its depth, with the cells of COLUMNS and, beside them, its `run`,
|
|
342
|
+
`session`, `agent_id`, `directory` and `state` (the status as it is)."""
|
|
343
|
+
lines = []
|
|
344
|
+
for session in sessions:
|
|
345
|
+
for agent in session.get("agents") or []:
|
|
346
|
+
main = agent["depth"] == 0
|
|
347
|
+
lines.append({"session": session["id"] if main else "", "agent": " " * agent["depth"] + agent["id"],
|
|
348
|
+
"kind": session.get("kind", "harness") if main else "",
|
|
349
|
+
"project": session.get("project") if main else "",
|
|
350
|
+
"status": word(agent["status"]),
|
|
351
|
+
"waiting": agent.get("waiting") or "", "spent": spent(agent.get("usage")),
|
|
352
|
+
"from": session["frontend"] if main else "",
|
|
353
|
+
"started": formats.timestamp(agent.get("created") or 0),
|
|
354
|
+
"title": session["title"] if main else agent.get("title") or "",
|
|
355
|
+
"run": agent["run"], "session_id": session["id"], "agent_id": agent["id"],
|
|
356
|
+
"directory": agent.get("directory"), "state": agent["status"]})
|
|
357
|
+
return lines
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def history(index: Path, skip=()) -> list[dict]:
|
|
361
|
+
"""The sessions an index lists (newest first), each described from its files: what a
|
|
362
|
+
host that ended left behind. Sessions in `skip` (ids) and those whose directory is gone
|
|
363
|
+
are left out."""
|
|
364
|
+
entries = {}
|
|
365
|
+
try:
|
|
366
|
+
lines = Path(index).read_text(encoding="utf-8").splitlines()
|
|
367
|
+
except OSError:
|
|
368
|
+
return []
|
|
369
|
+
for line in lines:
|
|
370
|
+
try:
|
|
371
|
+
item = json.loads(line)
|
|
372
|
+
except ValueError:
|
|
373
|
+
continue
|
|
374
|
+
if item.get("id") in skip or not item.get("directory"):
|
|
375
|
+
continue
|
|
376
|
+
entry = entries.setdefault(item["id"], {"id": item["id"], "title": item.get("title") or "",
|
|
377
|
+
"frontend": item.get("frontend") or "", "created": item.get("created"),
|
|
378
|
+
"agents": {}})
|
|
379
|
+
if item.get("agent", MAIN) == MAIN:
|
|
380
|
+
entry.update(title=item.get("title") or "", frontend=item.get("frontend") or "", created=item.get("created"))
|
|
381
|
+
entry["agents"][item.get("agent", MAIN)] = item
|
|
382
|
+
rows = []
|
|
383
|
+
for entry in entries.values():
|
|
384
|
+
agents = {}
|
|
385
|
+
for name, item in entry["agents"].items():
|
|
386
|
+
directory = Path(item["directory"])
|
|
387
|
+
if not directory.is_dir():
|
|
388
|
+
continue
|
|
389
|
+
agents[name] = {"id": name, "parent": item.get("parent"), "run": item.get("run"),
|
|
390
|
+
"title": item.get("title"), "status": ended_status(directory), "waiting": None,
|
|
391
|
+
"directory": str(directory), "created": item.get("created") or 0,
|
|
392
|
+
"metadata": item.get("metadata") or {},
|
|
393
|
+
"usage": episodes.usage(directory)}
|
|
394
|
+
if MAIN in agents:
|
|
395
|
+
rows.append(_session_row(entry, agents))
|
|
396
|
+
rows.sort(key=lambda row: row["created"] or 0, reverse=True)
|
|
397
|
+
return rows
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _waiting(owner: dict) -> str | None:
|
|
401
|
+
"""What an agent of a session waits for, as a package says (the computer's input lock;
|
|
402
|
+
harness/extensions.py)."""
|
|
403
|
+
from ..extensions import first
|
|
404
|
+
|
|
405
|
+
waiting = first("waiting")
|
|
406
|
+
return waiting(owner) if waiting is not None else None
|