@lmmslab/harness 0.83.0 → 0.85.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.
Files changed (38) hide show
  1. package/bin/harness.js +6 -1
  2. package/package.json +1 -1
  3. package/python/harness/__init__.py +1 -1
  4. package/python/harness/builtin/prompts/core/core.md +68 -38
  5. package/python/harness/builtin/prompts/shared/learning-goal.md +1 -1
  6. package/python/harness/cli.py +140 -18
  7. package/python/harness/config/agent.py +3 -0
  8. package/python/harness/core/trace.py +23 -3
  9. package/python/harness/core/worker.py +6 -0
  10. package/python/harness/host/client.py +26 -21
  11. package/python/harness/host/http.py +11 -1
  12. package/python/harness/host/sessions.py +38 -3
  13. package/python/harness/host/tasks.py +71 -27
  14. package/python/harness/instructions.py +329 -0
  15. package/python/harness/model_list.py +25 -5
  16. package/python/harness/packages/environments.py +51 -12
  17. package/python/harness/packages/manager.py +379 -102
  18. package/python/harness/packages/resolve.py +52 -15
  19. package/python/harness/packages/sources.py +17 -5
  20. package/python/harness/packages/state.py +10 -0
  21. package/python/harness/providers.py +66 -24
  22. package/python/harness/runtime/decision/model.py +9 -4
  23. package/python/harness/runtime/events.py +1 -0
  24. package/python/harness/runtime/execution/entries.py +53 -7
  25. package/python/harness/runtime/execution/session.py +57 -10
  26. package/python/harness/runtime/learning/active.py +4 -4
  27. package/python/harness/runtime/reactive/tree.py +96 -53
  28. package/python/harness/runtime/task/environments.py +3 -1
  29. package/python/harness/runtime/task/run.py +93 -4
  30. package/python/harness/runtime/tick.py +34 -3
  31. package/python/harness/settings.py +23 -1
  32. package/python/harness/terminal.py +3 -0
  33. package/python/harness/transcript.py +12 -0
  34. package/python/harness/tui/__init__.py +28 -6
  35. package/python/harness/tui/chat.py +323 -80
  36. package/python/harness/tui/pty.py +16 -0
  37. package/python/harness/tui/renderer.py +1 -0
  38. package/python/harness/tui/views.py +160 -38
@@ -8,6 +8,7 @@ tunnel to the server's port. It is also how every frontend drives a session of t
8
8
  session host (host/): `run` is then the session's id, or "<session>/<agent>".
9
9
  """
10
10
 
11
+ from http.client import IncompleteRead
11
12
  import json
12
13
  import time
13
14
  from urllib.error import HTTPError
@@ -112,6 +113,10 @@ class RemoteConversation:
112
113
  """Send terminal input to a session started with an interactive PTY."""
113
114
  self._post("terminal", text=text)
114
115
 
116
+ def terminal_resize(self, columns: int, rows: int) -> None:
117
+ """Match a hosted PTY to the attached terminal's character dimensions."""
118
+ self._post("terminal/resize", columns=columns, rows=rows)
119
+
115
120
  def handoff(self, agent: str, context: str, *, folder=None, isolation=None):
116
121
  """Start another agent with the context chosen by the user."""
117
122
  answer = self._post("handoff", agent=agent, context=context, folder=str(folder) if folder else None,
@@ -154,22 +159,24 @@ class RemoteConversation:
154
159
  turn's end is its turn_result record, after which the conversation waits). With
155
160
  `stop` (a threading.Event), it ends once the event is set, within the server's
156
161
  keep-alive interval. When the server stops answering, it tries again, waiting longer
157
- each time, and raises HostGone after GONE_SECONDS without a connection."""
162
+ each time, and raises HostGone after GONE_SECONDS of failures without records or keep-alives."""
158
163
  failing, delay = None, RETRY_SECONDS
159
164
  while True:
160
165
  if stop is not None and stop.is_set():
161
166
  return
162
- ended = False
167
+ reason = "the records stream ended before its end event"
163
168
  try:
164
169
  with open_url(f"{self.url}/api/stream?run={quote(self.run)}", timeout=self.timeout,
165
170
  headers={"X-Session-API-Key": self.token, "Last-Event-ID": str(after)}) as response:
166
- failing, delay = None, RETRY_SECONDS
167
171
  for event, data in read_sse(response):
168
172
  if stop is not None and stop.is_set():
169
173
  return
174
+ # Headers alone do not prove a working stream. Records and
175
+ # keep-alive comments do, including on an otherwise quiet turn.
176
+ if event in (None, "record", "end"):
177
+ failing, delay = None, RETRY_SECONDS
170
178
  if event == "end":
171
- ended = True
172
- break
179
+ return
173
180
  if event == "record":
174
181
  record = json.loads(data)
175
182
  after = record["seq"]
@@ -178,23 +185,21 @@ class RemoteConversation:
178
185
  yield record
179
186
  except HTTPError as error:
180
187
  raise RemoteError(_reason(error)) from None
181
- except TimeoutError: # a quiet stream: open it again
182
- continue
183
- except OSError as error: # refused, reset: the server may be restarting, or gone
184
- now = time.monotonic()
185
- failing = failing or now
186
- if now - failing >= GONE_SECONDS:
187
- raise HostGone(f"the session host at {self.url} does not answer "
188
- f"({getattr(error, 'reason', None) or error})") from None
189
- if stop is not None:
190
- if stop.wait(delay):
191
- return
192
- else:
193
- time.sleep(delay)
194
- delay = min(delay * 2, RETRY_LIMIT)
195
- continue
196
- if ended:
188
+ except (OSError, IncompleteRead) as error: # Timeouts, truncated bodies and connection failures.
189
+ reason = getattr(error, "reason", None) or error
190
+ if stop is not None and stop.is_set():
197
191
  return
192
+ now = time.monotonic()
193
+ if failing is None:
194
+ failing = now
195
+ if now - failing >= GONE_SECONDS:
196
+ raise HostGone(f"the session host at {self.url} does not answer ({reason})") from None
197
+ if stop is not None:
198
+ if stop.wait(delay):
199
+ return
200
+ else:
201
+ time.sleep(delay)
202
+ delay = min(delay * 2, RETRY_LIMIT)
198
203
 
199
204
 
200
205
  def _reason(error: HTTPError) -> str:
@@ -480,6 +480,7 @@ class Handler(BaseHTTPRequestHandler):
480
480
 
481
481
  def post_conversations_message(self, body):
482
482
  self._conversation(body).send_message(str(body.get("text") or ""), files=body.get("files") or ())
483
+ self.server.conversations.interact(self.server.conversations.resolve(body.get("run")))
483
484
  self._json({"ok": True})
484
485
 
485
486
  def _control(self, body, capability, method, *args):
@@ -490,6 +491,7 @@ class Handler(BaseHTTPRequestHandler):
490
491
 
491
492
  def post_conversations_steer(self, body):
492
493
  self._control(body, "steer", "steer", str(body.get("text") or ""), body.get("files") or ())
494
+ self.server.conversations.interact(self.server.conversations.resolve(body.get("run")))
493
495
  self._json({"ok": True})
494
496
 
495
497
  def post_conversations_cancel(self, body):
@@ -516,12 +518,17 @@ class Handler(BaseHTTPRequestHandler):
516
518
  self._control(body, "terminal_input", "terminal_input", body.get("text"))
517
519
  self._json({"ok": True})
518
520
 
521
+ def post_conversations_terminal_resize(self, body):
522
+ self._control(body, "terminal_resize", "terminal_resize", body.get("columns"), body.get("rows"))
523
+ self._json({"ok": True})
524
+
519
525
  def post_conversations_pause(self, body):
520
526
  self._conversation(body).pause()
521
527
  self._json({"ok": True})
522
528
 
523
529
  def post_conversations_resume(self, body):
524
530
  self._conversation(body).resume()
531
+ self.server.conversations.interact(self.server.conversations.resolve(body.get("run")))
525
532
  self._json({"ok": True})
526
533
 
527
534
  def post_conversations_confirm(self, body):
@@ -584,11 +591,14 @@ class Handler(BaseHTTPRequestHandler):
584
591
  row = self._session((query.get("id") or [""])[0])
585
592
  lines = int((query.get("lines") or ["40"])[0])
586
593
  for agent in row["agents"]:
594
+ agent["lines"] = []
595
+ if lines <= 0:
596
+ continue
587
597
  directory = Path(agent["directory"]) if agent["directory"] else None
588
598
  records = runs.read_records(directory) if directory and (directory / "events.jsonl").is_file() else []
589
599
  printer = TextTranscript()
590
600
  text = [line for record in records for line in printer.lines(record)]
591
- agent["lines"] = text[-lines:] if lines > 0 else []
601
+ agent["lines"] = text[-lines:]
592
602
  self._json(row)
593
603
 
594
604
  def post_sessions_stop(self, body):
@@ -17,6 +17,7 @@ listed after the host exits (history()).
17
17
  import json
18
18
  from pathlib import Path
19
19
  import secrets
20
+ import sys
20
21
  import threading
21
22
  import time
22
23
 
@@ -54,7 +55,10 @@ def waiting(status, note=None) -> str | None:
54
55
 
55
56
  def ended_status(directory: Path) -> str:
56
57
  """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
+ summary = episodes.summary(directory)
59
+ if summary.get("open"):
60
+ return "INTERRUPTED"
61
+ return {"error": "ERROR", "interrupted": "INTERRUPTED", None: "INTERRUPTED"}.get(episodes.ending(summary), "FINISHED")
58
62
 
59
63
 
60
64
  def _usage(conversation) -> dict:
@@ -91,6 +95,8 @@ class Sessions(dict):
91
95
  # Run -> (session id, agent id).
92
96
  self._runs = {}
93
97
  self._lock = threading.RLock()
98
+ # Last session whose user selection was persisted; repeated messages need no new row.
99
+ self._last_interacted = None
94
100
 
95
101
  # The dict, as servers use it.
96
102
 
@@ -127,7 +133,8 @@ class Sessions(dict):
127
133
  now = created if created is not None else time.time()
128
134
  if new:
129
135
  entry = {"id": session, "title": title or _title(conversation),
130
- "frontend": frontend or self.default_frontend, "created": now, "agents": {}}
136
+ "frontend": frontend or self.default_frontend, "created": now,
137
+ "last_interaction": time.time(), "agents": {}}
131
138
  self._sessions[session] = entry
132
139
  agent, parent = MAIN, None
133
140
  else:
@@ -141,6 +148,8 @@ class Sessions(dict):
141
148
  except AttributeError:
142
149
  pass
143
150
  self.save_metadata(run)
151
+ if new:
152
+ self._last_interacted = session
144
153
  self.registered(run, conversation)
145
154
  return session
146
155
 
@@ -232,6 +241,27 @@ class Sessions(dict):
232
241
  """(session id, agent id) of a run."""
233
242
  return self._runs.get(run)
234
243
 
244
+ def interact(self, run: str) -> None:
245
+ """Keep a successful user message or resume, independently of background events."""
246
+ with self._lock:
247
+ found = self._runs.get(run)
248
+ if found is None:
249
+ return
250
+ session, _ = found
251
+ self._sessions[session]["last_interaction"] = time.time()
252
+ if self._last_interacted == session:
253
+ return
254
+ try:
255
+ self.save_metadata(run)
256
+ except OSError as error:
257
+ # The message/resume already succeeded. Leave the selection dirty for retry.
258
+ try:
259
+ print(f"harness: could not save session activity: {error}", file=sys.stderr, flush=True)
260
+ except OSError:
261
+ pass
262
+ else:
263
+ self._last_interacted = session
264
+
235
265
  def save_metadata(self, run: str) -> None:
236
266
  """Persist the public identity once a provider has returned its external ID."""
237
267
  with self._lock:
@@ -242,6 +272,7 @@ class Sessions(dict):
242
272
  self._write({"id": session, "agent": agent, "parent": item["parent"], "run": run,
243
273
  "directory": str(Path(conversation.directory).resolve()), "title": item["title"],
244
274
  "frontend": entry["frontend"], "created": item["created"],
275
+ "last_interaction": entry.get("last_interaction") or entry["created"],
245
276
  "metadata": session_metadata(conversation)})
246
277
 
247
278
  # Describing.
@@ -268,7 +299,8 @@ class Sessions(dict):
268
299
  "model": main.get("model"), "reasoning_effort": main.get("reasoning_effort"),
269
300
  "workspace": getattr(conversation, "workspace_kind", None),
270
301
  "directory": str(Path(conversation.directory).resolve()) if conversation is not None else None,
271
- "created": item["created"], "usage": _usage(conversation) if conversation is not None else None}
302
+ "created": item["created"],
303
+ "usage": _usage(conversation) if conversation is not None else None}
272
304
 
273
305
  def describe(self, session: str) -> dict | None:
274
306
  """One session as it is listed: its id, title, the frontend that started it, its
@@ -325,6 +357,7 @@ def _session_row(entry: dict, agents: dict) -> dict:
325
357
  "cost_usd": round(sum(item["cost_usd"] for item in usage), 6)} if usage else None)
326
358
  return {"id": entry["id"], "title": entry["title"], "frontend": entry["frontend"], "created": entry["created"],
327
359
  "run": main.get("run", entry["id"]), "directory": main.get("directory"), "status": status,
360
+ "last_interaction": entry.get("last_interaction") or entry["created"],
328
361
  "live": any(live(agent["status"]) for agent in tree),
329
362
  "waiting": ("approval" if approvals else main.get("waiting")), "approvals": approvals, "usage": total,
330
363
  "kind": main.get("metadata", {}).get("kind", "harness"),
@@ -377,6 +410,8 @@ def history(index: Path, skip=()) -> list[dict]:
377
410
  entry = entries.setdefault(item["id"], {"id": item["id"], "title": item.get("title") or "",
378
411
  "frontend": item.get("frontend") or "", "created": item.get("created"),
379
412
  "agents": {}})
413
+ if item.get("last_interaction") is not None:
414
+ entry["last_interaction"] = max(entry.get("last_interaction") or 0, item["last_interaction"])
380
415
  if item.get("agent", MAIN) == MAIN:
381
416
  entry.update(title=item.get("title") or "", frontend=item.get("frontend") or "", created=item.get("created"))
382
417
  entry["agents"][item.get("agent", MAIN)] = item
@@ -37,7 +37,8 @@ CONVERSATION = ROOT / "configs" / "assistant.toml"
37
37
  # --window-details, --think; and `learn`, a conversation that learns its environment for live
38
38
  # minutes (true: learning.active_minutes) instead of doing a task (runtime/learning/active.py).
39
39
  # `agents`: sub-agents on in this conversation whatever session.agents says.
40
- RUN_KEYS = ("physical", "privacy", "think_while_acting", "think_interval", "learn", "managed_workspace", "agents")
40
+ RUN_KEYS = ("physical", "privacy", "think_while_acting", "think_interval", "learn", "managed_workspace", "agents",
41
+ "instructions")
41
42
  # The keys of a conversation profile's file (profiles()).
42
43
  PROFILE_KEYS = {
43
44
  "description": "one line: what conversations of this profile are for",
@@ -82,10 +83,20 @@ class TaskHost:
82
83
 
83
84
  def llm(self) -> dict:
84
85
  """The model the user chose, and whether its provider's key is there."""
85
- settings = providers.load(self.directory)
86
- provider = providers.PROVIDERS[settings["provider"]]
87
- key = self.credentials.status(provider.key_env) if provider.key_env else {"set": True, "source": None}
88
- return {**settings, "key_env": provider.key_env, "key": key, "ready": key["set"]}
86
+ from .. import model_list
87
+
88
+ try:
89
+ chosen = model_list.select(self.directory, native=True)
90
+ except model_list.SelectionError as error:
91
+ return {"provider": None, "model": None, "base_url": None, "key_env": None,
92
+ "key": {"set": False, "source": None}, "ready": False,
93
+ "detail": str(error), "selection_error": True}
94
+ settings = chosen if chosen is not None else providers.load(self.directory)
95
+ provider = providers.PROVIDERS.get(settings["provider"])
96
+ key_env = provider.key_env if provider else None
97
+ key = self.credentials.status(key_env) if key_env else {"set": True, "source": None}
98
+ return {**settings, "key_env": key_env, "key": key,
99
+ "ready": chosen is not None and (key["set"] or not providers.requires_key(settings["provider"]))}
89
100
 
90
101
  def status(self) -> dict:
91
102
  workspaces = self.available_workspaces()
@@ -252,7 +263,7 @@ class TaskHost:
252
263
  settings = providers.check(body)
253
264
  provider = providers.PROVIDERS[settings["provider"]]
254
265
  key = str(body.get("key") or "").strip() or (os.environ.get(provider.key_env) if provider.key_env else None)
255
- if provider.key_env and not key:
266
+ if providers.requires_key(settings["provider"]) and not key:
256
267
  return {"ok": False, "detail": "no key"}
257
268
  result = providers.reach(settings, key)
258
269
  if result["ok"]:
@@ -280,14 +291,22 @@ class TaskHost:
280
291
  kind = self.kind(kind)
281
292
  from .. import model_list
282
293
 
283
- current = providers.load(self.directory)
294
+ try:
295
+ current = providers.load(self.directory)
296
+ except model_list.SelectionError:
297
+ if choice is None:
298
+ raise
299
+ current = {}
284
300
  advanced = values["model"]
285
301
  if choice is not None:
286
302
  advanced = {**advanced, "reasoning_effort": effort}
287
- if any(choice.get(key) != current.get(key) for key in ("provider", "base_url")):
288
- advanced.pop("checker", None)
289
- advanced.pop("vision", None)
290
- choice = choice or current
303
+ choice = choice if choice is not None else model_list.select(self.directory, native=True)
304
+ if choice is None:
305
+ raise ValueError("add an enabled Harness model in Settings")
306
+ if any(choice.get(key) != current.get(key) for key in ("provider", "base_url")):
307
+ advanced = dict(advanced)
308
+ advanced.pop("checker", None)
309
+ advanced.pop("vision", None)
291
310
  if model:
292
311
  choice = {**choice, "model": str(model)}
293
312
  # A model the list says reads no images is sent none (its role's `images`).
@@ -316,6 +335,10 @@ class TaskHost:
316
335
  "agent_skills": addons.agent_skill_options(self.packages, skills["agent"])}
317
336
  # No implicit cross-task knowledge. A caller can explicitly bind a learning library.
318
337
  embodiment_config["runtime"] = {**embodiment_config.get("runtime", {}), "library": None}
338
+ # The user's and the project's instruction files (instructions.py): a conversation a user
339
+ # starts reads them; an experiment or a benchmark, whose config has none of this, does not.
340
+ embodiment_config["runtime"] = {**embodiment_config.get("runtime", {}),
341
+ "instructions": dict(values["instructions"])}
319
342
  servers = self.mcp_servers()
320
343
  if servers:
321
344
  # The MCP servers a package connects (the app's connectors, through its gateway).
@@ -403,6 +426,18 @@ class TaskHost:
403
426
  enable.append("agents")
404
427
  return {"enable": enable, "installed": installed, "agent": agent}
405
428
 
429
+ def _package_context(self):
430
+ """Optional workspace context for package management, which also works before setup."""
431
+ from ..bench import bench_spec
432
+
433
+ available = self.workspaces.providers()
434
+ matches = [provider for provider in available if provider.accepts({})]
435
+ if len(matches) != 1 and len(available) != 1:
436
+ # Installing the first environment or managing several needs no default.
437
+ return None, None
438
+ kind = self.kind()
439
+ return kind, bench_spec(self.workspaces.bench(kind)).kind
440
+
406
441
  def skills(self) -> dict:
407
442
  """The skills as Settings lists them: the built-in ones of this computer and the
408
443
  installed ones, each on or off; why an installed one cannot load."""
@@ -410,18 +445,19 @@ class TaskHost:
410
445
 
411
446
  off = set((self.settings.get().get("skills") or {}).get("off", []))
412
447
  loaded = load_skills()
413
- from ..bench import bench_spec
414
- embodiment = bench_spec(self.workspaces.bench(self.kind())).kind
415
- rows = [{"name": embodiment, "format": "built-in", "summary": loaded[embodiment].summary, "locked": True,
416
- "on": True},
417
- {"name": "checklist", "format": "built-in", "summary": loaded["checklist"].summary,
418
- "on": not {"checklist", "plan"} & off}]
419
- for name in self.workspaces.provider().builtin_skills(self.kind()):
420
- if name != embodiment:
448
+ kind, embodiment = self._package_context()
449
+ rows = ([{"name": embodiment, "format": "built-in", "summary": loaded[embodiment].summary,
450
+ "locked": True, "on": True}] if embodiment in loaded else [])
451
+ rows.append({"name": "checklist", "format": "built-in", "summary": loaded["checklist"].summary,
452
+ "on": not {"checklist", "plan"} & off})
453
+ builtin = self.workspaces.provider(kind).builtin_skills(kind) if kind is not None else ()
454
+ for name in builtin:
455
+ if name != embodiment and name in loaded:
421
456
  rows.append({"name": name, "format": "built-in", "summary": loaded[name].summary,
422
457
  "locked": True, "on": True})
423
458
  for row in addons.skills(self.packages):
424
- if row["format"] == "harness" and "embodiments" in row and embodiment not in row["embodiments"]:
459
+ if (embodiment is not None and row["format"] == "harness" and "embodiments" in row
460
+ and embodiment not in row["embodiments"]):
425
461
  continue
426
462
  problem = row.get("problem") or USER_PROBLEMS.get(row["path"]) if row["format"] == "harness" else \
427
463
  row.get("problem")
@@ -451,7 +487,6 @@ class TaskHost:
451
487
  installed only with `trust`, after the page showed what it brings. A folder of
452
488
  skills becomes a package per skill, taken only when it runs on this computer."""
453
489
  import base64
454
- from ..bench import bench_spec
455
490
 
456
491
  zip_bytes = base64.b64decode(body["zip"]) if body.get("zip") else None
457
492
  if not zip_bytes and not body.get("source"):
@@ -459,11 +494,13 @@ class TaskHost:
459
494
 
460
495
  def kernel_python():
461
496
  # A skill's requirements are for the kernel: the environment of the computer's mode.
462
- return self.workspaces.provider().python(self.kind(), log=lambda message: None)
497
+ kind = self.kind()
498
+ return self.workspaces.provider(kind).python(kind, log=lambda message: None)
463
499
 
500
+ _, embodiment = self._package_context()
464
501
  result = self.packages.install([body["source"]] if body.get("source") else [], zip_bytes=zip_bytes,
465
502
  consent=lambda found: bool(body.get("trust")), python=kernel_python,
466
- embodiment=bench_spec(self.workspaces.bench(self.kind())).kind,
503
+ embodiment=embodiment,
467
504
  log=lambda message: None)
468
505
  if result.get("found"):
469
506
  result = {**result, "found": [{**found, "shown": describe(found)} for found in result["found"]]}
@@ -609,10 +646,12 @@ class TaskHost:
609
646
  provider = providers.PROVIDERS[choice["provider"]]
610
647
  if provider.key_env:
611
648
  self.credentials.load()
612
- if not os.environ.get(provider.key_env):
649
+ if providers.requires_key(choice["provider"]) and not os.environ.get(provider.key_env):
613
650
  raise ValueError(f"configure credentials for {provider.name} in Settings")
614
- elif not self.llm()["ready"]:
615
- raise ValueError("no model key yet")
651
+ else:
652
+ state = self.llm()
653
+ if not state["ready"]:
654
+ raise ValueError(state.get("detail") or "no model key yet")
616
655
  kind, folder = self.environment(workspace, folder, last=frontend == "taptab", model_entry=model_entry)
617
656
  request = {"folder": folder} if folder is not None else {}
618
657
  self.workspaces.require_choices(kind, runtime)
@@ -640,6 +679,9 @@ class TaskHost:
640
679
  if unknown:
641
680
  raise ValueError(f"a conversation's own runtime keys are {', '.join(RUN_KEYS)}, not {sorted(unknown)}")
642
681
  runtime = dict(runtime or {})
682
+ if "instructions" in runtime:
683
+ # harness run --bare: {"load": "off"} over the settings' instructions.
684
+ runtime["instructions"] = {**(config.runtime.get("instructions") or {}), **dict(runtime["instructions"])}
643
685
  learn = runtime.pop("learn", None)
644
686
  runtime.pop("agents", None)
645
687
  managed = runtime.pop("managed_workspace", False)
@@ -793,7 +835,8 @@ class TaskHost:
793
835
  rows = [row for row in active + (history(index, skip={row["id"] for row in active}) if index else [])
794
836
  if row.get("kind", "harness") == "harness" and row.get("directory")]
795
837
  if identifier is None:
796
- found = sorted(rows, key=lambda row: row["created"] or 0)[-1:]
838
+ found = sorted(rows, key=lambda row: (row.get("last_interaction") or row["created"] or 0,
839
+ row["created"] or 0))[-1:]
797
840
  else:
798
841
  name = str(identifier)
799
842
  found = ([row for row in rows if name in (row["id"], row["run"])]
@@ -803,6 +846,7 @@ class TaskHost:
803
846
  f"no session {identifier} to continue (harness sessions ls --all lists them)")
804
847
  row = found[0]
805
848
  if row["live"]:
849
+ server.conversations.interact(row["run"])
806
850
  return row["run"]
807
851
  directory = Path(row["directory"])
808
852
  kept = saved(directory)